sqlite3.c 3.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.6.13. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a one 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% are 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 in the first
  14. ** 5503 lines past this header comment.) Additional code files may be
  15. ** needed if you want a wrapper to interface SQLite with your choice of
  16. ** programming language. The code for the "sqlite3" command-line shell
  17. ** is also in a separate file. This file contains only code for the core
  18. ** SQLite library.
  19. **
  20. ** This amalgamation was generated on 2009-04-15 12:44:27 UTC.
  21. */
  22. #define SQLITE_CORE 1
  23. #define SQLITE_AMALGAMATION 1
  24. #ifndef SQLITE_PRIVATE
  25. # define SQLITE_PRIVATE static
  26. #endif
  27. #ifndef SQLITE_API
  28. # define SQLITE_API
  29. #endif
  30. /************** Begin file sqliteInt.h ***************************************/
  31. /*
  32. ** 2001 September 15
  33. **
  34. ** The author disclaims copyright to this source code. In place of
  35. ** a legal notice, here is a blessing:
  36. **
  37. ** May you do good and not evil.
  38. ** May you find forgiveness for yourself and forgive others.
  39. ** May you share freely, never taking more than you give.
  40. **
  41. *************************************************************************
  42. ** Internal interface definitions for SQLite.
  43. **
  44. ** @(#) $Id: sqliteInt.h,v 1.854 2009/04/08 13:51:51 drh Exp $
  45. */
  46. #ifndef _SQLITEINT_H_
  47. #define _SQLITEINT_H_
  48. /*
  49. ** Include the configuration header output by 'configure' if we're using the
  50. ** autoconf-based build
  51. */
  52. #ifdef _HAVE_SQLITE_CONFIG_H
  53. #include "config.h"
  54. #endif
  55. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  56. /************** Begin file sqliteLimit.h *************************************/
  57. /*
  58. ** 2007 May 7
  59. **
  60. ** The author disclaims copyright to this source code. In place of
  61. ** a legal notice, here is a blessing:
  62. **
  63. ** May you do good and not evil.
  64. ** May you find forgiveness for yourself and forgive others.
  65. ** May you share freely, never taking more than you give.
  66. **
  67. *************************************************************************
  68. **
  69. ** This file defines various limits of what SQLite can process.
  70. **
  71. ** @(#) $Id: sqliteLimit.h,v 1.10 2009/01/10 16:15:09 danielk1977 Exp $
  72. */
  73. /*
  74. ** The maximum length of a TEXT or BLOB in bytes. This also
  75. ** limits the size of a row in a table or index.
  76. **
  77. ** The hard limit is the ability of a 32-bit signed integer
  78. ** to count the size: 2^31-1 or 2147483647.
  79. */
  80. #ifndef SQLITE_MAX_LENGTH
  81. # define SQLITE_MAX_LENGTH 1000000000
  82. #endif
  83. /*
  84. ** This is the maximum number of
  85. **
  86. ** * Columns in a table
  87. ** * Columns in an index
  88. ** * Columns in a view
  89. ** * Terms in the SET clause of an UPDATE statement
  90. ** * Terms in the result set of a SELECT statement
  91. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  92. ** * Terms in the VALUES clause of an INSERT statement
  93. **
  94. ** The hard upper limit here is 32676. Most database people will
  95. ** tell you that in a well-normalized database, you usually should
  96. ** not have more than a dozen or so columns in any table. And if
  97. ** that is the case, there is no point in having more than a few
  98. ** dozen values in any of the other situations described above.
  99. */
  100. #ifndef SQLITE_MAX_COLUMN
  101. # define SQLITE_MAX_COLUMN 2000
  102. #endif
  103. /*
  104. ** The maximum length of a single SQL statement in bytes.
  105. **
  106. ** It used to be the case that setting this value to zero would
  107. ** turn the limit off. That is no longer true. It is not possible
  108. ** to turn this limit off.
  109. */
  110. #ifndef SQLITE_MAX_SQL_LENGTH
  111. # define SQLITE_MAX_SQL_LENGTH 1000000000
  112. #endif
  113. /*
  114. ** The maximum depth of an expression tree. This is limited to
  115. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  116. ** want to place more severe limits on the complexity of an
  117. ** expression.
  118. **
  119. ** A value of 0 used to mean that the limit was not enforced.
  120. ** But that is no longer true. The limit is now strictly enforced
  121. ** at all times.
  122. */
  123. #ifndef SQLITE_MAX_EXPR_DEPTH
  124. # define SQLITE_MAX_EXPR_DEPTH 1000
  125. #endif
  126. /*
  127. ** The maximum number of terms in a compound SELECT statement.
  128. ** The code generator for compound SELECT statements does one
  129. ** level of recursion for each term. A stack overflow can result
  130. ** if the number of terms is too large. In practice, most SQL
  131. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  132. ** any limit on the number of terms in a compount SELECT.
  133. */
  134. #ifndef SQLITE_MAX_COMPOUND_SELECT
  135. # define SQLITE_MAX_COMPOUND_SELECT 500
  136. #endif
  137. /*
  138. ** The maximum number of opcodes in a VDBE program.
  139. ** Not currently enforced.
  140. */
  141. #ifndef SQLITE_MAX_VDBE_OP
  142. # define SQLITE_MAX_VDBE_OP 25000
  143. #endif
  144. /*
  145. ** The maximum number of arguments to an SQL function.
  146. */
  147. #ifndef SQLITE_MAX_FUNCTION_ARG
  148. # define SQLITE_MAX_FUNCTION_ARG 127
  149. #endif
  150. /*
  151. ** The maximum number of in-memory pages to use for the main database
  152. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  153. */
  154. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  155. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  156. #endif
  157. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  158. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  159. #endif
  160. /*
  161. ** The maximum number of attached databases. This must be between 0
  162. ** and 30. The upper bound on 30 is because a 32-bit integer bitmap
  163. ** is used internally to track attached databases.
  164. */
  165. #ifndef SQLITE_MAX_ATTACHED
  166. # define SQLITE_MAX_ATTACHED 10
  167. #endif
  168. /*
  169. ** The maximum value of a ?nnn wildcard that the parser will accept.
  170. */
  171. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  172. # define SQLITE_MAX_VARIABLE_NUMBER 999
  173. #endif
  174. /* Maximum page size. The upper bound on this value is 32768. This a limit
  175. ** imposed by the necessity of storing the value in a 2-byte unsigned integer
  176. ** and the fact that the page size must be a power of 2.
  177. **
  178. ** If this limit is changed, then the compiled library is technically
  179. ** incompatible with an SQLite library compiled with a different limit. If
  180. ** a process operating on a database with a page-size of 65536 bytes
  181. ** crashes, then an instance of SQLite compiled with the default page-size
  182. ** limit will not be able to rollback the aborted transaction. This could
  183. ** lead to database corruption.
  184. */
  185. #ifndef SQLITE_MAX_PAGE_SIZE
  186. # define SQLITE_MAX_PAGE_SIZE 32768
  187. #endif
  188. /*
  189. ** The default size of a database page.
  190. */
  191. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  192. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  193. #endif
  194. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  195. # undef SQLITE_DEFAULT_PAGE_SIZE
  196. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  197. #endif
  198. /*
  199. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  200. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  201. ** device characteristics (sector-size and atomic write() support),
  202. ** SQLite may choose a larger value. This constant is the maximum value
  203. ** SQLite will choose on its own.
  204. */
  205. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  206. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  207. #endif
  208. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  209. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  210. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  211. #endif
  212. /*
  213. ** Maximum number of pages in one database file.
  214. **
  215. ** This is really just the default value for the max_page_count pragma.
  216. ** This value can be lowered (or raised) at run-time using that the
  217. ** max_page_count macro.
  218. */
  219. #ifndef SQLITE_MAX_PAGE_COUNT
  220. # define SQLITE_MAX_PAGE_COUNT 1073741823
  221. #endif
  222. /*
  223. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  224. ** operator.
  225. */
  226. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  227. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  228. #endif
  229. /************** End of sqliteLimit.h *****************************************/
  230. /************** Continuing where we left off in sqliteInt.h ******************/
  231. /* Disable nuisance warnings on Borland compilers */
  232. #if defined(__BORLANDC__)
  233. #pragma warn -rch /* unreachable code */
  234. #pragma warn -ccc /* Condition is always true or false */
  235. #pragma warn -aus /* Assigned value is never used */
  236. #pragma warn -csu /* Comparing signed and unsigned */
  237. #pragma warn -spa /* Suspicious pointer arithmetic */
  238. #endif
  239. /* Needed for various definitions... */
  240. #ifndef _GNU_SOURCE
  241. # define _GNU_SOURCE
  242. #endif
  243. /*
  244. ** Include standard header files as necessary
  245. */
  246. #ifdef HAVE_STDINT_H
  247. #include <stdint.h>
  248. #endif
  249. #ifdef HAVE_INTTYPES_H
  250. #include <inttypes.h>
  251. #endif
  252. /*
  253. * This macro is used to "hide" some ugliness in casting an int
  254. * value to a ptr value under the MSVC 64-bit compiler. Casting
  255. * non 64-bit values to ptr types results in a "hard" error with
  256. * the MSVC 64-bit compiler which this attempts to avoid.
  257. *
  258. * A simple compiler pragma or casting sequence could not be found
  259. * to correct this in all situations, so this macro was introduced.
  260. *
  261. * It could be argued that the intptr_t type could be used in this
  262. * case, but that type is not available on all compilers, or
  263. * requires the #include of specific headers which differs between
  264. * platforms.
  265. */
  266. #define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  267. #define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  268. /*
  269. ** These #defines should enable >2GB file support on POSIX if the
  270. ** underlying operating system supports it. If the OS lacks
  271. ** large file support, or if the OS is windows, these should be no-ops.
  272. **
  273. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  274. ** system #includes. Hence, this block of code must be the very first
  275. ** code in all source files.
  276. **
  277. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  278. ** on the compiler command line. This is necessary if you are compiling
  279. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  280. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  281. ** without this option, LFS is enable. But LFS does not exist in the kernel
  282. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  283. ** portability you should omit LFS.
  284. **
  285. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  286. */
  287. #ifndef SQLITE_DISABLE_LFS
  288. # define _LARGE_FILE 1
  289. # ifndef _FILE_OFFSET_BITS
  290. # define _FILE_OFFSET_BITS 64
  291. # endif
  292. # define _LARGEFILE_SOURCE 1
  293. #endif
  294. /*
  295. ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
  296. ** Older versions of SQLite used an optional THREADSAFE macro.
  297. ** We support that for legacy
  298. */
  299. #if !defined(SQLITE_THREADSAFE)
  300. #if defined(THREADSAFE)
  301. # define SQLITE_THREADSAFE THREADSAFE
  302. #else
  303. # define SQLITE_THREADSAFE 1
  304. #endif
  305. #endif
  306. /*
  307. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  308. ** It determines whether or not the features related to
  309. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  310. ** be overridden at runtime using the sqlite3_config() API.
  311. */
  312. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  313. # define SQLITE_DEFAULT_MEMSTATUS 1
  314. #endif
  315. /*
  316. ** Exactly one of the following macros must be defined in order to
  317. ** specify which memory allocation subsystem to use.
  318. **
  319. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  320. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  321. ** SQLITE_MEMORY_SIZE // internal allocator #1
  322. ** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator
  323. ** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator
  324. **
  325. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  326. ** the default.
  327. */
  328. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
  329. defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
  330. defined(SQLITE_POW2_MEMORY_SIZE)>1
  331. # error "At most one of the following compile-time configuration options\
  332. is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
  333. SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
  334. #endif
  335. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
  336. defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
  337. defined(SQLITE_POW2_MEMORY_SIZE)==0
  338. # define SQLITE_SYSTEM_MALLOC 1
  339. #endif
  340. /*
  341. ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
  342. ** sizes of memory allocations below this value where possible.
  343. */
  344. #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
  345. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  346. #endif
  347. /*
  348. ** We need to define _XOPEN_SOURCE as follows in order to enable
  349. ** recursive mutexes on most Unix systems. But Mac OS X is different.
  350. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  351. ** so it is omitted there. See ticket #2673.
  352. **
  353. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  354. ** implemented on some systems. So we avoid defining it at all
  355. ** if it is already defined or if it is unneeded because we are
  356. ** not doing a threadsafe build. Ticket #2681.
  357. **
  358. ** See also ticket #2741.
  359. */
  360. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
  361. # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
  362. #endif
  363. /*
  364. ** The TCL headers are only needed when compiling the TCL bindings.
  365. */
  366. #if defined(SQLITE_TCL) || defined(TCLSH)
  367. # include <tcl.h>
  368. #endif
  369. /*
  370. ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
  371. ** Setting NDEBUG makes the code smaller and run faster. So the following
  372. ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
  373. ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  374. ** feature.
  375. */
  376. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  377. # define NDEBUG 1
  378. #endif
  379. /*
  380. ** The testcase() macro is used to aid in coverage testing. When
  381. ** doing coverage testing, the condition inside the argument to
  382. ** testcase() must be evaluated both true and false in order to
  383. ** get full branch coverage. The testcase() macro is inserted
  384. ** to help ensure adequate test coverage in places where simple
  385. ** condition/decision coverage is inadequate. For example, testcase()
  386. ** can be used to make sure boundary values are tested. For
  387. ** bitmask tests, testcase() can be used to make sure each bit
  388. ** is significant and used at least once. On switch statements
  389. ** where multiple cases go to the same block of code, testcase()
  390. ** can insure that all cases are evaluated.
  391. **
  392. */
  393. #ifdef SQLITE_COVERAGE_TEST
  394. SQLITE_PRIVATE void sqlite3Coverage(int);
  395. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  396. #else
  397. # define testcase(X)
  398. #endif
  399. /*
  400. ** The TESTONLY macro is used to enclose variable declarations or
  401. ** other bits of code that are needed to support the arguments
  402. ** within testcase() and assert() macros.
  403. */
  404. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  405. # define TESTONLY(X) X
  406. #else
  407. # define TESTONLY(X)
  408. #endif
  409. /*
  410. ** The ALWAYS and NEVER macros surround boolean expressions which
  411. ** are intended to always be true or false, respectively. Such
  412. ** expressions could be omitted from the code completely. But they
  413. ** are included in a few cases in order to enhance the resilience
  414. ** of SQLite to unexpected behavior - to make the code "self-healing"
  415. ** or "ductile" rather than being "brittle" and crashing at the first
  416. ** hint of unplanned behavior.
  417. **
  418. ** In other words, ALWAYS and NEVER are added for defensive code.
  419. **
  420. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  421. ** be true and false so that the unreachable code then specify will
  422. ** not be counted as untested code.
  423. */
  424. #if defined(SQLITE_COVERAGE_TEST)
  425. # define ALWAYS(X) (1)
  426. # define NEVER(X) (0)
  427. #elif !defined(NDEBUG)
  428. SQLITE_PRIVATE int sqlite3Assert(void);
  429. # define ALWAYS(X) ((X)?1:sqlite3Assert())
  430. # define NEVER(X) ((X)?sqlite3Assert():0)
  431. #else
  432. # define ALWAYS(X) (X)
  433. # define NEVER(X) (X)
  434. #endif
  435. /*
  436. ** The macro unlikely() is a hint that surrounds a boolean
  437. ** expression that is usually false. Macro likely() surrounds
  438. ** a boolean expression that is usually true. GCC is able to
  439. ** use these hints to generate better code, sometimes.
  440. */
  441. #if defined(__GNUC__) && 0
  442. # define likely(X) __builtin_expect((X),1)
  443. # define unlikely(X) __builtin_expect((X),0)
  444. #else
  445. # define likely(X) !!(X)
  446. # define unlikely(X) !!(X)
  447. #endif
  448. /*
  449. ** Sometimes we need a small amount of code such as a variable initialization
  450. ** to setup for a later assert() statement. We do not want this code to
  451. ** appear when assert() is disabled. The following macro is therefore
  452. ** used to contain that setup code. The "VVA" acronym stands for
  453. ** "Verification, Validation, and Accreditation". In other words, the
  454. ** code within VVA_ONLY() will only run during verification processes.
  455. */
  456. #ifndef NDEBUG
  457. # define VVA_ONLY(X) X
  458. #else
  459. # define VVA_ONLY(X)
  460. #endif
  461. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  462. /************** Begin file sqlite3.h *****************************************/
  463. /*
  464. ** 2001 September 15
  465. **
  466. ** The author disclaims copyright to this source code. In place of
  467. ** a legal notice, here is a blessing:
  468. **
  469. ** May you do good and not evil.
  470. ** May you find forgiveness for yourself and forgive others.
  471. ** May you share freely, never taking more than you give.
  472. **
  473. *************************************************************************
  474. ** This header file defines the interface that the SQLite library
  475. ** presents to client programs. If a C-function, structure, datatype,
  476. ** or constant definition does not appear in this file, then it is
  477. ** not a published API of SQLite, is subject to change without
  478. ** notice, and should not be referenced by programs that use SQLite.
  479. **
  480. ** Some of the definitions that are in this file are marked as
  481. ** "experimental". Experimental interfaces are normally new
  482. ** features recently added to SQLite. We do not anticipate changes
  483. ** to experimental interfaces but reserve to make minor changes if
  484. ** experience from use "in the wild" suggest such changes are prudent.
  485. **
  486. ** The official C-language API documentation for SQLite is derived
  487. ** from comments in this file. This file is the authoritative source
  488. ** on how SQLite interfaces are suppose to operate.
  489. **
  490. ** The name of this file under configuration management is "sqlite.h.in".
  491. ** The makefile makes some minor changes to this file (such as inserting
  492. ** the version number) and changes its name to "sqlite3.h" as
  493. ** part of the build process.
  494. **
  495. ** @(#) $Id: sqlite.h.in,v 1.440 2009/04/06 15:55:04 drh Exp $
  496. */
  497. #ifndef _SQLite3_H_
  498. #define _SQLite3_H_
  499. #include <stdarg.h> /* Needed for the definition of va_list */
  500. /*
  501. ** Make sure we can call this stuff from C++.
  502. */
  503. #if 0
  504. extern "C" {
  505. #endif
  506. /*
  507. ** Add the ability to override 'extern'
  508. */
  509. #ifndef SQLITE_EXTERN
  510. # define SQLITE_EXTERN extern
  511. #endif
  512. /*
  513. ** These no-op macros are used in front of interfaces to mark those
  514. ** interfaces as either deprecated or experimental. New applications
  515. ** should not use deprecated intrfaces - they are support for backwards
  516. ** compatibility only. Application writers should be aware that
  517. ** experimental interfaces are subject to change in point releases.
  518. **
  519. ** These macros used to resolve to various kinds of compiler magic that
  520. ** would generate warning messages when they were used. But that
  521. ** compiler magic ended up generating such a flurry of bug reports
  522. ** that we have taken it all out and gone back to using simple
  523. ** noop macros.
  524. */
  525. #define SQLITE_DEPRECATED
  526. #define SQLITE_EXPERIMENTAL
  527. /*
  528. ** Ensure these symbols were not defined by some previous header file.
  529. */
  530. #ifdef SQLITE_VERSION
  531. # undef SQLITE_VERSION
  532. #endif
  533. #ifdef SQLITE_VERSION_NUMBER
  534. # undef SQLITE_VERSION_NUMBER
  535. #endif
  536. /*
  537. ** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
  538. **
  539. ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
  540. ** the sqlite3.h file specify the version of SQLite with which
  541. ** that header file is associated.
  542. **
  543. ** The "version" of SQLite is a string of the form "X.Y.Z".
  544. ** The phrase "alpha" or "beta" might be appended after the Z.
  545. ** The X value is major version number always 3 in SQLite3.
  546. ** The X value only changes when backwards compatibility is
  547. ** broken and we intend to never break backwards compatibility.
  548. ** The Y value is the minor version number and only changes when
  549. ** there are major feature enhancements that are forwards compatible
  550. ** but not backwards compatible.
  551. ** The Z value is the release number and is incremented with
  552. ** each release but resets back to 0 whenever Y is incremented.
  553. **
  554. ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
  555. **
  556. ** Requirements: [H10011] [H10014]
  557. */
  558. #define SQLITE_VERSION "3.6.13"
  559. #define SQLITE_VERSION_NUMBER 3006013
  560. /*
  561. ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
  562. ** KEYWORDS: sqlite3_version
  563. **
  564. ** These features provide the same information as the [SQLITE_VERSION]
  565. ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
  566. ** with the library instead of the header file. Cautious programmers might
  567. ** include a check in their application to verify that
  568. ** sqlite3_libversion_number() always returns the value
  569. ** [SQLITE_VERSION_NUMBER].
  570. **
  571. ** The sqlite3_libversion() function returns the same information as is
  572. ** in the sqlite3_version[] string constant. The function is provided
  573. ** for use in DLLs since DLL users usually do not have direct access to string
  574. ** constants within the DLL.
  575. **
  576. ** Requirements: [H10021] [H10022] [H10023]
  577. */
  578. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  579. SQLITE_API const char *sqlite3_libversion(void);
  580. SQLITE_API int sqlite3_libversion_number(void);
  581. /*
  582. ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
  583. **
  584. ** SQLite can be compiled with or without mutexes. When
  585. ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes
  586. ** are enabled and SQLite is threadsafe. When the
  587. ** [SQLITE_THREADSAFE] macro is 0,
  588. ** the mutexes are omitted. Without the mutexes, it is not safe
  589. ** to use SQLite concurrently from more than one thread.
  590. **
  591. ** Enabling mutexes incurs a measurable performance penalty.
  592. ** So if speed is of utmost importance, it makes sense to disable
  593. ** the mutexes. But for maximum safety, mutexes should be enabled.
  594. ** The default behavior is for mutexes to be enabled.
  595. **
  596. ** This interface can be used by a program to make sure that the
  597. ** version of SQLite that it is linking against was compiled with
  598. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  599. **
  600. ** This interface only reports on the compile-time mutex setting
  601. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  602. ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
  603. ** can be fully or partially disabled using a call to [sqlite3_config()]
  604. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  605. ** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows
  606. ** only the default compile-time setting, not any run-time changes
  607. ** to that setting.
  608. **
  609. ** See the [threading mode] documentation for additional information.
  610. **
  611. ** Requirements: [H10101] [H10102]
  612. */
  613. SQLITE_API int sqlite3_threadsafe(void);
  614. /*
  615. ** CAPI3REF: Database Connection Handle {H12000} <S40200>
  616. ** KEYWORDS: {database connection} {database connections}
  617. **
  618. ** Each open SQLite database is represented by a pointer to an instance of
  619. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  620. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  621. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  622. ** is its destructor. There are many other interfaces (such as
  623. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  624. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  625. ** sqlite3 object.
  626. */
  627. typedef struct sqlite3 sqlite3;
  628. /*
  629. ** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
  630. ** KEYWORDS: sqlite_int64 sqlite_uint64
  631. **
  632. ** Because there is no cross-platform way to specify 64-bit integer types
  633. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  634. **
  635. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  636. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  637. ** compatibility only.
  638. **
  639. ** Requirements: [H10201] [H10202]
  640. */
  641. #ifdef SQLITE_INT64_TYPE
  642. typedef SQLITE_INT64_TYPE sqlite_int64;
  643. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  644. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  645. typedef __int64 sqlite_int64;
  646. typedef unsigned __int64 sqlite_uint64;
  647. #else
  648. typedef long long int sqlite_int64;
  649. typedef unsigned long long int sqlite_uint64;
  650. #endif
  651. typedef sqlite_int64 sqlite3_int64;
  652. typedef sqlite_uint64 sqlite3_uint64;
  653. /*
  654. ** If compiling for a processor that lacks floating point support,
  655. ** substitute integer for floating-point.
  656. */
  657. #ifdef SQLITE_OMIT_FLOATING_POINT
  658. # define double sqlite3_int64
  659. #endif
  660. /*
  661. ** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
  662. **
  663. ** This routine is the destructor for the [sqlite3] object.
  664. **
  665. ** Applications should [sqlite3_finalize | finalize] all [prepared statements]
  666. ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
  667. ** the [sqlite3] object prior to attempting to close the object.
  668. ** The [sqlite3_next_stmt()] interface can be used to locate all
  669. ** [prepared statements] associated with a [database connection] if desired.
  670. ** Typical code might look like this:
  671. **
  672. ** <blockquote><pre>
  673. ** sqlite3_stmt *pStmt;
  674. ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
  675. ** &nbsp; sqlite3_finalize(pStmt);
  676. ** }
  677. ** </pre></blockquote>
  678. **
  679. ** If [sqlite3_close()] is invoked while a transaction is open,
  680. ** the transaction is automatically rolled back.
  681. **
  682. ** The C parameter to [sqlite3_close(C)] must be either a NULL
  683. ** pointer or an [sqlite3] object pointer obtained
  684. ** from [sqlite3_open()], [sqlite3_open16()], or
  685. ** [sqlite3_open_v2()], and not previously closed.
  686. **
  687. ** Requirements:
  688. ** [H12011] [H12012] [H12013] [H12014] [H12015] [H12019]
  689. */
  690. SQLITE_API int sqlite3_close(sqlite3 *);
  691. /*
  692. ** The type for a callback function.
  693. ** This is legacy and deprecated. It is included for historical
  694. ** compatibility and is not documented.
  695. */
  696. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  697. /*
  698. ** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
  699. **
  700. ** The sqlite3_exec() interface is a convenient way of running one or more
  701. ** SQL statements without having to write a lot of C code. The UTF-8 encoded
  702. ** SQL statements are passed in as the second parameter to sqlite3_exec().
  703. ** The statements are evaluated one by one until either an error or
  704. ** an interrupt is encountered, or until they are all done. The 3rd parameter
  705. ** is an optional callback that is invoked once for each row of any query
  706. ** results produced by the SQL statements. The 5th parameter tells where
  707. ** to write any error messages.
  708. **
  709. ** The error message passed back through the 5th parameter is held
  710. ** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak,
  711. ** the calling application should call [sqlite3_free()] on any error
  712. ** message returned through the 5th parameter when it has finished using
  713. ** the error message.
  714. **
  715. ** If the SQL statement in the 2nd parameter is NULL or an empty string
  716. ** or a string containing only whitespace and comments, then no SQL
  717. ** statements are evaluated and the database is not changed.
  718. **
  719. ** The sqlite3_exec() interface is implemented in terms of
  720. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
  721. ** The sqlite3_exec() routine does nothing to the database that cannot be done
  722. ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
  723. **
  724. ** The first parameter to [sqlite3_exec()] must be an valid and open
  725. ** [database connection].
  726. **
  727. ** The database connection must not be closed while
  728. ** [sqlite3_exec()] is running.
  729. **
  730. ** The calling function should use [sqlite3_free()] to free
  731. ** the memory that *errmsg is left pointing at once the error
  732. ** message is no longer needed.
  733. **
  734. ** The SQL statement text in the 2nd parameter to [sqlite3_exec()]
  735. ** must remain unchanged while [sqlite3_exec()] is running.
  736. **
  737. ** Requirements:
  738. ** [H12101] [H12102] [H12104] [H12105] [H12107] [H12110] [H12113] [H12116]
  739. ** [H12119] [H12122] [H12125] [H12131] [H12134] [H12137] [H12138]
  740. */
  741. SQLITE_API int sqlite3_exec(
  742. sqlite3*, /* An open database */
  743. const char *sql, /* SQL to be evaluated */
  744. int (*callback)(void*,int,char**,char**), /* Callback function */
  745. void *, /* 1st argument to callback */
  746. char **errmsg /* Error msg written here */
  747. );
  748. /*
  749. ** CAPI3REF: Result Codes {H10210} <S10700>
  750. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  751. ** KEYWORDS: {result code} {result codes}
  752. **
  753. ** Many SQLite functions return an integer result code from the set shown
  754. ** here in order to indicates success or failure.
  755. **
  756. ** New error codes may be added in future versions of SQLite.
  757. **
  758. ** See also: [SQLITE_IOERR_READ | extended result codes]
  759. */
  760. #define SQLITE_OK 0 /* Successful result */
  761. /* beginning-of-error-codes */
  762. #define SQLITE_ERROR 1 /* SQL error or missing database */
  763. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  764. #define SQLITE_PERM 3 /* Access permission denied */
  765. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  766. #define SQLITE_BUSY 5 /* The database file is locked */
  767. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  768. #define SQLITE_NOMEM 7 /* A malloc() failed */
  769. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  770. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  771. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  772. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  773. #define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */
  774. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  775. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  776. #define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */
  777. #define SQLITE_EMPTY 16 /* Database is empty */
  778. #define SQLITE_SCHEMA 17 /* The database schema changed */
  779. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  780. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  781. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  782. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  783. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  784. #define SQLITE_AUTH 23 /* Authorization denied */
  785. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  786. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  787. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  788. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  789. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  790. /* end-of-error-codes */
  791. /*
  792. ** CAPI3REF: Extended Result Codes {H10220} <S10700>
  793. ** KEYWORDS: {extended error code} {extended error codes}
  794. ** KEYWORDS: {extended result code} {extended result codes}
  795. **
  796. ** In its default configuration, SQLite API routines return one of 26 integer
  797. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  798. ** these result codes are too coarse-grained. They do not provide as
  799. ** much information about problems as programmers might like. In an effort to
  800. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  801. ** support for additional result codes that provide more detailed information
  802. ** about errors. The extended result codes are enabled or disabled
  803. ** on a per database connection basis using the
  804. ** [sqlite3_extended_result_codes()] API.
  805. **
  806. ** Some of the available extended result codes are listed here.
  807. ** One may expect the number of extended result codes will be expand
  808. ** over time. Software that uses extended result codes should expect
  809. ** to see new result codes in future releases of SQLite.
  810. **
  811. ** The SQLITE_OK result code will never be extended. It will always
  812. ** be exactly zero.
  813. */
  814. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  815. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  816. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  817. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  818. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  819. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  820. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  821. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  822. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  823. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  824. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  825. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  826. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  827. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  828. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  829. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  830. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  831. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8) )
  832. /*
  833. ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
  834. **
  835. ** These bit values are intended for use in the
  836. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  837. ** in the 4th parameter to the xOpen method of the
  838. ** [sqlite3_vfs] object.
  839. */
  840. #define SQLITE_OPEN_READONLY 0x00000001
  841. #define SQLITE_OPEN_READWRITE 0x00000002
  842. #define SQLITE_OPEN_CREATE 0x00000004
  843. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008
  844. #define SQLITE_OPEN_EXCLUSIVE 0x00000010
  845. #define SQLITE_OPEN_MAIN_DB 0x00000100
  846. #define SQLITE_OPEN_TEMP_DB 0x00000200
  847. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400
  848. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800
  849. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000
  850. #define SQLITE_OPEN_SUBJOURNAL 0x00002000
  851. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000
  852. #define SQLITE_OPEN_NOMUTEX 0x00008000
  853. #define SQLITE_OPEN_FULLMUTEX 0x00010000
  854. /*
  855. ** CAPI3REF: Device Characteristics {H10240} <H11120>
  856. **
  857. ** The xDeviceCapabilities method of the [sqlite3_io_methods]
  858. ** object returns an integer which is a vector of the these
  859. ** bit values expressing I/O characteristics of the mass storage
  860. ** device that holds the file that the [sqlite3_io_methods]
  861. ** refers to.
  862. **
  863. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  864. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  865. ** mean that writes of blocks that are nnn bytes in size and
  866. ** are aligned to an address which is an integer multiple of
  867. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  868. ** that when data is appended to a file, the data is appended
  869. ** first then the size of the file is extended, never the other
  870. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  871. ** information is written to disk in the same order as calls
  872. ** to xWrite().
  873. */
  874. #define SQLITE_IOCAP_ATOMIC 0x00000001
  875. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  876. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  877. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  878. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  879. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  880. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  881. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  882. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  883. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  884. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  885. /*
  886. ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
  887. **
  888. ** SQLite uses one of these integer values as the second
  889. ** argument to calls it makes to the xLock() and xUnlock() methods
  890. ** of an [sqlite3_io_methods] object.
  891. */
  892. #define SQLITE_LOCK_NONE 0
  893. #define SQLITE_LOCK_SHARED 1
  894. #define SQLITE_LOCK_RESERVED 2
  895. #define SQLITE_LOCK_PENDING 3
  896. #define SQLITE_LOCK_EXCLUSIVE 4
  897. /*
  898. ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
  899. **
  900. ** When SQLite invokes the xSync() method of an
  901. ** [sqlite3_io_methods] object it uses a combination of
  902. ** these integer values as the second argument.
  903. **
  904. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  905. ** sync operation only needs to flush data to mass storage. Inode
  906. ** information need not be flushed. If the lower four bits of the flag
  907. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  908. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  909. ** to use Mac OS X style fullsync instead of fsync().
  910. */
  911. #define SQLITE_SYNC_NORMAL 0x00002
  912. #define SQLITE_SYNC_FULL 0x00003
  913. #define SQLITE_SYNC_DATAONLY 0x00010
  914. /*
  915. ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
  916. **
  917. ** An [sqlite3_file] object represents an open file in the OS
  918. ** interface layer. Individual OS interface implementations will
  919. ** want to subclass this object by appending additional fields
  920. ** for their own use. The pMethods entry is a pointer to an
  921. ** [sqlite3_io_methods] object that defines methods for performing
  922. ** I/O operations on the open file.
  923. */
  924. typedef struct sqlite3_file sqlite3_file;
  925. struct sqlite3_file {
  926. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  927. };
  928. /*
  929. ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
  930. **
  931. ** Every file opened by the [sqlite3_vfs] xOpen method populates an
  932. ** [sqlite3_file] object (or, more commonly, a subclass of the
  933. ** [sqlite3_file] object) with a pointer to an instance of this object.
  934. ** This object defines the methods used to perform various operations
  935. ** against the open file represented by the [sqlite3_file] object.
  936. **
  937. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  938. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  939. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  940. ** flag may be ORed in to indicate that only the data of the file
  941. ** and not its inode needs to be synced.
  942. **
  943. ** The integer values to xLock() and xUnlock() are one of
  944. ** <ul>
  945. ** <li> [SQLITE_LOCK_NONE],
  946. ** <li> [SQLITE_LOCK_SHARED],
  947. ** <li> [SQLITE_LOCK_RESERVED],
  948. ** <li> [SQLITE_LOCK_PENDING], or
  949. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  950. ** </ul>
  951. ** xLock() increases the lock. xUnlock() decreases the lock.
  952. ** The xCheckReservedLock() method checks whether any database connection,
  953. ** either in this process or in some other process, is holding a RESERVED,
  954. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  955. ** if such a lock exists and false otherwise.
  956. **
  957. ** The xFileControl() method is a generic interface that allows custom
  958. ** VFS implementations to directly control an open file using the
  959. ** [sqlite3_file_control()] interface. The second "op" argument is an
  960. ** integer opcode. The third argument is a generic pointer intended to
  961. ** point to a structure that may contain arguments or space in which to
  962. ** write return values. Potential uses for xFileControl() might be
  963. ** functions to enable blocking locks with timeouts, to change the
  964. ** locking strategy (for example to use dot-file locks), to inquire
  965. ** about the status of a lock, or to break stale locks. The SQLite
  966. ** core reserves all opcodes less than 100 for its own use.
  967. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  968. ** Applications that define a custom xFileControl method should use opcodes
  969. ** greater than 100 to avoid conflicts.
  970. **
  971. ** The xSectorSize() method returns the sector size of the
  972. ** device that underlies the file. The sector size is the
  973. ** minimum write that can be performed without disturbing
  974. ** other bytes in the file. The xDeviceCharacteristics()
  975. ** method returns a bit vector describing behaviors of the
  976. ** underlying device:
  977. **
  978. ** <ul>
  979. ** <li> [SQLITE_IOCAP_ATOMIC]
  980. ** <li> [SQLITE_IOCAP_ATOMIC512]
  981. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  982. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  983. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  984. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  985. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  986. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  987. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  988. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  989. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  990. ** </ul>
  991. **
  992. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  993. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  994. ** mean that writes of blocks that are nnn bytes in size and
  995. ** are aligned to an address which is an integer multiple of
  996. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  997. ** that when data is appended to a file, the data is appended
  998. ** first then the size of the file is extended, never the other
  999. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1000. ** information is written to disk in the same order as calls
  1001. ** to xWrite().
  1002. **
  1003. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1004. ** in the unread portions of the buffer with zeros. A VFS that
  1005. ** fails to zero-fill short reads might seem to work. However,
  1006. ** failure to zero-fill short reads will eventually lead to
  1007. ** database corruption.
  1008. */
  1009. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1010. struct sqlite3_io_methods {
  1011. int iVersion;
  1012. int (*xClose)(sqlite3_file*);
  1013. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1014. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1015. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1016. int (*xSync)(sqlite3_file*, int flags);
  1017. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1018. int (*xLock)(sqlite3_file*, int);
  1019. int (*xUnlock)(sqlite3_file*, int);
  1020. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1021. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1022. int (*xSectorSize)(sqlite3_file*);
  1023. int (*xDeviceCharacteristics)(sqlite3_file*);
  1024. /* Additional methods may be added in future releases */
  1025. };
  1026. /*
  1027. ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
  1028. **
  1029. ** These integer constants are opcodes for the xFileControl method
  1030. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1031. ** interface.
  1032. **
  1033. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1034. ** opcode causes the xFileControl method to write the current state of
  1035. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1036. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1037. ** into an integer that the pArg argument points to. This capability
  1038. ** is used during testing and only needs to be supported when SQLITE_TEST
  1039. ** is defined.
  1040. */
  1041. #define SQLITE_FCNTL_LOCKSTATE 1
  1042. #define SQLITE_GET_LOCKPROXYFILE 2
  1043. #define SQLITE_SET_LOCKPROXYFILE 3
  1044. #define SQLITE_LAST_ERRNO 4
  1045. /*
  1046. ** CAPI3REF: Mutex Handle {H17110} <S20130>
  1047. **
  1048. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1049. ** abstract type for a mutex object. The SQLite core never looks
  1050. ** at the internal representation of an [sqlite3_mutex]. It only
  1051. ** deals with pointers to the [sqlite3_mutex] object.
  1052. **
  1053. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1054. */
  1055. typedef struct sqlite3_mutex sqlite3_mutex;
  1056. /*
  1057. ** CAPI3REF: OS Interface Object {H11140} <S20100>
  1058. **
  1059. ** An instance of the sqlite3_vfs object defines the interface between
  1060. ** the SQLite core and the underlying operating system. The "vfs"
  1061. ** in the name of the object stands for "virtual file system".
  1062. **
  1063. ** The value of the iVersion field is initially 1 but may be larger in
  1064. ** future versions of SQLite. Additional fields may be appended to this
  1065. ** object when the iVersion value is increased. Note that the structure
  1066. ** of the sqlite3_vfs object changes in the transaction between
  1067. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1068. ** modified.
  1069. **
  1070. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1071. ** structure used by this VFS. mxPathname is the maximum length of
  1072. ** a pathname in this VFS.
  1073. **
  1074. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1075. ** the pNext pointer. The [sqlite3_vfs_register()]
  1076. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1077. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1078. ** searches the list. Neither the application code nor the VFS
  1079. ** implementation should use the pNext pointer.
  1080. **
  1081. ** The pNext field is the only field in the sqlite3_vfs
  1082. ** structure that SQLite will ever modify. SQLite will only access
  1083. ** or modify this field while holding a particular static mutex.
  1084. ** The application should never modify anything within the sqlite3_vfs
  1085. ** object once the object has been registered.
  1086. **
  1087. ** The zName field holds the name of the VFS module. The name must
  1088. ** be unique across all VFS modules.
  1089. **
  1090. ** SQLite will guarantee that the zFilename parameter to xOpen
  1091. ** is either a NULL pointer or string obtained
  1092. ** from xFullPathname(). SQLite further guarantees that
  1093. ** the string will be valid and unchanged until xClose() is
  1094. ** called. Because of the previous sentense,
  1095. ** the [sqlite3_file] can safely store a pointer to the
  1096. ** filename if it needs to remember the filename for some reason.
  1097. ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
  1098. ** must invite its own temporary name for the file. Whenever the
  1099. ** xFilename parameter is NULL it will also be the case that the
  1100. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1101. **
  1102. ** The flags argument to xOpen() includes all bits set in
  1103. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1104. ** or [sqlite3_open16()] is used, then flags includes at least
  1105. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1106. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1107. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1108. **
  1109. ** SQLite will also add one of the following flags to the xOpen()
  1110. ** call, depending on the object being opened:
  1111. **
  1112. ** <ul>
  1113. ** <li> [SQLITE_OPEN_MAIN_DB]
  1114. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1115. ** <li> [SQLITE_OPEN_TEMP_DB]
  1116. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1117. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1118. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1119. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1120. ** </ul>
  1121. **
  1122. ** The file I/O implementation can use the object type flags to
  1123. ** change the way it deals with files. For example, an application
  1124. ** that does not care about crash recovery or rollback might make
  1125. ** the open of a journal file a no-op. Writes to this journal would
  1126. ** also be no-ops, and any attempt to read the journal would return
  1127. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1128. ** file will be doing page-aligned sector reads and writes in a random
  1129. ** order and set up its I/O subsystem accordingly.
  1130. **
  1131. ** SQLite might also add one of the following flags to the xOpen method:
  1132. **
  1133. ** <ul>
  1134. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1135. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1136. ** </ul>
  1137. **
  1138. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1139. ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
  1140. ** will be set for TEMP databases, journals and for subjournals.
  1141. **
  1142. ** The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
  1143. ** for exclusive access. This flag is set for all files except
  1144. ** for the main database file.
  1145. **
  1146. ** At least szOsFile bytes of memory are allocated by SQLite
  1147. ** to hold the [sqlite3_file] structure passed as the third
  1148. ** argument to xOpen. The xOpen method does not have to
  1149. ** allocate the structure; it should just fill it in.
  1150. **
  1151. ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1152. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1153. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1154. ** to test whether a file is at least readable. The file can be a
  1155. ** directory.
  1156. **
  1157. ** SQLite will always allocate at least mxPathname+1 bytes for the
  1158. ** output buffer xFullPathname. The exact size of the output buffer
  1159. ** is also passed as a parameter to both methods. If the output buffer
  1160. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1161. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1162. ** to prevent this by setting mxPathname to a sufficiently large value.
  1163. **
  1164. ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
  1165. ** are not strictly a part of the filesystem, but they are
  1166. ** included in the VFS structure for completeness.
  1167. ** The xRandomness() function attempts to return nBytes bytes
  1168. ** of good-quality randomness into zOut. The return value is
  1169. ** the actual number of bytes of randomness obtained.
  1170. ** The xSleep() method causes the calling thread to sleep for at
  1171. ** least the number of microseconds given. The xCurrentTime()
  1172. ** method returns a Julian Day Number for the current date and time.
  1173. **
  1174. */
  1175. typedef struct sqlite3_vfs sqlite3_vfs;
  1176. struct sqlite3_vfs {
  1177. int iVersion; /* Structure version number */
  1178. int szOsFile; /* Size of subclassed sqlite3_file */
  1179. int mxPathname; /* Maximum file pathname length */
  1180. sqlite3_vfs *pNext; /* Next registered VFS */
  1181. const char *zName; /* Name of this virtual file system */
  1182. void *pAppData; /* Pointer to application-specific data */
  1183. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1184. int flags, int *pOutFlags);
  1185. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1186. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1187. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1188. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1189. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1190. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1191. void (*xDlClose)(sqlite3_vfs*, void*);
  1192. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1193. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1194. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1195. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1196. /* New fields may be appended in figure versions. The iVersion
  1197. ** value will increment whenever this happens. */
  1198. };
  1199. /*
  1200. ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
  1201. **
  1202. ** These integer constants can be used as the third parameter to
  1203. ** the xAccess method of an [sqlite3_vfs] object. {END} They determine
  1204. ** what kind of permissions the xAccess method is looking for.
  1205. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1206. ** simply checks whether the file exists.
  1207. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1208. ** checks whether the file is both readable and writable.
  1209. ** With SQLITE_ACCESS_READ, the xAccess method
  1210. ** checks whether the file is readable.
  1211. */
  1212. #define SQLITE_ACCESS_EXISTS 0
  1213. #define SQLITE_ACCESS_READWRITE 1
  1214. #define SQLITE_ACCESS_READ 2
  1215. /*
  1216. ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
  1217. **
  1218. ** The sqlite3_initialize() routine initializes the
  1219. ** SQLite library. The sqlite3_shutdown() routine
  1220. ** deallocates any resources that were allocated by sqlite3_initialize().
  1221. **
  1222. ** A call to sqlite3_initialize() is an "effective" call if it is
  1223. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1224. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1225. ** following a call to sqlite3_shutdown(). Only an effective call
  1226. ** of sqlite3_initialize() does any initialization. All other calls
  1227. ** are harmless no-ops.
  1228. **
  1229. ** Among other things, sqlite3_initialize() shall invoke
  1230. ** sqlite3_os_init(). Similarly, sqlite3_shutdown()
  1231. ** shall invoke sqlite3_os_end().
  1232. **
  1233. ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1234. ** If for some reason, sqlite3_initialize() is unable to initialize
  1235. ** the library (perhaps it is unable to allocate a needed resource such
  1236. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1237. **
  1238. ** The sqlite3_initialize() routine is called internally by many other
  1239. ** SQLite interfaces so that an application usually does not need to
  1240. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1241. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1242. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1243. ** already. However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1244. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1245. ** are omitted and the application must call sqlite3_initialize() directly
  1246. ** prior to using any other SQLite interface. For maximum portability,
  1247. ** it is recommended that applications always invoke sqlite3_initialize()
  1248. ** directly prior to using any other SQLite interface. Future releases
  1249. ** of SQLite may require this. In other words, the behavior exhibited
  1250. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1251. ** default behavior in some future release of SQLite.
  1252. **
  1253. ** The sqlite3_os_init() routine does operating-system specific
  1254. ** initialization of the SQLite library. The sqlite3_os_end()
  1255. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1256. ** performed by these routines include allocation or deallocation
  1257. ** of static resources, initialization of global variables,
  1258. ** setting up a default [sqlite3_vfs] module, or setting up
  1259. ** a default configuration using [sqlite3_config()].
  1260. **
  1261. ** The application should never invoke either sqlite3_os_init()
  1262. ** or sqlite3_os_end() directly. The application should only invoke
  1263. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1264. ** interface is called automatically by sqlite3_initialize() and
  1265. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1266. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1267. ** are built into SQLite when it is compiled for unix, windows, or os/2.
  1268. ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time
  1269. ** option) the application must supply a suitable implementation for
  1270. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1271. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1272. ** must return [SQLITE_OK] on success and some other [error code] upon
  1273. ** failure.
  1274. */
  1275. SQLITE_API int sqlite3_initialize(void);
  1276. SQLITE_API int sqlite3_shutdown(void);
  1277. SQLITE_API int sqlite3_os_init(void);
  1278. SQLITE_API int sqlite3_os_end(void);
  1279. /*
  1280. ** CAPI3REF: Configuring The SQLite Library {H14100} <S20000><S30200>
  1281. ** EXPERIMENTAL
  1282. **
  1283. ** The sqlite3_config() interface is used to make global configuration
  1284. ** changes to SQLite in order to tune SQLite to the specific needs of
  1285. ** the application. The default configuration is recommended for most
  1286. ** applications and so this routine is usually not necessary. It is
  1287. ** provided to support rare applications with unusual needs.
  1288. **
  1289. ** The sqlite3_config() interface is not threadsafe. The application
  1290. ** must insure that no other SQLite interfaces are invoked by other
  1291. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1292. ** may only be invoked prior to library initialization using
  1293. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1294. ** Note, however, that sqlite3_config() can be called as part of the
  1295. ** implementation of an application-defined [sqlite3_os_init()].
  1296. **
  1297. ** The first argument to sqlite3_config() is an integer
  1298. ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
  1299. ** what property of SQLite is to be configured. Subsequent arguments
  1300. ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
  1301. ** in the first argument.
  1302. **
  1303. ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1304. ** If the option is unknown or SQLite is unable to set the option
  1305. ** then this routine returns a non-zero [error code].
  1306. **
  1307. ** Requirements:
  1308. ** [H14103] [H14106] [H14120] [H14123] [H14126] [H14129] [H14132] [H14135]
  1309. ** [H14138] [H14141] [H14144] [H14147] [H14150] [H14153] [H14156] [H14159]
  1310. ** [H14162] [H14165] [H14168]
  1311. */
  1312. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
  1313. /*
  1314. ** CAPI3REF: Configure database connections {H14200} <S20000>
  1315. ** EXPERIMENTAL
  1316. **
  1317. ** The sqlite3_db_config() interface is used to make configuration
  1318. ** changes to a [database connection]. The interface is similar to
  1319. ** [sqlite3_config()] except that the changes apply to a single
  1320. ** [database connection] (specified in the first argument). The
  1321. ** sqlite3_db_config() interface can only be used immediately after
  1322. ** the database connection is created using [sqlite3_open()],
  1323. ** [sqlite3_open16()], or [sqlite3_open_v2()].
  1324. **
  1325. ** The second argument to sqlite3_db_config(D,V,...) is the
  1326. ** configuration verb - an integer code that indicates what
  1327. ** aspect of the [database connection] is being configured.
  1328. ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
  1329. ** New verbs are likely to be added in future releases of SQLite.
  1330. ** Additional arguments depend on the verb.
  1331. **
  1332. ** Requirements:
  1333. ** [H14203] [H14206] [H14209] [H14212] [H14215]
  1334. */
  1335. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
  1336. /*
  1337. ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
  1338. ** EXPERIMENTAL
  1339. **
  1340. ** An instance of this object defines the interface between SQLite
  1341. ** and low-level memory allocation routines.
  1342. **
  1343. ** This object is used in only one place in the SQLite interface.
  1344. ** A pointer to an instance of this object is the argument to
  1345. ** [sqlite3_config()] when the configuration option is
  1346. ** [SQLITE_CONFIG_MALLOC]. By creating an instance of this object
  1347. ** and passing it to [sqlite3_config()] during configuration, an
  1348. ** application can specify an alternative memory allocation subsystem
  1349. ** for SQLite to use for all of its dynamic memory needs.
  1350. **
  1351. ** Note that SQLite comes with a built-in memory allocator that is
  1352. ** perfectly adequate for the overwhelming majority of applications
  1353. ** and that this object is only useful to a tiny minority of applications
  1354. ** with specialized memory allocation requirements. This object is
  1355. ** also used during testing of SQLite in order to specify an alternative
  1356. ** memory allocator that simulates memory out-of-memory conditions in
  1357. ** order to verify that SQLite recovers gracefully from such
  1358. ** conditions.
  1359. **
  1360. ** The xMalloc, xFree, and xRealloc methods must work like the
  1361. ** malloc(), free(), and realloc() functions from the standard library.
  1362. **
  1363. ** xSize should return the allocated size of a memory allocation
  1364. ** previously obtained from xMalloc or xRealloc. The allocated size
  1365. ** is always at least as big as the requested size but may be larger.
  1366. **
  1367. ** The xRoundup method returns what would be the allocated size of
  1368. ** a memory allocation given a particular requested size. Most memory
  1369. ** allocators round up memory allocations at least to the next multiple
  1370. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1371. **
  1372. ** The xInit method initializes the memory allocator. (For example,
  1373. ** it might allocate any require mutexes or initialize internal data
  1374. ** structures. The xShutdown method is invoked (indirectly) by
  1375. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1376. ** by xInit. The pAppData pointer is used as the only parameter to
  1377. ** xInit and xShutdown.
  1378. */
  1379. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1380. struct sqlite3_mem_methods {
  1381. void *(*xMalloc)(int); /* Memory allocation function */
  1382. void (*xFree)(void*); /* Free a prior allocation */
  1383. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1384. int (*xSize)(void*); /* Return the size of an allocation */
  1385. int (*xRoundup)(int); /* Round up request size to allocation size */
  1386. int (*xInit)(void*); /* Initialize the memory allocator */
  1387. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1388. void *pAppData; /* Argument to xInit() and xShutdown() */
  1389. };
  1390. /*
  1391. ** CAPI3REF: Configuration Options {H10160} <S20000>
  1392. ** EXPERIMENTAL
  1393. **
  1394. ** These constants are the available integer configuration options that
  1395. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1396. **
  1397. ** New configuration options may be added in future releases of SQLite.
  1398. ** Existing configuration options might be discontinued. Applications
  1399. ** should check the return code from [sqlite3_config()] to make sure that
  1400. ** the call worked. The [sqlite3_config()] interface will return a
  1401. ** non-zero [error code] if a discontinued or unsupported configuration option
  1402. ** is invoked.
  1403. **
  1404. ** <dl>
  1405. ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1406. ** <dd>There are no arguments to this option. This option disables
  1407. ** all mutexing and puts SQLite into a mode where it can only be used
  1408. ** by a single thread.</dd>
  1409. **
  1410. ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1411. ** <dd>There are no arguments to this option. This option disables
  1412. ** mutexing on [database connection] and [prepared statement] objects.
  1413. ** The application is responsible for serializing access to
  1414. ** [database connections] and [prepared statements]. But other mutexes
  1415. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1416. ** environment as long as no two threads attempt to use the same
  1417. ** [database connection] at the same time. See the [threading mode]
  1418. ** documentation for additional information.</dd>
  1419. **
  1420. ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1421. ** <dd>There are no arguments to this option. This option enables
  1422. ** all mutexes including the recursive
  1423. ** mutexes on [database connection] and [prepared statement] objects.
  1424. ** In this mode (which is the default when SQLite is compiled with
  1425. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1426. ** to [database connections] and [prepared statements] so that the
  1427. ** application is free to use the same [database connection] or the
  1428. ** same [prepared statement] in different threads at the same time.
  1429. ** See the [threading mode] documentation for additional information.</dd>
  1430. **
  1431. ** <dt>SQLITE_CONFIG_MALLOC</dt>
  1432. ** <dd>This option takes a single argument which is a pointer to an
  1433. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1434. ** alternative low-level memory allocation routines to be used in place of
  1435. ** the memory allocation routines built into SQLite.</dd>
  1436. **
  1437. ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1438. ** <dd>This option takes a single argument which is a pointer to an
  1439. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1440. ** structure is filled with the currently defined memory allocation routines.
  1441. ** This option can be used to overload the default memory allocation
  1442. ** routines with a wrapper that simulations memory allocation failure or
  1443. ** tracks memory usage, for example.</dd>
  1444. **
  1445. ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1446. ** <dd>This option takes single argument of type int, interpreted as a
  1447. ** boolean, which enables or disables the collection of memory allocation
  1448. ** statistics. When disabled, the following SQLite interfaces become
  1449. ** non-operational:
  1450. ** <ul>
  1451. ** <li> [sqlite3_memory_used()]
  1452. ** <li> [sqlite3_memory_highwater()]
  1453. ** <li> [sqlite3_soft_heap_limit()]
  1454. ** <li> [sqlite3_status()]
  1455. ** </ul>
  1456. ** </dd>
  1457. **
  1458. ** <dt>SQLITE_CONFIG_SCRATCH</dt>
  1459. ** <dd>This option specifies a static memory buffer that SQLite can use for
  1460. ** scratch memory. There are three arguments: A pointer to the memory, the
  1461. ** size of each scratch buffer (sz), and the number of buffers (N). The sz
  1462. ** argument must be a multiple of 16. The sz parameter should be a few bytes
  1463. ** larger than the actual scratch space required due internal overhead.
  1464. ** The first
  1465. ** argument should point to an allocation of at least sz*N bytes of memory.
  1466. ** SQLite will use no more than one scratch buffer at once per thread, so
  1467. ** N should be set to the expected maximum number of threads. The sz
  1468. ** parameter should be 6 times the size of the largest database page size.
  1469. ** Scratch buffers are used as part of the btree balance operation. If
  1470. ** The btree balancer needs additional memory beyond what is provided by
  1471. ** scratch buffers or if no scratch buffer space is specified, then SQLite
  1472. ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
  1473. **
  1474. ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1475. ** <dd>This option specifies a static memory buffer that SQLite can use for
  1476. ** the database page cache with the default page cache implemenation.
  1477. ** This configuration should not be used if an application-define page
  1478. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
  1479. ** There are three arguments to this option: A pointer to the
  1480. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1481. ** The sz argument must be a power of two between 512 and 32768. The first
  1482. ** argument should point to an allocation of at least sz*N bytes of memory.
  1483. ** SQLite will use the memory provided by the first argument to satisfy its
  1484. ** memory needs for the first N pages that it adds to cache. If additional
  1485. ** page cache memory is needed beyond what is provided by this option, then
  1486. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1487. ** The implementation might use one or more of the N buffers to hold
  1488. ** memory accounting information. </dd>
  1489. **
  1490. ** <dt>SQLITE_CONFIG_HEAP</dt>
  1491. ** <dd>This option specifies a static memory buffer that SQLite will use
  1492. ** for all of its dynamic memory allocation needs beyond those provided
  1493. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1494. ** There are three arguments: A pointer to the memory, the number of
  1495. ** bytes in the memory buffer, and the minimum allocation size. If
  1496. ** the first pointer (the memory pointer) is NULL, then SQLite reverts
  1497. ** to using its default memory allocator (the system malloc() implementation),
  1498. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the
  1499. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1500. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1501. ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
  1502. **
  1503. ** <dt>SQLITE_CONFIG_MUTEX</dt>
  1504. ** <dd>This option takes a single argument which is a pointer to an
  1505. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1506. ** alternative low-level mutex routines to be used in place
  1507. ** the mutex routines built into SQLite.</dd>
  1508. **
  1509. ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1510. ** <dd>This option takes a single argument which is a pointer to an
  1511. ** instance of the [sqlite3_mutex_methods] structure. The
  1512. ** [sqlite3_mutex_methods]
  1513. ** structure is filled with the currently defined mutex routines.
  1514. ** This option can be used to overload the default mutex allocation
  1515. ** routines with a wrapper used to track mutex usage for performance
  1516. ** profiling or testing, for example.</dd>
  1517. **
  1518. ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1519. ** <dd>This option takes two arguments that determine the default
  1520. ** memory allcation lookaside optimization. The first argument is the
  1521. ** size of each lookaside buffer slot and the second is the number of
  1522. ** slots allocated to each database connection.</dd>
  1523. **
  1524. ** <dt>SQLITE_CONFIG_PCACHE</dt>
  1525. ** <dd>This option takes a single argument which is a pointer to
  1526. ** an [sqlite3_pcache_methods] object. This object specifies the interface
  1527. ** to a custom page cache implementation. SQLite makes a copy of the
  1528. ** object and uses it for page cache memory allocations.</dd>
  1529. **
  1530. ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
  1531. ** <dd>This option takes a single argument which is a pointer to an
  1532. ** [sqlite3_pcache_methods] object. SQLite copies of the current
  1533. ** page cache implementation into that object.</dd>
  1534. **
  1535. ** </dl>
  1536. */
  1537. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1538. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1539. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1540. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1541. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1542. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1543. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1544. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1545. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1546. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1547. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1548. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1549. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1550. #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
  1551. #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
  1552. /*
  1553. ** CAPI3REF: Configuration Options {H10170} <S20000>
  1554. ** EXPERIMENTAL
  1555. **
  1556. ** These constants are the available integer configuration options that
  1557. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1558. **
  1559. ** New configuration options may be added in future releases of SQLite.
  1560. ** Existing configuration options might be discontinued. Applications
  1561. ** should check the return code from [sqlite3_db_config()] to make sure that
  1562. ** the call worked. The [sqlite3_db_config()] interface will return a
  1563. ** non-zero [error code] if a discontinued or unsupported configuration option
  1564. ** is invoked.
  1565. **
  1566. ** <dl>
  1567. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1568. ** <dd>This option takes three additional arguments that determine the
  1569. ** [lookaside memory allocator] configuration for the [database connection].
  1570. ** The first argument (the third parameter to [sqlite3_db_config()] is a
  1571. ** pointer to a memory buffer to use for lookaside memory. The first
  1572. ** argument may be NULL in which case SQLite will allocate the lookaside
  1573. ** buffer itself using [sqlite3_malloc()]. The second argument is the
  1574. ** size of each lookaside buffer slot and the third argument is the number of
  1575. ** slots. The size of the buffer in the first argument must be greater than
  1576. ** or equal to the product of the second and third arguments.</dd>
  1577. **
  1578. ** </dl>
  1579. */
  1580. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1581. /*
  1582. ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
  1583. **
  1584. ** The sqlite3_extended_result_codes() routine enables or disables the
  1585. ** [extended result codes] feature of SQLite. The extended result
  1586. ** codes are disabled by default for historical compatibility considerations.
  1587. **
  1588. ** Requirements:
  1589. ** [H12201] [H12202]
  1590. */
  1591. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1592. /*
  1593. ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
  1594. **
  1595. ** Each entry in an SQLite table has a unique 64-bit signed
  1596. ** integer key called the [ROWID | "rowid"]. The rowid is always available
  1597. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1598. ** names are not also used by explicitly declared columns. If
  1599. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1600. ** is another alias for the rowid.
  1601. **
  1602. ** This routine returns the [rowid] of the most recent
  1603. ** successful [INSERT] into the database from the [database connection]
  1604. ** in the first argument. If no successful [INSERT]s
  1605. ** have ever occurred on that database connection, zero is returned.
  1606. **
  1607. ** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
  1608. ** row is returned by this routine as long as the trigger is running.
  1609. ** But once the trigger terminates, the value returned by this routine
  1610. ** reverts to the last value inserted before the trigger fired.
  1611. **
  1612. ** An [INSERT] that fails due to a constraint violation is not a
  1613. ** successful [INSERT] and does not change the value returned by this
  1614. ** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1615. ** and INSERT OR ABORT make no changes to the return value of this
  1616. ** routine when their insertion fails. When INSERT OR REPLACE
  1617. ** encounters a constraint violation, it does not fail. The
  1618. ** INSERT continues to completion after deleting rows that caused
  1619. ** the constraint problem so INSERT OR REPLACE will always change
  1620. ** the return value of this interface.
  1621. **
  1622. ** For the purposes of this routine, an [INSERT] is considered to
  1623. ** be successful even if it is subsequently rolled back.
  1624. **
  1625. ** Requirements:
  1626. ** [H12221] [H12223]
  1627. **
  1628. ** If a separate thread performs a new [INSERT] on the same
  1629. ** database connection while the [sqlite3_last_insert_rowid()]
  1630. ** function is running and thus changes the last insert [rowid],
  1631. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1632. ** unpredictable and might not equal either the old or the new
  1633. ** last insert [rowid].
  1634. */
  1635. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1636. /*
  1637. ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
  1638. **
  1639. ** This function returns the number of database rows that were changed
  1640. ** or inserted or deleted by the most recently completed SQL statement
  1641. ** on the [database connection] specified by the first parameter.
  1642. ** Only changes that are directly specified by the [INSERT], [UPDATE],
  1643. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1644. ** triggers are not counted. Use the [sqlite3_total_changes()] function
  1645. ** to find the total number of changes including changes caused by triggers.
  1646. **
  1647. ** A "row change" is a change to a single row of a single table
  1648. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1649. ** are changed as side effects of REPLACE constraint resolution,
  1650. ** rollback, ABORT processing, DROP TABLE, or by any other
  1651. ** mechanisms do not count as direct row changes.
  1652. **
  1653. ** A "trigger context" is a scope of execution that begins and
  1654. ** ends with the script of a trigger. Most SQL statements are
  1655. ** evaluated outside of any trigger. This is the "top level"
  1656. ** trigger context. If a trigger fires from the top level, a
  1657. ** new trigger context is entered for the duration of that one
  1658. ** trigger. Subtriggers create subcontexts for their duration.
  1659. **
  1660. ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1661. ** not create a new trigger context.
  1662. **
  1663. ** This function returns the number of direct row changes in the
  1664. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1665. ** trigger context.
  1666. **
  1667. ** Thus, when called from the top level, this function returns the
  1668. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1669. ** that also occurred at the top level. Within the body of a trigger,
  1670. ** the sqlite3_changes() interface can be called to find the number of
  1671. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1672. ** statement within the body of the same trigger.
  1673. ** However, the number returned does not include changes
  1674. ** caused by subtriggers since those have their own context.
  1675. **
  1676. ** SQLite implements the command "DELETE FROM table" without a WHERE clause
  1677. ** by dropping and recreating the table. Doing so is much faster than going
  1678. ** through and deleting individual elements from the table. Because of this
  1679. ** optimization, the deletions in "DELETE FROM table" are not row changes and
  1680. ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
  1681. ** functions, regardless of the number of elements that were originally
  1682. ** in the table. To get an accurate count of the number of rows deleted, use
  1683. ** "DELETE FROM table WHERE 1" instead. Or recompile using the
  1684. ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
  1685. ** optimization on all queries.
  1686. **
  1687. ** Requirements:
  1688. ** [H12241] [H12243]
  1689. **
  1690. ** If a separate thread makes changes on the same database connection
  1691. ** while [sqlite3_changes()] is running then the value returned
  1692. ** is unpredictable and not meaningful.
  1693. */
  1694. SQLITE_API int sqlite3_changes(sqlite3*);
  1695. /*
  1696. ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
  1697. **
  1698. ** This function returns the number of row changes caused by INSERT,
  1699. ** UPDATE or DELETE statements since the [database connection] was opened.
  1700. ** The count includes all changes from all trigger contexts. However,
  1701. ** the count does not include changes used to implement REPLACE constraints,
  1702. ** do rollbacks or ABORT processing, or DROP table processing.
  1703. ** The changes are counted as soon as the statement that makes them is
  1704. ** completed (when the statement handle is passed to [sqlite3_reset()] or
  1705. ** [sqlite3_finalize()]).
  1706. **
  1707. ** SQLite implements the command "DELETE FROM table" without a WHERE clause
  1708. ** by dropping and recreating the table. (This is much faster than going
  1709. ** through and deleting individual elements from the table.) Because of this
  1710. ** optimization, the deletions in "DELETE FROM table" are not row changes and
  1711. ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
  1712. ** functions, regardless of the number of elements that were originally
  1713. ** in the table. To get an accurate count of the number of rows deleted, use
  1714. ** "DELETE FROM table WHERE 1" instead. Or recompile using the
  1715. ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
  1716. ** optimization on all queries.
  1717. **
  1718. ** See also the [sqlite3_changes()] interface.
  1719. **
  1720. ** Requirements:
  1721. ** [H12261] [H12263]
  1722. **
  1723. ** If a separate thread makes changes on the same database connection
  1724. ** while [sqlite3_total_changes()] is running then the value
  1725. ** returned is unpredictable and not meaningful.
  1726. */
  1727. SQLITE_API int sqlite3_total_changes(sqlite3*);
  1728. /*
  1729. ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
  1730. **
  1731. ** This function causes any pending database operation to abort and
  1732. ** return at its earliest opportunity. This routine is typically
  1733. ** called in response to a user action such as pressing "Cancel"
  1734. ** or Ctrl-C where the user wants a long query operation to halt
  1735. ** immediately.
  1736. **
  1737. ** It is safe to call this routine from a thread different from the
  1738. ** thread that is currently running the database operation. But it
  1739. ** is not safe to call this routine with a [database connection] that
  1740. ** is closed or might close before sqlite3_interrupt() returns.
  1741. **
  1742. ** If an SQL operation is very nearly finished at the time when
  1743. ** sqlite3_interrupt() is called, then it might not have an opportunity
  1744. ** to be interrupted and might continue to completion.
  1745. **
  1746. ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  1747. ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  1748. ** that is inside an explicit transaction, then the entire transaction
  1749. ** will be rolled back automatically.
  1750. **
  1751. ** A call to sqlite3_interrupt() has no effect on SQL statements
  1752. ** that are started after sqlite3_interrupt() returns.
  1753. **
  1754. ** Requirements:
  1755. ** [H12271] [H12272]
  1756. **
  1757. ** If the database connection closes while [sqlite3_interrupt()]
  1758. ** is running then bad things will likely happen.
  1759. */
  1760. SQLITE_API void sqlite3_interrupt(sqlite3*);
  1761. /*
  1762. ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
  1763. **
  1764. ** These routines are useful for command-line input to determine if the
  1765. ** currently entered text seems to form complete a SQL statement or
  1766. ** if additional input is needed before sending the text into
  1767. ** SQLite for parsing. These routines return true if the input string
  1768. ** appears to be a complete SQL statement. A statement is judged to be
  1769. ** complete if it ends with a semicolon token and is not a fragment of a
  1770. ** CREATE TRIGGER statement. Semicolons that are embedded within
  1771. ** string literals or quoted identifier names or comments are not
  1772. ** independent tokens (they are part of the token in which they are
  1773. ** embedded) and thus do not count as a statement terminator.
  1774. **
  1775. ** These routines do not parse the SQL statements thus
  1776. ** will not detect syntactically incorrect SQL.
  1777. **
  1778. ** Requirements: [H10511] [H10512]
  1779. **
  1780. ** The input to [sqlite3_complete()] must be a zero-terminated
  1781. ** UTF-8 string.
  1782. **
  1783. ** The input to [sqlite3_complete16()] must be a zero-terminated
  1784. ** UTF-16 string in native byte order.
  1785. */
  1786. SQLITE_API int sqlite3_complete(const char *sql);
  1787. SQLITE_API int sqlite3_complete16(const void *sql);
  1788. /*
  1789. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
  1790. **
  1791. ** This routine sets a callback function that might be invoked whenever
  1792. ** an attempt is made to open a database table that another thread
  1793. ** or process has locked.
  1794. **
  1795. ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  1796. ** is returned immediately upon encountering the lock. If the busy callback
  1797. ** is not NULL, then the callback will be invoked with two arguments.
  1798. **
  1799. ** The first argument to the handler is a copy of the void* pointer which
  1800. ** is the third argument to sqlite3_busy_handler(). The second argument to
  1801. ** the handler callback is the number of times that the busy handler has
  1802. ** been invoked for this locking event. If the
  1803. ** busy callback returns 0, then no additional attempts are made to
  1804. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  1805. ** If the callback returns non-zero, then another attempt
  1806. ** is made to open the database for reading and the cycle repeats.
  1807. **
  1808. ** The presence of a busy handler does not guarantee that it will be invoked
  1809. ** when there is lock contention. If SQLite determines that invoking the busy
  1810. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  1811. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  1812. ** Consider a scenario where one process is holding a read lock that
  1813. ** it is trying to promote to a reserved lock and
  1814. ** a second process is holding a reserved lock that it is trying
  1815. ** to promote to an exclusive lock. The first process cannot proceed
  1816. ** because it is blocked by the second and the second process cannot
  1817. ** proceed because it is blocked by the first. If both processes
  1818. ** invoke the busy handlers, neither will make any progress. Therefore,
  1819. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  1820. ** will induce the first process to release its read lock and allow
  1821. ** the second process to proceed.
  1822. **
  1823. ** The default busy callback is NULL.
  1824. **
  1825. ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  1826. ** when SQLite is in the middle of a large transaction where all the
  1827. ** changes will not fit into the in-memory cache. SQLite will
  1828. ** already hold a RESERVED lock on the database file, but it needs
  1829. ** to promote this lock to EXCLUSIVE so that it can spill cache
  1830. ** pages into the database file without harm to concurrent
  1831. ** readers. If it is unable to promote the lock, then the in-memory
  1832. ** cache will be left in an inconsistent state and so the error
  1833. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  1834. ** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion
  1835. ** forces an automatic rollback of the changes. See the
  1836. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  1837. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  1838. ** this is important.
  1839. **
  1840. ** There can only be a single busy handler defined for each
  1841. ** [database connection]. Setting a new busy handler clears any
  1842. ** previously set handler. Note that calling [sqlite3_busy_timeout()]
  1843. ** will also set or clear the busy handler.
  1844. **
  1845. ** The busy callback should not take any actions which modify the
  1846. ** database connection that invoked the busy handler. Any such actions
  1847. ** result in undefined behavior.
  1848. **
  1849. ** Requirements:
  1850. ** [H12311] [H12312] [H12314] [H12316] [H12318]
  1851. **
  1852. ** A busy handler must not close the database connection
  1853. ** or [prepared statement] that invoked the busy handler.
  1854. */
  1855. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  1856. /*
  1857. ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
  1858. **
  1859. ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  1860. ** for a specified amount of time when a table is locked. The handler
  1861. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  1862. ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
  1863. ** the handler returns 0 which causes [sqlite3_step()] to return
  1864. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  1865. **
  1866. ** Calling this routine with an argument less than or equal to zero
  1867. ** turns off all busy handlers.
  1868. **
  1869. ** There can only be a single busy handler for a particular
  1870. ** [database connection] any any given moment. If another busy handler
  1871. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  1872. ** this routine, that other busy handler is cleared.
  1873. **
  1874. ** Requirements:
  1875. ** [H12341] [H12343] [H12344]
  1876. */
  1877. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  1878. /*
  1879. ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
  1880. **
  1881. ** Definition: A <b>result table</b> is memory data structure created by the
  1882. ** [sqlite3_get_table()] interface. A result table records the
  1883. ** complete query results from one or more queries.
  1884. **
  1885. ** The table conceptually has a number of rows and columns. But
  1886. ** these numbers are not part of the result table itself. These
  1887. ** numbers are obtained separately. Let N be the number of rows
  1888. ** and M be the number of columns.
  1889. **
  1890. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  1891. ** There are (N+1)*M elements in the array. The first M pointers point
  1892. ** to zero-terminated strings that contain the names of the columns.
  1893. ** The remaining entries all point to query results. NULL values result
  1894. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  1895. ** string representation as returned by [sqlite3_column_text()].
  1896. **
  1897. ** A result table might consist of one or more memory allocations.
  1898. ** It is not safe to pass a result table directly to [sqlite3_free()].
  1899. ** A result table should be deallocated using [sqlite3_free_table()].
  1900. **
  1901. ** As an example of the result table format, suppose a query result
  1902. ** is as follows:
  1903. **
  1904. ** <blockquote><pre>
  1905. ** Name | Age
  1906. ** -----------------------
  1907. ** Alice | 43
  1908. ** Bob | 28
  1909. ** Cindy | 21
  1910. ** </pre></blockquote>
  1911. **
  1912. ** There are two column (M==2) and three rows (N==3). Thus the
  1913. ** result table has 8 entries. Suppose the result table is stored
  1914. ** in an array names azResult. Then azResult holds this content:
  1915. **
  1916. ** <blockquote><pre>
  1917. ** azResult&#91;0] = "Name";
  1918. ** azResult&#91;1] = "Age";
  1919. ** azResult&#91;2] = "Alice";
  1920. ** azResult&#91;3] = "43";
  1921. ** azResult&#91;4] = "Bob";
  1922. ** azResult&#91;5] = "28";
  1923. ** azResult&#91;6] = "Cindy";
  1924. ** azResult&#91;7] = "21";
  1925. ** </pre></blockquote>
  1926. **
  1927. ** The sqlite3_get_table() function evaluates one or more
  1928. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  1929. ** string of its 2nd parameter. It returns a result table to the
  1930. ** pointer given in its 3rd parameter.
  1931. **
  1932. ** After the calling function has finished using the result, it should
  1933. ** pass the pointer to the result table to sqlite3_free_table() in order to
  1934. ** release the memory that was malloced. Because of the way the
  1935. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  1936. ** function must not try to call [sqlite3_free()] directly. Only
  1937. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  1938. **
  1939. ** The sqlite3_get_table() interface is implemented as a wrapper around
  1940. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  1941. ** to any internal data structures of SQLite. It uses only the public
  1942. ** interface defined here. As a consequence, errors that occur in the
  1943. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  1944. ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
  1945. **
  1946. ** Requirements:
  1947. ** [H12371] [H12373] [H12374] [H12376] [H12379] [H12382]
  1948. */
  1949. SQLITE_API int sqlite3_get_table(
  1950. sqlite3 *db, /* An open database */
  1951. const char *zSql, /* SQL to be evaluated */
  1952. char ***pazResult, /* Results of the query */
  1953. int *pnRow, /* Number of result rows written here */
  1954. int *pnColumn, /* Number of result columns written here */
  1955. char **pzErrmsg /* Error msg written here */
  1956. );
  1957. SQLITE_API void sqlite3_free_table(char **result);
  1958. /*
  1959. ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
  1960. **
  1961. ** These routines are workalikes of the "printf()" family of functions
  1962. ** from the standard C library.
  1963. **
  1964. ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  1965. ** results into memory obtained from [sqlite3_malloc()].
  1966. ** The strings returned by these two routines should be
  1967. ** released by [sqlite3_free()]. Both routines return a
  1968. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  1969. ** memory to hold the resulting string.
  1970. **
  1971. ** In sqlite3_snprintf() routine is similar to "snprintf()" from
  1972. ** the standard C library. The result is written into the
  1973. ** buffer supplied as the second parameter whose size is given by
  1974. ** the first parameter. Note that the order of the
  1975. ** first two parameters is reversed from snprintf(). This is an
  1976. ** historical accident that cannot be fixed without breaking
  1977. ** backwards compatibility. Note also that sqlite3_snprintf()
  1978. ** returns a pointer to its buffer instead of the number of
  1979. ** characters actually written into the buffer. We admit that
  1980. ** the number of characters written would be a more useful return
  1981. ** value but we cannot change the implementation of sqlite3_snprintf()
  1982. ** now without breaking compatibility.
  1983. **
  1984. ** As long as the buffer size is greater than zero, sqlite3_snprintf()
  1985. ** guarantees that the buffer is always zero-terminated. The first
  1986. ** parameter "n" is the total size of the buffer, including space for
  1987. ** the zero terminator. So the longest string that can be completely
  1988. ** written will be n-1 characters.
  1989. **
  1990. ** These routines all implement some additional formatting
  1991. ** options that are useful for constructing SQL statements.
  1992. ** All of the usual printf() formatting options apply. In addition, there
  1993. ** is are "%q", "%Q", and "%z" options.
  1994. **
  1995. ** The %q option works like %s in that it substitutes a null-terminated
  1996. ** string from the argument list. But %q also doubles every '\'' character.
  1997. ** %q is designed for use inside a string literal. By doubling each '\''
  1998. ** character it escapes that character and allows it to be inserted into
  1999. ** the string.
  2000. **
  2001. ** For example, assume the string variable zText contains text as follows:
  2002. **
  2003. ** <blockquote><pre>
  2004. ** char *zText = "It's a happy day!";
  2005. ** </pre></blockquote>
  2006. **
  2007. ** One can use this text in an SQL statement as follows:
  2008. **
  2009. ** <blockquote><pre>
  2010. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2011. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2012. ** sqlite3_free(zSQL);
  2013. ** </pre></blockquote>
  2014. **
  2015. ** Because the %q format string is used, the '\'' character in zText
  2016. ** is escaped and the SQL generated is as follows:
  2017. **
  2018. ** <blockquote><pre>
  2019. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2020. ** </pre></blockquote>
  2021. **
  2022. ** This is correct. Had we used %s instead of %q, the generated SQL
  2023. ** would have looked like this:
  2024. **
  2025. ** <blockquote><pre>
  2026. ** INSERT INTO table1 VALUES('It's a happy day!');
  2027. ** </pre></blockquote>
  2028. **
  2029. ** This second example is an SQL syntax error. As a general rule you should
  2030. ** always use %q instead of %s when inserting text into a string literal.
  2031. **
  2032. ** The %Q option works like %q except it also adds single quotes around
  2033. ** the outside of the total string. Additionally, if the parameter in the
  2034. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2035. ** single quotes) in place of the %Q option. So, for example, one could say:
  2036. **
  2037. ** <blockquote><pre>
  2038. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2039. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2040. ** sqlite3_free(zSQL);
  2041. ** </pre></blockquote>
  2042. **
  2043. ** The code above will render a correct SQL statement in the zSQL
  2044. ** variable even if the zText variable is a NULL pointer.
  2045. **
  2046. ** The "%z" formatting option works exactly like "%s" with the
  2047. ** addition that after the string has been read and copied into
  2048. ** the result, [sqlite3_free()] is called on the input string. {END}
  2049. **
  2050. ** Requirements:
  2051. ** [H17403] [H17406] [H17407]
  2052. */
  2053. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2054. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2055. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2056. /*
  2057. ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
  2058. **
  2059. ** The SQLite core uses these three routines for all of its own
  2060. ** internal memory allocation needs. "Core" in the previous sentence
  2061. ** does not include operating-system specific VFS implementation. The
  2062. ** Windows VFS uses native malloc() and free() for some operations.
  2063. **
  2064. ** The sqlite3_malloc() routine returns a pointer to a block
  2065. ** of memory at least N bytes in length, where N is the parameter.
  2066. ** If sqlite3_malloc() is unable to obtain sufficient free
  2067. ** memory, it returns a NULL pointer. If the parameter N to
  2068. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2069. ** a NULL pointer.
  2070. **
  2071. ** Calling sqlite3_free() with a pointer previously returned
  2072. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2073. ** that it might be reused. The sqlite3_free() routine is
  2074. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2075. ** to sqlite3_free() is harmless. After being freed, memory
  2076. ** should neither be read nor written. Even reading previously freed
  2077. ** memory might result in a segmentation fault or other severe error.
  2078. ** Memory corruption, a segmentation fault, or other severe error
  2079. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2080. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2081. **
  2082. ** The sqlite3_realloc() interface attempts to resize a
  2083. ** prior memory allocation to be at least N bytes, where N is the
  2084. ** second parameter. The memory allocation to be resized is the first
  2085. ** parameter. If the first parameter to sqlite3_realloc()
  2086. ** is a NULL pointer then its behavior is identical to calling
  2087. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2088. ** If the second parameter to sqlite3_realloc() is zero or
  2089. ** negative then the behavior is exactly the same as calling
  2090. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2091. ** sqlite3_realloc() returns a pointer to a memory allocation
  2092. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2093. ** If M is the size of the prior allocation, then min(N,M) bytes
  2094. ** of the prior allocation are copied into the beginning of buffer returned
  2095. ** by sqlite3_realloc() and the prior allocation is freed.
  2096. ** If sqlite3_realloc() returns NULL, then the prior allocation
  2097. ** is not freed.
  2098. **
  2099. ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2100. ** is always aligned to at least an 8 byte boundary. {END}
  2101. **
  2102. ** The default implementation of the memory allocation subsystem uses
  2103. ** the malloc(), realloc() and free() provided by the standard C library.
  2104. ** {H17382} However, if SQLite is compiled with the
  2105. ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
  2106. ** is an integer), then SQLite create a static array of at least
  2107. ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
  2108. ** memory allocation needs. {END} Additional memory allocator options
  2109. ** may be added in future releases.
  2110. **
  2111. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2112. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2113. ** implementation of these routines to be omitted. That capability
  2114. ** is no longer provided. Only built-in memory allocators can be used.
  2115. **
  2116. ** The Windows OS interface layer calls
  2117. ** the system malloc() and free() directly when converting
  2118. ** filenames between the UTF-8 encoding used by SQLite
  2119. ** and whatever filename encoding is used by the particular Windows
  2120. ** installation. Memory allocation errors are detected, but
  2121. ** they are reported back as [SQLITE_CANTOPEN] or
  2122. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2123. **
  2124. ** Requirements:
  2125. ** [H17303] [H17304] [H17305] [H17306] [H17310] [H17312] [H17315] [H17318]
  2126. ** [H17321] [H17322] [H17323]
  2127. **
  2128. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2129. ** must be either NULL or else pointers obtained from a prior
  2130. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2131. ** not yet been released.
  2132. **
  2133. ** The application must not read or write any part of
  2134. ** a block of memory after it has been released using
  2135. ** [sqlite3_free()] or [sqlite3_realloc()].
  2136. */
  2137. SQLITE_API void *sqlite3_malloc(int);
  2138. SQLITE_API void *sqlite3_realloc(void*, int);
  2139. SQLITE_API void sqlite3_free(void*);
  2140. /*
  2141. ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
  2142. **
  2143. ** SQLite provides these two interfaces for reporting on the status
  2144. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2145. ** routines, which form the built-in memory allocation subsystem.
  2146. **
  2147. ** Requirements:
  2148. ** [H17371] [H17373] [H17374] [H17375]
  2149. */
  2150. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2151. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2152. /*
  2153. ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
  2154. **
  2155. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2156. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2157. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2158. ** the build-in random() and randomblob() SQL functions. This interface allows
  2159. ** applications to access the same PRNG for other purposes.
  2160. **
  2161. ** A call to this routine stores N bytes of randomness into buffer P.
  2162. **
  2163. ** The first time this routine is invoked (either internally or by
  2164. ** the application) the PRNG is seeded using randomness obtained
  2165. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2166. ** On all subsequent invocations, the pseudo-randomness is generated
  2167. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2168. ** method.
  2169. **
  2170. ** Requirements:
  2171. ** [H17392]
  2172. */
  2173. SQLITE_API void sqlite3_randomness(int N, void *P);
  2174. /*
  2175. ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
  2176. **
  2177. ** This routine registers a authorizer callback with a particular
  2178. ** [database connection], supplied in the first argument.
  2179. ** The authorizer callback is invoked as SQL statements are being compiled
  2180. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2181. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various
  2182. ** points during the compilation process, as logic is being created
  2183. ** to perform various actions, the authorizer callback is invoked to
  2184. ** see if those actions are allowed. The authorizer callback should
  2185. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2186. ** specific action but allow the SQL statement to continue to be
  2187. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2188. ** rejected with an error. If the authorizer callback returns
  2189. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2190. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2191. ** the authorizer will fail with an error message.
  2192. **
  2193. ** When the callback returns [SQLITE_OK], that means the operation
  2194. ** requested is ok. When the callback returns [SQLITE_DENY], the
  2195. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2196. ** authorizer will fail with an error message explaining that
  2197. ** access is denied. If the authorizer code is [SQLITE_READ]
  2198. ** and the callback returns [SQLITE_IGNORE] then the
  2199. ** [prepared statement] statement is constructed to substitute
  2200. ** a NULL value in place of the table column that would have
  2201. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2202. ** return can be used to deny an untrusted user access to individual
  2203. ** columns of a table.
  2204. **
  2205. ** The first parameter to the authorizer callback is a copy of the third
  2206. ** parameter to the sqlite3_set_authorizer() interface. The second parameter
  2207. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2208. ** the particular action to be authorized. The third through sixth parameters
  2209. ** to the callback are zero-terminated strings that contain additional
  2210. ** details about the action to be authorized.
  2211. **
  2212. ** An authorizer is used when [sqlite3_prepare | preparing]
  2213. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2214. ** do not try to access data they are not allowed to see, or that they do not
  2215. ** try to execute malicious statements that damage the database. For
  2216. ** example, an application may allow a user to enter arbitrary
  2217. ** SQL queries for evaluation by a database. But the application does
  2218. ** not want the user to be able to make arbitrary changes to the
  2219. ** database. An authorizer could then be put in place while the
  2220. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2221. ** disallows everything except [SELECT] statements.
  2222. **
  2223. ** Applications that need to process SQL from untrusted sources
  2224. ** might also consider lowering resource limits using [sqlite3_limit()]
  2225. ** and limiting database size using the [max_page_count] [PRAGMA]
  2226. ** in addition to using an authorizer.
  2227. **
  2228. ** Only a single authorizer can be in place on a database connection
  2229. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2230. ** previous call. Disable the authorizer by installing a NULL callback.
  2231. ** The authorizer is disabled by default.
  2232. **
  2233. ** The authorizer callback must not do anything that will modify
  2234. ** the database connection that invoked the authorizer callback.
  2235. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2236. ** database connections for the meaning of "modify" in this paragraph.
  2237. **
  2238. ** When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2239. ** statement might be reprepared during [sqlite3_step()] due to a
  2240. ** schema change. Hence, the application should ensure that the
  2241. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2242. **
  2243. ** Note that the authorizer callback is invoked only during
  2244. ** [sqlite3_prepare()] or its variants. Authorization is not
  2245. ** performed during statement evaluation in [sqlite3_step()].
  2246. **
  2247. ** Requirements:
  2248. ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
  2249. ** [H12511] [H12512] [H12520] [H12521] [H12522]
  2250. */
  2251. SQLITE_API int sqlite3_set_authorizer(
  2252. sqlite3*,
  2253. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2254. void *pUserData
  2255. );
  2256. /*
  2257. ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
  2258. **
  2259. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2260. ** return either [SQLITE_OK] or one of these two constants in order
  2261. ** to signal SQLite whether or not the action is permitted. See the
  2262. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2263. ** information.
  2264. */
  2265. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2266. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2267. /*
  2268. ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
  2269. **
  2270. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2271. ** that is invoked to authorize certain SQL statement actions. The
  2272. ** second parameter to the callback is an integer code that specifies
  2273. ** what action is being authorized. These are the integer action codes that
  2274. ** the authorizer callback may be passed.
  2275. **
  2276. ** These action code values signify what kind of operation is to be
  2277. ** authorized. The 3rd and 4th parameters to the authorization
  2278. ** callback function will be parameters or NULL depending on which of these
  2279. ** codes is used as the second parameter. The 5th parameter to the
  2280. ** authorizer callback is the name of the database ("main", "temp",
  2281. ** etc.) if applicable. The 6th parameter to the authorizer callback
  2282. ** is the name of the inner-most trigger or view that is responsible for
  2283. ** the access attempt or NULL if this access attempt is directly from
  2284. ** top-level SQL code.
  2285. **
  2286. ** Requirements:
  2287. ** [H12551] [H12552] [H12553] [H12554]
  2288. */
  2289. /******************************************* 3rd ************ 4th ***********/
  2290. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2291. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2292. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2293. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2294. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2295. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2296. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2297. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2298. #define SQLITE_DELETE 9 /* Table Name NULL */
  2299. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2300. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2301. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2302. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2303. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2304. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2305. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2306. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2307. #define SQLITE_INSERT 18 /* Table Name NULL */
  2308. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2309. #define SQLITE_READ 20 /* Table Name Column Name */
  2310. #define SQLITE_SELECT 21 /* NULL NULL */
  2311. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2312. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2313. #define SQLITE_ATTACH 24 /* Filename NULL */
  2314. #define SQLITE_DETACH 25 /* Database Name NULL */
  2315. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2316. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2317. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2318. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2319. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2320. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2321. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2322. #define SQLITE_COPY 0 /* No longer used */
  2323. /*
  2324. ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
  2325. ** EXPERIMENTAL
  2326. **
  2327. ** These routines register callback functions that can be used for
  2328. ** tracing and profiling the execution of SQL statements.
  2329. **
  2330. ** The callback function registered by sqlite3_trace() is invoked at
  2331. ** various times when an SQL statement is being run by [sqlite3_step()].
  2332. ** The callback returns a UTF-8 rendering of the SQL statement text
  2333. ** as the statement first begins executing. Additional callbacks occur
  2334. ** as each triggered subprogram is entered. The callbacks for triggers
  2335. ** contain a UTF-8 SQL comment that identifies the trigger.
  2336. **
  2337. ** The callback function registered by sqlite3_profile() is invoked
  2338. ** as each SQL statement finishes. The profile callback contains
  2339. ** the original statement text and an estimate of wall-clock time
  2340. ** of how long that statement took to run.
  2341. **
  2342. ** Requirements:
  2343. ** [H12281] [H12282] [H12283] [H12284] [H12285] [H12287] [H12288] [H12289]
  2344. ** [H12290]
  2345. */
  2346. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2347. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2348. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2349. /*
  2350. ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
  2351. **
  2352. ** This routine configures a callback function - the
  2353. ** progress callback - that is invoked periodically during long
  2354. ** running calls to [sqlite3_exec()], [sqlite3_step()] and
  2355. ** [sqlite3_get_table()]. An example use for this
  2356. ** interface is to keep a GUI updated during a large query.
  2357. **
  2358. ** If the progress callback returns non-zero, the operation is
  2359. ** interrupted. This feature can be used to implement a
  2360. ** "Cancel" button on a GUI progress dialog box.
  2361. **
  2362. ** The progress handler must not do anything that will modify
  2363. ** the database connection that invoked the progress handler.
  2364. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2365. ** database connections for the meaning of "modify" in this paragraph.
  2366. **
  2367. ** Requirements:
  2368. ** [H12911] [H12912] [H12913] [H12914] [H12915] [H12916] [H12917] [H12918]
  2369. **
  2370. */
  2371. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2372. /*
  2373. ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
  2374. **
  2375. ** These routines open an SQLite database file whose name is given by the
  2376. ** filename argument. The filename argument is interpreted as UTF-8 for
  2377. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2378. ** order for sqlite3_open16(). A [database connection] handle is usually
  2379. ** returned in *ppDb, even if an error occurs. The only exception is that
  2380. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2381. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2382. ** object. If the database is opened (and/or created) successfully, then
  2383. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The
  2384. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2385. ** an English language description of the error.
  2386. **
  2387. ** The default encoding for the database will be UTF-8 if
  2388. ** sqlite3_open() or sqlite3_open_v2() is called and
  2389. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2390. **
  2391. ** Whether or not an error occurs when it is opened, resources
  2392. ** associated with the [database connection] handle should be released by
  2393. ** passing it to [sqlite3_close()] when it is no longer required.
  2394. **
  2395. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2396. ** except that it accepts two additional parameters for additional control
  2397. ** over the new database connection. The flags parameter can take one of
  2398. ** the following three values, optionally combined with the
  2399. ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags:
  2400. **
  2401. ** <dl>
  2402. ** <dt>[SQLITE_OPEN_READONLY]</dt>
  2403. ** <dd>The database is opened in read-only mode. If the database does not
  2404. ** already exist, an error is returned.</dd>
  2405. **
  2406. ** <dt>[SQLITE_OPEN_READWRITE]</dt>
  2407. ** <dd>The database is opened for reading and writing if possible, or reading
  2408. ** only if the file is write protected by the operating system. In either
  2409. ** case the database must already exist, otherwise an error is returned.</dd>
  2410. **
  2411. ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2412. ** <dd>The database is opened for reading and writing, and is creates it if
  2413. ** it does not already exist. This is the behavior that is always used for
  2414. ** sqlite3_open() and sqlite3_open16().</dd>
  2415. ** </dl>
  2416. **
  2417. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2418. ** combinations shown above or one of the combinations shown above combined
  2419. ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags,
  2420. ** then the behavior is undefined.
  2421. **
  2422. ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2423. ** opens in the multi-thread [threading mode] as long as the single-thread
  2424. ** mode has not been set at compile-time or start-time. If the
  2425. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2426. ** in the serialized [threading mode] unless single-thread was
  2427. ** previously selected at compile-time or start-time.
  2428. **
  2429. ** If the filename is ":memory:", then a private, temporary in-memory database
  2430. ** is created for the connection. This in-memory database will vanish when
  2431. ** the database connection is closed. Future versions of SQLite might
  2432. ** make use of additional special filenames that begin with the ":" character.
  2433. ** It is recommended that when a database filename actually does begin with
  2434. ** a ":" character you should prefix the filename with a pathname such as
  2435. ** "./" to avoid ambiguity.
  2436. **
  2437. ** If the filename is an empty string, then a private, temporary
  2438. ** on-disk database will be created. This private database will be
  2439. ** automatically deleted as soon as the database connection is closed.
  2440. **
  2441. ** The fourth parameter to sqlite3_open_v2() is the name of the
  2442. ** [sqlite3_vfs] object that defines the operating system interface that
  2443. ** the new database connection should use. If the fourth parameter is
  2444. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2445. **
  2446. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2447. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2448. ** codepage is currently defined. Filenames containing international
  2449. ** characters must be converted to UTF-8 prior to passing them into
  2450. ** sqlite3_open() or sqlite3_open_v2().
  2451. **
  2452. ** Requirements:
  2453. ** [H12701] [H12702] [H12703] [H12704] [H12706] [H12707] [H12709] [H12711]
  2454. ** [H12712] [H12713] [H12714] [H12717] [H12719] [H12721] [H12723]
  2455. */
  2456. SQLITE_API int sqlite3_open(
  2457. const char *filename, /* Database filename (UTF-8) */
  2458. sqlite3 **ppDb /* OUT: SQLite db handle */
  2459. );
  2460. SQLITE_API int sqlite3_open16(
  2461. const void *filename, /* Database filename (UTF-16) */
  2462. sqlite3 **ppDb /* OUT: SQLite db handle */
  2463. );
  2464. SQLITE_API int sqlite3_open_v2(
  2465. const char *filename, /* Database filename (UTF-8) */
  2466. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2467. int flags, /* Flags */
  2468. const char *zVfs /* Name of VFS module to use */
  2469. );
  2470. /*
  2471. ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
  2472. **
  2473. ** The sqlite3_errcode() interface returns the numeric [result code] or
  2474. ** [extended result code] for the most recent failed sqlite3_* API call
  2475. ** associated with a [database connection]. If a prior API call failed
  2476. ** but the most recent API call succeeded, the return value from
  2477. ** sqlite3_errcode() is undefined. The sqlite3_extended_errcode()
  2478. ** interface is the same except that it always returns the
  2479. ** [extended result code] even when extended result codes are
  2480. ** disabled.
  2481. **
  2482. ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  2483. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  2484. ** Memory to hold the error message string is managed internally.
  2485. ** The application does not need to worry about freeing the result.
  2486. ** However, the error string might be overwritten or deallocated by
  2487. ** subsequent calls to other SQLite interface functions.
  2488. **
  2489. ** When the serialized [threading mode] is in use, it might be the
  2490. ** case that a second error occurs on a separate thread in between
  2491. ** the time of the first error and the call to these interfaces.
  2492. ** When that happens, the second error will be reported since these
  2493. ** interfaces always report the most recent result. To avoid
  2494. ** this, each thread can obtain exclusive use of the [database connection] D
  2495. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  2496. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  2497. ** all calls to the interfaces listed here are completed.
  2498. **
  2499. ** If an interface fails with SQLITE_MISUSE, that means the interface
  2500. ** was invoked incorrectly by the application. In that case, the
  2501. ** error code and message may or may not be set.
  2502. **
  2503. ** Requirements:
  2504. ** [H12801] [H12802] [H12803] [H12807] [H12808] [H12809]
  2505. */
  2506. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  2507. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  2508. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  2509. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  2510. /*
  2511. ** CAPI3REF: SQL Statement Object {H13000} <H13010>
  2512. ** KEYWORDS: {prepared statement} {prepared statements}
  2513. **
  2514. ** An instance of this object represents a single SQL statement.
  2515. ** This object is variously known as a "prepared statement" or a
  2516. ** "compiled SQL statement" or simply as a "statement".
  2517. **
  2518. ** The life of a statement object goes something like this:
  2519. **
  2520. ** <ol>
  2521. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  2522. ** function.
  2523. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  2524. ** interfaces.
  2525. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  2526. ** <li> Reset the statement using [sqlite3_reset()] then go back
  2527. ** to step 2. Do this zero or more times.
  2528. ** <li> Destroy the object using [sqlite3_finalize()].
  2529. ** </ol>
  2530. **
  2531. ** Refer to documentation on individual methods above for additional
  2532. ** information.
  2533. */
  2534. typedef struct sqlite3_stmt sqlite3_stmt;
  2535. /*
  2536. ** CAPI3REF: Run-time Limits {H12760} <S20600>
  2537. **
  2538. ** This interface allows the size of various constructs to be limited
  2539. ** on a connection by connection basis. The first parameter is the
  2540. ** [database connection] whose limit is to be set or queried. The
  2541. ** second parameter is one of the [limit categories] that define a
  2542. ** class of constructs to be size limited. The third parameter is the
  2543. ** new limit for that construct. The function returns the old limit.
  2544. **
  2545. ** If the new limit is a negative number, the limit is unchanged.
  2546. ** For the limit category of SQLITE_LIMIT_XYZ there is a
  2547. ** [limits | hard upper bound]
  2548. ** set by a compile-time C preprocessor macro named
  2549. ** [limits | SQLITE_MAX_XYZ].
  2550. ** (The "_LIMIT_" in the name is changed to "_MAX_".)
  2551. ** Attempts to increase a limit above its hard upper bound are
  2552. ** silently truncated to the hard upper limit.
  2553. **
  2554. ** Run time limits are intended for use in applications that manage
  2555. ** both their own internal database and also databases that are controlled
  2556. ** by untrusted external sources. An example application might be a
  2557. ** web browser that has its own databases for storing history and
  2558. ** separate databases controlled by JavaScript applications downloaded
  2559. ** off the Internet. The internal databases can be given the
  2560. ** large, default limits. Databases managed by external sources can
  2561. ** be given much smaller limits designed to prevent a denial of service
  2562. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  2563. ** interface to further control untrusted SQL. The size of the database
  2564. ** created by an untrusted script can be contained using the
  2565. ** [max_page_count] [PRAGMA].
  2566. **
  2567. ** New run-time limit categories may be added in future releases.
  2568. **
  2569. ** Requirements:
  2570. ** [H12762] [H12766] [H12769]
  2571. */
  2572. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  2573. /*
  2574. ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
  2575. ** KEYWORDS: {limit category} {limit categories}
  2576. **
  2577. ** These constants define various performance limits
  2578. ** that can be lowered at run-time using [sqlite3_limit()].
  2579. ** The synopsis of the meanings of the various limits is shown below.
  2580. ** Additional information is available at [limits | Limits in SQLite].
  2581. **
  2582. ** <dl>
  2583. ** <dt>SQLITE_LIMIT_LENGTH</dt>
  2584. ** <dd>The maximum size of any string or BLOB or table row.<dd>
  2585. **
  2586. ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  2587. ** <dd>The maximum length of an SQL statement.</dd>
  2588. **
  2589. ** <dt>SQLITE_LIMIT_COLUMN</dt>
  2590. ** <dd>The maximum number of columns in a table definition or in the
  2591. ** result set of a [SELECT] or the maximum number of columns in an index
  2592. ** or in an ORDER BY or GROUP BY clause.</dd>
  2593. **
  2594. ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  2595. ** <dd>The maximum depth of the parse tree on any expression.</dd>
  2596. **
  2597. ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  2598. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
  2599. **
  2600. ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
  2601. ** <dd>The maximum number of instructions in a virtual machine program
  2602. ** used to implement an SQL statement.</dd>
  2603. **
  2604. ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  2605. ** <dd>The maximum number of arguments on a function.</dd>
  2606. **
  2607. ** <dt>SQLITE_LIMIT_ATTACHED</dt>
  2608. ** <dd>The maximum number of [ATTACH | attached databases].</dd>
  2609. **
  2610. ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  2611. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  2612. ** [GLOB] operators.</dd>
  2613. **
  2614. ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  2615. ** <dd>The maximum number of variables in an SQL statement that can
  2616. ** be bound.</dd>
  2617. ** </dl>
  2618. */
  2619. #define SQLITE_LIMIT_LENGTH 0
  2620. #define SQLITE_LIMIT_SQL_LENGTH 1
  2621. #define SQLITE_LIMIT_COLUMN 2
  2622. #define SQLITE_LIMIT_EXPR_DEPTH 3
  2623. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  2624. #define SQLITE_LIMIT_VDBE_OP 5
  2625. #define SQLITE_LIMIT_FUNCTION_ARG 6
  2626. #define SQLITE_LIMIT_ATTACHED 7
  2627. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  2628. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  2629. /*
  2630. ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
  2631. ** KEYWORDS: {SQL statement compiler}
  2632. **
  2633. ** To execute an SQL query, it must first be compiled into a byte-code
  2634. ** program using one of these routines.
  2635. **
  2636. ** The first argument, "db", is a [database connection] obtained from a
  2637. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  2638. ** [sqlite3_open16()]. The database connection must not have been closed.
  2639. **
  2640. ** The second argument, "zSql", is the statement to be compiled, encoded
  2641. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  2642. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  2643. ** use UTF-16.
  2644. **
  2645. ** If the nByte argument is less than zero, then zSql is read up to the
  2646. ** first zero terminator. If nByte is non-negative, then it is the maximum
  2647. ** number of bytes read from zSql. When nByte is non-negative, the
  2648. ** zSql string ends at either the first '\000' or '\u0000' character or
  2649. ** the nByte-th byte, whichever comes first. If the caller knows
  2650. ** that the supplied string is nul-terminated, then there is a small
  2651. ** performance advantage to be gained by passing an nByte parameter that
  2652. ** is equal to the number of bytes in the input string <i>including</i>
  2653. ** the nul-terminator bytes.
  2654. **
  2655. ** If pzTail is not NULL then *pzTail is made to point to the first byte
  2656. ** past the end of the first SQL statement in zSql. These routines only
  2657. ** compile the first statement in zSql, so *pzTail is left pointing to
  2658. ** what remains uncompiled.
  2659. **
  2660. ** *ppStmt is left pointing to a compiled [prepared statement] that can be
  2661. ** executed using [sqlite3_step()]. If there is an error, *ppStmt is set
  2662. ** to NULL. If the input text contains no SQL (if the input is an empty
  2663. ** string or a comment) then *ppStmt is set to NULL.
  2664. ** The calling procedure is responsible for deleting the compiled
  2665. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  2666. ** ppStmt may not be NULL.
  2667. **
  2668. ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
  2669. **
  2670. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  2671. ** recommended for all new programs. The two older interfaces are retained
  2672. ** for backwards compatibility, but their use is discouraged.
  2673. ** In the "v2" interfaces, the prepared statement
  2674. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  2675. ** original SQL text. This causes the [sqlite3_step()] interface to
  2676. ** behave a differently in two ways:
  2677. **
  2678. ** <ol>
  2679. ** <li>
  2680. ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  2681. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  2682. ** statement and try to run it again. If the schema has changed in
  2683. ** a way that makes the statement no longer valid, [sqlite3_step()] will still
  2684. ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
  2685. ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
  2686. ** error go away. Note: use [sqlite3_errmsg()] to find the text
  2687. ** of the parsing error that results in an [SQLITE_SCHEMA] return.
  2688. ** </li>
  2689. **
  2690. ** <li>
  2691. ** When an error occurs, [sqlite3_step()] will return one of the detailed
  2692. ** [error codes] or [extended error codes]. The legacy behavior was that
  2693. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  2694. ** and you would have to make a second call to [sqlite3_reset()] in order
  2695. ** to find the underlying cause of the problem. With the "v2" prepare
  2696. ** interfaces, the underlying reason for the error is returned immediately.
  2697. ** </li>
  2698. ** </ol>
  2699. **
  2700. ** Requirements:
  2701. ** [H13011] [H13012] [H13013] [H13014] [H13015] [H13016] [H13019] [H13021]
  2702. **
  2703. */
  2704. SQLITE_API int sqlite3_prepare(
  2705. sqlite3 *db, /* Database handle */
  2706. const char *zSql, /* SQL statement, UTF-8 encoded */
  2707. int nByte, /* Maximum length of zSql in bytes. */
  2708. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  2709. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  2710. );
  2711. SQLITE_API int sqlite3_prepare_v2(
  2712. sqlite3 *db, /* Database handle */
  2713. const char *zSql, /* SQL statement, UTF-8 encoded */
  2714. int nByte, /* Maximum length of zSql in bytes. */
  2715. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  2716. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  2717. );
  2718. SQLITE_API int sqlite3_prepare16(
  2719. sqlite3 *db, /* Database handle */
  2720. const void *zSql, /* SQL statement, UTF-16 encoded */
  2721. int nByte, /* Maximum length of zSql in bytes. */
  2722. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  2723. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  2724. );
  2725. SQLITE_API int sqlite3_prepare16_v2(
  2726. sqlite3 *db, /* Database handle */
  2727. const void *zSql, /* SQL statement, UTF-16 encoded */
  2728. int nByte, /* Maximum length of zSql in bytes. */
  2729. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  2730. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  2731. );
  2732. /*
  2733. ** CAPI3REF: Retrieving Statement SQL {H13100} <H13000>
  2734. **
  2735. ** This interface can be used to retrieve a saved copy of the original
  2736. ** SQL text used to create a [prepared statement] if that statement was
  2737. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  2738. **
  2739. ** Requirements:
  2740. ** [H13101] [H13102] [H13103]
  2741. */
  2742. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  2743. /*
  2744. ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
  2745. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  2746. **
  2747. ** SQLite uses the sqlite3_value object to represent all values
  2748. ** that can be stored in a database table. SQLite uses dynamic typing
  2749. ** for the values it stores. Values stored in sqlite3_value objects
  2750. ** can be integers, floating point values, strings, BLOBs, or NULL.
  2751. **
  2752. ** An sqlite3_value object may be either "protected" or "unprotected".
  2753. ** Some interfaces require a protected sqlite3_value. Other interfaces
  2754. ** will accept either a protected or an unprotected sqlite3_value.
  2755. ** Every interface that accepts sqlite3_value arguments specifies
  2756. ** whether or not it requires a protected sqlite3_value.
  2757. **
  2758. ** The terms "protected" and "unprotected" refer to whether or not
  2759. ** a mutex is held. A internal mutex is held for a protected
  2760. ** sqlite3_value object but no mutex is held for an unprotected
  2761. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  2762. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  2763. ** or if SQLite is run in one of reduced mutex modes
  2764. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  2765. ** then there is no distinction between protected and unprotected
  2766. ** sqlite3_value objects and they can be used interchangeably. However,
  2767. ** for maximum code portability it is recommended that applications
  2768. ** still make the distinction between between protected and unprotected
  2769. ** sqlite3_value objects even when not strictly required.
  2770. **
  2771. ** The sqlite3_value objects that are passed as parameters into the
  2772. ** implementation of [application-defined SQL functions] are protected.
  2773. ** The sqlite3_value object returned by
  2774. ** [sqlite3_column_value()] is unprotected.
  2775. ** Unprotected sqlite3_value objects may only be used with
  2776. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  2777. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  2778. ** interfaces require protected sqlite3_value objects.
  2779. */
  2780. typedef struct Mem sqlite3_value;
  2781. /*
  2782. ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
  2783. **
  2784. ** The context in which an SQL function executes is stored in an
  2785. ** sqlite3_context object. A pointer to an sqlite3_context object
  2786. ** is always first parameter to [application-defined SQL functions].
  2787. ** The application-defined SQL function implementation will pass this
  2788. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  2789. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  2790. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  2791. ** and/or [sqlite3_set_auxdata()].
  2792. */
  2793. typedef struct sqlite3_context sqlite3_context;
  2794. /*
  2795. ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
  2796. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  2797. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  2798. **
  2799. ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
  2800. ** literals may be replaced by a [parameter] in one of these forms:
  2801. **
  2802. ** <ul>
  2803. ** <li> ?
  2804. ** <li> ?NNN
  2805. ** <li> :VVV
  2806. ** <li> @VVV
  2807. ** <li> $VVV
  2808. ** </ul>
  2809. **
  2810. ** In the parameter forms shown above NNN is an integer literal,
  2811. ** and VVV is an alpha-numeric parameter name. The values of these
  2812. ** parameters (also called "host parameter names" or "SQL parameters")
  2813. ** can be set using the sqlite3_bind_*() routines defined here.
  2814. **
  2815. ** The first argument to the sqlite3_bind_*() routines is always
  2816. ** a pointer to the [sqlite3_stmt] object returned from
  2817. ** [sqlite3_prepare_v2()] or its variants.
  2818. **
  2819. ** The second argument is the index of the SQL parameter to be set.
  2820. ** The leftmost SQL parameter has an index of 1. When the same named
  2821. ** SQL parameter is used more than once, second and subsequent
  2822. ** occurrences have the same index as the first occurrence.
  2823. ** The index for named parameters can be looked up using the
  2824. ** [sqlite3_bind_parameter_index()] API if desired. The index
  2825. ** for "?NNN" parameters is the value of NNN.
  2826. ** The NNN value must be between 1 and the [sqlite3_limit()]
  2827. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  2828. **
  2829. ** The third argument is the value to bind to the parameter.
  2830. **
  2831. ** In those routines that have a fourth argument, its value is the
  2832. ** number of bytes in the parameter. To be clear: the value is the
  2833. ** number of <u>bytes</u> in the value, not the number of characters.
  2834. ** If the fourth parameter is negative, the length of the string is
  2835. ** the number of bytes up to the first zero terminator.
  2836. **
  2837. ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  2838. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  2839. ** string after SQLite has finished with it. If the fifth argument is
  2840. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  2841. ** information is in static, unmanaged space and does not need to be freed.
  2842. ** If the fifth argument has the value [SQLITE_TRANSIENT], then
  2843. ** SQLite makes its own private copy of the data immediately, before
  2844. ** the sqlite3_bind_*() routine returns.
  2845. **
  2846. ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  2847. ** is filled with zeroes. A zeroblob uses a fixed amount of memory
  2848. ** (just an integer to hold its size) while it is being processed.
  2849. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  2850. ** content is later written using
  2851. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  2852. ** A negative value for the zeroblob results in a zero-length BLOB.
  2853. **
  2854. ** The sqlite3_bind_*() routines must be called after
  2855. ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
  2856. ** before [sqlite3_step()].
  2857. ** Bindings are not cleared by the [sqlite3_reset()] routine.
  2858. ** Unbound parameters are interpreted as NULL.
  2859. **
  2860. ** These routines return [SQLITE_OK] on success or an error code if
  2861. ** anything goes wrong. [SQLITE_RANGE] is returned if the parameter
  2862. ** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails.
  2863. ** [SQLITE_MISUSE] might be returned if these routines are called on a
  2864. ** virtual machine that is the wrong state or which has already been finalized.
  2865. ** Detection of misuse is unreliable. Applications should not depend
  2866. ** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a
  2867. ** a logic error in the application. Future versions of SQLite might
  2868. ** panic rather than return SQLITE_MISUSE.
  2869. **
  2870. ** See also: [sqlite3_bind_parameter_count()],
  2871. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  2872. **
  2873. ** Requirements:
  2874. ** [H13506] [H13509] [H13512] [H13515] [H13518] [H13521] [H13524] [H13527]
  2875. ** [H13530] [H13533] [H13536] [H13539] [H13542] [H13545] [H13548] [H13551]
  2876. **
  2877. */
  2878. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  2879. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  2880. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  2881. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  2882. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  2883. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  2884. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  2885. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  2886. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  2887. /*
  2888. ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
  2889. **
  2890. ** This routine can be used to find the number of [SQL parameters]
  2891. ** in a [prepared statement]. SQL parameters are tokens of the
  2892. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  2893. ** placeholders for values that are [sqlite3_bind_blob | bound]
  2894. ** to the parameters at a later time.
  2895. **
  2896. ** This routine actually returns the index of the largest (rightmost)
  2897. ** parameter. For all forms except ?NNN, this will correspond to the
  2898. ** number of unique parameters. If parameters of the ?NNN are used,
  2899. ** there may be gaps in the list.
  2900. **
  2901. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  2902. ** [sqlite3_bind_parameter_name()], and
  2903. ** [sqlite3_bind_parameter_index()].
  2904. **
  2905. ** Requirements:
  2906. ** [H13601]
  2907. */
  2908. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  2909. /*
  2910. ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
  2911. **
  2912. ** This routine returns a pointer to the name of the n-th
  2913. ** [SQL parameter] in a [prepared statement].
  2914. ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  2915. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  2916. ** respectively.
  2917. ** In other words, the initial ":" or "$" or "@" or "?"
  2918. ** is included as part of the name.
  2919. ** Parameters of the form "?" without a following integer have no name
  2920. ** and are also referred to as "anonymous parameters".
  2921. **
  2922. ** The first host parameter has an index of 1, not 0.
  2923. **
  2924. ** If the value n is out of range or if the n-th parameter is
  2925. ** nameless, then NULL is returned. The returned string is
  2926. ** always in UTF-8 encoding even if the named parameter was
  2927. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  2928. ** [sqlite3_prepare16_v2()].
  2929. **
  2930. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  2931. ** [sqlite3_bind_parameter_count()], and
  2932. ** [sqlite3_bind_parameter_index()].
  2933. **
  2934. ** Requirements:
  2935. ** [H13621]
  2936. */
  2937. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  2938. /*
  2939. ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
  2940. **
  2941. ** Return the index of an SQL parameter given its name. The
  2942. ** index value returned is suitable for use as the second
  2943. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero
  2944. ** is returned if no matching parameter is found. The parameter
  2945. ** name must be given in UTF-8 even if the original statement
  2946. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  2947. **
  2948. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  2949. ** [sqlite3_bind_parameter_count()], and
  2950. ** [sqlite3_bind_parameter_index()].
  2951. **
  2952. ** Requirements:
  2953. ** [H13641]
  2954. */
  2955. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  2956. /*
  2957. ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
  2958. **
  2959. ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
  2960. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  2961. ** Use this routine to reset all host parameters to NULL.
  2962. **
  2963. ** Requirements:
  2964. ** [H13661]
  2965. */
  2966. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  2967. /*
  2968. ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
  2969. **
  2970. ** Return the number of columns in the result set returned by the
  2971. ** [prepared statement]. This routine returns 0 if pStmt is an SQL
  2972. ** statement that does not return data (for example an [UPDATE]).
  2973. **
  2974. ** Requirements:
  2975. ** [H13711]
  2976. */
  2977. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  2978. /*
  2979. ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
  2980. **
  2981. ** These routines return the name assigned to a particular column
  2982. ** in the result set of a [SELECT] statement. The sqlite3_column_name()
  2983. ** interface returns a pointer to a zero-terminated UTF-8 string
  2984. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  2985. ** UTF-16 string. The first parameter is the [prepared statement]
  2986. ** that implements the [SELECT] statement. The second parameter is the
  2987. ** column number. The leftmost column is number 0.
  2988. **
  2989. ** The returned string pointer is valid until either the [prepared statement]
  2990. ** is destroyed by [sqlite3_finalize()] or until the next call to
  2991. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  2992. **
  2993. ** If sqlite3_malloc() fails during the processing of either routine
  2994. ** (for example during a conversion from UTF-8 to UTF-16) then a
  2995. ** NULL pointer is returned.
  2996. **
  2997. ** The name of a result column is the value of the "AS" clause for
  2998. ** that column, if there is an AS clause. If there is no AS clause
  2999. ** then the name of the column is unspecified and may change from
  3000. ** one release of SQLite to the next.
  3001. **
  3002. ** Requirements:
  3003. ** [H13721] [H13723] [H13724] [H13725] [H13726] [H13727]
  3004. */
  3005. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3006. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3007. /*
  3008. ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
  3009. **
  3010. ** These routines provide a means to determine what column of what
  3011. ** table in which database a result of a [SELECT] statement comes from.
  3012. ** The name of the database or table or column can be returned as
  3013. ** either a UTF-8 or UTF-16 string. The _database_ routines return
  3014. ** the database name, the _table_ routines return the table name, and
  3015. ** the origin_ routines return the column name.
  3016. ** The returned string is valid until the [prepared statement] is destroyed
  3017. ** using [sqlite3_finalize()] or until the same information is requested
  3018. ** again in a different encoding.
  3019. **
  3020. ** The names returned are the original un-aliased names of the
  3021. ** database, table, and column.
  3022. **
  3023. ** The first argument to the following calls is a [prepared statement].
  3024. ** These functions return information about the Nth column returned by
  3025. ** the statement, where N is the second function argument.
  3026. **
  3027. ** If the Nth column returned by the statement is an expression or
  3028. ** subquery and is not a column value, then all of these functions return
  3029. ** NULL. These routine might also return NULL if a memory allocation error
  3030. ** occurs. Otherwise, they return the name of the attached database, table
  3031. ** and column that query result column was extracted from.
  3032. **
  3033. ** As with all other SQLite APIs, those postfixed with "16" return
  3034. ** UTF-16 encoded strings, the other functions return UTF-8. {END}
  3035. **
  3036. ** These APIs are only available if the library was compiled with the
  3037. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  3038. **
  3039. ** {A13751}
  3040. ** If two or more threads call one or more of these routines against the same
  3041. ** prepared statement and column at the same time then the results are
  3042. ** undefined.
  3043. **
  3044. ** Requirements:
  3045. ** [H13741] [H13742] [H13743] [H13744] [H13745] [H13746] [H13748]
  3046. **
  3047. ** If two or more threads call one or more
  3048. ** [sqlite3_column_database_name | column metadata interfaces]
  3049. ** for the same [prepared statement] and result column
  3050. ** at the same time then the results are undefined.
  3051. */
  3052. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3053. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3054. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3055. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3056. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3057. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3058. /*
  3059. ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
  3060. **
  3061. ** The first parameter is a [prepared statement].
  3062. ** If this statement is a [SELECT] statement and the Nth column of the
  3063. ** returned result set of that [SELECT] is a table column (not an
  3064. ** expression or subquery) then the declared type of the table
  3065. ** column is returned. If the Nth column of the result set is an
  3066. ** expression or subquery, then a NULL pointer is returned.
  3067. ** The returned string is always UTF-8 encoded. {END}
  3068. **
  3069. ** For example, given the database schema:
  3070. **
  3071. ** CREATE TABLE t1(c1 VARIANT);
  3072. **
  3073. ** and the following statement to be compiled:
  3074. **
  3075. ** SELECT c1 + 1, c1 FROM t1;
  3076. **
  3077. ** this routine would return the string "VARIANT" for the second result
  3078. ** column (i==1), and a NULL pointer for the first result column (i==0).
  3079. **
  3080. ** SQLite uses dynamic run-time typing. So just because a column
  3081. ** is declared to contain a particular type does not mean that the
  3082. ** data stored in that column is of the declared type. SQLite is
  3083. ** strongly typed, but the typing is dynamic not static. Type
  3084. ** is associated with individual values, not with the containers
  3085. ** used to hold those values.
  3086. **
  3087. ** Requirements:
  3088. ** [H13761] [H13762] [H13763]
  3089. */
  3090. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3091. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3092. /*
  3093. ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
  3094. **
  3095. ** After a [prepared statement] has been prepared using either
  3096. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3097. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3098. ** must be called one or more times to evaluate the statement.
  3099. **
  3100. ** The details of the behavior of the sqlite3_step() interface depend
  3101. ** on whether the statement was prepared using the newer "v2" interface
  3102. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3103. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3104. ** new "v2" interface is recommended for new applications but the legacy
  3105. ** interface will continue to be supported.
  3106. **
  3107. ** In the legacy interface, the return value will be either [SQLITE_BUSY],
  3108. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3109. ** With the "v2" interface, any of the other [result codes] or
  3110. ** [extended result codes] might be returned as well.
  3111. **
  3112. ** [SQLITE_BUSY] means that the database engine was unable to acquire the
  3113. ** database locks it needs to do its job. If the statement is a [COMMIT]
  3114. ** or occurs outside of an explicit transaction, then you can retry the
  3115. ** statement. If the statement is not a [COMMIT] and occurs within a
  3116. ** explicit transaction then you should rollback the transaction before
  3117. ** continuing.
  3118. **
  3119. ** [SQLITE_DONE] means that the statement has finished executing
  3120. ** successfully. sqlite3_step() should not be called again on this virtual
  3121. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3122. ** machine back to its initial state.
  3123. **
  3124. ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3125. ** is returned each time a new row of data is ready for processing by the
  3126. ** caller. The values may be accessed using the [column access functions].
  3127. ** sqlite3_step() is called again to retrieve the next row of data.
  3128. **
  3129. ** [SQLITE_ERROR] means that a run-time error (such as a constraint
  3130. ** violation) has occurred. sqlite3_step() should not be called again on
  3131. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3132. ** With the legacy interface, a more specific error code (for example,
  3133. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3134. ** can be obtained by calling [sqlite3_reset()] on the
  3135. ** [prepared statement]. In the "v2" interface,
  3136. ** the more specific error code is returned directly by sqlite3_step().
  3137. **
  3138. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3139. ** Perhaps it was called on a [prepared statement] that has
  3140. ** already been [sqlite3_finalize | finalized] or on one that had
  3141. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3142. ** be the case that the same database connection is being used by two or
  3143. ** more threads at the same moment in time.
  3144. **
  3145. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3146. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3147. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3148. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3149. ** specific [error codes] that better describes the error.
  3150. ** We admit that this is a goofy design. The problem has been fixed
  3151. ** with the "v2" interface. If you prepare all of your SQL statements
  3152. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3153. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3154. ** then the more specific [error codes] are returned directly
  3155. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3156. **
  3157. ** Requirements:
  3158. ** [H13202] [H15304] [H15306] [H15308] [H15310]
  3159. */
  3160. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3161. /*
  3162. ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
  3163. **
  3164. ** Returns the number of values in the current row of the result set.
  3165. **
  3166. ** Requirements:
  3167. ** [H13771] [H13772]
  3168. */
  3169. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3170. /*
  3171. ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
  3172. ** KEYWORDS: SQLITE_TEXT
  3173. **
  3174. ** {H10266} Every value in SQLite has one of five fundamental datatypes:
  3175. **
  3176. ** <ul>
  3177. ** <li> 64-bit signed integer
  3178. ** <li> 64-bit IEEE floating point number
  3179. ** <li> string
  3180. ** <li> BLOB
  3181. ** <li> NULL
  3182. ** </ul> {END}
  3183. **
  3184. ** These constants are codes for each of those types.
  3185. **
  3186. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3187. ** for a completely different meaning. Software that links against both
  3188. ** SQLite version 2 and SQLite version 3 should use SQLite3_TEXT, not
  3189. ** SQLITE_TEXT.
  3190. */
  3191. #define SQLITE_INTEGER 1
  3192. #define SQLITE_FLOAT 2
  3193. #define SQLITE_BLOB 4
  3194. #define SQLITE_NULL 5
  3195. #ifdef SQLITE_TEXT
  3196. # undef SQLITE_TEXT
  3197. #else
  3198. # define SQLITE_TEXT 3
  3199. #endif
  3200. #define SQLite3_TEXT 3
  3201. /*
  3202. ** CAPI3REF: Result Values From A Query {H13800} <S10700>
  3203. ** KEYWORDS: {column access functions}
  3204. **
  3205. ** These routines form the "result set query" interface.
  3206. **
  3207. ** These routines return information about a single column of the current
  3208. ** result row of a query. In every case the first argument is a pointer
  3209. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3210. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3211. ** and the second argument is the index of the column for which information
  3212. ** should be returned. The leftmost column of the result set has the index 0.
  3213. **
  3214. ** If the SQL statement does not currently point to a valid row, or if the
  3215. ** column index is out of range, the result is undefined.
  3216. ** These routines may only be called when the most recent call to
  3217. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3218. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3219. ** If any of these routines are called after [sqlite3_reset()] or
  3220. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3221. ** something other than [SQLITE_ROW], the results are undefined.
  3222. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3223. ** are called from a different thread while any of these routines
  3224. ** are pending, then the results are undefined.
  3225. **
  3226. ** The sqlite3_column_type() routine returns the
  3227. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3228. ** of the result column. The returned value is one of [SQLITE_INTEGER],
  3229. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3230. ** returned by sqlite3_column_type() is only meaningful if no type
  3231. ** conversions have occurred as described below. After a type conversion,
  3232. ** the value returned by sqlite3_column_type() is undefined. Future
  3233. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3234. ** following a type conversion.
  3235. **
  3236. ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3237. ** routine returns the number of bytes in that BLOB or string.
  3238. ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3239. ** the string to UTF-8 and then returns the number of bytes.
  3240. ** If the result is a numeric value then sqlite3_column_bytes() uses
  3241. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3242. ** the number of bytes in that string.
  3243. ** The value returned does not include the zero terminator at the end
  3244. ** of the string. For clarity: the value returned is the number of
  3245. ** bytes in the string, not the number of characters.
  3246. **
  3247. ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3248. ** even empty strings, are always zero terminated. The return
  3249. ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
  3250. ** pointer, possibly even a NULL pointer.
  3251. **
  3252. ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
  3253. ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
  3254. ** The zero terminator is not included in this count.
  3255. **
  3256. ** The object returned by [sqlite3_column_value()] is an
  3257. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3258. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3259. ** If the [unprotected sqlite3_value] object returned by
  3260. ** [sqlite3_column_value()] is used in any other way, including calls
  3261. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3262. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3263. **
  3264. ** These routines attempt to convert the value where appropriate. For
  3265. ** example, if the internal representation is FLOAT and a text result
  3266. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3267. ** conversion automatically. The following table details the conversions
  3268. ** that are applied:
  3269. **
  3270. ** <blockquote>
  3271. ** <table border="1">
  3272. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3273. **
  3274. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3275. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3276. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3277. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3278. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3279. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3280. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3281. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3282. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3283. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  3284. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  3285. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  3286. ** <tr><td> TEXT <td> BLOB <td> No change
  3287. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  3288. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  3289. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3290. ** </table>
  3291. ** </blockquote>
  3292. **
  3293. ** The table above makes reference to standard C library functions atoi()
  3294. ** and atof(). SQLite does not really use these functions. It has its
  3295. ** own equivalent internal routines. The atoi() and atof() names are
  3296. ** used in the table for brevity and because they are familiar to most
  3297. ** C programmers.
  3298. **
  3299. ** Note that when type conversions occur, pointers returned by prior
  3300. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3301. ** sqlite3_column_text16() may be invalidated.
  3302. ** Type conversions and pointer invalidations might occur
  3303. ** in the following cases:
  3304. **
  3305. ** <ul>
  3306. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3307. ** sqlite3_column_text16() is called. A zero-terminator might
  3308. ** need to be added to the string.</li>
  3309. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3310. ** sqlite3_column_text16() is called. The content must be converted
  3311. ** to UTF-16.</li>
  3312. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3313. ** sqlite3_column_text() is called. The content must be converted
  3314. ** to UTF-8.</li>
  3315. ** </ul>
  3316. **
  3317. ** Conversions between UTF-16be and UTF-16le are always done in place and do
  3318. ** not invalidate a prior pointer, though of course the content of the buffer
  3319. ** that the prior pointer points to will have been modified. Other kinds
  3320. ** of conversion are done in place when it is possible, but sometimes they
  3321. ** are not possible and in those cases prior pointers are invalidated.
  3322. **
  3323. ** The safest and easiest to remember policy is to invoke these routines
  3324. ** in one of the following ways:
  3325. **
  3326. ** <ul>
  3327. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3328. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3329. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3330. ** </ul>
  3331. **
  3332. ** In other words, you should call sqlite3_column_text(),
  3333. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3334. ** into the desired format, then invoke sqlite3_column_bytes() or
  3335. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3336. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3337. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3338. ** with calls to sqlite3_column_bytes().
  3339. **
  3340. ** The pointers returned are valid until a type conversion occurs as
  3341. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3342. ** [sqlite3_finalize()] is called. The memory space used to hold strings
  3343. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3344. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3345. ** [sqlite3_free()].
  3346. **
  3347. ** If a memory allocation error occurs during the evaluation of any
  3348. ** of these routines, a default value is returned. The default value
  3349. ** is either the integer 0, the floating point number 0.0, or a NULL
  3350. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3351. ** [SQLITE_NOMEM].
  3352. **
  3353. ** Requirements:
  3354. ** [H13803] [H13806] [H13809] [H13812] [H13815] [H13818] [H13821] [H13824]
  3355. ** [H13827] [H13830]
  3356. */
  3357. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3358. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3359. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3360. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3361. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3362. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3363. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3364. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3365. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3366. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3367. /*
  3368. ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
  3369. **
  3370. ** The sqlite3_finalize() function is called to delete a [prepared statement].
  3371. ** If the statement was executed successfully or not executed at all, then
  3372. ** SQLITE_OK is returned. If execution of the statement failed then an
  3373. ** [error code] or [extended error code] is returned.
  3374. **
  3375. ** This routine can be called at any point during the execution of the
  3376. ** [prepared statement]. If the virtual machine has not
  3377. ** completed execution when this routine is called, that is like
  3378. ** encountering an error or an [sqlite3_interrupt | interrupt].
  3379. ** Incomplete updates may be rolled back and transactions canceled,
  3380. ** depending on the circumstances, and the
  3381. ** [error code] returned will be [SQLITE_ABORT].
  3382. **
  3383. ** Requirements:
  3384. ** [H11302] [H11304]
  3385. */
  3386. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  3387. /*
  3388. ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
  3389. **
  3390. ** The sqlite3_reset() function is called to reset a [prepared statement]
  3391. ** object back to its initial state, ready to be re-executed.
  3392. ** Any SQL statement variables that had values bound to them using
  3393. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  3394. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  3395. **
  3396. ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
  3397. ** back to the beginning of its program.
  3398. **
  3399. ** {H11334} If the most recent call to [sqlite3_step(S)] for the
  3400. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  3401. ** or if [sqlite3_step(S)] has never before been called on S,
  3402. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  3403. **
  3404. ** {H11336} If the most recent call to [sqlite3_step(S)] for the
  3405. ** [prepared statement] S indicated an error, then
  3406. ** [sqlite3_reset(S)] returns an appropriate [error code].
  3407. **
  3408. ** {H11338} The [sqlite3_reset(S)] interface does not change the values
  3409. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  3410. */
  3411. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  3412. /*
  3413. ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
  3414. ** KEYWORDS: {function creation routines}
  3415. ** KEYWORDS: {application-defined SQL function}
  3416. ** KEYWORDS: {application-defined SQL functions}
  3417. **
  3418. ** These two functions (collectively known as "function creation routines")
  3419. ** are used to add SQL functions or aggregates or to redefine the behavior
  3420. ** of existing SQL functions or aggregates. The only difference between the
  3421. ** two is that the second parameter, the name of the (scalar) function or
  3422. ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
  3423. ** for sqlite3_create_function16().
  3424. **
  3425. ** The first parameter is the [database connection] to which the SQL
  3426. ** function is to be added. If a single program uses more than one database
  3427. ** connection internally, then SQL functions must be added individually to
  3428. ** each database connection.
  3429. **
  3430. ** The second parameter is the name of the SQL function to be created or
  3431. ** redefined. The length of the name is limited to 255 bytes, exclusive of
  3432. ** the zero-terminator. Note that the name length limit is in bytes, not
  3433. ** characters. Any attempt to create a function with a longer name
  3434. ** will result in [SQLITE_ERROR] being returned.
  3435. **
  3436. ** The third parameter (nArg)
  3437. ** is the number of arguments that the SQL function or
  3438. ** aggregate takes. If this parameter is negative, then the SQL function or
  3439. ** aggregate may take any number of arguments.
  3440. **
  3441. ** The fourth parameter, eTextRep, specifies what
  3442. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  3443. ** its parameters. Any SQL function implementation should be able to work
  3444. ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  3445. ** more efficient with one encoding than another. It is allowed to
  3446. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  3447. ** times with the same function but with different values of eTextRep.
  3448. ** When multiple implementations of the same function are available, SQLite
  3449. ** will pick the one that involves the least amount of data conversion.
  3450. ** If there is only a single implementation which does not care what text
  3451. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  3452. **
  3453. ** The fifth parameter is an arbitrary pointer. The implementation of the
  3454. ** function can gain access to this pointer using [sqlite3_user_data()].
  3455. **
  3456. ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
  3457. ** pointers to C-language functions that implement the SQL function or
  3458. ** aggregate. A scalar SQL function requires an implementation of the xFunc
  3459. ** callback only, NULL pointers should be passed as the xStep and xFinal
  3460. ** parameters. An aggregate SQL function requires an implementation of xStep
  3461. ** and xFinal and NULL should be passed for xFunc. To delete an existing
  3462. ** SQL function or aggregate, pass NULL for all three function callbacks.
  3463. **
  3464. ** It is permitted to register multiple implementations of the same
  3465. ** functions with the same name but with either differing numbers of
  3466. ** arguments or differing preferred text encodings. SQLite will use
  3467. ** the implementation most closely matches the way in which the
  3468. ** SQL function is used. A function implementation with a non-negative
  3469. ** nArg parameter is a better match than a function implementation with
  3470. ** a negative nArg. A function where the preferred text encoding
  3471. ** matches the database encoding is a better
  3472. ** match than a function where the encoding is different.
  3473. ** A function where the encoding difference is between UTF16le and UTF16be
  3474. ** is a closer match than a function where the encoding difference is
  3475. ** between UTF8 and UTF16.
  3476. **
  3477. ** Built-in functions may be overloaded by new application-defined functions.
  3478. ** The first application-defined function with a given name overrides all
  3479. ** built-in functions in the same [database connection] with the same name.
  3480. ** Subsequent application-defined functions of the same name only override
  3481. ** prior application-defined functions that are an exact match for the
  3482. ** number of parameters and preferred encoding.
  3483. **
  3484. ** An application-defined function is permitted to call other
  3485. ** SQLite interfaces. However, such calls must not
  3486. ** close the database connection nor finalize or reset the prepared
  3487. ** statement in which the function is running.
  3488. **
  3489. ** Requirements:
  3490. ** [H16103] [H16106] [H16109] [H16112] [H16118] [H16121] [H16124] [H16127]
  3491. ** [H16130] [H16133] [H16136] [H16139] [H16142]
  3492. */
  3493. SQLITE_API int sqlite3_create_function(
  3494. sqlite3 *db,
  3495. const char *zFunctionName,
  3496. int nArg,
  3497. int eTextRep,
  3498. void *pApp,
  3499. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3500. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3501. void (*xFinal)(sqlite3_context*)
  3502. );
  3503. SQLITE_API int sqlite3_create_function16(
  3504. sqlite3 *db,
  3505. const void *zFunctionName,
  3506. int nArg,
  3507. int eTextRep,
  3508. void *pApp,
  3509. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3510. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3511. void (*xFinal)(sqlite3_context*)
  3512. );
  3513. /*
  3514. ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
  3515. **
  3516. ** These constant define integer codes that represent the various
  3517. ** text encodings supported by SQLite.
  3518. */
  3519. #define SQLITE_UTF8 1
  3520. #define SQLITE_UTF16LE 2
  3521. #define SQLITE_UTF16BE 3
  3522. #define SQLITE_UTF16 4 /* Use native byte order */
  3523. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  3524. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  3525. /*
  3526. ** CAPI3REF: Deprecated Functions
  3527. ** DEPRECATED
  3528. **
  3529. ** These functions are [deprecated]. In order to maintain
  3530. ** backwards compatibility with older code, these functions continue
  3531. ** to be supported. However, new applications should avoid
  3532. ** the use of these functions. To help encourage people to avoid
  3533. ** using these functions, we are not going to tell you what they do.
  3534. */
  3535. #ifndef SQLITE_OMIT_DEPRECATED
  3536. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  3537. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  3538. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  3539. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  3540. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  3541. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
  3542. #endif
  3543. /*
  3544. ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
  3545. **
  3546. ** The C-language implementation of SQL functions and aggregates uses
  3547. ** this set of interface routines to access the parameter values on
  3548. ** the function or aggregate.
  3549. **
  3550. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  3551. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  3552. ** define callbacks that implement the SQL functions and aggregates.
  3553. ** The 4th parameter to these callbacks is an array of pointers to
  3554. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  3555. ** each parameter to the SQL function. These routines are used to
  3556. ** extract values from the [sqlite3_value] objects.
  3557. **
  3558. ** These routines work only with [protected sqlite3_value] objects.
  3559. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  3560. ** object results in undefined behavior.
  3561. **
  3562. ** These routines work just like the corresponding [column access functions]
  3563. ** except that these routines take a single [protected sqlite3_value] object
  3564. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  3565. **
  3566. ** The sqlite3_value_text16() interface extracts a UTF-16 string
  3567. ** in the native byte-order of the host machine. The
  3568. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  3569. ** extract UTF-16 strings as big-endian and little-endian respectively.
  3570. **
  3571. ** The sqlite3_value_numeric_type() interface attempts to apply
  3572. ** numeric affinity to the value. This means that an attempt is
  3573. ** made to convert the value to an integer or floating point. If
  3574. ** such a conversion is possible without loss of information (in other
  3575. ** words, if the value is a string that looks like a number)
  3576. ** then the conversion is performed. Otherwise no conversion occurs.
  3577. ** The [SQLITE_INTEGER | datatype] after conversion is returned.
  3578. **
  3579. ** Please pay particular attention to the fact that the pointer returned
  3580. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  3581. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  3582. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  3583. ** or [sqlite3_value_text16()].
  3584. **
  3585. ** These routines must be called from the same thread as
  3586. ** the SQL function that supplied the [sqlite3_value*] parameters.
  3587. **
  3588. ** Requirements:
  3589. ** [H15103] [H15106] [H15109] [H15112] [H15115] [H15118] [H15121] [H15124]
  3590. ** [H15127] [H15130] [H15133] [H15136]
  3591. */
  3592. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  3593. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  3594. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  3595. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  3596. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  3597. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  3598. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  3599. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  3600. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  3601. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  3602. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  3603. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  3604. /*
  3605. ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
  3606. **
  3607. ** The implementation of aggregate SQL functions use this routine to allocate
  3608. ** a structure for storing their state.
  3609. **
  3610. ** The first time the sqlite3_aggregate_context() routine is called for a
  3611. ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
  3612. ** memory, and returns a pointer to it. On second and subsequent calls to
  3613. ** sqlite3_aggregate_context() for the same aggregate function index,
  3614. ** the same buffer is returned. The implementation of the aggregate can use
  3615. ** the returned buffer to accumulate data.
  3616. **
  3617. ** SQLite automatically frees the allocated buffer when the aggregate
  3618. ** query concludes.
  3619. **
  3620. ** The first parameter should be a copy of the
  3621. ** [sqlite3_context | SQL function context] that is the first parameter
  3622. ** to the callback routine that implements the aggregate function.
  3623. **
  3624. ** This routine must be called from the same thread in which
  3625. ** the aggregate SQL function is running.
  3626. **
  3627. ** Requirements:
  3628. ** [H16211] [H16213] [H16215] [H16217]
  3629. */
  3630. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  3631. /*
  3632. ** CAPI3REF: User Data For Functions {H16240} <S20200>
  3633. **
  3634. ** The sqlite3_user_data() interface returns a copy of
  3635. ** the pointer that was the pUserData parameter (the 5th parameter)
  3636. ** of the [sqlite3_create_function()]
  3637. ** and [sqlite3_create_function16()] routines that originally
  3638. ** registered the application defined function. {END}
  3639. **
  3640. ** This routine must be called from the same thread in which
  3641. ** the application-defined function is running.
  3642. **
  3643. ** Requirements:
  3644. ** [H16243]
  3645. */
  3646. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  3647. /*
  3648. ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
  3649. **
  3650. ** The sqlite3_context_db_handle() interface returns a copy of
  3651. ** the pointer to the [database connection] (the 1st parameter)
  3652. ** of the [sqlite3_create_function()]
  3653. ** and [sqlite3_create_function16()] routines that originally
  3654. ** registered the application defined function.
  3655. **
  3656. ** Requirements:
  3657. ** [H16253]
  3658. */
  3659. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  3660. /*
  3661. ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
  3662. **
  3663. ** The following two functions may be used by scalar SQL functions to
  3664. ** associate metadata with argument values. If the same value is passed to
  3665. ** multiple invocations of the same SQL function during query execution, under
  3666. ** some circumstances the associated metadata may be preserved. This may
  3667. ** be used, for example, to add a regular-expression matching scalar
  3668. ** function. The compiled version of the regular expression is stored as
  3669. ** metadata associated with the SQL value passed as the regular expression
  3670. ** pattern. The compiled regular expression can be reused on multiple
  3671. ** invocations of the same function so that the original pattern string
  3672. ** does not need to be recompiled on each invocation.
  3673. **
  3674. ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
  3675. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  3676. ** value to the application-defined function. If no metadata has been ever
  3677. ** been set for the Nth argument of the function, or if the corresponding
  3678. ** function parameter has changed since the meta-data was set,
  3679. ** then sqlite3_get_auxdata() returns a NULL pointer.
  3680. **
  3681. ** The sqlite3_set_auxdata() interface saves the metadata
  3682. ** pointed to by its 3rd parameter as the metadata for the N-th
  3683. ** argument of the application-defined function. Subsequent
  3684. ** calls to sqlite3_get_auxdata() might return this data, if it has
  3685. ** not been destroyed.
  3686. ** If it is not NULL, SQLite will invoke the destructor
  3687. ** function given by the 4th parameter to sqlite3_set_auxdata() on
  3688. ** the metadata when the corresponding function parameter changes
  3689. ** or when the SQL statement completes, whichever comes first.
  3690. **
  3691. ** SQLite is free to call the destructor and drop metadata on any
  3692. ** parameter of any function at any time. The only guarantee is that
  3693. ** the destructor will be called before the metadata is dropped.
  3694. **
  3695. ** In practice, metadata is preserved between function calls for
  3696. ** expressions that are constant at compile time. This includes literal
  3697. ** values and SQL variables.
  3698. **
  3699. ** These routines must be called from the same thread in which
  3700. ** the SQL function is running.
  3701. **
  3702. ** Requirements:
  3703. ** [H16272] [H16274] [H16276] [H16277] [H16278] [H16279]
  3704. */
  3705. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  3706. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  3707. /*
  3708. ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
  3709. **
  3710. ** These are special values for the destructor that is passed in as the
  3711. ** final argument to routines like [sqlite3_result_blob()]. If the destructor
  3712. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  3713. ** and will never change. It does not need to be destroyed. The
  3714. ** SQLITE_TRANSIENT value means that the content will likely change in
  3715. ** the near future and that SQLite should make its own private copy of
  3716. ** the content before returning.
  3717. **
  3718. ** The typedef is necessary to work around problems in certain
  3719. ** C++ compilers. See ticket #2191.
  3720. */
  3721. typedef void (*sqlite3_destructor_type)(void*);
  3722. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  3723. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  3724. /*
  3725. ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
  3726. **
  3727. ** These routines are used by the xFunc or xFinal callbacks that
  3728. ** implement SQL functions and aggregates. See
  3729. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  3730. ** for additional information.
  3731. **
  3732. ** These functions work very much like the [parameter binding] family of
  3733. ** functions used to bind values to host parameters in prepared statements.
  3734. ** Refer to the [SQL parameter] documentation for additional information.
  3735. **
  3736. ** The sqlite3_result_blob() interface sets the result from
  3737. ** an application-defined function to be the BLOB whose content is pointed
  3738. ** to by the second parameter and which is N bytes long where N is the
  3739. ** third parameter.
  3740. **
  3741. ** The sqlite3_result_zeroblob() interfaces set the result of
  3742. ** the application-defined function to be a BLOB containing all zero
  3743. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  3744. **
  3745. ** The sqlite3_result_double() interface sets the result from
  3746. ** an application-defined function to be a floating point value specified
  3747. ** by its 2nd argument.
  3748. **
  3749. ** The sqlite3_result_error() and sqlite3_result_error16() functions
  3750. ** cause the implemented SQL function to throw an exception.
  3751. ** SQLite uses the string pointed to by the
  3752. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  3753. ** as the text of an error message. SQLite interprets the error
  3754. ** message string from sqlite3_result_error() as UTF-8. SQLite
  3755. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  3756. ** byte order. If the third parameter to sqlite3_result_error()
  3757. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  3758. ** message all text up through the first zero character.
  3759. ** If the third parameter to sqlite3_result_error() or
  3760. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  3761. ** bytes (not characters) from the 2nd parameter as the error message.
  3762. ** The sqlite3_result_error() and sqlite3_result_error16()
  3763. ** routines make a private copy of the error message text before
  3764. ** they return. Hence, the calling function can deallocate or
  3765. ** modify the text after they return without harm.
  3766. ** The sqlite3_result_error_code() function changes the error code
  3767. ** returned by SQLite as a result of an error in a function. By default,
  3768. ** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error()
  3769. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  3770. **
  3771. ** The sqlite3_result_toobig() interface causes SQLite to throw an error
  3772. ** indicating that a string or BLOB is to long to represent.
  3773. **
  3774. ** The sqlite3_result_nomem() interface causes SQLite to throw an error
  3775. ** indicating that a memory allocation failed.
  3776. **
  3777. ** The sqlite3_result_int() interface sets the return value
  3778. ** of the application-defined function to be the 32-bit signed integer
  3779. ** value given in the 2nd argument.
  3780. ** The sqlite3_result_int64() interface sets the return value
  3781. ** of the application-defined function to be the 64-bit signed integer
  3782. ** value given in the 2nd argument.
  3783. **
  3784. ** The sqlite3_result_null() interface sets the return value
  3785. ** of the application-defined function to be NULL.
  3786. **
  3787. ** The sqlite3_result_text(), sqlite3_result_text16(),
  3788. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  3789. ** set the return value of the application-defined function to be
  3790. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  3791. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  3792. ** SQLite takes the text result from the application from
  3793. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  3794. ** If the 3rd parameter to the sqlite3_result_text* interfaces
  3795. ** is negative, then SQLite takes result text from the 2nd parameter
  3796. ** through the first zero character.
  3797. ** If the 3rd parameter to the sqlite3_result_text* interfaces
  3798. ** is non-negative, then as many bytes (not characters) of the text
  3799. ** pointed to by the 2nd parameter are taken as the application-defined
  3800. ** function result.
  3801. ** If the 4th parameter to the sqlite3_result_text* interfaces
  3802. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  3803. ** function as the destructor on the text or BLOB result when it has
  3804. ** finished using that result.
  3805. ** If the 4th parameter to the sqlite3_result_text* interfaces or
  3806. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  3807. ** assumes that the text or BLOB result is in constant space and does not
  3808. ** copy the it or call a destructor when it has finished using that result.
  3809. ** If the 4th parameter to the sqlite3_result_text* interfaces
  3810. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  3811. ** then SQLite makes a copy of the result into space obtained from
  3812. ** from [sqlite3_malloc()] before it returns.
  3813. **
  3814. ** The sqlite3_result_value() interface sets the result of
  3815. ** the application-defined function to be a copy the
  3816. ** [unprotected sqlite3_value] object specified by the 2nd parameter. The
  3817. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  3818. ** so that the [sqlite3_value] specified in the parameter may change or
  3819. ** be deallocated after sqlite3_result_value() returns without harm.
  3820. ** A [protected sqlite3_value] object may always be used where an
  3821. ** [unprotected sqlite3_value] object is required, so either
  3822. ** kind of [sqlite3_value] object can be used with this interface.
  3823. **
  3824. ** If these routines are called from within the different thread
  3825. ** than the one containing the application-defined function that received
  3826. ** the [sqlite3_context] pointer, the results are undefined.
  3827. **
  3828. ** Requirements:
  3829. ** [H16403] [H16406] [H16409] [H16412] [H16415] [H16418] [H16421] [H16424]
  3830. ** [H16427] [H16430] [H16433] [H16436] [H16439] [H16442] [H16445] [H16448]
  3831. ** [H16451] [H16454] [H16457] [H16460] [H16463]
  3832. */
  3833. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  3834. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  3835. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  3836. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  3837. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  3838. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  3839. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  3840. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  3841. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  3842. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  3843. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  3844. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  3845. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  3846. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  3847. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  3848. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  3849. /*
  3850. ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
  3851. **
  3852. ** These functions are used to add new collation sequences to the
  3853. ** [database connection] specified as the first argument.
  3854. **
  3855. ** The name of the new collation sequence is specified as a UTF-8 string
  3856. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  3857. ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
  3858. ** the name is passed as the second function argument.
  3859. **
  3860. ** The third argument may be one of the constants [SQLITE_UTF8],
  3861. ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
  3862. ** routine expects to be passed pointers to strings encoded using UTF-8,
  3863. ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
  3864. ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
  3865. ** the routine expects pointers to 16-bit word aligned strings
  3866. ** of UTF-16 in the native byte order of the host computer.
  3867. **
  3868. ** A pointer to the user supplied routine must be passed as the fifth
  3869. ** argument. If it is NULL, this is the same as deleting the collation
  3870. ** sequence (so that SQLite cannot call it anymore).
  3871. ** Each time the application supplied function is invoked, it is passed
  3872. ** as its first parameter a copy of the void* passed as the fourth argument
  3873. ** to sqlite3_create_collation() or sqlite3_create_collation16().
  3874. **
  3875. ** The remaining arguments to the application-supplied routine are two strings,
  3876. ** each represented by a (length, data) pair and encoded in the encoding
  3877. ** that was passed as the third argument when the collation sequence was
  3878. ** registered. {END} The application defined collation routine should
  3879. ** return negative, zero or positive if the first string is less than,
  3880. ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
  3881. **
  3882. ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  3883. ** except that it takes an extra argument which is a destructor for
  3884. ** the collation. The destructor is called when the collation is
  3885. ** destroyed and is passed a copy of the fourth parameter void* pointer
  3886. ** of the sqlite3_create_collation_v2().
  3887. ** Collations are destroyed when they are overridden by later calls to the
  3888. ** collation creation functions or when the [database connection] is closed
  3889. ** using [sqlite3_close()].
  3890. **
  3891. ** Requirements:
  3892. ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
  3893. ** [H16624] [H16627] [H16630]
  3894. */
  3895. SQLITE_API int sqlite3_create_collation(
  3896. sqlite3*,
  3897. const char *zName,
  3898. int eTextRep,
  3899. void*,
  3900. int(*xCompare)(void*,int,const void*,int,const void*)
  3901. );
  3902. SQLITE_API int sqlite3_create_collation_v2(
  3903. sqlite3*,
  3904. const char *zName,
  3905. int eTextRep,
  3906. void*,
  3907. int(*xCompare)(void*,int,const void*,int,const void*),
  3908. void(*xDestroy)(void*)
  3909. );
  3910. SQLITE_API int sqlite3_create_collation16(
  3911. sqlite3*,
  3912. const void *zName,
  3913. int eTextRep,
  3914. void*,
  3915. int(*xCompare)(void*,int,const void*,int,const void*)
  3916. );
  3917. /*
  3918. ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
  3919. **
  3920. ** To avoid having to register all collation sequences before a database
  3921. ** can be used, a single callback function may be registered with the
  3922. ** [database connection] to be called whenever an undefined collation
  3923. ** sequence is required.
  3924. **
  3925. ** If the function is registered using the sqlite3_collation_needed() API,
  3926. ** then it is passed the names of undefined collation sequences as strings
  3927. ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
  3928. ** the names are passed as UTF-16 in machine native byte order.
  3929. ** A call to either function replaces any existing callback.
  3930. **
  3931. ** When the callback is invoked, the first argument passed is a copy
  3932. ** of the second argument to sqlite3_collation_needed() or
  3933. ** sqlite3_collation_needed16(). The second argument is the database
  3934. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  3935. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  3936. ** sequence function required. The fourth parameter is the name of the
  3937. ** required collation sequence.
  3938. **
  3939. ** The callback function should register the desired collation using
  3940. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  3941. ** [sqlite3_create_collation_v2()].
  3942. **
  3943. ** Requirements:
  3944. ** [H16702] [H16704] [H16706]
  3945. */
  3946. SQLITE_API int sqlite3_collation_needed(
  3947. sqlite3*,
  3948. void*,
  3949. void(*)(void*,sqlite3*,int eTextRep,const char*)
  3950. );
  3951. SQLITE_API int sqlite3_collation_needed16(
  3952. sqlite3*,
  3953. void*,
  3954. void(*)(void*,sqlite3*,int eTextRep,const void*)
  3955. );
  3956. /*
  3957. ** Specify the key for an encrypted database. This routine should be
  3958. ** called right after sqlite3_open().
  3959. **
  3960. ** The code to implement this API is not available in the public release
  3961. ** of SQLite.
  3962. */
  3963. SQLITE_API int sqlite3_key(
  3964. sqlite3 *db, /* Database to be rekeyed */
  3965. const void *pKey, int nKey /* The key */
  3966. );
  3967. /*
  3968. ** Change the key on an open database. If the current database is not
  3969. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  3970. ** database is decrypted.
  3971. **
  3972. ** The code to implement this API is not available in the public release
  3973. ** of SQLite.
  3974. */
  3975. SQLITE_API int sqlite3_rekey(
  3976. sqlite3 *db, /* Database to be rekeyed */
  3977. const void *pKey, int nKey /* The new key */
  3978. );
  3979. /*
  3980. ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
  3981. **
  3982. ** The sqlite3_sleep() function causes the current thread to suspend execution
  3983. ** for at least a number of milliseconds specified in its parameter.
  3984. **
  3985. ** If the operating system does not support sleep requests with
  3986. ** millisecond time resolution, then the time will be rounded up to
  3987. ** the nearest second. The number of milliseconds of sleep actually
  3988. ** requested from the operating system is returned.
  3989. **
  3990. ** SQLite implements this interface by calling the xSleep()
  3991. ** method of the default [sqlite3_vfs] object.
  3992. **
  3993. ** Requirements: [H10533] [H10536]
  3994. */
  3995. SQLITE_API int sqlite3_sleep(int);
  3996. /*
  3997. ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
  3998. **
  3999. ** If this global variable is made to point to a string which is
  4000. ** the name of a folder (a.k.a. directory), then all temporary files
  4001. ** created by SQLite will be placed in that directory. If this variable
  4002. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4003. ** temporary file directory.
  4004. **
  4005. ** It is not safe to read or modify this variable in more than one
  4006. ** thread at a time. It is not safe to read or modify this variable
  4007. ** if a [database connection] is being used at the same time in a separate
  4008. ** thread.
  4009. ** It is intended that this variable be set once
  4010. ** as part of process initialization and before any SQLite interface
  4011. ** routines have been called and that this variable remain unchanged
  4012. ** thereafter.
  4013. **
  4014. ** The [temp_store_directory pragma] may modify this variable and cause
  4015. ** it to point to memory obtained from [sqlite3_malloc]. Furthermore,
  4016. ** the [temp_store_directory pragma] always assumes that any string
  4017. ** that this variable points to is held in memory obtained from
  4018. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4019. ** using [sqlite3_free].
  4020. ** Hence, if this variable is modified directly, either it should be
  4021. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4022. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4023. */
  4024. SQLITE_API char *sqlite3_temp_directory;
  4025. /*
  4026. ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
  4027. ** KEYWORDS: {autocommit mode}
  4028. **
  4029. ** The sqlite3_get_autocommit() interface returns non-zero or
  4030. ** zero if the given database connection is or is not in autocommit mode,
  4031. ** respectively. Autocommit mode is on by default.
  4032. ** Autocommit mode is disabled by a [BEGIN] statement.
  4033. ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4034. **
  4035. ** If certain kinds of errors occur on a statement within a multi-statement
  4036. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4037. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4038. ** transaction might be rolled back automatically. The only way to
  4039. ** find out whether SQLite automatically rolled back the transaction after
  4040. ** an error is to use this function.
  4041. **
  4042. ** If another thread changes the autocommit status of the database
  4043. ** connection while this routine is running, then the return value
  4044. ** is undefined.
  4045. **
  4046. ** Requirements: [H12931] [H12932] [H12933] [H12934]
  4047. */
  4048. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4049. /*
  4050. ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
  4051. **
  4052. ** The sqlite3_db_handle interface returns the [database connection] handle
  4053. ** to which a [prepared statement] belongs. The [database connection]
  4054. ** returned by sqlite3_db_handle is the same [database connection] that was the first argument
  4055. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4056. ** create the statement in the first place.
  4057. **
  4058. ** Requirements: [H13123]
  4059. */
  4060. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4061. /*
  4062. ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
  4063. **
  4064. ** This interface returns a pointer to the next [prepared statement] after
  4065. ** pStmt associated with the [database connection] pDb. If pStmt is NULL
  4066. ** then this interface returns a pointer to the first prepared statement
  4067. ** associated with the database connection pDb. If no prepared statement
  4068. ** satisfies the conditions of this routine, it returns NULL.
  4069. **
  4070. ** The [database connection] pointer D in a call to
  4071. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4072. ** connection and in particular must not be a NULL pointer.
  4073. **
  4074. ** Requirements: [H13143] [H13146] [H13149] [H13152]
  4075. */
  4076. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4077. /*
  4078. ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
  4079. **
  4080. ** The sqlite3_commit_hook() interface registers a callback
  4081. ** function to be invoked whenever a transaction is committed.
  4082. ** Any callback set by a previous call to sqlite3_commit_hook()
  4083. ** for the same database connection is overridden.
  4084. ** The sqlite3_rollback_hook() interface registers a callback
  4085. ** function to be invoked whenever a transaction is committed.
  4086. ** Any callback set by a previous call to sqlite3_commit_hook()
  4087. ** for the same database connection is overridden.
  4088. ** The pArg argument is passed through to the callback.
  4089. ** If the callback on a commit hook function returns non-zero,
  4090. ** then the commit is converted into a rollback.
  4091. **
  4092. ** If another function was previously registered, its
  4093. ** pArg value is returned. Otherwise NULL is returned.
  4094. **
  4095. ** The callback implementation must not do anything that will modify
  4096. ** the database connection that invoked the callback. Any actions
  4097. ** to modify the database connection must be deferred until after the
  4098. ** completion of the [sqlite3_step()] call that triggered the commit
  4099. ** or rollback hook in the first place.
  4100. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4101. ** database connections for the meaning of "modify" in this paragraph.
  4102. **
  4103. ** Registering a NULL function disables the callback.
  4104. **
  4105. ** For the purposes of this API, a transaction is said to have been
  4106. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4107. ** an error or constraint causes an implicit rollback to occur.
  4108. ** The rollback callback is not invoked if a transaction is
  4109. ** automatically rolled back because the database connection is closed.
  4110. ** The rollback callback is not invoked if a transaction is
  4111. ** rolled back because a commit callback returned non-zero.
  4112. ** <todo> Check on this </todo>
  4113. **
  4114. ** Requirements:
  4115. ** [H12951] [H12952] [H12953] [H12954] [H12955]
  4116. ** [H12961] [H12962] [H12963] [H12964]
  4117. */
  4118. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4119. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4120. /*
  4121. ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
  4122. **
  4123. ** The sqlite3_update_hook() interface registers a callback function
  4124. ** with the [database connection] identified by the first argument
  4125. ** to be invoked whenever a row is updated, inserted or deleted.
  4126. ** Any callback set by a previous call to this function
  4127. ** for the same database connection is overridden.
  4128. **
  4129. ** The second argument is a pointer to the function to invoke when a
  4130. ** row is updated, inserted or deleted.
  4131. ** The first argument to the callback is a copy of the third argument
  4132. ** to sqlite3_update_hook().
  4133. ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4134. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4135. ** to be invoked.
  4136. ** The third and fourth arguments to the callback contain pointers to the
  4137. ** database and table name containing the affected row.
  4138. ** The final callback parameter is the [rowid] of the row.
  4139. ** In the case of an update, this is the [rowid] after the update takes place.
  4140. **
  4141. ** The update hook is not invoked when internal system tables are
  4142. ** modified (i.e. sqlite_master and sqlite_sequence).
  4143. **
  4144. ** The update hook implementation must not do anything that will modify
  4145. ** the database connection that invoked the update hook. Any actions
  4146. ** to modify the database connection must be deferred until after the
  4147. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4148. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4149. ** database connections for the meaning of "modify" in this paragraph.
  4150. **
  4151. ** If another function was previously registered, its pArg value
  4152. ** is returned. Otherwise NULL is returned.
  4153. **
  4154. ** Requirements:
  4155. ** [H12971] [H12973] [H12975] [H12977] [H12979] [H12981] [H12983] [H12986]
  4156. */
  4157. SQLITE_API void *sqlite3_update_hook(
  4158. sqlite3*,
  4159. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4160. void*
  4161. );
  4162. /*
  4163. ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
  4164. ** KEYWORDS: {shared cache} {shared cache mode}
  4165. **
  4166. ** This routine enables or disables the sharing of the database cache
  4167. ** and schema data structures between [database connection | connections]
  4168. ** to the same database. Sharing is enabled if the argument is true
  4169. ** and disabled if the argument is false.
  4170. **
  4171. ** Cache sharing is enabled and disabled for an entire process.
  4172. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4173. ** sharing was enabled or disabled for each thread separately.
  4174. **
  4175. ** The cache sharing mode set by this interface effects all subsequent
  4176. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4177. ** Existing database connections continue use the sharing mode
  4178. ** that was in effect at the time they were opened.
  4179. **
  4180. ** Virtual tables cannot be used with a shared cache. When shared
  4181. ** cache is enabled, the [sqlite3_create_module()] API used to register
  4182. ** virtual tables will always return an error.
  4183. **
  4184. ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4185. ** successfully. An [error code] is returned otherwise.
  4186. **
  4187. ** Shared cache is disabled by default. But this might change in
  4188. ** future releases of SQLite. Applications that care about shared
  4189. ** cache setting should set it explicitly.
  4190. **
  4191. ** See Also: [SQLite Shared-Cache Mode]
  4192. **
  4193. ** Requirements: [H10331] [H10336] [H10337] [H10339]
  4194. */
  4195. SQLITE_API int sqlite3_enable_shared_cache(int);
  4196. /*
  4197. ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
  4198. **
  4199. ** The sqlite3_release_memory() interface attempts to free N bytes
  4200. ** of heap memory by deallocating non-essential memory allocations
  4201. ** held by the database library. {END} Memory used to cache database
  4202. ** pages to improve performance is an example of non-essential memory.
  4203. ** sqlite3_release_memory() returns the number of bytes actually freed,
  4204. ** which might be more or less than the amount requested.
  4205. **
  4206. ** Requirements: [H17341] [H17342]
  4207. */
  4208. SQLITE_API int sqlite3_release_memory(int);
  4209. /*
  4210. ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
  4211. **
  4212. ** The sqlite3_soft_heap_limit() interface places a "soft" limit
  4213. ** on the amount of heap memory that may be allocated by SQLite.
  4214. ** If an internal allocation is requested that would exceed the
  4215. ** soft heap limit, [sqlite3_release_memory()] is invoked one or
  4216. ** more times to free up some space before the allocation is performed.
  4217. **
  4218. ** The limit is called "soft", because if [sqlite3_release_memory()]
  4219. ** cannot free sufficient memory to prevent the limit from being exceeded,
  4220. ** the memory is allocated anyway and the current operation proceeds.
  4221. **
  4222. ** A negative or zero value for N means that there is no soft heap limit and
  4223. ** [sqlite3_release_memory()] will only be called when memory is exhausted.
  4224. ** The default value for the soft heap limit is zero.
  4225. **
  4226. ** SQLite makes a best effort to honor the soft heap limit.
  4227. ** But if the soft heap limit cannot be honored, execution will
  4228. ** continue without error or notification. This is why the limit is
  4229. ** called a "soft" limit. It is advisory only.
  4230. **
  4231. ** Prior to SQLite version 3.5.0, this routine only constrained the memory
  4232. ** allocated by a single thread - the same thread in which this routine
  4233. ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
  4234. ** applied to all threads. The value specified for the soft heap limit
  4235. ** is an upper bound on the total memory allocation for all threads. In
  4236. ** version 3.5.0 there is no mechanism for limiting the heap usage for
  4237. ** individual threads.
  4238. **
  4239. ** Requirements:
  4240. ** [H16351] [H16352] [H16353] [H16354] [H16355] [H16358]
  4241. */
  4242. SQLITE_API void sqlite3_soft_heap_limit(int);
  4243. /*
  4244. ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
  4245. **
  4246. ** This routine returns metadata about a specific column of a specific
  4247. ** database table accessible using the [database connection] handle
  4248. ** passed as the first function argument.
  4249. **
  4250. ** The column is identified by the second, third and fourth parameters to
  4251. ** this function. The second parameter is either the name of the database
  4252. ** (i.e. "main", "temp" or an attached database) containing the specified
  4253. ** table or NULL. If it is NULL, then all attached databases are searched
  4254. ** for the table using the same algorithm used by the database engine to
  4255. ** resolve unqualified table references.
  4256. **
  4257. ** The third and fourth parameters to this function are the table and column
  4258. ** name of the desired column, respectively. Neither of these parameters
  4259. ** may be NULL.
  4260. **
  4261. ** Metadata is returned by writing to the memory locations passed as the 5th
  4262. ** and subsequent parameters to this function. Any of these arguments may be
  4263. ** NULL, in which case the corresponding element of metadata is omitted.
  4264. **
  4265. ** <blockquote>
  4266. ** <table border="1">
  4267. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  4268. **
  4269. ** <tr><td> 5th <td> const char* <td> Data type
  4270. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  4271. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  4272. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  4273. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  4274. ** </table>
  4275. ** </blockquote>
  4276. **
  4277. ** The memory pointed to by the character pointers returned for the
  4278. ** declaration type and collation sequence is valid only until the next
  4279. ** call to any SQLite API function.
  4280. **
  4281. ** If the specified table is actually a view, an [error code] is returned.
  4282. **
  4283. ** If the specified column is "rowid", "oid" or "_rowid_" and an
  4284. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  4285. ** parameters are set for the explicitly declared column. If there is no
  4286. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  4287. ** parameters are set as follows:
  4288. **
  4289. ** <pre>
  4290. ** data type: "INTEGER"
  4291. ** collation sequence: "BINARY"
  4292. ** not null: 0
  4293. ** primary key: 1
  4294. ** auto increment: 0
  4295. ** </pre>
  4296. **
  4297. ** This function may load one or more schemas from database files. If an
  4298. ** error occurs during this process, or if the requested table or column
  4299. ** cannot be found, an [error code] is returned and an error message left
  4300. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
  4301. **
  4302. ** This API is only available if the library was compiled with the
  4303. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  4304. */
  4305. SQLITE_API int sqlite3_table_column_metadata(
  4306. sqlite3 *db, /* Connection handle */
  4307. const char *zDbName, /* Database name or NULL */
  4308. const char *zTableName, /* Table name */
  4309. const char *zColumnName, /* Column name */
  4310. char const **pzDataType, /* OUTPUT: Declared data type */
  4311. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  4312. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  4313. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  4314. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  4315. );
  4316. /*
  4317. ** CAPI3REF: Load An Extension {H12600} <S20500>
  4318. **
  4319. ** This interface loads an SQLite extension library from the named file.
  4320. **
  4321. ** {H12601} The sqlite3_load_extension() interface attempts to load an
  4322. ** SQLite extension library contained in the file zFile.
  4323. **
  4324. ** {H12602} The entry point is zProc.
  4325. **
  4326. ** {H12603} zProc may be 0, in which case the name of the entry point
  4327. ** defaults to "sqlite3_extension_init".
  4328. **
  4329. ** {H12604} The sqlite3_load_extension() interface shall return
  4330. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  4331. **
  4332. ** {H12605} If an error occurs and pzErrMsg is not 0, then the
  4333. ** [sqlite3_load_extension()] interface shall attempt to
  4334. ** fill *pzErrMsg with error message text stored in memory
  4335. ** obtained from [sqlite3_malloc()]. {END} The calling function
  4336. ** should free this memory by calling [sqlite3_free()].
  4337. **
  4338. ** {H12606} Extension loading must be enabled using
  4339. ** [sqlite3_enable_load_extension()] prior to calling this API,
  4340. ** otherwise an error will be returned.
  4341. */
  4342. SQLITE_API int sqlite3_load_extension(
  4343. sqlite3 *db, /* Load the extension into this database connection */
  4344. const char *zFile, /* Name of the shared library containing extension */
  4345. const char *zProc, /* Entry point. Derived from zFile if 0 */
  4346. char **pzErrMsg /* Put error message here if not 0 */
  4347. );
  4348. /*
  4349. ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
  4350. **
  4351. ** So as not to open security holes in older applications that are
  4352. ** unprepared to deal with extension loading, and as a means of disabling
  4353. ** extension loading while evaluating user-entered SQL, the following API
  4354. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  4355. **
  4356. ** Extension loading is off by default. See ticket #1863.
  4357. **
  4358. ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
  4359. ** to turn extension loading on and call it with onoff==0 to turn
  4360. ** it back off again.
  4361. **
  4362. ** {H12622} Extension loading is off by default.
  4363. */
  4364. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  4365. /*
  4366. ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
  4367. **
  4368. ** This API can be invoked at program startup in order to register
  4369. ** one or more statically linked extensions that will be available
  4370. ** to all new [database connections]. {END}
  4371. **
  4372. ** This routine stores a pointer to the extension in an array that is
  4373. ** obtained from [sqlite3_malloc()]. If you run a memory leak checker
  4374. ** on your program and it reports a leak because of this array, invoke
  4375. ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
  4376. **
  4377. ** {H12641} This function registers an extension entry point that is
  4378. ** automatically invoked whenever a new [database connection]
  4379. ** is opened using [sqlite3_open()], [sqlite3_open16()],
  4380. ** or [sqlite3_open_v2()].
  4381. **
  4382. ** {H12642} Duplicate extensions are detected so calling this routine
  4383. ** multiple times with the same extension is harmless.
  4384. **
  4385. ** {H12643} This routine stores a pointer to the extension in an array
  4386. ** that is obtained from [sqlite3_malloc()].
  4387. **
  4388. ** {H12644} Automatic extensions apply across all threads.
  4389. */
  4390. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  4391. /*
  4392. ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
  4393. **
  4394. ** This function disables all previously registered automatic
  4395. ** extensions. {END} It undoes the effect of all prior
  4396. ** [sqlite3_auto_extension()] calls.
  4397. **
  4398. ** {H12661} This function disables all previously registered
  4399. ** automatic extensions.
  4400. **
  4401. ** {H12662} This function disables automatic extensions in all threads.
  4402. */
  4403. SQLITE_API void sqlite3_reset_auto_extension(void);
  4404. /*
  4405. ****** EXPERIMENTAL - subject to change without notice **************
  4406. **
  4407. ** The interface to the virtual-table mechanism is currently considered
  4408. ** to be experimental. The interface might change in incompatible ways.
  4409. ** If this is a problem for you, do not use the interface at this time.
  4410. **
  4411. ** When the virtual-table mechanism stabilizes, we will declare the
  4412. ** interface fixed, support it indefinitely, and remove this comment.
  4413. */
  4414. /*
  4415. ** Structures used by the virtual table interface
  4416. */
  4417. typedef struct sqlite3_vtab sqlite3_vtab;
  4418. typedef struct sqlite3_index_info sqlite3_index_info;
  4419. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  4420. typedef struct sqlite3_module sqlite3_module;
  4421. /*
  4422. ** CAPI3REF: Virtual Table Object {H18000} <S20400>
  4423. ** KEYWORDS: sqlite3_module
  4424. ** EXPERIMENTAL
  4425. **
  4426. ** A module is a class of virtual tables. Each module is defined
  4427. ** by an instance of the following structure. This structure consists
  4428. ** mostly of methods for the module.
  4429. **
  4430. ** This interface is experimental and is subject to change or
  4431. ** removal in future releases of SQLite.
  4432. */
  4433. struct sqlite3_module {
  4434. int iVersion;
  4435. int (*xCreate)(sqlite3*, void *pAux,
  4436. int argc, const char *const*argv,
  4437. sqlite3_vtab **ppVTab, char**);
  4438. int (*xConnect)(sqlite3*, void *pAux,
  4439. int argc, const char *const*argv,
  4440. sqlite3_vtab **ppVTab, char**);
  4441. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  4442. int (*xDisconnect)(sqlite3_vtab *pVTab);
  4443. int (*xDestroy)(sqlite3_vtab *pVTab);
  4444. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  4445. int (*xClose)(sqlite3_vtab_cursor*);
  4446. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  4447. int argc, sqlite3_value **argv);
  4448. int (*xNext)(sqlite3_vtab_cursor*);
  4449. int (*xEof)(sqlite3_vtab_cursor*);
  4450. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  4451. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  4452. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  4453. int (*xBegin)(sqlite3_vtab *pVTab);
  4454. int (*xSync)(sqlite3_vtab *pVTab);
  4455. int (*xCommit)(sqlite3_vtab *pVTab);
  4456. int (*xRollback)(sqlite3_vtab *pVTab);
  4457. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  4458. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  4459. void **ppArg);
  4460. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  4461. };
  4462. /*
  4463. ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
  4464. ** KEYWORDS: sqlite3_index_info
  4465. ** EXPERIMENTAL
  4466. **
  4467. ** The sqlite3_index_info structure and its substructures is used to
  4468. ** pass information into and receive the reply from the xBestIndex
  4469. ** method of an sqlite3_module. The fields under **Inputs** are the
  4470. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  4471. ** results into the **Outputs** fields.
  4472. **
  4473. ** The aConstraint[] array records WHERE clause constraints of the form:
  4474. **
  4475. ** <pre>column OP expr</pre>
  4476. **
  4477. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=. The particular operator is
  4478. ** stored in aConstraint[].op. The index of the column is stored in
  4479. ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the
  4480. ** expr on the right-hand side can be evaluated (and thus the constraint
  4481. ** is usable) and false if it cannot.
  4482. **
  4483. ** The optimizer automatically inverts terms of the form "expr OP column"
  4484. ** and makes other simplifications to the WHERE clause in an attempt to
  4485. ** get as many WHERE clause terms into the form shown above as possible.
  4486. ** The aConstraint[] array only reports WHERE clause terms in the correct
  4487. ** form that refer to the particular virtual table being queried.
  4488. **
  4489. ** Information about the ORDER BY clause is stored in aOrderBy[].
  4490. ** Each term of aOrderBy records a column of the ORDER BY clause.
  4491. **
  4492. ** The xBestIndex method must fill aConstraintUsage[] with information
  4493. ** about what parameters to pass to xFilter. If argvIndex>0 then
  4494. ** the right-hand side of the corresponding aConstraint[] is evaluated
  4495. ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
  4496. ** is true, then the constraint is assumed to be fully handled by the
  4497. ** virtual table and is not checked again by SQLite.
  4498. **
  4499. ** The idxNum and idxPtr values are recorded and passed into xFilter.
  4500. ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
  4501. **
  4502. ** The orderByConsumed means that output from xFilter will occur in
  4503. ** the correct order to satisfy the ORDER BY clause so that no separate
  4504. ** sorting step is required.
  4505. **
  4506. ** The estimatedCost value is an estimate of the cost of doing the
  4507. ** particular lookup. A full scan of a table with N entries should have
  4508. ** a cost of N. A binary search of a table of N entries should have a
  4509. ** cost of approximately log(N).
  4510. **
  4511. ** This interface is experimental and is subject to change or
  4512. ** removal in future releases of SQLite.
  4513. */
  4514. struct sqlite3_index_info {
  4515. /* Inputs */
  4516. int nConstraint; /* Number of entries in aConstraint */
  4517. struct sqlite3_index_constraint {
  4518. int iColumn; /* Column on left-hand side of constraint */
  4519. unsigned char op; /* Constraint operator */
  4520. unsigned char usable; /* True if this constraint is usable */
  4521. int iTermOffset; /* Used internally - xBestIndex should ignore */
  4522. } *aConstraint; /* Table of WHERE clause constraints */
  4523. int nOrderBy; /* Number of terms in the ORDER BY clause */
  4524. struct sqlite3_index_orderby {
  4525. int iColumn; /* Column number */
  4526. unsigned char desc; /* True for DESC. False for ASC. */
  4527. } *aOrderBy; /* The ORDER BY clause */
  4528. /* Outputs */
  4529. struct sqlite3_index_constraint_usage {
  4530. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  4531. unsigned char omit; /* Do not code a test for this constraint */
  4532. } *aConstraintUsage;
  4533. int idxNum; /* Number used to identify the index */
  4534. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  4535. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  4536. int orderByConsumed; /* True if output is already ordered */
  4537. double estimatedCost; /* Estimated cost of using this index */
  4538. };
  4539. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  4540. #define SQLITE_INDEX_CONSTRAINT_GT 4
  4541. #define SQLITE_INDEX_CONSTRAINT_LE 8
  4542. #define SQLITE_INDEX_CONSTRAINT_LT 16
  4543. #define SQLITE_INDEX_CONSTRAINT_GE 32
  4544. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  4545. /*
  4546. ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
  4547. ** EXPERIMENTAL
  4548. **
  4549. ** This routine is used to register a new module name with a
  4550. ** [database connection]. Module names must be registered before
  4551. ** creating new virtual tables on the module, or before using
  4552. ** preexisting virtual tables of the module.
  4553. **
  4554. ** This interface is experimental and is subject to change or
  4555. ** removal in future releases of SQLite.
  4556. */
  4557. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
  4558. sqlite3 *db, /* SQLite connection to register module with */
  4559. const char *zName, /* Name of the module */
  4560. const sqlite3_module *, /* Methods for the module */
  4561. void * /* Client data for xCreate/xConnect */
  4562. );
  4563. /*
  4564. ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
  4565. ** EXPERIMENTAL
  4566. **
  4567. ** This routine is identical to the [sqlite3_create_module()] method above,
  4568. ** except that it allows a destructor function to be specified. It is
  4569. ** even more experimental than the rest of the virtual tables API.
  4570. */
  4571. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
  4572. sqlite3 *db, /* SQLite connection to register module with */
  4573. const char *zName, /* Name of the module */
  4574. const sqlite3_module *, /* Methods for the module */
  4575. void *, /* Client data for xCreate/xConnect */
  4576. void(*xDestroy)(void*) /* Module destructor function */
  4577. );
  4578. /*
  4579. ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
  4580. ** KEYWORDS: sqlite3_vtab
  4581. ** EXPERIMENTAL
  4582. **
  4583. ** Every module implementation uses a subclass of the following structure
  4584. ** to describe a particular instance of the module. Each subclass will
  4585. ** be tailored to the specific needs of the module implementation.
  4586. ** The purpose of this superclass is to define certain fields that are
  4587. ** common to all module implementations.
  4588. **
  4589. ** Virtual tables methods can set an error message by assigning a
  4590. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  4591. ** take care that any prior string is freed by a call to [sqlite3_free()]
  4592. ** prior to assigning a new string to zErrMsg. After the error message
  4593. ** is delivered up to the client application, the string will be automatically
  4594. ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
  4595. ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
  4596. ** since virtual tables are commonly implemented in loadable extensions which
  4597. ** do not have access to sqlite3MPrintf() or sqlite3Free().
  4598. **
  4599. ** This interface is experimental and is subject to change or
  4600. ** removal in future releases of SQLite.
  4601. */
  4602. struct sqlite3_vtab {
  4603. const sqlite3_module *pModule; /* The module for this virtual table */
  4604. int nRef; /* Used internally */
  4605. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  4606. /* Virtual table implementations will typically add additional fields */
  4607. };
  4608. /*
  4609. ** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
  4610. ** KEYWORDS: sqlite3_vtab_cursor
  4611. ** EXPERIMENTAL
  4612. **
  4613. ** Every module implementation uses a subclass of the following structure
  4614. ** to describe cursors that point into the virtual table and are used
  4615. ** to loop through the virtual table. Cursors are created using the
  4616. ** xOpen method of the module. Each module implementation will define
  4617. ** the content of a cursor structure to suit its own needs.
  4618. **
  4619. ** This superclass exists in order to define fields of the cursor that
  4620. ** are common to all implementations.
  4621. **
  4622. ** This interface is experimental and is subject to change or
  4623. ** removal in future releases of SQLite.
  4624. */
  4625. struct sqlite3_vtab_cursor {
  4626. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  4627. /* Virtual table implementations will typically add additional fields */
  4628. };
  4629. /*
  4630. ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
  4631. ** EXPERIMENTAL
  4632. **
  4633. ** The xCreate and xConnect methods of a module use the following API
  4634. ** to declare the format (the names and datatypes of the columns) of
  4635. ** the virtual tables they implement.
  4636. **
  4637. ** This interface is experimental and is subject to change or
  4638. ** removal in future releases of SQLite.
  4639. */
  4640. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
  4641. /*
  4642. ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
  4643. ** EXPERIMENTAL
  4644. **
  4645. ** Virtual tables can provide alternative implementations of functions
  4646. ** using the xFindFunction method. But global versions of those functions
  4647. ** must exist in order to be overloaded.
  4648. **
  4649. ** This API makes sure a global version of a function with a particular
  4650. ** name and number of parameters exists. If no such function exists
  4651. ** before this API is called, a new function is created. The implementation
  4652. ** of the new function always causes an exception to be thrown. So
  4653. ** the new function is not good for anything by itself. Its only
  4654. ** purpose is to be a placeholder function that can be overloaded
  4655. ** by virtual tables.
  4656. **
  4657. ** This API should be considered part of the virtual table interface,
  4658. ** which is experimental and subject to change.
  4659. */
  4660. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  4661. /*
  4662. ** The interface to the virtual-table mechanism defined above (back up
  4663. ** to a comment remarkably similar to this one) is currently considered
  4664. ** to be experimental. The interface might change in incompatible ways.
  4665. ** If this is a problem for you, do not use the interface at this time.
  4666. **
  4667. ** When the virtual-table mechanism stabilizes, we will declare the
  4668. ** interface fixed, support it indefinitely, and remove this comment.
  4669. **
  4670. ****** EXPERIMENTAL - subject to change without notice **************
  4671. */
  4672. /*
  4673. ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
  4674. ** KEYWORDS: {BLOB handle} {BLOB handles}
  4675. **
  4676. ** An instance of this object represents an open BLOB on which
  4677. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  4678. ** Objects of this type are created by [sqlite3_blob_open()]
  4679. ** and destroyed by [sqlite3_blob_close()].
  4680. ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  4681. ** can be used to read or write small subsections of the BLOB.
  4682. ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  4683. */
  4684. typedef struct sqlite3_blob sqlite3_blob;
  4685. /*
  4686. ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
  4687. **
  4688. ** This interfaces opens a [BLOB handle | handle] to the BLOB located
  4689. ** in row iRow, column zColumn, table zTable in database zDb;
  4690. ** in other words, the same BLOB that would be selected by:
  4691. **
  4692. ** <pre>
  4693. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  4694. ** </pre> {END}
  4695. **
  4696. ** If the flags parameter is non-zero, the the BLOB is opened for read
  4697. ** and write access. If it is zero, the BLOB is opened for read access.
  4698. **
  4699. ** Note that the database name is not the filename that contains
  4700. ** the database but rather the symbolic name of the database that
  4701. ** is assigned when the database is connected using [ATTACH].
  4702. ** For the main database file, the database name is "main".
  4703. ** For TEMP tables, the database name is "temp".
  4704. **
  4705. ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  4706. ** to *ppBlob. Otherwise an [error code] is returned and any value written
  4707. ** to *ppBlob should not be used by the caller.
  4708. ** This function sets the [database connection] error code and message
  4709. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
  4710. **
  4711. ** If the row that a BLOB handle points to is modified by an
  4712. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  4713. ** then the BLOB handle is marked as "expired".
  4714. ** This is true if any column of the row is changed, even a column
  4715. ** other than the one the BLOB handle is open on.
  4716. ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  4717. ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
  4718. ** Changes written into a BLOB prior to the BLOB expiring are not
  4719. ** rollback by the expiration of the BLOB. Such changes will eventually
  4720. ** commit if the transaction continues to completion.
  4721. **
  4722. ** Requirements:
  4723. ** [H17813] [H17814] [H17816] [H17819] [H17821] [H17824]
  4724. */
  4725. SQLITE_API int sqlite3_blob_open(
  4726. sqlite3*,
  4727. const char *zDb,
  4728. const char *zTable,
  4729. const char *zColumn,
  4730. sqlite3_int64 iRow,
  4731. int flags,
  4732. sqlite3_blob **ppBlob
  4733. );
  4734. /*
  4735. ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
  4736. **
  4737. ** Closes an open [BLOB handle].
  4738. **
  4739. ** Closing a BLOB shall cause the current transaction to commit
  4740. ** if there are no other BLOBs, no pending prepared statements, and the
  4741. ** database connection is in [autocommit mode].
  4742. ** If any writes were made to the BLOB, they might be held in cache
  4743. ** until the close operation if they will fit. {END}
  4744. **
  4745. ** Closing the BLOB often forces the changes
  4746. ** out to disk and so if any I/O errors occur, they will likely occur
  4747. ** at the time when the BLOB is closed. {H17833} Any errors that occur during
  4748. ** closing are reported as a non-zero return value.
  4749. **
  4750. ** The BLOB is closed unconditionally. Even if this routine returns
  4751. ** an error code, the BLOB is still closed.
  4752. **
  4753. ** Requirements:
  4754. ** [H17833] [H17836] [H17839]
  4755. */
  4756. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  4757. /*
  4758. ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
  4759. **
  4760. ** Returns the size in bytes of the BLOB accessible via the open
  4761. ** []BLOB handle] in its only argument.
  4762. **
  4763. ** Requirements:
  4764. ** [H17843]
  4765. */
  4766. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  4767. /*
  4768. ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
  4769. **
  4770. ** This function is used to read data from an open [BLOB handle] into a
  4771. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  4772. ** from the open BLOB, starting at offset iOffset.
  4773. **
  4774. ** If offset iOffset is less than N bytes from the end of the BLOB,
  4775. ** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is
  4776. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  4777. **
  4778. ** An attempt to read from an expired [BLOB handle] fails with an
  4779. ** error code of [SQLITE_ABORT].
  4780. **
  4781. ** On success, SQLITE_OK is returned.
  4782. ** Otherwise, an [error code] or an [extended error code] is returned.
  4783. **
  4784. ** Requirements:
  4785. ** [H17853] [H17856] [H17859] [H17862] [H17863] [H17865] [H17868]
  4786. */
  4787. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  4788. /*
  4789. ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
  4790. **
  4791. ** This function is used to write data into an open [BLOB handle] from a
  4792. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  4793. ** into the open BLOB, starting at offset iOffset.
  4794. **
  4795. ** If the [BLOB handle] passed as the first argument was not opened for
  4796. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  4797. ** this function returns [SQLITE_READONLY].
  4798. **
  4799. ** This function may only modify the contents of the BLOB; it is
  4800. ** not possible to increase the size of a BLOB using this API.
  4801. ** If offset iOffset is less than N bytes from the end of the BLOB,
  4802. ** [SQLITE_ERROR] is returned and no data is written. If N is
  4803. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  4804. **
  4805. ** An attempt to write to an expired [BLOB handle] fails with an
  4806. ** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred
  4807. ** before the [BLOB handle] expired are not rolled back by the
  4808. ** expiration of the handle, though of course those changes might
  4809. ** have been overwritten by the statement that expired the BLOB handle
  4810. ** or by other independent statements.
  4811. **
  4812. ** On success, SQLITE_OK is returned.
  4813. ** Otherwise, an [error code] or an [extended error code] is returned.
  4814. **
  4815. ** Requirements:
  4816. ** [H17873] [H17874] [H17875] [H17876] [H17877] [H17879] [H17882] [H17885]
  4817. ** [H17888]
  4818. */
  4819. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  4820. /*
  4821. ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
  4822. **
  4823. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  4824. ** that SQLite uses to interact
  4825. ** with the underlying operating system. Most SQLite builds come with a
  4826. ** single default VFS that is appropriate for the host computer.
  4827. ** New VFSes can be registered and existing VFSes can be unregistered.
  4828. ** The following interfaces are provided.
  4829. **
  4830. ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  4831. ** Names are case sensitive.
  4832. ** Names are zero-terminated UTF-8 strings.
  4833. ** If there is no match, a NULL pointer is returned.
  4834. ** If zVfsName is NULL then the default VFS is returned.
  4835. **
  4836. ** New VFSes are registered with sqlite3_vfs_register().
  4837. ** Each new VFS becomes the default VFS if the makeDflt flag is set.
  4838. ** The same VFS can be registered multiple times without injury.
  4839. ** To make an existing VFS into the default VFS, register it again
  4840. ** with the makeDflt flag set. If two different VFSes with the
  4841. ** same name are registered, the behavior is undefined. If a
  4842. ** VFS is registered with a name that is NULL or an empty string,
  4843. ** then the behavior is undefined.
  4844. **
  4845. ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
  4846. ** If the default VFS is unregistered, another VFS is chosen as
  4847. ** the default. The choice for the new VFS is arbitrary.
  4848. **
  4849. ** Requirements:
  4850. ** [H11203] [H11206] [H11209] [H11212] [H11215] [H11218]
  4851. */
  4852. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  4853. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  4854. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  4855. /*
  4856. ** CAPI3REF: Mutexes {H17000} <S20000>
  4857. **
  4858. ** The SQLite core uses these routines for thread
  4859. ** synchronization. Though they are intended for internal
  4860. ** use by SQLite, code that links against SQLite is
  4861. ** permitted to use any of these routines.
  4862. **
  4863. ** The SQLite source code contains multiple implementations
  4864. ** of these mutex routines. An appropriate implementation
  4865. ** is selected automatically at compile-time. The following
  4866. ** implementations are available in the SQLite core:
  4867. **
  4868. ** <ul>
  4869. ** <li> SQLITE_MUTEX_OS2
  4870. ** <li> SQLITE_MUTEX_PTHREAD
  4871. ** <li> SQLITE_MUTEX_W32
  4872. ** <li> SQLITE_MUTEX_NOOP
  4873. ** </ul>
  4874. **
  4875. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  4876. ** that does no real locking and is appropriate for use in
  4877. ** a single-threaded application. The SQLITE_MUTEX_OS2,
  4878. ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
  4879. ** are appropriate for use on OS/2, Unix, and Windows.
  4880. **
  4881. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  4882. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  4883. ** implementation is included with the library. In this case the
  4884. ** application must supply a custom mutex implementation using the
  4885. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  4886. ** before calling sqlite3_initialize() or any other public sqlite3_
  4887. ** function that calls sqlite3_initialize().
  4888. **
  4889. ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
  4890. ** mutex and returns a pointer to it. {H17012} If it returns NULL
  4891. ** that means that a mutex could not be allocated. {H17013} SQLite
  4892. ** will unwind its stack and return an error. {H17014} The argument
  4893. ** to sqlite3_mutex_alloc() is one of these integer constants:
  4894. **
  4895. ** <ul>
  4896. ** <li> SQLITE_MUTEX_FAST
  4897. ** <li> SQLITE_MUTEX_RECURSIVE
  4898. ** <li> SQLITE_MUTEX_STATIC_MASTER
  4899. ** <li> SQLITE_MUTEX_STATIC_MEM
  4900. ** <li> SQLITE_MUTEX_STATIC_MEM2
  4901. ** <li> SQLITE_MUTEX_STATIC_PRNG
  4902. ** <li> SQLITE_MUTEX_STATIC_LRU
  4903. ** <li> SQLITE_MUTEX_STATIC_LRU2
  4904. ** </ul>
  4905. **
  4906. ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
  4907. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  4908. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
  4909. ** The mutex implementation does not need to make a distinction
  4910. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  4911. ** not want to. {H17016} But SQLite will only request a recursive mutex in
  4912. ** cases where it really needs one. {END} If a faster non-recursive mutex
  4913. ** implementation is available on the host platform, the mutex subsystem
  4914. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  4915. **
  4916. ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
  4917. ** a pointer to a static preexisting mutex. {END} Four static mutexes are
  4918. ** used by the current version of SQLite. Future versions of SQLite
  4919. ** may add additional static mutexes. Static mutexes are for internal
  4920. ** use by SQLite only. Applications that use SQLite mutexes should
  4921. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  4922. ** SQLITE_MUTEX_RECURSIVE.
  4923. **
  4924. ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  4925. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  4926. ** returns a different mutex on every call. {H17034} But for the static
  4927. ** mutex types, the same mutex is returned on every call that has
  4928. ** the same type number.
  4929. **
  4930. ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
  4931. ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
  4932. ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
  4933. ** use when they are deallocated. {A17022} Attempting to deallocate a static
  4934. ** mutex results in undefined behavior. {H17023} SQLite never deallocates
  4935. ** a static mutex. {END}
  4936. **
  4937. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  4938. ** to enter a mutex. {H17024} If another thread is already within the mutex,
  4939. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  4940. ** SQLITE_BUSY. {H17025} The sqlite3_mutex_try() interface returns [SQLITE_OK]
  4941. ** upon successful entry. {H17026} Mutexes created using
  4942. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  4943. ** {H17027} In such cases the,
  4944. ** mutex must be exited an equal number of times before another thread
  4945. ** can enter. {A17028} If the same thread tries to enter any other
  4946. ** kind of mutex more than once, the behavior is undefined.
  4947. ** {H17029} SQLite will never exhibit
  4948. ** such behavior in its own use of mutexes.
  4949. **
  4950. ** Some systems (for example, Windows 95) do not support the operation
  4951. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  4952. ** will always return SQLITE_BUSY. {H17030} The SQLite core only ever uses
  4953. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
  4954. **
  4955. ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
  4956. ** previously entered by the same thread. {A17032} The behavior
  4957. ** is undefined if the mutex is not currently entered by the
  4958. ** calling thread or is not currently allocated. {H17033} SQLite will
  4959. ** never do either. {END}
  4960. **
  4961. ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  4962. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  4963. ** behave as no-ops.
  4964. **
  4965. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  4966. */
  4967. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  4968. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  4969. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  4970. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  4971. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  4972. /*
  4973. ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
  4974. ** EXPERIMENTAL
  4975. **
  4976. ** An instance of this structure defines the low-level routines
  4977. ** used to allocate and use mutexes.
  4978. **
  4979. ** Usually, the default mutex implementations provided by SQLite are
  4980. ** sufficient, however the user has the option of substituting a custom
  4981. ** implementation for specialized deployments or systems for which SQLite
  4982. ** does not provide a suitable implementation. In this case, the user
  4983. ** creates and populates an instance of this structure to pass
  4984. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  4985. ** Additionally, an instance of this structure can be used as an
  4986. ** output variable when querying the system for the current mutex
  4987. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  4988. **
  4989. ** The xMutexInit method defined by this structure is invoked as
  4990. ** part of system initialization by the sqlite3_initialize() function.
  4991. ** {H17001} The xMutexInit routine shall be called by SQLite once for each
  4992. ** effective call to [sqlite3_initialize()].
  4993. **
  4994. ** The xMutexEnd method defined by this structure is invoked as
  4995. ** part of system shutdown by the sqlite3_shutdown() function. The
  4996. ** implementation of this method is expected to release all outstanding
  4997. ** resources obtained by the mutex methods implementation, especially
  4998. ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
  4999. ** interface shall be invoked once for each call to [sqlite3_shutdown()].
  5000. **
  5001. ** The remaining seven methods defined by this structure (xMutexAlloc,
  5002. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5003. ** xMutexNotheld) implement the following interfaces (respectively):
  5004. **
  5005. ** <ul>
  5006. ** <li> [sqlite3_mutex_alloc()] </li>
  5007. ** <li> [sqlite3_mutex_free()] </li>
  5008. ** <li> [sqlite3_mutex_enter()] </li>
  5009. ** <li> [sqlite3_mutex_try()] </li>
  5010. ** <li> [sqlite3_mutex_leave()] </li>
  5011. ** <li> [sqlite3_mutex_held()] </li>
  5012. ** <li> [sqlite3_mutex_notheld()] </li>
  5013. ** </ul>
  5014. **
  5015. ** The only difference is that the public sqlite3_XXX functions enumerated
  5016. ** above silently ignore any invocations that pass a NULL pointer instead
  5017. ** of a valid mutex handle. The implementations of the methods defined
  5018. ** by this structure are not required to handle this case, the results
  5019. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5020. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5021. ** it is passed a NULL pointer).
  5022. */
  5023. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5024. struct sqlite3_mutex_methods {
  5025. int (*xMutexInit)(void);
  5026. int (*xMutexEnd)(void);
  5027. sqlite3_mutex *(*xMutexAlloc)(int);
  5028. void (*xMutexFree)(sqlite3_mutex *);
  5029. void (*xMutexEnter)(sqlite3_mutex *);
  5030. int (*xMutexTry)(sqlite3_mutex *);
  5031. void (*xMutexLeave)(sqlite3_mutex *);
  5032. int (*xMutexHeld)(sqlite3_mutex *);
  5033. int (*xMutexNotheld)(sqlite3_mutex *);
  5034. };
  5035. /*
  5036. ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
  5037. **
  5038. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5039. ** are intended for use inside assert() statements. {H17081} The SQLite core
  5040. ** never uses these routines except inside an assert() and applications
  5041. ** are advised to follow the lead of the core. {H17082} The core only
  5042. ** provides implementations for these routines when it is compiled
  5043. ** with the SQLITE_DEBUG flag. {A17087} External mutex implementations
  5044. ** are only required to provide these routines if SQLITE_DEBUG is
  5045. ** defined and if NDEBUG is not defined.
  5046. **
  5047. ** {H17083} These routines should return true if the mutex in their argument
  5048. ** is held or not held, respectively, by the calling thread.
  5049. **
  5050. ** {X17084} The implementation is not required to provided versions of these
  5051. ** routines that actually work. If the implementation does not provide working
  5052. ** versions of these routines, it should at least provide stubs that always
  5053. ** return true so that one does not get spurious assertion failures.
  5054. **
  5055. ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
  5056. ** the routine should return 1. {END} This seems counter-intuitive since
  5057. ** clearly the mutex cannot be held if it does not exist. But the
  5058. ** the reason the mutex does not exist is because the build is not
  5059. ** using mutexes. And we do not want the assert() containing the
  5060. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5061. ** the appropriate thing to do. {H17086} The sqlite3_mutex_notheld()
  5062. ** interface should also return 1 when given a NULL pointer.
  5063. */
  5064. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5065. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5066. /*
  5067. ** CAPI3REF: Mutex Types {H17001} <H17000>
  5068. **
  5069. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5070. ** which is one of these integer constants.
  5071. **
  5072. ** The set of static mutexes may change from one SQLite release to the
  5073. ** next. Applications that override the built-in mutex logic must be
  5074. ** prepared to accommodate additional static mutexes.
  5075. */
  5076. #define SQLITE_MUTEX_FAST 0
  5077. #define SQLITE_MUTEX_RECURSIVE 1
  5078. #define SQLITE_MUTEX_STATIC_MASTER 2
  5079. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  5080. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  5081. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  5082. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  5083. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  5084. #define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */
  5085. /*
  5086. ** CAPI3REF: Retrieve the mutex for a database connection {H17002} <H17000>
  5087. **
  5088. ** This interface returns a pointer the [sqlite3_mutex] object that
  5089. ** serializes access to the [database connection] given in the argument
  5090. ** when the [threading mode] is Serialized.
  5091. ** If the [threading mode] is Single-thread or Multi-thread then this
  5092. ** routine returns a NULL pointer.
  5093. */
  5094. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  5095. /*
  5096. ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
  5097. **
  5098. ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
  5099. ** xFileControl method for the [sqlite3_io_methods] object associated
  5100. ** with a particular database identified by the second argument. {H11302} The
  5101. ** name of the database is the name assigned to the database by the
  5102. ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
  5103. ** database. {H11303} To control the main database file, use the name "main"
  5104. ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
  5105. ** are passed directly through to the second and third parameters of
  5106. ** the xFileControl method. {H11305} The return value of the xFileControl
  5107. ** method becomes the return value of this routine.
  5108. **
  5109. ** {H11306} If the second parameter (zDbName) does not match the name of any
  5110. ** open database file, then SQLITE_ERROR is returned. {H11307} This error
  5111. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  5112. ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
  5113. ** also return SQLITE_ERROR. {A11309} There is no way to distinguish between
  5114. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  5115. ** xFileControl method. {END}
  5116. **
  5117. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  5118. */
  5119. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  5120. /*
  5121. ** CAPI3REF: Testing Interface {H11400} <S30800>
  5122. **
  5123. ** The sqlite3_test_control() interface is used to read out internal
  5124. ** state of SQLite and to inject faults into SQLite for testing
  5125. ** purposes. The first parameter is an operation code that determines
  5126. ** the number, meaning, and operation of all subsequent parameters.
  5127. **
  5128. ** This interface is not for use by applications. It exists solely
  5129. ** for verifying the correct operation of the SQLite library. Depending
  5130. ** on how the SQLite library is compiled, this interface might not exist.
  5131. **
  5132. ** The details of the operation codes, their meanings, the parameters
  5133. ** they take, and what they do are all subject to change without notice.
  5134. ** Unlike most of the SQLite API, this function is not guaranteed to
  5135. ** operate consistently from one release to the next.
  5136. */
  5137. SQLITE_API int sqlite3_test_control(int op, ...);
  5138. /*
  5139. ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
  5140. **
  5141. ** These constants are the valid operation code parameters used
  5142. ** as the first argument to [sqlite3_test_control()].
  5143. **
  5144. ** These parameters and their meanings are subject to change
  5145. ** without notice. These values are for testing purposes only.
  5146. ** Applications should not use any of these parameters or the
  5147. ** [sqlite3_test_control()] interface.
  5148. */
  5149. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  5150. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  5151. #define SQLITE_TESTCTRL_PRNG_RESET 7
  5152. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  5153. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  5154. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  5155. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  5156. /*
  5157. ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
  5158. ** EXPERIMENTAL
  5159. **
  5160. ** This interface is used to retrieve runtime status information
  5161. ** about the preformance of SQLite, and optionally to reset various
  5162. ** highwater marks. The first argument is an integer code for
  5163. ** the specific parameter to measure. Recognized integer codes
  5164. ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
  5165. ** The current value of the parameter is returned into *pCurrent.
  5166. ** The highest recorded value is returned in *pHighwater. If the
  5167. ** resetFlag is true, then the highest record value is reset after
  5168. ** *pHighwater is written. Some parameters do not record the highest
  5169. ** value. For those parameters
  5170. ** nothing is written into *pHighwater and the resetFlag is ignored.
  5171. ** Other parameters record only the highwater mark and not the current
  5172. ** value. For these latter parameters nothing is written into *pCurrent.
  5173. **
  5174. ** This routine returns SQLITE_OK on success and a non-zero
  5175. ** [error code] on failure.
  5176. **
  5177. ** This routine is threadsafe but is not atomic. This routine can
  5178. ** called while other threads are running the same or different SQLite
  5179. ** interfaces. However the values returned in *pCurrent and
  5180. ** *pHighwater reflect the status of SQLite at different points in time
  5181. ** and it is possible that another thread might change the parameter
  5182. ** in between the times when *pCurrent and *pHighwater are written.
  5183. **
  5184. ** See also: [sqlite3_db_status()]
  5185. */
  5186. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  5187. /*
  5188. ** CAPI3REF: Status Parameters {H17250} <H17200>
  5189. ** EXPERIMENTAL
  5190. **
  5191. ** These integer constants designate various run-time status parameters
  5192. ** that can be returned by [sqlite3_status()].
  5193. **
  5194. ** <dl>
  5195. ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
  5196. ** <dd>This parameter is the current amount of memory checked out
  5197. ** using [sqlite3_malloc()], either directly or indirectly. The
  5198. ** figure includes calls made to [sqlite3_malloc()] by the application
  5199. ** and internal memory usage by the SQLite library. Scratch memory
  5200. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  5201. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  5202. ** this parameter. The amount returned is the sum of the allocation
  5203. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
  5204. **
  5205. ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  5206. ** <dd>This parameter records the largest memory allocation request
  5207. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  5208. ** internal equivalents). Only the value returned in the
  5209. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5210. ** The value written into the *pCurrent parameter is undefined.</dd>
  5211. **
  5212. ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  5213. ** <dd>This parameter returns the number of pages used out of the
  5214. ** [pagecache memory allocator] that was configured using
  5215. ** [SQLITE_CONFIG_PAGECACHE]. The
  5216. ** value returned is in pages, not in bytes.</dd>
  5217. **
  5218. ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  5219. ** <dd>This parameter returns the number of bytes of page cache
  5220. ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
  5221. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  5222. ** returned value includes allocations that overflowed because they
  5223. ** where too large (they were larger than the "sz" parameter to
  5224. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  5225. ** no space was left in the page cache.</dd>
  5226. **
  5227. ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  5228. ** <dd>This parameter records the largest memory allocation request
  5229. ** handed to [pagecache memory allocator]. Only the value returned in the
  5230. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5231. ** The value written into the *pCurrent parameter is undefined.</dd>
  5232. **
  5233. ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  5234. ** <dd>This parameter returns the number of allocations used out of the
  5235. ** [scratch memory allocator] configured using
  5236. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  5237. ** in bytes. Since a single thread may only have one scratch allocation
  5238. ** outstanding at time, this parameter also reports the number of threads
  5239. ** using scratch memory at the same time.</dd>
  5240. **
  5241. ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  5242. ** <dd>This parameter returns the number of bytes of scratch memory
  5243. ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
  5244. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  5245. ** returned include overflows because the requested allocation was too
  5246. ** larger (that is, because the requested allocation was larger than the
  5247. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  5248. ** slots were available.
  5249. ** </dd>
  5250. **
  5251. ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  5252. ** <dd>This parameter records the largest memory allocation request
  5253. ** handed to [scratch memory allocator]. Only the value returned in the
  5254. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5255. ** The value written into the *pCurrent parameter is undefined.</dd>
  5256. **
  5257. ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
  5258. ** <dd>This parameter records the deepest parser stack. It is only
  5259. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
  5260. ** </dl>
  5261. **
  5262. ** New status parameters may be added from time to time.
  5263. */
  5264. #define SQLITE_STATUS_MEMORY_USED 0
  5265. #define SQLITE_STATUS_PAGECACHE_USED 1
  5266. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  5267. #define SQLITE_STATUS_SCRATCH_USED 3
  5268. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  5269. #define SQLITE_STATUS_MALLOC_SIZE 5
  5270. #define SQLITE_STATUS_PARSER_STACK 6
  5271. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  5272. #define SQLITE_STATUS_SCRATCH_SIZE 8
  5273. /*
  5274. ** CAPI3REF: Database Connection Status {H17500} <S60200>
  5275. ** EXPERIMENTAL
  5276. **
  5277. ** This interface is used to retrieve runtime status information
  5278. ** about a single [database connection]. The first argument is the
  5279. ** database connection object to be interrogated. The second argument
  5280. ** is the parameter to interrogate. Currently, the only allowed value
  5281. ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
  5282. ** Additional options will likely appear in future releases of SQLite.
  5283. **
  5284. ** The current value of the requested parameter is written into *pCur
  5285. ** and the highest instantaneous value is written into *pHiwtr. If
  5286. ** the resetFlg is true, then the highest instantaneous value is
  5287. ** reset back down to the current value.
  5288. **
  5289. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  5290. */
  5291. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  5292. /*
  5293. ** CAPI3REF: Status Parameters for database connections {H17520} <H17500>
  5294. ** EXPERIMENTAL
  5295. **
  5296. ** Status verbs for [sqlite3_db_status()].
  5297. **
  5298. ** <dl>
  5299. ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  5300. ** <dd>This parameter returns the number of lookaside memory slots currently
  5301. ** checked out.</dd>
  5302. ** </dl>
  5303. */
  5304. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  5305. /*
  5306. ** CAPI3REF: Prepared Statement Status {H17550} <S60200>
  5307. ** EXPERIMENTAL
  5308. **
  5309. ** Each prepared statement maintains various
  5310. ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
  5311. ** of times it has performed specific operations. These counters can
  5312. ** be used to monitor the performance characteristics of the prepared
  5313. ** statements. For example, if the number of table steps greatly exceeds
  5314. ** the number of table searches or result rows, that would tend to indicate
  5315. ** that the prepared statement is using a full table scan rather than
  5316. ** an index.
  5317. **
  5318. ** This interface is used to retrieve and reset counter values from
  5319. ** a [prepared statement]. The first argument is the prepared statement
  5320. ** object to be interrogated. The second argument
  5321. ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
  5322. ** to be interrogated.
  5323. ** The current value of the requested counter is returned.
  5324. ** If the resetFlg is true, then the counter is reset to zero after this
  5325. ** interface call returns.
  5326. **
  5327. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  5328. */
  5329. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  5330. /*
  5331. ** CAPI3REF: Status Parameters for prepared statements {H17570} <H17550>
  5332. ** EXPERIMENTAL
  5333. **
  5334. ** These preprocessor macros define integer codes that name counter
  5335. ** values associated with the [sqlite3_stmt_status()] interface.
  5336. ** The meanings of the various counters are as follows:
  5337. **
  5338. ** <dl>
  5339. ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  5340. ** <dd>This is the number of times that SQLite has stepped forward in
  5341. ** a table as part of a full table scan. Large numbers for this counter
  5342. ** may indicate opportunities for performance improvement through
  5343. ** careful use of indices.</dd>
  5344. **
  5345. ** <dt>SQLITE_STMTSTATUS_SORT</dt>
  5346. ** <dd>This is the number of sort operations that have occurred.
  5347. ** A non-zero value in this counter may indicate an opportunity to
  5348. ** improvement performance through careful use of indices.</dd>
  5349. **
  5350. ** </dl>
  5351. */
  5352. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  5353. #define SQLITE_STMTSTATUS_SORT 2
  5354. /*
  5355. ** CAPI3REF: Custom Page Cache Object
  5356. ** EXPERIMENTAL
  5357. **
  5358. ** The sqlite3_pcache type is opaque. It is implemented by
  5359. ** the pluggable module. The SQLite core has no knowledge of
  5360. ** its size or internal structure and never deals with the
  5361. ** sqlite3_pcache object except by holding and passing pointers
  5362. ** to the object.
  5363. **
  5364. ** See [sqlite3_pcache_methods] for additional information.
  5365. */
  5366. typedef struct sqlite3_pcache sqlite3_pcache;
  5367. /*
  5368. ** CAPI3REF: Application Defined Page Cache.
  5369. ** EXPERIMENTAL
  5370. **
  5371. ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
  5372. ** register an alternative page cache implementation by passing in an
  5373. ** instance of the sqlite3_pcache_methods structure. The majority of the
  5374. ** heap memory used by sqlite is used by the page cache to cache data read
  5375. ** from, or ready to be written to, the database file. By implementing a
  5376. ** custom page cache using this API, an application can control more
  5377. ** precisely the amount of memory consumed by sqlite, the way in which
  5378. ** said memory is allocated and released, and the policies used to
  5379. ** determine exactly which parts of a database file are cached and for
  5380. ** how long.
  5381. **
  5382. ** The contents of the structure are copied to an internal buffer by sqlite
  5383. ** within the call to [sqlite3_config].
  5384. **
  5385. ** The xInit() method is called once for each call to [sqlite3_initialize()]
  5386. ** (usually only once during the lifetime of the process). It is passed
  5387. ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set
  5388. ** up global structures and mutexes required by the custom page cache
  5389. ** implementation. The xShutdown() method is called from within
  5390. ** [sqlite3_shutdown()], if the application invokes this API. It can be used
  5391. ** to clean up any outstanding resources before process shutdown, if required.
  5392. **
  5393. ** The xCreate() method is used to construct a new cache instance. The
  5394. ** first parameter, szPage, is the size in bytes of the pages that must
  5395. ** be allocated by the cache. szPage will not be a power of two. The
  5396. ** second argument, bPurgeable, is true if the cache being created will
  5397. ** be used to cache database pages read from a file stored on disk, or
  5398. ** false if it is used for an in-memory database. The cache implementation
  5399. ** does not have to do anything special based on the value of bPurgeable,
  5400. ** it is purely advisory.
  5401. **
  5402. ** The xCachesize() method may be called at any time by SQLite to set the
  5403. ** suggested maximum cache-size (number of pages stored by) the cache
  5404. ** instance passed as the first argument. This is the value configured using
  5405. ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter,
  5406. ** the implementation is not required to do anything special with this
  5407. ** value, it is advisory only.
  5408. **
  5409. ** The xPagecount() method should return the number of pages currently
  5410. ** stored in the cache supplied as an argument.
  5411. **
  5412. ** The xFetch() method is used to fetch a page and return a pointer to it.
  5413. ** A 'page', in this context, is a buffer of szPage bytes aligned at an
  5414. ** 8-byte boundary. The page to be fetched is determined by the key. The
  5415. ** mimimum key value is 1. After it has been retrieved using xFetch, the page
  5416. ** is considered to be pinned.
  5417. **
  5418. ** If the requested page is already in the page cache, then a pointer to
  5419. ** the cached buffer should be returned with its contents intact. If the
  5420. ** page is not already in the cache, then the expected behaviour of the
  5421. ** cache is determined by the value of the createFlag parameter passed
  5422. ** to xFetch, according to the following table:
  5423. **
  5424. ** <table border=1 width=85% align=center>
  5425. ** <tr><th>createFlag<th>Expected Behaviour
  5426. ** <tr><td>0<td>NULL should be returned. No new cache entry is created.
  5427. ** <tr><td>1<td>If createFlag is set to 1, this indicates that
  5428. ** SQLite is holding pinned pages that can be unpinned
  5429. ** by writing their contents to the database file (a
  5430. ** relatively expensive operation). In this situation the
  5431. ** cache implementation has two choices: it can return NULL,
  5432. ** in which case SQLite will attempt to unpin one or more
  5433. ** pages before re-requesting the same page, or it can
  5434. ** allocate a new page and return a pointer to it. If a new
  5435. ** page is allocated, then the first sizeof(void*) bytes of
  5436. ** it (at least) must be zeroed before it is returned.
  5437. ** <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
  5438. ** pinned pages associated with the specific cache passed
  5439. ** as the first argument to xFetch() that can be unpinned. The
  5440. ** cache implementation should attempt to allocate a new
  5441. ** cache entry and return a pointer to it. Again, the first
  5442. ** sizeof(void*) bytes of the page should be zeroed before
  5443. ** it is returned. If the xFetch() method returns NULL when
  5444. ** createFlag==2, SQLite assumes that a memory allocation
  5445. ** failed and returns SQLITE_NOMEM to the user.
  5446. ** </table>
  5447. **
  5448. ** xUnpin() is called by SQLite with a pointer to a currently pinned page
  5449. ** as its second argument. If the third parameter, discard, is non-zero,
  5450. ** then the page should be evicted from the cache. In this case SQLite
  5451. ** assumes that the next time the page is retrieved from the cache using
  5452. ** the xFetch() method, it will be zeroed. If the discard parameter is
  5453. ** zero, then the page is considered to be unpinned. The cache implementation
  5454. ** may choose to reclaim (free or recycle) unpinned pages at any time.
  5455. ** SQLite assumes that next time the page is retrieved from the cache
  5456. ** it will either be zeroed, or contain the same data that it did when it
  5457. ** was unpinned.
  5458. **
  5459. ** The cache is not required to perform any reference counting. A single
  5460. ** call to xUnpin() unpins the page regardless of the number of prior calls
  5461. ** to xFetch().
  5462. **
  5463. ** The xRekey() method is used to change the key value associated with the
  5464. ** page passed as the second argument from oldKey to newKey. If the cache
  5465. ** previously contains an entry associated with newKey, it should be
  5466. ** discarded. Any prior cache entry associated with newKey is guaranteed not
  5467. ** to be pinned.
  5468. **
  5469. ** When SQLite calls the xTruncate() method, the cache must discard all
  5470. ** existing cache entries with page numbers (keys) greater than or equal
  5471. ** to the value of the iLimit parameter passed to xTruncate(). If any
  5472. ** of these pages are pinned, they are implicitly unpinned, meaning that
  5473. ** they can be safely discarded.
  5474. **
  5475. ** The xDestroy() method is used to delete a cache allocated by xCreate().
  5476. ** All resources associated with the specified cache should be freed. After
  5477. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  5478. ** handle invalid, and will not use it with any other sqlite3_pcache_methods
  5479. ** functions.
  5480. */
  5481. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  5482. struct sqlite3_pcache_methods {
  5483. void *pArg;
  5484. int (*xInit)(void*);
  5485. void (*xShutdown)(void*);
  5486. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  5487. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  5488. int (*xPagecount)(sqlite3_pcache*);
  5489. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  5490. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  5491. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  5492. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  5493. void (*xDestroy)(sqlite3_pcache*);
  5494. };
  5495. /*
  5496. ** CAPI3REF: Online Backup Object
  5497. ** EXPERIMENTAL
  5498. **
  5499. ** The sqlite3_backup object records state information about an ongoing
  5500. ** online backup operation. The sqlite3_backup object is created by
  5501. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  5502. ** [sqlite3_backup_finish()].
  5503. **
  5504. ** See Also: [Using the SQLite Online Backup API]
  5505. */
  5506. typedef struct sqlite3_backup sqlite3_backup;
  5507. /*
  5508. ** CAPI3REF: Online Backup API.
  5509. ** EXPERIMENTAL
  5510. **
  5511. ** This API is used to overwrite the contents of one database with that
  5512. ** of another. It is useful either for creating backups of databases or
  5513. ** for copying in-memory databases to or from persistent files.
  5514. **
  5515. ** See Also: [Using the SQLite Online Backup API]
  5516. **
  5517. ** Exclusive access is required to the destination database for the
  5518. ** duration of the operation. However the source database is only
  5519. ** read-locked while it is actually being read, it is not locked
  5520. ** continuously for the entire operation. Thus, the backup may be
  5521. ** performed on a live database without preventing other users from
  5522. ** writing to the database for an extended period of time.
  5523. **
  5524. ** To perform a backup operation:
  5525. ** <ol>
  5526. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  5527. ** backup,
  5528. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  5529. ** the data between the two databases, and finally
  5530. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  5531. ** associated with the backup operation.
  5532. ** </ol>
  5533. ** There should be exactly one call to sqlite3_backup_finish() for each
  5534. ** successful call to sqlite3_backup_init().
  5535. **
  5536. ** <b>sqlite3_backup_init()</b>
  5537. **
  5538. ** The first two arguments passed to [sqlite3_backup_init()] are the database
  5539. ** handle associated with the destination database and the database name
  5540. ** used to attach the destination database to the handle. The database name
  5541. ** is "main" for the main database, "temp" for the temporary database, or
  5542. ** the name specified as part of the [ATTACH] statement if the destination is
  5543. ** an attached database. The third and fourth arguments passed to
  5544. ** sqlite3_backup_init() identify the [database connection]
  5545. ** and database name used
  5546. ** to access the source database. The values passed for the source and
  5547. ** destination [database connection] parameters must not be the same.
  5548. **
  5549. ** If an error occurs within sqlite3_backup_init(), then NULL is returned
  5550. ** and an error code and error message written into the [database connection]
  5551. ** passed as the first argument. They may be retrieved using the
  5552. ** [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] functions.
  5553. ** Otherwise, if successful, a pointer to an [sqlite3_backup] object is
  5554. ** returned. This pointer may be used with the sqlite3_backup_step() and
  5555. ** sqlite3_backup_finish() functions to perform the specified backup
  5556. ** operation.
  5557. **
  5558. ** <b>sqlite3_backup_step()</b>
  5559. **
  5560. ** Function [sqlite3_backup_step()] is used to copy up to nPage pages between
  5561. ** the source and destination databases, where nPage is the value of the
  5562. ** second parameter passed to sqlite3_backup_step(). If nPage is a negative
  5563. ** value, all remaining source pages are copied. If the required pages are
  5564. ** succesfully copied, but there are still more pages to copy before the
  5565. ** backup is complete, it returns [SQLITE_OK]. If no error occured and there
  5566. ** are no more pages to copy, then [SQLITE_DONE] is returned. If an error
  5567. ** occurs, then an SQLite error code is returned. As well as [SQLITE_OK] and
  5568. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  5569. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  5570. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  5571. **
  5572. ** As well as the case where the destination database file was opened for
  5573. ** read-only access, sqlite3_backup_step() may return [SQLITE_READONLY] if
  5574. ** the destination is an in-memory database with a different page size
  5575. ** from the source database.
  5576. **
  5577. ** If sqlite3_backup_step() cannot obtain a required file-system lock, then
  5578. ** the [sqlite3_busy_handler | busy-handler function]
  5579. ** is invoked (if one is specified). If the
  5580. ** busy-handler returns non-zero before the lock is available, then
  5581. ** [SQLITE_BUSY] is returned to the caller. In this case the call to
  5582. ** sqlite3_backup_step() can be retried later. If the source
  5583. ** [database connection]
  5584. ** is being used to write to the source database when sqlite3_backup_step()
  5585. ** is called, then [SQLITE_LOCKED] is returned immediately. Again, in this
  5586. ** case the call to sqlite3_backup_step() can be retried later on. If
  5587. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  5588. ** [SQLITE_READONLY] is returned, then
  5589. ** there is no point in retrying the call to sqlite3_backup_step(). These
  5590. ** errors are considered fatal. At this point the application must accept
  5591. ** that the backup operation has failed and pass the backup operation handle
  5592. ** to the sqlite3_backup_finish() to release associated resources.
  5593. **
  5594. ** Following the first call to sqlite3_backup_step(), an exclusive lock is
  5595. ** obtained on the destination file. It is not released until either
  5596. ** sqlite3_backup_finish() is called or the backup operation is complete
  5597. ** and sqlite3_backup_step() returns [SQLITE_DONE]. Additionally, each time
  5598. ** a call to sqlite3_backup_step() is made a [shared lock] is obtained on
  5599. ** the source database file. This lock is released before the
  5600. ** sqlite3_backup_step() call returns. Because the source database is not
  5601. ** locked between calls to sqlite3_backup_step(), it may be modified mid-way
  5602. ** through the backup procedure. If the source database is modified by an
  5603. ** external process or via a database connection other than the one being
  5604. ** used by the backup operation, then the backup will be transparently
  5605. ** restarted by the next call to sqlite3_backup_step(). If the source
  5606. ** database is modified by the using the same database connection as is used
  5607. ** by the backup operation, then the backup database is transparently
  5608. ** updated at the same time.
  5609. **
  5610. ** <b>sqlite3_backup_finish()</b>
  5611. **
  5612. ** Once sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  5613. ** application wishes to abandon the backup operation, the [sqlite3_backup]
  5614. ** object should be passed to sqlite3_backup_finish(). This releases all
  5615. ** resources associated with the backup operation. If sqlite3_backup_step()
  5616. ** has not yet returned [SQLITE_DONE], then any active write-transaction on the
  5617. ** destination database is rolled back. The [sqlite3_backup] object is invalid
  5618. ** and may not be used following a call to sqlite3_backup_finish().
  5619. **
  5620. ** The value returned by sqlite3_backup_finish is [SQLITE_OK] if no error
  5621. ** occurred, regardless or whether or not sqlite3_backup_step() was called
  5622. ** a sufficient number of times to complete the backup operation. Or, if
  5623. ** an out-of-memory condition or IO error occured during a call to
  5624. ** sqlite3_backup_step() then [SQLITE_NOMEM] or an
  5625. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] error code
  5626. ** is returned. In this case the error code and an error message are
  5627. ** written to the destination [database connection].
  5628. **
  5629. ** A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() is
  5630. ** not a permanent error and does not affect the return value of
  5631. ** sqlite3_backup_finish().
  5632. **
  5633. ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
  5634. **
  5635. ** Each call to sqlite3_backup_step() sets two values stored internally
  5636. ** by an [sqlite3_backup] object. The number of pages still to be backed
  5637. ** up, which may be queried by sqlite3_backup_remaining(), and the total
  5638. ** number of pages in the source database file, which may be queried by
  5639. ** sqlite3_backup_pagecount().
  5640. **
  5641. ** The values returned by these functions are only updated by
  5642. ** sqlite3_backup_step(). If the source database is modified during a backup
  5643. ** operation, then the values are not updated to account for any extra
  5644. ** pages that need to be updated or the size of the source database file
  5645. ** changing.
  5646. **
  5647. ** <b>Concurrent Usage of Database Handles</b>
  5648. **
  5649. ** The source [database connection] may be used by the application for other
  5650. ** purposes while a backup operation is underway or being initialized.
  5651. ** If SQLite is compiled and configured to support threadsafe database
  5652. ** connections, then the source database connection may be used concurrently
  5653. ** from within other threads.
  5654. **
  5655. ** However, the application must guarantee that the destination database
  5656. ** connection handle is not passed to any other API (by any thread) after
  5657. ** sqlite3_backup_init() is called and before the corresponding call to
  5658. ** sqlite3_backup_finish(). Unfortunately SQLite does not currently check
  5659. ** for this, if the application does use the destination [database connection]
  5660. ** for some other purpose during a backup operation, things may appear to
  5661. ** work correctly but in fact be subtly malfunctioning. Use of the
  5662. ** destination database connection while a backup is in progress might
  5663. ** also cause a mutex deadlock.
  5664. **
  5665. ** Furthermore, if running in [shared cache mode], the application must
  5666. ** guarantee that the shared cache used by the destination database
  5667. ** is not accessed while the backup is running. In practice this means
  5668. ** that the application must guarantee that the file-system file being
  5669. ** backed up to is not accessed by any connection within the process,
  5670. ** not just the specific connection that was passed to sqlite3_backup_init().
  5671. **
  5672. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  5673. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  5674. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  5675. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  5676. ** same time as another thread is invoking sqlite3_backup_step() it is
  5677. ** possible that they return invalid values.
  5678. */
  5679. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  5680. sqlite3 *pDest, /* Destination database handle */
  5681. const char *zDestName, /* Destination database name */
  5682. sqlite3 *pSource, /* Source database handle */
  5683. const char *zSourceName /* Source database name */
  5684. );
  5685. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  5686. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  5687. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  5688. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  5689. /*
  5690. ** CAPI3REF: Unlock Notification
  5691. ** EXPERIMENTAL
  5692. **
  5693. ** When running in shared-cache mode, a database operation may fail with
  5694. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  5695. ** individual tables within the shared-cache cannot be obtained. See
  5696. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  5697. ** This API may be used to register a callback that SQLite will invoke
  5698. ** when the connection currently holding the required lock relinquishes it.
  5699. ** This API is only available if the library was compiled with the
  5700. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  5701. **
  5702. ** See Also: [Using the SQLite Unlock Notification Feature].
  5703. **
  5704. ** Shared-cache locks are released when a database connection concludes
  5705. ** its current transaction, either by committing it or rolling it back.
  5706. **
  5707. ** When a connection (known as the blocked connection) fails to obtain a
  5708. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  5709. ** identity of the database connection (the blocking connection) that
  5710. ** has locked the required resource is stored internally. After an
  5711. ** application receives an SQLITE_LOCKED error, it may call the
  5712. ** sqlite3_unlock_notify() method with the blocked connection handle as
  5713. ** the first argument to register for a callback that will be invoked
  5714. ** when the blocking connections current transaction is concluded. The
  5715. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  5716. ** call that concludes the blocking connections transaction.
  5717. **
  5718. ** If sqlite3_unlock_notify() is called in a multi-threaded application,
  5719. ** there is a chance that the blocking connection will have already
  5720. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  5721. ** If this happens, then the specified callback is invoked immediately,
  5722. ** from within the call to sqlite3_unlock_notify().
  5723. **
  5724. ** If the blocked connection is attempting to obtain a write-lock on a
  5725. ** shared-cache table, and more than one other connection currently holds
  5726. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  5727. ** the other connections to use as the blocking connection.
  5728. **
  5729. ** There may be at most one unlock-notify callback registered by a
  5730. ** blocked connection. If sqlite3_unlock_notify() is called when the
  5731. ** blocked connection already has a registered unlock-notify callback,
  5732. ** then the new callback replaces the old. If sqlite3_unlock_notify() is
  5733. ** called with a NULL pointer as its second argument, then any existing
  5734. ** unlock-notify callback is cancelled. The blocked connections
  5735. ** unlock-notify callback may also be canceled by closing the blocked
  5736. ** connection using [sqlite3_close()].
  5737. **
  5738. ** The unlock-notify callback is not reentrant. If an application invokes
  5739. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  5740. ** crash or deadlock may be the result.
  5741. **
  5742. ** Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  5743. ** returns SQLITE_OK.
  5744. **
  5745. ** <b>Callback Invocation Details</b>
  5746. **
  5747. ** When an unlock-notify callback is registered, the application provides a
  5748. ** single void* pointer that is passed to the callback when it is invoked.
  5749. ** However, the signature of the callback function allows SQLite to pass
  5750. ** it an array of void* context pointers. The first argument passed to
  5751. ** an unlock-notify callback is a pointer to an array of void* pointers,
  5752. ** and the second is the number of entries in the array.
  5753. **
  5754. ** When a blocking connections transaction is concluded, there may be
  5755. ** more than one blocked connection that has registered for an unlock-notify
  5756. ** callback. If two or more such blocked connections have specified the
  5757. ** same callback function, then instead of invoking the callback function
  5758. ** multiple times, it is invoked once with the set of void* context pointers
  5759. ** specified by the blocked connections bundled together into an array.
  5760. ** This gives the application an opportunity to prioritize any actions
  5761. ** related to the set of unblocked database connections.
  5762. **
  5763. ** <b>Deadlock Detection</b>
  5764. **
  5765. ** Assuming that after registering for an unlock-notify callback a
  5766. ** database waits for the callback to be issued before taking any further
  5767. ** action (a reasonable assumption), then using this API may cause the
  5768. ** application to deadlock. For example, if connection X is waiting for
  5769. ** connection Y's transaction to be concluded, and similarly connection
  5770. ** Y is waiting on connection X's transaction, then neither connection
  5771. ** will proceed and the system may remain deadlocked indefinitely.
  5772. **
  5773. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  5774. ** detection. If a given call to sqlite3_unlock_notify() would put the
  5775. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  5776. ** unlock-notify callback is registered. The system is said to be in
  5777. ** a deadlocked state if connection A has registered for an unlock-notify
  5778. ** callback on the conclusion of connection B's transaction, and connection
  5779. ** B has itself registered for an unlock-notify callback when connection
  5780. ** A's transaction is concluded. Indirect deadlock is also detected, so
  5781. ** the system is also considered to be deadlocked if connection B has
  5782. ** registered for an unlock-notify callback on the conclusion of connection
  5783. ** C's transaction, where connection C is waiting on connection A. Any
  5784. ** number of levels of indirection are allowed.
  5785. **
  5786. ** <b>The "DROP TABLE" Exception</b>
  5787. **
  5788. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  5789. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  5790. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  5791. ** SQLite checks if there are any currently executing SELECT statements
  5792. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  5793. ** returned. In this case there is no "blocking connection", so invoking
  5794. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  5795. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  5796. ** or "DROP INDEX" query, an infinite loop might be the result.
  5797. **
  5798. ** One way around this problem is to check the extended error code returned
  5799. ** by an sqlite3_step() call. If there is a blocking connection, then the
  5800. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  5801. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  5802. ** SQLITE_LOCKED.
  5803. */
  5804. SQLITE_API int sqlite3_unlock_notify(
  5805. sqlite3 *pBlocked, /* Waiting connection */
  5806. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  5807. void *pNotifyArg /* Argument to pass to xNotify */
  5808. );
  5809. /*
  5810. ** Undo the hack that converts floating point types to integer for
  5811. ** builds on processors without floating point support.
  5812. */
  5813. #ifdef SQLITE_OMIT_FLOATING_POINT
  5814. # undef double
  5815. #endif
  5816. #if 0
  5817. } /* End of the 'extern "C"' block */
  5818. #endif
  5819. #endif
  5820. /************** End of sqlite3.h *********************************************/
  5821. /************** Continuing where we left off in sqliteInt.h ******************/
  5822. /************** Include hash.h in the middle of sqliteInt.h ******************/
  5823. /************** Begin file hash.h ********************************************/
  5824. /*
  5825. ** 2001 September 22
  5826. **
  5827. ** The author disclaims copyright to this source code. In place of
  5828. ** a legal notice, here is a blessing:
  5829. **
  5830. ** May you do good and not evil.
  5831. ** May you find forgiveness for yourself and forgive others.
  5832. ** May you share freely, never taking more than you give.
  5833. **
  5834. *************************************************************************
  5835. ** This is the header file for the generic hash-table implemenation
  5836. ** used in SQLite.
  5837. **
  5838. ** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
  5839. */
  5840. #ifndef _SQLITE_HASH_H_
  5841. #define _SQLITE_HASH_H_
  5842. /* Forward declarations of structures. */
  5843. typedef struct Hash Hash;
  5844. typedef struct HashElem HashElem;
  5845. /* A complete hash table is an instance of the following structure.
  5846. ** The internals of this structure are intended to be opaque -- client
  5847. ** code should not attempt to access or modify the fields of this structure
  5848. ** directly. Change this structure only by using the routines below.
  5849. ** However, many of the "procedures" and "functions" for modifying and
  5850. ** accessing this structure are really macros, so we can't really make
  5851. ** this structure opaque.
  5852. */
  5853. struct Hash {
  5854. unsigned int copyKey: 1; /* True if copy of key made on insert */
  5855. unsigned int htsize : 31; /* Number of buckets in the hash table */
  5856. unsigned int count; /* Number of entries in this table */
  5857. HashElem *first; /* The first element of the array */
  5858. struct _ht { /* the hash table */
  5859. int count; /* Number of entries with this hash */
  5860. HashElem *chain; /* Pointer to first entry with this hash */
  5861. } *ht;
  5862. };
  5863. /* Each element in the hash table is an instance of the following
  5864. ** structure. All elements are stored on a single doubly-linked list.
  5865. **
  5866. ** Again, this structure is intended to be opaque, but it can't really
  5867. ** be opaque because it is used by macros.
  5868. */
  5869. struct HashElem {
  5870. HashElem *next, *prev; /* Next and previous elements in the table */
  5871. void *data; /* Data associated with this element */
  5872. void *pKey; int nKey; /* Key associated with this element */
  5873. };
  5874. /*
  5875. ** Access routines. To delete, insert a NULL pointer.
  5876. */
  5877. SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
  5878. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
  5879. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
  5880. SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
  5881. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  5882. /*
  5883. ** Macros for looping over all elements of a hash table. The idiom is
  5884. ** like this:
  5885. **
  5886. ** Hash h;
  5887. ** HashElem *p;
  5888. ** ...
  5889. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  5890. ** SomeStructure *pData = sqliteHashData(p);
  5891. ** // do something with pData
  5892. ** }
  5893. */
  5894. #define sqliteHashFirst(H) ((H)->first)
  5895. #define sqliteHashNext(E) ((E)->next)
  5896. #define sqliteHashData(E) ((E)->data)
  5897. #define sqliteHashKey(E) ((E)->pKey)
  5898. #define sqliteHashKeysize(E) ((E)->nKey)
  5899. /*
  5900. ** Number of entries in a hash table
  5901. */
  5902. #define sqliteHashCount(H) ((H)->count)
  5903. #endif /* _SQLITE_HASH_H_ */
  5904. /************** End of hash.h ************************************************/
  5905. /************** Continuing where we left off in sqliteInt.h ******************/
  5906. /************** Include parse.h in the middle of sqliteInt.h *****************/
  5907. /************** Begin file parse.h *******************************************/
  5908. #define TK_SEMI 1
  5909. #define TK_EXPLAIN 2
  5910. #define TK_QUERY 3
  5911. #define TK_PLAN 4
  5912. #define TK_BEGIN 5
  5913. #define TK_TRANSACTION 6
  5914. #define TK_DEFERRED 7
  5915. #define TK_IMMEDIATE 8
  5916. #define TK_EXCLUSIVE 9
  5917. #define TK_COMMIT 10
  5918. #define TK_END 11
  5919. #define TK_ROLLBACK 12
  5920. #define TK_SAVEPOINT 13
  5921. #define TK_RELEASE 14
  5922. #define TK_TO 15
  5923. #define TK_TABLE 16
  5924. #define TK_CREATE 17
  5925. #define TK_IF 18
  5926. #define TK_NOT 19
  5927. #define TK_EXISTS 20
  5928. #define TK_TEMP 21
  5929. #define TK_LP 22
  5930. #define TK_RP 23
  5931. #define TK_AS 24
  5932. #define TK_COMMA 25
  5933. #define TK_ID 26
  5934. #define TK_INDEXED 27
  5935. #define TK_ABORT 28
  5936. #define TK_AFTER 29
  5937. #define TK_ANALYZE 30
  5938. #define TK_ASC 31
  5939. #define TK_ATTACH 32
  5940. #define TK_BEFORE 33
  5941. #define TK_BY 34
  5942. #define TK_CASCADE 35
  5943. #define TK_CAST 36
  5944. #define TK_COLUMNKW 37
  5945. #define TK_CONFLICT 38
  5946. #define TK_DATABASE 39
  5947. #define TK_DESC 40
  5948. #define TK_DETACH 41
  5949. #define TK_EACH 42
  5950. #define TK_FAIL 43
  5951. #define TK_FOR 44
  5952. #define TK_IGNORE 45
  5953. #define TK_INITIALLY 46
  5954. #define TK_INSTEAD 47
  5955. #define TK_LIKE_KW 48
  5956. #define TK_MATCH 49
  5957. #define TK_KEY 50
  5958. #define TK_OF 51
  5959. #define TK_OFFSET 52
  5960. #define TK_PRAGMA 53
  5961. #define TK_RAISE 54
  5962. #define TK_REPLACE 55
  5963. #define TK_RESTRICT 56
  5964. #define TK_ROW 57
  5965. #define TK_TRIGGER 58
  5966. #define TK_VACUUM 59
  5967. #define TK_VIEW 60
  5968. #define TK_VIRTUAL 61
  5969. #define TK_REINDEX 62
  5970. #define TK_RENAME 63
  5971. #define TK_CTIME_KW 64
  5972. #define TK_ANY 65
  5973. #define TK_OR 66
  5974. #define TK_AND 67
  5975. #define TK_IS 68
  5976. #define TK_BETWEEN 69
  5977. #define TK_IN 70
  5978. #define TK_ISNULL 71
  5979. #define TK_NOTNULL 72
  5980. #define TK_NE 73
  5981. #define TK_EQ 74
  5982. #define TK_GT 75
  5983. #define TK_LE 76
  5984. #define TK_LT 77
  5985. #define TK_GE 78
  5986. #define TK_ESCAPE 79
  5987. #define TK_BITAND 80
  5988. #define TK_BITOR 81
  5989. #define TK_LSHIFT 82
  5990. #define TK_RSHIFT 83
  5991. #define TK_PLUS 84
  5992. #define TK_MINUS 85
  5993. #define TK_STAR 86
  5994. #define TK_SLASH 87
  5995. #define TK_REM 88
  5996. #define TK_CONCAT 89
  5997. #define TK_COLLATE 90
  5998. #define TK_UMINUS 91
  5999. #define TK_UPLUS 92
  6000. #define TK_BITNOT 93
  6001. #define TK_STRING 94
  6002. #define TK_JOIN_KW 95
  6003. #define TK_CONSTRAINT 96
  6004. #define TK_DEFAULT 97
  6005. #define TK_NULL 98
  6006. #define TK_PRIMARY 99
  6007. #define TK_UNIQUE 100
  6008. #define TK_CHECK 101
  6009. #define TK_REFERENCES 102
  6010. #define TK_AUTOINCR 103
  6011. #define TK_ON 104
  6012. #define TK_DELETE 105
  6013. #define TK_UPDATE 106
  6014. #define TK_INSERT 107
  6015. #define TK_SET 108
  6016. #define TK_DEFERRABLE 109
  6017. #define TK_FOREIGN 110
  6018. #define TK_DROP 111
  6019. #define TK_UNION 112
  6020. #define TK_ALL 113
  6021. #define TK_EXCEPT 114
  6022. #define TK_INTERSECT 115
  6023. #define TK_SELECT 116
  6024. #define TK_DISTINCT 117
  6025. #define TK_DOT 118
  6026. #define TK_FROM 119
  6027. #define TK_JOIN 120
  6028. #define TK_USING 121
  6029. #define TK_ORDER 122
  6030. #define TK_GROUP 123
  6031. #define TK_HAVING 124
  6032. #define TK_LIMIT 125
  6033. #define TK_WHERE 126
  6034. #define TK_INTO 127
  6035. #define TK_VALUES 128
  6036. #define TK_INTEGER 129
  6037. #define TK_FLOAT 130
  6038. #define TK_BLOB 131
  6039. #define TK_REGISTER 132
  6040. #define TK_VARIABLE 133
  6041. #define TK_CASE 134
  6042. #define TK_WHEN 135
  6043. #define TK_THEN 136
  6044. #define TK_ELSE 137
  6045. #define TK_INDEX 138
  6046. #define TK_ALTER 139
  6047. #define TK_ADD 140
  6048. #define TK_TO_TEXT 141
  6049. #define TK_TO_BLOB 142
  6050. #define TK_TO_NUMERIC 143
  6051. #define TK_TO_INT 144
  6052. #define TK_TO_REAL 145
  6053. #define TK_END_OF_FILE 146
  6054. #define TK_ILLEGAL 147
  6055. #define TK_SPACE 148
  6056. #define TK_UNCLOSED_STRING 149
  6057. #define TK_FUNCTION 150
  6058. #define TK_COLUMN 151
  6059. #define TK_AGG_FUNCTION 152
  6060. #define TK_AGG_COLUMN 153
  6061. #define TK_CONST_FUNC 154
  6062. /************** End of parse.h ***********************************************/
  6063. /************** Continuing where we left off in sqliteInt.h ******************/
  6064. #include <stdio.h>
  6065. #include <stdlib.h>
  6066. #include <string.h>
  6067. #include <assert.h>
  6068. #include <stddef.h>
  6069. /*
  6070. ** If compiling for a processor that lacks floating point support,
  6071. ** substitute integer for floating-point
  6072. */
  6073. #ifdef SQLITE_OMIT_FLOATING_POINT
  6074. # define double sqlite_int64
  6075. # define LONGDOUBLE_TYPE sqlite_int64
  6076. # ifndef SQLITE_BIG_DBL
  6077. # define SQLITE_BIG_DBL (0x7fffffffffffffff)
  6078. # endif
  6079. # define SQLITE_OMIT_DATETIME_FUNCS 1
  6080. # define SQLITE_OMIT_TRACE 1
  6081. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  6082. #endif
  6083. #ifndef SQLITE_BIG_DBL
  6084. # define SQLITE_BIG_DBL (1e99)
  6085. #endif
  6086. /*
  6087. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  6088. ** afterward. Having this macro allows us to cause the C compiler
  6089. ** to omit code used by TEMP tables without messy #ifndef statements.
  6090. */
  6091. #ifdef SQLITE_OMIT_TEMPDB
  6092. #define OMIT_TEMPDB 1
  6093. #else
  6094. #define OMIT_TEMPDB 0
  6095. #endif
  6096. /*
  6097. ** If the following macro is set to 1, then NULL values are considered
  6098. ** distinct when determining whether or not two entries are the same
  6099. ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
  6100. ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
  6101. ** is the way things are suppose to work.
  6102. **
  6103. ** If the following macro is set to 0, the NULLs are indistinct for
  6104. ** a UNIQUE index. In this mode, you can only have a single NULL entry
  6105. ** for a column declared UNIQUE. This is the way Informix and SQL Server
  6106. ** work.
  6107. */
  6108. #define NULL_DISTINCT_FOR_UNIQUE 1
  6109. /*
  6110. ** The "file format" number is an integer that is incremented whenever
  6111. ** the VDBE-level file format changes. The following macros define the
  6112. ** the default file format for new databases and the maximum file format
  6113. ** that the library can read.
  6114. */
  6115. #define SQLITE_MAX_FILE_FORMAT 4
  6116. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  6117. # define SQLITE_DEFAULT_FILE_FORMAT 1
  6118. #endif
  6119. /*
  6120. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  6121. ** on the command-line
  6122. */
  6123. #ifndef SQLITE_TEMP_STORE
  6124. # define SQLITE_TEMP_STORE 1
  6125. #endif
  6126. /*
  6127. ** GCC does not define the offsetof() macro so we'll have to do it
  6128. ** ourselves.
  6129. */
  6130. #ifndef offsetof
  6131. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  6132. #endif
  6133. /*
  6134. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  6135. ** not, there are still machines out there that use EBCDIC.)
  6136. */
  6137. #if 'A' == '\301'
  6138. # define SQLITE_EBCDIC 1
  6139. #else
  6140. # define SQLITE_ASCII 1
  6141. #endif
  6142. /*
  6143. ** Integers of known sizes. These typedefs might change for architectures
  6144. ** where the sizes very. Preprocessor macros are available so that the
  6145. ** types can be conveniently redefined at compile-type. Like this:
  6146. **
  6147. ** cc '-DUINTPTR_TYPE=long long int' ...
  6148. */
  6149. #ifndef UINT32_TYPE
  6150. # ifdef HAVE_UINT32_T
  6151. # define UINT32_TYPE uint32_t
  6152. # else
  6153. # define UINT32_TYPE unsigned int
  6154. # endif
  6155. #endif
  6156. #ifndef UINT16_TYPE
  6157. # ifdef HAVE_UINT16_T
  6158. # define UINT16_TYPE uint16_t
  6159. # else
  6160. # define UINT16_TYPE unsigned short int
  6161. # endif
  6162. #endif
  6163. #ifndef INT16_TYPE
  6164. # ifdef HAVE_INT16_T
  6165. # define INT16_TYPE int16_t
  6166. # else
  6167. # define INT16_TYPE short int
  6168. # endif
  6169. #endif
  6170. #ifndef UINT8_TYPE
  6171. # ifdef HAVE_UINT8_T
  6172. # define UINT8_TYPE uint8_t
  6173. # else
  6174. # define UINT8_TYPE unsigned char
  6175. # endif
  6176. #endif
  6177. #ifndef INT8_TYPE
  6178. # ifdef HAVE_INT8_T
  6179. # define INT8_TYPE int8_t
  6180. # else
  6181. # define INT8_TYPE signed char
  6182. # endif
  6183. #endif
  6184. #ifndef LONGDOUBLE_TYPE
  6185. # define LONGDOUBLE_TYPE long double
  6186. #endif
  6187. typedef sqlite_int64 i64; /* 8-byte signed integer */
  6188. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  6189. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  6190. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  6191. typedef INT16_TYPE i16; /* 2-byte signed integer */
  6192. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  6193. typedef INT8_TYPE i8; /* 1-byte signed integer */
  6194. /*
  6195. ** Macros to determine whether the machine is big or little endian,
  6196. ** evaluated at runtime.
  6197. */
  6198. #ifdef SQLITE_AMALGAMATION
  6199. SQLITE_PRIVATE const int sqlite3one = 1;
  6200. #else
  6201. SQLITE_PRIVATE const int sqlite3one;
  6202. #endif
  6203. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  6204. || defined(__x86_64) || defined(__x86_64__)
  6205. # define SQLITE_BIGENDIAN 0
  6206. # define SQLITE_LITTLEENDIAN 1
  6207. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  6208. #else
  6209. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  6210. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  6211. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  6212. #endif
  6213. /*
  6214. ** Constants for the largest and smallest possible 64-bit signed integers.
  6215. ** These macros are designed to work correctly on both 32-bit and 64-bit
  6216. ** compilers.
  6217. */
  6218. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  6219. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  6220. /*
  6221. ** Round up a number to the next larger multiple of 8. This is used
  6222. ** to force 8-byte alignment on 64-bit architectures.
  6223. */
  6224. #define ROUND8(x) (((x)+7)&~7)
  6225. /*
  6226. ** Round down to the nearest multiple of 8
  6227. */
  6228. #define ROUNDDOWN8(x) ((x)&~7)
  6229. /*
  6230. ** Assert that the pointer X is aligned to an 8-byte boundary.
  6231. */
  6232. #define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  6233. /*
  6234. ** An instance of the following structure is used to store the busy-handler
  6235. ** callback for a given sqlite handle.
  6236. **
  6237. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  6238. ** callback for the database handle. Each pager opened via the sqlite
  6239. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  6240. ** callback is currently invoked only from within pager.c.
  6241. */
  6242. typedef struct BusyHandler BusyHandler;
  6243. struct BusyHandler {
  6244. int (*xFunc)(void *,int); /* The busy callback */
  6245. void *pArg; /* First arg to busy callback */
  6246. int nBusy; /* Incremented with each busy call */
  6247. };
  6248. /*
  6249. ** Name of the master database table. The master database table
  6250. ** is a special table that holds the names and attributes of all
  6251. ** user tables and indices.
  6252. */
  6253. #define MASTER_NAME "sqlite_master"
  6254. #define TEMP_MASTER_NAME "sqlite_temp_master"
  6255. /*
  6256. ** The root-page of the master database table.
  6257. */
  6258. #define MASTER_ROOT 1
  6259. /*
  6260. ** The name of the schema table.
  6261. */
  6262. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  6263. /*
  6264. ** A convenience macro that returns the number of elements in
  6265. ** an array.
  6266. */
  6267. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  6268. /*
  6269. ** The following value as a destructor means to use sqlite3DbFree().
  6270. ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
  6271. */
  6272. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
  6273. /*
  6274. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  6275. ** not support Writable Static Data (WSD) such as global and static variables.
  6276. ** All variables must either be on the stack or dynamically allocated from
  6277. ** the heap. When WSD is unsupported, the variable declarations scattered
  6278. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  6279. ** macro is used for this purpose. And instead of referencing the variable
  6280. ** directly, we use its constant as a key to lookup the run-time allocated
  6281. ** buffer that holds real variable. The constant is also the initializer
  6282. ** for the run-time allocated buffer.
  6283. **
  6284. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  6285. ** macros become no-ops and have zero performance impact.
  6286. */
  6287. #ifdef SQLITE_OMIT_WSD
  6288. #define SQLITE_WSD const
  6289. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  6290. #define sqlite3GlobalConfig GLOBAL(struct SQLite3Config, sqlite3Config)
  6291. SQLITE_API int sqlite3_wsd_init(int N, int J);
  6292. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  6293. #else
  6294. #define SQLITE_WSD
  6295. #define GLOBAL(t,v) v
  6296. #define sqlite3GlobalConfig sqlite3Config
  6297. #endif
  6298. /*
  6299. ** The following macros are used to suppress compiler warnings and to
  6300. ** make it clear to human readers when a function parameter is deliberately
  6301. ** left unused within the body of a function. This usually happens when
  6302. ** a function is called via a function pointer. For example the
  6303. ** implementation of an SQL aggregate step callback may not use the
  6304. ** parameter indicating the number of arguments passed to the aggregate,
  6305. ** if it knows that this is enforced elsewhere.
  6306. **
  6307. ** When a function parameter is not used at all within the body of a function,
  6308. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  6309. ** However, these macros may also be used to suppress warnings related to
  6310. ** parameters that may or may not be used depending on compilation options.
  6311. ** For example those parameters only used in assert() statements. In these
  6312. ** cases the parameters are named as per the usual conventions.
  6313. */
  6314. #define UNUSED_PARAMETER(x) (void)(x)
  6315. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  6316. /*
  6317. ** Forward references to structures
  6318. */
  6319. typedef struct AggInfo AggInfo;
  6320. typedef struct AuthContext AuthContext;
  6321. typedef struct Bitvec Bitvec;
  6322. typedef struct RowSet RowSet;
  6323. typedef struct CollSeq CollSeq;
  6324. typedef struct Column Column;
  6325. typedef struct Db Db;
  6326. typedef struct Schema Schema;
  6327. typedef struct Expr Expr;
  6328. typedef struct ExprList ExprList;
  6329. typedef struct FKey FKey;
  6330. typedef struct FuncDef FuncDef;
  6331. typedef struct FuncDefHash FuncDefHash;
  6332. typedef struct IdList IdList;
  6333. typedef struct Index Index;
  6334. typedef struct KeyClass KeyClass;
  6335. typedef struct KeyInfo KeyInfo;
  6336. typedef struct Lookaside Lookaside;
  6337. typedef struct LookasideSlot LookasideSlot;
  6338. typedef struct Module Module;
  6339. typedef struct NameContext NameContext;
  6340. typedef struct Parse Parse;
  6341. typedef struct Savepoint Savepoint;
  6342. typedef struct Select Select;
  6343. typedef struct SrcList SrcList;
  6344. typedef struct StrAccum StrAccum;
  6345. typedef struct Table Table;
  6346. typedef struct TableLock TableLock;
  6347. typedef struct Token Token;
  6348. typedef struct TriggerStack TriggerStack;
  6349. typedef struct TriggerStep TriggerStep;
  6350. typedef struct Trigger Trigger;
  6351. typedef struct UnpackedRecord UnpackedRecord;
  6352. typedef struct Walker Walker;
  6353. typedef struct WherePlan WherePlan;
  6354. typedef struct WhereInfo WhereInfo;
  6355. typedef struct WhereLevel WhereLevel;
  6356. /*
  6357. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  6358. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  6359. ** pointer types (i.e. FuncDef) defined above.
  6360. */
  6361. /************** Include btree.h in the middle of sqliteInt.h *****************/
  6362. /************** Begin file btree.h *******************************************/
  6363. /*
  6364. ** 2001 September 15
  6365. **
  6366. ** The author disclaims copyright to this source code. In place of
  6367. ** a legal notice, here is a blessing:
  6368. **
  6369. ** May you do good and not evil.
  6370. ** May you find forgiveness for yourself and forgive others.
  6371. ** May you share freely, never taking more than you give.
  6372. **
  6373. *************************************************************************
  6374. ** This header file defines the interface that the sqlite B-Tree file
  6375. ** subsystem. See comments in the source code for a detailed description
  6376. ** of what each interface routine does.
  6377. **
  6378. ** @(#) $Id: btree.h,v 1.113 2009/04/10 12:55:17 danielk1977 Exp $
  6379. */
  6380. #ifndef _BTREE_H_
  6381. #define _BTREE_H_
  6382. /* TODO: This definition is just included so other modules compile. It
  6383. ** needs to be revisited.
  6384. */
  6385. #define SQLITE_N_BTREE_META 10
  6386. /*
  6387. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  6388. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  6389. */
  6390. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  6391. #define SQLITE_DEFAULT_AUTOVACUUM 0
  6392. #endif
  6393. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  6394. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  6395. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  6396. /*
  6397. ** Forward declarations of structure
  6398. */
  6399. typedef struct Btree Btree;
  6400. typedef struct BtCursor BtCursor;
  6401. typedef struct BtShared BtShared;
  6402. typedef struct BtreeMutexArray BtreeMutexArray;
  6403. /*
  6404. ** This structure records all of the Btrees that need to hold
  6405. ** a mutex before we enter sqlite3VdbeExec(). The Btrees are
  6406. ** are placed in aBtree[] in order of aBtree[]->pBt. That way,
  6407. ** we can always lock and unlock them all quickly.
  6408. */
  6409. struct BtreeMutexArray {
  6410. int nMutex;
  6411. Btree *aBtree[SQLITE_MAX_ATTACHED+1];
  6412. };
  6413. SQLITE_PRIVATE int sqlite3BtreeOpen(
  6414. const char *zFilename, /* Name of database file to open */
  6415. sqlite3 *db, /* Associated database connection */
  6416. Btree **, /* Return open Btree* here */
  6417. int flags, /* Flags */
  6418. int vfsFlags /* Flags passed through to VFS open */
  6419. );
  6420. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  6421. ** following values.
  6422. **
  6423. ** NOTE: These values must match the corresponding PAGER_ values in
  6424. ** pager.h.
  6425. */
  6426. #define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
  6427. #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
  6428. #define BTREE_MEMORY 4 /* In-memory DB. No argument */
  6429. #define BTREE_READONLY 8 /* Open the database in read-only mode */
  6430. #define BTREE_READWRITE 16 /* Open for both reading and writing */
  6431. #define BTREE_CREATE 32 /* Create the database if it does not exist */
  6432. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  6433. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  6434. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
  6435. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  6436. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int,int);
  6437. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  6438. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  6439. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  6440. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  6441. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  6442. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  6443. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  6444. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
  6445. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  6446. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
  6447. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  6448. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  6449. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  6450. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  6451. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  6452. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  6453. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
  6454. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
  6455. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  6456. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  6457. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  6458. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  6459. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  6460. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  6461. ** of the following flags:
  6462. */
  6463. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  6464. #define BTREE_ZERODATA 2 /* Table has keys only - no data */
  6465. #define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
  6466. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  6467. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  6468. SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
  6469. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  6470. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  6471. SQLITE_PRIVATE int sqlite3BtreeCursor(
  6472. Btree*, /* BTree containing table to open */
  6473. int iTable, /* Index of root page */
  6474. int wrFlag, /* 1 for writing. 0 for read-only */
  6475. struct KeyInfo*, /* First argument to compare function */
  6476. BtCursor *pCursor /* Space to write cursor structure */
  6477. );
  6478. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  6479. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  6480. SQLITE_PRIVATE int sqlite3BtreeMoveto(
  6481. BtCursor*,
  6482. const void *pKey,
  6483. i64 nKey,
  6484. int bias,
  6485. int *pRes
  6486. );
  6487. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  6488. BtCursor*,
  6489. UnpackedRecord *pUnKey,
  6490. i64 intKey,
  6491. int bias,
  6492. int *pRes
  6493. );
  6494. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  6495. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  6496. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  6497. const void *pData, int nData,
  6498. int nZero, int bias);
  6499. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  6500. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  6501. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  6502. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  6503. SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
  6504. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  6505. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  6506. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  6507. SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
  6508. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  6509. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  6510. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  6511. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  6512. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  6513. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  6514. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  6515. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  6516. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  6517. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  6518. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  6519. #ifndef SQLITE_OMIT_BTREECOUNT
  6520. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  6521. #endif
  6522. #ifdef SQLITE_TEST
  6523. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  6524. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  6525. #endif
  6526. /*
  6527. ** If we are not using shared cache, then there is no need to
  6528. ** use mutexes to access the BtShared structures. So make the
  6529. ** Enter and Leave procedures no-ops.
  6530. */
  6531. #ifndef SQLITE_OMIT_SHARED_CACHE
  6532. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  6533. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  6534. #else
  6535. # define sqlite3BtreeEnter(X)
  6536. # define sqlite3BtreeEnterAll(X)
  6537. #endif
  6538. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  6539. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  6540. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  6541. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  6542. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  6543. SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
  6544. SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
  6545. SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
  6546. #ifndef NDEBUG
  6547. /* These routines are used inside assert() statements only. */
  6548. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  6549. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  6550. #endif
  6551. #else
  6552. # define sqlite3BtreeLeave(X)
  6553. # define sqlite3BtreeEnterCursor(X)
  6554. # define sqlite3BtreeLeaveCursor(X)
  6555. # define sqlite3BtreeLeaveAll(X)
  6556. # define sqlite3BtreeMutexArrayEnter(X)
  6557. # define sqlite3BtreeMutexArrayLeave(X)
  6558. # define sqlite3BtreeMutexArrayInsert(X,Y)
  6559. # define sqlite3BtreeHoldsMutex(X) 1
  6560. # define sqlite3BtreeHoldsAllMutexes(X) 1
  6561. #endif
  6562. #endif /* _BTREE_H_ */
  6563. /************** End of btree.h ***********************************************/
  6564. /************** Continuing where we left off in sqliteInt.h ******************/
  6565. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  6566. /************** Begin file vdbe.h ********************************************/
  6567. /*
  6568. ** 2001 September 15
  6569. **
  6570. ** The author disclaims copyright to this source code. In place of
  6571. ** a legal notice, here is a blessing:
  6572. **
  6573. ** May you do good and not evil.
  6574. ** May you find forgiveness for yourself and forgive others.
  6575. ** May you share freely, never taking more than you give.
  6576. **
  6577. *************************************************************************
  6578. ** Header file for the Virtual DataBase Engine (VDBE)
  6579. **
  6580. ** This header defines the interface to the virtual database engine
  6581. ** or VDBE. The VDBE implements an abstract machine that runs a
  6582. ** simple program to access and modify the underlying database.
  6583. **
  6584. ** $Id: vdbe.h,v 1.141 2009/04/10 00:56:29 drh Exp $
  6585. */
  6586. #ifndef _SQLITE_VDBE_H_
  6587. #define _SQLITE_VDBE_H_
  6588. /*
  6589. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  6590. ** in the source file sqliteVdbe.c are allowed to see the insides
  6591. ** of this structure.
  6592. */
  6593. typedef struct Vdbe Vdbe;
  6594. /*
  6595. ** The names of the following types declared in vdbeInt.h are required
  6596. ** for the VdbeOp definition.
  6597. */
  6598. typedef struct VdbeFunc VdbeFunc;
  6599. typedef struct Mem Mem;
  6600. /*
  6601. ** A single instruction of the virtual machine has an opcode
  6602. ** and as many as three operands. The instruction is recorded
  6603. ** as an instance of the following structure:
  6604. */
  6605. struct VdbeOp {
  6606. u8 opcode; /* What operation to perform */
  6607. signed char p4type; /* One of the P4_xxx constants for p4 */
  6608. u8 opflags; /* Not currently used */
  6609. u8 p5; /* Fifth parameter is an unsigned character */
  6610. int p1; /* First operand */
  6611. int p2; /* Second parameter (often the jump destination) */
  6612. int p3; /* The third parameter */
  6613. union { /* forth parameter */
  6614. int i; /* Integer value if p4type==P4_INT32 */
  6615. void *p; /* Generic pointer */
  6616. char *z; /* Pointer to data for string (char array) types */
  6617. i64 *pI64; /* Used when p4type is P4_INT64 */
  6618. double *pReal; /* Used when p4type is P4_REAL */
  6619. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  6620. VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
  6621. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  6622. Mem *pMem; /* Used when p4type is P4_MEM */
  6623. sqlite3_vtab *pVtab; /* Used when p4type is P4_VTAB */
  6624. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  6625. int *ai; /* Used when p4type is P4_INTARRAY */
  6626. } p4;
  6627. #ifdef SQLITE_DEBUG
  6628. char *zComment; /* Comment to improve readability */
  6629. #endif
  6630. #ifdef VDBE_PROFILE
  6631. int cnt; /* Number of times this instruction was executed */
  6632. u64 cycles; /* Total time spent executing this instruction */
  6633. #endif
  6634. };
  6635. typedef struct VdbeOp VdbeOp;
  6636. /*
  6637. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  6638. ** it takes up less space.
  6639. */
  6640. struct VdbeOpList {
  6641. u8 opcode; /* What operation to perform */
  6642. signed char p1; /* First operand */
  6643. signed char p2; /* Second parameter (often the jump destination) */
  6644. signed char p3; /* Third parameter */
  6645. };
  6646. typedef struct VdbeOpList VdbeOpList;
  6647. /*
  6648. ** Allowed values of VdbeOp.p3type
  6649. */
  6650. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  6651. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  6652. #define P4_STATIC (-2) /* Pointer to a static string */
  6653. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  6654. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  6655. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  6656. #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
  6657. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  6658. #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
  6659. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  6660. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  6661. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  6662. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  6663. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  6664. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  6665. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  6666. ** is made. That copy is freed when the Vdbe is finalized. But if the
  6667. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  6668. ** gets freed when the Vdbe is finalized so it still should be obtained
  6669. ** from a single sqliteMalloc(). But no copy is made and the calling
  6670. ** function should *not* try to free the KeyInfo.
  6671. */
  6672. #define P4_KEYINFO_HANDOFF (-16)
  6673. #define P4_KEYINFO_STATIC (-17)
  6674. /*
  6675. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  6676. ** number of columns of data returned by the statement.
  6677. */
  6678. #define COLNAME_NAME 0
  6679. #define COLNAME_DECLTYPE 1
  6680. #define COLNAME_DATABASE 2
  6681. #define COLNAME_TABLE 3
  6682. #define COLNAME_COLUMN 4
  6683. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  6684. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  6685. #else
  6686. # ifdef SQLITE_OMIT_DECLTYPE
  6687. # define COLNAME_N 1 /* Store only the name */
  6688. # else
  6689. # define COLNAME_N 2 /* Store the name and decltype */
  6690. # endif
  6691. #endif
  6692. /*
  6693. ** The following macro converts a relative address in the p2 field
  6694. ** of a VdbeOp structure into a negative number so that
  6695. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  6696. ** the macro again restores the address.
  6697. */
  6698. #define ADDR(X) (-1-(X))
  6699. /*
  6700. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  6701. ** header file that defines a number for each opcode used by the VDBE.
  6702. */
  6703. /************** Include opcodes.h in the middle of vdbe.h ********************/
  6704. /************** Begin file opcodes.h *****************************************/
  6705. /* Automatically generated. Do not edit */
  6706. /* See the mkopcodeh.awk script for details */
  6707. #define OP_VNext 1
  6708. #define OP_Affinity 2
  6709. #define OP_Column 3
  6710. #define OP_SetCookie 4
  6711. #define OP_Seek 5
  6712. #define OP_Real 130 /* same as TK_FLOAT */
  6713. #define OP_Sequence 6
  6714. #define OP_Savepoint 7
  6715. #define OP_Ge 78 /* same as TK_GE */
  6716. #define OP_RowKey 8
  6717. #define OP_SCopy 9
  6718. #define OP_Eq 74 /* same as TK_EQ */
  6719. #define OP_OpenWrite 10
  6720. #define OP_NotNull 72 /* same as TK_NOTNULL */
  6721. #define OP_If 11
  6722. #define OP_ToInt 144 /* same as TK_TO_INT */
  6723. #define OP_String8 94 /* same as TK_STRING */
  6724. #define OP_VRowid 12
  6725. #define OP_CollSeq 13
  6726. #define OP_OpenRead 14
  6727. #define OP_Expire 15
  6728. #define OP_AutoCommit 16
  6729. #define OP_Gt 75 /* same as TK_GT */
  6730. #define OP_Pagecount 17
  6731. #define OP_IntegrityCk 18
  6732. #define OP_Sort 20
  6733. #define OP_Copy 21
  6734. #define OP_Trace 22
  6735. #define OP_Function 23
  6736. #define OP_IfNeg 24
  6737. #define OP_And 67 /* same as TK_AND */
  6738. #define OP_Subtract 85 /* same as TK_MINUS */
  6739. #define OP_Noop 25
  6740. #define OP_Return 26
  6741. #define OP_Remainder 88 /* same as TK_REM */
  6742. #define OP_NewRowid 27
  6743. #define OP_Multiply 86 /* same as TK_STAR */
  6744. #define OP_Variable 28
  6745. #define OP_String 29
  6746. #define OP_RealAffinity 30
  6747. #define OP_VRename 31
  6748. #define OP_ParseSchema 32
  6749. #define OP_VOpen 33
  6750. #define OP_Close 34
  6751. #define OP_CreateIndex 35
  6752. #define OP_IsUnique 36
  6753. #define OP_NotFound 37
  6754. #define OP_Int64 38
  6755. #define OP_MustBeInt 39
  6756. #define OP_Halt 40
  6757. #define OP_Rowid 41
  6758. #define OP_IdxLT 42
  6759. #define OP_AddImm 43
  6760. #define OP_Statement 44
  6761. #define OP_RowData 45
  6762. #define OP_MemMax 46
  6763. #define OP_Or 66 /* same as TK_OR */
  6764. #define OP_NotExists 47
  6765. #define OP_Gosub 48
  6766. #define OP_Divide 87 /* same as TK_SLASH */
  6767. #define OP_Integer 49
  6768. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  6769. #define OP_Prev 50
  6770. #define OP_RowSetRead 51
  6771. #define OP_Concat 89 /* same as TK_CONCAT */
  6772. #define OP_RowSetAdd 52
  6773. #define OP_BitAnd 80 /* same as TK_BITAND */
  6774. #define OP_VColumn 53
  6775. #define OP_CreateTable 54
  6776. #define OP_Last 55
  6777. #define OP_SeekLe 56
  6778. #define OP_IsNull 71 /* same as TK_ISNULL */
  6779. #define OP_IncrVacuum 57
  6780. #define OP_IdxRowid 58
  6781. #define OP_ShiftRight 83 /* same as TK_RSHIFT */
  6782. #define OP_ResetCount 59
  6783. #define OP_ContextPush 60
  6784. #define OP_Yield 61
  6785. #define OP_DropTrigger 62
  6786. #define OP_DropIndex 63
  6787. #define OP_IdxGE 64
  6788. #define OP_IdxDelete 65
  6789. #define OP_Vacuum 68
  6790. #define OP_IfNot 69
  6791. #define OP_DropTable 70
  6792. #define OP_SeekLt 79
  6793. #define OP_MakeRecord 90
  6794. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  6795. #define OP_ResultRow 91
  6796. #define OP_Delete 92
  6797. #define OP_AggFinal 95
  6798. #define OP_Compare 96
  6799. #define OP_ShiftLeft 82 /* same as TK_LSHIFT */
  6800. #define OP_Goto 97
  6801. #define OP_TableLock 98
  6802. #define OP_Clear 99
  6803. #define OP_Le 76 /* same as TK_LE */
  6804. #define OP_VerifyCookie 100
  6805. #define OP_AggStep 101
  6806. #define OP_ToText 141 /* same as TK_TO_TEXT */
  6807. #define OP_Not 19 /* same as TK_NOT */
  6808. #define OP_ToReal 145 /* same as TK_TO_REAL */
  6809. #define OP_SetNumColumns 102
  6810. #define OP_Transaction 103
  6811. #define OP_VFilter 104
  6812. #define OP_Ne 73 /* same as TK_NE */
  6813. #define OP_VDestroy 105
  6814. #define OP_ContextPop 106
  6815. #define OP_BitOr 81 /* same as TK_BITOR */
  6816. #define OP_Next 107
  6817. #define OP_Count 108
  6818. #define OP_IdxInsert 109
  6819. #define OP_Lt 77 /* same as TK_LT */
  6820. #define OP_SeekGe 110
  6821. #define OP_Insert 111
  6822. #define OP_Destroy 112
  6823. #define OP_ReadCookie 113
  6824. #define OP_LoadAnalysis 114
  6825. #define OP_Explain 115
  6826. #define OP_HaltIfNull 116
  6827. #define OP_OpenPseudo 117
  6828. #define OP_OpenEphemeral 118
  6829. #define OP_Null 119
  6830. #define OP_Move 120
  6831. #define OP_Blob 121
  6832. #define OP_Add 84 /* same as TK_PLUS */
  6833. #define OP_Rewind 122
  6834. #define OP_SeekGt 123
  6835. #define OP_VBegin 124
  6836. #define OP_VUpdate 125
  6837. #define OP_IfZero 126
  6838. #define OP_BitNot 93 /* same as TK_BITNOT */
  6839. #define OP_VCreate 127
  6840. #define OP_Found 128
  6841. #define OP_IfPos 129
  6842. #define OP_NullRow 131
  6843. #define OP_Jump 132
  6844. #define OP_Permutation 133
  6845. /* The following opcode values are never used */
  6846. #define OP_NotUsed_134 134
  6847. #define OP_NotUsed_135 135
  6848. #define OP_NotUsed_136 136
  6849. #define OP_NotUsed_137 137
  6850. #define OP_NotUsed_138 138
  6851. #define OP_NotUsed_139 139
  6852. #define OP_NotUsed_140 140
  6853. /* Properties such as "out2" or "jump" that are specified in
  6854. ** comments following the "case" for each opcode in the vdbe.c
  6855. ** are encoded into bitvectors as follows:
  6856. */
  6857. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  6858. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  6859. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  6860. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  6861. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  6862. #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
  6863. #define OPFLG_INITIALIZER {\
  6864. /* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
  6865. /* 8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
  6866. /* 16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
  6867. /* 24 */ 0x05, 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00,\
  6868. /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
  6869. /* 40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
  6870. /* 48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
  6871. /* 56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00,\
  6872. /* 64 */ 0x11, 0x00, 0x2c, 0x2c, 0x00, 0x05, 0x00, 0x05,\
  6873. /* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x11,\
  6874. /* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
  6875. /* 88 */ 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00,\
  6876. /* 96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  6877. /* 104 */ 0x01, 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00,\
  6878. /* 112 */ 0x02, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02,\
  6879. /* 120 */ 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05, 0x00,\
  6880. /* 128 */ 0x11, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00,\
  6881. /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
  6882. /* 144 */ 0x04, 0x04,}
  6883. /************** End of opcodes.h *********************************************/
  6884. /************** Continuing where we left off in vdbe.h ***********************/
  6885. /*
  6886. ** Prototypes for the VDBE interface. See comments on the implementation
  6887. ** for a description of what each of these routines does.
  6888. */
  6889. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  6890. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  6891. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  6892. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  6893. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  6894. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  6895. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  6896. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
  6897. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
  6898. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
  6899. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  6900. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  6901. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
  6902. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  6903. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  6904. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  6905. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  6906. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  6907. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
  6908. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  6909. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  6910. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  6911. #ifdef SQLITE_DEBUG
  6912. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  6913. #endif
  6914. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  6915. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  6916. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  6917. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  6918. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  6919. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  6920. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  6921. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  6922. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  6923. SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
  6924. #endif
  6925. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
  6926. SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
  6927. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  6928. #ifndef NDEBUG
  6929. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  6930. # define VdbeComment(X) sqlite3VdbeComment X
  6931. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  6932. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  6933. #else
  6934. # define VdbeComment(X)
  6935. # define VdbeNoopComment(X)
  6936. #endif
  6937. #endif
  6938. /************** End of vdbe.h ************************************************/
  6939. /************** Continuing where we left off in sqliteInt.h ******************/
  6940. /************** Include pager.h in the middle of sqliteInt.h *****************/
  6941. /************** Begin file pager.h *******************************************/
  6942. /*
  6943. ** 2001 September 15
  6944. **
  6945. ** The author disclaims copyright to this source code. In place of
  6946. ** a legal notice, here is a blessing:
  6947. **
  6948. ** May you do good and not evil.
  6949. ** May you find forgiveness for yourself and forgive others.
  6950. ** May you share freely, never taking more than you give.
  6951. **
  6952. *************************************************************************
  6953. ** This header file defines the interface that the sqlite page cache
  6954. ** subsystem. The page cache subsystem reads and writes a file a page
  6955. ** at a time and provides a journal for rollback.
  6956. **
  6957. ** @(#) $Id: pager.h,v 1.100 2009/02/03 16:51:25 danielk1977 Exp $
  6958. */
  6959. #ifndef _PAGER_H_
  6960. #define _PAGER_H_
  6961. /*
  6962. ** Default maximum size for persistent journal files. A negative
  6963. ** value means no limit. This value may be overridden using the
  6964. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  6965. */
  6966. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  6967. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  6968. #endif
  6969. /*
  6970. ** The type used to represent a page number. The first page in a file
  6971. ** is called page 1. 0 is used to represent "not a page".
  6972. */
  6973. typedef u32 Pgno;
  6974. /*
  6975. ** Each open file is managed by a separate instance of the "Pager" structure.
  6976. */
  6977. typedef struct Pager Pager;
  6978. /*
  6979. ** Handle type for pages.
  6980. */
  6981. typedef struct PgHdr DbPage;
  6982. /*
  6983. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  6984. ** reserved for working around a windows/posix incompatibility). It is
  6985. ** used in the journal to signify that the remainder of the journal file
  6986. ** is devoted to storing a master journal name - there are no more pages to
  6987. ** roll back. See comments for function writeMasterJournal() in pager.c
  6988. ** for details.
  6989. */
  6990. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  6991. /*
  6992. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  6993. **
  6994. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  6995. */
  6996. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  6997. #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
  6998. /*
  6999. ** Valid values for the second argument to sqlite3PagerLockingMode().
  7000. */
  7001. #define PAGER_LOCKINGMODE_QUERY -1
  7002. #define PAGER_LOCKINGMODE_NORMAL 0
  7003. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  7004. /*
  7005. ** Valid values for the second argument to sqlite3PagerJournalMode().
  7006. */
  7007. #define PAGER_JOURNALMODE_QUERY -1
  7008. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  7009. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  7010. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  7011. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  7012. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  7013. /*
  7014. ** The remainder of this file contains the declarations of the functions
  7015. ** that make up the Pager sub-system API. See source code comments for
  7016. ** a detailed description of each routine.
  7017. */
  7018. /* Open and close a Pager connection. */
  7019. SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
  7020. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  7021. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  7022. /* Functions used to configure a Pager object. */
  7023. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  7024. SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
  7025. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
  7026. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  7027. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  7028. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
  7029. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  7030. SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
  7031. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  7032. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  7033. /* Functions used to obtain and release page references. */
  7034. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  7035. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  7036. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  7037. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  7038. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  7039. /* Operations on page references. */
  7040. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  7041. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  7042. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  7043. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  7044. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  7045. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  7046. /* Functions used to manage pager transactions and savepoints. */
  7047. SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
  7048. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag);
  7049. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  7050. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  7051. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  7052. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  7053. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  7054. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  7055. /* Functions used to query pager state and configuration. */
  7056. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  7057. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  7058. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
  7059. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  7060. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  7061. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  7062. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  7063. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  7064. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  7065. /* Functions used to truncate the database file. */
  7066. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  7067. /* Used by encryption extensions. */
  7068. #ifdef SQLITE_HAS_CODEC
  7069. SQLITE_PRIVATE void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
  7070. #endif
  7071. /* Functions to support testing and debugging. */
  7072. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  7073. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  7074. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  7075. #endif
  7076. #ifdef SQLITE_TEST
  7077. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  7078. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  7079. void disable_simulated_io_errors(void);
  7080. void enable_simulated_io_errors(void);
  7081. #else
  7082. # define disable_simulated_io_errors()
  7083. # define enable_simulated_io_errors()
  7084. #endif
  7085. #endif /* _PAGER_H_ */
  7086. /************** End of pager.h ***********************************************/
  7087. /************** Continuing where we left off in sqliteInt.h ******************/
  7088. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  7089. /************** Begin file pcache.h ******************************************/
  7090. /*
  7091. ** 2008 August 05
  7092. **
  7093. ** The author disclaims copyright to this source code. In place of
  7094. ** a legal notice, here is a blessing:
  7095. **
  7096. ** May you do good and not evil.
  7097. ** May you find forgiveness for yourself and forgive others.
  7098. ** May you share freely, never taking more than you give.
  7099. **
  7100. *************************************************************************
  7101. ** This header file defines the interface that the sqlite page cache
  7102. ** subsystem.
  7103. **
  7104. ** @(#) $Id: pcache.h,v 1.19 2009/01/20 17:06:27 danielk1977 Exp $
  7105. */
  7106. #ifndef _PCACHE_H_
  7107. typedef struct PgHdr PgHdr;
  7108. typedef struct PCache PCache;
  7109. /*
  7110. ** Every page in the cache is controlled by an instance of the following
  7111. ** structure.
  7112. */
  7113. struct PgHdr {
  7114. void *pData; /* Content of this page */
  7115. void *pExtra; /* Extra content */
  7116. PgHdr *pDirty; /* Transient list of dirty pages */
  7117. Pgno pgno; /* Page number for this page */
  7118. Pager *pPager; /* The pager this page is part of */
  7119. #ifdef SQLITE_CHECK_PAGES
  7120. u32 pageHash; /* Hash of page content */
  7121. #endif
  7122. u16 flags; /* PGHDR flags defined below */
  7123. /**********************************************************************
  7124. ** Elements above are public. All that follows is private to pcache.c
  7125. ** and should not be accessed by other modules.
  7126. */
  7127. i16 nRef; /* Number of users of this page */
  7128. PCache *pCache; /* Cache that owns this page */
  7129. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  7130. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  7131. };
  7132. /* Bit values for PgHdr.flags */
  7133. #define PGHDR_DIRTY 0x002 /* Page has changed */
  7134. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  7135. ** writing this page to the database */
  7136. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  7137. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  7138. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  7139. /* Initialize and shutdown the page cache subsystem */
  7140. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  7141. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  7142. /* Page cache buffer management:
  7143. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  7144. */
  7145. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  7146. /* Create a new pager cache.
  7147. ** Under memory stress, invoke xStress to try to make pages clean.
  7148. ** Only clean and unpinned pages can be reclaimed.
  7149. */
  7150. SQLITE_PRIVATE void sqlite3PcacheOpen(
  7151. int szPage, /* Size of every page */
  7152. int szExtra, /* Extra space associated with each page */
  7153. int bPurgeable, /* True if pages are on backing store */
  7154. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  7155. void *pStress, /* Argument to xStress */
  7156. PCache *pToInit /* Preallocated space for the PCache */
  7157. );
  7158. /* Modify the page-size after the cache has been created. */
  7159. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  7160. /* Return the size in bytes of a PCache object. Used to preallocate
  7161. ** storage space.
  7162. */
  7163. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  7164. /* One release per successful fetch. Page is pinned until released.
  7165. ** Reference counted.
  7166. */
  7167. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  7168. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  7169. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  7170. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  7171. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  7172. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  7173. /* Change a page number. Used by incr-vacuum. */
  7174. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  7175. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  7176. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  7177. /* Get a list of all dirty pages in the cache, sorted by page number */
  7178. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  7179. /* Reset and close the cache object */
  7180. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  7181. /* Clear flags from pages of the page cache */
  7182. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  7183. /* Discard the contents of the cache */
  7184. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  7185. /* Return the total number of outstanding page references */
  7186. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  7187. /* Increment the reference count of an existing page */
  7188. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  7189. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  7190. /* Return the total number of pages stored in the cache */
  7191. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  7192. #ifdef SQLITE_CHECK_PAGES
  7193. /* Iterate through all dirty pages currently stored in the cache. This
  7194. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  7195. ** library is built.
  7196. */
  7197. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  7198. #endif
  7199. /* Set and get the suggested cache-size for the specified pager-cache.
  7200. **
  7201. ** If no global maximum is configured, then the system attempts to limit
  7202. ** the total number of pages cached by purgeable pager-caches to the sum
  7203. ** of the suggested cache-sizes.
  7204. */
  7205. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  7206. #ifdef SQLITE_TEST
  7207. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  7208. #endif
  7209. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  7210. /* Try to return memory used by the pcache module to the main memory heap */
  7211. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  7212. #endif
  7213. #ifdef SQLITE_TEST
  7214. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  7215. #endif
  7216. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  7217. #endif /* _PCACHE_H_ */
  7218. /************** End of pcache.h **********************************************/
  7219. /************** Continuing where we left off in sqliteInt.h ******************/
  7220. /************** Include os.h in the middle of sqliteInt.h ********************/
  7221. /************** Begin file os.h **********************************************/
  7222. /*
  7223. ** 2001 September 16
  7224. **
  7225. ** The author disclaims copyright to this source code. In place of
  7226. ** a legal notice, here is a blessing:
  7227. **
  7228. ** May you do good and not evil.
  7229. ** May you find forgiveness for yourself and forgive others.
  7230. ** May you share freely, never taking more than you give.
  7231. **
  7232. ******************************************************************************
  7233. **
  7234. ** This header file (together with is companion C source-code file
  7235. ** "os.c") attempt to abstract the underlying operating system so that
  7236. ** the SQLite library will work on both POSIX and windows systems.
  7237. **
  7238. ** This header file is #include-ed by sqliteInt.h and thus ends up
  7239. ** being included by every source file.
  7240. **
  7241. ** $Id: os.h,v 1.108 2009/02/05 16:31:46 drh Exp $
  7242. */
  7243. #ifndef _SQLITE_OS_H_
  7244. #define _SQLITE_OS_H_
  7245. /*
  7246. ** Figure out if we are dealing with Unix, Windows, or some other
  7247. ** operating system. After the following block of preprocess macros,
  7248. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
  7249. ** will defined to either 1 or 0. One of the four will be 1. The other
  7250. ** three will be 0.
  7251. */
  7252. #if defined(SQLITE_OS_OTHER)
  7253. # if SQLITE_OS_OTHER==1
  7254. # undef SQLITE_OS_UNIX
  7255. # define SQLITE_OS_UNIX 0
  7256. # undef SQLITE_OS_WIN
  7257. # define SQLITE_OS_WIN 0
  7258. # undef SQLITE_OS_OS2
  7259. # define SQLITE_OS_OS2 0
  7260. # else
  7261. # undef SQLITE_OS_OTHER
  7262. # endif
  7263. #endif
  7264. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  7265. # define SQLITE_OS_OTHER 0
  7266. # ifndef SQLITE_OS_WIN
  7267. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  7268. # define SQLITE_OS_WIN 1
  7269. # define SQLITE_OS_UNIX 0
  7270. # define SQLITE_OS_OS2 0
  7271. # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
  7272. # define SQLITE_OS_WIN 0
  7273. # define SQLITE_OS_UNIX 0
  7274. # define SQLITE_OS_OS2 1
  7275. # else
  7276. # define SQLITE_OS_WIN 0
  7277. # define SQLITE_OS_UNIX 1
  7278. # define SQLITE_OS_OS2 0
  7279. # endif
  7280. # else
  7281. # define SQLITE_OS_UNIX 0
  7282. # define SQLITE_OS_OS2 0
  7283. # endif
  7284. #else
  7285. # ifndef SQLITE_OS_WIN
  7286. # define SQLITE_OS_WIN 0
  7287. # endif
  7288. #endif
  7289. /*
  7290. ** Determine if we are dealing with WindowsCE - which has a much
  7291. ** reduced API.
  7292. */
  7293. #if defined(_WIN32_WCE)
  7294. # define SQLITE_OS_WINCE 1
  7295. #else
  7296. # define SQLITE_OS_WINCE 0
  7297. #endif
  7298. /*
  7299. ** Define the maximum size of a temporary filename
  7300. */
  7301. #if SQLITE_OS_WIN
  7302. # include <windows.h>
  7303. # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
  7304. #elif SQLITE_OS_OS2
  7305. # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
  7306. # include <os2safe.h> /* has to be included before os2.h for linking to work */
  7307. # endif
  7308. # define INCL_DOSDATETIME
  7309. # define INCL_DOSFILEMGR
  7310. # define INCL_DOSERRORS
  7311. # define INCL_DOSMISC
  7312. # define INCL_DOSPROCESS
  7313. # define INCL_DOSMODULEMGR
  7314. # define INCL_DOSSEMAPHORES
  7315. # include <os2.h>
  7316. # include <uconv.h>
  7317. # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
  7318. #else
  7319. # define SQLITE_TEMPNAME_SIZE 200
  7320. #endif
  7321. /* If the SET_FULLSYNC macro is not defined above, then make it
  7322. ** a no-op
  7323. */
  7324. #ifndef SET_FULLSYNC
  7325. # define SET_FULLSYNC(x,y)
  7326. #endif
  7327. /*
  7328. ** The default size of a disk sector
  7329. */
  7330. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  7331. # define SQLITE_DEFAULT_SECTOR_SIZE 512
  7332. #endif
  7333. /*
  7334. ** Temporary files are named starting with this prefix followed by 16 random
  7335. ** alphanumeric characters, and no file extension. They are stored in the
  7336. ** OS's standard temporary file directory, and are deleted prior to exit.
  7337. ** If sqlite is being embedded in another program, you may wish to change the
  7338. ** prefix to reflect your program's name, so that if your program exits
  7339. ** prematurely, old temporary files can be easily identified. This can be done
  7340. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  7341. **
  7342. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  7343. ** Mcafee started using SQLite in their anti-virus product and it
  7344. ** started putting files with the "sqlite" name in the c:/temp folder.
  7345. ** This annoyed many windows users. Those users would then do a
  7346. ** Google search for "sqlite", find the telephone numbers of the
  7347. ** developers and call to wake them up at night and complain.
  7348. ** For this reason, the default name prefix is changed to be "sqlite"
  7349. ** spelled backwards. So the temp files are still identified, but
  7350. ** anybody smart enough to figure out the code is also likely smart
  7351. ** enough to know that calling the developer will not help get rid
  7352. ** of the file.
  7353. */
  7354. #ifndef SQLITE_TEMP_FILE_PREFIX
  7355. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  7356. #endif
  7357. /*
  7358. ** The following values may be passed as the second argument to
  7359. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  7360. **
  7361. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  7362. ** RESERVED: A single process may hold a RESERVED lock on a file at
  7363. ** any time. Other processes may hold and obtain new SHARED locks.
  7364. ** PENDING: A single process may hold a PENDING lock on a file at
  7365. ** any one time. Existing SHARED locks may persist, but no new
  7366. ** SHARED locks may be obtained by other processes.
  7367. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  7368. **
  7369. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  7370. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  7371. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  7372. ** sqlite3OsLock().
  7373. */
  7374. #define NO_LOCK 0
  7375. #define SHARED_LOCK 1
  7376. #define RESERVED_LOCK 2
  7377. #define PENDING_LOCK 3
  7378. #define EXCLUSIVE_LOCK 4
  7379. /*
  7380. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  7381. **
  7382. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  7383. ** those functions are not available. So we use only LockFile() and
  7384. ** UnlockFile().
  7385. **
  7386. ** LockFile() prevents not just writing but also reading by other processes.
  7387. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  7388. ** byte out of a specific range of bytes. The lock byte is obtained at
  7389. ** random so two separate readers can probably access the file at the
  7390. ** same time, unless they are unlucky and choose the same lock byte.
  7391. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  7392. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  7393. ** a single byte of the file that is designated as the reserved lock byte.
  7394. ** A PENDING_LOCK is obtained by locking a designated byte different from
  7395. ** the RESERVED_LOCK byte.
  7396. **
  7397. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  7398. ** which means we can use reader/writer locks. When reader/writer locks
  7399. ** are used, the lock is placed on the same range of bytes that is used
  7400. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  7401. ** will support two or more Win95 readers or two or more WinNT readers.
  7402. ** But a single Win95 reader will lock out all WinNT readers and a single
  7403. ** WinNT reader will lock out all other Win95 readers.
  7404. **
  7405. ** The following #defines specify the range of bytes used for locking.
  7406. ** SHARED_SIZE is the number of bytes available in the pool from which
  7407. ** a random byte is selected for a shared lock. The pool of bytes for
  7408. ** shared locks begins at SHARED_FIRST.
  7409. **
  7410. ** The same locking strategy and
  7411. ** byte ranges are used for Unix. This leaves open the possiblity of having
  7412. ** clients on win95, winNT, and unix all talking to the same shared file
  7413. ** and all locking correctly. To do so would require that samba (or whatever
  7414. ** tool is being used for file sharing) implements locks correctly between
  7415. ** windows and unix. I'm guessing that isn't likely to happen, but by
  7416. ** using the same locking range we are at least open to the possibility.
  7417. **
  7418. ** Locking in windows is manditory. For this reason, we cannot store
  7419. ** actual data in the bytes used for locking. The pager never allocates
  7420. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  7421. ** that all locks will fit on a single page even at the minimum page size.
  7422. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  7423. ** is set high so that we don't have to allocate an unused page except
  7424. ** for very large databases. But one should test the page skipping logic
  7425. ** by setting PENDING_BYTE low and running the entire regression suite.
  7426. **
  7427. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  7428. ** file format. Depending on how it is changed, you might not notice
  7429. ** the incompatibility right away, even running a full regression test.
  7430. ** The default location of PENDING_BYTE is the first byte past the
  7431. ** 1GB boundary.
  7432. **
  7433. */
  7434. #define PENDING_BYTE sqlite3PendingByte
  7435. #define RESERVED_BYTE (PENDING_BYTE+1)
  7436. #define SHARED_FIRST (PENDING_BYTE+2)
  7437. #define SHARED_SIZE 510
  7438. /*
  7439. ** Functions for accessing sqlite3_file methods
  7440. */
  7441. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  7442. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  7443. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  7444. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  7445. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  7446. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  7447. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  7448. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  7449. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  7450. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  7451. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  7452. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  7453. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  7454. /*
  7455. ** Functions for accessing sqlite3_vfs methods
  7456. */
  7457. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  7458. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  7459. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  7460. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  7461. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  7462. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  7463. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  7464. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  7465. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  7466. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  7467. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  7468. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  7469. SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
  7470. /*
  7471. ** Convenience functions for opening and closing files using
  7472. ** sqlite3_malloc() to obtain space for the file-handle structure.
  7473. */
  7474. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  7475. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  7476. #endif /* _SQLITE_OS_H_ */
  7477. /************** End of os.h **************************************************/
  7478. /************** Continuing where we left off in sqliteInt.h ******************/
  7479. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  7480. /************** Begin file mutex.h *******************************************/
  7481. /*
  7482. ** 2007 August 28
  7483. **
  7484. ** The author disclaims copyright to this source code. In place of
  7485. ** a legal notice, here is a blessing:
  7486. **
  7487. ** May you do good and not evil.
  7488. ** May you find forgiveness for yourself and forgive others.
  7489. ** May you share freely, never taking more than you give.
  7490. **
  7491. *************************************************************************
  7492. **
  7493. ** This file contains the common header for all mutex implementations.
  7494. ** The sqliteInt.h header #includes this file so that it is available
  7495. ** to all source files. We break it out in an effort to keep the code
  7496. ** better organized.
  7497. **
  7498. ** NOTE: source files should *not* #include this header file directly.
  7499. ** Source files should #include the sqliteInt.h file and let that file
  7500. ** include this one indirectly.
  7501. **
  7502. ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $
  7503. */
  7504. /*
  7505. ** Figure out what version of the code to use. The choices are
  7506. **
  7507. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  7508. ** mutexes implemention cannot be overridden
  7509. ** at start-time.
  7510. **
  7511. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  7512. ** mutual exclusion is provided. But this
  7513. ** implementation can be overridden at
  7514. ** start-time.
  7515. **
  7516. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  7517. **
  7518. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  7519. **
  7520. ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
  7521. */
  7522. #if !SQLITE_THREADSAFE
  7523. # define SQLITE_MUTEX_OMIT
  7524. #endif
  7525. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  7526. # if SQLITE_OS_UNIX
  7527. # define SQLITE_MUTEX_PTHREADS
  7528. # elif SQLITE_OS_WIN
  7529. # define SQLITE_MUTEX_W32
  7530. # elif SQLITE_OS_OS2
  7531. # define SQLITE_MUTEX_OS2
  7532. # else
  7533. # define SQLITE_MUTEX_NOOP
  7534. # endif
  7535. #endif
  7536. #ifdef SQLITE_MUTEX_OMIT
  7537. /*
  7538. ** If this is a no-op implementation, implement everything as macros.
  7539. */
  7540. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  7541. #define sqlite3_mutex_free(X)
  7542. #define sqlite3_mutex_enter(X)
  7543. #define sqlite3_mutex_try(X) SQLITE_OK
  7544. #define sqlite3_mutex_leave(X)
  7545. #define sqlite3_mutex_held(X) 1
  7546. #define sqlite3_mutex_notheld(X) 1
  7547. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  7548. #define sqlite3MutexInit() SQLITE_OK
  7549. #define sqlite3MutexEnd()
  7550. #endif /* defined(SQLITE_OMIT_MUTEX) */
  7551. /************** End of mutex.h ***********************************************/
  7552. /************** Continuing where we left off in sqliteInt.h ******************/
  7553. /*
  7554. ** Each database file to be accessed by the system is an instance
  7555. ** of the following structure. There are normally two of these structures
  7556. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  7557. ** aDb[1] is the database file used to hold temporary tables. Additional
  7558. ** databases may be attached.
  7559. */
  7560. struct Db {
  7561. char *zName; /* Name of this database */
  7562. Btree *pBt; /* The B*Tree structure for this database file */
  7563. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  7564. u8 safety_level; /* How aggressive at syncing data to disk */
  7565. void *pAux; /* Auxiliary data. Usually NULL */
  7566. void (*xFreeAux)(void*); /* Routine to free pAux */
  7567. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  7568. };
  7569. /*
  7570. ** An instance of the following structure stores a database schema.
  7571. **
  7572. ** If there are no virtual tables configured in this schema, the
  7573. ** Schema.db variable is set to NULL. After the first virtual table
  7574. ** has been added, it is set to point to the database connection
  7575. ** used to create the connection. Once a virtual table has been
  7576. ** added to the Schema structure and the Schema.db variable populated,
  7577. ** only that database connection may use the Schema to prepare
  7578. ** statements.
  7579. */
  7580. struct Schema {
  7581. int schema_cookie; /* Database schema version number for this file */
  7582. Hash tblHash; /* All tables indexed by name */
  7583. Hash idxHash; /* All (named) indices indexed by name */
  7584. Hash trigHash; /* All triggers indexed by name */
  7585. Hash aFKey; /* Foreign keys indexed by to-table */
  7586. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  7587. u8 file_format; /* Schema format version for this file */
  7588. u8 enc; /* Text encoding used by this database */
  7589. u16 flags; /* Flags associated with this schema */
  7590. int cache_size; /* Number of pages to use in the cache */
  7591. #ifndef SQLITE_OMIT_VIRTUALTABLE
  7592. sqlite3 *db; /* "Owner" connection. See comment above */
  7593. #endif
  7594. };
  7595. /*
  7596. ** These macros can be used to test, set, or clear bits in the
  7597. ** Db.flags field.
  7598. */
  7599. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  7600. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  7601. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  7602. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  7603. /*
  7604. ** Allowed values for the DB.flags field.
  7605. **
  7606. ** The DB_SchemaLoaded flag is set after the database schema has been
  7607. ** read into internal hash tables.
  7608. **
  7609. ** DB_UnresetViews means that one or more views have column names that
  7610. ** have been filled out. If the schema changes, these column names might
  7611. ** changes and so the view will need to be reset.
  7612. */
  7613. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  7614. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  7615. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  7616. /*
  7617. ** The number of different kinds of things that can be limited
  7618. ** using the sqlite3_limit() interface.
  7619. */
  7620. #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
  7621. /*
  7622. ** Lookaside malloc is a set of fixed-size buffers that can be used
  7623. ** to satisfy small transient memory allocation requests for objects
  7624. ** associated with a particular database connection. The use of
  7625. ** lookaside malloc provides a significant performance enhancement
  7626. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  7627. ** SQL statements.
  7628. **
  7629. ** The Lookaside structure holds configuration information about the
  7630. ** lookaside malloc subsystem. Each available memory allocation in
  7631. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  7632. ** objects.
  7633. **
  7634. ** Lookaside allocations are only allowed for objects that are associated
  7635. ** with a particular database connection. Hence, schema information cannot
  7636. ** be stored in lookaside because in shared cache mode the schema information
  7637. ** is shared by multiple database connections. Therefore, while parsing
  7638. ** schema information, the Lookaside.bEnabled flag is cleared so that
  7639. ** lookaside allocations are not used to construct the schema objects.
  7640. */
  7641. struct Lookaside {
  7642. u16 sz; /* Size of each buffer in bytes */
  7643. u8 bEnabled; /* False to disable new lookaside allocations */
  7644. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  7645. int nOut; /* Number of buffers currently checked out */
  7646. int mxOut; /* Highwater mark for nOut */
  7647. LookasideSlot *pFree; /* List of available buffers */
  7648. void *pStart; /* First byte of available memory space */
  7649. void *pEnd; /* First byte past end of available space */
  7650. };
  7651. struct LookasideSlot {
  7652. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  7653. };
  7654. /*
  7655. ** A hash table for function definitions.
  7656. **
  7657. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  7658. ** Collisions are on the FuncDef.pHash chain.
  7659. */
  7660. struct FuncDefHash {
  7661. FuncDef *a[23]; /* Hash table for functions */
  7662. };
  7663. /*
  7664. ** Each database is an instance of the following structure.
  7665. **
  7666. ** The sqlite.lastRowid records the last insert rowid generated by an
  7667. ** insert statement. Inserts on views do not affect its value. Each
  7668. ** trigger has its own context, so that lastRowid can be updated inside
  7669. ** triggers as usual. The previous value will be restored once the trigger
  7670. ** exits. Upon entering a before or instead of trigger, lastRowid is no
  7671. ** longer (since after version 2.8.12) reset to -1.
  7672. **
  7673. ** The sqlite.nChange does not count changes within triggers and keeps no
  7674. ** context. It is reset at start of sqlite3_exec.
  7675. ** The sqlite.lsChange represents the number of changes made by the last
  7676. ** insert, update, or delete statement. It remains constant throughout the
  7677. ** length of a statement and is then updated by OP_SetCounts. It keeps a
  7678. ** context stack just like lastRowid so that the count of changes
  7679. ** within a trigger is not seen outside the trigger. Changes to views do not
  7680. ** affect the value of lsChange.
  7681. ** The sqlite.csChange keeps track of the number of current changes (since
  7682. ** the last statement) and is used to update sqlite_lsChange.
  7683. **
  7684. ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
  7685. ** store the most recent error code and, if applicable, string. The
  7686. ** internal function sqlite3Error() is used to set these variables
  7687. ** consistently.
  7688. */
  7689. struct sqlite3 {
  7690. sqlite3_vfs *pVfs; /* OS Interface */
  7691. int nDb; /* Number of backends currently in use */
  7692. Db *aDb; /* All backends */
  7693. int flags; /* Miscellaneous flags. See below */
  7694. int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  7695. int errCode; /* Most recent error code (SQLITE_*) */
  7696. int errMask; /* & result codes with this before returning */
  7697. u8 autoCommit; /* The auto-commit flag. */
  7698. u8 temp_store; /* 1: file 2: memory 0: default */
  7699. u8 mallocFailed; /* True if we have seen a malloc failure */
  7700. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  7701. u8 dfltJournalMode; /* Default journal mode for attached dbs */
  7702. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  7703. int nextPagesize; /* Pagesize after VACUUM if >0 */
  7704. int nTable; /* Number of tables in the database */
  7705. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  7706. i64 lastRowid; /* ROWID of most recent insert (see above) */
  7707. i64 priorNewRowid; /* Last randomly generated ROWID */
  7708. u32 magic; /* Magic number for detect library misuse */
  7709. int nChange; /* Value returned by sqlite3_changes() */
  7710. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  7711. sqlite3_mutex *mutex; /* Connection mutex */
  7712. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  7713. struct sqlite3InitInfo { /* Information used during initialization */
  7714. int iDb; /* When back is being initialized */
  7715. int newTnum; /* Rootpage of table being initialized */
  7716. u8 busy; /* TRUE if currently initializing */
  7717. } init;
  7718. int nExtension; /* Number of loaded extensions */
  7719. void **aExtension; /* Array of shared library handles */
  7720. struct Vdbe *pVdbe; /* List of active virtual machines */
  7721. int activeVdbeCnt; /* Number of VDBEs currently executing */
  7722. int writeVdbeCnt; /* Number of active VDBEs that are writing */
  7723. void (*xTrace)(void*,const char*); /* Trace function */
  7724. void *pTraceArg; /* Argument to the trace function */
  7725. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  7726. void *pProfileArg; /* Argument to profile function */
  7727. void *pCommitArg; /* Argument to xCommitCallback() */
  7728. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  7729. void *pRollbackArg; /* Argument to xRollbackCallback() */
  7730. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  7731. void *pUpdateArg;
  7732. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  7733. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  7734. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  7735. void *pCollNeededArg;
  7736. sqlite3_value *pErr; /* Most recent error message */
  7737. char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
  7738. char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
  7739. union {
  7740. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  7741. double notUsed1; /* Spacer */
  7742. } u1;
  7743. Lookaside lookaside; /* Lookaside malloc configuration */
  7744. #ifndef SQLITE_OMIT_AUTHORIZATION
  7745. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  7746. /* Access authorization function */
  7747. void *pAuthArg; /* 1st argument to the access auth function */
  7748. #endif
  7749. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  7750. int (*xProgress)(void *); /* The progress callback */
  7751. void *pProgressArg; /* Argument to the progress callback */
  7752. int nProgressOps; /* Number of opcodes for progress callback */
  7753. #endif
  7754. #ifndef SQLITE_OMIT_VIRTUALTABLE
  7755. Hash aModule; /* populated by sqlite3_create_module() */
  7756. Table *pVTab; /* vtab with active Connect/Create method */
  7757. sqlite3_vtab **aVTrans; /* Virtual tables with open transactions */
  7758. int nVTrans; /* Allocated size of aVTrans */
  7759. #endif
  7760. FuncDefHash aFunc; /* Hash table of connection functions */
  7761. Hash aCollSeq; /* All collating sequences */
  7762. BusyHandler busyHandler; /* Busy callback */
  7763. int busyTimeout; /* Busy handler timeout, in msec */
  7764. Db aDbStatic[2]; /* Static space for the 2 default backends */
  7765. #ifdef SQLITE_SSE
  7766. sqlite3_stmt *pFetch; /* Used by SSE to fetch stored statements */
  7767. #endif
  7768. Savepoint *pSavepoint; /* List of active savepoints */
  7769. int nSavepoint; /* Number of non-transaction savepoints */
  7770. int nStatement; /* Number of nested statement-transactions */
  7771. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  7772. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  7773. /* The following variables are all protected by the STATIC_MASTER
  7774. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  7775. **
  7776. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  7777. ** unlock so that it can proceed.
  7778. **
  7779. ** When X.pBlockingConnection==Y, that means that something that X tried
  7780. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  7781. ** held by Y.
  7782. */
  7783. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  7784. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  7785. void *pUnlockArg; /* Argument to xUnlockNotify */
  7786. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  7787. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  7788. #endif
  7789. };
  7790. /*
  7791. ** A macro to discover the encoding of a database.
  7792. */
  7793. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  7794. /*
  7795. ** Possible values for the sqlite.flags and or Db.flags fields.
  7796. **
  7797. ** On sqlite.flags, the SQLITE_InTrans value means that we have
  7798. ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
  7799. ** transaction is active on that particular database file.
  7800. */
  7801. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  7802. #define SQLITE_InTrans 0x00000008 /* True if in a transaction */
  7803. #define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
  7804. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  7805. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  7806. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  7807. /* DELETE, or UPDATE and return */
  7808. /* the count using a callback. */
  7809. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  7810. /* result set is empty */
  7811. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  7812. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  7813. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  7814. #define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when
  7815. ** accessing read-only databases */
  7816. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  7817. #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
  7818. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  7819. #define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */
  7820. #define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */
  7821. #define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */
  7822. #define SQLITE_SharedCache 0x00080000 /* Cache sharing is enabled */
  7823. #define SQLITE_CommitBusy 0x00200000 /* In the process of committing */
  7824. #define SQLITE_ReverseOrder 0x00400000 /* Reverse unordered SELECTs */
  7825. /*
  7826. ** Possible values for the sqlite.magic field.
  7827. ** The numbers are obtained at random and have no special meaning, other
  7828. ** than being distinct from one another.
  7829. */
  7830. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  7831. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  7832. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  7833. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  7834. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  7835. /*
  7836. ** Each SQL function is defined by an instance of the following
  7837. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  7838. ** hash table. When multiple functions have the same name, the hash table
  7839. ** points to a linked list of these structures.
  7840. */
  7841. struct FuncDef {
  7842. i16 nArg; /* Number of arguments. -1 means unlimited */
  7843. u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  7844. u8 flags; /* Some combination of SQLITE_FUNC_* */
  7845. void *pUserData; /* User data parameter */
  7846. FuncDef *pNext; /* Next function with same name */
  7847. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  7848. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  7849. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  7850. char *zName; /* SQL name of the function. */
  7851. FuncDef *pHash; /* Next with a different name but the same hash */
  7852. };
  7853. /*
  7854. ** Possible values for FuncDef.flags
  7855. */
  7856. #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
  7857. #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
  7858. #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
  7859. #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
  7860. #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
  7861. #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
  7862. /*
  7863. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  7864. ** used to create the initializers for the FuncDef structures.
  7865. **
  7866. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  7867. ** Used to create a scalar function definition of a function zName
  7868. ** implemented by C function xFunc that accepts nArg arguments. The
  7869. ** value passed as iArg is cast to a (void*) and made available
  7870. ** as the user-data (sqlite3_user_data()) for the function. If
  7871. ** argument bNC is true, then the FuncDef.needCollate flag is set.
  7872. **
  7873. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  7874. ** Used to create an aggregate function definition implemented by
  7875. ** the C functions xStep and xFinal. The first four parameters
  7876. ** are interpreted in the same way as the first 4 parameters to
  7877. ** FUNCTION().
  7878. **
  7879. ** LIKEFUNC(zName, nArg, pArg, flags)
  7880. ** Used to create a scalar function definition of a function zName
  7881. ** that accepts nArg arguments and is implemented by a call to C
  7882. ** function likeFunc. Argument pArg is cast to a (void *) and made
  7883. ** available as the function user-data (sqlite3_user_data()). The
  7884. ** FuncDef.flags variable is set to the value passed as the flags
  7885. ** parameter.
  7886. */
  7887. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  7888. {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
  7889. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  7890. {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName, 0}
  7891. #define LIKEFUNC(zName, nArg, arg, flags) \
  7892. {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
  7893. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  7894. {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
  7895. /*
  7896. ** All current savepoints are stored in a linked list starting at
  7897. ** sqlite3.pSavepoint. The first element in the list is the most recently
  7898. ** opened savepoint. Savepoints are added to the list by the vdbe
  7899. ** OP_Savepoint instruction.
  7900. */
  7901. struct Savepoint {
  7902. char *zName; /* Savepoint name (nul-terminated) */
  7903. Savepoint *pNext; /* Parent savepoint (if any) */
  7904. };
  7905. /*
  7906. ** The following are used as the second parameter to sqlite3Savepoint(),
  7907. ** and as the P1 argument to the OP_Savepoint instruction.
  7908. */
  7909. #define SAVEPOINT_BEGIN 0
  7910. #define SAVEPOINT_RELEASE 1
  7911. #define SAVEPOINT_ROLLBACK 2
  7912. /*
  7913. ** Each SQLite module (virtual table definition) is defined by an
  7914. ** instance of the following structure, stored in the sqlite3.aModule
  7915. ** hash table.
  7916. */
  7917. struct Module {
  7918. const sqlite3_module *pModule; /* Callback pointers */
  7919. const char *zName; /* Name passed to create_module() */
  7920. void *pAux; /* pAux passed to create_module() */
  7921. void (*xDestroy)(void *); /* Module destructor function */
  7922. };
  7923. /*
  7924. ** information about each column of an SQL table is held in an instance
  7925. ** of this structure.
  7926. */
  7927. struct Column {
  7928. char *zName; /* Name of this column */
  7929. Expr *pDflt; /* Default value of this column */
  7930. char *zType; /* Data type for this column */
  7931. char *zColl; /* Collating sequence. If NULL, use the default */
  7932. u8 notNull; /* True if there is a NOT NULL constraint */
  7933. u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
  7934. char affinity; /* One of the SQLITE_AFF_... values */
  7935. #ifndef SQLITE_OMIT_VIRTUALTABLE
  7936. u8 isHidden; /* True if this column is 'hidden' */
  7937. #endif
  7938. };
  7939. /*
  7940. ** A "Collating Sequence" is defined by an instance of the following
  7941. ** structure. Conceptually, a collating sequence consists of a name and
  7942. ** a comparison routine that defines the order of that sequence.
  7943. **
  7944. ** There may two separate implementations of the collation function, one
  7945. ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
  7946. ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
  7947. ** native byte order. When a collation sequence is invoked, SQLite selects
  7948. ** the version that will require the least expensive encoding
  7949. ** translations, if any.
  7950. **
  7951. ** The CollSeq.pUser member variable is an extra parameter that passed in
  7952. ** as the first argument to the UTF-8 comparison function, xCmp.
  7953. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
  7954. ** xCmp16.
  7955. **
  7956. ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
  7957. ** collating sequence is undefined. Indices built on an undefined
  7958. ** collating sequence may not be read or written.
  7959. */
  7960. struct CollSeq {
  7961. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  7962. u8 enc; /* Text encoding handled by xCmp() */
  7963. u8 type; /* One of the SQLITE_COLL_... values below */
  7964. void *pUser; /* First argument to xCmp() */
  7965. int (*xCmp)(void*,int, const void*, int, const void*);
  7966. void (*xDel)(void*); /* Destructor for pUser */
  7967. };
  7968. /*
  7969. ** Allowed values of CollSeq.type:
  7970. */
  7971. #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
  7972. #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
  7973. #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
  7974. #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
  7975. /*
  7976. ** A sort order can be either ASC or DESC.
  7977. */
  7978. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  7979. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  7980. /*
  7981. ** Column affinity types.
  7982. **
  7983. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  7984. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  7985. ** the speed a little by numbering the values consecutively.
  7986. **
  7987. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  7988. ** when multiple affinity types are concatenated into a string and
  7989. ** used as the P4 operand, they will be more readable.
  7990. **
  7991. ** Note also that the numeric types are grouped together so that testing
  7992. ** for a numeric type is a single comparison.
  7993. */
  7994. #define SQLITE_AFF_TEXT 'a'
  7995. #define SQLITE_AFF_NONE 'b'
  7996. #define SQLITE_AFF_NUMERIC 'c'
  7997. #define SQLITE_AFF_INTEGER 'd'
  7998. #define SQLITE_AFF_REAL 'e'
  7999. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  8000. /*
  8001. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  8002. ** affinity value.
  8003. */
  8004. #define SQLITE_AFF_MASK 0x67
  8005. /*
  8006. ** Additional bit values that can be ORed with an affinity without
  8007. ** changing the affinity.
  8008. */
  8009. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  8010. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  8011. /*
  8012. ** Each SQL table is represented in memory by an instance of the
  8013. ** following structure.
  8014. **
  8015. ** Table.zName is the name of the table. The case of the original
  8016. ** CREATE TABLE statement is stored, but case is not significant for
  8017. ** comparisons.
  8018. **
  8019. ** Table.nCol is the number of columns in this table. Table.aCol is a
  8020. ** pointer to an array of Column structures, one for each column.
  8021. **
  8022. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  8023. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  8024. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  8025. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  8026. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  8027. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  8028. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  8029. **
  8030. ** Table.tnum is the page number for the root BTree page of the table in the
  8031. ** database file. If Table.iDb is the index of the database table backend
  8032. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  8033. ** holds temporary tables and indices. If TF_Ephemeral is set
  8034. ** then the table is stored in a file that is automatically deleted
  8035. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  8036. ** refers VDBE cursor number that holds the table open, not to the root
  8037. ** page number. Transient tables are used to hold the results of a
  8038. ** sub-query that appears instead of a real table name in the FROM clause
  8039. ** of a SELECT statement.
  8040. */
  8041. struct Table {
  8042. sqlite3 *dbMem; /* DB connection used for lookaside allocations. */
  8043. char *zName; /* Name of the table or view */
  8044. int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  8045. int nCol; /* Number of columns in this table */
  8046. Column *aCol; /* Information about each column */
  8047. Index *pIndex; /* List of SQL indexes on this table. */
  8048. int tnum; /* Root BTree node for this table (see note above) */
  8049. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  8050. u16 nRef; /* Number of pointers to this Table */
  8051. u8 tabFlags; /* Mask of TF_* values */
  8052. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  8053. FKey *pFKey; /* Linked list of all foreign keys in this table */
  8054. char *zColAff; /* String defining the affinity of each column */
  8055. #ifndef SQLITE_OMIT_CHECK
  8056. Expr *pCheck; /* The AND of all CHECK constraints */
  8057. #endif
  8058. #ifndef SQLITE_OMIT_ALTERTABLE
  8059. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  8060. #endif
  8061. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8062. Module *pMod; /* Pointer to the implementation of the module */
  8063. sqlite3_vtab *pVtab; /* Pointer to the module instance */
  8064. int nModuleArg; /* Number of arguments to the module */
  8065. char **azModuleArg; /* Text of all module args. [0] is module name */
  8066. #endif
  8067. Trigger *pTrigger; /* List of triggers stored in pSchema */
  8068. Schema *pSchema; /* Schema that contains this table */
  8069. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  8070. };
  8071. /*
  8072. ** Allowed values for Tabe.tabFlags.
  8073. */
  8074. #define TF_Readonly 0x01 /* Read-only system table */
  8075. #define TF_Ephemeral 0x02 /* An ephemeral table */
  8076. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  8077. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  8078. #define TF_Virtual 0x10 /* Is a virtual table */
  8079. #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
  8080. /*
  8081. ** Test to see whether or not a table is a virtual table. This is
  8082. ** done as a macro so that it will be optimized out when virtual
  8083. ** table support is omitted from the build.
  8084. */
  8085. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8086. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  8087. # define IsHiddenColumn(X) ((X)->isHidden)
  8088. #else
  8089. # define IsVirtual(X) 0
  8090. # define IsHiddenColumn(X) 0
  8091. #endif
  8092. /*
  8093. ** Each foreign key constraint is an instance of the following structure.
  8094. **
  8095. ** A foreign key is associated with two tables. The "from" table is
  8096. ** the table that contains the REFERENCES clause that creates the foreign
  8097. ** key. The "to" table is the table that is named in the REFERENCES clause.
  8098. ** Consider this example:
  8099. **
  8100. ** CREATE TABLE ex1(
  8101. ** a INTEGER PRIMARY KEY,
  8102. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  8103. ** );
  8104. **
  8105. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  8106. **
  8107. ** Each REFERENCES clause generates an instance of the following structure
  8108. ** which is attached to the from-table. The to-table need not exist when
  8109. ** the from-table is created. The existence of the to-table is not checked
  8110. ** until an attempt is made to insert data into the from-table.
  8111. **
  8112. ** The sqlite.aFKey hash table stores pointers to this structure
  8113. ** given the name of a to-table. For each to-table, all foreign keys
  8114. ** associated with that table are on a linked list using the FKey.pNextTo
  8115. ** field.
  8116. */
  8117. struct FKey {
  8118. Table *pFrom; /* The table that contains the REFERENCES clause */
  8119. FKey *pNextFrom; /* Next foreign key in pFrom */
  8120. char *zTo; /* Name of table that the key points to */
  8121. FKey *pNextTo; /* Next foreign key that points to zTo */
  8122. int nCol; /* Number of columns in this key */
  8123. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  8124. int iFrom; /* Index of column in pFrom */
  8125. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  8126. } *aCol; /* One entry for each of nCol column s */
  8127. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  8128. u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
  8129. u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
  8130. u8 insertConf; /* How to resolve conflicts that occur on INSERT */
  8131. };
  8132. /*
  8133. ** SQLite supports many different ways to resolve a constraint
  8134. ** error. ROLLBACK processing means that a constraint violation
  8135. ** causes the operation in process to fail and for the current transaction
  8136. ** to be rolled back. ABORT processing means the operation in process
  8137. ** fails and any prior changes from that one operation are backed out,
  8138. ** but the transaction is not rolled back. FAIL processing means that
  8139. ** the operation in progress stops and returns an error code. But prior
  8140. ** changes due to the same operation are not backed out and no rollback
  8141. ** occurs. IGNORE means that the particular row that caused the constraint
  8142. ** error is not inserted or updated. Processing continues and no error
  8143. ** is returned. REPLACE means that preexisting database rows that caused
  8144. ** a UNIQUE constraint violation are removed so that the new insert or
  8145. ** update can proceed. Processing continues and no error is reported.
  8146. **
  8147. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  8148. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  8149. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  8150. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  8151. ** referenced table row is propagated into the row that holds the
  8152. ** foreign key.
  8153. **
  8154. ** The following symbolic values are used to record which type
  8155. ** of action to take.
  8156. */
  8157. #define OE_None 0 /* There is no constraint to check */
  8158. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  8159. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  8160. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  8161. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  8162. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  8163. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  8164. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  8165. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  8166. #define OE_Cascade 9 /* Cascade the changes */
  8167. #define OE_Default 99 /* Do whatever the default action is */
  8168. /*
  8169. ** An instance of the following structure is passed as the first
  8170. ** argument to sqlite3VdbeKeyCompare and is used to control the
  8171. ** comparison of the two index keys.
  8172. */
  8173. struct KeyInfo {
  8174. sqlite3 *db; /* The database connection */
  8175. u8 enc; /* Text encoding - one of the TEXT_Utf* values */
  8176. u16 nField; /* Number of entries in aColl[] */
  8177. u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */
  8178. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  8179. };
  8180. /*
  8181. ** An instance of the following structure holds information about a
  8182. ** single index record that has already been parsed out into individual
  8183. ** values.
  8184. **
  8185. ** A record is an object that contains one or more fields of data.
  8186. ** Records are used to store the content of a table row and to store
  8187. ** the key of an index. A blob encoding of a record is created by
  8188. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  8189. ** OP_Column opcode.
  8190. **
  8191. ** This structure holds a record that has already been disassembled
  8192. ** into its constituent fields.
  8193. */
  8194. struct UnpackedRecord {
  8195. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  8196. u16 nField; /* Number of entries in apMem[] */
  8197. u16 flags; /* Boolean settings. UNPACKED_... below */
  8198. Mem *aMem; /* Values */
  8199. };
  8200. /*
  8201. ** Allowed values of UnpackedRecord.flags
  8202. */
  8203. #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
  8204. #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
  8205. #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
  8206. #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
  8207. #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
  8208. /*
  8209. ** Each SQL index is represented in memory by an
  8210. ** instance of the following structure.
  8211. **
  8212. ** The columns of the table that are to be indexed are described
  8213. ** by the aiColumn[] field of this structure. For example, suppose
  8214. ** we have the following table and index:
  8215. **
  8216. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  8217. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  8218. **
  8219. ** In the Table structure describing Ex1, nCol==3 because there are
  8220. ** three columns in the table. In the Index structure describing
  8221. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  8222. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  8223. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  8224. ** The second column to be indexed (c1) has an index of 0 in
  8225. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  8226. **
  8227. ** The Index.onError field determines whether or not the indexed columns
  8228. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  8229. ** it means this is not a unique index. Otherwise it is a unique index
  8230. ** and the value of Index.onError indicate the which conflict resolution
  8231. ** algorithm to employ whenever an attempt is made to insert a non-unique
  8232. ** element.
  8233. */
  8234. struct Index {
  8235. char *zName; /* Name of this index */
  8236. int nColumn; /* Number of columns in the table used by this index */
  8237. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  8238. unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  8239. Table *pTable; /* The SQL table being indexed */
  8240. int tnum; /* Page containing root of this index in database file */
  8241. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  8242. u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  8243. char *zColAff; /* String defining the affinity of each column */
  8244. Index *pNext; /* The next index associated with the same table */
  8245. Schema *pSchema; /* Schema containing this index */
  8246. u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
  8247. char **azColl; /* Array of collation sequence names for index */
  8248. };
  8249. /*
  8250. ** Each token coming out of the lexer is an instance of
  8251. ** this structure. Tokens are also used as part of an expression.
  8252. **
  8253. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  8254. ** may contain random values. Do not make any assumptions about Token.dyn
  8255. ** and Token.n when Token.z==0.
  8256. */
  8257. struct Token {
  8258. const unsigned char *z; /* Text of the token. Not NULL-terminated! */
  8259. unsigned dyn : 1; /* True for malloced memory, false for static */
  8260. unsigned n : 31; /* Number of characters in this token */
  8261. };
  8262. /*
  8263. ** An instance of this structure contains information needed to generate
  8264. ** code for a SELECT that contains aggregate functions.
  8265. **
  8266. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  8267. ** pointer to this structure. The Expr.iColumn field is the index in
  8268. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  8269. ** code for that node.
  8270. **
  8271. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  8272. ** original Select structure that describes the SELECT statement. These
  8273. ** fields do not need to be freed when deallocating the AggInfo structure.
  8274. */
  8275. struct AggInfo {
  8276. u8 directMode; /* Direct rendering mode means take data directly
  8277. ** from source tables rather than from accumulators */
  8278. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  8279. ** than the source table */
  8280. int sortingIdx; /* Cursor number of the sorting index */
  8281. ExprList *pGroupBy; /* The group by clause */
  8282. int nSortingColumn; /* Number of columns in the sorting index */
  8283. struct AggInfo_col { /* For each column used in source tables */
  8284. Table *pTab; /* Source table */
  8285. int iTable; /* Cursor number of the source table */
  8286. int iColumn; /* Column number within the source table */
  8287. int iSorterColumn; /* Column number in the sorting index */
  8288. int iMem; /* Memory location that acts as accumulator */
  8289. Expr *pExpr; /* The original expression */
  8290. } *aCol;
  8291. int nColumn; /* Number of used entries in aCol[] */
  8292. int nColumnAlloc; /* Number of slots allocated for aCol[] */
  8293. int nAccumulator; /* Number of columns that show through to the output.
  8294. ** Additional columns are used only as parameters to
  8295. ** aggregate functions */
  8296. struct AggInfo_func { /* For each aggregate function */
  8297. Expr *pExpr; /* Expression encoding the function */
  8298. FuncDef *pFunc; /* The aggregate function implementation */
  8299. int iMem; /* Memory location that acts as accumulator */
  8300. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  8301. } *aFunc;
  8302. int nFunc; /* Number of entries in aFunc[] */
  8303. int nFuncAlloc; /* Number of slots allocated for aFunc[] */
  8304. };
  8305. /*
  8306. ** Each node of an expression in the parse tree is an instance
  8307. ** of this structure.
  8308. **
  8309. ** Expr.op is the opcode. The integer parser token codes are reused
  8310. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  8311. ** code representing the ">=" operator. This same integer code is reused
  8312. ** to represent the greater-than-or-equal-to operator in the expression
  8313. ** tree.
  8314. **
  8315. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  8316. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  8317. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  8318. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  8319. ** then Expr.token contains the name of the function.
  8320. **
  8321. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  8322. ** binary operator. Either or both may be NULL.
  8323. **
  8324. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  8325. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  8326. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  8327. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  8328. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  8329. ** valid.
  8330. **
  8331. ** An expression of the form ID or ID.ID refers to a column in a table.
  8332. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  8333. ** the integer cursor number of a VDBE cursor pointing to that table and
  8334. ** Expr.iColumn is the column number for the specific column. If the
  8335. ** expression is used as a result in an aggregate SELECT, then the
  8336. ** value is also stored in the Expr.iAgg column in the aggregate so that
  8337. ** it can be accessed after all aggregates are computed.
  8338. **
  8339. ** If the expression is an unbound variable marker (a question mark
  8340. ** character '?' in the original SQL) then the Expr.iTable holds the index
  8341. ** number for that variable.
  8342. **
  8343. ** If the expression is a subquery then Expr.iColumn holds an integer
  8344. ** register number containing the result of the subquery. If the
  8345. ** subquery gives a constant result, then iTable is -1. If the subquery
  8346. ** gives a different answer at different times during statement processing
  8347. ** then iTable is the address of a subroutine that computes the subquery.
  8348. **
  8349. ** If the Expr is of type OP_Column, and the table it is selecting from
  8350. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  8351. ** corresponding table definition.
  8352. **
  8353. ** ALLOCATION NOTES:
  8354. **
  8355. ** Expr objects can use a lot of memory space in database schema. To
  8356. ** help reduce memory requirements, sometimes an Expr object will be
  8357. ** truncated. And to reduce the number of memory allocations, sometimes
  8358. ** two or more Expr objects will be stored in a single memory allocation,
  8359. ** together with Expr.token and/or Expr.span strings.
  8360. **
  8361. ** If the EP_Reduced, EP_SpanToken, and EP_TokenOnly flags are set when
  8362. ** an Expr object is truncated. When EP_Reduced is set, then all
  8363. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  8364. ** are contained within the same memory allocation. Note, however, that
  8365. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  8366. ** allocated, regardless of whether or not EP_Reduced is set.
  8367. */
  8368. struct Expr {
  8369. u8 op; /* Operation performed by this node */
  8370. char affinity; /* The affinity of the column or 0 if not a column */
  8371. VVA_ONLY(u8 vvaFlags;) /* Flags used for VV&A only. EVVA_* below. */
  8372. u16 flags; /* Various flags. EP_* See below */
  8373. Token token; /* An operand token */
  8374. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  8375. ** space is allocated for the fields below this point. An attempt to
  8376. ** access them will result in a segfault or malfunction.
  8377. *********************************************************************/
  8378. Token span; /* Complete text of the expression */
  8379. /* If the EP_SpanToken flag is set in the Expr.flags mask, then no
  8380. ** space is allocated for the fields below this point. An attempt to
  8381. ** access them will result in a segfault or malfunction.
  8382. *********************************************************************/
  8383. Expr *pLeft; /* Left subnode */
  8384. Expr *pRight; /* Right subnode */
  8385. union {
  8386. ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
  8387. Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
  8388. } x;
  8389. CollSeq *pColl; /* The collation type of the column or 0 */
  8390. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  8391. ** space is allocated for the fields below this point. An attempt to
  8392. ** access them will result in a segfault or malfunction.
  8393. *********************************************************************/
  8394. int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
  8395. ** iColumn-th field of the iTable-th table. */
  8396. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  8397. int iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  8398. int iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  8399. Table *pTab; /* Table for TK_COLUMN expressions. */
  8400. #if SQLITE_MAX_EXPR_DEPTH>0
  8401. int nHeight; /* Height of the tree headed by this node */
  8402. #endif
  8403. };
  8404. /*
  8405. ** The following are the meanings of bits in the Expr.flags field.
  8406. */
  8407. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  8408. #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
  8409. #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
  8410. #define EP_Error 0x0008 /* Expression contains one or more errors */
  8411. #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
  8412. #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
  8413. #define EP_Dequoted 0x0040 /* True if the string has been dequoted */
  8414. #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
  8415. #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
  8416. #define EP_AnyAff 0x0200 /* Can take a cached column of any affinity */
  8417. #define EP_FixedDest 0x0400 /* Result needed in a specific register */
  8418. #define EP_IntValue 0x0800 /* Integer value contained in iTable */
  8419. #define EP_xIsSelect 0x1000 /* x.pSelect is valid (otherwise x.pList is) */
  8420. #define EP_Reduced 0x2000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
  8421. #define EP_TokenOnly 0x4000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
  8422. #define EP_SpanToken 0x8000 /* Expr size is EXPR_SPANTOKENSIZE bytes */
  8423. /*
  8424. ** The following are the meanings of bits in the Expr.vvaFlags field.
  8425. ** This information is only used when SQLite is compiled with
  8426. ** SQLITE_DEBUG defined.
  8427. */
  8428. #ifndef NDEBUG
  8429. #define EVVA_ReadOnlyToken 0x01 /* Expr.token.z is read-only */
  8430. #endif
  8431. /*
  8432. ** These macros can be used to test, set, or clear bits in the
  8433. ** Expr.flags field.
  8434. */
  8435. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  8436. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  8437. #define ExprSetProperty(E,P) (E)->flags|=(P)
  8438. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  8439. /*
  8440. ** Macros to determine the number of bytes required by a normal Expr
  8441. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  8442. ** and an Expr struct with the EP_TokenOnly flag set.
  8443. */
  8444. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  8445. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  8446. #define EXPR_SPANTOKENSIZE offsetof(Expr,pLeft) /* Fewer features */
  8447. #define EXPR_TOKENONLYSIZE offsetof(Expr,span) /* Smallest possible */
  8448. /*
  8449. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  8450. ** above sqlite3ExprDup() for details.
  8451. */
  8452. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  8453. #define EXPRDUP_SPAN 0x0002 /* Make a copy of Expr.span */
  8454. /*
  8455. ** A list of expressions. Each expression may optionally have a
  8456. ** name. An expr/name combination can be used in several ways, such
  8457. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  8458. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  8459. ** also be used as the argument to a function, in which case the a.zName
  8460. ** field is not used.
  8461. */
  8462. struct ExprList {
  8463. int nExpr; /* Number of expressions on the list */
  8464. int nAlloc; /* Number of entries allocated below */
  8465. int iECursor; /* VDBE Cursor associated with this ExprList */
  8466. struct ExprList_item {
  8467. Expr *pExpr; /* The list of expressions */
  8468. char *zName; /* Token associated with this expression */
  8469. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  8470. u8 done; /* A flag to indicate when processing is finished */
  8471. u16 iCol; /* For ORDER BY, column number in result set */
  8472. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  8473. } *a; /* One entry for each expression */
  8474. };
  8475. /*
  8476. ** An instance of this structure can hold a simple list of identifiers,
  8477. ** such as the list "a,b,c" in the following statements:
  8478. **
  8479. ** INSERT INTO t(a,b,c) VALUES ...;
  8480. ** CREATE INDEX idx ON t(a,b,c);
  8481. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  8482. **
  8483. ** The IdList.a.idx field is used when the IdList represents the list of
  8484. ** column names after a table name in an INSERT statement. In the statement
  8485. **
  8486. ** INSERT INTO t(a,b,c) ...
  8487. **
  8488. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  8489. */
  8490. struct IdList {
  8491. struct IdList_item {
  8492. char *zName; /* Name of the identifier */
  8493. int idx; /* Index in some Table.aCol[] of a column named zName */
  8494. } *a;
  8495. int nId; /* Number of identifiers on the list */
  8496. int nAlloc; /* Number of entries allocated for a[] below */
  8497. };
  8498. /*
  8499. ** The bitmask datatype defined below is used for various optimizations.
  8500. **
  8501. ** Changing this from a 64-bit to a 32-bit type limits the number of
  8502. ** tables in a join to 32 instead of 64. But it also reduces the size
  8503. ** of the library by 738 bytes on ix86.
  8504. */
  8505. typedef u64 Bitmask;
  8506. /*
  8507. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  8508. */
  8509. #define BMS ((int)(sizeof(Bitmask)*8))
  8510. /*
  8511. ** The following structure describes the FROM clause of a SELECT statement.
  8512. ** Each table or subquery in the FROM clause is a separate element of
  8513. ** the SrcList.a[] array.
  8514. **
  8515. ** With the addition of multiple database support, the following structure
  8516. ** can also be used to describe a particular table such as the table that
  8517. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  8518. ** such a table must be a simple name: ID. But in SQLite, the table can
  8519. ** now be identified by a database name, a dot, then the table name: ID.ID.
  8520. **
  8521. ** The jointype starts out showing the join type between the current table
  8522. ** and the next table on the list. The parser builds the list this way.
  8523. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  8524. ** jointype expresses the join between the table and the previous table.
  8525. */
  8526. struct SrcList {
  8527. i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  8528. i16 nAlloc; /* Number of entries allocated in a[] below */
  8529. struct SrcList_item {
  8530. char *zDatabase; /* Name of database holding this table */
  8531. char *zName; /* Name of the table */
  8532. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  8533. Table *pTab; /* An SQL table corresponding to zName */
  8534. Select *pSelect; /* A SELECT statement used in place of a table name */
  8535. u8 isPopulated; /* Temporary table associated with SELECT is populated */
  8536. u8 jointype; /* Type of join between this able and the previous */
  8537. u8 notIndexed; /* True if there is a NOT INDEXED clause */
  8538. int iCursor; /* The VDBE cursor number used to access this table */
  8539. Expr *pOn; /* The ON clause of a join */
  8540. IdList *pUsing; /* The USING clause of a join */
  8541. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  8542. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  8543. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  8544. } a[1]; /* One entry for each identifier on the list */
  8545. };
  8546. /*
  8547. ** Permitted values of the SrcList.a.jointype field
  8548. */
  8549. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  8550. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  8551. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  8552. #define JT_LEFT 0x0008 /* Left outer join */
  8553. #define JT_RIGHT 0x0010 /* Right outer join */
  8554. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  8555. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  8556. /*
  8557. ** A WherePlan object holds information that describes a lookup
  8558. ** strategy.
  8559. **
  8560. ** This object is intended to be opaque outside of the where.c module.
  8561. ** It is included here only so that that compiler will know how big it
  8562. ** is. None of the fields in this object should be used outside of
  8563. ** the where.c module.
  8564. **
  8565. ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
  8566. ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
  8567. ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
  8568. ** case that more than one of these conditions is true.
  8569. */
  8570. struct WherePlan {
  8571. u32 wsFlags; /* WHERE_* flags that describe the strategy */
  8572. u32 nEq; /* Number of == constraints */
  8573. union {
  8574. Index *pIdx; /* Index when WHERE_INDEXED is true */
  8575. struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
  8576. sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
  8577. } u;
  8578. };
  8579. /*
  8580. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  8581. ** structure contains a single instance of this structure. This structure
  8582. ** is intended to be private the the where.c module and should not be
  8583. ** access or modified by other modules.
  8584. **
  8585. ** The pIdxInfo field is used to help pick the best index on a
  8586. ** virtual table. The pIdxInfo pointer contains indexing
  8587. ** information for the i-th table in the FROM clause before reordering.
  8588. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  8589. ** All other information in the i-th WhereLevel object for the i-th table
  8590. ** after FROM clause ordering.
  8591. */
  8592. struct WhereLevel {
  8593. WherePlan plan; /* query plan for this element of the FROM clause */
  8594. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  8595. int iTabCur; /* The VDBE cursor used to access the table */
  8596. int iIdxCur; /* The VDBE cursor used to access pIdx */
  8597. int addrBrk; /* Jump here to break out of the loop */
  8598. int addrNxt; /* Jump here to start the next IN combination */
  8599. int addrCont; /* Jump here to continue with the next loop cycle */
  8600. int addrFirst; /* First instruction of interior of the loop */
  8601. u8 iFrom; /* Which entry in the FROM clause */
  8602. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  8603. int p1, p2; /* Operands of the opcode used to ends the loop */
  8604. union { /* Information that depends on plan.wsFlags */
  8605. struct {
  8606. int nIn; /* Number of entries in aInLoop[] */
  8607. struct InLoop {
  8608. int iCur; /* The VDBE cursor used by this IN operator */
  8609. int addrInTop; /* Top of the IN loop */
  8610. } *aInLoop; /* Information about each nested IN operator */
  8611. } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
  8612. } u;
  8613. /* The following field is really not part of the current level. But
  8614. ** we need a place to cache virtual table index information for each
  8615. ** virtual table in the FROM clause and the WhereLevel structure is
  8616. ** a convenient place since there is one WhereLevel for each FROM clause
  8617. ** element.
  8618. */
  8619. sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
  8620. };
  8621. /*
  8622. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin().
  8623. */
  8624. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  8625. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  8626. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  8627. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  8628. #define WHERE_FILL_ROWSET 0x0008 /* Save results in a RowSet object */
  8629. #define WHERE_OMIT_OPEN 0x0010 /* Table cursor are already open */
  8630. #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
  8631. /*
  8632. ** The WHERE clause processing routine has two halves. The
  8633. ** first part does the start of the WHERE loop and the second
  8634. ** half does the tail of the WHERE loop. An instance of
  8635. ** this structure is returned by the first half and passed
  8636. ** into the second half to give some continuity.
  8637. */
  8638. struct WhereInfo {
  8639. Parse *pParse; /* Parsing and code generating context */
  8640. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  8641. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
  8642. int regRowSet; /* Store rowids in this rowset if >=0 */
  8643. SrcList *pTabList; /* List of tables in the join */
  8644. int iTop; /* The very beginning of the WHERE loop */
  8645. int iContinue; /* Jump here to continue with next record */
  8646. int iBreak; /* Jump here to break out of the loop */
  8647. int nLevel; /* Number of nested loop */
  8648. struct WhereClause *pWC; /* Decomposition of the WHERE clause */
  8649. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  8650. };
  8651. /*
  8652. ** A NameContext defines a context in which to resolve table and column
  8653. ** names. The context consists of a list of tables (the pSrcList) field and
  8654. ** a list of named expression (pEList). The named expression list may
  8655. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  8656. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  8657. ** pEList corresponds to the result set of a SELECT and is NULL for
  8658. ** other statements.
  8659. **
  8660. ** NameContexts can be nested. When resolving names, the inner-most
  8661. ** context is searched first. If no match is found, the next outer
  8662. ** context is checked. If there is still no match, the next context
  8663. ** is checked. This process continues until either a match is found
  8664. ** or all contexts are check. When a match is found, the nRef member of
  8665. ** the context containing the match is incremented.
  8666. **
  8667. ** Each subquery gets a new NameContext. The pNext field points to the
  8668. ** NameContext in the parent query. Thus the process of scanning the
  8669. ** NameContext list corresponds to searching through successively outer
  8670. ** subqueries looking for a match.
  8671. */
  8672. struct NameContext {
  8673. Parse *pParse; /* The parser */
  8674. SrcList *pSrcList; /* One or more tables used to resolve names */
  8675. ExprList *pEList; /* Optional list of named expressions */
  8676. int nRef; /* Number of names resolved by this context */
  8677. int nErr; /* Number of errors encountered while resolving names */
  8678. u8 allowAgg; /* Aggregate functions allowed here */
  8679. u8 hasAgg; /* True if aggregates are seen */
  8680. u8 isCheck; /* True if resolving names in a CHECK constraint */
  8681. int nDepth; /* Depth of subquery recursion. 1 for no recursion */
  8682. AggInfo *pAggInfo; /* Information about aggregates at this level */
  8683. NameContext *pNext; /* Next outer name context. NULL for outermost */
  8684. };
  8685. /*
  8686. ** An instance of the following structure contains all information
  8687. ** needed to generate code for a single SELECT statement.
  8688. **
  8689. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  8690. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  8691. ** limit and nOffset to the value of the offset (or 0 if there is not
  8692. ** offset). But later on, nLimit and nOffset become the memory locations
  8693. ** in the VDBE that record the limit and offset counters.
  8694. **
  8695. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  8696. ** These addresses must be stored so that we can go back and fill in
  8697. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  8698. ** the number of columns in P2 can be computed at the same time
  8699. ** as the OP_OpenEphm instruction is coded because not
  8700. ** enough information about the compound query is known at that point.
  8701. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  8702. ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
  8703. ** sequences for the ORDER BY clause.
  8704. */
  8705. struct Select {
  8706. ExprList *pEList; /* The fields of the result */
  8707. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  8708. char affinity; /* MakeRecord with this affinity for SRT_Set */
  8709. u16 selFlags; /* Various SF_* values */
  8710. SrcList *pSrc; /* The FROM clause */
  8711. Expr *pWhere; /* The WHERE clause */
  8712. ExprList *pGroupBy; /* The GROUP BY clause */
  8713. Expr *pHaving; /* The HAVING clause */
  8714. ExprList *pOrderBy; /* The ORDER BY clause */
  8715. Select *pPrior; /* Prior select in a compound select statement */
  8716. Select *pNext; /* Next select to the left in a compound */
  8717. Select *pRightmost; /* Right-most select in a compound select statement */
  8718. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  8719. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  8720. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  8721. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  8722. };
  8723. /*
  8724. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  8725. ** "Select Flag".
  8726. */
  8727. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  8728. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  8729. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  8730. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  8731. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  8732. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  8733. /*
  8734. ** The results of a select can be distributed in several ways. The
  8735. ** "SRT" prefix means "SELECT Result Type".
  8736. */
  8737. #define SRT_Union 1 /* Store result as keys in an index */
  8738. #define SRT_Except 2 /* Remove result from a UNION index */
  8739. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  8740. #define SRT_Discard 4 /* Do not save the results anywhere */
  8741. /* The ORDER BY clause is ignored for all of the above */
  8742. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  8743. #define SRT_Output 5 /* Output each row of result */
  8744. #define SRT_Mem 6 /* Store result in a memory cell */
  8745. #define SRT_Set 7 /* Store results as keys in an index */
  8746. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  8747. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  8748. #define SRT_Coroutine 10 /* Generate a single row of result */
  8749. /*
  8750. ** A structure used to customize the behavior of sqlite3Select(). See
  8751. ** comments above sqlite3Select() for details.
  8752. */
  8753. typedef struct SelectDest SelectDest;
  8754. struct SelectDest {
  8755. u8 eDest; /* How to dispose of the results */
  8756. u8 affinity; /* Affinity used when eDest==SRT_Set */
  8757. int iParm; /* A parameter used by the eDest disposal method */
  8758. int iMem; /* Base register where results are written */
  8759. int nMem; /* Number of registers allocated */
  8760. };
  8761. /*
  8762. ** An SQL parser context. A copy of this structure is passed through
  8763. ** the parser and down into all the parser action routine in order to
  8764. ** carry around information that is global to the entire parse.
  8765. **
  8766. ** The structure is divided into two parts. When the parser and code
  8767. ** generate call themselves recursively, the first part of the structure
  8768. ** is constant but the second part is reset at the beginning and end of
  8769. ** each recursion.
  8770. **
  8771. ** The nTableLock and aTableLock variables are only used if the shared-cache
  8772. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  8773. ** used to store the set of table-locks required by the statement being
  8774. ** compiled. Function sqlite3TableLock() is used to add entries to the
  8775. ** list.
  8776. */
  8777. struct Parse {
  8778. sqlite3 *db; /* The main database structure */
  8779. int rc; /* Return code from execution */
  8780. char *zErrMsg; /* An error message */
  8781. Vdbe *pVdbe; /* An engine for executing database bytecode */
  8782. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  8783. u8 nameClash; /* A permanent table name clashes with temp table name */
  8784. u8 checkSchema; /* Causes schema cookie check after an error */
  8785. u8 nested; /* Number of nested calls to the parser/code generator */
  8786. u8 parseError; /* True after a parsing error. Ticket #1794 */
  8787. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  8788. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  8789. int aTempReg[8]; /* Holding area for temporary registers */
  8790. int nRangeReg; /* Size of the temporary register block */
  8791. int iRangeReg; /* First register in temporary register block */
  8792. int nErr; /* Number of errors seen */
  8793. int nTab; /* Number of previously allocated VDBE cursors */
  8794. int nMem; /* Number of memory cells used so far */
  8795. int nSet; /* Number of sets used so far */
  8796. int ckBase; /* Base register of data during check constraints */
  8797. int disableColCache; /* True to disable adding to column cache */
  8798. int nColCache; /* Number of entries in the column cache */
  8799. int iColCache; /* Next entry of the cache to replace */
  8800. struct yColCache {
  8801. int iTable; /* Table cursor number */
  8802. int iColumn; /* Table column number */
  8803. char affChange; /* True if this register has had an affinity change */
  8804. int iReg; /* Register holding value of this column */
  8805. } aColCache[10]; /* One for each valid column cache entry */
  8806. u32 writeMask; /* Start a write transaction on these databases */
  8807. u32 cookieMask; /* Bitmask of schema verified databases */
  8808. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  8809. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  8810. #ifndef SQLITE_OMIT_SHARED_CACHE
  8811. int nTableLock; /* Number of locks in aTableLock */
  8812. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  8813. #endif
  8814. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  8815. int regRoot; /* Register holding root page number for new objects */
  8816. /* Above is constant between recursions. Below is reset before and after
  8817. ** each recursion */
  8818. int nVar; /* Number of '?' variables seen in the SQL so far */
  8819. int nVarExpr; /* Number of used slots in apVarExpr[] */
  8820. int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
  8821. Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
  8822. int nAlias; /* Number of aliased result set columns */
  8823. int nAliasAlloc; /* Number of allocated slots for aAlias[] */
  8824. int *aAlias; /* Register used to hold aliased result */
  8825. u8 explain; /* True if the EXPLAIN flag is found on the query */
  8826. Token sErrToken; /* The token at which the error occurred */
  8827. Token sNameToken; /* Token with unqualified schema object name */
  8828. Token sLastToken; /* The last token parsed */
  8829. const char *zSql; /* All SQL text */
  8830. const char *zTail; /* All SQL text past the last semicolon parsed */
  8831. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  8832. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  8833. TriggerStack *trigStack; /* Trigger actions being coded */
  8834. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  8835. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8836. Token sArg; /* Complete text of a module argument */
  8837. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  8838. int nVtabLock; /* Number of virtual tables to lock */
  8839. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  8840. #endif
  8841. int nHeight; /* Expression tree height of current sub-select */
  8842. Table *pZombieTab; /* List of Table objects to delete after code gen */
  8843. };
  8844. #ifdef SQLITE_OMIT_VIRTUALTABLE
  8845. #define IN_DECLARE_VTAB 0
  8846. #else
  8847. #define IN_DECLARE_VTAB (pParse->declareVtab)
  8848. #endif
  8849. /*
  8850. ** An instance of the following structure can be declared on a stack and used
  8851. ** to save the Parse.zAuthContext value so that it can be restored later.
  8852. */
  8853. struct AuthContext {
  8854. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  8855. Parse *pParse; /* The Parse structure */
  8856. };
  8857. /*
  8858. ** Bitfield flags for P2 value in OP_Insert and OP_Delete
  8859. */
  8860. #define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
  8861. #define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
  8862. #define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
  8863. #define OPFLAG_APPEND 8 /* This is likely to be an append */
  8864. /*
  8865. * Each trigger present in the database schema is stored as an instance of
  8866. * struct Trigger.
  8867. *
  8868. * Pointers to instances of struct Trigger are stored in two ways.
  8869. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  8870. * database). This allows Trigger structures to be retrieved by name.
  8871. * 2. All triggers associated with a single table form a linked list, using the
  8872. * pNext member of struct Trigger. A pointer to the first element of the
  8873. * linked list is stored as the "pTrigger" member of the associated
  8874. * struct Table.
  8875. *
  8876. * The "step_list" member points to the first element of a linked list
  8877. * containing the SQL statements specified as the trigger program.
  8878. */
  8879. struct Trigger {
  8880. char *name; /* The name of the trigger */
  8881. char *table; /* The table or view to which the trigger applies */
  8882. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  8883. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  8884. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  8885. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  8886. the <column-list> is stored here */
  8887. Token nameToken; /* Token containing zName. Use during parsing only */
  8888. Schema *pSchema; /* Schema containing the trigger */
  8889. Schema *pTabSchema; /* Schema containing the table */
  8890. TriggerStep *step_list; /* Link list of trigger program steps */
  8891. Trigger *pNext; /* Next trigger associated with the table */
  8892. };
  8893. /*
  8894. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  8895. ** determine which.
  8896. **
  8897. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  8898. ** In that cases, the constants below can be ORed together.
  8899. */
  8900. #define TRIGGER_BEFORE 1
  8901. #define TRIGGER_AFTER 2
  8902. /*
  8903. * An instance of struct TriggerStep is used to store a single SQL statement
  8904. * that is a part of a trigger-program.
  8905. *
  8906. * Instances of struct TriggerStep are stored in a singly linked list (linked
  8907. * using the "pNext" member) referenced by the "step_list" member of the
  8908. * associated struct Trigger instance. The first element of the linked list is
  8909. * the first step of the trigger-program.
  8910. *
  8911. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  8912. * "SELECT" statement. The meanings of the other members is determined by the
  8913. * value of "op" as follows:
  8914. *
  8915. * (op == TK_INSERT)
  8916. * orconf -> stores the ON CONFLICT algorithm
  8917. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  8918. * this stores a pointer to the SELECT statement. Otherwise NULL.
  8919. * target -> A token holding the name of the table to insert into.
  8920. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  8921. * this stores values to be inserted. Otherwise NULL.
  8922. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  8923. * statement, then this stores the column-names to be
  8924. * inserted into.
  8925. *
  8926. * (op == TK_DELETE)
  8927. * target -> A token holding the name of the table to delete from.
  8928. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  8929. * Otherwise NULL.
  8930. *
  8931. * (op == TK_UPDATE)
  8932. * target -> A token holding the name of the table to update rows of.
  8933. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  8934. * Otherwise NULL.
  8935. * pExprList -> A list of the columns to update and the expressions to update
  8936. * them to. See sqlite3Update() documentation of "pChanges"
  8937. * argument.
  8938. *
  8939. */
  8940. struct TriggerStep {
  8941. int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  8942. int orconf; /* OE_Rollback etc. */
  8943. Trigger *pTrig; /* The trigger that this step is a part of */
  8944. Select *pSelect; /* Valid for SELECT and sometimes
  8945. INSERT steps (when pExprList == 0) */
  8946. Token target; /* Valid for DELETE, UPDATE, INSERT steps */
  8947. Expr *pWhere; /* Valid for DELETE, UPDATE steps */
  8948. ExprList *pExprList; /* Valid for UPDATE statements and sometimes
  8949. INSERT steps (when pSelect == 0) */
  8950. IdList *pIdList; /* Valid for INSERT statements only */
  8951. TriggerStep *pNext; /* Next in the link-list */
  8952. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  8953. };
  8954. /*
  8955. * An instance of struct TriggerStack stores information required during code
  8956. * generation of a single trigger program. While the trigger program is being
  8957. * coded, its associated TriggerStack instance is pointed to by the
  8958. * "pTriggerStack" member of the Parse structure.
  8959. *
  8960. * The pTab member points to the table that triggers are being coded on. The
  8961. * newIdx member contains the index of the vdbe cursor that points at the temp
  8962. * table that stores the new.* references. If new.* references are not valid
  8963. * for the trigger being coded (for example an ON DELETE trigger), then newIdx
  8964. * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
  8965. *
  8966. * The ON CONFLICT policy to be used for the trigger program steps is stored
  8967. * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
  8968. * specified for individual triggers steps is used.
  8969. *
  8970. * struct TriggerStack has a "pNext" member, to allow linked lists to be
  8971. * constructed. When coding nested triggers (triggers fired by other triggers)
  8972. * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
  8973. * pointer. Once the nested trigger has been coded, the pNext value is restored
  8974. * to the pTriggerStack member of the Parse stucture and coding of the parent
  8975. * trigger continues.
  8976. *
  8977. * Before a nested trigger is coded, the linked list pointed to by the
  8978. * pTriggerStack is scanned to ensure that the trigger is not about to be coded
  8979. * recursively. If this condition is detected, the nested trigger is not coded.
  8980. */
  8981. struct TriggerStack {
  8982. Table *pTab; /* Table that triggers are currently being coded on */
  8983. int newIdx; /* Index of vdbe cursor to "new" temp table */
  8984. int oldIdx; /* Index of vdbe cursor to "old" temp table */
  8985. u32 newColMask;
  8986. u32 oldColMask;
  8987. int orconf; /* Current orconf policy */
  8988. int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
  8989. Trigger *pTrigger; /* The trigger currently being coded */
  8990. TriggerStack *pNext; /* Next trigger down on the trigger stack */
  8991. };
  8992. /*
  8993. ** The following structure contains information used by the sqliteFix...
  8994. ** routines as they walk the parse tree to make database references
  8995. ** explicit.
  8996. */
  8997. typedef struct DbFixer DbFixer;
  8998. struct DbFixer {
  8999. Parse *pParse; /* The parsing context. Error messages written here */
  9000. const char *zDb; /* Make sure all objects are contained in this database */
  9001. const char *zType; /* Type of the container - used for error messages */
  9002. const Token *pName; /* Name of the container - used for error messages */
  9003. };
  9004. /*
  9005. ** An objected used to accumulate the text of a string where we
  9006. ** do not necessarily know how big the string will be in the end.
  9007. */
  9008. struct StrAccum {
  9009. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  9010. char *zBase; /* A base allocation. Not from malloc. */
  9011. char *zText; /* The string collected so far */
  9012. int nChar; /* Length of the string so far */
  9013. int nAlloc; /* Amount of space allocated in zText */
  9014. int mxAlloc; /* Maximum allowed string length */
  9015. u8 mallocFailed; /* Becomes true if any memory allocation fails */
  9016. u8 useMalloc; /* True if zText is enlargeable using realloc */
  9017. u8 tooBig; /* Becomes true if string size exceeds limits */
  9018. };
  9019. /*
  9020. ** A pointer to this structure is used to communicate information
  9021. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  9022. */
  9023. typedef struct {
  9024. sqlite3 *db; /* The database being initialized */
  9025. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  9026. char **pzErrMsg; /* Error message stored here */
  9027. int rc; /* Result code stored here */
  9028. } InitData;
  9029. /*
  9030. ** Structure containing global configuration data for the SQLite library.
  9031. **
  9032. ** This structure also contains some state information.
  9033. */
  9034. struct SQLite3Config {
  9035. int bMemstat; /* True to enable memory status */
  9036. int bCoreMutex; /* True to enable core mutexing */
  9037. int bFullMutex; /* True to enable full mutexing */
  9038. int mxStrlen; /* Maximum string length */
  9039. int szLookaside; /* Default lookaside buffer size */
  9040. int nLookaside; /* Default lookaside buffer count */
  9041. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  9042. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  9043. sqlite3_pcache_methods pcache; /* Low-level page-cache interface */
  9044. void *pHeap; /* Heap storage space */
  9045. int nHeap; /* Size of pHeap[] */
  9046. int mnReq, mxReq; /* Min and max heap requests sizes */
  9047. void *pScratch; /* Scratch memory */
  9048. int szScratch; /* Size of each scratch buffer */
  9049. int nScratch; /* Number of scratch buffers */
  9050. void *pPage; /* Page cache memory */
  9051. int szPage; /* Size of each page in pPage[] */
  9052. int nPage; /* Number of pages in pPage[] */
  9053. int mxParserStack; /* maximum depth of the parser stack */
  9054. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  9055. /* The above might be initialized to non-zero. The following need to always
  9056. ** initially be zero, however. */
  9057. int isInit; /* True after initialization has finished */
  9058. int inProgress; /* True while initialization in progress */
  9059. int isMallocInit; /* True after malloc is initialized */
  9060. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  9061. int nRefInitMutex; /* Number of users of pInitMutex */
  9062. };
  9063. /*
  9064. ** Context pointer passed down through the tree-walk.
  9065. */
  9066. struct Walker {
  9067. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  9068. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  9069. Parse *pParse; /* Parser context. */
  9070. union { /* Extra data for callback */
  9071. NameContext *pNC; /* Naming context */
  9072. int i; /* Integer value */
  9073. } u;
  9074. };
  9075. /* Forward declarations */
  9076. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  9077. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  9078. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  9079. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  9080. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  9081. /*
  9082. ** Return code from the parse-tree walking primitives and their
  9083. ** callbacks.
  9084. */
  9085. #define WRC_Continue 0 /* Continue down into children */
  9086. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  9087. #define WRC_Abort 2 /* Abandon the tree walk */
  9088. /*
  9089. ** Assuming zIn points to the first byte of a UTF-8 character,
  9090. ** advance zIn to point to the first byte of the next UTF-8 character.
  9091. */
  9092. #define SQLITE_SKIP_UTF8(zIn) { \
  9093. if( (*(zIn++))>=0xc0 ){ \
  9094. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  9095. } \
  9096. }
  9097. /*
  9098. ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
  9099. ** builds) or a function call (for debugging). If it is a function call,
  9100. ** it allows the operator to set a breakpoint at the spot where database
  9101. ** corruption is first detected.
  9102. */
  9103. #ifdef SQLITE_DEBUG
  9104. SQLITE_PRIVATE int sqlite3Corrupt(void);
  9105. # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
  9106. #else
  9107. # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
  9108. #endif
  9109. /*
  9110. ** The following macros mimic the standard library functions toupper(),
  9111. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  9112. ** sqlite versions only work for ASCII characters, regardless of locale.
  9113. */
  9114. #ifdef SQLITE_ASCII
  9115. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  9116. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  9117. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  9118. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  9119. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  9120. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  9121. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  9122. #else
  9123. # include <ctype.h>
  9124. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  9125. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  9126. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  9127. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  9128. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  9129. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  9130. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  9131. #endif
  9132. /*
  9133. ** Internal function prototypes
  9134. */
  9135. SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
  9136. SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
  9137. SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
  9138. SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
  9139. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  9140. SQLITE_PRIVATE int sqlite3MallocInit(void);
  9141. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  9142. SQLITE_PRIVATE void *sqlite3Malloc(int);
  9143. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  9144. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  9145. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  9146. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  9147. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  9148. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  9149. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  9150. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  9151. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  9152. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  9153. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  9154. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  9155. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  9156. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  9157. SQLITE_PRIVATE void sqlite3PageFree(void*);
  9158. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  9159. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  9160. SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
  9161. #ifdef SQLITE_ENABLE_MEMSYS3
  9162. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  9163. #endif
  9164. #ifdef SQLITE_ENABLE_MEMSYS5
  9165. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  9166. #endif
  9167. #ifndef SQLITE_MUTEX_OMIT
  9168. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void);
  9169. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  9170. SQLITE_PRIVATE int sqlite3MutexInit(void);
  9171. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  9172. #endif
  9173. SQLITE_PRIVATE int sqlite3StatusValue(int);
  9174. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  9175. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  9176. SQLITE_PRIVATE int sqlite3IsNaN(double);
  9177. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  9178. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  9179. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  9180. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  9181. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  9182. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  9183. #endif
  9184. #if defined(SQLITE_TEST)
  9185. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  9186. #endif
  9187. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  9188. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  9189. SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
  9190. SQLITE_PRIVATE void sqlite3Dequote(char*);
  9191. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
  9192. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  9193. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  9194. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  9195. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  9196. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  9197. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  9198. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  9199. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
  9200. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  9201. SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
  9202. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  9203. SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
  9204. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  9205. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  9206. SQLITE_PRIVATE void sqlite3ExprClear(sqlite3*, Expr*);
  9207. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  9208. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
  9209. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  9210. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  9211. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  9212. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  9213. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
  9214. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  9215. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  9216. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  9217. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  9218. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  9219. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  9220. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  9221. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  9222. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  9223. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  9224. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
  9225. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  9226. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  9227. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  9228. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  9229. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  9230. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
  9231. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  9232. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  9233. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  9234. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  9235. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  9236. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  9237. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  9238. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  9239. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  9240. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  9241. #else
  9242. # define sqlite3ViewGetColumnNames(A,B) 0
  9243. #endif
  9244. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  9245. SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
  9246. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  9247. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
  9248. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  9249. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  9250. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  9251. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  9252. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  9253. Token*, Select*, Expr*, IdList*);
  9254. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  9255. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  9256. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  9257. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  9258. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  9259. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  9260. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  9261. Token*, int, int);
  9262. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  9263. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  9264. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  9265. Expr*,ExprList*,int,Expr*,Expr*);
  9266. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  9267. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  9268. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  9269. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  9270. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  9271. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
  9272. #endif
  9273. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  9274. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  9275. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8, int);
  9276. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  9277. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
  9278. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  9279. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
  9280. SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
  9281. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  9282. SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse*,int);
  9283. SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
  9284. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  9285. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  9286. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  9287. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  9288. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  9289. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  9290. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  9291. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  9292. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  9293. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  9294. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  9295. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  9296. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  9297. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  9298. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  9299. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  9300. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
  9301. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  9302. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  9303. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  9304. SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
  9305. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  9306. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  9307. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  9308. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
  9309. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  9310. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  9311. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  9312. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  9313. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  9314. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  9315. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  9316. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  9317. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  9318. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  9319. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  9320. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
  9321. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  9322. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  9323. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  9324. int*,int,int,int,int);
  9325. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  9326. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  9327. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  9328. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  9329. SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*,const Token*);
  9330. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  9331. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  9332. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  9333. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  9334. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  9335. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
  9336. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  9337. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  9338. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  9339. #ifdef SQLITE_DEBUG
  9340. SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*);
  9341. SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*);
  9342. #else
  9343. # define sqlite3SafetyOn(A) 0
  9344. # define sqlite3SafetyOff(A) 0
  9345. #endif
  9346. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  9347. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  9348. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  9349. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  9350. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  9351. #endif
  9352. #ifndef SQLITE_OMIT_TRIGGER
  9353. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  9354. Expr*,int, int);
  9355. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  9356. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  9357. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  9358. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  9359. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  9360. SQLITE_PRIVATE int sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  9361. int, int, int, int, u32*, u32*);
  9362. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  9363. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  9364. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  9365. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  9366. ExprList*,Select*,int);
  9367. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
  9368. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  9369. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  9370. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  9371. #else
  9372. # define sqlite3TriggersExist(B,C,D,E,F) 0
  9373. # define sqlite3DeleteTrigger(A,B)
  9374. # define sqlite3DropTriggerPtr(A,B)
  9375. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  9376. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K,L) 0
  9377. # define sqlite3TriggerList(X, Y) 0
  9378. #endif
  9379. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  9380. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  9381. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  9382. #ifndef SQLITE_OMIT_AUTHORIZATION
  9383. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  9384. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  9385. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  9386. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  9387. #else
  9388. # define sqlite3AuthRead(a,b,c,d)
  9389. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  9390. # define sqlite3AuthContextPush(a,b,c)
  9391. # define sqlite3AuthContextPop(a) ((void)(a))
  9392. #endif
  9393. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  9394. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  9395. SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
  9396. int omitJournal, int nCache, int flags, Btree **ppBtree);
  9397. SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  9398. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  9399. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  9400. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  9401. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  9402. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  9403. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
  9404. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  9405. SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
  9406. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  9407. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  9408. SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
  9409. /*
  9410. ** Routines to read and write variable-length integers. These used to
  9411. ** be defined locally, but now we use the varint routines in the util.c
  9412. ** file. Code should use the MACRO forms below, as the Varint32 versions
  9413. ** are coded to assume the single byte case is already handled (which
  9414. ** the MACRO form does).
  9415. */
  9416. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  9417. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  9418. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  9419. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  9420. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  9421. /*
  9422. ** The header of a record consists of a sequence variable-length integers.
  9423. ** These integers are almost always small and are encoded as a single byte.
  9424. ** The following macros take advantage this fact to provide a fast encode
  9425. ** and decode of the integers in a record header. It is faster for the common
  9426. ** case where the integer is a single byte. It is a little slower when the
  9427. ** integer is two or more bytes. But overall it is faster.
  9428. **
  9429. ** The following expressions are equivalent:
  9430. **
  9431. ** x = sqlite3GetVarint32( A, &B );
  9432. ** x = sqlite3PutVarint32( A, B );
  9433. **
  9434. ** x = getVarint32( A, B );
  9435. ** x = putVarint32( A, B );
  9436. **
  9437. */
  9438. #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
  9439. #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
  9440. #define getVarint sqlite3GetVarint
  9441. #define putVarint sqlite3PutVarint
  9442. SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
  9443. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  9444. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  9445. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  9446. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  9447. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
  9448. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  9449. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  9450. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  9451. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  9452. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  9453. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
  9454. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
  9455. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  9456. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
  9457. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  9458. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  9459. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  9460. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  9461. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  9462. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  9463. void(*)(void*));
  9464. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  9465. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  9466. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
  9467. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  9468. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  9469. #ifndef SQLITE_AMALGAMATION
  9470. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  9471. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  9472. SQLITE_PRIVATE SQLITE_WSD struct SQLite3Config sqlite3Config;
  9473. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  9474. SQLITE_PRIVATE int sqlite3PendingByte;
  9475. #endif
  9476. SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
  9477. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  9478. SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
  9479. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  9480. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  9481. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  9482. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  9483. SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int, int);
  9484. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  9485. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  9486. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  9487. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  9488. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
  9489. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  9490. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  9491. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
  9492. SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
  9493. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  9494. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  9495. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  9496. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  9497. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  9498. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  9499. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  9500. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  9501. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  9502. SQLITE_PRIVATE void sqlite3SchemaFree(void *);
  9503. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  9504. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  9505. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  9506. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  9507. void (*)(sqlite3_context*,int,sqlite3_value **),
  9508. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
  9509. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  9510. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  9511. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  9512. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  9513. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  9514. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  9515. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  9516. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  9517. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  9518. /*
  9519. ** The interface to the LEMON-generated parser
  9520. */
  9521. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  9522. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  9523. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  9524. #ifdef YYTRACKMAXSTACKDEPTH
  9525. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  9526. #endif
  9527. SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
  9528. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9529. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  9530. #else
  9531. # define sqlite3CloseExtensions(X)
  9532. #endif
  9533. #ifndef SQLITE_OMIT_SHARED_CACHE
  9534. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  9535. #else
  9536. #define sqlite3TableLock(v,w,x,y,z)
  9537. #endif
  9538. #ifdef SQLITE_TEST
  9539. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  9540. #endif
  9541. #ifdef SQLITE_OMIT_VIRTUALTABLE
  9542. # define sqlite3VtabClear(X)
  9543. # define sqlite3VtabSync(X,Y) SQLITE_OK
  9544. # define sqlite3VtabRollback(X)
  9545. # define sqlite3VtabCommit(X)
  9546. # define sqlite3VtabInSync(db) 0
  9547. #else
  9548. SQLITE_PRIVATE void sqlite3VtabClear(Table*);
  9549. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
  9550. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  9551. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  9552. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  9553. #endif
  9554. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  9555. SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
  9556. SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
  9557. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
  9558. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  9559. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  9560. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  9561. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  9562. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  9563. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  9564. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
  9565. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  9566. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  9567. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  9568. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  9569. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  9570. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  9571. /*
  9572. ** Available fault injectors. Should be numbered beginning with 0.
  9573. */
  9574. #define SQLITE_FAULTINJECTOR_MALLOC 0
  9575. #define SQLITE_FAULTINJECTOR_COUNT 1
  9576. /*
  9577. ** The interface to the code in fault.c used for identifying "benign"
  9578. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  9579. ** is not defined.
  9580. */
  9581. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9582. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  9583. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  9584. #else
  9585. #define sqlite3BeginBenignMalloc()
  9586. #define sqlite3EndBenignMalloc()
  9587. #endif
  9588. #define IN_INDEX_ROWID 1
  9589. #define IN_INDEX_EPH 2
  9590. #define IN_INDEX_INDEX 3
  9591. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  9592. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  9593. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  9594. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  9595. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  9596. #else
  9597. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  9598. #endif
  9599. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  9600. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  9601. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  9602. #if SQLITE_MAX_EXPR_DEPTH>0
  9603. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  9604. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  9605. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  9606. #else
  9607. #define sqlite3ExprSetHeight(x,y)
  9608. #define sqlite3SelectExprHeight(x) 0
  9609. #define sqlite3ExprCheckHeight(x,y)
  9610. #endif
  9611. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  9612. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  9613. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9614. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  9615. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  9616. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  9617. #else
  9618. #define sqlite3ConnectionBlocked(x,y)
  9619. #define sqlite3ConnectionUnlocked(x)
  9620. #define sqlite3ConnectionClosed(x)
  9621. #endif
  9622. #ifdef SQLITE_SSE
  9623. #include "sseInt.h"
  9624. #endif
  9625. #ifdef SQLITE_DEBUG
  9626. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  9627. #endif
  9628. /*
  9629. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  9630. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  9631. ** print I/O tracing messages.
  9632. */
  9633. #ifdef SQLITE_ENABLE_IOTRACE
  9634. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  9635. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  9636. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  9637. #else
  9638. # define IOTRACE(A)
  9639. # define sqlite3VdbeIOTraceSql(X)
  9640. #endif
  9641. #endif
  9642. /************** End of sqliteInt.h *******************************************/
  9643. /************** Begin file global.c ******************************************/
  9644. /*
  9645. ** 2008 June 13
  9646. **
  9647. ** The author disclaims copyright to this source code. In place of
  9648. ** a legal notice, here is a blessing:
  9649. **
  9650. ** May you do good and not evil.
  9651. ** May you find forgiveness for yourself and forgive others.
  9652. ** May you share freely, never taking more than you give.
  9653. **
  9654. *************************************************************************
  9655. **
  9656. ** This file contains definitions of global variables and contants.
  9657. **
  9658. ** $Id: global.c,v 1.12 2009/02/05 16:31:46 drh Exp $
  9659. */
  9660. /* An array to map all upper-case characters into their corresponding
  9661. ** lower-case character.
  9662. **
  9663. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  9664. ** handle case conversions for the UTF character set since the tables
  9665. ** involved are nearly as big or bigger than SQLite itself.
  9666. */
  9667. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  9668. #ifdef SQLITE_ASCII
  9669. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  9670. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  9671. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  9672. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  9673. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  9674. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  9675. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  9676. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  9677. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  9678. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  9679. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  9680. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  9681. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  9682. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  9683. 252,253,254,255
  9684. #endif
  9685. #ifdef SQLITE_EBCDIC
  9686. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  9687. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  9688. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  9689. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  9690. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  9691. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  9692. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  9693. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  9694. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  9695. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  9696. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  9697. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  9698. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  9699. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  9700. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  9701. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  9702. #endif
  9703. };
  9704. /*
  9705. ** The following 256 byte lookup table is used to support SQLites built-in
  9706. ** equivalents to the following standard library functions:
  9707. **
  9708. ** isspace() 0x01
  9709. ** isalpha() 0x02
  9710. ** isdigit() 0x04
  9711. ** isalnum() 0x06
  9712. ** isxdigit() 0x08
  9713. ** toupper() 0x20
  9714. **
  9715. ** Bit 0x20 is set if the mapped character requires translation to upper
  9716. ** case. i.e. if the character is a lower-case ASCII character.
  9717. ** If x is a lower-case ASCII character, then its upper-case equivalent
  9718. ** is (x - 0x20). Therefore toupper() can be implemented as:
  9719. **
  9720. ** (x & ~(map[x]&0x20))
  9721. **
  9722. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  9723. ** array. tolower() is used more often than toupper() by SQLite.
  9724. **
  9725. ** SQLite's versions are identical to the standard versions assuming a
  9726. ** locale of "C". They are implemented as macros in sqliteInt.h.
  9727. */
  9728. #ifdef SQLITE_ASCII
  9729. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  9730. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  9731. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  9732. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  9733. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  9734. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  9735. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  9736. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  9737. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  9738. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  9739. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  9740. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  9741. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, /* 58..5f XYZ[\]^_ */
  9742. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  9743. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  9744. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  9745. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  9746. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 80..87 ........ */
  9747. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 88..8f ........ */
  9748. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 90..97 ........ */
  9749. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 98..9f ........ */
  9750. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a0..a7 ........ */
  9751. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a8..af ........ */
  9752. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b0..b7 ........ */
  9753. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b8..bf ........ */
  9754. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c0..c7 ........ */
  9755. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c8..cf ........ */
  9756. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d0..d7 ........ */
  9757. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d8..df ........ */
  9758. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e0..e7 ........ */
  9759. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e8..ef ........ */
  9760. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f0..f7 ........ */
  9761. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* f8..ff ........ */
  9762. };
  9763. #endif
  9764. /*
  9765. ** The following singleton contains the global configuration for
  9766. ** the SQLite library.
  9767. */
  9768. SQLITE_PRIVATE SQLITE_WSD struct SQLite3Config sqlite3Config = {
  9769. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  9770. 1, /* bCoreMutex */
  9771. SQLITE_THREADSAFE==1, /* bFullMutex */
  9772. 0x7ffffffe, /* mxStrlen */
  9773. 100, /* szLookaside */
  9774. 500, /* nLookaside */
  9775. {0,0,0,0,0,0,0,0}, /* m */
  9776. {0,0,0,0,0,0,0,0,0}, /* mutex */
  9777. {0,0,0,0,0,0,0,0,0,0,0}, /* pcache */
  9778. (void*)0, /* pHeap */
  9779. 0, /* nHeap */
  9780. 0, 0, /* mnHeap, mxHeap */
  9781. (void*)0, /* pScratch */
  9782. 0, /* szScratch */
  9783. 0, /* nScratch */
  9784. (void*)0, /* pPage */
  9785. 0, /* szPage */
  9786. 0, /* nPage */
  9787. 0, /* mxParserStack */
  9788. 0, /* sharedCacheEnabled */
  9789. /* All the rest need to always be zero */
  9790. 0, /* isInit */
  9791. 0, /* inProgress */
  9792. 0, /* isMallocInit */
  9793. 0, /* pInitMutex */
  9794. 0, /* nRefInitMutex */
  9795. };
  9796. /*
  9797. ** Hash table for global functions - functions common to all
  9798. ** database connections. After initialization, this table is
  9799. ** read-only.
  9800. */
  9801. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  9802. /*
  9803. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  9804. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  9805. ** the database page that contains the pending byte. It never attempts
  9806. ** to read or write that page. The pending byte page is set assign
  9807. ** for use by the VFS layers as space for managing file locks.
  9808. **
  9809. ** During testing, it is often desirable to move the pending byte to
  9810. ** a different position in the file. This allows code that has to
  9811. ** deal with the pending byte to run on files that are much smaller
  9812. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  9813. ** move the pending byte.
  9814. **
  9815. ** IMPORTANT: Changing the pending byte to any value other than
  9816. ** 0x40000000 results in an incompatible database file format!
  9817. ** Changing the pending byte during operating results in undefined
  9818. ** and dileterious behavior.
  9819. */
  9820. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  9821. /************** End of global.c **********************************************/
  9822. /************** Begin file status.c ******************************************/
  9823. /*
  9824. ** 2008 June 18
  9825. **
  9826. ** The author disclaims copyright to this source code. In place of
  9827. ** a legal notice, here is a blessing:
  9828. **
  9829. ** May you do good and not evil.
  9830. ** May you find forgiveness for yourself and forgive others.
  9831. ** May you share freely, never taking more than you give.
  9832. **
  9833. *************************************************************************
  9834. **
  9835. ** This module implements the sqlite3_status() interface and related
  9836. ** functionality.
  9837. **
  9838. ** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
  9839. */
  9840. /*
  9841. ** Variables in which to record status information.
  9842. */
  9843. typedef struct sqlite3StatType sqlite3StatType;
  9844. static SQLITE_WSD struct sqlite3StatType {
  9845. int nowValue[9]; /* Current value */
  9846. int mxValue[9]; /* Maximum value */
  9847. } sqlite3Stat = { {0,}, {0,} };
  9848. /* The "wsdStat" macro will resolve to the status information
  9849. ** state vector. If writable static data is unsupported on the target,
  9850. ** we have to locate the state vector at run-time. In the more common
  9851. ** case where writable static data is supported, wsdStat can refer directly
  9852. ** to the "sqlite3Stat" state vector declared above.
  9853. */
  9854. #ifdef SQLITE_OMIT_WSD
  9855. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  9856. # define wsdStat x[0]
  9857. #else
  9858. # define wsdStatInit
  9859. # define wsdStat sqlite3Stat
  9860. #endif
  9861. /*
  9862. ** Return the current value of a status parameter.
  9863. */
  9864. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  9865. wsdStatInit;
  9866. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  9867. return wsdStat.nowValue[op];
  9868. }
  9869. /*
  9870. ** Add N to the value of a status record. It is assumed that the
  9871. ** caller holds appropriate locks.
  9872. */
  9873. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  9874. wsdStatInit;
  9875. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  9876. wsdStat.nowValue[op] += N;
  9877. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  9878. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  9879. }
  9880. }
  9881. /*
  9882. ** Set the value of a status to X.
  9883. */
  9884. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  9885. wsdStatInit;
  9886. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  9887. wsdStat.nowValue[op] = X;
  9888. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  9889. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  9890. }
  9891. }
  9892. /*
  9893. ** Query status information.
  9894. **
  9895. ** This implementation assumes that reading or writing an aligned
  9896. ** 32-bit integer is an atomic operation. If that assumption is not true,
  9897. ** then this routine is not threadsafe.
  9898. */
  9899. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  9900. wsdStatInit;
  9901. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  9902. return SQLITE_MISUSE;
  9903. }
  9904. *pCurrent = wsdStat.nowValue[op];
  9905. *pHighwater = wsdStat.mxValue[op];
  9906. if( resetFlag ){
  9907. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  9908. }
  9909. return SQLITE_OK;
  9910. }
  9911. /*
  9912. ** Query status information for a single database connection
  9913. */
  9914. SQLITE_API int sqlite3_db_status(
  9915. sqlite3 *db, /* The database connection whose status is desired */
  9916. int op, /* Status verb */
  9917. int *pCurrent, /* Write current value here */
  9918. int *pHighwater, /* Write high-water mark here */
  9919. int resetFlag /* Reset high-water mark if true */
  9920. ){
  9921. switch( op ){
  9922. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  9923. *pCurrent = db->lookaside.nOut;
  9924. *pHighwater = db->lookaside.mxOut;
  9925. if( resetFlag ){
  9926. db->lookaside.mxOut = db->lookaside.nOut;
  9927. }
  9928. break;
  9929. }
  9930. default: {
  9931. return SQLITE_ERROR;
  9932. }
  9933. }
  9934. return SQLITE_OK;
  9935. }
  9936. /************** End of status.c **********************************************/
  9937. /************** Begin file date.c ********************************************/
  9938. /*
  9939. ** 2003 October 31
  9940. **
  9941. ** The author disclaims copyright to this source code. In place of
  9942. ** a legal notice, here is a blessing:
  9943. **
  9944. ** May you do good and not evil.
  9945. ** May you find forgiveness for yourself and forgive others.
  9946. ** May you share freely, never taking more than you give.
  9947. **
  9948. *************************************************************************
  9949. ** This file contains the C functions that implement date and time
  9950. ** functions for SQLite.
  9951. **
  9952. ** There is only one exported symbol in this file - the function
  9953. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  9954. ** All other code has file scope.
  9955. **
  9956. ** $Id: date.c,v 1.105 2009/04/03 12:04:37 drh Exp $
  9957. **
  9958. ** SQLite processes all times and dates as Julian Day numbers. The
  9959. ** dates and times are stored as the number of days since noon
  9960. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  9961. ** calendar system.
  9962. **
  9963. ** 1970-01-01 00:00:00 is JD 2440587.5
  9964. ** 2000-01-01 00:00:00 is JD 2451544.5
  9965. **
  9966. ** This implemention requires years to be expressed as a 4-digit number
  9967. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  9968. ** be represented, even though julian day numbers allow a much wider
  9969. ** range of dates.
  9970. **
  9971. ** The Gregorian calendar system is used for all dates and times,
  9972. ** even those that predate the Gregorian calendar. Historians usually
  9973. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  9974. ** dates afterwards, depending on locale. Beware of this difference.
  9975. **
  9976. ** The conversion algorithms are implemented based on descriptions
  9977. ** in the following text:
  9978. **
  9979. ** Jean Meeus
  9980. ** Astronomical Algorithms, 2nd Edition, 1998
  9981. ** ISBM 0-943396-61-1
  9982. ** Willmann-Bell, Inc
  9983. ** Richmond, Virginia (USA)
  9984. */
  9985. #include <time.h>
  9986. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  9987. /*
  9988. ** On recent Windows platforms, the localtime_s() function is available
  9989. ** as part of the "Secure CRT". It is essentially equivalent to
  9990. ** localtime_r() available under most POSIX platforms, except that the
  9991. ** order of the parameters is reversed.
  9992. **
  9993. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  9994. **
  9995. ** If the user has not indicated to use localtime_r() or localtime_s()
  9996. ** already, check for an MSVC build environment that provides
  9997. ** localtime_s().
  9998. */
  9999. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  10000. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  10001. #define HAVE_LOCALTIME_S 1
  10002. #endif
  10003. /*
  10004. ** A structure for holding a single date and time.
  10005. */
  10006. typedef struct DateTime DateTime;
  10007. struct DateTime {
  10008. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  10009. int Y, M, D; /* Year, month, and day */
  10010. int h, m; /* Hour and minutes */
  10011. int tz; /* Timezone offset in minutes */
  10012. double s; /* Seconds */
  10013. char validYMD; /* True (1) if Y,M,D are valid */
  10014. char validHMS; /* True (1) if h,m,s are valid */
  10015. char validJD; /* True (1) if iJD is valid */
  10016. char validTZ; /* True (1) if tz is valid */
  10017. };
  10018. /*
  10019. ** Convert zDate into one or more integers. Additional arguments
  10020. ** come in groups of 5 as follows:
  10021. **
  10022. ** N number of digits in the integer
  10023. ** min minimum allowed value of the integer
  10024. ** max maximum allowed value of the integer
  10025. ** nextC first character after the integer
  10026. ** pVal where to write the integers value.
  10027. **
  10028. ** Conversions continue until one with nextC==0 is encountered.
  10029. ** The function returns the number of successful conversions.
  10030. */
  10031. static int getDigits(const char *zDate, ...){
  10032. va_list ap;
  10033. int val;
  10034. int N;
  10035. int min;
  10036. int max;
  10037. int nextC;
  10038. int *pVal;
  10039. int cnt = 0;
  10040. va_start(ap, zDate);
  10041. do{
  10042. N = va_arg(ap, int);
  10043. min = va_arg(ap, int);
  10044. max = va_arg(ap, int);
  10045. nextC = va_arg(ap, int);
  10046. pVal = va_arg(ap, int*);
  10047. val = 0;
  10048. while( N-- ){
  10049. if( !sqlite3Isdigit(*zDate) ){
  10050. goto end_getDigits;
  10051. }
  10052. val = val*10 + *zDate - '0';
  10053. zDate++;
  10054. }
  10055. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  10056. goto end_getDigits;
  10057. }
  10058. *pVal = val;
  10059. zDate++;
  10060. cnt++;
  10061. }while( nextC );
  10062. end_getDigits:
  10063. va_end(ap);
  10064. return cnt;
  10065. }
  10066. /*
  10067. ** Read text from z[] and convert into a floating point number. Return
  10068. ** the number of digits converted.
  10069. */
  10070. #define getValue sqlite3AtoF
  10071. /*
  10072. ** Parse a timezone extension on the end of a date-time.
  10073. ** The extension is of the form:
  10074. **
  10075. ** (+/-)HH:MM
  10076. **
  10077. ** Or the "zulu" notation:
  10078. **
  10079. ** Z
  10080. **
  10081. ** If the parse is successful, write the number of minutes
  10082. ** of change in p->tz and return 0. If a parser error occurs,
  10083. ** return non-zero.
  10084. **
  10085. ** A missing specifier is not considered an error.
  10086. */
  10087. static int parseTimezone(const char *zDate, DateTime *p){
  10088. int sgn = 0;
  10089. int nHr, nMn;
  10090. int c;
  10091. while( sqlite3Isspace(*zDate) ){ zDate++; }
  10092. p->tz = 0;
  10093. c = *zDate;
  10094. if( c=='-' ){
  10095. sgn = -1;
  10096. }else if( c=='+' ){
  10097. sgn = +1;
  10098. }else if( c=='Z' || c=='z' ){
  10099. zDate++;
  10100. goto zulu_time;
  10101. }else{
  10102. return c!=0;
  10103. }
  10104. zDate++;
  10105. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  10106. return 1;
  10107. }
  10108. zDate += 5;
  10109. p->tz = sgn*(nMn + nHr*60);
  10110. zulu_time:
  10111. while( sqlite3Isspace(*zDate) ){ zDate++; }
  10112. return *zDate!=0;
  10113. }
  10114. /*
  10115. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  10116. ** The HH, MM, and SS must each be exactly 2 digits. The
  10117. ** fractional seconds FFFF can be one or more digits.
  10118. **
  10119. ** Return 1 if there is a parsing error and 0 on success.
  10120. */
  10121. static int parseHhMmSs(const char *zDate, DateTime *p){
  10122. int h, m, s;
  10123. double ms = 0.0;
  10124. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  10125. return 1;
  10126. }
  10127. zDate += 5;
  10128. if( *zDate==':' ){
  10129. zDate++;
  10130. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  10131. return 1;
  10132. }
  10133. zDate += 2;
  10134. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  10135. double rScale = 1.0;
  10136. zDate++;
  10137. while( sqlite3Isdigit(*zDate) ){
  10138. ms = ms*10.0 + *zDate - '0';
  10139. rScale *= 10.0;
  10140. zDate++;
  10141. }
  10142. ms /= rScale;
  10143. }
  10144. }else{
  10145. s = 0;
  10146. }
  10147. p->validJD = 0;
  10148. p->validHMS = 1;
  10149. p->h = h;
  10150. p->m = m;
  10151. p->s = s + ms;
  10152. if( parseTimezone(zDate, p) ) return 1;
  10153. p->validTZ = (p->tz!=0)?1:0;
  10154. return 0;
  10155. }
  10156. /*
  10157. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  10158. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  10159. **
  10160. ** Reference: Meeus page 61
  10161. */
  10162. static void computeJD(DateTime *p){
  10163. int Y, M, D, A, B, X1, X2;
  10164. if( p->validJD ) return;
  10165. if( p->validYMD ){
  10166. Y = p->Y;
  10167. M = p->M;
  10168. D = p->D;
  10169. }else{
  10170. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  10171. M = 1;
  10172. D = 1;
  10173. }
  10174. if( M<=2 ){
  10175. Y--;
  10176. M += 12;
  10177. }
  10178. A = Y/100;
  10179. B = 2 - A + (A/4);
  10180. X1 = 36525*(Y+4716)/100;
  10181. X2 = 306001*(M+1)/10000;
  10182. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  10183. p->validJD = 1;
  10184. if( p->validHMS ){
  10185. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  10186. if( p->validTZ ){
  10187. p->iJD -= p->tz*60000;
  10188. p->validYMD = 0;
  10189. p->validHMS = 0;
  10190. p->validTZ = 0;
  10191. }
  10192. }
  10193. }
  10194. /*
  10195. ** Parse dates of the form
  10196. **
  10197. ** YYYY-MM-DD HH:MM:SS.FFF
  10198. ** YYYY-MM-DD HH:MM:SS
  10199. ** YYYY-MM-DD HH:MM
  10200. ** YYYY-MM-DD
  10201. **
  10202. ** Write the result into the DateTime structure and return 0
  10203. ** on success and 1 if the input string is not a well-formed
  10204. ** date.
  10205. */
  10206. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  10207. int Y, M, D, neg;
  10208. if( zDate[0]=='-' ){
  10209. zDate++;
  10210. neg = 1;
  10211. }else{
  10212. neg = 0;
  10213. }
  10214. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  10215. return 1;
  10216. }
  10217. zDate += 10;
  10218. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  10219. if( parseHhMmSs(zDate, p)==0 ){
  10220. /* We got the time */
  10221. }else if( *zDate==0 ){
  10222. p->validHMS = 0;
  10223. }else{
  10224. return 1;
  10225. }
  10226. p->validJD = 0;
  10227. p->validYMD = 1;
  10228. p->Y = neg ? -Y : Y;
  10229. p->M = M;
  10230. p->D = D;
  10231. if( p->validTZ ){
  10232. computeJD(p);
  10233. }
  10234. return 0;
  10235. }
  10236. /*
  10237. ** Set the time to the current time reported by the VFS
  10238. */
  10239. static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  10240. double r;
  10241. sqlite3 *db = sqlite3_context_db_handle(context);
  10242. sqlite3OsCurrentTime(db->pVfs, &r);
  10243. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  10244. p->validJD = 1;
  10245. }
  10246. /*
  10247. ** Attempt to parse the given string into a Julian Day Number. Return
  10248. ** the number of errors.
  10249. **
  10250. ** The following are acceptable forms for the input string:
  10251. **
  10252. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  10253. ** DDDD.DD
  10254. ** now
  10255. **
  10256. ** In the first form, the +/-HH:MM is always optional. The fractional
  10257. ** seconds extension (the ".FFF") is optional. The seconds portion
  10258. ** (":SS.FFF") is option. The year and date can be omitted as long
  10259. ** as there is a time string. The time string can be omitted as long
  10260. ** as there is a year and date.
  10261. */
  10262. static int parseDateOrTime(
  10263. sqlite3_context *context,
  10264. const char *zDate,
  10265. DateTime *p
  10266. ){
  10267. if( parseYyyyMmDd(zDate,p)==0 ){
  10268. return 0;
  10269. }else if( parseHhMmSs(zDate, p)==0 ){
  10270. return 0;
  10271. }else if( sqlite3StrICmp(zDate,"now")==0){
  10272. setDateTimeToCurrent(context, p);
  10273. return 0;
  10274. }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
  10275. double r;
  10276. getValue(zDate, &r);
  10277. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  10278. p->validJD = 1;
  10279. return 0;
  10280. }
  10281. return 1;
  10282. }
  10283. /*
  10284. ** Compute the Year, Month, and Day from the julian day number.
  10285. */
  10286. static void computeYMD(DateTime *p){
  10287. int Z, A, B, C, D, E, X1;
  10288. if( p->validYMD ) return;
  10289. if( !p->validJD ){
  10290. p->Y = 2000;
  10291. p->M = 1;
  10292. p->D = 1;
  10293. }else{
  10294. Z = (int)((p->iJD + 43200000)/86400000);
  10295. A = (int)((Z - 1867216.25)/36524.25);
  10296. A = Z + 1 + A - (A/4);
  10297. B = A + 1524;
  10298. C = (int)((B - 122.1)/365.25);
  10299. D = (36525*C)/100;
  10300. E = (int)((B-D)/30.6001);
  10301. X1 = (int)(30.6001*E);
  10302. p->D = B - D - X1;
  10303. p->M = E<14 ? E-1 : E-13;
  10304. p->Y = p->M>2 ? C - 4716 : C - 4715;
  10305. }
  10306. p->validYMD = 1;
  10307. }
  10308. /*
  10309. ** Compute the Hour, Minute, and Seconds from the julian day number.
  10310. */
  10311. static void computeHMS(DateTime *p){
  10312. int s;
  10313. if( p->validHMS ) return;
  10314. computeJD(p);
  10315. s = (int)((p->iJD + 43200000) % 86400000);
  10316. p->s = s/1000.0;
  10317. s = (int)p->s;
  10318. p->s -= s;
  10319. p->h = s/3600;
  10320. s -= p->h*3600;
  10321. p->m = s/60;
  10322. p->s += s - p->m*60;
  10323. p->validHMS = 1;
  10324. }
  10325. /*
  10326. ** Compute both YMD and HMS
  10327. */
  10328. static void computeYMD_HMS(DateTime *p){
  10329. computeYMD(p);
  10330. computeHMS(p);
  10331. }
  10332. /*
  10333. ** Clear the YMD and HMS and the TZ
  10334. */
  10335. static void clearYMD_HMS_TZ(DateTime *p){
  10336. p->validYMD = 0;
  10337. p->validHMS = 0;
  10338. p->validTZ = 0;
  10339. }
  10340. #ifndef SQLITE_OMIT_LOCALTIME
  10341. /*
  10342. ** Compute the difference (in milliseconds)
  10343. ** between localtime and UTC (a.k.a. GMT)
  10344. ** for the time value p where p is in UTC.
  10345. */
  10346. static sqlite3_int64 localtimeOffset(DateTime *p){
  10347. DateTime x, y;
  10348. time_t t;
  10349. x = *p;
  10350. computeYMD_HMS(&x);
  10351. if( x.Y<1971 || x.Y>=2038 ){
  10352. x.Y = 2000;
  10353. x.M = 1;
  10354. x.D = 1;
  10355. x.h = 0;
  10356. x.m = 0;
  10357. x.s = 0.0;
  10358. } else {
  10359. int s = (int)(x.s + 0.5);
  10360. x.s = s;
  10361. }
  10362. x.tz = 0;
  10363. x.validJD = 0;
  10364. computeJD(&x);
  10365. t = x.iJD/1000 - 21086676*(i64)10000;
  10366. #ifdef HAVE_LOCALTIME_R
  10367. {
  10368. struct tm sLocal;
  10369. localtime_r(&t, &sLocal);
  10370. y.Y = sLocal.tm_year + 1900;
  10371. y.M = sLocal.tm_mon + 1;
  10372. y.D = sLocal.tm_mday;
  10373. y.h = sLocal.tm_hour;
  10374. y.m = sLocal.tm_min;
  10375. y.s = sLocal.tm_sec;
  10376. }
  10377. #elif defined(HAVE_LOCALTIME_S)
  10378. {
  10379. struct tm sLocal;
  10380. localtime_s(&sLocal, &t);
  10381. y.Y = sLocal.tm_year + 1900;
  10382. y.M = sLocal.tm_mon + 1;
  10383. y.D = sLocal.tm_mday;
  10384. y.h = sLocal.tm_hour;
  10385. y.m = sLocal.tm_min;
  10386. y.s = sLocal.tm_sec;
  10387. }
  10388. #else
  10389. {
  10390. struct tm *pTm;
  10391. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  10392. pTm = localtime(&t);
  10393. y.Y = pTm->tm_year + 1900;
  10394. y.M = pTm->tm_mon + 1;
  10395. y.D = pTm->tm_mday;
  10396. y.h = pTm->tm_hour;
  10397. y.m = pTm->tm_min;
  10398. y.s = pTm->tm_sec;
  10399. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  10400. }
  10401. #endif
  10402. y.validYMD = 1;
  10403. y.validHMS = 1;
  10404. y.validJD = 0;
  10405. y.validTZ = 0;
  10406. computeJD(&y);
  10407. return y.iJD - x.iJD;
  10408. }
  10409. #endif /* SQLITE_OMIT_LOCALTIME */
  10410. /*
  10411. ** Process a modifier to a date-time stamp. The modifiers are
  10412. ** as follows:
  10413. **
  10414. ** NNN days
  10415. ** NNN hours
  10416. ** NNN minutes
  10417. ** NNN.NNNN seconds
  10418. ** NNN months
  10419. ** NNN years
  10420. ** start of month
  10421. ** start of year
  10422. ** start of week
  10423. ** start of day
  10424. ** weekday N
  10425. ** unixepoch
  10426. ** localtime
  10427. ** utc
  10428. **
  10429. ** Return 0 on success and 1 if there is any kind of error.
  10430. */
  10431. static int parseModifier(const char *zMod, DateTime *p){
  10432. int rc = 1;
  10433. int n;
  10434. double r;
  10435. char *z, zBuf[30];
  10436. z = zBuf;
  10437. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  10438. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  10439. }
  10440. z[n] = 0;
  10441. switch( z[0] ){
  10442. #ifndef SQLITE_OMIT_LOCALTIME
  10443. case 'l': {
  10444. /* localtime
  10445. **
  10446. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  10447. ** show local time.
  10448. */
  10449. if( strcmp(z, "localtime")==0 ){
  10450. computeJD(p);
  10451. p->iJD += localtimeOffset(p);
  10452. clearYMD_HMS_TZ(p);
  10453. rc = 0;
  10454. }
  10455. break;
  10456. }
  10457. #endif
  10458. case 'u': {
  10459. /*
  10460. ** unixepoch
  10461. **
  10462. ** Treat the current value of p->iJD as the number of
  10463. ** seconds since 1970. Convert to a real julian day number.
  10464. */
  10465. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  10466. p->iJD = p->iJD/86400 + 21086676*(i64)10000000;
  10467. clearYMD_HMS_TZ(p);
  10468. rc = 0;
  10469. }
  10470. #ifndef SQLITE_OMIT_LOCALTIME
  10471. else if( strcmp(z, "utc")==0 ){
  10472. sqlite3_int64 c1;
  10473. computeJD(p);
  10474. c1 = localtimeOffset(p);
  10475. p->iJD -= c1;
  10476. clearYMD_HMS_TZ(p);
  10477. p->iJD += c1 - localtimeOffset(p);
  10478. rc = 0;
  10479. }
  10480. #endif
  10481. break;
  10482. }
  10483. case 'w': {
  10484. /*
  10485. ** weekday N
  10486. **
  10487. ** Move the date to the same time on the next occurrence of
  10488. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  10489. ** date is already on the appropriate weekday, this is a no-op.
  10490. */
  10491. if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
  10492. && (n=(int)r)==r && n>=0 && r<7 ){
  10493. sqlite3_int64 Z;
  10494. computeYMD_HMS(p);
  10495. p->validTZ = 0;
  10496. p->validJD = 0;
  10497. computeJD(p);
  10498. Z = ((p->iJD + 129600000)/86400000) % 7;
  10499. if( Z>n ) Z -= 7;
  10500. p->iJD += (n - Z)*86400000;
  10501. clearYMD_HMS_TZ(p);
  10502. rc = 0;
  10503. }
  10504. break;
  10505. }
  10506. case 's': {
  10507. /*
  10508. ** start of TTTTT
  10509. **
  10510. ** Move the date backwards to the beginning of the current day,
  10511. ** or month or year.
  10512. */
  10513. if( strncmp(z, "start of ", 9)!=0 ) break;
  10514. z += 9;
  10515. computeYMD(p);
  10516. p->validHMS = 1;
  10517. p->h = p->m = 0;
  10518. p->s = 0.0;
  10519. p->validTZ = 0;
  10520. p->validJD = 0;
  10521. if( strcmp(z,"month")==0 ){
  10522. p->D = 1;
  10523. rc = 0;
  10524. }else if( strcmp(z,"year")==0 ){
  10525. computeYMD(p);
  10526. p->M = 1;
  10527. p->D = 1;
  10528. rc = 0;
  10529. }else if( strcmp(z,"day")==0 ){
  10530. rc = 0;
  10531. }
  10532. break;
  10533. }
  10534. case '+':
  10535. case '-':
  10536. case '0':
  10537. case '1':
  10538. case '2':
  10539. case '3':
  10540. case '4':
  10541. case '5':
  10542. case '6':
  10543. case '7':
  10544. case '8':
  10545. case '9': {
  10546. double rRounder;
  10547. n = getValue(z, &r);
  10548. assert( n>=1 );
  10549. if( z[n]==':' ){
  10550. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  10551. ** specified number of hours, minutes, seconds, and fractional seconds
  10552. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  10553. ** omitted.
  10554. */
  10555. const char *z2 = z;
  10556. DateTime tx;
  10557. sqlite3_int64 day;
  10558. if( !sqlite3Isdigit(*z2) ) z2++;
  10559. memset(&tx, 0, sizeof(tx));
  10560. if( parseHhMmSs(z2, &tx) ) break;
  10561. computeJD(&tx);
  10562. tx.iJD -= 43200000;
  10563. day = tx.iJD/86400000;
  10564. tx.iJD -= day*86400000;
  10565. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  10566. computeJD(p);
  10567. clearYMD_HMS_TZ(p);
  10568. p->iJD += tx.iJD;
  10569. rc = 0;
  10570. break;
  10571. }
  10572. z += n;
  10573. while( sqlite3Isspace(*z) ) z++;
  10574. n = sqlite3Strlen30(z);
  10575. if( n>10 || n<3 ) break;
  10576. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  10577. computeJD(p);
  10578. rc = 0;
  10579. rRounder = r<0 ? -0.5 : +0.5;
  10580. if( n==3 && strcmp(z,"day")==0 ){
  10581. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  10582. }else if( n==4 && strcmp(z,"hour")==0 ){
  10583. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  10584. }else if( n==6 && strcmp(z,"minute")==0 ){
  10585. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  10586. }else if( n==6 && strcmp(z,"second")==0 ){
  10587. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  10588. }else if( n==5 && strcmp(z,"month")==0 ){
  10589. int x, y;
  10590. computeYMD_HMS(p);
  10591. p->M += (int)r;
  10592. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  10593. p->Y += x;
  10594. p->M -= x*12;
  10595. p->validJD = 0;
  10596. computeJD(p);
  10597. y = (int)r;
  10598. if( y!=r ){
  10599. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  10600. }
  10601. }else if( n==4 && strcmp(z,"year")==0 ){
  10602. int y = (int)r;
  10603. computeYMD_HMS(p);
  10604. p->Y += y;
  10605. p->validJD = 0;
  10606. computeJD(p);
  10607. if( y!=r ){
  10608. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  10609. }
  10610. }else{
  10611. rc = 1;
  10612. }
  10613. clearYMD_HMS_TZ(p);
  10614. break;
  10615. }
  10616. default: {
  10617. break;
  10618. }
  10619. }
  10620. return rc;
  10621. }
  10622. /*
  10623. ** Process time function arguments. argv[0] is a date-time stamp.
  10624. ** argv[1] and following are modifiers. Parse them all and write
  10625. ** the resulting time into the DateTime structure p. Return 0
  10626. ** on success and 1 if there are any errors.
  10627. **
  10628. ** If there are zero parameters (if even argv[0] is undefined)
  10629. ** then assume a default value of "now" for argv[0].
  10630. */
  10631. static int isDate(
  10632. sqlite3_context *context,
  10633. int argc,
  10634. sqlite3_value **argv,
  10635. DateTime *p
  10636. ){
  10637. int i;
  10638. const unsigned char *z;
  10639. int eType;
  10640. memset(p, 0, sizeof(*p));
  10641. if( argc==0 ){
  10642. setDateTimeToCurrent(context, p);
  10643. }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  10644. || eType==SQLITE_INTEGER ){
  10645. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  10646. p->validJD = 1;
  10647. }else{
  10648. z = sqlite3_value_text(argv[0]);
  10649. if( !z || parseDateOrTime(context, (char*)z, p) ){
  10650. return 1;
  10651. }
  10652. }
  10653. for(i=1; i<argc; i++){
  10654. if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
  10655. return 1;
  10656. }
  10657. }
  10658. return 0;
  10659. }
  10660. /*
  10661. ** The following routines implement the various date and time functions
  10662. ** of SQLite.
  10663. */
  10664. /*
  10665. ** julianday( TIMESTRING, MOD, MOD, ...)
  10666. **
  10667. ** Return the julian day number of the date specified in the arguments
  10668. */
  10669. static void juliandayFunc(
  10670. sqlite3_context *context,
  10671. int argc,
  10672. sqlite3_value **argv
  10673. ){
  10674. DateTime x;
  10675. if( isDate(context, argc, argv, &x)==0 ){
  10676. computeJD(&x);
  10677. sqlite3_result_double(context, x.iJD/86400000.0);
  10678. }
  10679. }
  10680. /*
  10681. ** datetime( TIMESTRING, MOD, MOD, ...)
  10682. **
  10683. ** Return YYYY-MM-DD HH:MM:SS
  10684. */
  10685. static void datetimeFunc(
  10686. sqlite3_context *context,
  10687. int argc,
  10688. sqlite3_value **argv
  10689. ){
  10690. DateTime x;
  10691. if( isDate(context, argc, argv, &x)==0 ){
  10692. char zBuf[100];
  10693. computeYMD_HMS(&x);
  10694. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  10695. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  10696. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  10697. }
  10698. }
  10699. /*
  10700. ** time( TIMESTRING, MOD, MOD, ...)
  10701. **
  10702. ** Return HH:MM:SS
  10703. */
  10704. static void timeFunc(
  10705. sqlite3_context *context,
  10706. int argc,
  10707. sqlite3_value **argv
  10708. ){
  10709. DateTime x;
  10710. if( isDate(context, argc, argv, &x)==0 ){
  10711. char zBuf[100];
  10712. computeHMS(&x);
  10713. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  10714. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  10715. }
  10716. }
  10717. /*
  10718. ** date( TIMESTRING, MOD, MOD, ...)
  10719. **
  10720. ** Return YYYY-MM-DD
  10721. */
  10722. static void dateFunc(
  10723. sqlite3_context *context,
  10724. int argc,
  10725. sqlite3_value **argv
  10726. ){
  10727. DateTime x;
  10728. if( isDate(context, argc, argv, &x)==0 ){
  10729. char zBuf[100];
  10730. computeYMD(&x);
  10731. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  10732. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  10733. }
  10734. }
  10735. /*
  10736. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  10737. **
  10738. ** Return a string described by FORMAT. Conversions as follows:
  10739. **
  10740. ** %d day of month
  10741. ** %f ** fractional seconds SS.SSS
  10742. ** %H hour 00-24
  10743. ** %j day of year 000-366
  10744. ** %J ** Julian day number
  10745. ** %m month 01-12
  10746. ** %M minute 00-59
  10747. ** %s seconds since 1970-01-01
  10748. ** %S seconds 00-59
  10749. ** %w day of week 0-6 sunday==0
  10750. ** %W week of year 00-53
  10751. ** %Y year 0000-9999
  10752. ** %% %
  10753. */
  10754. static void strftimeFunc(
  10755. sqlite3_context *context,
  10756. int argc,
  10757. sqlite3_value **argv
  10758. ){
  10759. DateTime x;
  10760. u64 n;
  10761. size_t i,j;
  10762. char *z;
  10763. sqlite3 *db;
  10764. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  10765. char zBuf[100];
  10766. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  10767. db = sqlite3_context_db_handle(context);
  10768. for(i=0, n=1; zFmt[i]; i++, n++){
  10769. if( zFmt[i]=='%' ){
  10770. switch( zFmt[i+1] ){
  10771. case 'd':
  10772. case 'H':
  10773. case 'm':
  10774. case 'M':
  10775. case 'S':
  10776. case 'W':
  10777. n++;
  10778. /* fall thru */
  10779. case 'w':
  10780. case '%':
  10781. break;
  10782. case 'f':
  10783. n += 8;
  10784. break;
  10785. case 'j':
  10786. n += 3;
  10787. break;
  10788. case 'Y':
  10789. n += 8;
  10790. break;
  10791. case 's':
  10792. case 'J':
  10793. n += 50;
  10794. break;
  10795. default:
  10796. return; /* ERROR. return a NULL */
  10797. }
  10798. i++;
  10799. }
  10800. }
  10801. testcase( n==sizeof(zBuf)-1 );
  10802. testcase( n==sizeof(zBuf) );
  10803. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  10804. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  10805. if( n<sizeof(zBuf) ){
  10806. z = zBuf;
  10807. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  10808. sqlite3_result_error_toobig(context);
  10809. return;
  10810. }else{
  10811. z = sqlite3DbMallocRaw(db, (int)n);
  10812. if( z==0 ){
  10813. sqlite3_result_error_nomem(context);
  10814. return;
  10815. }
  10816. }
  10817. computeJD(&x);
  10818. computeYMD_HMS(&x);
  10819. for(i=j=0; zFmt[i]; i++){
  10820. if( zFmt[i]!='%' ){
  10821. z[j++] = zFmt[i];
  10822. }else{
  10823. i++;
  10824. switch( zFmt[i] ){
  10825. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  10826. case 'f': {
  10827. double s = x.s;
  10828. if( s>59.999 ) s = 59.999;
  10829. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  10830. j += sqlite3Strlen30(&z[j]);
  10831. break;
  10832. }
  10833. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  10834. case 'W': /* Fall thru */
  10835. case 'j': {
  10836. int nDay; /* Number of days since 1st day of year */
  10837. DateTime y = x;
  10838. y.validJD = 0;
  10839. y.M = 1;
  10840. y.D = 1;
  10841. computeJD(&y);
  10842. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  10843. if( zFmt[i]=='W' ){
  10844. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  10845. wd = (int)(((x.iJD+43200000)/86400000)%7);
  10846. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  10847. j += 2;
  10848. }else{
  10849. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  10850. j += 3;
  10851. }
  10852. break;
  10853. }
  10854. case 'J': {
  10855. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  10856. j+=sqlite3Strlen30(&z[j]);
  10857. break;
  10858. }
  10859. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  10860. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  10861. case 's': {
  10862. sqlite3_snprintf(30,&z[j],"%lld",
  10863. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  10864. j += sqlite3Strlen30(&z[j]);
  10865. break;
  10866. }
  10867. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  10868. case 'w': {
  10869. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  10870. break;
  10871. }
  10872. case 'Y': {
  10873. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  10874. break;
  10875. }
  10876. default: z[j++] = '%'; break;
  10877. }
  10878. }
  10879. }
  10880. z[j] = 0;
  10881. sqlite3_result_text(context, z, -1,
  10882. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  10883. }
  10884. /*
  10885. ** current_time()
  10886. **
  10887. ** This function returns the same value as time('now').
  10888. */
  10889. static void ctimeFunc(
  10890. sqlite3_context *context,
  10891. int NotUsed,
  10892. sqlite3_value **NotUsed2
  10893. ){
  10894. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  10895. timeFunc(context, 0, 0);
  10896. }
  10897. /*
  10898. ** current_date()
  10899. **
  10900. ** This function returns the same value as date('now').
  10901. */
  10902. static void cdateFunc(
  10903. sqlite3_context *context,
  10904. int NotUsed,
  10905. sqlite3_value **NotUsed2
  10906. ){
  10907. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  10908. dateFunc(context, 0, 0);
  10909. }
  10910. /*
  10911. ** current_timestamp()
  10912. **
  10913. ** This function returns the same value as datetime('now').
  10914. */
  10915. static void ctimestampFunc(
  10916. sqlite3_context *context,
  10917. int NotUsed,
  10918. sqlite3_value **NotUsed2
  10919. ){
  10920. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  10921. datetimeFunc(context, 0, 0);
  10922. }
  10923. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  10924. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  10925. /*
  10926. ** If the library is compiled to omit the full-scale date and time
  10927. ** handling (to get a smaller binary), the following minimal version
  10928. ** of the functions current_time(), current_date() and current_timestamp()
  10929. ** are included instead. This is to support column declarations that
  10930. ** include "DEFAULT CURRENT_TIME" etc.
  10931. **
  10932. ** This function uses the C-library functions time(), gmtime()
  10933. ** and strftime(). The format string to pass to strftime() is supplied
  10934. ** as the user-data for the function.
  10935. */
  10936. static void currentTimeFunc(
  10937. sqlite3_context *context,
  10938. int argc,
  10939. sqlite3_value **argv
  10940. ){
  10941. time_t t;
  10942. char *zFormat = (char *)sqlite3_user_data(context);
  10943. sqlite3 *db;
  10944. double rT;
  10945. char zBuf[20];
  10946. UNUSED_PARAMETER(argc);
  10947. UNUSED_PARAMETER(argv);
  10948. db = sqlite3_context_db_handle(context);
  10949. sqlite3OsCurrentTime(db->pVfs, &rT);
  10950. #ifndef SQLITE_OMIT_FLOATING_POINT
  10951. t = 86400.0*(rT - 2440587.5) + 0.5;
  10952. #else
  10953. /* without floating point support, rT will have
  10954. ** already lost fractional day precision.
  10955. */
  10956. t = 86400 * (rT - 2440587) - 43200;
  10957. #endif
  10958. #ifdef HAVE_GMTIME_R
  10959. {
  10960. struct tm sNow;
  10961. gmtime_r(&t, &sNow);
  10962. strftime(zBuf, 20, zFormat, &sNow);
  10963. }
  10964. #else
  10965. {
  10966. struct tm *pTm;
  10967. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  10968. pTm = gmtime(&t);
  10969. strftime(zBuf, 20, zFormat, pTm);
  10970. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  10971. }
  10972. #endif
  10973. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  10974. }
  10975. #endif
  10976. /*
  10977. ** This function registered all of the above C functions as SQL
  10978. ** functions. This should be the only routine in this file with
  10979. ** external linkage.
  10980. */
  10981. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  10982. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  10983. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  10984. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  10985. FUNCTION(date, -1, 0, 0, dateFunc ),
  10986. FUNCTION(time, -1, 0, 0, timeFunc ),
  10987. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  10988. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  10989. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  10990. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  10991. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  10992. #else
  10993. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  10994. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d", 0, currentTimeFunc),
  10995. STR_FUNCTION(current_date, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  10996. #endif
  10997. };
  10998. int i;
  10999. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  11000. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  11001. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  11002. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  11003. }
  11004. }
  11005. /************** End of date.c ************************************************/
  11006. /************** Begin file os.c **********************************************/
  11007. /*
  11008. ** 2005 November 29
  11009. **
  11010. ** The author disclaims copyright to this source code. In place of
  11011. ** a legal notice, here is a blessing:
  11012. **
  11013. ** May you do good and not evil.
  11014. ** May you find forgiveness for yourself and forgive others.
  11015. ** May you share freely, never taking more than you give.
  11016. **
  11017. ******************************************************************************
  11018. **
  11019. ** This file contains OS interface code that is common to all
  11020. ** architectures.
  11021. **
  11022. ** $Id: os.c,v 1.126 2009/03/25 14:24:42 drh Exp $
  11023. */
  11024. #define _SQLITE_OS_C_ 1
  11025. #undef _SQLITE_OS_C_
  11026. /*
  11027. ** The default SQLite sqlite3_vfs implementations do not allocate
  11028. ** memory (actually, os_unix.c allocates a small amount of memory
  11029. ** from within OsOpen()), but some third-party implementations may.
  11030. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  11031. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  11032. **
  11033. ** The following functions are instrumented for malloc() failure
  11034. ** testing:
  11035. **
  11036. ** sqlite3OsOpen()
  11037. ** sqlite3OsRead()
  11038. ** sqlite3OsWrite()
  11039. ** sqlite3OsSync()
  11040. ** sqlite3OsLock()
  11041. **
  11042. */
  11043. #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
  11044. #define DO_OS_MALLOC_TEST if (1) { \
  11045. void *pTstAlloc = sqlite3Malloc(10); \
  11046. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  11047. sqlite3_free(pTstAlloc); \
  11048. }
  11049. #else
  11050. #define DO_OS_MALLOC_TEST
  11051. #endif
  11052. /*
  11053. ** The following routines are convenience wrappers around methods
  11054. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  11055. ** of this would be completely automatic if SQLite were coded using
  11056. ** C++ instead of plain old C.
  11057. */
  11058. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  11059. int rc = SQLITE_OK;
  11060. if( pId->pMethods ){
  11061. rc = pId->pMethods->xClose(pId);
  11062. pId->pMethods = 0;
  11063. }
  11064. return rc;
  11065. }
  11066. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  11067. DO_OS_MALLOC_TEST;
  11068. return id->pMethods->xRead(id, pBuf, amt, offset);
  11069. }
  11070. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  11071. DO_OS_MALLOC_TEST;
  11072. return id->pMethods->xWrite(id, pBuf, amt, offset);
  11073. }
  11074. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  11075. return id->pMethods->xTruncate(id, size);
  11076. }
  11077. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  11078. DO_OS_MALLOC_TEST;
  11079. return id->pMethods->xSync(id, flags);
  11080. }
  11081. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  11082. DO_OS_MALLOC_TEST;
  11083. return id->pMethods->xFileSize(id, pSize);
  11084. }
  11085. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  11086. DO_OS_MALLOC_TEST;
  11087. return id->pMethods->xLock(id, lockType);
  11088. }
  11089. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  11090. return id->pMethods->xUnlock(id, lockType);
  11091. }
  11092. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  11093. DO_OS_MALLOC_TEST;
  11094. return id->pMethods->xCheckReservedLock(id, pResOut);
  11095. }
  11096. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  11097. return id->pMethods->xFileControl(id, op, pArg);
  11098. }
  11099. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  11100. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  11101. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  11102. }
  11103. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  11104. return id->pMethods->xDeviceCharacteristics(id);
  11105. }
  11106. /*
  11107. ** The next group of routines are convenience wrappers around the
  11108. ** VFS methods.
  11109. */
  11110. SQLITE_PRIVATE int sqlite3OsOpen(
  11111. sqlite3_vfs *pVfs,
  11112. const char *zPath,
  11113. sqlite3_file *pFile,
  11114. int flags,
  11115. int *pFlagsOut
  11116. ){
  11117. int rc;
  11118. DO_OS_MALLOC_TEST;
  11119. rc = pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
  11120. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  11121. return rc;
  11122. }
  11123. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  11124. return pVfs->xDelete(pVfs, zPath, dirSync);
  11125. }
  11126. SQLITE_PRIVATE int sqlite3OsAccess(
  11127. sqlite3_vfs *pVfs,
  11128. const char *zPath,
  11129. int flags,
  11130. int *pResOut
  11131. ){
  11132. DO_OS_MALLOC_TEST;
  11133. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  11134. }
  11135. SQLITE_PRIVATE int sqlite3OsFullPathname(
  11136. sqlite3_vfs *pVfs,
  11137. const char *zPath,
  11138. int nPathOut,
  11139. char *zPathOut
  11140. ){
  11141. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  11142. }
  11143. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11144. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  11145. return pVfs->xDlOpen(pVfs, zPath);
  11146. }
  11147. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  11148. pVfs->xDlError(pVfs, nByte, zBufOut);
  11149. }
  11150. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  11151. return pVfs->xDlSym(pVfs, pHdle, zSym);
  11152. }
  11153. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  11154. pVfs->xDlClose(pVfs, pHandle);
  11155. }
  11156. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  11157. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  11158. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  11159. }
  11160. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  11161. return pVfs->xSleep(pVfs, nMicro);
  11162. }
  11163. SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  11164. return pVfs->xCurrentTime(pVfs, pTimeOut);
  11165. }
  11166. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  11167. sqlite3_vfs *pVfs,
  11168. const char *zFile,
  11169. sqlite3_file **ppFile,
  11170. int flags,
  11171. int *pOutFlags
  11172. ){
  11173. int rc = SQLITE_NOMEM;
  11174. sqlite3_file *pFile;
  11175. pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
  11176. if( pFile ){
  11177. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  11178. if( rc!=SQLITE_OK ){
  11179. sqlite3_free(pFile);
  11180. }else{
  11181. *ppFile = pFile;
  11182. }
  11183. }
  11184. return rc;
  11185. }
  11186. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  11187. int rc = SQLITE_OK;
  11188. assert( pFile );
  11189. rc = sqlite3OsClose(pFile);
  11190. sqlite3_free(pFile);
  11191. return rc;
  11192. }
  11193. /*
  11194. ** The list of all registered VFS implementations.
  11195. */
  11196. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  11197. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  11198. /*
  11199. ** Locate a VFS by name. If no name is given, simply return the
  11200. ** first VFS on the list.
  11201. */
  11202. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  11203. sqlite3_vfs *pVfs = 0;
  11204. #if SQLITE_THREADSAFE
  11205. sqlite3_mutex *mutex;
  11206. #endif
  11207. #ifndef SQLITE_OMIT_AUTOINIT
  11208. int rc = sqlite3_initialize();
  11209. if( rc ) return 0;
  11210. #endif
  11211. #if SQLITE_THREADSAFE
  11212. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  11213. #endif
  11214. sqlite3_mutex_enter(mutex);
  11215. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  11216. if( zVfs==0 ) break;
  11217. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  11218. }
  11219. sqlite3_mutex_leave(mutex);
  11220. return pVfs;
  11221. }
  11222. /*
  11223. ** Unlink a VFS from the linked list
  11224. */
  11225. static void vfsUnlink(sqlite3_vfs *pVfs){
  11226. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  11227. if( pVfs==0 ){
  11228. /* No-op */
  11229. }else if( vfsList==pVfs ){
  11230. vfsList = pVfs->pNext;
  11231. }else if( vfsList ){
  11232. sqlite3_vfs *p = vfsList;
  11233. while( p->pNext && p->pNext!=pVfs ){
  11234. p = p->pNext;
  11235. }
  11236. if( p->pNext==pVfs ){
  11237. p->pNext = pVfs->pNext;
  11238. }
  11239. }
  11240. }
  11241. /*
  11242. ** Register a VFS with the system. It is harmless to register the same
  11243. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  11244. ** true.
  11245. */
  11246. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  11247. sqlite3_mutex *mutex = 0;
  11248. #ifndef SQLITE_OMIT_AUTOINIT
  11249. int rc = sqlite3_initialize();
  11250. if( rc ) return rc;
  11251. #endif
  11252. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  11253. sqlite3_mutex_enter(mutex);
  11254. vfsUnlink(pVfs);
  11255. if( makeDflt || vfsList==0 ){
  11256. pVfs->pNext = vfsList;
  11257. vfsList = pVfs;
  11258. }else{
  11259. pVfs->pNext = vfsList->pNext;
  11260. vfsList->pNext = pVfs;
  11261. }
  11262. assert(vfsList);
  11263. sqlite3_mutex_leave(mutex);
  11264. return SQLITE_OK;
  11265. }
  11266. /*
  11267. ** Unregister a VFS so that it is no longer accessible.
  11268. */
  11269. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  11270. #if SQLITE_THREADSAFE
  11271. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  11272. #endif
  11273. sqlite3_mutex_enter(mutex);
  11274. vfsUnlink(pVfs);
  11275. sqlite3_mutex_leave(mutex);
  11276. return SQLITE_OK;
  11277. }
  11278. /************** End of os.c **************************************************/
  11279. /************** Begin file fault.c *******************************************/
  11280. /*
  11281. ** 2008 Jan 22
  11282. **
  11283. ** The author disclaims copyright to this source code. In place of
  11284. ** a legal notice, here is a blessing:
  11285. **
  11286. ** May you do good and not evil.
  11287. ** May you find forgiveness for yourself and forgive others.
  11288. ** May you share freely, never taking more than you give.
  11289. **
  11290. *************************************************************************
  11291. **
  11292. ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
  11293. */
  11294. /*
  11295. ** This file contains code to support the concept of "benign"
  11296. ** malloc failures (when the xMalloc() or xRealloc() method of the
  11297. ** sqlite3_mem_methods structure fails to allocate a block of memory
  11298. ** and returns 0).
  11299. **
  11300. ** Most malloc failures are non-benign. After they occur, SQLite
  11301. ** abandons the current operation and returns an error code (usually
  11302. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  11303. ** fatal. For example, if a malloc fails while resizing a hash table, this
  11304. ** is completely recoverable simply by not carrying out the resize. The
  11305. ** hash table will continue to function normally. So a malloc failure
  11306. ** during a hash table resize is a benign fault.
  11307. */
  11308. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11309. /*
  11310. ** Global variables.
  11311. */
  11312. typedef struct BenignMallocHooks BenignMallocHooks;
  11313. static SQLITE_WSD struct BenignMallocHooks {
  11314. void (*xBenignBegin)(void);
  11315. void (*xBenignEnd)(void);
  11316. } sqlite3Hooks = { 0, 0 };
  11317. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  11318. ** structure. If writable static data is unsupported on the target,
  11319. ** we have to locate the state vector at run-time. In the more common
  11320. ** case where writable static data is supported, wsdHooks can refer directly
  11321. ** to the "sqlite3Hooks" state vector declared above.
  11322. */
  11323. #ifdef SQLITE_OMIT_WSD
  11324. # define wsdHooksInit \
  11325. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  11326. # define wsdHooks x[0]
  11327. #else
  11328. # define wsdHooksInit
  11329. # define wsdHooks sqlite3Hooks
  11330. #endif
  11331. /*
  11332. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  11333. ** sqlite3EndBenignMalloc() are called, respectively.
  11334. */
  11335. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  11336. void (*xBenignBegin)(void),
  11337. void (*xBenignEnd)(void)
  11338. ){
  11339. wsdHooksInit;
  11340. wsdHooks.xBenignBegin = xBenignBegin;
  11341. wsdHooks.xBenignEnd = xBenignEnd;
  11342. }
  11343. /*
  11344. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  11345. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  11346. ** indicates that subsequent malloc failures are non-benign.
  11347. */
  11348. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  11349. wsdHooksInit;
  11350. if( wsdHooks.xBenignBegin ){
  11351. wsdHooks.xBenignBegin();
  11352. }
  11353. }
  11354. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  11355. wsdHooksInit;
  11356. if( wsdHooks.xBenignEnd ){
  11357. wsdHooks.xBenignEnd();
  11358. }
  11359. }
  11360. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  11361. /************** End of fault.c ***********************************************/
  11362. /************** Begin file mem0.c ********************************************/
  11363. /*
  11364. ** 2008 October 28
  11365. **
  11366. ** The author disclaims copyright to this source code. In place of
  11367. ** a legal notice, here is a blessing:
  11368. **
  11369. ** May you do good and not evil.
  11370. ** May you find forgiveness for yourself and forgive others.
  11371. ** May you share freely, never taking more than you give.
  11372. **
  11373. *************************************************************************
  11374. **
  11375. ** This file contains a no-op memory allocation drivers for use when
  11376. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  11377. ** here always fail. SQLite will not operate with these drivers. These
  11378. ** are merely placeholders. Real drivers must be substituted using
  11379. ** sqlite3_config() before SQLite will operate.
  11380. **
  11381. ** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $
  11382. */
  11383. /*
  11384. ** This version of the memory allocator is the default. It is
  11385. ** used when no other memory allocator is specified using compile-time
  11386. ** macros.
  11387. */
  11388. #ifdef SQLITE_ZERO_MALLOC
  11389. /*
  11390. ** No-op versions of all memory allocation routines
  11391. */
  11392. static void *sqlite3MemMalloc(int nByte){ return 0; }
  11393. static void sqlite3MemFree(void *pPrior){ return; }
  11394. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  11395. static int sqlite3MemSize(void *pPrior){ return 0; }
  11396. static int sqlite3MemRoundup(int n){ return n; }
  11397. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  11398. static void sqlite3MemShutdown(void *NotUsed){ return; }
  11399. /*
  11400. ** This routine is the only routine in this file with external linkage.
  11401. **
  11402. ** Populate the low-level memory allocation function pointers in
  11403. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  11404. */
  11405. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  11406. static const sqlite3_mem_methods defaultMethods = {
  11407. sqlite3MemMalloc,
  11408. sqlite3MemFree,
  11409. sqlite3MemRealloc,
  11410. sqlite3MemSize,
  11411. sqlite3MemRoundup,
  11412. sqlite3MemInit,
  11413. sqlite3MemShutdown,
  11414. 0
  11415. };
  11416. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  11417. }
  11418. #endif /* SQLITE_ZERO_MALLOC */
  11419. /************** End of mem0.c ************************************************/
  11420. /************** Begin file mem1.c ********************************************/
  11421. /*
  11422. ** 2007 August 14
  11423. **
  11424. ** The author disclaims copyright to this source code. In place of
  11425. ** a legal notice, here is a blessing:
  11426. **
  11427. ** May you do good and not evil.
  11428. ** May you find forgiveness for yourself and forgive others.
  11429. ** May you share freely, never taking more than you give.
  11430. **
  11431. *************************************************************************
  11432. **
  11433. ** This file contains low-level memory allocation drivers for when
  11434. ** SQLite will use the standard C-library malloc/realloc/free interface
  11435. ** to obtain the memory it needs.
  11436. **
  11437. ** This file contains implementations of the low-level memory allocation
  11438. ** routines specified in the sqlite3_mem_methods object.
  11439. **
  11440. ** $Id: mem1.c,v 1.30 2009/03/23 04:33:33 danielk1977 Exp $
  11441. */
  11442. /*
  11443. ** This version of the memory allocator is the default. It is
  11444. ** used when no other memory allocator is specified using compile-time
  11445. ** macros.
  11446. */
  11447. #ifdef SQLITE_SYSTEM_MALLOC
  11448. /*
  11449. ** Like malloc(), but remember the size of the allocation
  11450. ** so that we can find it later using sqlite3MemSize().
  11451. **
  11452. ** For this low-level routine, we are guaranteed that nByte>0 because
  11453. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  11454. ** routines.
  11455. */
  11456. static void *sqlite3MemMalloc(int nByte){
  11457. sqlite3_int64 *p;
  11458. assert( nByte>0 );
  11459. nByte = ROUND8(nByte);
  11460. p = malloc( nByte+8 );
  11461. if( p ){
  11462. p[0] = nByte;
  11463. p++;
  11464. }
  11465. return (void *)p;
  11466. }
  11467. /*
  11468. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  11469. ** or sqlite3MemRealloc().
  11470. **
  11471. ** For this low-level routine, we already know that pPrior!=0 since
  11472. ** cases where pPrior==0 will have been intecepted and dealt with
  11473. ** by higher-level routines.
  11474. */
  11475. static void sqlite3MemFree(void *pPrior){
  11476. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  11477. assert( pPrior!=0 );
  11478. p--;
  11479. free(p);
  11480. }
  11481. /*
  11482. ** Like realloc(). Resize an allocation previously obtained from
  11483. ** sqlite3MemMalloc().
  11484. **
  11485. ** For this low-level interface, we know that pPrior!=0. Cases where
  11486. ** pPrior==0 while have been intercepted by higher-level routine and
  11487. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  11488. ** cases where nByte<=0 will have been intercepted by higher-level
  11489. ** routines and redirected to xFree.
  11490. */
  11491. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  11492. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  11493. assert( pPrior!=0 && nByte>0 );
  11494. nByte = ROUND8(nByte);
  11495. p = (sqlite3_int64*)pPrior;
  11496. p--;
  11497. p = realloc(p, nByte+8 );
  11498. if( p ){
  11499. p[0] = nByte;
  11500. p++;
  11501. }
  11502. return (void*)p;
  11503. }
  11504. /*
  11505. ** Report the allocated size of a prior return from xMalloc()
  11506. ** or xRealloc().
  11507. */
  11508. static int sqlite3MemSize(void *pPrior){
  11509. sqlite3_int64 *p;
  11510. if( pPrior==0 ) return 0;
  11511. p = (sqlite3_int64*)pPrior;
  11512. p--;
  11513. return (int)p[0];
  11514. }
  11515. /*
  11516. ** Round up a request size to the next valid allocation size.
  11517. */
  11518. static int sqlite3MemRoundup(int n){
  11519. return ROUND8(n);
  11520. }
  11521. /*
  11522. ** Initialize this module.
  11523. */
  11524. static int sqlite3MemInit(void *NotUsed){
  11525. UNUSED_PARAMETER(NotUsed);
  11526. return SQLITE_OK;
  11527. }
  11528. /*
  11529. ** Deinitialize this module.
  11530. */
  11531. static void sqlite3MemShutdown(void *NotUsed){
  11532. UNUSED_PARAMETER(NotUsed);
  11533. return;
  11534. }
  11535. /*
  11536. ** This routine is the only routine in this file with external linkage.
  11537. **
  11538. ** Populate the low-level memory allocation function pointers in
  11539. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  11540. */
  11541. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  11542. static const sqlite3_mem_methods defaultMethods = {
  11543. sqlite3MemMalloc,
  11544. sqlite3MemFree,
  11545. sqlite3MemRealloc,
  11546. sqlite3MemSize,
  11547. sqlite3MemRoundup,
  11548. sqlite3MemInit,
  11549. sqlite3MemShutdown,
  11550. 0
  11551. };
  11552. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  11553. }
  11554. #endif /* SQLITE_SYSTEM_MALLOC */
  11555. /************** End of mem1.c ************************************************/
  11556. /************** Begin file mem2.c ********************************************/
  11557. /*
  11558. ** 2007 August 15
  11559. **
  11560. ** The author disclaims copyright to this source code. In place of
  11561. ** a legal notice, here is a blessing:
  11562. **
  11563. ** May you do good and not evil.
  11564. ** May you find forgiveness for yourself and forgive others.
  11565. ** May you share freely, never taking more than you give.
  11566. **
  11567. *************************************************************************
  11568. **
  11569. ** This file contains low-level memory allocation drivers for when
  11570. ** SQLite will use the standard C-library malloc/realloc/free interface
  11571. ** to obtain the memory it needs while adding lots of additional debugging
  11572. ** information to each allocation in order to help detect and fix memory
  11573. ** leaks and memory usage errors.
  11574. **
  11575. ** This file contains implementations of the low-level memory allocation
  11576. ** routines specified in the sqlite3_mem_methods object.
  11577. **
  11578. ** $Id: mem2.c,v 1.45 2009/03/23 04:33:33 danielk1977 Exp $
  11579. */
  11580. /*
  11581. ** This version of the memory allocator is used only if the
  11582. ** SQLITE_MEMDEBUG macro is defined
  11583. */
  11584. #ifdef SQLITE_MEMDEBUG
  11585. /*
  11586. ** The backtrace functionality is only available with GLIBC
  11587. */
  11588. #ifdef __GLIBC__
  11589. extern int backtrace(void**,int);
  11590. extern void backtrace_symbols_fd(void*const*,int,int);
  11591. #else
  11592. # define backtrace(A,B) 1
  11593. # define backtrace_symbols_fd(A,B,C)
  11594. #endif
  11595. /*
  11596. ** Each memory allocation looks like this:
  11597. **
  11598. ** ------------------------------------------------------------------------
  11599. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  11600. ** ------------------------------------------------------------------------
  11601. **
  11602. ** The application code sees only a pointer to the allocation. We have
  11603. ** to back up from the allocation pointer to find the MemBlockHdr. The
  11604. ** MemBlockHdr tells us the size of the allocation and the number of
  11605. ** backtrace pointers. There is also a guard word at the end of the
  11606. ** MemBlockHdr.
  11607. */
  11608. struct MemBlockHdr {
  11609. i64 iSize; /* Size of this allocation */
  11610. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  11611. char nBacktrace; /* Number of backtraces on this alloc */
  11612. char nBacktraceSlots; /* Available backtrace slots */
  11613. short nTitle; /* Bytes of title; includes '\0' */
  11614. int iForeGuard; /* Guard word for sanity */
  11615. };
  11616. /*
  11617. ** Guard words
  11618. */
  11619. #define FOREGUARD 0x80F5E153
  11620. #define REARGUARD 0xE4676B53
  11621. /*
  11622. ** Number of malloc size increments to track.
  11623. */
  11624. #define NCSIZE 1000
  11625. /*
  11626. ** All of the static variables used by this module are collected
  11627. ** into a single structure named "mem". This is to keep the
  11628. ** static variables organized and to reduce namespace pollution
  11629. ** when this module is combined with other in the amalgamation.
  11630. */
  11631. static struct {
  11632. /*
  11633. ** Mutex to control access to the memory allocation subsystem.
  11634. */
  11635. sqlite3_mutex *mutex;
  11636. /*
  11637. ** Head and tail of a linked list of all outstanding allocations
  11638. */
  11639. struct MemBlockHdr *pFirst;
  11640. struct MemBlockHdr *pLast;
  11641. /*
  11642. ** The number of levels of backtrace to save in new allocations.
  11643. */
  11644. int nBacktrace;
  11645. void (*xBacktrace)(int, int, void **);
  11646. /*
  11647. ** Title text to insert in front of each block
  11648. */
  11649. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  11650. char zTitle[100]; /* The title text */
  11651. /*
  11652. ** sqlite3MallocDisallow() increments the following counter.
  11653. ** sqlite3MallocAllow() decrements it.
  11654. */
  11655. int disallow; /* Do not allow memory allocation */
  11656. /*
  11657. ** Gather statistics on the sizes of memory allocations.
  11658. ** nAlloc[i] is the number of allocation attempts of i*8
  11659. ** bytes. i==NCSIZE is the number of allocation attempts for
  11660. ** sizes more than NCSIZE*8 bytes.
  11661. */
  11662. int nAlloc[NCSIZE]; /* Total number of allocations */
  11663. int nCurrent[NCSIZE]; /* Current number of allocations */
  11664. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  11665. } mem;
  11666. /*
  11667. ** Adjust memory usage statistics
  11668. */
  11669. static void adjustStats(int iSize, int increment){
  11670. int i = ROUND8(iSize)/8;
  11671. if( i>NCSIZE-1 ){
  11672. i = NCSIZE - 1;
  11673. }
  11674. if( increment>0 ){
  11675. mem.nAlloc[i]++;
  11676. mem.nCurrent[i]++;
  11677. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  11678. mem.mxCurrent[i] = mem.nCurrent[i];
  11679. }
  11680. }else{
  11681. mem.nCurrent[i]--;
  11682. assert( mem.nCurrent[i]>=0 );
  11683. }
  11684. }
  11685. /*
  11686. ** Given an allocation, find the MemBlockHdr for that allocation.
  11687. **
  11688. ** This routine checks the guards at either end of the allocation and
  11689. ** if they are incorrect it asserts.
  11690. */
  11691. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  11692. struct MemBlockHdr *p;
  11693. int *pInt;
  11694. u8 *pU8;
  11695. int nReserve;
  11696. p = (struct MemBlockHdr*)pAllocation;
  11697. p--;
  11698. assert( p->iForeGuard==(int)FOREGUARD );
  11699. nReserve = ROUND8(p->iSize);
  11700. pInt = (int*)pAllocation;
  11701. pU8 = (u8*)pAllocation;
  11702. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  11703. /* This checks any of the "extra" bytes allocated due
  11704. ** to rounding up to an 8 byte boundary to ensure
  11705. ** they haven't been overwritten.
  11706. */
  11707. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  11708. return p;
  11709. }
  11710. /*
  11711. ** Return the number of bytes currently allocated at address p.
  11712. */
  11713. static int sqlite3MemSize(void *p){
  11714. struct MemBlockHdr *pHdr;
  11715. if( !p ){
  11716. return 0;
  11717. }
  11718. pHdr = sqlite3MemsysGetHeader(p);
  11719. return pHdr->iSize;
  11720. }
  11721. /*
  11722. ** Initialize the memory allocation subsystem.
  11723. */
  11724. static int sqlite3MemInit(void *NotUsed){
  11725. UNUSED_PARAMETER(NotUsed);
  11726. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  11727. if( !sqlite3GlobalConfig.bMemstat ){
  11728. /* If memory status is enabled, then the malloc.c wrapper will already
  11729. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  11730. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  11731. }
  11732. return SQLITE_OK;
  11733. }
  11734. /*
  11735. ** Deinitialize the memory allocation subsystem.
  11736. */
  11737. static void sqlite3MemShutdown(void *NotUsed){
  11738. UNUSED_PARAMETER(NotUsed);
  11739. mem.mutex = 0;
  11740. }
  11741. /*
  11742. ** Round up a request size to the next valid allocation size.
  11743. */
  11744. static int sqlite3MemRoundup(int n){
  11745. return ROUND8(n);
  11746. }
  11747. /*
  11748. ** Allocate nByte bytes of memory.
  11749. */
  11750. static void *sqlite3MemMalloc(int nByte){
  11751. struct MemBlockHdr *pHdr;
  11752. void **pBt;
  11753. char *z;
  11754. int *pInt;
  11755. void *p = 0;
  11756. int totalSize;
  11757. int nReserve;
  11758. sqlite3_mutex_enter(mem.mutex);
  11759. assert( mem.disallow==0 );
  11760. nReserve = ROUND8(nByte);
  11761. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  11762. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  11763. p = malloc(totalSize);
  11764. if( p ){
  11765. z = p;
  11766. pBt = (void**)&z[mem.nTitle];
  11767. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  11768. pHdr->pNext = 0;
  11769. pHdr->pPrev = mem.pLast;
  11770. if( mem.pLast ){
  11771. mem.pLast->pNext = pHdr;
  11772. }else{
  11773. mem.pFirst = pHdr;
  11774. }
  11775. mem.pLast = pHdr;
  11776. pHdr->iForeGuard = FOREGUARD;
  11777. pHdr->nBacktraceSlots = mem.nBacktrace;
  11778. pHdr->nTitle = mem.nTitle;
  11779. if( mem.nBacktrace ){
  11780. void *aAddr[40];
  11781. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  11782. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  11783. assert(pBt[0]);
  11784. if( mem.xBacktrace ){
  11785. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  11786. }
  11787. }else{
  11788. pHdr->nBacktrace = 0;
  11789. }
  11790. if( mem.nTitle ){
  11791. memcpy(z, mem.zTitle, mem.nTitle);
  11792. }
  11793. pHdr->iSize = nByte;
  11794. adjustStats(nByte, +1);
  11795. pInt = (int*)&pHdr[1];
  11796. pInt[nReserve/sizeof(int)] = REARGUARD;
  11797. memset(pInt, 0x65, nReserve);
  11798. p = (void*)pInt;
  11799. }
  11800. sqlite3_mutex_leave(mem.mutex);
  11801. return p;
  11802. }
  11803. /*
  11804. ** Free memory.
  11805. */
  11806. static void sqlite3MemFree(void *pPrior){
  11807. struct MemBlockHdr *pHdr;
  11808. void **pBt;
  11809. char *z;
  11810. assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
  11811. pHdr = sqlite3MemsysGetHeader(pPrior);
  11812. pBt = (void**)pHdr;
  11813. pBt -= pHdr->nBacktraceSlots;
  11814. sqlite3_mutex_enter(mem.mutex);
  11815. if( pHdr->pPrev ){
  11816. assert( pHdr->pPrev->pNext==pHdr );
  11817. pHdr->pPrev->pNext = pHdr->pNext;
  11818. }else{
  11819. assert( mem.pFirst==pHdr );
  11820. mem.pFirst = pHdr->pNext;
  11821. }
  11822. if( pHdr->pNext ){
  11823. assert( pHdr->pNext->pPrev==pHdr );
  11824. pHdr->pNext->pPrev = pHdr->pPrev;
  11825. }else{
  11826. assert( mem.pLast==pHdr );
  11827. mem.pLast = pHdr->pPrev;
  11828. }
  11829. z = (char*)pBt;
  11830. z -= pHdr->nTitle;
  11831. adjustStats(pHdr->iSize, -1);
  11832. memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  11833. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  11834. free(z);
  11835. sqlite3_mutex_leave(mem.mutex);
  11836. }
  11837. /*
  11838. ** Change the size of an existing memory allocation.
  11839. **
  11840. ** For this debugging implementation, we *always* make a copy of the
  11841. ** allocation into a new place in memory. In this way, if the
  11842. ** higher level code is using pointer to the old allocation, it is
  11843. ** much more likely to break and we are much more liking to find
  11844. ** the error.
  11845. */
  11846. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  11847. struct MemBlockHdr *pOldHdr;
  11848. void *pNew;
  11849. assert( mem.disallow==0 );
  11850. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  11851. pNew = sqlite3MemMalloc(nByte);
  11852. if( pNew ){
  11853. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  11854. if( nByte>pOldHdr->iSize ){
  11855. memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
  11856. }
  11857. sqlite3MemFree(pPrior);
  11858. }
  11859. return pNew;
  11860. }
  11861. /*
  11862. ** Populate the low-level memory allocation function pointers in
  11863. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  11864. */
  11865. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  11866. static const sqlite3_mem_methods defaultMethods = {
  11867. sqlite3MemMalloc,
  11868. sqlite3MemFree,
  11869. sqlite3MemRealloc,
  11870. sqlite3MemSize,
  11871. sqlite3MemRoundup,
  11872. sqlite3MemInit,
  11873. sqlite3MemShutdown,
  11874. 0
  11875. };
  11876. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  11877. }
  11878. /*
  11879. ** Set the number of backtrace levels kept for each allocation.
  11880. ** A value of zero turns off backtracing. The number is always rounded
  11881. ** up to a multiple of 2.
  11882. */
  11883. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  11884. if( depth<0 ){ depth = 0; }
  11885. if( depth>20 ){ depth = 20; }
  11886. depth = (depth+1)&0xfe;
  11887. mem.nBacktrace = depth;
  11888. }
  11889. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  11890. mem.xBacktrace = xBacktrace;
  11891. }
  11892. /*
  11893. ** Set the title string for subsequent allocations.
  11894. */
  11895. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  11896. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  11897. sqlite3_mutex_enter(mem.mutex);
  11898. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  11899. memcpy(mem.zTitle, zTitle, n);
  11900. mem.zTitle[n] = 0;
  11901. mem.nTitle = ROUND8(n);
  11902. sqlite3_mutex_leave(mem.mutex);
  11903. }
  11904. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  11905. struct MemBlockHdr *pHdr;
  11906. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  11907. void **pBt = (void**)pHdr;
  11908. pBt -= pHdr->nBacktraceSlots;
  11909. mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  11910. }
  11911. }
  11912. /*
  11913. ** Open the file indicated and write a log of all unfreed memory
  11914. ** allocations into that log.
  11915. */
  11916. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  11917. FILE *out;
  11918. struct MemBlockHdr *pHdr;
  11919. void **pBt;
  11920. int i;
  11921. out = fopen(zFilename, "w");
  11922. if( out==0 ){
  11923. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  11924. zFilename);
  11925. return;
  11926. }
  11927. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  11928. char *z = (char*)pHdr;
  11929. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  11930. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  11931. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  11932. if( pHdr->nBacktrace ){
  11933. fflush(out);
  11934. pBt = (void**)pHdr;
  11935. pBt -= pHdr->nBacktraceSlots;
  11936. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  11937. fprintf(out, "\n");
  11938. }
  11939. }
  11940. fprintf(out, "COUNTS:\n");
  11941. for(i=0; i<NCSIZE-1; i++){
  11942. if( mem.nAlloc[i] ){
  11943. fprintf(out, " %5d: %10d %10d %10d\n",
  11944. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  11945. }
  11946. }
  11947. if( mem.nAlloc[NCSIZE-1] ){
  11948. fprintf(out, " %5d: %10d %10d %10d\n",
  11949. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  11950. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  11951. }
  11952. fclose(out);
  11953. }
  11954. /*
  11955. ** Return the number of times sqlite3MemMalloc() has been called.
  11956. */
  11957. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  11958. int i;
  11959. int nTotal = 0;
  11960. for(i=0; i<NCSIZE; i++){
  11961. nTotal += mem.nAlloc[i];
  11962. }
  11963. return nTotal;
  11964. }
  11965. #endif /* SQLITE_MEMDEBUG */
  11966. /************** End of mem2.c ************************************************/
  11967. /************** Begin file mem3.c ********************************************/
  11968. /*
  11969. ** 2007 October 14
  11970. **
  11971. ** The author disclaims copyright to this source code. In place of
  11972. ** a legal notice, here is a blessing:
  11973. **
  11974. ** May you do good and not evil.
  11975. ** May you find forgiveness for yourself and forgive others.
  11976. ** May you share freely, never taking more than you give.
  11977. **
  11978. *************************************************************************
  11979. ** This file contains the C functions that implement a memory
  11980. ** allocation subsystem for use by SQLite.
  11981. **
  11982. ** This version of the memory allocation subsystem omits all
  11983. ** use of malloc(). The SQLite user supplies a block of memory
  11984. ** before calling sqlite3_initialize() from which allocations
  11985. ** are made and returned by the xMalloc() and xRealloc()
  11986. ** implementations. Once sqlite3_initialize() has been called,
  11987. ** the amount of memory available to SQLite is fixed and cannot
  11988. ** be changed.
  11989. **
  11990. ** This version of the memory allocation subsystem is included
  11991. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  11992. **
  11993. ** $Id: mem3.c,v 1.25 2008/11/19 16:52:44 danielk1977 Exp $
  11994. */
  11995. /*
  11996. ** This version of the memory allocator is only built into the library
  11997. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  11998. ** mean that the library will use a memory-pool by default, just that
  11999. ** it is available. The mempool allocator is activated by calling
  12000. ** sqlite3_config().
  12001. */
  12002. #ifdef SQLITE_ENABLE_MEMSYS3
  12003. /*
  12004. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  12005. */
  12006. #define MX_SMALL 10
  12007. /*
  12008. ** Number of freelist hash slots
  12009. */
  12010. #define N_HASH 61
  12011. /*
  12012. ** A memory allocation (also called a "chunk") consists of two or
  12013. ** more blocks where each block is 8 bytes. The first 8 bytes are
  12014. ** a header that is not returned to the user.
  12015. **
  12016. ** A chunk is two or more blocks that is either checked out or
  12017. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  12018. ** size of the allocation in blocks if the allocation is free.
  12019. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  12020. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  12021. ** is true if the previous chunk is checked out and false if the
  12022. ** previous chunk is free. The u.hdr.prevSize field is the size of
  12023. ** the previous chunk in blocks if the previous chunk is on the
  12024. ** freelist. If the previous chunk is checked out, then
  12025. ** u.hdr.prevSize can be part of the data for that chunk and should
  12026. ** not be read or written.
  12027. **
  12028. ** We often identify a chunk by its index in mem3.aPool[]. When
  12029. ** this is done, the chunk index refers to the second block of
  12030. ** the chunk. In this way, the first chunk has an index of 1.
  12031. ** A chunk index of 0 means "no such chunk" and is the equivalent
  12032. ** of a NULL pointer.
  12033. **
  12034. ** The second block of free chunks is of the form u.list. The
  12035. ** two fields form a double-linked list of chunks of related sizes.
  12036. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  12037. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  12038. **
  12039. ** The second block of a chunk is user data if the chunk is checked
  12040. ** out. If a chunk is checked out, the user data may extend into
  12041. ** the u.hdr.prevSize value of the following chunk.
  12042. */
  12043. typedef struct Mem3Block Mem3Block;
  12044. struct Mem3Block {
  12045. union {
  12046. struct {
  12047. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  12048. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  12049. } hdr;
  12050. struct {
  12051. u32 next; /* Index in mem3.aPool[] of next free chunk */
  12052. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  12053. } list;
  12054. } u;
  12055. };
  12056. /*
  12057. ** All of the static variables used by this module are collected
  12058. ** into a single structure named "mem3". This is to keep the
  12059. ** static variables organized and to reduce namespace pollution
  12060. ** when this module is combined with other in the amalgamation.
  12061. */
  12062. static SQLITE_WSD struct Mem3Global {
  12063. /*
  12064. ** Memory available for allocation. nPool is the size of the array
  12065. ** (in Mem3Blocks) pointed to by aPool less 2.
  12066. */
  12067. u32 nPool;
  12068. Mem3Block *aPool;
  12069. /*
  12070. ** True if we are evaluating an out-of-memory callback.
  12071. */
  12072. int alarmBusy;
  12073. /*
  12074. ** Mutex to control access to the memory allocation subsystem.
  12075. */
  12076. sqlite3_mutex *mutex;
  12077. /*
  12078. ** The minimum amount of free space that we have seen.
  12079. */
  12080. u32 mnMaster;
  12081. /*
  12082. ** iMaster is the index of the master chunk. Most new allocations
  12083. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  12084. ** of the current master. iMaster is 0 if there is not master chunk.
  12085. ** The master chunk is not in either the aiHash[] or aiSmall[].
  12086. */
  12087. u32 iMaster;
  12088. u32 szMaster;
  12089. /*
  12090. ** Array of lists of free blocks according to the block size
  12091. ** for smaller chunks, or a hash on the block size for larger
  12092. ** chunks.
  12093. */
  12094. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  12095. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  12096. } mem3 = { 97535575 };
  12097. #define mem3 GLOBAL(struct Mem3Global, mem3)
  12098. /*
  12099. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  12100. ** on. *pRoot is the list that i is a member of.
  12101. */
  12102. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  12103. u32 next = mem3.aPool[i].u.list.next;
  12104. u32 prev = mem3.aPool[i].u.list.prev;
  12105. assert( sqlite3_mutex_held(mem3.mutex) );
  12106. if( prev==0 ){
  12107. *pRoot = next;
  12108. }else{
  12109. mem3.aPool[prev].u.list.next = next;
  12110. }
  12111. if( next ){
  12112. mem3.aPool[next].u.list.prev = prev;
  12113. }
  12114. mem3.aPool[i].u.list.next = 0;
  12115. mem3.aPool[i].u.list.prev = 0;
  12116. }
  12117. /*
  12118. ** Unlink the chunk at index i from
  12119. ** whatever list is currently a member of.
  12120. */
  12121. static void memsys3Unlink(u32 i){
  12122. u32 size, hash;
  12123. assert( sqlite3_mutex_held(mem3.mutex) );
  12124. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  12125. assert( i>=1 );
  12126. size = mem3.aPool[i-1].u.hdr.size4x/4;
  12127. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  12128. assert( size>=2 );
  12129. if( size <= MX_SMALL ){
  12130. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  12131. }else{
  12132. hash = size % N_HASH;
  12133. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  12134. }
  12135. }
  12136. /*
  12137. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  12138. ** at *pRoot.
  12139. */
  12140. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  12141. assert( sqlite3_mutex_held(mem3.mutex) );
  12142. mem3.aPool[i].u.list.next = *pRoot;
  12143. mem3.aPool[i].u.list.prev = 0;
  12144. if( *pRoot ){
  12145. mem3.aPool[*pRoot].u.list.prev = i;
  12146. }
  12147. *pRoot = i;
  12148. }
  12149. /*
  12150. ** Link the chunk at index i into either the appropriate
  12151. ** small chunk list, or into the large chunk hash table.
  12152. */
  12153. static void memsys3Link(u32 i){
  12154. u32 size, hash;
  12155. assert( sqlite3_mutex_held(mem3.mutex) );
  12156. assert( i>=1 );
  12157. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  12158. size = mem3.aPool[i-1].u.hdr.size4x/4;
  12159. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  12160. assert( size>=2 );
  12161. if( size <= MX_SMALL ){
  12162. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  12163. }else{
  12164. hash = size % N_HASH;
  12165. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  12166. }
  12167. }
  12168. /*
  12169. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  12170. ** will already be held (obtained by code in malloc.c) if
  12171. ** sqlite3GlobalConfig.bMemStat is true.
  12172. */
  12173. static void memsys3Enter(void){
  12174. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  12175. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  12176. }
  12177. sqlite3_mutex_enter(mem3.mutex);
  12178. }
  12179. static void memsys3Leave(void){
  12180. sqlite3_mutex_leave(mem3.mutex);
  12181. }
  12182. /*
  12183. ** Called when we are unable to satisfy an allocation of nBytes.
  12184. */
  12185. static void memsys3OutOfMemory(int nByte){
  12186. if( !mem3.alarmBusy ){
  12187. mem3.alarmBusy = 1;
  12188. assert( sqlite3_mutex_held(mem3.mutex) );
  12189. sqlite3_mutex_leave(mem3.mutex);
  12190. sqlite3_release_memory(nByte);
  12191. sqlite3_mutex_enter(mem3.mutex);
  12192. mem3.alarmBusy = 0;
  12193. }
  12194. }
  12195. /*
  12196. ** Chunk i is a free chunk that has been unlinked. Adjust its
  12197. ** size parameters for check-out and return a pointer to the
  12198. ** user portion of the chunk.
  12199. */
  12200. static void *memsys3Checkout(u32 i, u32 nBlock){
  12201. u32 x;
  12202. assert( sqlite3_mutex_held(mem3.mutex) );
  12203. assert( i>=1 );
  12204. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  12205. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  12206. x = mem3.aPool[i-1].u.hdr.size4x;
  12207. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  12208. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  12209. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  12210. return &mem3.aPool[i];
  12211. }
  12212. /*
  12213. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  12214. ** Return a pointer to the new allocation. Or, if the master chunk
  12215. ** is not large enough, return 0.
  12216. */
  12217. static void *memsys3FromMaster(u32 nBlock){
  12218. assert( sqlite3_mutex_held(mem3.mutex) );
  12219. assert( mem3.szMaster>=nBlock );
  12220. if( nBlock>=mem3.szMaster-1 ){
  12221. /* Use the entire master */
  12222. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  12223. mem3.iMaster = 0;
  12224. mem3.szMaster = 0;
  12225. mem3.mnMaster = 0;
  12226. return p;
  12227. }else{
  12228. /* Split the master block. Return the tail. */
  12229. u32 newi, x;
  12230. newi = mem3.iMaster + mem3.szMaster - nBlock;
  12231. assert( newi > mem3.iMaster+1 );
  12232. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  12233. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  12234. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  12235. mem3.szMaster -= nBlock;
  12236. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  12237. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  12238. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  12239. if( mem3.szMaster < mem3.mnMaster ){
  12240. mem3.mnMaster = mem3.szMaster;
  12241. }
  12242. return (void*)&mem3.aPool[newi];
  12243. }
  12244. }
  12245. /*
  12246. ** *pRoot is the head of a list of free chunks of the same size
  12247. ** or same size hash. In other words, *pRoot is an entry in either
  12248. ** mem3.aiSmall[] or mem3.aiHash[].
  12249. **
  12250. ** This routine examines all entries on the given list and tries
  12251. ** to coalesce each entries with adjacent free chunks.
  12252. **
  12253. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  12254. ** the current mem3.iMaster with the new larger chunk. In order for
  12255. ** this mem3.iMaster replacement to work, the master chunk must be
  12256. ** linked into the hash tables. That is not the normal state of
  12257. ** affairs, of course. The calling routine must link the master
  12258. ** chunk before invoking this routine, then must unlink the (possibly
  12259. ** changed) master chunk once this routine has finished.
  12260. */
  12261. static void memsys3Merge(u32 *pRoot){
  12262. u32 iNext, prev, size, i, x;
  12263. assert( sqlite3_mutex_held(mem3.mutex) );
  12264. for(i=*pRoot; i>0; i=iNext){
  12265. iNext = mem3.aPool[i].u.list.next;
  12266. size = mem3.aPool[i-1].u.hdr.size4x;
  12267. assert( (size&1)==0 );
  12268. if( (size&2)==0 ){
  12269. memsys3UnlinkFromList(i, pRoot);
  12270. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  12271. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  12272. if( prev==iNext ){
  12273. iNext = mem3.aPool[prev].u.list.next;
  12274. }
  12275. memsys3Unlink(prev);
  12276. size = i + size/4 - prev;
  12277. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  12278. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  12279. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  12280. memsys3Link(prev);
  12281. i = prev;
  12282. }else{
  12283. size /= 4;
  12284. }
  12285. if( size>mem3.szMaster ){
  12286. mem3.iMaster = i;
  12287. mem3.szMaster = size;
  12288. }
  12289. }
  12290. }
  12291. /*
  12292. ** Return a block of memory of at least nBytes in size.
  12293. ** Return NULL if unable.
  12294. **
  12295. ** This function assumes that the necessary mutexes, if any, are
  12296. ** already held by the caller. Hence "Unsafe".
  12297. */
  12298. static void *memsys3MallocUnsafe(int nByte){
  12299. u32 i;
  12300. u32 nBlock;
  12301. u32 toFree;
  12302. assert( sqlite3_mutex_held(mem3.mutex) );
  12303. assert( sizeof(Mem3Block)==8 );
  12304. if( nByte<=12 ){
  12305. nBlock = 2;
  12306. }else{
  12307. nBlock = (nByte + 11)/8;
  12308. }
  12309. assert( nBlock>=2 );
  12310. /* STEP 1:
  12311. ** Look for an entry of the correct size in either the small
  12312. ** chunk table or in the large chunk hash table. This is
  12313. ** successful most of the time (about 9 times out of 10).
  12314. */
  12315. if( nBlock <= MX_SMALL ){
  12316. i = mem3.aiSmall[nBlock-2];
  12317. if( i>0 ){
  12318. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  12319. return memsys3Checkout(i, nBlock);
  12320. }
  12321. }else{
  12322. int hash = nBlock % N_HASH;
  12323. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  12324. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  12325. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  12326. return memsys3Checkout(i, nBlock);
  12327. }
  12328. }
  12329. }
  12330. /* STEP 2:
  12331. ** Try to satisfy the allocation by carving a piece off of the end
  12332. ** of the master chunk. This step usually works if step 1 fails.
  12333. */
  12334. if( mem3.szMaster>=nBlock ){
  12335. return memsys3FromMaster(nBlock);
  12336. }
  12337. /* STEP 3:
  12338. ** Loop through the entire memory pool. Coalesce adjacent free
  12339. ** chunks. Recompute the master chunk as the largest free chunk.
  12340. ** Then try again to satisfy the allocation by carving a piece off
  12341. ** of the end of the master chunk. This step happens very
  12342. ** rarely (we hope!)
  12343. */
  12344. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  12345. memsys3OutOfMemory(toFree);
  12346. if( mem3.iMaster ){
  12347. memsys3Link(mem3.iMaster);
  12348. mem3.iMaster = 0;
  12349. mem3.szMaster = 0;
  12350. }
  12351. for(i=0; i<N_HASH; i++){
  12352. memsys3Merge(&mem3.aiHash[i]);
  12353. }
  12354. for(i=0; i<MX_SMALL-1; i++){
  12355. memsys3Merge(&mem3.aiSmall[i]);
  12356. }
  12357. if( mem3.szMaster ){
  12358. memsys3Unlink(mem3.iMaster);
  12359. if( mem3.szMaster>=nBlock ){
  12360. return memsys3FromMaster(nBlock);
  12361. }
  12362. }
  12363. }
  12364. /* If none of the above worked, then we fail. */
  12365. return 0;
  12366. }
  12367. /*
  12368. ** Free an outstanding memory allocation.
  12369. **
  12370. ** This function assumes that the necessary mutexes, if any, are
  12371. ** already held by the caller. Hence "Unsafe".
  12372. */
  12373. void memsys3FreeUnsafe(void *pOld){
  12374. Mem3Block *p = (Mem3Block*)pOld;
  12375. int i;
  12376. u32 size, x;
  12377. assert( sqlite3_mutex_held(mem3.mutex) );
  12378. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  12379. i = p - mem3.aPool;
  12380. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  12381. size = mem3.aPool[i-1].u.hdr.size4x/4;
  12382. assert( i+size<=mem3.nPool+1 );
  12383. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  12384. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  12385. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  12386. memsys3Link(i);
  12387. /* Try to expand the master using the newly freed chunk */
  12388. if( mem3.iMaster ){
  12389. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  12390. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  12391. mem3.iMaster -= size;
  12392. mem3.szMaster += size;
  12393. memsys3Unlink(mem3.iMaster);
  12394. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  12395. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  12396. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  12397. }
  12398. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  12399. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  12400. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  12401. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  12402. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  12403. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  12404. }
  12405. }
  12406. }
  12407. /*
  12408. ** Return the size of an outstanding allocation, in bytes. The
  12409. ** size returned omits the 8-byte header overhead. This only
  12410. ** works for chunks that are currently checked out.
  12411. */
  12412. static int memsys3Size(void *p){
  12413. Mem3Block *pBlock;
  12414. if( p==0 ) return 0;
  12415. pBlock = (Mem3Block*)p;
  12416. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  12417. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  12418. }
  12419. /*
  12420. ** Round up a request size to the next valid allocation size.
  12421. */
  12422. static int memsys3Roundup(int n){
  12423. if( n<=12 ){
  12424. return 12;
  12425. }else{
  12426. return ((n+11)&~7) - 4;
  12427. }
  12428. }
  12429. /*
  12430. ** Allocate nBytes of memory.
  12431. */
  12432. static void *memsys3Malloc(int nBytes){
  12433. sqlite3_int64 *p;
  12434. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  12435. memsys3Enter();
  12436. p = memsys3MallocUnsafe(nBytes);
  12437. memsys3Leave();
  12438. return (void*)p;
  12439. }
  12440. /*
  12441. ** Free memory.
  12442. */
  12443. void memsys3Free(void *pPrior){
  12444. assert( pPrior );
  12445. memsys3Enter();
  12446. memsys3FreeUnsafe(pPrior);
  12447. memsys3Leave();
  12448. }
  12449. /*
  12450. ** Change the size of an existing memory allocation
  12451. */
  12452. void *memsys3Realloc(void *pPrior, int nBytes){
  12453. int nOld;
  12454. void *p;
  12455. if( pPrior==0 ){
  12456. return sqlite3_malloc(nBytes);
  12457. }
  12458. if( nBytes<=0 ){
  12459. sqlite3_free(pPrior);
  12460. return 0;
  12461. }
  12462. nOld = memsys3Size(pPrior);
  12463. if( nBytes<=nOld && nBytes>=nOld-128 ){
  12464. return pPrior;
  12465. }
  12466. memsys3Enter();
  12467. p = memsys3MallocUnsafe(nBytes);
  12468. if( p ){
  12469. if( nOld<nBytes ){
  12470. memcpy(p, pPrior, nOld);
  12471. }else{
  12472. memcpy(p, pPrior, nBytes);
  12473. }
  12474. memsys3FreeUnsafe(pPrior);
  12475. }
  12476. memsys3Leave();
  12477. return p;
  12478. }
  12479. /*
  12480. ** Initialize this module.
  12481. */
  12482. static int memsys3Init(void *NotUsed){
  12483. UNUSED_PARAMETER(NotUsed);
  12484. if( !sqlite3GlobalConfig.pHeap ){
  12485. return SQLITE_ERROR;
  12486. }
  12487. /* Store a pointer to the memory block in global structure mem3. */
  12488. assert( sizeof(Mem3Block)==8 );
  12489. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  12490. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  12491. /* Initialize the master block. */
  12492. mem3.szMaster = mem3.nPool;
  12493. mem3.mnMaster = mem3.szMaster;
  12494. mem3.iMaster = 1;
  12495. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  12496. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  12497. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  12498. return SQLITE_OK;
  12499. }
  12500. /*
  12501. ** Deinitialize this module.
  12502. */
  12503. static void memsys3Shutdown(void *NotUsed){
  12504. UNUSED_PARAMETER(NotUsed);
  12505. return;
  12506. }
  12507. /*
  12508. ** Open the file indicated and write a log of all unfreed memory
  12509. ** allocations into that log.
  12510. */
  12511. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  12512. #ifdef SQLITE_DEBUG
  12513. FILE *out;
  12514. u32 i, j;
  12515. u32 size;
  12516. if( zFilename==0 || zFilename[0]==0 ){
  12517. out = stdout;
  12518. }else{
  12519. out = fopen(zFilename, "w");
  12520. if( out==0 ){
  12521. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  12522. zFilename);
  12523. return;
  12524. }
  12525. }
  12526. memsys3Enter();
  12527. fprintf(out, "CHUNKS:\n");
  12528. for(i=1; i<=mem3.nPool; i+=size/4){
  12529. size = mem3.aPool[i-1].u.hdr.size4x;
  12530. if( size/4<=1 ){
  12531. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  12532. assert( 0 );
  12533. break;
  12534. }
  12535. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  12536. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  12537. assert( 0 );
  12538. break;
  12539. }
  12540. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  12541. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  12542. assert( 0 );
  12543. break;
  12544. }
  12545. if( size&1 ){
  12546. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  12547. }else{
  12548. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  12549. i==mem3.iMaster ? " **master**" : "");
  12550. }
  12551. }
  12552. for(i=0; i<MX_SMALL-1; i++){
  12553. if( mem3.aiSmall[i]==0 ) continue;
  12554. fprintf(out, "small(%2d):", i);
  12555. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  12556. fprintf(out, " %p(%d)", &mem3.aPool[j],
  12557. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  12558. }
  12559. fprintf(out, "\n");
  12560. }
  12561. for(i=0; i<N_HASH; i++){
  12562. if( mem3.aiHash[i]==0 ) continue;
  12563. fprintf(out, "hash(%2d):", i);
  12564. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  12565. fprintf(out, " %p(%d)", &mem3.aPool[j],
  12566. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  12567. }
  12568. fprintf(out, "\n");
  12569. }
  12570. fprintf(out, "master=%d\n", mem3.iMaster);
  12571. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  12572. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  12573. sqlite3_mutex_leave(mem3.mutex);
  12574. if( out==stdout ){
  12575. fflush(stdout);
  12576. }else{
  12577. fclose(out);
  12578. }
  12579. #else
  12580. UNUSED_PARAMETER(zFilename);
  12581. #endif
  12582. }
  12583. /*
  12584. ** This routine is the only routine in this file with external
  12585. ** linkage.
  12586. **
  12587. ** Populate the low-level memory allocation function pointers in
  12588. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  12589. ** arguments specify the block of memory to manage.
  12590. **
  12591. ** This routine is only called by sqlite3_config(), and therefore
  12592. ** is not required to be threadsafe (it is not).
  12593. */
  12594. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  12595. static const sqlite3_mem_methods mempoolMethods = {
  12596. memsys3Malloc,
  12597. memsys3Free,
  12598. memsys3Realloc,
  12599. memsys3Size,
  12600. memsys3Roundup,
  12601. memsys3Init,
  12602. memsys3Shutdown,
  12603. 0
  12604. };
  12605. return &mempoolMethods;
  12606. }
  12607. #endif /* SQLITE_ENABLE_MEMSYS3 */
  12608. /************** End of mem3.c ************************************************/
  12609. /************** Begin file mem5.c ********************************************/
  12610. /*
  12611. ** 2007 October 14
  12612. **
  12613. ** The author disclaims copyright to this source code. In place of
  12614. ** a legal notice, here is a blessing:
  12615. **
  12616. ** May you do good and not evil.
  12617. ** May you find forgiveness for yourself and forgive others.
  12618. ** May you share freely, never taking more than you give.
  12619. **
  12620. *************************************************************************
  12621. ** This file contains the C functions that implement a memory
  12622. ** allocation subsystem for use by SQLite.
  12623. **
  12624. ** This version of the memory allocation subsystem omits all
  12625. ** use of malloc(). The SQLite user supplies a block of memory
  12626. ** before calling sqlite3_initialize() from which allocations
  12627. ** are made and returned by the xMalloc() and xRealloc()
  12628. ** implementations. Once sqlite3_initialize() has been called,
  12629. ** the amount of memory available to SQLite is fixed and cannot
  12630. ** be changed.
  12631. **
  12632. ** This version of the memory allocation subsystem is included
  12633. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  12634. **
  12635. ** $Id: mem5.c,v 1.19 2008/11/19 16:52:44 danielk1977 Exp $
  12636. */
  12637. /*
  12638. ** This version of the memory allocator is used only when
  12639. ** SQLITE_ENABLE_MEMSYS5 is defined.
  12640. */
  12641. #ifdef SQLITE_ENABLE_MEMSYS5
  12642. /*
  12643. ** A minimum allocation is an instance of the following structure.
  12644. ** Larger allocations are an array of these structures where the
  12645. ** size of the array is a power of 2.
  12646. */
  12647. typedef struct Mem5Link Mem5Link;
  12648. struct Mem5Link {
  12649. int next; /* Index of next free chunk */
  12650. int prev; /* Index of previous free chunk */
  12651. };
  12652. /*
  12653. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
  12654. ** mem5.nAtom is always at least 8, this is not really a practical
  12655. ** limitation.
  12656. */
  12657. #define LOGMAX 30
  12658. /*
  12659. ** Masks used for mem5.aCtrl[] elements.
  12660. */
  12661. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block relative to POW2_MIN */
  12662. #define CTRL_FREE 0x20 /* True if not checked out */
  12663. /*
  12664. ** All of the static variables used by this module are collected
  12665. ** into a single structure named "mem5". This is to keep the
  12666. ** static variables organized and to reduce namespace pollution
  12667. ** when this module is combined with other in the amalgamation.
  12668. */
  12669. static SQLITE_WSD struct Mem5Global {
  12670. /*
  12671. ** Memory available for allocation
  12672. */
  12673. int nAtom; /* Smallest possible allocation in bytes */
  12674. int nBlock; /* Number of nAtom sized blocks in zPool */
  12675. u8 *zPool;
  12676. /*
  12677. ** Mutex to control access to the memory allocation subsystem.
  12678. */
  12679. sqlite3_mutex *mutex;
  12680. /*
  12681. ** Performance statistics
  12682. */
  12683. u64 nAlloc; /* Total number of calls to malloc */
  12684. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  12685. u64 totalExcess; /* Total internal fragmentation */
  12686. u32 currentOut; /* Current checkout, including internal fragmentation */
  12687. u32 currentCount; /* Current number of distinct checkouts */
  12688. u32 maxOut; /* Maximum instantaneous currentOut */
  12689. u32 maxCount; /* Maximum instantaneous currentCount */
  12690. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  12691. /*
  12692. ** Lists of free blocks of various sizes.
  12693. */
  12694. int aiFreelist[LOGMAX+1];
  12695. /*
  12696. ** Space for tracking which blocks are checked out and the size
  12697. ** of each block. One byte per block.
  12698. */
  12699. u8 *aCtrl;
  12700. } mem5 = { 19804167 };
  12701. #define mem5 GLOBAL(struct Mem5Global, mem5)
  12702. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
  12703. /*
  12704. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  12705. ** on. It should be found on mem5.aiFreelist[iLogsize].
  12706. */
  12707. static void memsys5Unlink(int i, int iLogsize){
  12708. int next, prev;
  12709. assert( i>=0 && i<mem5.nBlock );
  12710. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  12711. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  12712. next = MEM5LINK(i)->next;
  12713. prev = MEM5LINK(i)->prev;
  12714. if( prev<0 ){
  12715. mem5.aiFreelist[iLogsize] = next;
  12716. }else{
  12717. MEM5LINK(prev)->next = next;
  12718. }
  12719. if( next>=0 ){
  12720. MEM5LINK(next)->prev = prev;
  12721. }
  12722. }
  12723. /*
  12724. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  12725. ** free list.
  12726. */
  12727. static void memsys5Link(int i, int iLogsize){
  12728. int x;
  12729. assert( sqlite3_mutex_held(mem5.mutex) );
  12730. assert( i>=0 && i<mem5.nBlock );
  12731. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  12732. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  12733. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  12734. MEM5LINK(i)->prev = -1;
  12735. if( x>=0 ){
  12736. assert( x<mem5.nBlock );
  12737. MEM5LINK(x)->prev = i;
  12738. }
  12739. mem5.aiFreelist[iLogsize] = i;
  12740. }
  12741. /*
  12742. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  12743. ** will already be held (obtained by code in malloc.c) if
  12744. ** sqlite3GlobalConfig.bMemStat is true.
  12745. */
  12746. static void memsys5Enter(void){
  12747. if( sqlite3GlobalConfig.bMemstat==0 && mem5.mutex==0 ){
  12748. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  12749. }
  12750. sqlite3_mutex_enter(mem5.mutex);
  12751. }
  12752. static void memsys5Leave(void){
  12753. sqlite3_mutex_leave(mem5.mutex);
  12754. }
  12755. /*
  12756. ** Return the size of an outstanding allocation, in bytes. The
  12757. ** size returned omits the 8-byte header overhead. This only
  12758. ** works for chunks that are currently checked out.
  12759. */
  12760. static int memsys5Size(void *p){
  12761. int iSize = 0;
  12762. if( p ){
  12763. int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
  12764. assert( i>=0 && i<mem5.nBlock );
  12765. iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  12766. }
  12767. return iSize;
  12768. }
  12769. /*
  12770. ** Find the first entry on the freelist iLogsize. Unlink that
  12771. ** entry and return its index.
  12772. */
  12773. static int memsys5UnlinkFirst(int iLogsize){
  12774. int i;
  12775. int iFirst;
  12776. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  12777. i = iFirst = mem5.aiFreelist[iLogsize];
  12778. assert( iFirst>=0 );
  12779. while( i>0 ){
  12780. if( i<iFirst ) iFirst = i;
  12781. i = MEM5LINK(i)->next;
  12782. }
  12783. memsys5Unlink(iFirst, iLogsize);
  12784. return iFirst;
  12785. }
  12786. /*
  12787. ** Return a block of memory of at least nBytes in size.
  12788. ** Return NULL if unable.
  12789. */
  12790. static void *memsys5MallocUnsafe(int nByte){
  12791. int i; /* Index of a mem5.aPool[] slot */
  12792. int iBin; /* Index into mem5.aiFreelist[] */
  12793. int iFullSz; /* Size of allocation rounded up to power of 2 */
  12794. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  12795. /* Keep track of the maximum allocation request. Even unfulfilled
  12796. ** requests are counted */
  12797. if( (u32)nByte>mem5.maxRequest ){
  12798. mem5.maxRequest = nByte;
  12799. }
  12800. /* Round nByte up to the next valid power of two */
  12801. for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  12802. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  12803. ** block. If not, then split a block of the next larger power of
  12804. ** two in order to create a new free block of size iLogsize.
  12805. */
  12806. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  12807. if( iBin>LOGMAX ) return 0;
  12808. i = memsys5UnlinkFirst(iBin);
  12809. while( iBin>iLogsize ){
  12810. int newSize;
  12811. iBin--;
  12812. newSize = 1 << iBin;
  12813. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  12814. memsys5Link(i+newSize, iBin);
  12815. }
  12816. mem5.aCtrl[i] = iLogsize;
  12817. /* Update allocator performance statistics. */
  12818. mem5.nAlloc++;
  12819. mem5.totalAlloc += iFullSz;
  12820. mem5.totalExcess += iFullSz - nByte;
  12821. mem5.currentCount++;
  12822. mem5.currentOut += iFullSz;
  12823. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  12824. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  12825. /* Return a pointer to the allocated memory. */
  12826. return (void*)&mem5.zPool[i*mem5.nAtom];
  12827. }
  12828. /*
  12829. ** Free an outstanding memory allocation.
  12830. */
  12831. static void memsys5FreeUnsafe(void *pOld){
  12832. u32 size, iLogsize;
  12833. int iBlock;
  12834. /* Set iBlock to the index of the block pointed to by pOld in
  12835. ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
  12836. */
  12837. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
  12838. /* Check that the pointer pOld points to a valid, non-free block. */
  12839. assert( iBlock>=0 && iBlock<mem5.nBlock );
  12840. assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
  12841. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  12842. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  12843. size = 1<<iLogsize;
  12844. assert( iBlock+size-1<(u32)mem5.nBlock );
  12845. mem5.aCtrl[iBlock] |= CTRL_FREE;
  12846. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  12847. assert( mem5.currentCount>0 );
  12848. assert( mem5.currentOut>=(size*mem5.nAtom) );
  12849. mem5.currentCount--;
  12850. mem5.currentOut -= size*mem5.nAtom;
  12851. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  12852. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  12853. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  12854. while( iLogsize<LOGMAX ){
  12855. int iBuddy;
  12856. if( (iBlock>>iLogsize) & 1 ){
  12857. iBuddy = iBlock - size;
  12858. }else{
  12859. iBuddy = iBlock + size;
  12860. }
  12861. assert( iBuddy>=0 );
  12862. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  12863. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  12864. memsys5Unlink(iBuddy, iLogsize);
  12865. iLogsize++;
  12866. if( iBuddy<iBlock ){
  12867. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  12868. mem5.aCtrl[iBlock] = 0;
  12869. iBlock = iBuddy;
  12870. }else{
  12871. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  12872. mem5.aCtrl[iBuddy] = 0;
  12873. }
  12874. size *= 2;
  12875. }
  12876. memsys5Link(iBlock, iLogsize);
  12877. }
  12878. /*
  12879. ** Allocate nBytes of memory
  12880. */
  12881. static void *memsys5Malloc(int nBytes){
  12882. sqlite3_int64 *p = 0;
  12883. if( nBytes>0 ){
  12884. memsys5Enter();
  12885. p = memsys5MallocUnsafe(nBytes);
  12886. memsys5Leave();
  12887. }
  12888. return (void*)p;
  12889. }
  12890. /*
  12891. ** Free memory.
  12892. */
  12893. static void memsys5Free(void *pPrior){
  12894. if( pPrior==0 ){
  12895. assert(0);
  12896. return;
  12897. }
  12898. memsys5Enter();
  12899. memsys5FreeUnsafe(pPrior);
  12900. memsys5Leave();
  12901. }
  12902. /*
  12903. ** Change the size of an existing memory allocation
  12904. */
  12905. static void *memsys5Realloc(void *pPrior, int nBytes){
  12906. int nOld;
  12907. void *p;
  12908. if( pPrior==0 ){
  12909. return memsys5Malloc(nBytes);
  12910. }
  12911. if( nBytes<=0 ){
  12912. memsys5Free(pPrior);
  12913. return 0;
  12914. }
  12915. nOld = memsys5Size(pPrior);
  12916. if( nBytes<=nOld ){
  12917. return pPrior;
  12918. }
  12919. memsys5Enter();
  12920. p = memsys5MallocUnsafe(nBytes);
  12921. if( p ){
  12922. memcpy(p, pPrior, nOld);
  12923. memsys5FreeUnsafe(pPrior);
  12924. }
  12925. memsys5Leave();
  12926. return p;
  12927. }
  12928. /*
  12929. ** Round up a request size to the next valid allocation size.
  12930. */
  12931. static int memsys5Roundup(int n){
  12932. int iFullSz;
  12933. for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
  12934. return iFullSz;
  12935. }
  12936. static int memsys5Log(int iValue){
  12937. int iLog;
  12938. for(iLog=0; (1<<iLog)<iValue; iLog++);
  12939. return iLog;
  12940. }
  12941. /*
  12942. ** Initialize this module.
  12943. */
  12944. static int memsys5Init(void *NotUsed){
  12945. int ii;
  12946. int nByte = sqlite3GlobalConfig.nHeap;
  12947. u8 *zByte = (u8 *)sqlite3GlobalConfig.pHeap;
  12948. int nMinLog; /* Log of minimum allocation size in bytes*/
  12949. int iOffset;
  12950. UNUSED_PARAMETER(NotUsed);
  12951. if( !zByte ){
  12952. return SQLITE_ERROR;
  12953. }
  12954. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  12955. mem5.nAtom = (1<<nMinLog);
  12956. while( (int)sizeof(Mem5Link)>mem5.nAtom ){
  12957. mem5.nAtom = mem5.nAtom << 1;
  12958. }
  12959. mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
  12960. mem5.zPool = zByte;
  12961. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
  12962. for(ii=0; ii<=LOGMAX; ii++){
  12963. mem5.aiFreelist[ii] = -1;
  12964. }
  12965. iOffset = 0;
  12966. for(ii=LOGMAX; ii>=0; ii--){
  12967. int nAlloc = (1<<ii);
  12968. if( (iOffset+nAlloc)<=mem5.nBlock ){
  12969. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  12970. memsys5Link(iOffset, ii);
  12971. iOffset += nAlloc;
  12972. }
  12973. assert((iOffset+nAlloc)>mem5.nBlock);
  12974. }
  12975. return SQLITE_OK;
  12976. }
  12977. /*
  12978. ** Deinitialize this module.
  12979. */
  12980. static void memsys5Shutdown(void *NotUsed){
  12981. UNUSED_PARAMETER(NotUsed);
  12982. return;
  12983. }
  12984. /*
  12985. ** Open the file indicated and write a log of all unfreed memory
  12986. ** allocations into that log.
  12987. */
  12988. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  12989. #ifdef SQLITE_DEBUG
  12990. FILE *out;
  12991. int i, j, n;
  12992. int nMinLog;
  12993. if( zFilename==0 || zFilename[0]==0 ){
  12994. out = stdout;
  12995. }else{
  12996. out = fopen(zFilename, "w");
  12997. if( out==0 ){
  12998. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  12999. zFilename);
  13000. return;
  13001. }
  13002. }
  13003. memsys5Enter();
  13004. nMinLog = memsys5Log(mem5.nAtom);
  13005. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  13006. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  13007. fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
  13008. }
  13009. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  13010. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  13011. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  13012. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  13013. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  13014. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  13015. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  13016. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  13017. memsys5Leave();
  13018. if( out==stdout ){
  13019. fflush(stdout);
  13020. }else{
  13021. fclose(out);
  13022. }
  13023. #else
  13024. UNUSED_PARAMETER(zFilename);
  13025. #endif
  13026. }
  13027. /*
  13028. ** This routine is the only routine in this file with external
  13029. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  13030. ** struct populated with the memsys5 methods.
  13031. */
  13032. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  13033. static const sqlite3_mem_methods memsys5Methods = {
  13034. memsys5Malloc,
  13035. memsys5Free,
  13036. memsys5Realloc,
  13037. memsys5Size,
  13038. memsys5Roundup,
  13039. memsys5Init,
  13040. memsys5Shutdown,
  13041. 0
  13042. };
  13043. return &memsys5Methods;
  13044. }
  13045. #endif /* SQLITE_ENABLE_MEMSYS5 */
  13046. /************** End of mem5.c ************************************************/
  13047. /************** Begin file mutex.c *******************************************/
  13048. /*
  13049. ** 2007 August 14
  13050. **
  13051. ** The author disclaims copyright to this source code. In place of
  13052. ** a legal notice, here is a blessing:
  13053. **
  13054. ** May you do good and not evil.
  13055. ** May you find forgiveness for yourself and forgive others.
  13056. ** May you share freely, never taking more than you give.
  13057. **
  13058. *************************************************************************
  13059. ** This file contains the C functions that implement mutexes.
  13060. **
  13061. ** This file contains code that is common across all mutex implementations.
  13062. **
  13063. ** $Id: mutex.c,v 1.30 2009/02/17 16:29:11 danielk1977 Exp $
  13064. */
  13065. #ifndef SQLITE_MUTEX_OMIT
  13066. /*
  13067. ** Initialize the mutex system.
  13068. */
  13069. SQLITE_PRIVATE int sqlite3MutexInit(void){
  13070. int rc = SQLITE_OK;
  13071. if( sqlite3GlobalConfig.bCoreMutex ){
  13072. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  13073. /* If the xMutexAlloc method has not been set, then the user did not
  13074. ** install a mutex implementation via sqlite3_config() prior to
  13075. ** sqlite3_initialize() being called. This block copies pointers to
  13076. ** the default implementation into the sqlite3GlobalConfig structure.
  13077. **
  13078. ** The danger is that although sqlite3_config() is not a threadsafe
  13079. ** API, sqlite3_initialize() is, and so multiple threads may be
  13080. ** attempting to run this function simultaneously. To guard write
  13081. ** access to the sqlite3GlobalConfig structure, the 'MASTER' static mutex
  13082. ** is obtained before modifying it.
  13083. */
  13084. sqlite3_mutex_methods *p = sqlite3DefaultMutex();
  13085. sqlite3_mutex *pMaster = 0;
  13086. rc = p->xMutexInit();
  13087. if( rc==SQLITE_OK ){
  13088. pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13089. assert(pMaster);
  13090. p->xMutexEnter(pMaster);
  13091. assert( sqlite3GlobalConfig.mutex.xMutexAlloc==0
  13092. || sqlite3GlobalConfig.mutex.xMutexAlloc==p->xMutexAlloc
  13093. );
  13094. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  13095. sqlite3GlobalConfig.mutex = *p;
  13096. }
  13097. p->xMutexLeave(pMaster);
  13098. }
  13099. }else{
  13100. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  13101. }
  13102. }
  13103. return rc;
  13104. }
  13105. /*
  13106. ** Shutdown the mutex system. This call frees resources allocated by
  13107. ** sqlite3MutexInit().
  13108. */
  13109. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  13110. int rc = SQLITE_OK;
  13111. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  13112. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  13113. }
  13114. return rc;
  13115. }
  13116. /*
  13117. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  13118. */
  13119. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  13120. #ifndef SQLITE_OMIT_AUTOINIT
  13121. if( sqlite3_initialize() ) return 0;
  13122. #endif
  13123. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  13124. }
  13125. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  13126. if( !sqlite3GlobalConfig.bCoreMutex ){
  13127. return 0;
  13128. }
  13129. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  13130. }
  13131. /*
  13132. ** Free a dynamic mutex.
  13133. */
  13134. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  13135. if( p ){
  13136. sqlite3GlobalConfig.mutex.xMutexFree(p);
  13137. }
  13138. }
  13139. /*
  13140. ** Obtain the mutex p. If some other thread already has the mutex, block
  13141. ** until it can be obtained.
  13142. */
  13143. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  13144. if( p ){
  13145. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  13146. }
  13147. }
  13148. /*
  13149. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  13150. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  13151. */
  13152. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  13153. int rc = SQLITE_OK;
  13154. if( p ){
  13155. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  13156. }
  13157. return rc;
  13158. }
  13159. /*
  13160. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  13161. ** entered by the same thread. The behavior is undefined if the mutex
  13162. ** is not currently entered. If a NULL pointer is passed as an argument
  13163. ** this function is a no-op.
  13164. */
  13165. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  13166. if( p ){
  13167. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  13168. }
  13169. }
  13170. #ifndef NDEBUG
  13171. /*
  13172. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  13173. ** intended for use inside assert() statements.
  13174. */
  13175. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  13176. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  13177. }
  13178. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  13179. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  13180. }
  13181. #endif
  13182. #endif /* SQLITE_OMIT_MUTEX */
  13183. /************** End of mutex.c ***********************************************/
  13184. /************** Begin file mutex_noop.c **************************************/
  13185. /*
  13186. ** 2008 October 07
  13187. **
  13188. ** The author disclaims copyright to this source code. In place of
  13189. ** a legal notice, here is a blessing:
  13190. **
  13191. ** May you do good and not evil.
  13192. ** May you find forgiveness for yourself and forgive others.
  13193. ** May you share freely, never taking more than you give.
  13194. **
  13195. *************************************************************************
  13196. ** This file contains the C functions that implement mutexes.
  13197. **
  13198. ** This implementation in this file does not provide any mutual
  13199. ** exclusion and is thus suitable for use only in applications
  13200. ** that use SQLite in a single thread. The routines defined
  13201. ** here are place-holders. Applications can substitute working
  13202. ** mutex routines at start-time using the
  13203. **
  13204. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  13205. **
  13206. ** interface.
  13207. **
  13208. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  13209. ** that does error checking on mutexes to make sure they are being
  13210. ** called correctly.
  13211. **
  13212. ** $Id: mutex_noop.c,v 1.3 2008/12/05 17:17:08 drh Exp $
  13213. */
  13214. #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
  13215. /*
  13216. ** Stub routines for all mutex methods.
  13217. **
  13218. ** This routines provide no mutual exclusion or error checking.
  13219. */
  13220. static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
  13221. static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
  13222. static int noopMutexInit(void){ return SQLITE_OK; }
  13223. static int noopMutexEnd(void){ return SQLITE_OK; }
  13224. static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
  13225. static void noopMutexFree(sqlite3_mutex *p){ return; }
  13226. static void noopMutexEnter(sqlite3_mutex *p){ return; }
  13227. static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
  13228. static void noopMutexLeave(sqlite3_mutex *p){ return; }
  13229. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  13230. static sqlite3_mutex_methods sMutex = {
  13231. noopMutexInit,
  13232. noopMutexEnd,
  13233. noopMutexAlloc,
  13234. noopMutexFree,
  13235. noopMutexEnter,
  13236. noopMutexTry,
  13237. noopMutexLeave,
  13238. noopMutexHeld,
  13239. noopMutexNotheld
  13240. };
  13241. return &sMutex;
  13242. }
  13243. #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
  13244. #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
  13245. /*
  13246. ** In this implementation, error checking is provided for testing
  13247. ** and debugging purposes. The mutexes still do not provide any
  13248. ** mutual exclusion.
  13249. */
  13250. /*
  13251. ** The mutex object
  13252. */
  13253. struct sqlite3_mutex {
  13254. int id; /* The mutex type */
  13255. int cnt; /* Number of entries without a matching leave */
  13256. };
  13257. /*
  13258. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  13259. ** intended for use inside assert() statements.
  13260. */
  13261. static int debugMutexHeld(sqlite3_mutex *p){
  13262. return p==0 || p->cnt>0;
  13263. }
  13264. static int debugMutexNotheld(sqlite3_mutex *p){
  13265. return p==0 || p->cnt==0;
  13266. }
  13267. /*
  13268. ** Initialize and deinitialize the mutex subsystem.
  13269. */
  13270. static int debugMutexInit(void){ return SQLITE_OK; }
  13271. static int debugMutexEnd(void){ return SQLITE_OK; }
  13272. /*
  13273. ** The sqlite3_mutex_alloc() routine allocates a new
  13274. ** mutex and returns a pointer to it. If it returns NULL
  13275. ** that means that a mutex could not be allocated.
  13276. */
  13277. static sqlite3_mutex *debugMutexAlloc(int id){
  13278. static sqlite3_mutex aStatic[6];
  13279. sqlite3_mutex *pNew = 0;
  13280. switch( id ){
  13281. case SQLITE_MUTEX_FAST:
  13282. case SQLITE_MUTEX_RECURSIVE: {
  13283. pNew = sqlite3Malloc(sizeof(*pNew));
  13284. if( pNew ){
  13285. pNew->id = id;
  13286. pNew->cnt = 0;
  13287. }
  13288. break;
  13289. }
  13290. default: {
  13291. assert( id-2 >= 0 );
  13292. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  13293. pNew = &aStatic[id-2];
  13294. pNew->id = id;
  13295. break;
  13296. }
  13297. }
  13298. return pNew;
  13299. }
  13300. /*
  13301. ** This routine deallocates a previously allocated mutex.
  13302. */
  13303. static void debugMutexFree(sqlite3_mutex *p){
  13304. assert( p->cnt==0 );
  13305. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  13306. sqlite3_free(p);
  13307. }
  13308. /*
  13309. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  13310. ** to enter a mutex. If another thread is already within the mutex,
  13311. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  13312. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  13313. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  13314. ** be entered multiple times by the same thread. In such cases the,
  13315. ** mutex must be exited an equal number of times before another thread
  13316. ** can enter. If the same thread tries to enter any other kind of mutex
  13317. ** more than once, the behavior is undefined.
  13318. */
  13319. static void debugMutexEnter(sqlite3_mutex *p){
  13320. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  13321. p->cnt++;
  13322. }
  13323. static int debugMutexTry(sqlite3_mutex *p){
  13324. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  13325. p->cnt++;
  13326. return SQLITE_OK;
  13327. }
  13328. /*
  13329. ** The sqlite3_mutex_leave() routine exits a mutex that was
  13330. ** previously entered by the same thread. The behavior
  13331. ** is undefined if the mutex is not currently entered or
  13332. ** is not currently allocated. SQLite will never do either.
  13333. */
  13334. static void debugMutexLeave(sqlite3_mutex *p){
  13335. assert( debugMutexHeld(p) );
  13336. p->cnt--;
  13337. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
  13338. }
  13339. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  13340. static sqlite3_mutex_methods sMutex = {
  13341. debugMutexInit,
  13342. debugMutexEnd,
  13343. debugMutexAlloc,
  13344. debugMutexFree,
  13345. debugMutexEnter,
  13346. debugMutexTry,
  13347. debugMutexLeave,
  13348. debugMutexHeld,
  13349. debugMutexNotheld
  13350. };
  13351. return &sMutex;
  13352. }
  13353. #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
  13354. /************** End of mutex_noop.c ******************************************/
  13355. /************** Begin file mutex_os2.c ***************************************/
  13356. /*
  13357. ** 2007 August 28
  13358. **
  13359. ** The author disclaims copyright to this source code. In place of
  13360. ** a legal notice, here is a blessing:
  13361. **
  13362. ** May you do good and not evil.
  13363. ** May you find forgiveness for yourself and forgive others.
  13364. ** May you share freely, never taking more than you give.
  13365. **
  13366. *************************************************************************
  13367. ** This file contains the C functions that implement mutexes for OS/2
  13368. **
  13369. ** $Id: mutex_os2.c,v 1.11 2008/11/22 19:50:54 pweilbacher Exp $
  13370. */
  13371. /*
  13372. ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
  13373. ** See the mutex.h file for details.
  13374. */
  13375. #ifdef SQLITE_MUTEX_OS2
  13376. /********************** OS/2 Mutex Implementation **********************
  13377. **
  13378. ** This implementation of mutexes is built using the OS/2 API.
  13379. */
  13380. /*
  13381. ** The mutex object
  13382. ** Each recursive mutex is an instance of the following structure.
  13383. */
  13384. struct sqlite3_mutex {
  13385. HMTX mutex; /* Mutex controlling the lock */
  13386. int id; /* Mutex type */
  13387. int nRef; /* Number of references */
  13388. TID owner; /* Thread holding this mutex */
  13389. };
  13390. #define OS2_MUTEX_INITIALIZER 0,0,0,0
  13391. /*
  13392. ** Initialize and deinitialize the mutex subsystem.
  13393. */
  13394. static int os2MutexInit(void){ return SQLITE_OK; }
  13395. static int os2MutexEnd(void){ return SQLITE_OK; }
  13396. /*
  13397. ** The sqlite3_mutex_alloc() routine allocates a new
  13398. ** mutex and returns a pointer to it. If it returns NULL
  13399. ** that means that a mutex could not be allocated.
  13400. ** SQLite will unwind its stack and return an error. The argument
  13401. ** to sqlite3_mutex_alloc() is one of these integer constants:
  13402. **
  13403. ** <ul>
  13404. ** <li> SQLITE_MUTEX_FAST 0
  13405. ** <li> SQLITE_MUTEX_RECURSIVE 1
  13406. ** <li> SQLITE_MUTEX_STATIC_MASTER 2
  13407. ** <li> SQLITE_MUTEX_STATIC_MEM 3
  13408. ** <li> SQLITE_MUTEX_STATIC_PRNG 4
  13409. ** </ul>
  13410. **
  13411. ** The first two constants cause sqlite3_mutex_alloc() to create
  13412. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  13413. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  13414. ** The mutex implementation does not need to make a distinction
  13415. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  13416. ** not want to. But SQLite will only request a recursive mutex in
  13417. ** cases where it really needs one. If a faster non-recursive mutex
  13418. ** implementation is available on the host platform, the mutex subsystem
  13419. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  13420. **
  13421. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  13422. ** a pointer to a static preexisting mutex. Three static mutexes are
  13423. ** used by the current version of SQLite. Future versions of SQLite
  13424. ** may add additional static mutexes. Static mutexes are for internal
  13425. ** use by SQLite only. Applications that use SQLite mutexes should
  13426. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  13427. ** SQLITE_MUTEX_RECURSIVE.
  13428. **
  13429. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  13430. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  13431. ** returns a different mutex on every call. But for the static
  13432. ** mutex types, the same mutex is returned on every call that has
  13433. ** the same type number.
  13434. */
  13435. static sqlite3_mutex *os2MutexAlloc(int iType){
  13436. sqlite3_mutex *p = NULL;
  13437. switch( iType ){
  13438. case SQLITE_MUTEX_FAST:
  13439. case SQLITE_MUTEX_RECURSIVE: {
  13440. p = sqlite3MallocZero( sizeof(*p) );
  13441. if( p ){
  13442. p->id = iType;
  13443. if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
  13444. sqlite3_free( p );
  13445. p = NULL;
  13446. }
  13447. }
  13448. break;
  13449. }
  13450. default: {
  13451. static volatile int isInit = 0;
  13452. static sqlite3_mutex staticMutexes[] = {
  13453. { OS2_MUTEX_INITIALIZER, },
  13454. { OS2_MUTEX_INITIALIZER, },
  13455. { OS2_MUTEX_INITIALIZER, },
  13456. { OS2_MUTEX_INITIALIZER, },
  13457. { OS2_MUTEX_INITIALIZER, },
  13458. { OS2_MUTEX_INITIALIZER, },
  13459. };
  13460. if ( !isInit ){
  13461. APIRET rc;
  13462. PTIB ptib;
  13463. PPIB ppib;
  13464. HMTX mutex;
  13465. char name[32];
  13466. DosGetInfoBlocks( &ptib, &ppib );
  13467. sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
  13468. ppib->pib_ulpid );
  13469. while( !isInit ){
  13470. mutex = 0;
  13471. rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
  13472. if( rc == NO_ERROR ){
  13473. unsigned int i;
  13474. if( !isInit ){
  13475. for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
  13476. DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
  13477. }
  13478. isInit = 1;
  13479. }
  13480. DosCloseMutexSem( mutex );
  13481. }else if( rc == ERROR_DUPLICATE_NAME ){
  13482. DosSleep( 1 );
  13483. }else{
  13484. return p;
  13485. }
  13486. }
  13487. }
  13488. assert( iType-2 >= 0 );
  13489. assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
  13490. p = &staticMutexes[iType-2];
  13491. p->id = iType;
  13492. break;
  13493. }
  13494. }
  13495. return p;
  13496. }
  13497. /*
  13498. ** This routine deallocates a previously allocated mutex.
  13499. ** SQLite is careful to deallocate every mutex that it allocates.
  13500. */
  13501. static void os2MutexFree(sqlite3_mutex *p){
  13502. if( p==0 ) return;
  13503. assert( p->nRef==0 );
  13504. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  13505. DosCloseMutexSem( p->mutex );
  13506. sqlite3_free( p );
  13507. }
  13508. /*
  13509. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  13510. ** to enter a mutex. If another thread is already within the mutex,
  13511. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  13512. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  13513. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  13514. ** be entered multiple times by the same thread. In such cases the,
  13515. ** mutex must be exited an equal number of times before another thread
  13516. ** can enter. If the same thread tries to enter any other kind of mutex
  13517. ** more than once, the behavior is undefined.
  13518. */
  13519. static void os2MutexEnter(sqlite3_mutex *p){
  13520. TID tid;
  13521. PID holder1;
  13522. ULONG holder2;
  13523. if( p==0 ) return;
  13524. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  13525. DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
  13526. DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  13527. p->owner = tid;
  13528. p->nRef++;
  13529. }
  13530. static int os2MutexTry(sqlite3_mutex *p){
  13531. int rc;
  13532. TID tid;
  13533. PID holder1;
  13534. ULONG holder2;
  13535. if( p==0 ) return SQLITE_OK;
  13536. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  13537. if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
  13538. DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  13539. p->owner = tid;
  13540. p->nRef++;
  13541. rc = SQLITE_OK;
  13542. } else {
  13543. rc = SQLITE_BUSY;
  13544. }
  13545. return rc;
  13546. }
  13547. /*
  13548. ** The sqlite3_mutex_leave() routine exits a mutex that was
  13549. ** previously entered by the same thread. The behavior
  13550. ** is undefined if the mutex is not currently entered or
  13551. ** is not currently allocated. SQLite will never do either.
  13552. */
  13553. static void os2MutexLeave(sqlite3_mutex *p){
  13554. TID tid;
  13555. PID holder1;
  13556. ULONG holder2;
  13557. if( p==0 ) return;
  13558. assert( p->nRef>0 );
  13559. DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
  13560. assert( p->owner==tid );
  13561. p->nRef--;
  13562. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  13563. DosReleaseMutexSem(p->mutex);
  13564. }
  13565. #ifdef SQLITE_DEBUG
  13566. /*
  13567. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  13568. ** intended for use inside assert() statements.
  13569. */
  13570. static int os2MutexHeld(sqlite3_mutex *p){
  13571. TID tid;
  13572. PID pid;
  13573. ULONG ulCount;
  13574. PTIB ptib;
  13575. if( p!=0 ) {
  13576. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  13577. } else {
  13578. DosGetInfoBlocks(&ptib, NULL);
  13579. tid = ptib->tib_ptib2->tib2_ultid;
  13580. }
  13581. return p==0 || (p->nRef!=0 && p->owner==tid);
  13582. }
  13583. static int os2MutexNotheld(sqlite3_mutex *p){
  13584. TID tid;
  13585. PID pid;
  13586. ULONG ulCount;
  13587. PTIB ptib;
  13588. if( p!= 0 ) {
  13589. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  13590. } else {
  13591. DosGetInfoBlocks(&ptib, NULL);
  13592. tid = ptib->tib_ptib2->tib2_ultid;
  13593. }
  13594. return p==0 || p->nRef==0 || p->owner!=tid;
  13595. }
  13596. #endif
  13597. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  13598. static sqlite3_mutex_methods sMutex = {
  13599. os2MutexInit,
  13600. os2MutexEnd,
  13601. os2MutexAlloc,
  13602. os2MutexFree,
  13603. os2MutexEnter,
  13604. os2MutexTry,
  13605. os2MutexLeave,
  13606. #ifdef SQLITE_DEBUG
  13607. os2MutexHeld,
  13608. os2MutexNotheld
  13609. #endif
  13610. };
  13611. return &sMutex;
  13612. }
  13613. #endif /* SQLITE_MUTEX_OS2 */
  13614. /************** End of mutex_os2.c *******************************************/
  13615. /************** Begin file mutex_unix.c **************************************/
  13616. /*
  13617. ** 2007 August 28
  13618. **
  13619. ** The author disclaims copyright to this source code. In place of
  13620. ** a legal notice, here is a blessing:
  13621. **
  13622. ** May you do good and not evil.
  13623. ** May you find forgiveness for yourself and forgive others.
  13624. ** May you share freely, never taking more than you give.
  13625. **
  13626. *************************************************************************
  13627. ** This file contains the C functions that implement mutexes for pthreads
  13628. **
  13629. ** $Id: mutex_unix.c,v 1.16 2008/12/08 18:19:18 drh Exp $
  13630. */
  13631. /*
  13632. ** The code in this file is only used if we are compiling threadsafe
  13633. ** under unix with pthreads.
  13634. **
  13635. ** Note that this implementation requires a version of pthreads that
  13636. ** supports recursive mutexes.
  13637. */
  13638. #ifdef SQLITE_MUTEX_PTHREADS
  13639. #include <pthread.h>
  13640. /*
  13641. ** Each recursive mutex is an instance of the following structure.
  13642. */
  13643. struct sqlite3_mutex {
  13644. pthread_mutex_t mutex; /* Mutex controlling the lock */
  13645. int id; /* Mutex type */
  13646. int nRef; /* Number of entrances */
  13647. pthread_t owner; /* Thread that is within this mutex */
  13648. #ifdef SQLITE_DEBUG
  13649. int trace; /* True to trace changes */
  13650. #endif
  13651. };
  13652. #ifdef SQLITE_DEBUG
  13653. #define SQLite3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  13654. #else
  13655. #define SQLite3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
  13656. #endif
  13657. /*
  13658. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  13659. ** intended for use only inside assert() statements. On some platforms,
  13660. ** there might be race conditions that can cause these routines to
  13661. ** deliver incorrect results. In particular, if pthread_equal() is
  13662. ** not an atomic operation, then these routines might delivery
  13663. ** incorrect results. On most platforms, pthread_equal() is a
  13664. ** comparison of two integers and is therefore atomic. But we are
  13665. ** told that HPUX is not such a platform. If so, then these routines
  13666. ** will not always work correctly on HPUX.
  13667. **
  13668. ** On those platforms where pthread_equal() is not atomic, SQLite
  13669. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  13670. ** make sure no assert() statements are evaluated and hence these
  13671. ** routines are never called.
  13672. */
  13673. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  13674. static int pthreadMutexHeld(sqlite3_mutex *p){
  13675. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  13676. }
  13677. static int pthreadMutexNotheld(sqlite3_mutex *p){
  13678. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  13679. }
  13680. #endif
  13681. /*
  13682. ** Initialize and deinitialize the mutex subsystem.
  13683. */
  13684. static int pthreadMutexInit(void){ return SQLITE_OK; }
  13685. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  13686. /*
  13687. ** The sqlite3_mutex_alloc() routine allocates a new
  13688. ** mutex and returns a pointer to it. If it returns NULL
  13689. ** that means that a mutex could not be allocated. SQLite
  13690. ** will unwind its stack and return an error. The argument
  13691. ** to sqlite3_mutex_alloc() is one of these integer constants:
  13692. **
  13693. ** <ul>
  13694. ** <li> SQLITE_MUTEX_FAST
  13695. ** <li> SQLITE_MUTEX_RECURSIVE
  13696. ** <li> SQLITE_MUTEX_STATIC_MASTER
  13697. ** <li> SQLITE_MUTEX_STATIC_MEM
  13698. ** <li> SQLITE_MUTEX_STATIC_MEM2
  13699. ** <li> SQLITE_MUTEX_STATIC_PRNG
  13700. ** <li> SQLITE_MUTEX_STATIC_LRU
  13701. ** </ul>
  13702. **
  13703. ** The first two constants cause sqlite3_mutex_alloc() to create
  13704. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  13705. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  13706. ** The mutex implementation does not need to make a distinction
  13707. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  13708. ** not want to. But SQLite will only request a recursive mutex in
  13709. ** cases where it really needs one. If a faster non-recursive mutex
  13710. ** implementation is available on the host platform, the mutex subsystem
  13711. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  13712. **
  13713. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  13714. ** a pointer to a static preexisting mutex. Three static mutexes are
  13715. ** used by the current version of SQLite. Future versions of SQLite
  13716. ** may add additional static mutexes. Static mutexes are for internal
  13717. ** use by SQLite only. Applications that use SQLite mutexes should
  13718. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  13719. ** SQLITE_MUTEX_RECURSIVE.
  13720. **
  13721. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  13722. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  13723. ** returns a different mutex on every call. But for the static
  13724. ** mutex types, the same mutex is returned on every call that has
  13725. ** the same type number.
  13726. */
  13727. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  13728. static sqlite3_mutex staticMutexes[] = {
  13729. SQLite3_MUTEX_INITIALIZER,
  13730. SQLite3_MUTEX_INITIALIZER,
  13731. SQLite3_MUTEX_INITIALIZER,
  13732. SQLite3_MUTEX_INITIALIZER,
  13733. SQLite3_MUTEX_INITIALIZER,
  13734. SQLite3_MUTEX_INITIALIZER
  13735. };
  13736. sqlite3_mutex *p;
  13737. switch( iType ){
  13738. case SQLITE_MUTEX_RECURSIVE: {
  13739. p = sqlite3MallocZero( sizeof(*p) );
  13740. if( p ){
  13741. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13742. /* If recursive mutexes are not available, we will have to
  13743. ** build our own. See below. */
  13744. pthread_mutex_init(&p->mutex, 0);
  13745. #else
  13746. /* Use a recursive mutex if it is available */
  13747. pthread_mutexattr_t recursiveAttr;
  13748. pthread_mutexattr_init(&recursiveAttr);
  13749. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  13750. pthread_mutex_init(&p->mutex, &recursiveAttr);
  13751. pthread_mutexattr_destroy(&recursiveAttr);
  13752. #endif
  13753. p->id = iType;
  13754. }
  13755. break;
  13756. }
  13757. case SQLITE_MUTEX_FAST: {
  13758. p = sqlite3MallocZero( sizeof(*p) );
  13759. if( p ){
  13760. p->id = iType;
  13761. pthread_mutex_init(&p->mutex, 0);
  13762. }
  13763. break;
  13764. }
  13765. default: {
  13766. assert( iType-2 >= 0 );
  13767. assert( iType-2 < ArraySize(staticMutexes) );
  13768. p = &staticMutexes[iType-2];
  13769. p->id = iType;
  13770. break;
  13771. }
  13772. }
  13773. return p;
  13774. }
  13775. /*
  13776. ** This routine deallocates a previously
  13777. ** allocated mutex. SQLite is careful to deallocate every
  13778. ** mutex that it allocates.
  13779. */
  13780. static void pthreadMutexFree(sqlite3_mutex *p){
  13781. assert( p->nRef==0 );
  13782. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  13783. pthread_mutex_destroy(&p->mutex);
  13784. sqlite3_free(p);
  13785. }
  13786. /*
  13787. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  13788. ** to enter a mutex. If another thread is already within the mutex,
  13789. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  13790. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  13791. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  13792. ** be entered multiple times by the same thread. In such cases the,
  13793. ** mutex must be exited an equal number of times before another thread
  13794. ** can enter. If the same thread tries to enter any other kind of mutex
  13795. ** more than once, the behavior is undefined.
  13796. */
  13797. static void pthreadMutexEnter(sqlite3_mutex *p){
  13798. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  13799. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13800. /* If recursive mutexes are not available, then we have to grow
  13801. ** our own. This implementation assumes that pthread_equal()
  13802. ** is atomic - that it cannot be deceived into thinking self
  13803. ** and p->owner are equal if p->owner changes between two values
  13804. ** that are not equal to self while the comparison is taking place.
  13805. ** This implementation also assumes a coherent cache - that
  13806. ** separate processes cannot read different values from the same
  13807. ** address at the same time. If either of these two conditions
  13808. ** are not met, then the mutexes will fail and problems will result.
  13809. */
  13810. {
  13811. pthread_t self = pthread_self();
  13812. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  13813. p->nRef++;
  13814. }else{
  13815. pthread_mutex_lock(&p->mutex);
  13816. assert( p->nRef==0 );
  13817. p->owner = self;
  13818. p->nRef = 1;
  13819. }
  13820. }
  13821. #else
  13822. /* Use the built-in recursive mutexes if they are available.
  13823. */
  13824. pthread_mutex_lock(&p->mutex);
  13825. p->owner = pthread_self();
  13826. p->nRef++;
  13827. #endif
  13828. #ifdef SQLITE_DEBUG
  13829. if( p->trace ){
  13830. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  13831. }
  13832. #endif
  13833. }
  13834. static int pthreadMutexTry(sqlite3_mutex *p){
  13835. int rc;
  13836. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  13837. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13838. /* If recursive mutexes are not available, then we have to grow
  13839. ** our own. This implementation assumes that pthread_equal()
  13840. ** is atomic - that it cannot be deceived into thinking self
  13841. ** and p->owner are equal if p->owner changes between two values
  13842. ** that are not equal to self while the comparison is taking place.
  13843. ** This implementation also assumes a coherent cache - that
  13844. ** separate processes cannot read different values from the same
  13845. ** address at the same time. If either of these two conditions
  13846. ** are not met, then the mutexes will fail and problems will result.
  13847. */
  13848. {
  13849. pthread_t self = pthread_self();
  13850. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  13851. p->nRef++;
  13852. rc = SQLITE_OK;
  13853. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  13854. assert( p->nRef==0 );
  13855. p->owner = self;
  13856. p->nRef = 1;
  13857. rc = SQLITE_OK;
  13858. }else{
  13859. rc = SQLITE_BUSY;
  13860. }
  13861. }
  13862. #else
  13863. /* Use the built-in recursive mutexes if they are available.
  13864. */
  13865. if( pthread_mutex_trylock(&p->mutex)==0 ){
  13866. p->owner = pthread_self();
  13867. p->nRef++;
  13868. rc = SQLITE_OK;
  13869. }else{
  13870. rc = SQLITE_BUSY;
  13871. }
  13872. #endif
  13873. #ifdef SQLITE_DEBUG
  13874. if( rc==SQLITE_OK && p->trace ){
  13875. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  13876. }
  13877. #endif
  13878. return rc;
  13879. }
  13880. /*
  13881. ** The sqlite3_mutex_leave() routine exits a mutex that was
  13882. ** previously entered by the same thread. The behavior
  13883. ** is undefined if the mutex is not currently entered or
  13884. ** is not currently allocated. SQLite will never do either.
  13885. */
  13886. static void pthreadMutexLeave(sqlite3_mutex *p){
  13887. assert( pthreadMutexHeld(p) );
  13888. p->nRef--;
  13889. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  13890. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13891. if( p->nRef==0 ){
  13892. pthread_mutex_unlock(&p->mutex);
  13893. }
  13894. #else
  13895. pthread_mutex_unlock(&p->mutex);
  13896. #endif
  13897. #ifdef SQLITE_DEBUG
  13898. if( p->trace ){
  13899. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  13900. }
  13901. #endif
  13902. }
  13903. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  13904. static sqlite3_mutex_methods sMutex = {
  13905. pthreadMutexInit,
  13906. pthreadMutexEnd,
  13907. pthreadMutexAlloc,
  13908. pthreadMutexFree,
  13909. pthreadMutexEnter,
  13910. pthreadMutexTry,
  13911. pthreadMutexLeave,
  13912. #ifdef SQLITE_DEBUG
  13913. pthreadMutexHeld,
  13914. pthreadMutexNotheld
  13915. #else
  13916. 0,
  13917. 0
  13918. #endif
  13919. };
  13920. return &sMutex;
  13921. }
  13922. #endif /* SQLITE_MUTEX_PTHREAD */
  13923. /************** End of mutex_unix.c ******************************************/
  13924. /************** Begin file mutex_w32.c ***************************************/
  13925. /*
  13926. ** 2007 August 14
  13927. **
  13928. ** The author disclaims copyright to this source code. In place of
  13929. ** a legal notice, here is a blessing:
  13930. **
  13931. ** May you do good and not evil.
  13932. ** May you find forgiveness for yourself and forgive others.
  13933. ** May you share freely, never taking more than you give.
  13934. **
  13935. *************************************************************************
  13936. ** This file contains the C functions that implement mutexes for win32
  13937. **
  13938. ** $Id: mutex_w32.c,v 1.15 2009/01/30 16:09:23 shane Exp $
  13939. */
  13940. /*
  13941. ** The code in this file is only used if we are compiling multithreaded
  13942. ** on a win32 system.
  13943. */
  13944. #ifdef SQLITE_MUTEX_W32
  13945. /*
  13946. ** Each recursive mutex is an instance of the following structure.
  13947. */
  13948. struct sqlite3_mutex {
  13949. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  13950. int id; /* Mutex type */
  13951. int nRef; /* Number of enterances */
  13952. DWORD owner; /* Thread holding this mutex */
  13953. };
  13954. /*
  13955. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  13956. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  13957. **
  13958. ** Here is an interesting observation: Win95, Win98, and WinME lack
  13959. ** the LockFileEx() API. But we can still statically link against that
  13960. ** API as long as we don't call it win running Win95/98/ME. A call to
  13961. ** this routine is used to determine if the host is Win95/98/ME or
  13962. ** WinNT/2K/XP so that we will know whether or not we can safely call
  13963. ** the LockFileEx() API.
  13964. **
  13965. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  13966. ** which is only available if your application was compiled with
  13967. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  13968. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  13969. ** this out as well.
  13970. */
  13971. #if 0
  13972. #if SQLITE_OS_WINCE
  13973. # define mutexIsNT() (1)
  13974. #else
  13975. static int mutexIsNT(void){
  13976. static int osType = 0;
  13977. if( osType==0 ){
  13978. OSVERSIONINFO sInfo;
  13979. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  13980. GetVersionEx(&sInfo);
  13981. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  13982. }
  13983. return osType==2;
  13984. }
  13985. #endif /* SQLITE_OS_WINCE */
  13986. #endif
  13987. #ifdef SQLITE_DEBUG
  13988. /*
  13989. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  13990. ** intended for use only inside assert() statements.
  13991. */
  13992. static int winMutexHeld(sqlite3_mutex *p){
  13993. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  13994. }
  13995. static int winMutexNotheld(sqlite3_mutex *p){
  13996. return p->nRef==0 || p->owner!=GetCurrentThreadId();
  13997. }
  13998. #endif
  13999. /*
  14000. ** Initialize and deinitialize the mutex subsystem.
  14001. */
  14002. static int winMutexInit(void){ return SQLITE_OK; }
  14003. static int winMutexEnd(void){ return SQLITE_OK; }
  14004. /*
  14005. ** The sqlite3_mutex_alloc() routine allocates a new
  14006. ** mutex and returns a pointer to it. If it returns NULL
  14007. ** that means that a mutex could not be allocated. SQLite
  14008. ** will unwind its stack and return an error. The argument
  14009. ** to sqlite3_mutex_alloc() is one of these integer constants:
  14010. **
  14011. ** <ul>
  14012. ** <li> SQLITE_MUTEX_FAST 0
  14013. ** <li> SQLITE_MUTEX_RECURSIVE 1
  14014. ** <li> SQLITE_MUTEX_STATIC_MASTER 2
  14015. ** <li> SQLITE_MUTEX_STATIC_MEM 3
  14016. ** <li> SQLITE_MUTEX_STATIC_PRNG 4
  14017. ** </ul>
  14018. **
  14019. ** The first two constants cause sqlite3_mutex_alloc() to create
  14020. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  14021. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  14022. ** The mutex implementation does not need to make a distinction
  14023. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  14024. ** not want to. But SQLite will only request a recursive mutex in
  14025. ** cases where it really needs one. If a faster non-recursive mutex
  14026. ** implementation is available on the host platform, the mutex subsystem
  14027. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  14028. **
  14029. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  14030. ** a pointer to a static preexisting mutex. Three static mutexes are
  14031. ** used by the current version of SQLite. Future versions of SQLite
  14032. ** may add additional static mutexes. Static mutexes are for internal
  14033. ** use by SQLite only. Applications that use SQLite mutexes should
  14034. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  14035. ** SQLITE_MUTEX_RECURSIVE.
  14036. **
  14037. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  14038. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  14039. ** returns a different mutex on every call. But for the static
  14040. ** mutex types, the same mutex is returned on every call that has
  14041. ** the same type number.
  14042. */
  14043. static sqlite3_mutex *winMutexAlloc(int iType){
  14044. sqlite3_mutex *p;
  14045. switch( iType ){
  14046. case SQLITE_MUTEX_FAST:
  14047. case SQLITE_MUTEX_RECURSIVE: {
  14048. p = sqlite3MallocZero( sizeof(*p) );
  14049. if( p ){
  14050. p->id = iType;
  14051. InitializeCriticalSection(&p->mutex);
  14052. }
  14053. break;
  14054. }
  14055. default: {
  14056. static sqlite3_mutex staticMutexes[6];
  14057. static int isInit = 0;
  14058. while( !isInit ){
  14059. static long lock = 0;
  14060. if( InterlockedIncrement(&lock)==1 ){
  14061. int i;
  14062. for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
  14063. InitializeCriticalSection(&staticMutexes[i].mutex);
  14064. }
  14065. isInit = 1;
  14066. }else{
  14067. Sleep(1);
  14068. }
  14069. }
  14070. assert( iType-2 >= 0 );
  14071. assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
  14072. p = &staticMutexes[iType-2];
  14073. p->id = iType;
  14074. break;
  14075. }
  14076. }
  14077. return p;
  14078. }
  14079. /*
  14080. ** This routine deallocates a previously
  14081. ** allocated mutex. SQLite is careful to deallocate every
  14082. ** mutex that it allocates.
  14083. */
  14084. static void winMutexFree(sqlite3_mutex *p){
  14085. assert( p );
  14086. assert( p->nRef==0 );
  14087. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  14088. DeleteCriticalSection(&p->mutex);
  14089. sqlite3_free(p);
  14090. }
  14091. /*
  14092. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  14093. ** to enter a mutex. If another thread is already within the mutex,
  14094. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  14095. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  14096. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  14097. ** be entered multiple times by the same thread. In such cases the,
  14098. ** mutex must be exited an equal number of times before another thread
  14099. ** can enter. If the same thread tries to enter any other kind of mutex
  14100. ** more than once, the behavior is undefined.
  14101. */
  14102. static void winMutexEnter(sqlite3_mutex *p){
  14103. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
  14104. EnterCriticalSection(&p->mutex);
  14105. p->owner = GetCurrentThreadId();
  14106. p->nRef++;
  14107. }
  14108. static int winMutexTry(sqlite3_mutex *p){
  14109. int rc = SQLITE_BUSY;
  14110. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
  14111. /*
  14112. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  14113. ** is used it is merely an optimization. So it is OK for it to always
  14114. ** fail.
  14115. **
  14116. ** The TryEnterCriticalSection() interface is only available on WinNT.
  14117. ** And some windows compilers complain if you try to use it without
  14118. ** first doing some #defines that prevent SQLite from building on Win98.
  14119. ** For that reason, we will omit this optimization for now. See
  14120. ** ticket #2685.
  14121. */
  14122. #if 0
  14123. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  14124. p->owner = GetCurrentThreadId();
  14125. p->nRef++;
  14126. rc = SQLITE_OK;
  14127. }
  14128. #else
  14129. UNUSED_PARAMETER(p);
  14130. #endif
  14131. return rc;
  14132. }
  14133. /*
  14134. ** The sqlite3_mutex_leave() routine exits a mutex that was
  14135. ** previously entered by the same thread. The behavior
  14136. ** is undefined if the mutex is not currently entered or
  14137. ** is not currently allocated. SQLite will never do either.
  14138. */
  14139. static void winMutexLeave(sqlite3_mutex *p){
  14140. assert( p->nRef>0 );
  14141. assert( p->owner==GetCurrentThreadId() );
  14142. p->nRef--;
  14143. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  14144. LeaveCriticalSection(&p->mutex);
  14145. }
  14146. SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
  14147. static sqlite3_mutex_methods sMutex = {
  14148. winMutexInit,
  14149. winMutexEnd,
  14150. winMutexAlloc,
  14151. winMutexFree,
  14152. winMutexEnter,
  14153. winMutexTry,
  14154. winMutexLeave,
  14155. #ifdef SQLITE_DEBUG
  14156. winMutexHeld,
  14157. winMutexNotheld
  14158. #else
  14159. 0,
  14160. 0
  14161. #endif
  14162. };
  14163. return &sMutex;
  14164. }
  14165. #endif /* SQLITE_MUTEX_W32 */
  14166. /************** End of mutex_w32.c *******************************************/
  14167. /************** Begin file malloc.c ******************************************/
  14168. /*
  14169. ** 2001 September 15
  14170. **
  14171. ** The author disclaims copyright to this source code. In place of
  14172. ** a legal notice, here is a blessing:
  14173. **
  14174. ** May you do good and not evil.
  14175. ** May you find forgiveness for yourself and forgive others.
  14176. ** May you share freely, never taking more than you give.
  14177. **
  14178. *************************************************************************
  14179. **
  14180. ** Memory allocation functions used throughout sqlite.
  14181. **
  14182. ** $Id: malloc.c,v 1.61 2009/03/24 15:08:10 drh Exp $
  14183. */
  14184. /*
  14185. ** This routine runs when the memory allocator sees that the
  14186. ** total memory allocation is about to exceed the soft heap
  14187. ** limit.
  14188. */
  14189. static void softHeapLimitEnforcer(
  14190. void *NotUsed,
  14191. sqlite3_int64 NotUsed2,
  14192. int allocSize
  14193. ){
  14194. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14195. sqlite3_release_memory(allocSize);
  14196. }
  14197. /*
  14198. ** Set the soft heap-size limit for the library. Passing a zero or
  14199. ** negative value indicates no limit.
  14200. */
  14201. SQLITE_API void sqlite3_soft_heap_limit(int n){
  14202. sqlite3_uint64 iLimit;
  14203. int overage;
  14204. if( n<0 ){
  14205. iLimit = 0;
  14206. }else{
  14207. iLimit = n;
  14208. }
  14209. sqlite3_initialize();
  14210. if( iLimit>0 ){
  14211. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
  14212. }else{
  14213. sqlite3MemoryAlarm(0, 0, 0);
  14214. }
  14215. overage = (int)(sqlite3_memory_used() - (i64)n);
  14216. if( overage>0 ){
  14217. sqlite3_release_memory(overage);
  14218. }
  14219. }
  14220. /*
  14221. ** Attempt to release up to n bytes of non-essential memory currently
  14222. ** held by SQLite. An example of non-essential memory is memory used to
  14223. ** cache database pages that are not currently in use.
  14224. */
  14225. SQLITE_API int sqlite3_release_memory(int n){
  14226. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  14227. int nRet = 0;
  14228. #if 0
  14229. nRet += sqlite3VdbeReleaseMemory(n);
  14230. #endif
  14231. nRet += sqlite3PcacheReleaseMemory(n-nRet);
  14232. return nRet;
  14233. #else
  14234. UNUSED_PARAMETER(n);
  14235. return SQLITE_OK;
  14236. #endif
  14237. }
  14238. /*
  14239. ** State information local to the memory allocation subsystem.
  14240. */
  14241. static SQLITE_WSD struct Mem0Global {
  14242. /* Number of free pages for scratch and page-cache memory */
  14243. u32 nScratchFree;
  14244. u32 nPageFree;
  14245. sqlite3_mutex *mutex; /* Mutex to serialize access */
  14246. /*
  14247. ** The alarm callback and its arguments. The mem0.mutex lock will
  14248. ** be held while the callback is running. Recursive calls into
  14249. ** the memory subsystem are allowed, but no new callbacks will be
  14250. ** issued. The alarmBusy variable is set to prevent recursive
  14251. ** callbacks.
  14252. */
  14253. sqlite3_int64 alarmThreshold;
  14254. void (*alarmCallback)(void*, sqlite3_int64,int);
  14255. void *alarmArg;
  14256. int alarmBusy;
  14257. /*
  14258. ** Pointers to the end of sqlite3GlobalConfig.pScratch and
  14259. ** sqlite3GlobalConfig.pPage to a block of memory that records
  14260. ** which pages are available.
  14261. */
  14262. u32 *aScratchFree;
  14263. u32 *aPageFree;
  14264. } mem0 = { 62560955, 0, 0, 0, 0, 0, 0, 0, 0 };
  14265. #define mem0 GLOBAL(struct Mem0Global, mem0)
  14266. /*
  14267. ** Initialize the memory allocation subsystem.
  14268. */
  14269. SQLITE_PRIVATE int sqlite3MallocInit(void){
  14270. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  14271. sqlite3MemSetDefault();
  14272. }
  14273. memset(&mem0, 0, sizeof(mem0));
  14274. if( sqlite3GlobalConfig.bCoreMutex ){
  14275. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  14276. }
  14277. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  14278. && sqlite3GlobalConfig.nScratch>=0 ){
  14279. int i;
  14280. sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
  14281. mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
  14282. [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
  14283. for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
  14284. mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
  14285. }else{
  14286. sqlite3GlobalConfig.pScratch = 0;
  14287. sqlite3GlobalConfig.szScratch = 0;
  14288. }
  14289. if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
  14290. && sqlite3GlobalConfig.nPage>=1 ){
  14291. int i;
  14292. int overhead;
  14293. int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
  14294. int n = sqlite3GlobalConfig.nPage;
  14295. overhead = (4*n + sz - 1)/sz;
  14296. sqlite3GlobalConfig.nPage -= overhead;
  14297. mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
  14298. [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
  14299. for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
  14300. mem0.nPageFree = sqlite3GlobalConfig.nPage;
  14301. }else{
  14302. sqlite3GlobalConfig.pPage = 0;
  14303. sqlite3GlobalConfig.szPage = 0;
  14304. }
  14305. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  14306. }
  14307. /*
  14308. ** Deinitialize the memory allocation subsystem.
  14309. */
  14310. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  14311. if( sqlite3GlobalConfig.m.xShutdown ){
  14312. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  14313. }
  14314. memset(&mem0, 0, sizeof(mem0));
  14315. }
  14316. /*
  14317. ** Return the amount of memory currently checked out.
  14318. */
  14319. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  14320. int n, mx;
  14321. sqlite3_int64 res;
  14322. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  14323. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  14324. return res;
  14325. }
  14326. /*
  14327. ** Return the maximum amount of memory that has ever been
  14328. ** checked out since either the beginning of this process
  14329. ** or since the most recent reset.
  14330. */
  14331. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  14332. int n, mx;
  14333. sqlite3_int64 res;
  14334. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  14335. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  14336. return res;
  14337. }
  14338. /*
  14339. ** Change the alarm callback
  14340. */
  14341. SQLITE_PRIVATE int sqlite3MemoryAlarm(
  14342. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  14343. void *pArg,
  14344. sqlite3_int64 iThreshold
  14345. ){
  14346. sqlite3_mutex_enter(mem0.mutex);
  14347. mem0.alarmCallback = xCallback;
  14348. mem0.alarmArg = pArg;
  14349. mem0.alarmThreshold = iThreshold;
  14350. sqlite3_mutex_leave(mem0.mutex);
  14351. return SQLITE_OK;
  14352. }
  14353. #ifndef SQLITE_OMIT_DEPRECATED
  14354. /*
  14355. ** Deprecated external interface. Internal/core SQLite code
  14356. ** should call sqlite3MemoryAlarm.
  14357. */
  14358. SQLITE_API int sqlite3_memory_alarm(
  14359. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  14360. void *pArg,
  14361. sqlite3_int64 iThreshold
  14362. ){
  14363. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  14364. }
  14365. #endif
  14366. /*
  14367. ** Trigger the alarm
  14368. */
  14369. static void sqlite3MallocAlarm(int nByte){
  14370. void (*xCallback)(void*,sqlite3_int64,int);
  14371. sqlite3_int64 nowUsed;
  14372. void *pArg;
  14373. if( mem0.alarmCallback==0 || mem0.alarmBusy ) return;
  14374. mem0.alarmBusy = 1;
  14375. xCallback = mem0.alarmCallback;
  14376. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  14377. pArg = mem0.alarmArg;
  14378. sqlite3_mutex_leave(mem0.mutex);
  14379. xCallback(pArg, nowUsed, nByte);
  14380. sqlite3_mutex_enter(mem0.mutex);
  14381. mem0.alarmBusy = 0;
  14382. }
  14383. /*
  14384. ** Do a memory allocation with statistics and alarms. Assume the
  14385. ** lock is already held.
  14386. */
  14387. static int mallocWithAlarm(int n, void **pp){
  14388. int nFull;
  14389. void *p;
  14390. assert( sqlite3_mutex_held(mem0.mutex) );
  14391. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  14392. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  14393. if( mem0.alarmCallback!=0 ){
  14394. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  14395. if( nUsed+nFull >= mem0.alarmThreshold ){
  14396. sqlite3MallocAlarm(nFull);
  14397. }
  14398. }
  14399. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  14400. if( p==0 && mem0.alarmCallback ){
  14401. sqlite3MallocAlarm(nFull);
  14402. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  14403. }
  14404. if( p ){
  14405. nFull = sqlite3MallocSize(p);
  14406. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  14407. }
  14408. *pp = p;
  14409. return nFull;
  14410. }
  14411. /*
  14412. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  14413. ** assumes the memory subsystem has already been initialized.
  14414. */
  14415. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  14416. void *p;
  14417. if( n<=0 || NEVER(n>=0x7fffff00) ){
  14418. /* The NEVER(n>=0x7fffff00) term is added out of paranoia. We want to make
  14419. ** absolutely sure that there is nothing within SQLite that can cause a
  14420. ** memory allocation of a number of bytes which is near the maximum signed
  14421. ** integer value and thus cause an integer overflow inside of the xMalloc()
  14422. ** implementation. The n>=0x7fffff00 gives us 255 bytes of headroom. The
  14423. ** test should never be true because SQLITE_MAX_LENGTH should be much
  14424. ** less than 0x7fffff00 and it should catch large memory allocations
  14425. ** before they reach this point. */
  14426. p = 0;
  14427. }else if( sqlite3GlobalConfig.bMemstat ){
  14428. sqlite3_mutex_enter(mem0.mutex);
  14429. mallocWithAlarm(n, &p);
  14430. sqlite3_mutex_leave(mem0.mutex);
  14431. }else{
  14432. p = sqlite3GlobalConfig.m.xMalloc(n);
  14433. }
  14434. return p;
  14435. }
  14436. /*
  14437. ** This version of the memory allocation is for use by the application.
  14438. ** First make sure the memory subsystem is initialized, then do the
  14439. ** allocation.
  14440. */
  14441. SQLITE_API void *sqlite3_malloc(int n){
  14442. #ifndef SQLITE_OMIT_AUTOINIT
  14443. if( sqlite3_initialize() ) return 0;
  14444. #endif
  14445. return sqlite3Malloc(n);
  14446. }
  14447. /*
  14448. ** Each thread may only have a single outstanding allocation from
  14449. ** xScratchMalloc(). We verify this constraint in the single-threaded
  14450. ** case by setting scratchAllocOut to 1 when an allocation
  14451. ** is outstanding clearing it when the allocation is freed.
  14452. */
  14453. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  14454. static int scratchAllocOut = 0;
  14455. #endif
  14456. /*
  14457. ** Allocate memory that is to be used and released right away.
  14458. ** This routine is similar to alloca() in that it is not intended
  14459. ** for situations where the memory might be held long-term. This
  14460. ** routine is intended to get memory to old large transient data
  14461. ** structures that would not normally fit on the stack of an
  14462. ** embedded processor.
  14463. */
  14464. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  14465. void *p;
  14466. assert( n>0 );
  14467. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  14468. /* Verify that no more than one scratch allocation per thread
  14469. ** is outstanding at one time. (This is only checked in the
  14470. ** single-threaded case since checking in the multi-threaded case
  14471. ** would be much more complicated.) */
  14472. assert( scratchAllocOut==0 );
  14473. #endif
  14474. if( sqlite3GlobalConfig.szScratch<n ){
  14475. goto scratch_overflow;
  14476. }else{
  14477. sqlite3_mutex_enter(mem0.mutex);
  14478. if( mem0.nScratchFree==0 ){
  14479. sqlite3_mutex_leave(mem0.mutex);
  14480. goto scratch_overflow;
  14481. }else{
  14482. int i;
  14483. i = mem0.aScratchFree[--mem0.nScratchFree];
  14484. i *= sqlite3GlobalConfig.szScratch;
  14485. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  14486. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  14487. sqlite3_mutex_leave(mem0.mutex);
  14488. p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
  14489. assert( (((u8*)p - (u8*)0) & 7)==0 );
  14490. }
  14491. }
  14492. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  14493. scratchAllocOut = p!=0;
  14494. #endif
  14495. return p;
  14496. scratch_overflow:
  14497. if( sqlite3GlobalConfig.bMemstat ){
  14498. sqlite3_mutex_enter(mem0.mutex);
  14499. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  14500. n = mallocWithAlarm(n, &p);
  14501. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  14502. sqlite3_mutex_leave(mem0.mutex);
  14503. }else{
  14504. p = sqlite3GlobalConfig.m.xMalloc(n);
  14505. }
  14506. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  14507. scratchAllocOut = p!=0;
  14508. #endif
  14509. return p;
  14510. }
  14511. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  14512. if( p ){
  14513. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  14514. /* Verify that no more than one scratch allocation per thread
  14515. ** is outstanding at one time. (This is only checked in the
  14516. ** single-threaded case since checking in the multi-threaded case
  14517. ** would be much more complicated.) */
  14518. assert( scratchAllocOut==1 );
  14519. scratchAllocOut = 0;
  14520. #endif
  14521. if( sqlite3GlobalConfig.pScratch==0
  14522. || p<sqlite3GlobalConfig.pScratch
  14523. || p>=(void*)mem0.aScratchFree ){
  14524. if( sqlite3GlobalConfig.bMemstat ){
  14525. int iSize = sqlite3MallocSize(p);
  14526. sqlite3_mutex_enter(mem0.mutex);
  14527. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  14528. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  14529. sqlite3GlobalConfig.m.xFree(p);
  14530. sqlite3_mutex_leave(mem0.mutex);
  14531. }else{
  14532. sqlite3GlobalConfig.m.xFree(p);
  14533. }
  14534. }else{
  14535. int i;
  14536. i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
  14537. i /= sqlite3GlobalConfig.szScratch;
  14538. assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
  14539. sqlite3_mutex_enter(mem0.mutex);
  14540. assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
  14541. mem0.aScratchFree[mem0.nScratchFree++] = i;
  14542. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  14543. sqlite3_mutex_leave(mem0.mutex);
  14544. }
  14545. }
  14546. }
  14547. /*
  14548. ** TRUE if p is a lookaside memory allocation from db
  14549. */
  14550. #ifndef SQLITE_OMIT_LOOKASIDE
  14551. static int isLookaside(sqlite3 *db, void *p){
  14552. return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  14553. }
  14554. #else
  14555. #define isLookaside(A,B) 0
  14556. #endif
  14557. /*
  14558. ** Return the size of a memory allocation previously obtained from
  14559. ** sqlite3Malloc() or sqlite3_malloc().
  14560. */
  14561. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  14562. return sqlite3GlobalConfig.m.xSize(p);
  14563. }
  14564. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  14565. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  14566. if( p==0 ){
  14567. return 0;
  14568. }else if( isLookaside(db, p) ){
  14569. return db->lookaside.sz;
  14570. }else{
  14571. return sqlite3GlobalConfig.m.xSize(p);
  14572. }
  14573. }
  14574. /*
  14575. ** Free memory previously obtained from sqlite3Malloc().
  14576. */
  14577. SQLITE_API void sqlite3_free(void *p){
  14578. if( p==0 ) return;
  14579. if( sqlite3GlobalConfig.bMemstat ){
  14580. sqlite3_mutex_enter(mem0.mutex);
  14581. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  14582. sqlite3GlobalConfig.m.xFree(p);
  14583. sqlite3_mutex_leave(mem0.mutex);
  14584. }else{
  14585. sqlite3GlobalConfig.m.xFree(p);
  14586. }
  14587. }
  14588. /*
  14589. ** Free memory that might be associated with a particular database
  14590. ** connection.
  14591. */
  14592. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  14593. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  14594. if( isLookaside(db, p) ){
  14595. LookasideSlot *pBuf = (LookasideSlot*)p;
  14596. pBuf->pNext = db->lookaside.pFree;
  14597. db->lookaside.pFree = pBuf;
  14598. db->lookaside.nOut--;
  14599. }else{
  14600. sqlite3_free(p);
  14601. }
  14602. }
  14603. /*
  14604. ** Change the size of an existing memory allocation
  14605. */
  14606. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  14607. int nOld, nNew;
  14608. void *pNew;
  14609. if( pOld==0 ){
  14610. return sqlite3Malloc(nBytes);
  14611. }
  14612. if( nBytes<=0 || NEVER(nBytes>=0x7fffff00) ){
  14613. /* The NEVER(...) term is explained in comments on sqlite3Malloc() */
  14614. sqlite3_free(pOld);
  14615. return 0;
  14616. }
  14617. nOld = sqlite3MallocSize(pOld);
  14618. if( sqlite3GlobalConfig.bMemstat ){
  14619. sqlite3_mutex_enter(mem0.mutex);
  14620. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  14621. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  14622. if( nOld==nNew ){
  14623. pNew = pOld;
  14624. }else{
  14625. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
  14626. mem0.alarmThreshold ){
  14627. sqlite3MallocAlarm(nNew-nOld);
  14628. }
  14629. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  14630. if( pNew==0 && mem0.alarmCallback ){
  14631. sqlite3MallocAlarm(nBytes);
  14632. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  14633. }
  14634. if( pNew ){
  14635. nNew = sqlite3MallocSize(pNew);
  14636. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  14637. }
  14638. }
  14639. sqlite3_mutex_leave(mem0.mutex);
  14640. }else{
  14641. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
  14642. }
  14643. return pNew;
  14644. }
  14645. /*
  14646. ** The public interface to sqlite3Realloc. Make sure that the memory
  14647. ** subsystem is initialized prior to invoking sqliteRealloc.
  14648. */
  14649. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  14650. #ifndef SQLITE_OMIT_AUTOINIT
  14651. if( sqlite3_initialize() ) return 0;
  14652. #endif
  14653. return sqlite3Realloc(pOld, n);
  14654. }
  14655. /*
  14656. ** Allocate and zero memory.
  14657. */
  14658. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  14659. void *p = sqlite3Malloc(n);
  14660. if( p ){
  14661. memset(p, 0, n);
  14662. }
  14663. return p;
  14664. }
  14665. /*
  14666. ** Allocate and zero memory. If the allocation fails, make
  14667. ** the mallocFailed flag in the connection pointer.
  14668. */
  14669. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  14670. void *p = sqlite3DbMallocRaw(db, n);
  14671. if( p ){
  14672. memset(p, 0, n);
  14673. }
  14674. return p;
  14675. }
  14676. /*
  14677. ** Allocate and zero memory. If the allocation fails, make
  14678. ** the mallocFailed flag in the connection pointer.
  14679. **
  14680. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  14681. ** failure on the same database connection) then always return 0.
  14682. ** Hence for a particular database connection, once malloc starts
  14683. ** failing, it fails consistently until mallocFailed is reset.
  14684. ** This is an important assumption. There are many places in the
  14685. ** code that do things like this:
  14686. **
  14687. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  14688. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  14689. ** if( b ) a[10] = 9;
  14690. **
  14691. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  14692. ** that all prior mallocs (ex: "a") worked too.
  14693. */
  14694. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  14695. void *p;
  14696. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  14697. #ifndef SQLITE_OMIT_LOOKASIDE
  14698. if( db ){
  14699. LookasideSlot *pBuf;
  14700. if( db->mallocFailed ){
  14701. return 0;
  14702. }
  14703. if( db->lookaside.bEnabled && n<=db->lookaside.sz
  14704. && (pBuf = db->lookaside.pFree)!=0 ){
  14705. db->lookaside.pFree = pBuf->pNext;
  14706. db->lookaside.nOut++;
  14707. if( db->lookaside.nOut>db->lookaside.mxOut ){
  14708. db->lookaside.mxOut = db->lookaside.nOut;
  14709. }
  14710. return (void*)pBuf;
  14711. }
  14712. }
  14713. #else
  14714. if( db && db->mallocFailed ){
  14715. return 0;
  14716. }
  14717. #endif
  14718. p = sqlite3Malloc(n);
  14719. if( !p && db ){
  14720. db->mallocFailed = 1;
  14721. }
  14722. return p;
  14723. }
  14724. /*
  14725. ** Resize the block of memory pointed to by p to n bytes. If the
  14726. ** resize fails, set the mallocFailed flag in the connection object.
  14727. */
  14728. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  14729. void *pNew = 0;
  14730. assert( db!=0 );
  14731. assert( sqlite3_mutex_held(db->mutex) );
  14732. if( db->mallocFailed==0 ){
  14733. if( p==0 ){
  14734. return sqlite3DbMallocRaw(db, n);
  14735. }
  14736. if( isLookaside(db, p) ){
  14737. if( n<=db->lookaside.sz ){
  14738. return p;
  14739. }
  14740. pNew = sqlite3DbMallocRaw(db, n);
  14741. if( pNew ){
  14742. memcpy(pNew, p, db->lookaside.sz);
  14743. sqlite3DbFree(db, p);
  14744. }
  14745. }else{
  14746. pNew = sqlite3_realloc(p, n);
  14747. if( !pNew ){
  14748. db->mallocFailed = 1;
  14749. }
  14750. }
  14751. }
  14752. return pNew;
  14753. }
  14754. /*
  14755. ** Attempt to reallocate p. If the reallocation fails, then free p
  14756. ** and set the mallocFailed flag in the database connection.
  14757. */
  14758. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  14759. void *pNew;
  14760. pNew = sqlite3DbRealloc(db, p, n);
  14761. if( !pNew ){
  14762. sqlite3DbFree(db, p);
  14763. }
  14764. return pNew;
  14765. }
  14766. /*
  14767. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  14768. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  14769. ** is because when memory debugging is turned on, these two functions are
  14770. ** called via macros that record the current file and line number in the
  14771. ** ThreadData structure.
  14772. */
  14773. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  14774. char *zNew;
  14775. size_t n;
  14776. if( z==0 ){
  14777. return 0;
  14778. }
  14779. n = (db ? sqlite3Strlen(db, z) : sqlite3Strlen30(z))+1;
  14780. assert( (n&0x7fffffff)==n );
  14781. zNew = sqlite3DbMallocRaw(db, (int)n);
  14782. if( zNew ){
  14783. memcpy(zNew, z, n);
  14784. }
  14785. return zNew;
  14786. }
  14787. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  14788. char *zNew;
  14789. if( z==0 ){
  14790. return 0;
  14791. }
  14792. assert( (n&0x7fffffff)==n );
  14793. zNew = sqlite3DbMallocRaw(db, n+1);
  14794. if( zNew ){
  14795. memcpy(zNew, z, n);
  14796. zNew[n] = 0;
  14797. }
  14798. return zNew;
  14799. }
  14800. /*
  14801. ** Create a string from the zFromat argument and the va_list that follows.
  14802. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  14803. ** point to that string.
  14804. */
  14805. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  14806. va_list ap;
  14807. char *z;
  14808. va_start(ap, zFormat);
  14809. z = sqlite3VMPrintf(db, zFormat, ap);
  14810. va_end(ap);
  14811. sqlite3DbFree(db, *pz);
  14812. *pz = z;
  14813. }
  14814. /*
  14815. ** This function must be called before exiting any API function (i.e.
  14816. ** returning control to the user) that has called sqlite3_malloc or
  14817. ** sqlite3_realloc.
  14818. **
  14819. ** The returned value is normally a copy of the second argument to this
  14820. ** function. However, if a malloc() failure has occurred since the previous
  14821. ** invocation SQLITE_NOMEM is returned instead.
  14822. **
  14823. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  14824. ** then the connection error-code (the value returned by sqlite3_errcode())
  14825. ** is set to SQLITE_NOMEM.
  14826. */
  14827. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  14828. /* If the db handle is not NULL, then we must hold the connection handle
  14829. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  14830. ** is unsafe, as is the call to sqlite3Error().
  14831. */
  14832. assert( !db || sqlite3_mutex_held(db->mutex) );
  14833. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  14834. sqlite3Error(db, SQLITE_NOMEM, 0);
  14835. db->mallocFailed = 0;
  14836. rc = SQLITE_NOMEM;
  14837. }
  14838. return rc & (db ? db->errMask : 0xff);
  14839. }
  14840. /************** End of malloc.c **********************************************/
  14841. /************** Begin file printf.c ******************************************/
  14842. /*
  14843. ** The "printf" code that follows dates from the 1980's. It is in
  14844. ** the public domain. The original comments are included here for
  14845. ** completeness. They are very out-of-date but might be useful as
  14846. ** an historical reference. Most of the "enhancements" have been backed
  14847. ** out so that the functionality is now the same as standard printf().
  14848. **
  14849. ** $Id: printf.c,v 1.102 2009/04/08 16:10:04 drh Exp $
  14850. **
  14851. **************************************************************************
  14852. **
  14853. ** The following modules is an enhanced replacement for the "printf" subroutines
  14854. ** found in the standard C library. The following enhancements are
  14855. ** supported:
  14856. **
  14857. ** + Additional functions. The standard set of "printf" functions
  14858. ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
  14859. ** vsprintf. This module adds the following:
  14860. **
  14861. ** * snprintf -- Works like sprintf, but has an extra argument
  14862. ** which is the size of the buffer written to.
  14863. **
  14864. ** * mprintf -- Similar to sprintf. Writes output to memory
  14865. ** obtained from malloc.
  14866. **
  14867. ** * xprintf -- Calls a function to dispose of output.
  14868. **
  14869. ** * nprintf -- No output, but returns the number of characters
  14870. ** that would have been output by printf.
  14871. **
  14872. ** * A v- version (ex: vsnprintf) of every function is also
  14873. ** supplied.
  14874. **
  14875. ** + A few extensions to the formatting notation are supported:
  14876. **
  14877. ** * The "=" flag (similar to "-") causes the output to be
  14878. ** be centered in the appropriately sized field.
  14879. **
  14880. ** * The %b field outputs an integer in binary notation.
  14881. **
  14882. ** * The %c field now accepts a precision. The character output
  14883. ** is repeated by the number of times the precision specifies.
  14884. **
  14885. ** * The %' field works like %c, but takes as its character the
  14886. ** next character of the format string, instead of the next
  14887. ** argument. For example, printf("%.78'-") prints 78 minus
  14888. ** signs, the same as printf("%.78c",'-').
  14889. **
  14890. ** + When compiled using GCC on a SPARC, this version of printf is
  14891. ** faster than the library printf for SUN OS 4.1.
  14892. **
  14893. ** + All functions are fully reentrant.
  14894. **
  14895. */
  14896. /*
  14897. ** Conversion types fall into various categories as defined by the
  14898. ** following enumeration.
  14899. */
  14900. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  14901. #define etFLOAT 2 /* Floating point. %f */
  14902. #define etEXP 3 /* Exponentional notation. %e and %E */
  14903. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  14904. #define etSIZE 5 /* Return number of characters processed so far. %n */
  14905. #define etSTRING 6 /* Strings. %s */
  14906. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  14907. #define etPERCENT 8 /* Percent symbol. %% */
  14908. #define etCHARX 9 /* Characters. %c */
  14909. /* The rest are extensions, not normally found in printf() */
  14910. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  14911. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  14912. NULL pointers replaced by SQL NULL. %Q */
  14913. #define etTOKEN 12 /* a pointer to a Token structure */
  14914. #define etSRCLIST 13 /* a pointer to a SrcList */
  14915. #define etPOINTER 14 /* The %p conversion */
  14916. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  14917. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  14918. #define etINVALID 0 /* Any unrecognized conversion type */
  14919. /*
  14920. ** An "etByte" is an 8-bit unsigned value.
  14921. */
  14922. typedef unsigned char etByte;
  14923. /*
  14924. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  14925. ** by an instance of the following structure
  14926. */
  14927. typedef struct et_info { /* Information about each format field */
  14928. char fmttype; /* The format field code letter */
  14929. etByte base; /* The base for radix conversion */
  14930. etByte flags; /* One or more of FLAG_ constants below */
  14931. etByte type; /* Conversion paradigm */
  14932. etByte charset; /* Offset into aDigits[] of the digits string */
  14933. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  14934. } et_info;
  14935. /*
  14936. ** Allowed values for et_info.flags
  14937. */
  14938. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  14939. #define FLAG_INTERN 2 /* True if for internal use only */
  14940. #define FLAG_STRING 4 /* Allow infinity precision */
  14941. /*
  14942. ** The following table is searched linearly, so it is good to put the
  14943. ** most frequently used conversion types first.
  14944. */
  14945. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  14946. static const char aPrefix[] = "-x0\000X0";
  14947. static const et_info fmtinfo[] = {
  14948. { 'd', 10, 1, etRADIX, 0, 0 },
  14949. { 's', 0, 4, etSTRING, 0, 0 },
  14950. { 'g', 0, 1, etGENERIC, 30, 0 },
  14951. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  14952. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  14953. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  14954. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  14955. { 'c', 0, 0, etCHARX, 0, 0 },
  14956. { 'o', 8, 0, etRADIX, 0, 2 },
  14957. { 'u', 10, 0, etRADIX, 0, 0 },
  14958. { 'x', 16, 0, etRADIX, 16, 1 },
  14959. { 'X', 16, 0, etRADIX, 0, 4 },
  14960. #ifndef SQLITE_OMIT_FLOATING_POINT
  14961. { 'f', 0, 1, etFLOAT, 0, 0 },
  14962. { 'e', 0, 1, etEXP, 30, 0 },
  14963. { 'E', 0, 1, etEXP, 14, 0 },
  14964. { 'G', 0, 1, etGENERIC, 14, 0 },
  14965. #endif
  14966. { 'i', 10, 1, etRADIX, 0, 0 },
  14967. { 'n', 0, 0, etSIZE, 0, 0 },
  14968. { '%', 0, 0, etPERCENT, 0, 0 },
  14969. { 'p', 16, 0, etPOINTER, 0, 1 },
  14970. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  14971. ** use only */
  14972. { 'T', 0, 2, etTOKEN, 0, 0 },
  14973. { 'S', 0, 2, etSRCLIST, 0, 0 },
  14974. { 'r', 10, 3, etORDINAL, 0, 0 },
  14975. };
  14976. /*
  14977. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  14978. ** conversions will work.
  14979. */
  14980. #ifndef SQLITE_OMIT_FLOATING_POINT
  14981. /*
  14982. ** "*val" is a double such that 0.1 <= *val < 10.0
  14983. ** Return the ascii code for the leading digit of *val, then
  14984. ** multiply "*val" by 10.0 to renormalize.
  14985. **
  14986. ** Example:
  14987. ** input: *val = 3.14159
  14988. ** output: *val = 1.4159 function return = '3'
  14989. **
  14990. ** The counter *cnt is incremented each time. After counter exceeds
  14991. ** 16 (the number of significant digits in a 64-bit float) '0' is
  14992. ** always returned.
  14993. */
  14994. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  14995. int digit;
  14996. LONGDOUBLE_TYPE d;
  14997. if( (*cnt)++ >= 16 ) return '0';
  14998. digit = (int)*val;
  14999. d = digit;
  15000. digit += '0';
  15001. *val = (*val - d)*10.0;
  15002. return (char)digit;
  15003. }
  15004. #endif /* SQLITE_OMIT_FLOATING_POINT */
  15005. /*
  15006. ** Append N space characters to the given string buffer.
  15007. */
  15008. static void appendSpace(StrAccum *pAccum, int N){
  15009. static const char zSpaces[] = " ";
  15010. while( N>=(int)sizeof(zSpaces)-1 ){
  15011. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  15012. N -= sizeof(zSpaces)-1;
  15013. }
  15014. if( N>0 ){
  15015. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  15016. }
  15017. }
  15018. /*
  15019. ** On machines with a small stack size, you can redefine the
  15020. ** SQLITE_PRINT_BUF_SIZE to be less than 350. But beware - for
  15021. ** smaller values some %f conversions may go into an infinite loop.
  15022. */
  15023. #ifndef SQLITE_PRINT_BUF_SIZE
  15024. # define SQLITE_PRINT_BUF_SIZE 350
  15025. #endif
  15026. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  15027. /*
  15028. ** The root program. All variations call this core.
  15029. **
  15030. ** INPUTS:
  15031. ** func This is a pointer to a function taking three arguments
  15032. ** 1. A pointer to anything. Same as the "arg" parameter.
  15033. ** 2. A pointer to the list of characters to be output
  15034. ** (Note, this list is NOT null terminated.)
  15035. ** 3. An integer number of characters to be output.
  15036. ** (Note: This number might be zero.)
  15037. **
  15038. ** arg This is the pointer to anything which will be passed as the
  15039. ** first argument to "func". Use it for whatever you like.
  15040. **
  15041. ** fmt This is the format string, as in the usual print.
  15042. **
  15043. ** ap This is a pointer to a list of arguments. Same as in
  15044. ** vfprint.
  15045. **
  15046. ** OUTPUTS:
  15047. ** The return value is the total number of characters sent to
  15048. ** the function "func". Returns -1 on a error.
  15049. **
  15050. ** Note that the order in which automatic variables are declared below
  15051. ** seems to make a big difference in determining how fast this beast
  15052. ** will run.
  15053. */
  15054. SQLITE_PRIVATE void sqlite3VXPrintf(
  15055. StrAccum *pAccum, /* Accumulate results here */
  15056. int useExtended, /* Allow extended %-conversions */
  15057. const char *fmt, /* Format string */
  15058. va_list ap /* arguments */
  15059. ){
  15060. int c; /* Next character in the format string */
  15061. char *bufpt; /* Pointer to the conversion buffer */
  15062. int precision; /* Precision of the current field */
  15063. int length; /* Length of the field */
  15064. int idx; /* A general purpose loop counter */
  15065. int width; /* Width of the current field */
  15066. etByte flag_leftjustify; /* True if "-" flag is present */
  15067. etByte flag_plussign; /* True if "+" flag is present */
  15068. etByte flag_blanksign; /* True if " " flag is present */
  15069. etByte flag_alternateform; /* True if "#" flag is present */
  15070. etByte flag_altform2; /* True if "!" flag is present */
  15071. etByte flag_zeropad; /* True if field width constant starts with zero */
  15072. etByte flag_long; /* True if "l" flag is present */
  15073. etByte flag_longlong; /* True if the "ll" flag is present */
  15074. etByte done; /* Loop termination flag */
  15075. sqlite_uint64 longvalue; /* Value for integer types */
  15076. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  15077. const et_info *infop; /* Pointer to the appropriate info structure */
  15078. char buf[etBUFSIZE]; /* Conversion buffer */
  15079. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  15080. etByte xtype = 0; /* Conversion paradigm */
  15081. char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
  15082. #ifndef SQLITE_OMIT_FLOATING_POINT
  15083. int exp, e2; /* exponent of real numbers */
  15084. double rounder; /* Used for rounding floating point values */
  15085. etByte flag_dp; /* True if decimal point should be shown */
  15086. etByte flag_rtz; /* True if trailing zeros should be removed */
  15087. etByte flag_exp; /* True to force display of the exponent */
  15088. int nsd; /* Number of significant digits returned */
  15089. #endif
  15090. length = 0;
  15091. bufpt = 0;
  15092. for(; (c=(*fmt))!=0; ++fmt){
  15093. if( c!='%' ){
  15094. int amt;
  15095. bufpt = (char *)fmt;
  15096. amt = 1;
  15097. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  15098. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  15099. if( c==0 ) break;
  15100. }
  15101. if( (c=(*++fmt))==0 ){
  15102. sqlite3StrAccumAppend(pAccum, "%", 1);
  15103. break;
  15104. }
  15105. /* Find out what flags are present */
  15106. flag_leftjustify = flag_plussign = flag_blanksign =
  15107. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  15108. done = 0;
  15109. do{
  15110. switch( c ){
  15111. case '-': flag_leftjustify = 1; break;
  15112. case '+': flag_plussign = 1; break;
  15113. case ' ': flag_blanksign = 1; break;
  15114. case '#': flag_alternateform = 1; break;
  15115. case '!': flag_altform2 = 1; break;
  15116. case '0': flag_zeropad = 1; break;
  15117. default: done = 1; break;
  15118. }
  15119. }while( !done && (c=(*++fmt))!=0 );
  15120. /* Get the field width */
  15121. width = 0;
  15122. if( c=='*' ){
  15123. width = va_arg(ap,int);
  15124. if( width<0 ){
  15125. flag_leftjustify = 1;
  15126. width = -width;
  15127. }
  15128. c = *++fmt;
  15129. }else{
  15130. while( c>='0' && c<='9' ){
  15131. width = width*10 + c - '0';
  15132. c = *++fmt;
  15133. }
  15134. }
  15135. if( width > etBUFSIZE-10 ){
  15136. width = etBUFSIZE-10;
  15137. }
  15138. /* Get the precision */
  15139. if( c=='.' ){
  15140. precision = 0;
  15141. c = *++fmt;
  15142. if( c=='*' ){
  15143. precision = va_arg(ap,int);
  15144. if( precision<0 ) precision = -precision;
  15145. c = *++fmt;
  15146. }else{
  15147. while( c>='0' && c<='9' ){
  15148. precision = precision*10 + c - '0';
  15149. c = *++fmt;
  15150. }
  15151. }
  15152. }else{
  15153. precision = -1;
  15154. }
  15155. /* Get the conversion type modifier */
  15156. if( c=='l' ){
  15157. flag_long = 1;
  15158. c = *++fmt;
  15159. if( c=='l' ){
  15160. flag_longlong = 1;
  15161. c = *++fmt;
  15162. }else{
  15163. flag_longlong = 0;
  15164. }
  15165. }else{
  15166. flag_long = flag_longlong = 0;
  15167. }
  15168. /* Fetch the info entry for the field */
  15169. infop = &fmtinfo[0];
  15170. xtype = etINVALID;
  15171. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  15172. if( c==fmtinfo[idx].fmttype ){
  15173. infop = &fmtinfo[idx];
  15174. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  15175. xtype = infop->type;
  15176. }else{
  15177. return;
  15178. }
  15179. break;
  15180. }
  15181. }
  15182. zExtra = 0;
  15183. /* Limit the precision to prevent overflowing buf[] during conversion */
  15184. if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
  15185. precision = etBUFSIZE-40;
  15186. }
  15187. /*
  15188. ** At this point, variables are initialized as follows:
  15189. **
  15190. ** flag_alternateform TRUE if a '#' is present.
  15191. ** flag_altform2 TRUE if a '!' is present.
  15192. ** flag_plussign TRUE if a '+' is present.
  15193. ** flag_leftjustify TRUE if a '-' is present or if the
  15194. ** field width was negative.
  15195. ** flag_zeropad TRUE if the width began with 0.
  15196. ** flag_long TRUE if the letter 'l' (ell) prefixed
  15197. ** the conversion character.
  15198. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  15199. ** the conversion character.
  15200. ** flag_blanksign TRUE if a ' ' is present.
  15201. ** width The specified field width. This is
  15202. ** always non-negative. Zero is the default.
  15203. ** precision The specified precision. The default
  15204. ** is -1.
  15205. ** xtype The class of the conversion.
  15206. ** infop Pointer to the appropriate info struct.
  15207. */
  15208. switch( xtype ){
  15209. case etPOINTER:
  15210. flag_longlong = sizeof(char*)==sizeof(i64);
  15211. flag_long = sizeof(char*)==sizeof(long int);
  15212. /* Fall through into the next case */
  15213. case etORDINAL:
  15214. case etRADIX:
  15215. if( infop->flags & FLAG_SIGNED ){
  15216. i64 v;
  15217. if( flag_longlong ) v = va_arg(ap,i64);
  15218. else if( flag_long ) v = va_arg(ap,long int);
  15219. else v = va_arg(ap,int);
  15220. if( v<0 ){
  15221. longvalue = -v;
  15222. prefix = '-';
  15223. }else{
  15224. longvalue = v;
  15225. if( flag_plussign ) prefix = '+';
  15226. else if( flag_blanksign ) prefix = ' ';
  15227. else prefix = 0;
  15228. }
  15229. }else{
  15230. if( flag_longlong ) longvalue = va_arg(ap,u64);
  15231. else if( flag_long ) longvalue = va_arg(ap,unsigned long int);
  15232. else longvalue = va_arg(ap,unsigned int);
  15233. prefix = 0;
  15234. }
  15235. if( longvalue==0 ) flag_alternateform = 0;
  15236. if( flag_zeropad && precision<width-(prefix!=0) ){
  15237. precision = width-(prefix!=0);
  15238. }
  15239. bufpt = &buf[etBUFSIZE-1];
  15240. if( xtype==etORDINAL ){
  15241. static const char zOrd[] = "thstndrd";
  15242. int x = (int)(longvalue % 10);
  15243. if( x>=4 || (longvalue/10)%10==1 ){
  15244. x = 0;
  15245. }
  15246. buf[etBUFSIZE-3] = zOrd[x*2];
  15247. buf[etBUFSIZE-2] = zOrd[x*2+1];
  15248. bufpt -= 2;
  15249. }
  15250. {
  15251. register const char *cset; /* Use registers for speed */
  15252. register int base;
  15253. cset = &aDigits[infop->charset];
  15254. base = infop->base;
  15255. do{ /* Convert to ascii */
  15256. *(--bufpt) = cset[longvalue%base];
  15257. longvalue = longvalue/base;
  15258. }while( longvalue>0 );
  15259. }
  15260. length = (int)(&buf[etBUFSIZE-1]-bufpt);
  15261. for(idx=precision-length; idx>0; idx--){
  15262. *(--bufpt) = '0'; /* Zero pad */
  15263. }
  15264. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  15265. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  15266. const char *pre;
  15267. char x;
  15268. pre = &aPrefix[infop->prefix];
  15269. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  15270. }
  15271. length = (int)(&buf[etBUFSIZE-1]-bufpt);
  15272. break;
  15273. case etFLOAT:
  15274. case etEXP:
  15275. case etGENERIC:
  15276. realvalue = va_arg(ap,double);
  15277. #ifndef SQLITE_OMIT_FLOATING_POINT
  15278. if( precision<0 ) precision = 6; /* Set default precision */
  15279. if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
  15280. if( realvalue<0.0 ){
  15281. realvalue = -realvalue;
  15282. prefix = '-';
  15283. }else{
  15284. if( flag_plussign ) prefix = '+';
  15285. else if( flag_blanksign ) prefix = ' ';
  15286. else prefix = 0;
  15287. }
  15288. if( xtype==etGENERIC && precision>0 ) precision--;
  15289. #if 0
  15290. /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  15291. for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  15292. #else
  15293. /* It makes more sense to use 0.5 */
  15294. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  15295. #endif
  15296. if( xtype==etFLOAT ) realvalue += rounder;
  15297. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  15298. exp = 0;
  15299. if( sqlite3IsNaN((double)realvalue) ){
  15300. bufpt = "NaN";
  15301. length = 3;
  15302. break;
  15303. }
  15304. if( realvalue>0.0 ){
  15305. while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
  15306. while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
  15307. while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
  15308. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  15309. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  15310. if( exp>350 ){
  15311. if( prefix=='-' ){
  15312. bufpt = "-Inf";
  15313. }else if( prefix=='+' ){
  15314. bufpt = "+Inf";
  15315. }else{
  15316. bufpt = "Inf";
  15317. }
  15318. length = sqlite3Strlen30(bufpt);
  15319. break;
  15320. }
  15321. }
  15322. bufpt = buf;
  15323. /*
  15324. ** If the field type is etGENERIC, then convert to either etEXP
  15325. ** or etFLOAT, as appropriate.
  15326. */
  15327. flag_exp = xtype==etEXP;
  15328. if( xtype!=etFLOAT ){
  15329. realvalue += rounder;
  15330. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  15331. }
  15332. if( xtype==etGENERIC ){
  15333. flag_rtz = !flag_alternateform;
  15334. if( exp<-4 || exp>precision ){
  15335. xtype = etEXP;
  15336. }else{
  15337. precision = precision - exp;
  15338. xtype = etFLOAT;
  15339. }
  15340. }else{
  15341. flag_rtz = 0;
  15342. }
  15343. if( xtype==etEXP ){
  15344. e2 = 0;
  15345. }else{
  15346. e2 = exp;
  15347. }
  15348. nsd = 0;
  15349. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  15350. /* The sign in front of the number */
  15351. if( prefix ){
  15352. *(bufpt++) = prefix;
  15353. }
  15354. /* Digits prior to the decimal point */
  15355. if( e2<0 ){
  15356. *(bufpt++) = '0';
  15357. }else{
  15358. for(; e2>=0; e2--){
  15359. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  15360. }
  15361. }
  15362. /* The decimal point */
  15363. if( flag_dp ){
  15364. *(bufpt++) = '.';
  15365. }
  15366. /* "0" digits after the decimal point but before the first
  15367. ** significant digit of the number */
  15368. for(e2++; e2<0; precision--, e2++){
  15369. assert( precision>0 );
  15370. *(bufpt++) = '0';
  15371. }
  15372. /* Significant digits after the decimal point */
  15373. while( (precision--)>0 ){
  15374. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  15375. }
  15376. /* Remove trailing zeros and the "." if no digits follow the "." */
  15377. if( flag_rtz && flag_dp ){
  15378. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  15379. assert( bufpt>buf );
  15380. if( bufpt[-1]=='.' ){
  15381. if( flag_altform2 ){
  15382. *(bufpt++) = '0';
  15383. }else{
  15384. *(--bufpt) = 0;
  15385. }
  15386. }
  15387. }
  15388. /* Add the "eNNN" suffix */
  15389. if( flag_exp || xtype==etEXP ){
  15390. *(bufpt++) = aDigits[infop->charset];
  15391. if( exp<0 ){
  15392. *(bufpt++) = '-'; exp = -exp;
  15393. }else{
  15394. *(bufpt++) = '+';
  15395. }
  15396. if( exp>=100 ){
  15397. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  15398. exp %= 100;
  15399. }
  15400. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  15401. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  15402. }
  15403. *bufpt = 0;
  15404. /* The converted number is in buf[] and zero terminated. Output it.
  15405. ** Note that the number is in the usual order, not reversed as with
  15406. ** integer conversions. */
  15407. length = (int)(bufpt-buf);
  15408. bufpt = buf;
  15409. /* Special case: Add leading zeros if the flag_zeropad flag is
  15410. ** set and we are not left justified */
  15411. if( flag_zeropad && !flag_leftjustify && length < width){
  15412. int i;
  15413. int nPad = width - length;
  15414. for(i=width; i>=nPad; i--){
  15415. bufpt[i] = bufpt[i-nPad];
  15416. }
  15417. i = prefix!=0;
  15418. while( nPad-- ) bufpt[i++] = '0';
  15419. length = width;
  15420. }
  15421. #endif
  15422. break;
  15423. case etSIZE:
  15424. *(va_arg(ap,int*)) = pAccum->nChar;
  15425. length = width = 0;
  15426. break;
  15427. case etPERCENT:
  15428. buf[0] = '%';
  15429. bufpt = buf;
  15430. length = 1;
  15431. break;
  15432. case etCHARX:
  15433. c = va_arg(ap,int);
  15434. buf[0] = (char)c;
  15435. if( precision>=0 ){
  15436. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  15437. length = precision;
  15438. }else{
  15439. length =1;
  15440. }
  15441. bufpt = buf;
  15442. break;
  15443. case etSTRING:
  15444. case etDYNSTRING:
  15445. bufpt = va_arg(ap,char*);
  15446. if( bufpt==0 ){
  15447. bufpt = "";
  15448. }else if( xtype==etDYNSTRING ){
  15449. zExtra = bufpt;
  15450. }
  15451. if( precision>=0 ){
  15452. for(length=0; length<precision && bufpt[length]; length++){}
  15453. }else{
  15454. length = sqlite3Strlen30(bufpt);
  15455. }
  15456. break;
  15457. case etSQLESCAPE:
  15458. case etSQLESCAPE2:
  15459. case etSQLESCAPE3: {
  15460. int i, j, n, isnull;
  15461. int needQuote;
  15462. char ch;
  15463. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  15464. char *escarg = va_arg(ap,char*);
  15465. isnull = escarg==0;
  15466. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  15467. for(i=n=0; (ch=escarg[i])!=0; i++){
  15468. if( ch==q ) n++;
  15469. }
  15470. needQuote = !isnull && xtype==etSQLESCAPE2;
  15471. n += i + 1 + needQuote*2;
  15472. if( n>etBUFSIZE ){
  15473. bufpt = zExtra = sqlite3Malloc( n );
  15474. if( bufpt==0 ){
  15475. pAccum->mallocFailed = 1;
  15476. return;
  15477. }
  15478. }else{
  15479. bufpt = buf;
  15480. }
  15481. j = 0;
  15482. if( needQuote ) bufpt[j++] = q;
  15483. for(i=0; (ch=escarg[i])!=0; i++){
  15484. bufpt[j++] = ch;
  15485. if( ch==q ) bufpt[j++] = ch;
  15486. }
  15487. if( needQuote ) bufpt[j++] = q;
  15488. bufpt[j] = 0;
  15489. length = j;
  15490. /* The precision is ignored on %q and %Q */
  15491. /* if( precision>=0 && precision<length ) length = precision; */
  15492. break;
  15493. }
  15494. case etTOKEN: {
  15495. Token *pToken = va_arg(ap, Token*);
  15496. if( pToken ){
  15497. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  15498. }
  15499. length = width = 0;
  15500. break;
  15501. }
  15502. case etSRCLIST: {
  15503. SrcList *pSrc = va_arg(ap, SrcList*);
  15504. int k = va_arg(ap, int);
  15505. struct SrcList_item *pItem = &pSrc->a[k];
  15506. assert( k>=0 && k<pSrc->nSrc );
  15507. if( pItem->zDatabase ){
  15508. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  15509. sqlite3StrAccumAppend(pAccum, ".", 1);
  15510. }
  15511. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  15512. length = width = 0;
  15513. break;
  15514. }
  15515. default: {
  15516. assert( xtype==etINVALID );
  15517. return;
  15518. }
  15519. }/* End switch over the format type */
  15520. /*
  15521. ** The text of the conversion is pointed to by "bufpt" and is
  15522. ** "length" characters long. The field width is "width". Do
  15523. ** the output.
  15524. */
  15525. if( !flag_leftjustify ){
  15526. register int nspace;
  15527. nspace = width-length;
  15528. if( nspace>0 ){
  15529. appendSpace(pAccum, nspace);
  15530. }
  15531. }
  15532. if( length>0 ){
  15533. sqlite3StrAccumAppend(pAccum, bufpt, length);
  15534. }
  15535. if( flag_leftjustify ){
  15536. register int nspace;
  15537. nspace = width-length;
  15538. if( nspace>0 ){
  15539. appendSpace(pAccum, nspace);
  15540. }
  15541. }
  15542. if( zExtra ){
  15543. sqlite3_free(zExtra);
  15544. }
  15545. }/* End for loop over the format string */
  15546. } /* End of function */
  15547. /*
  15548. ** Append N bytes of text from z to the StrAccum object.
  15549. */
  15550. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  15551. assert( z!=0 || N==0 );
  15552. if( p->tooBig | p->mallocFailed ){
  15553. testcase(p->tooBig);
  15554. testcase(p->mallocFailed);
  15555. return;
  15556. }
  15557. if( N<0 ){
  15558. N = sqlite3Strlen30(z);
  15559. }
  15560. if( N==0 || NEVER(z==0) ){
  15561. return;
  15562. }
  15563. if( p->nChar+N >= p->nAlloc ){
  15564. char *zNew;
  15565. if( !p->useMalloc ){
  15566. p->tooBig = 1;
  15567. N = p->nAlloc - p->nChar - 1;
  15568. if( N<=0 ){
  15569. return;
  15570. }
  15571. }else{
  15572. i64 szNew = p->nChar;
  15573. szNew += N + 1;
  15574. if( szNew > p->mxAlloc ){
  15575. sqlite3StrAccumReset(p);
  15576. p->tooBig = 1;
  15577. return;
  15578. }else{
  15579. p->nAlloc = (int)szNew;
  15580. }
  15581. zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
  15582. if( zNew ){
  15583. memcpy(zNew, p->zText, p->nChar);
  15584. sqlite3StrAccumReset(p);
  15585. p->zText = zNew;
  15586. }else{
  15587. p->mallocFailed = 1;
  15588. sqlite3StrAccumReset(p);
  15589. return;
  15590. }
  15591. }
  15592. }
  15593. memcpy(&p->zText[p->nChar], z, N);
  15594. p->nChar += N;
  15595. }
  15596. /*
  15597. ** Finish off a string by making sure it is zero-terminated.
  15598. ** Return a pointer to the resulting string. Return a NULL
  15599. ** pointer if any kind of error was encountered.
  15600. */
  15601. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  15602. if( p->zText ){
  15603. p->zText[p->nChar] = 0;
  15604. if( p->useMalloc && p->zText==p->zBase ){
  15605. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  15606. if( p->zText ){
  15607. memcpy(p->zText, p->zBase, p->nChar+1);
  15608. }else{
  15609. p->mallocFailed = 1;
  15610. }
  15611. }
  15612. }
  15613. return p->zText;
  15614. }
  15615. /*
  15616. ** Reset an StrAccum string. Reclaim all malloced memory.
  15617. */
  15618. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  15619. if( p->zText!=p->zBase ){
  15620. sqlite3DbFree(p->db, p->zText);
  15621. }
  15622. p->zText = 0;
  15623. }
  15624. /*
  15625. ** Initialize a string accumulator
  15626. */
  15627. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  15628. p->zText = p->zBase = zBase;
  15629. p->db = 0;
  15630. p->nChar = 0;
  15631. p->nAlloc = n;
  15632. p->mxAlloc = mx;
  15633. p->useMalloc = 1;
  15634. p->tooBig = 0;
  15635. p->mallocFailed = 0;
  15636. }
  15637. /*
  15638. ** Print into memory obtained from sqliteMalloc(). Use the internal
  15639. ** %-conversion extensions.
  15640. */
  15641. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  15642. char *z;
  15643. char zBase[SQLITE_PRINT_BUF_SIZE];
  15644. StrAccum acc;
  15645. assert( db!=0 );
  15646. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  15647. db->aLimit[SQLITE_LIMIT_LENGTH]);
  15648. acc.db = db;
  15649. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  15650. z = sqlite3StrAccumFinish(&acc);
  15651. if( acc.mallocFailed ){
  15652. db->mallocFailed = 1;
  15653. }
  15654. return z;
  15655. }
  15656. /*
  15657. ** Print into memory obtained from sqliteMalloc(). Use the internal
  15658. ** %-conversion extensions.
  15659. */
  15660. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  15661. va_list ap;
  15662. char *z;
  15663. va_start(ap, zFormat);
  15664. z = sqlite3VMPrintf(db, zFormat, ap);
  15665. va_end(ap);
  15666. return z;
  15667. }
  15668. /*
  15669. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  15670. ** the string and before returnning. This routine is intended to be used
  15671. ** to modify an existing string. For example:
  15672. **
  15673. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  15674. **
  15675. */
  15676. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  15677. va_list ap;
  15678. char *z;
  15679. va_start(ap, zFormat);
  15680. z = sqlite3VMPrintf(db, zFormat, ap);
  15681. va_end(ap);
  15682. sqlite3DbFree(db, zStr);
  15683. return z;
  15684. }
  15685. /*
  15686. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  15687. ** %-conversion extensions.
  15688. */
  15689. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  15690. char *z;
  15691. char zBase[SQLITE_PRINT_BUF_SIZE];
  15692. StrAccum acc;
  15693. #ifndef SQLITE_OMIT_AUTOINIT
  15694. if( sqlite3_initialize() ) return 0;
  15695. #endif
  15696. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  15697. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  15698. z = sqlite3StrAccumFinish(&acc);
  15699. return z;
  15700. }
  15701. /*
  15702. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  15703. ** %-conversion extensions.
  15704. */
  15705. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  15706. va_list ap;
  15707. char *z;
  15708. #ifndef SQLITE_OMIT_AUTOINIT
  15709. if( sqlite3_initialize() ) return 0;
  15710. #endif
  15711. va_start(ap, zFormat);
  15712. z = sqlite3_vmprintf(zFormat, ap);
  15713. va_end(ap);
  15714. return z;
  15715. }
  15716. /*
  15717. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  15718. ** current locale settings. This is important for SQLite because we
  15719. ** are not able to use a "," as the decimal point in place of "." as
  15720. ** specified by some locales.
  15721. */
  15722. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  15723. char *z;
  15724. va_list ap;
  15725. StrAccum acc;
  15726. if( n<=0 ){
  15727. return zBuf;
  15728. }
  15729. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  15730. acc.useMalloc = 0;
  15731. va_start(ap,zFormat);
  15732. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  15733. va_end(ap);
  15734. z = sqlite3StrAccumFinish(&acc);
  15735. return z;
  15736. }
  15737. #if defined(SQLITE_DEBUG)
  15738. /*
  15739. ** A version of printf() that understands %lld. Used for debugging.
  15740. ** The printf() built into some versions of windows does not understand %lld
  15741. ** and segfaults if you give it a long long int.
  15742. */
  15743. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  15744. va_list ap;
  15745. StrAccum acc;
  15746. char zBuf[500];
  15747. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  15748. acc.useMalloc = 0;
  15749. va_start(ap,zFormat);
  15750. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  15751. va_end(ap);
  15752. sqlite3StrAccumFinish(&acc);
  15753. fprintf(stdout,"%s", zBuf);
  15754. fflush(stdout);
  15755. }
  15756. #endif
  15757. /************** End of printf.c **********************************************/
  15758. /************** Begin file random.c ******************************************/
  15759. /*
  15760. ** 2001 September 15
  15761. **
  15762. ** The author disclaims copyright to this source code. In place of
  15763. ** a legal notice, here is a blessing:
  15764. **
  15765. ** May you do good and not evil.
  15766. ** May you find forgiveness for yourself and forgive others.
  15767. ** May you share freely, never taking more than you give.
  15768. **
  15769. *************************************************************************
  15770. ** This file contains code to implement a pseudo-random number
  15771. ** generator (PRNG) for SQLite.
  15772. **
  15773. ** Random numbers are used by some of the database backends in order
  15774. ** to generate random integer keys for tables or random filenames.
  15775. **
  15776. ** $Id: random.c,v 1.29 2008/12/10 19:26:24 drh Exp $
  15777. */
  15778. /* All threads share a single random number generator.
  15779. ** This structure is the current state of the generator.
  15780. */
  15781. static SQLITE_WSD struct sqlite3PrngType {
  15782. unsigned char isInit; /* True if initialized */
  15783. unsigned char i, j; /* State variables */
  15784. unsigned char s[256]; /* State variables */
  15785. } sqlite3Prng;
  15786. /*
  15787. ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  15788. ** must be held while executing this routine.
  15789. **
  15790. ** Why not just use a library random generator like lrand48() for this?
  15791. ** Because the OP_NewRowid opcode in the VDBE depends on having a very
  15792. ** good source of random numbers. The lrand48() library function may
  15793. ** well be good enough. But maybe not. Or maybe lrand48() has some
  15794. ** subtle problems on some systems that could cause problems. It is hard
  15795. ** to know. To minimize the risk of problems due to bad lrand48()
  15796. ** implementations, SQLite uses this random number generator based
  15797. ** on RC4, which we know works very well.
  15798. **
  15799. ** (Later): Actually, OP_NewRowid does not depend on a good source of
  15800. ** randomness any more. But we will leave this code in all the same.
  15801. */
  15802. static u8 randomByte(void){
  15803. unsigned char t;
  15804. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  15805. ** state vector. If writable static data is unsupported on the target,
  15806. ** we have to locate the state vector at run-time. In the more common
  15807. ** case where writable static data is supported, wsdPrng can refer directly
  15808. ** to the "sqlite3Prng" state vector declared above.
  15809. */
  15810. #ifdef SQLITE_OMIT_WSD
  15811. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  15812. # define wsdPrng p[0]
  15813. #else
  15814. # define wsdPrng sqlite3Prng
  15815. #endif
  15816. /* Initialize the state of the random number generator once,
  15817. ** the first time this routine is called. The seed value does
  15818. ** not need to contain a lot of randomness since we are not
  15819. ** trying to do secure encryption or anything like that...
  15820. **
  15821. ** Nothing in this file or anywhere else in SQLite does any kind of
  15822. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  15823. ** number generator) not as an encryption device.
  15824. */
  15825. if( !wsdPrng.isInit ){
  15826. int i;
  15827. char k[256];
  15828. wsdPrng.j = 0;
  15829. wsdPrng.i = 0;
  15830. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  15831. for(i=0; i<256; i++){
  15832. wsdPrng.s[i] = (u8)i;
  15833. }
  15834. for(i=0; i<256; i++){
  15835. wsdPrng.j += wsdPrng.s[i] + k[i];
  15836. t = wsdPrng.s[wsdPrng.j];
  15837. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  15838. wsdPrng.s[i] = t;
  15839. }
  15840. wsdPrng.isInit = 1;
  15841. }
  15842. /* Generate and return single random byte
  15843. */
  15844. wsdPrng.i++;
  15845. t = wsdPrng.s[wsdPrng.i];
  15846. wsdPrng.j += t;
  15847. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  15848. wsdPrng.s[wsdPrng.j] = t;
  15849. t += wsdPrng.s[wsdPrng.i];
  15850. return wsdPrng.s[t];
  15851. }
  15852. /*
  15853. ** Return N random bytes.
  15854. */
  15855. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  15856. unsigned char *zBuf = pBuf;
  15857. #if SQLITE_THREADSAFE
  15858. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  15859. #endif
  15860. sqlite3_mutex_enter(mutex);
  15861. while( N-- ){
  15862. *(zBuf++) = randomByte();
  15863. }
  15864. sqlite3_mutex_leave(mutex);
  15865. }
  15866. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15867. /*
  15868. ** For testing purposes, we sometimes want to preserve the state of
  15869. ** PRNG and restore the PRNG to its saved state at a later time, or
  15870. ** to reset the PRNG to its initial state. These routines accomplish
  15871. ** those tasks.
  15872. **
  15873. ** The sqlite3_test_control() interface calls these routines to
  15874. ** control the PRNG.
  15875. */
  15876. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  15877. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  15878. memcpy(
  15879. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  15880. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  15881. sizeof(sqlite3Prng)
  15882. );
  15883. }
  15884. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  15885. memcpy(
  15886. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  15887. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  15888. sizeof(sqlite3Prng)
  15889. );
  15890. }
  15891. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  15892. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  15893. }
  15894. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  15895. /************** End of random.c **********************************************/
  15896. /************** Begin file utf.c *********************************************/
  15897. /*
  15898. ** 2004 April 13
  15899. **
  15900. ** The author disclaims copyright to this source code. In place of
  15901. ** a legal notice, here is a blessing:
  15902. **
  15903. ** May you do good and not evil.
  15904. ** May you find forgiveness for yourself and forgive others.
  15905. ** May you share freely, never taking more than you give.
  15906. **
  15907. *************************************************************************
  15908. ** This file contains routines used to translate between UTF-8,
  15909. ** UTF-16, UTF-16BE, and UTF-16LE.
  15910. **
  15911. ** $Id: utf.c,v 1.73 2009/04/01 18:40:32 drh Exp $
  15912. **
  15913. ** Notes on UTF-8:
  15914. **
  15915. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  15916. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  15917. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  15918. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  15919. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  15920. **
  15921. **
  15922. ** Notes on UTF-16: (with wwww+1==uuuuu)
  15923. **
  15924. ** Word-0 Word-1 Value
  15925. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  15926. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  15927. **
  15928. **
  15929. ** BOM or Byte Order Mark:
  15930. ** 0xff 0xfe little-endian utf-16 follows
  15931. ** 0xfe 0xff big-endian utf-16 follows
  15932. **
  15933. */
  15934. /************** Include vdbeInt.h in the middle of utf.c *********************/
  15935. /************** Begin file vdbeInt.h *****************************************/
  15936. /*
  15937. ** 2003 September 6
  15938. **
  15939. ** The author disclaims copyright to this source code. In place of
  15940. ** a legal notice, here is a blessing:
  15941. **
  15942. ** May you do good and not evil.
  15943. ** May you find forgiveness for yourself and forgive others.
  15944. ** May you share freely, never taking more than you give.
  15945. **
  15946. *************************************************************************
  15947. ** This is the header file for information that is private to the
  15948. ** VDBE. This information used to all be at the top of the single
  15949. ** source code file "vdbe.c". When that file became too big (over
  15950. ** 6000 lines long) it was split up into several smaller files and
  15951. ** this header information was factored out.
  15952. **
  15953. ** $Id: vdbeInt.h,v 1.167 2009/04/10 12:55:17 danielk1977 Exp $
  15954. */
  15955. #ifndef _VDBEINT_H_
  15956. #define _VDBEINT_H_
  15957. /*
  15958. ** intToKey() and keyToInt() used to transform the rowid. But with
  15959. ** the latest versions of the design they are no-ops.
  15960. */
  15961. #define keyToInt(X) (X)
  15962. #define intToKey(X) (X)
  15963. /*
  15964. ** SQL is translated into a sequence of instructions to be
  15965. ** executed by a virtual machine. Each instruction is an instance
  15966. ** of the following structure.
  15967. */
  15968. typedef struct VdbeOp Op;
  15969. /*
  15970. ** Boolean values
  15971. */
  15972. typedef unsigned char Bool;
  15973. /*
  15974. ** A cursor is a pointer into a single BTree within a database file.
  15975. ** The cursor can seek to a BTree entry with a particular key, or
  15976. ** loop over all entries of the Btree. You can also insert new BTree
  15977. ** entries or retrieve the key or data from the entry that the cursor
  15978. ** is currently pointing to.
  15979. **
  15980. ** Every cursor that the virtual machine has open is represented by an
  15981. ** instance of the following structure.
  15982. **
  15983. ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
  15984. ** really a single row that represents the NEW or OLD pseudo-table of
  15985. ** a row trigger. The data for the row is stored in VdbeCursor.pData and
  15986. ** the rowid is in VdbeCursor.iKey.
  15987. */
  15988. struct VdbeCursor {
  15989. BtCursor *pCursor; /* The cursor structure of the backend */
  15990. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  15991. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  15992. Bool zeroed; /* True if zeroed out and ready for reuse */
  15993. Bool rowidIsValid; /* True if lastRowid is valid */
  15994. Bool atFirst; /* True if pointing to first entry */
  15995. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  15996. Bool nullRow; /* True if pointing to a row with no data */
  15997. Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
  15998. Bool ephemPseudoTable;
  15999. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  16000. Bool isTable; /* True if a table requiring integer keys */
  16001. Bool isIndex; /* True if an index containing keys only - no data */
  16002. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  16003. Btree *pBt; /* Separate file holding temporary table */
  16004. int nData; /* Number of bytes in pData */
  16005. char *pData; /* Data for a NEW or OLD pseudo-table */
  16006. i64 iKey; /* Key for the NEW or OLD pseudo-table row */
  16007. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  16008. int nField; /* Number of fields in the header */
  16009. i64 seqCount; /* Sequence counter */
  16010. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  16011. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  16012. /* Cached information about the header for the data record that the
  16013. ** cursor is currently pointing to. Only valid if cacheValid is true.
  16014. ** aRow might point to (ephemeral) data for the current row, or it might
  16015. ** be NULL.
  16016. */
  16017. int cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  16018. int payloadSize; /* Total number of bytes in the record */
  16019. u32 *aType; /* Type values for all entries in the record */
  16020. u32 *aOffset; /* Cached offsets to the start of each columns data */
  16021. u8 *aRow; /* Data for the current row, if all on one page */
  16022. };
  16023. typedef struct VdbeCursor VdbeCursor;
  16024. /*
  16025. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  16026. */
  16027. #define CACHE_STALE 0
  16028. /*
  16029. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  16030. ** structures. Each Mem struct may cache multiple representations (string,
  16031. ** integer etc.) of the same value. A value (and therefore Mem structure)
  16032. ** has the following properties:
  16033. **
  16034. ** Each value has a manifest type. The manifest type of the value stored
  16035. ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
  16036. ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
  16037. ** SQLITE_BLOB.
  16038. */
  16039. struct Mem {
  16040. union {
  16041. i64 i; /* Integer value. */
  16042. int nZero; /* Used when bit MEM_Zero is set in flags */
  16043. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  16044. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  16045. } u;
  16046. double r; /* Real value */
  16047. sqlite3 *db; /* The associated database connection */
  16048. char *z; /* String or BLOB value */
  16049. int n; /* Number of characters in string value, excluding '\0' */
  16050. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  16051. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  16052. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  16053. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  16054. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  16055. };
  16056. /* One or more of the following flags are set to indicate the validOK
  16057. ** representations of the value stored in the Mem struct.
  16058. **
  16059. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  16060. ** No other flags may be set in this case.
  16061. **
  16062. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  16063. ** Usually this is encoded in the same unicode encoding as the main
  16064. ** database (see below for exceptions). If the MEM_Term flag is also
  16065. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  16066. ** flags may coexist with the MEM_Str flag.
  16067. **
  16068. ** Multiple of these values can appear in Mem.flags. But only one
  16069. ** at a time can appear in Mem.type.
  16070. */
  16071. #define MEM_Null 0x0001 /* Value is NULL */
  16072. #define MEM_Str 0x0002 /* Value is a string */
  16073. #define MEM_Int 0x0004 /* Value is an integer */
  16074. #define MEM_Real 0x0008 /* Value is a real number */
  16075. #define MEM_Blob 0x0010 /* Value is a BLOB */
  16076. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  16077. #define MEM_TypeMask 0x00ff /* Mask of type bits */
  16078. /* Whenever Mem contains a valid string or blob representation, one of
  16079. ** the following flags must be set to determine the memory management
  16080. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  16081. ** string is \000 or \u0000 terminated
  16082. */
  16083. #define MEM_Term 0x0200 /* String rep is nul terminated */
  16084. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  16085. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  16086. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  16087. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  16088. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  16089. #ifdef SQLITE_OMIT_INCRBLOB
  16090. #undef MEM_Zero
  16091. #define MEM_Zero 0x0000
  16092. #endif
  16093. /*
  16094. ** Clear any existing type flags from a Mem and replace them with f
  16095. */
  16096. #define MemSetTypeFlag(p, f) \
  16097. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  16098. /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
  16099. ** additional information about auxiliary information bound to arguments
  16100. ** of the function. This is used to implement the sqlite3_get_auxdata()
  16101. ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
  16102. ** that can be associated with a constant argument to a function. This
  16103. ** allows functions such as "regexp" to compile their constant regular
  16104. ** expression argument once and reused the compiled code for multiple
  16105. ** invocations.
  16106. */
  16107. struct VdbeFunc {
  16108. FuncDef *pFunc; /* The definition of the function */
  16109. int nAux; /* Number of entries allocated for apAux[] */
  16110. struct AuxData {
  16111. void *pAux; /* Aux data for the i-th argument */
  16112. void (*xDelete)(void *); /* Destructor for the aux data */
  16113. } apAux[1]; /* One slot for each function argument */
  16114. };
  16115. /*
  16116. ** The "context" argument for a installable function. A pointer to an
  16117. ** instance of this structure is the first argument to the routines used
  16118. ** implement the SQL functions.
  16119. **
  16120. ** There is a typedef for this structure in sqlite.h. So all routines,
  16121. ** even the public interface to SQLite, can use a pointer to this structure.
  16122. ** But this file is the only place where the internal details of this
  16123. ** structure are known.
  16124. **
  16125. ** This structure is defined inside of vdbeInt.h because it uses substructures
  16126. ** (Mem) which are only defined there.
  16127. */
  16128. struct sqlite3_context {
  16129. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  16130. VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
  16131. Mem s; /* The return value is stored here */
  16132. Mem *pMem; /* Memory cell used to store aggregate context */
  16133. int isError; /* Error code returned by the function. */
  16134. CollSeq *pColl; /* Collating sequence */
  16135. };
  16136. /*
  16137. ** A Set structure is used for quick testing to see if a value
  16138. ** is part of a small set. Sets are used to implement code like
  16139. ** this:
  16140. ** x.y IN ('hi','hoo','hum')
  16141. */
  16142. typedef struct Set Set;
  16143. struct Set {
  16144. Hash hash; /* A set is just a hash table */
  16145. HashElem *prev; /* Previously accessed hash elemen */
  16146. };
  16147. /*
  16148. ** A Context stores the last insert rowid, the last statement change count,
  16149. ** and the current statement change count (i.e. changes since last statement).
  16150. ** The current keylist is also stored in the context.
  16151. ** Elements of Context structure type make up the ContextStack, which is
  16152. ** updated by the ContextPush and ContextPop opcodes (used by triggers).
  16153. ** The context is pushed before executing a trigger a popped when the
  16154. ** trigger finishes.
  16155. */
  16156. typedef struct Context Context;
  16157. struct Context {
  16158. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  16159. int nChange; /* Statement changes (Vdbe.nChanges) */
  16160. };
  16161. /*
  16162. ** An instance of the virtual machine. This structure contains the complete
  16163. ** state of the virtual machine.
  16164. **
  16165. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
  16166. ** is really a pointer to an instance of this structure.
  16167. **
  16168. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  16169. ** any virtual table method invocations made by the vdbe program. It is
  16170. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  16171. ** variable is used for two purposes: to allow xDestroy methods to execute
  16172. ** "DROP TABLE" statements and to prevent some nasty side effects of
  16173. ** malloc failure when SQLite is invoked recursively by a virtual table
  16174. ** method function.
  16175. */
  16176. struct Vdbe {
  16177. sqlite3 *db; /* The whole database */
  16178. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  16179. int nOp; /* Number of instructions in the program */
  16180. int nOpAlloc; /* Number of slots allocated for aOp[] */
  16181. Op *aOp; /* Space to hold the virtual machine's program */
  16182. int nLabel; /* Number of labels used */
  16183. int nLabelAlloc; /* Number of slots allocated in aLabel[] */
  16184. int *aLabel; /* Space to hold the labels */
  16185. Mem **apArg; /* Arguments to currently executing user function */
  16186. Mem *aColName; /* Column names to return */
  16187. int nCursor; /* Number of slots in apCsr[] */
  16188. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  16189. int nVar; /* Number of entries in aVar[] */
  16190. Mem *aVar; /* Values for the OP_Variable opcode. */
  16191. char **azVar; /* Name of variables */
  16192. int okVar; /* True if azVar[] has been initialized */
  16193. u32 magic; /* Magic number for sanity checking */
  16194. int nMem; /* Number of memory locations currently allocated */
  16195. Mem *aMem; /* The memory locations */
  16196. int cacheCtr; /* VdbeCursor row cache generation counter */
  16197. int contextStackTop; /* Index of top element in the context stack */
  16198. int contextStackDepth; /* The size of the "context" stack */
  16199. Context *contextStack; /* Stack used by opcodes ContextPush & ContextPop*/
  16200. int pc; /* The program counter */
  16201. int rc; /* Value to return */
  16202. int errorAction; /* Recovery action to do in case of an error */
  16203. int nResColumn; /* Number of columns in one row of the result set */
  16204. char **azResColumn; /* Values for one row of result */
  16205. char *zErrMsg; /* Error message written here */
  16206. Mem *pResultSet; /* Pointer to an array of results */
  16207. u8 explain; /* True if EXPLAIN present on SQL command */
  16208. u8 changeCntOn; /* True to update the change-counter */
  16209. u8 expired; /* True if the VM needs to be recompiled */
  16210. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  16211. u8 inVtabMethod; /* See comments above */
  16212. u8 usesStmtJournal; /* True if uses a statement journal */
  16213. u8 readOnly; /* True for read-only statements */
  16214. u8 isPrepareV2; /* True if prepared with prepare_v2() */
  16215. int nChange; /* Number of db changes made since last reset */
  16216. i64 startTime; /* Time when query started - used for profiling */
  16217. int btreeMask; /* Bitmask of db->aDb[] entries referenced */
  16218. BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
  16219. int aCounter[2]; /* Counters used by sqlite3_stmt_status() */
  16220. char *zSql; /* Text of the SQL statement that generated this */
  16221. void *pFree; /* Free this when deleting the vdbe */
  16222. #ifdef SQLITE_DEBUG
  16223. FILE *trace; /* Write an execution trace here, if not NULL */
  16224. #endif
  16225. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  16226. #ifdef SQLITE_SSE
  16227. int fetchId; /* Statement number used by sqlite3_fetch_statement */
  16228. int lru; /* Counter used for LRU cache replacement */
  16229. #endif
  16230. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  16231. Vdbe *pLruPrev;
  16232. Vdbe *pLruNext;
  16233. #endif
  16234. };
  16235. /*
  16236. ** The following are allowed values for Vdbe.magic
  16237. */
  16238. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  16239. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  16240. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  16241. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  16242. /*
  16243. ** Function prototypes
  16244. */
  16245. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  16246. void sqliteVdbePopStack(Vdbe*,int);
  16247. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  16248. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  16249. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  16250. #endif
  16251. SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
  16252. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  16253. SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  16254. SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  16255. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
  16256. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  16257. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  16258. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
  16259. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  16260. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  16261. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  16262. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  16263. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  16264. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  16265. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  16266. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  16267. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  16268. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  16269. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  16270. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  16271. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  16272. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  16273. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  16274. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  16275. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  16276. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  16277. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  16278. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  16279. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  16280. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  16281. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  16282. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  16283. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  16284. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  16285. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  16286. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  16287. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  16288. SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
  16289. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  16290. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  16291. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  16292. SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
  16293. #endif
  16294. #ifndef SQLITE_OMIT_SHARED_CACHE
  16295. SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
  16296. #else
  16297. # define sqlite3VdbeMutexArrayEnter(p)
  16298. #endif
  16299. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  16300. #ifdef SQLITE_DEBUG
  16301. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  16302. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  16303. #endif
  16304. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  16305. #ifndef SQLITE_OMIT_INCRBLOB
  16306. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  16307. #else
  16308. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  16309. #endif
  16310. #endif /* !defined(_VDBEINT_H_) */
  16311. /************** End of vdbeInt.h *********************************************/
  16312. /************** Continuing where we left off in utf.c ************************/
  16313. #ifndef SQLITE_AMALGAMATION
  16314. /*
  16315. ** The following constant value is used by the SQLITE_BIGENDIAN and
  16316. ** SQLITE_LITTLEENDIAN macros.
  16317. */
  16318. SQLITE_PRIVATE const int sqlite3one = 1;
  16319. #endif /* SQLITE_AMALGAMATION */
  16320. /*
  16321. ** This lookup table is used to help decode the first byte of
  16322. ** a multi-byte UTF8 character.
  16323. */
  16324. static const unsigned char sqlite3Utf8Trans1[] = {
  16325. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  16326. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  16327. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  16328. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  16329. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  16330. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  16331. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  16332. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  16333. };
  16334. #define WRITE_UTF8(zOut, c) { \
  16335. if( c<0x00080 ){ \
  16336. *zOut++ = (u8)(c&0xFF); \
  16337. } \
  16338. else if( c<0x00800 ){ \
  16339. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  16340. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  16341. } \
  16342. else if( c<0x10000 ){ \
  16343. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  16344. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  16345. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  16346. }else{ \
  16347. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  16348. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  16349. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  16350. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  16351. } \
  16352. }
  16353. #define WRITE_UTF16LE(zOut, c) { \
  16354. if( c<=0xFFFF ){ \
  16355. *zOut++ = (u8)(c&0x00FF); \
  16356. *zOut++ = (u8)((c>>8)&0x00FF); \
  16357. }else{ \
  16358. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  16359. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  16360. *zOut++ = (u8)(c&0x00FF); \
  16361. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  16362. } \
  16363. }
  16364. #define WRITE_UTF16BE(zOut, c) { \
  16365. if( c<=0xFFFF ){ \
  16366. *zOut++ = (u8)((c>>8)&0x00FF); \
  16367. *zOut++ = (u8)(c&0x00FF); \
  16368. }else{ \
  16369. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  16370. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  16371. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  16372. *zOut++ = (u8)(c&0x00FF); \
  16373. } \
  16374. }
  16375. #define READ_UTF16LE(zIn, c){ \
  16376. c = (*zIn++); \
  16377. c += ((*zIn++)<<8); \
  16378. if( c>=0xD800 && c<0xE000 ){ \
  16379. int c2 = (*zIn++); \
  16380. c2 += ((*zIn++)<<8); \
  16381. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  16382. } \
  16383. }
  16384. #define READ_UTF16BE(zIn, c){ \
  16385. c = ((*zIn++)<<8); \
  16386. c += (*zIn++); \
  16387. if( c>=0xD800 && c<0xE000 ){ \
  16388. int c2 = ((*zIn++)<<8); \
  16389. c2 += (*zIn++); \
  16390. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  16391. } \
  16392. }
  16393. /*
  16394. ** Translate a single UTF-8 character. Return the unicode value.
  16395. **
  16396. ** During translation, assume that the byte that zTerm points
  16397. ** is a 0x00.
  16398. **
  16399. ** Write a pointer to the next unread byte back into *pzNext.
  16400. **
  16401. ** Notes On Invalid UTF-8:
  16402. **
  16403. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  16404. ** be encoded as a multi-byte character. Any multi-byte character that
  16405. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  16406. **
  16407. ** * This routine never allows a UTF16 surrogate value to be encoded.
  16408. ** If a multi-byte character attempts to encode a value between
  16409. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  16410. **
  16411. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  16412. ** byte of a character are interpreted as single-byte characters
  16413. ** and rendered as themselves even though they are technically
  16414. ** invalid characters.
  16415. **
  16416. ** * This routine accepts an infinite number of different UTF8 encodings
  16417. ** for unicode values 0x80 and greater. It do not change over-length
  16418. ** encodings to 0xfffd as some systems recommend.
  16419. */
  16420. #define READ_UTF8(zIn, zTerm, c) \
  16421. c = *(zIn++); \
  16422. if( c>=0xc0 ){ \
  16423. c = sqlite3Utf8Trans1[c-0xc0]; \
  16424. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  16425. c = (c<<6) + (0x3f & *(zIn++)); \
  16426. } \
  16427. if( c<0x80 \
  16428. || (c&0xFFFFF800)==0xD800 \
  16429. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  16430. }
  16431. SQLITE_PRIVATE int sqlite3Utf8Read(
  16432. const unsigned char *zIn, /* First byte of UTF-8 character */
  16433. const unsigned char **pzNext /* Write first byte past UTF-8 char here */
  16434. ){
  16435. int c;
  16436. /* Same as READ_UTF8() above but without the zTerm parameter.
  16437. ** For this routine, we assume the UTF8 string is always zero-terminated.
  16438. */
  16439. c = *(zIn++);
  16440. if( c>=0xc0 ){
  16441. c = sqlite3Utf8Trans1[c-0xc0];
  16442. while( (*zIn & 0xc0)==0x80 ){
  16443. c = (c<<6) + (0x3f & *(zIn++));
  16444. }
  16445. if( c<0x80
  16446. || (c&0xFFFFF800)==0xD800
  16447. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  16448. }
  16449. *pzNext = zIn;
  16450. return c;
  16451. }
  16452. /*
  16453. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  16454. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  16455. */
  16456. /* #define TRANSLATE_TRACE 1 */
  16457. #ifndef SQLITE_OMIT_UTF16
  16458. /*
  16459. ** This routine transforms the internal text encoding used by pMem to
  16460. ** desiredEnc. It is an error if the string is already of the desired
  16461. ** encoding, or if *pMem does not contain a string value.
  16462. */
  16463. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  16464. int len; /* Maximum length of output string in bytes */
  16465. unsigned char *zOut; /* Output buffer */
  16466. unsigned char *zIn; /* Input iterator */
  16467. unsigned char *zTerm; /* End of input */
  16468. unsigned char *z; /* Output iterator */
  16469. unsigned int c;
  16470. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  16471. assert( pMem->flags&MEM_Str );
  16472. assert( pMem->enc!=desiredEnc );
  16473. assert( pMem->enc!=0 );
  16474. assert( pMem->n>=0 );
  16475. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  16476. {
  16477. char zBuf[100];
  16478. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  16479. fprintf(stderr, "INPUT: %s\n", zBuf);
  16480. }
  16481. #endif
  16482. /* If the translation is between UTF-16 little and big endian, then
  16483. ** all that is required is to swap the byte order. This case is handled
  16484. ** differently from the others.
  16485. */
  16486. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  16487. u8 temp;
  16488. int rc;
  16489. rc = sqlite3VdbeMemMakeWriteable(pMem);
  16490. if( rc!=SQLITE_OK ){
  16491. assert( rc==SQLITE_NOMEM );
  16492. return SQLITE_NOMEM;
  16493. }
  16494. zIn = (u8*)pMem->z;
  16495. zTerm = &zIn[pMem->n&~1];
  16496. while( zIn<zTerm ){
  16497. temp = *zIn;
  16498. *zIn = *(zIn+1);
  16499. zIn++;
  16500. *zIn++ = temp;
  16501. }
  16502. pMem->enc = desiredEnc;
  16503. goto translate_out;
  16504. }
  16505. /* Set len to the maximum number of bytes required in the output buffer. */
  16506. if( desiredEnc==SQLITE_UTF8 ){
  16507. /* When converting from UTF-16, the maximum growth results from
  16508. ** translating a 2-byte character to a 4-byte UTF-8 character.
  16509. ** A single byte is required for the output string
  16510. ** nul-terminator.
  16511. */
  16512. pMem->n &= ~1;
  16513. len = pMem->n * 2 + 1;
  16514. }else{
  16515. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  16516. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  16517. ** character. Two bytes are required in the output buffer for the
  16518. ** nul-terminator.
  16519. */
  16520. len = pMem->n * 2 + 2;
  16521. }
  16522. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  16523. ** byte past the end.
  16524. **
  16525. ** Variable zOut is set to point at the output buffer, space obtained
  16526. ** from sqlite3_malloc().
  16527. */
  16528. zIn = (u8*)pMem->z;
  16529. zTerm = &zIn[pMem->n];
  16530. zOut = sqlite3DbMallocRaw(pMem->db, len);
  16531. if( !zOut ){
  16532. return SQLITE_NOMEM;
  16533. }
  16534. z = zOut;
  16535. if( pMem->enc==SQLITE_UTF8 ){
  16536. if( desiredEnc==SQLITE_UTF16LE ){
  16537. /* UTF-8 -> UTF-16 Little-endian */
  16538. while( zIn<zTerm ){
  16539. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  16540. READ_UTF8(zIn, zTerm, c);
  16541. WRITE_UTF16LE(z, c);
  16542. }
  16543. }else{
  16544. assert( desiredEnc==SQLITE_UTF16BE );
  16545. /* UTF-8 -> UTF-16 Big-endian */
  16546. while( zIn<zTerm ){
  16547. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  16548. READ_UTF8(zIn, zTerm, c);
  16549. WRITE_UTF16BE(z, c);
  16550. }
  16551. }
  16552. pMem->n = (int)(z - zOut);
  16553. *z++ = 0;
  16554. }else{
  16555. assert( desiredEnc==SQLITE_UTF8 );
  16556. if( pMem->enc==SQLITE_UTF16LE ){
  16557. /* UTF-16 Little-endian -> UTF-8 */
  16558. while( zIn<zTerm ){
  16559. READ_UTF16LE(zIn, c);
  16560. WRITE_UTF8(z, c);
  16561. }
  16562. }else{
  16563. /* UTF-16 Big-endian -> UTF-8 */
  16564. while( zIn<zTerm ){
  16565. READ_UTF16BE(zIn, c);
  16566. WRITE_UTF8(z, c);
  16567. }
  16568. }
  16569. pMem->n = (int)(z - zOut);
  16570. }
  16571. *z = 0;
  16572. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  16573. sqlite3VdbeMemRelease(pMem);
  16574. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  16575. pMem->enc = desiredEnc;
  16576. pMem->flags |= (MEM_Term|MEM_Dyn);
  16577. pMem->z = (char*)zOut;
  16578. pMem->zMalloc = pMem->z;
  16579. translate_out:
  16580. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  16581. {
  16582. char zBuf[100];
  16583. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  16584. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  16585. }
  16586. #endif
  16587. return SQLITE_OK;
  16588. }
  16589. /*
  16590. ** This routine checks for a byte-order mark at the beginning of the
  16591. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  16592. ** the encoding of the Mem adjusted. This routine does not do any
  16593. ** byte-swapping, it just sets Mem.enc appropriately.
  16594. **
  16595. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  16596. ** changed by this function.
  16597. */
  16598. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  16599. int rc = SQLITE_OK;
  16600. u8 bom = 0;
  16601. assert( pMem->n>=0 );
  16602. if( pMem->n>1 ){
  16603. u8 b1 = *(u8 *)pMem->z;
  16604. u8 b2 = *(((u8 *)pMem->z) + 1);
  16605. if( b1==0xFE && b2==0xFF ){
  16606. bom = SQLITE_UTF16BE;
  16607. }
  16608. if( b1==0xFF && b2==0xFE ){
  16609. bom = SQLITE_UTF16LE;
  16610. }
  16611. }
  16612. if( bom ){
  16613. rc = sqlite3VdbeMemMakeWriteable(pMem);
  16614. if( rc==SQLITE_OK ){
  16615. pMem->n -= 2;
  16616. memmove(pMem->z, &pMem->z[2], pMem->n);
  16617. pMem->z[pMem->n] = '\0';
  16618. pMem->z[pMem->n+1] = '\0';
  16619. pMem->flags |= MEM_Term;
  16620. pMem->enc = bom;
  16621. }
  16622. }
  16623. return rc;
  16624. }
  16625. #endif /* SQLITE_OMIT_UTF16 */
  16626. /*
  16627. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  16628. ** return the number of unicode characters in pZ up to (but not including)
  16629. ** the first 0x00 byte. If nByte is not less than zero, return the
  16630. ** number of unicode characters in the first nByte of pZ (or up to
  16631. ** the first 0x00, whichever comes first).
  16632. */
  16633. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  16634. int r = 0;
  16635. const u8 *z = (const u8*)zIn;
  16636. const u8 *zTerm;
  16637. if( nByte>=0 ){
  16638. zTerm = &z[nByte];
  16639. }else{
  16640. zTerm = (const u8*)(-1);
  16641. }
  16642. assert( z<=zTerm );
  16643. while( *z!=0 && z<zTerm ){
  16644. SQLITE_SKIP_UTF8(z);
  16645. r++;
  16646. }
  16647. return r;
  16648. }
  16649. /* This test function is not currently used by the automated test-suite.
  16650. ** Hence it is only available in debug builds.
  16651. */
  16652. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  16653. /*
  16654. ** Translate UTF-8 to UTF-8.
  16655. **
  16656. ** This has the effect of making sure that the string is well-formed
  16657. ** UTF-8. Miscoded characters are removed.
  16658. **
  16659. ** The translation is done in-place (since it is impossible for the
  16660. ** correct UTF-8 encoding to be longer than a malformed encoding).
  16661. */
  16662. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  16663. unsigned char *zOut = zIn;
  16664. unsigned char *zStart = zIn;
  16665. u32 c;
  16666. while( zIn[0] ){
  16667. c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
  16668. if( c!=0xfffd ){
  16669. WRITE_UTF8(zOut, c);
  16670. }
  16671. }
  16672. *zOut = 0;
  16673. return (int)(zOut - zStart);
  16674. }
  16675. #endif
  16676. #ifndef SQLITE_OMIT_UTF16
  16677. /*
  16678. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  16679. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  16680. ** be freed by the calling function.
  16681. **
  16682. ** NULL is returned if there is an allocation error.
  16683. */
  16684. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
  16685. Mem m;
  16686. memset(&m, 0, sizeof(m));
  16687. m.db = db;
  16688. sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  16689. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  16690. if( db->mallocFailed ){
  16691. sqlite3VdbeMemRelease(&m);
  16692. m.z = 0;
  16693. }
  16694. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  16695. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  16696. return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
  16697. }
  16698. /*
  16699. ** pZ is a UTF-16 encoded unicode string at least nChar characters long.
  16700. ** Return the number of bytes in the first nChar unicode characters
  16701. ** in pZ. nChar must be non-negative.
  16702. */
  16703. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  16704. int c;
  16705. unsigned char const *z = zIn;
  16706. int n = 0;
  16707. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  16708. /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
  16709. ** and in other parts of this file means that at one branch will
  16710. ** not be covered by coverage testing on any single host. But coverage
  16711. ** will be complete if the tests are run on both a little-endian and
  16712. ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
  16713. ** macros are constant at compile time the compiler can determine
  16714. ** which branch will be followed. It is therefore assumed that no runtime
  16715. ** penalty is paid for this "if" statement.
  16716. */
  16717. while( n<nChar ){
  16718. READ_UTF16BE(z, c);
  16719. n++;
  16720. }
  16721. }else{
  16722. while( n<nChar ){
  16723. READ_UTF16LE(z, c);
  16724. n++;
  16725. }
  16726. }
  16727. return (int)(z-(unsigned char const *)zIn);
  16728. }
  16729. #if defined(SQLITE_TEST)
  16730. /*
  16731. ** This routine is called from the TCL test function "translate_selftest".
  16732. ** It checks that the primitives for serializing and deserializing
  16733. ** characters in each encoding are inverses of each other.
  16734. */
  16735. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  16736. unsigned int i, t;
  16737. unsigned char zBuf[20];
  16738. unsigned char *z;
  16739. int n;
  16740. unsigned int c;
  16741. for(i=0; i<0x00110000; i++){
  16742. z = zBuf;
  16743. WRITE_UTF8(z, i);
  16744. n = (int)(z-zBuf);
  16745. assert( n>0 && n<=4 );
  16746. z[0] = 0;
  16747. z = zBuf;
  16748. c = sqlite3Utf8Read(z, (const u8**)&z);
  16749. t = i;
  16750. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  16751. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  16752. assert( c==t );
  16753. assert( (z-zBuf)==n );
  16754. }
  16755. for(i=0; i<0x00110000; i++){
  16756. if( i>=0xD800 && i<0xE000 ) continue;
  16757. z = zBuf;
  16758. WRITE_UTF16LE(z, i);
  16759. n = (int)(z-zBuf);
  16760. assert( n>0 && n<=4 );
  16761. z[0] = 0;
  16762. z = zBuf;
  16763. READ_UTF16LE(z, c);
  16764. assert( c==i );
  16765. assert( (z-zBuf)==n );
  16766. }
  16767. for(i=0; i<0x00110000; i++){
  16768. if( i>=0xD800 && i<0xE000 ) continue;
  16769. z = zBuf;
  16770. WRITE_UTF16BE(z, i);
  16771. n = (int)(z-zBuf);
  16772. assert( n>0 && n<=4 );
  16773. z[0] = 0;
  16774. z = zBuf;
  16775. READ_UTF16BE(z, c);
  16776. assert( c==i );
  16777. assert( (z-zBuf)==n );
  16778. }
  16779. }
  16780. #endif /* SQLITE_TEST */
  16781. #endif /* SQLITE_OMIT_UTF16 */
  16782. /************** End of utf.c *************************************************/
  16783. /************** Begin file util.c ********************************************/
  16784. /*
  16785. ** 2001 September 15
  16786. **
  16787. ** The author disclaims copyright to this source code. In place of
  16788. ** a legal notice, here is a blessing:
  16789. **
  16790. ** May you do good and not evil.
  16791. ** May you find forgiveness for yourself and forgive others.
  16792. ** May you share freely, never taking more than you give.
  16793. **
  16794. *************************************************************************
  16795. ** Utility functions used throughout sqlite.
  16796. **
  16797. ** This file contains functions for allocating memory, comparing
  16798. ** strings, and stuff like that.
  16799. **
  16800. ** $Id: util.c,v 1.249 2009/03/01 22:29:20 drh Exp $
  16801. */
  16802. /*
  16803. ** Routine needed to support the testcase() macro.
  16804. */
  16805. #ifdef SQLITE_COVERAGE_TEST
  16806. SQLITE_PRIVATE void sqlite3Coverage(int x){
  16807. static int dummy = 0;
  16808. dummy += x;
  16809. }
  16810. #endif
  16811. /*
  16812. ** Routine needed to support the ALWAYS() and NEVER() macros.
  16813. **
  16814. ** The argument to ALWAYS() should always be true and the argument
  16815. ** to NEVER() should always be false. If either is not the case
  16816. ** then this routine is called in order to throw an error.
  16817. **
  16818. ** This routine only exists if assert() is operational. It always
  16819. ** throws an assert on its first invocation. The variable has a long
  16820. ** name to help the assert() message be more readable. The variable
  16821. ** is used to prevent a too-clever optimizer from optimizing out the
  16822. ** entire call.
  16823. */
  16824. #ifndef NDEBUG
  16825. SQLITE_PRIVATE int sqlite3Assert(void){
  16826. static volatile int ALWAYS_was_false_or_NEVER_was_true = 0;
  16827. assert( ALWAYS_was_false_or_NEVER_was_true ); /* Always fails */
  16828. return ALWAYS_was_false_or_NEVER_was_true++; /* Not Reached */
  16829. }
  16830. #endif
  16831. /*
  16832. ** Return true if the floating point value is Not a Number (NaN).
  16833. */
  16834. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  16835. /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
  16836. ** On the other hand, the use of -ffast-math comes with the following
  16837. ** warning:
  16838. **
  16839. ** This option [-ffast-math] should never be turned on by any
  16840. ** -O option since it can result in incorrect output for programs
  16841. ** which depend on an exact implementation of IEEE or ISO
  16842. ** rules/specifications for math functions.
  16843. **
  16844. ** Under MSVC, this NaN test may fail if compiled with a floating-
  16845. ** point precision mode other than /fp:precise. From the MSDN
  16846. ** documentation:
  16847. **
  16848. ** The compiler [with /fp:precise] will properly handle comparisons
  16849. ** involving NaN. For example, x != x evaluates to true if x is NaN
  16850. ** ...
  16851. */
  16852. #ifdef __FAST_MATH__
  16853. # error SQLite will not work correctly with the -ffast-math option of GCC.
  16854. #endif
  16855. volatile double y = x;
  16856. volatile double z = y;
  16857. return y!=z;
  16858. }
  16859. /*
  16860. ** Compute a string length that is limited to what can be stored in
  16861. ** lower 30 bits of a 32-bit signed integer.
  16862. */
  16863. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  16864. const char *z2 = z;
  16865. while( *z2 ){ z2++; }
  16866. return 0x3fffffff & (int)(z2 - z);
  16867. }
  16868. /*
  16869. ** Return the length of a string, except do not allow the string length
  16870. ** to exceed the SQLITE_LIMIT_LENGTH setting.
  16871. */
  16872. SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
  16873. const char *z2 = z;
  16874. int len;
  16875. int x;
  16876. while( *z2 ){ z2++; }
  16877. x = (int)(z2 - z);
  16878. len = 0x7fffffff & x;
  16879. if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
  16880. return db->aLimit[SQLITE_LIMIT_LENGTH];
  16881. }else{
  16882. return len;
  16883. }
  16884. }
  16885. /*
  16886. ** Set the most recent error code and error string for the sqlite
  16887. ** handle "db". The error code is set to "err_code".
  16888. **
  16889. ** If it is not NULL, string zFormat specifies the format of the
  16890. ** error string in the style of the printf functions: The following
  16891. ** format characters are allowed:
  16892. **
  16893. ** %s Insert a string
  16894. ** %z A string that should be freed after use
  16895. ** %d Insert an integer
  16896. ** %T Insert a token
  16897. ** %S Insert the first element of a SrcList
  16898. **
  16899. ** zFormat and any string tokens that follow it are assumed to be
  16900. ** encoded in UTF-8.
  16901. **
  16902. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  16903. ** should be called with err_code set to SQLITE_OK and zFormat set
  16904. ** to NULL.
  16905. */
  16906. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  16907. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  16908. db->errCode = err_code;
  16909. if( zFormat ){
  16910. char *z;
  16911. va_list ap;
  16912. va_start(ap, zFormat);
  16913. z = sqlite3VMPrintf(db, zFormat, ap);
  16914. va_end(ap);
  16915. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  16916. }else{
  16917. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  16918. }
  16919. }
  16920. }
  16921. /*
  16922. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  16923. ** The following formatting characters are allowed:
  16924. **
  16925. ** %s Insert a string
  16926. ** %z A string that should be freed after use
  16927. ** %d Insert an integer
  16928. ** %T Insert a token
  16929. ** %S Insert the first element of a SrcList
  16930. **
  16931. ** This function should be used to report any error that occurs whilst
  16932. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  16933. ** last thing the sqlite3_prepare() function does is copy the error
  16934. ** stored by this function into the database handle using sqlite3Error().
  16935. ** Function sqlite3Error() should be used during statement execution
  16936. ** (sqlite3_step() etc.).
  16937. */
  16938. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  16939. va_list ap;
  16940. sqlite3 *db = pParse->db;
  16941. pParse->nErr++;
  16942. sqlite3DbFree(db, pParse->zErrMsg);
  16943. va_start(ap, zFormat);
  16944. pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
  16945. va_end(ap);
  16946. if( pParse->rc==SQLITE_OK ){
  16947. pParse->rc = SQLITE_ERROR;
  16948. }
  16949. }
  16950. /*
  16951. ** Clear the error message in pParse, if any
  16952. */
  16953. SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
  16954. sqlite3DbFree(pParse->db, pParse->zErrMsg);
  16955. pParse->zErrMsg = 0;
  16956. pParse->nErr = 0;
  16957. }
  16958. /*
  16959. ** Convert an SQL-style quoted string into a normal string by removing
  16960. ** the quote characters. The conversion is done in-place. If the
  16961. ** input does not begin with a quote character, then this routine
  16962. ** is a no-op.
  16963. **
  16964. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  16965. ** brackets from around identifers. For example: "[a-b-c]" becomes
  16966. ** "a-b-c".
  16967. */
  16968. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  16969. char quote;
  16970. int i, j;
  16971. if( z==0 ) return;
  16972. quote = z[0];
  16973. switch( quote ){
  16974. case '\'': break;
  16975. case '"': break;
  16976. case '`': break; /* For MySQL compatibility */
  16977. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  16978. default: return;
  16979. }
  16980. for(i=1, j=0; z[i]; i++){
  16981. if( z[i]==quote ){
  16982. if( z[i+1]==quote ){
  16983. z[j++] = quote;
  16984. i++;
  16985. }else{
  16986. z[j++] = 0;
  16987. break;
  16988. }
  16989. }else{
  16990. z[j++] = z[i];
  16991. }
  16992. }
  16993. }
  16994. /* Convenient short-hand */
  16995. #define UpperToLower sqlite3UpperToLower
  16996. /*
  16997. ** Some systems have stricmp(). Others have strcasecmp(). Because
  16998. ** there is no consistency, we will define our own.
  16999. */
  17000. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  17001. register unsigned char *a, *b;
  17002. a = (unsigned char *)zLeft;
  17003. b = (unsigned char *)zRight;
  17004. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  17005. return UpperToLower[*a] - UpperToLower[*b];
  17006. }
  17007. SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
  17008. register unsigned char *a, *b;
  17009. a = (unsigned char *)zLeft;
  17010. b = (unsigned char *)zRight;
  17011. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  17012. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  17013. }
  17014. /*
  17015. ** Return TRUE if z is a pure numeric string. Return FALSE if the
  17016. ** string contains any character which is not part of a number. If
  17017. ** the string is numeric and contains the '.' character, set *realnum
  17018. ** to TRUE (otherwise FALSE).
  17019. **
  17020. ** An empty string is considered non-numeric.
  17021. */
  17022. SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
  17023. int incr = (enc==SQLITE_UTF8?1:2);
  17024. if( enc==SQLITE_UTF16BE ) z++;
  17025. if( *z=='-' || *z=='+' ) z += incr;
  17026. if( !sqlite3Isdigit(*z) ){
  17027. return 0;
  17028. }
  17029. z += incr;
  17030. if( realnum ) *realnum = 0;
  17031. while( sqlite3Isdigit(*z) ){ z += incr; }
  17032. if( *z=='.' ){
  17033. z += incr;
  17034. if( !sqlite3Isdigit(*z) ) return 0;
  17035. while( sqlite3Isdigit(*z) ){ z += incr; }
  17036. if( realnum ) *realnum = 1;
  17037. }
  17038. if( *z=='e' || *z=='E' ){
  17039. z += incr;
  17040. if( *z=='+' || *z=='-' ) z += incr;
  17041. if( !sqlite3Isdigit(*z) ) return 0;
  17042. while( sqlite3Isdigit(*z) ){ z += incr; }
  17043. if( realnum ) *realnum = 1;
  17044. }
  17045. return *z==0;
  17046. }
  17047. /*
  17048. ** The string z[] is an ascii representation of a real number.
  17049. ** Convert this string to a double.
  17050. **
  17051. ** This routine assumes that z[] really is a valid number. If it
  17052. ** is not, the result is undefined.
  17053. **
  17054. ** This routine is used instead of the library atof() function because
  17055. ** the library atof() might want to use "," as the decimal point instead
  17056. ** of "." depending on how locale is set. But that would cause problems
  17057. ** for SQL. So this routine always uses "." regardless of locale.
  17058. */
  17059. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
  17060. #ifndef SQLITE_OMIT_FLOATING_POINT
  17061. int sign = 1;
  17062. const char *zBegin = z;
  17063. LONGDOUBLE_TYPE v1 = 0.0;
  17064. int nSignificant = 0;
  17065. while( sqlite3Isspace(*z) ) z++;
  17066. if( *z=='-' ){
  17067. sign = -1;
  17068. z++;
  17069. }else if( *z=='+' ){
  17070. z++;
  17071. }
  17072. while( z[0]=='0' ){
  17073. z++;
  17074. }
  17075. while( sqlite3Isdigit(*z) ){
  17076. v1 = v1*10.0 + (*z - '0');
  17077. z++;
  17078. nSignificant++;
  17079. }
  17080. if( *z=='.' ){
  17081. LONGDOUBLE_TYPE divisor = 1.0;
  17082. z++;
  17083. if( nSignificant==0 ){
  17084. while( z[0]=='0' ){
  17085. divisor *= 10.0;
  17086. z++;
  17087. }
  17088. }
  17089. while( sqlite3Isdigit(*z) ){
  17090. if( nSignificant<18 ){
  17091. v1 = v1*10.0 + (*z - '0');
  17092. divisor *= 10.0;
  17093. nSignificant++;
  17094. }
  17095. z++;
  17096. }
  17097. v1 /= divisor;
  17098. }
  17099. if( *z=='e' || *z=='E' ){
  17100. int esign = 1;
  17101. int eval = 0;
  17102. LONGDOUBLE_TYPE scale = 1.0;
  17103. z++;
  17104. if( *z=='-' ){
  17105. esign = -1;
  17106. z++;
  17107. }else if( *z=='+' ){
  17108. z++;
  17109. }
  17110. while( sqlite3Isdigit(*z) ){
  17111. eval = eval*10 + *z - '0';
  17112. z++;
  17113. }
  17114. while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
  17115. while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
  17116. while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
  17117. while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
  17118. if( esign<0 ){
  17119. v1 /= scale;
  17120. }else{
  17121. v1 *= scale;
  17122. }
  17123. }
  17124. *pResult = (double)(sign<0 ? -v1 : v1);
  17125. return (int)(z - zBegin);
  17126. #else
  17127. return sqlite3Atoi64(z, pResult);
  17128. #endif /* SQLITE_OMIT_FLOATING_POINT */
  17129. }
  17130. /*
  17131. ** Compare the 19-character string zNum against the text representation
  17132. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  17133. ** if zNum is less than, equal to, or greater than the string.
  17134. **
  17135. ** Unlike memcmp() this routine is guaranteed to return the difference
  17136. ** in the values of the last digit if the only difference is in the
  17137. ** last digit. So, for example,
  17138. **
  17139. ** compare2pow63("9223372036854775800")
  17140. **
  17141. ** will return -8.
  17142. */
  17143. static int compare2pow63(const char *zNum){
  17144. int c;
  17145. c = memcmp(zNum,"922337203685477580",18);
  17146. if( c==0 ){
  17147. c = zNum[18] - '8';
  17148. }
  17149. return c;
  17150. }
  17151. /*
  17152. ** Return TRUE if zNum is a 64-bit signed integer and write
  17153. ** the value of the integer into *pNum. If zNum is not an integer
  17154. ** or is an integer that is too large to be expressed with 64 bits,
  17155. ** then return false.
  17156. **
  17157. ** When this routine was originally written it dealt with only
  17158. ** 32-bit numbers. At that time, it was much faster than the
  17159. ** atoi() library routine in RedHat 7.2.
  17160. */
  17161. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
  17162. i64 v = 0;
  17163. int neg;
  17164. int i, c;
  17165. const char *zStart;
  17166. while( sqlite3Isspace(*zNum) ) zNum++;
  17167. if( *zNum=='-' ){
  17168. neg = 1;
  17169. zNum++;
  17170. }else if( *zNum=='+' ){
  17171. neg = 0;
  17172. zNum++;
  17173. }else{
  17174. neg = 0;
  17175. }
  17176. zStart = zNum;
  17177. while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
  17178. for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
  17179. v = v*10 + c - '0';
  17180. }
  17181. *pNum = neg ? -v : v;
  17182. if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
  17183. /* zNum is empty or contains non-numeric text or is longer
  17184. ** than 19 digits (thus guaranting that it is too large) */
  17185. return 0;
  17186. }else if( i<19 ){
  17187. /* Less than 19 digits, so we know that it fits in 64 bits */
  17188. return 1;
  17189. }else{
  17190. /* 19-digit numbers must be no larger than 9223372036854775807 if positive
  17191. ** or 9223372036854775808 if negative. Note that 9223372036854665808
  17192. ** is 2^63. */
  17193. return compare2pow63(zNum)<neg;
  17194. }
  17195. }
  17196. /*
  17197. ** The string zNum represents an integer. There might be some other
  17198. ** information following the integer too, but that part is ignored.
  17199. ** If the integer that the prefix of zNum represents will fit in a
  17200. ** 64-bit signed integer, return TRUE. Otherwise return FALSE.
  17201. **
  17202. ** This routine returns FALSE for the string -9223372036854775808 even that
  17203. ** that number will, in theory fit in a 64-bit integer. Positive
  17204. ** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
  17205. ** false.
  17206. */
  17207. SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
  17208. int i, c;
  17209. int neg = 0;
  17210. if( *zNum=='-' ){
  17211. neg = 1;
  17212. zNum++;
  17213. }else if( *zNum=='+' ){
  17214. zNum++;
  17215. }
  17216. if( negFlag ) neg = 1-neg;
  17217. while( *zNum=='0' ){
  17218. zNum++; /* Skip leading zeros. Ticket #2454 */
  17219. }
  17220. for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  17221. if( i<19 ){
  17222. /* Guaranteed to fit if less than 19 digits */
  17223. return 1;
  17224. }else if( i>19 ){
  17225. /* Guaranteed to be too big if greater than 19 digits */
  17226. return 0;
  17227. }else{
  17228. /* Compare against 2^63. */
  17229. return compare2pow63(zNum)<neg;
  17230. }
  17231. }
  17232. /*
  17233. ** If zNum represents an integer that will fit in 32-bits, then set
  17234. ** *pValue to that integer and return true. Otherwise return false.
  17235. **
  17236. ** Any non-numeric characters that following zNum are ignored.
  17237. ** This is different from sqlite3Atoi64() which requires the
  17238. ** input number to be zero-terminated.
  17239. */
  17240. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  17241. sqlite_int64 v = 0;
  17242. int i, c;
  17243. int neg = 0;
  17244. if( zNum[0]=='-' ){
  17245. neg = 1;
  17246. zNum++;
  17247. }else if( zNum[0]=='+' ){
  17248. zNum++;
  17249. }
  17250. while( zNum[0]=='0' ) zNum++;
  17251. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  17252. v = v*10 + c;
  17253. }
  17254. /* The longest decimal representation of a 32 bit integer is 10 digits:
  17255. **
  17256. ** 1234567890
  17257. ** 2^31 -> 2147483648
  17258. */
  17259. if( i>10 ){
  17260. return 0;
  17261. }
  17262. if( v-neg>2147483647 ){
  17263. return 0;
  17264. }
  17265. if( neg ){
  17266. v = -v;
  17267. }
  17268. *pValue = (int)v;
  17269. return 1;
  17270. }
  17271. /*
  17272. ** The variable-length integer encoding is as follows:
  17273. **
  17274. ** KEY:
  17275. ** A = 0xxxxxxx 7 bits of data and one flag bit
  17276. ** B = 1xxxxxxx 7 bits of data and one flag bit
  17277. ** C = xxxxxxxx 8 bits of data
  17278. **
  17279. ** 7 bits - A
  17280. ** 14 bits - BA
  17281. ** 21 bits - BBA
  17282. ** 28 bits - BBBA
  17283. ** 35 bits - BBBBA
  17284. ** 42 bits - BBBBBA
  17285. ** 49 bits - BBBBBBA
  17286. ** 56 bits - BBBBBBBA
  17287. ** 64 bits - BBBBBBBBC
  17288. */
  17289. /*
  17290. ** Write a 64-bit variable-length integer to memory starting at p[0].
  17291. ** The length of data write will be between 1 and 9 bytes. The number
  17292. ** of bytes written is returned.
  17293. **
  17294. ** A variable-length integer consists of the lower 7 bits of each byte
  17295. ** for all bytes that have the 8th bit set and one byte with the 8th
  17296. ** bit clear. Except, if we get to the 9th byte, it stores the full
  17297. ** 8 bits and is the last byte.
  17298. */
  17299. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  17300. int i, j, n;
  17301. u8 buf[10];
  17302. if( v & (((u64)0xff000000)<<32) ){
  17303. p[8] = (u8)v;
  17304. v >>= 8;
  17305. for(i=7; i>=0; i--){
  17306. p[i] = (u8)((v & 0x7f) | 0x80);
  17307. v >>= 7;
  17308. }
  17309. return 9;
  17310. }
  17311. n = 0;
  17312. do{
  17313. buf[n++] = (u8)((v & 0x7f) | 0x80);
  17314. v >>= 7;
  17315. }while( v!=0 );
  17316. buf[0] &= 0x7f;
  17317. assert( n<=9 );
  17318. for(i=0, j=n-1; j>=0; j--, i++){
  17319. p[i] = buf[j];
  17320. }
  17321. return n;
  17322. }
  17323. /*
  17324. ** This routine is a faster version of sqlite3PutVarint() that only
  17325. ** works for 32-bit positive integers and which is optimized for
  17326. ** the common case of small integers. A MACRO version, putVarint32,
  17327. ** is provided which inlines the single-byte case. All code should use
  17328. ** the MACRO version as this function assumes the single-byte case has
  17329. ** already been handled.
  17330. */
  17331. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  17332. #ifndef putVarint32
  17333. if( (v & ~0x7f)==0 ){
  17334. p[0] = v;
  17335. return 1;
  17336. }
  17337. #endif
  17338. if( (v & ~0x3fff)==0 ){
  17339. p[0] = (u8)((v>>7) | 0x80);
  17340. p[1] = (u8)(v & 0x7f);
  17341. return 2;
  17342. }
  17343. return sqlite3PutVarint(p, v);
  17344. }
  17345. /*
  17346. ** Read a 64-bit variable-length integer from memory starting at p[0].
  17347. ** Return the number of bytes read. The value is stored in *v.
  17348. */
  17349. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  17350. u32 a,b,s;
  17351. a = *p;
  17352. /* a: p0 (unmasked) */
  17353. if (!(a&0x80))
  17354. {
  17355. *v = a;
  17356. return 1;
  17357. }
  17358. p++;
  17359. b = *p;
  17360. /* b: p1 (unmasked) */
  17361. if (!(b&0x80))
  17362. {
  17363. a &= 0x7f;
  17364. a = a<<7;
  17365. a |= b;
  17366. *v = a;
  17367. return 2;
  17368. }
  17369. p++;
  17370. a = a<<14;
  17371. a |= *p;
  17372. /* a: p0<<14 | p2 (unmasked) */
  17373. if (!(a&0x80))
  17374. {
  17375. a &= (0x7f<<14)|(0x7f);
  17376. b &= 0x7f;
  17377. b = b<<7;
  17378. a |= b;
  17379. *v = a;
  17380. return 3;
  17381. }
  17382. /* CSE1 from below */
  17383. a &= (0x7f<<14)|(0x7f);
  17384. p++;
  17385. b = b<<14;
  17386. b |= *p;
  17387. /* b: p1<<14 | p3 (unmasked) */
  17388. if (!(b&0x80))
  17389. {
  17390. b &= (0x7f<<14)|(0x7f);
  17391. /* moved CSE1 up */
  17392. /* a &= (0x7f<<14)|(0x7f); */
  17393. a = a<<7;
  17394. a |= b;
  17395. *v = a;
  17396. return 4;
  17397. }
  17398. /* a: p0<<14 | p2 (masked) */
  17399. /* b: p1<<14 | p3 (unmasked) */
  17400. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  17401. /* moved CSE1 up */
  17402. /* a &= (0x7f<<14)|(0x7f); */
  17403. b &= (0x7f<<14)|(0x7f);
  17404. s = a;
  17405. /* s: p0<<14 | p2 (masked) */
  17406. p++;
  17407. a = a<<14;
  17408. a |= *p;
  17409. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  17410. if (!(a&0x80))
  17411. {
  17412. /* we can skip these cause they were (effectively) done above in calc'ing s */
  17413. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  17414. /* b &= (0x7f<<14)|(0x7f); */
  17415. b = b<<7;
  17416. a |= b;
  17417. s = s>>18;
  17418. *v = ((u64)s)<<32 | a;
  17419. return 5;
  17420. }
  17421. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  17422. s = s<<7;
  17423. s |= b;
  17424. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  17425. p++;
  17426. b = b<<14;
  17427. b |= *p;
  17428. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  17429. if (!(b&0x80))
  17430. {
  17431. /* we can skip this cause it was (effectively) done above in calc'ing s */
  17432. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  17433. a &= (0x7f<<14)|(0x7f);
  17434. a = a<<7;
  17435. a |= b;
  17436. s = s>>18;
  17437. *v = ((u64)s)<<32 | a;
  17438. return 6;
  17439. }
  17440. p++;
  17441. a = a<<14;
  17442. a |= *p;
  17443. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  17444. if (!(a&0x80))
  17445. {
  17446. a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
  17447. b &= (0x7f<<14)|(0x7f);
  17448. b = b<<7;
  17449. a |= b;
  17450. s = s>>11;
  17451. *v = ((u64)s)<<32 | a;
  17452. return 7;
  17453. }
  17454. /* CSE2 from below */
  17455. a &= (0x7f<<14)|(0x7f);
  17456. p++;
  17457. b = b<<14;
  17458. b |= *p;
  17459. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  17460. if (!(b&0x80))
  17461. {
  17462. b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
  17463. /* moved CSE2 up */
  17464. /* a &= (0x7f<<14)|(0x7f); */
  17465. a = a<<7;
  17466. a |= b;
  17467. s = s>>4;
  17468. *v = ((u64)s)<<32 | a;
  17469. return 8;
  17470. }
  17471. p++;
  17472. a = a<<15;
  17473. a |= *p;
  17474. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  17475. /* moved CSE2 up */
  17476. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  17477. b &= (0x7f<<14)|(0x7f);
  17478. b = b<<8;
  17479. a |= b;
  17480. s = s<<4;
  17481. b = p[-4];
  17482. b &= 0x7f;
  17483. b = b>>3;
  17484. s |= b;
  17485. *v = ((u64)s)<<32 | a;
  17486. return 9;
  17487. }
  17488. /*
  17489. ** Read a 32-bit variable-length integer from memory starting at p[0].
  17490. ** Return the number of bytes read. The value is stored in *v.
  17491. ** A MACRO version, getVarint32, is provided which inlines the
  17492. ** single-byte case. All code should use the MACRO version as
  17493. ** this function assumes the single-byte case has already been handled.
  17494. */
  17495. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  17496. u32 a,b;
  17497. a = *p;
  17498. /* a: p0 (unmasked) */
  17499. #ifndef getVarint32
  17500. if (!(a&0x80))
  17501. {
  17502. *v = a;
  17503. return 1;
  17504. }
  17505. #endif
  17506. p++;
  17507. b = *p;
  17508. /* b: p1 (unmasked) */
  17509. if (!(b&0x80))
  17510. {
  17511. a &= 0x7f;
  17512. a = a<<7;
  17513. *v = a | b;
  17514. return 2;
  17515. }
  17516. p++;
  17517. a = a<<14;
  17518. a |= *p;
  17519. /* a: p0<<14 | p2 (unmasked) */
  17520. if (!(a&0x80))
  17521. {
  17522. a &= (0x7f<<14)|(0x7f);
  17523. b &= 0x7f;
  17524. b = b<<7;
  17525. *v = a | b;
  17526. return 3;
  17527. }
  17528. p++;
  17529. b = b<<14;
  17530. b |= *p;
  17531. /* b: p1<<14 | p3 (unmasked) */
  17532. if (!(b&0x80))
  17533. {
  17534. b &= (0x7f<<14)|(0x7f);
  17535. a &= (0x7f<<14)|(0x7f);
  17536. a = a<<7;
  17537. *v = a | b;
  17538. return 4;
  17539. }
  17540. p++;
  17541. a = a<<14;
  17542. a |= *p;
  17543. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  17544. if (!(a&0x80))
  17545. {
  17546. a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
  17547. b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
  17548. b = b<<7;
  17549. *v = a | b;
  17550. return 5;
  17551. }
  17552. /* We can only reach this point when reading a corrupt database
  17553. ** file. In that case we are not in any hurry. Use the (relatively
  17554. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  17555. ** value. */
  17556. {
  17557. u64 v64;
  17558. u8 n;
  17559. p -= 4;
  17560. n = sqlite3GetVarint(p, &v64);
  17561. assert( n>5 && n<=9 );
  17562. *v = (u32)v64;
  17563. return n;
  17564. }
  17565. }
  17566. /*
  17567. ** Return the number of bytes that will be needed to store the given
  17568. ** 64-bit integer.
  17569. */
  17570. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  17571. int i = 0;
  17572. do{
  17573. i++;
  17574. v >>= 7;
  17575. }while( v!=0 && i<9 );
  17576. return i;
  17577. }
  17578. /*
  17579. ** Read or write a four-byte big-endian integer value.
  17580. */
  17581. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  17582. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  17583. }
  17584. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  17585. p[0] = (u8)(v>>24);
  17586. p[1] = (u8)(v>>16);
  17587. p[2] = (u8)(v>>8);
  17588. p[3] = (u8)v;
  17589. }
  17590. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  17591. /*
  17592. ** Translate a single byte of Hex into an integer.
  17593. ** This routinen only works if h really is a valid hexadecimal
  17594. ** character: 0..9a..fA..F
  17595. */
  17596. static u8 hexToInt(int h){
  17597. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  17598. #ifdef SQLITE_ASCII
  17599. h += 9*(1&(h>>6));
  17600. #endif
  17601. #ifdef SQLITE_EBCDIC
  17602. h += 9*(1&~(h>>4));
  17603. #endif
  17604. return (u8)(h & 0xf);
  17605. }
  17606. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  17607. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  17608. /*
  17609. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  17610. ** value. Return a pointer to its binary value. Space to hold the
  17611. ** binary value has been obtained from malloc and must be freed by
  17612. ** the calling routine.
  17613. */
  17614. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  17615. char *zBlob;
  17616. int i;
  17617. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  17618. n--;
  17619. if( zBlob ){
  17620. for(i=0; i<n; i+=2){
  17621. zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
  17622. }
  17623. zBlob[i/2] = 0;
  17624. }
  17625. return zBlob;
  17626. }
  17627. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  17628. /*
  17629. ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
  17630. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
  17631. ** when this routine is called.
  17632. **
  17633. ** This routine is called when entering an SQLite API. The SQLITE_MAGIC_OPEN
  17634. ** value indicates that the database connection passed into the API is
  17635. ** open and is not being used by another thread. By changing the value
  17636. ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
  17637. ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
  17638. ** when the API exits.
  17639. **
  17640. ** This routine is a attempt to detect if two threads use the
  17641. ** same sqlite* pointer at the same time. There is a race
  17642. ** condition so it is possible that the error is not detected.
  17643. ** But usually the problem will be seen. The result will be an
  17644. ** error which can be used to debug the application that is
  17645. ** using SQLite incorrectly.
  17646. **
  17647. ** Ticket #202: If db->magic is not a valid open value, take care not
  17648. ** to modify the db structure at all. It could be that db is a stale
  17649. ** pointer. In other words, it could be that there has been a prior
  17650. ** call to sqlite3_close(db) and db has been deallocated. And we do
  17651. ** not want to write into deallocated memory.
  17652. */
  17653. #ifdef SQLITE_DEBUG
  17654. SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
  17655. if( db->magic==SQLITE_MAGIC_OPEN ){
  17656. db->magic = SQLITE_MAGIC_BUSY;
  17657. assert( sqlite3_mutex_held(db->mutex) );
  17658. return 0;
  17659. }else if( db->magic==SQLITE_MAGIC_BUSY ){
  17660. db->magic = SQLITE_MAGIC_ERROR;
  17661. db->u1.isInterrupted = 1;
  17662. }
  17663. return 1;
  17664. }
  17665. #endif
  17666. /*
  17667. ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
  17668. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
  17669. ** when this routine is called.
  17670. */
  17671. #ifdef SQLITE_DEBUG
  17672. SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
  17673. if( db->magic==SQLITE_MAGIC_BUSY ){
  17674. db->magic = SQLITE_MAGIC_OPEN;
  17675. assert( sqlite3_mutex_held(db->mutex) );
  17676. return 0;
  17677. }else{
  17678. db->magic = SQLITE_MAGIC_ERROR;
  17679. db->u1.isInterrupted = 1;
  17680. return 1;
  17681. }
  17682. }
  17683. #endif
  17684. /*
  17685. ** Check to make sure we have a valid db pointer. This test is not
  17686. ** foolproof but it does provide some measure of protection against
  17687. ** misuse of the interface such as passing in db pointers that are
  17688. ** NULL or which have been previously closed. If this routine returns
  17689. ** 1 it means that the db pointer is valid and 0 if it should not be
  17690. ** dereferenced for any reason. The calling function should invoke
  17691. ** SQLITE_MISUSE immediately.
  17692. **
  17693. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  17694. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  17695. ** open properly and is not fit for general use but which can be
  17696. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  17697. */
  17698. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  17699. u32 magic;
  17700. if( db==0 ) return 0;
  17701. magic = db->magic;
  17702. if( magic!=SQLITE_MAGIC_OPEN &&
  17703. magic!=SQLITE_MAGIC_BUSY ) return 0;
  17704. return 1;
  17705. }
  17706. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  17707. u32 magic;
  17708. if( db==0 ) return 0;
  17709. magic = db->magic;
  17710. if( magic!=SQLITE_MAGIC_SICK &&
  17711. magic!=SQLITE_MAGIC_OPEN &&
  17712. magic!=SQLITE_MAGIC_BUSY ) return 0;
  17713. return 1;
  17714. }
  17715. /************** End of util.c ************************************************/
  17716. /************** Begin file hash.c ********************************************/
  17717. /*
  17718. ** 2001 September 22
  17719. **
  17720. ** The author disclaims copyright to this source code. In place of
  17721. ** a legal notice, here is a blessing:
  17722. **
  17723. ** May you do good and not evil.
  17724. ** May you find forgiveness for yourself and forgive others.
  17725. ** May you share freely, never taking more than you give.
  17726. **
  17727. *************************************************************************
  17728. ** This is the implementation of generic hash-tables
  17729. ** used in SQLite.
  17730. **
  17731. ** $Id: hash.c,v 1.33 2009/01/09 01:12:28 drh Exp $
  17732. */
  17733. /* Turn bulk memory into a hash table object by initializing the
  17734. ** fields of the Hash structure.
  17735. **
  17736. ** "pNew" is a pointer to the hash table that is to be initialized.
  17737. ** "copyKey" is true if the hash table should make its own private
  17738. ** copy of keys and false if it should just use the supplied pointer.
  17739. */
  17740. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
  17741. assert( pNew!=0 );
  17742. pNew->copyKey = copyKey!=0;
  17743. pNew->first = 0;
  17744. pNew->count = 0;
  17745. pNew->htsize = 0;
  17746. pNew->ht = 0;
  17747. }
  17748. /* Remove all entries from a hash table. Reclaim all memory.
  17749. ** Call this routine to delete a hash table or to reset a hash table
  17750. ** to the empty state.
  17751. */
  17752. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  17753. HashElem *elem; /* For looping over all elements of the table */
  17754. assert( pH!=0 );
  17755. elem = pH->first;
  17756. pH->first = 0;
  17757. sqlite3_free(pH->ht);
  17758. pH->ht = 0;
  17759. pH->htsize = 0;
  17760. while( elem ){
  17761. HashElem *next_elem = elem->next;
  17762. if( pH->copyKey ){
  17763. sqlite3_free(elem->pKey);
  17764. }
  17765. sqlite3_free(elem);
  17766. elem = next_elem;
  17767. }
  17768. pH->count = 0;
  17769. }
  17770. /*
  17771. ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
  17772. */
  17773. static int strHash(const void *pKey, int nKey){
  17774. const char *z = (const char *)pKey;
  17775. int h = 0;
  17776. if( nKey<=0 ) nKey = sqlite3Strlen30(z);
  17777. while( nKey > 0 ){
  17778. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  17779. nKey--;
  17780. }
  17781. return h & 0x7fffffff;
  17782. }
  17783. static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  17784. if( n1!=n2 ) return 1;
  17785. return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
  17786. }
  17787. /* Link an element into the hash table
  17788. */
  17789. static void insertElement(
  17790. Hash *pH, /* The complete hash table */
  17791. struct _ht *pEntry, /* The entry into which pNew is inserted */
  17792. HashElem *pNew /* The element to be inserted */
  17793. ){
  17794. HashElem *pHead; /* First element already in pEntry */
  17795. pHead = pEntry->chain;
  17796. if( pHead ){
  17797. pNew->next = pHead;
  17798. pNew->prev = pHead->prev;
  17799. if( pHead->prev ){ pHead->prev->next = pNew; }
  17800. else { pH->first = pNew; }
  17801. pHead->prev = pNew;
  17802. }else{
  17803. pNew->next = pH->first;
  17804. if( pH->first ){ pH->first->prev = pNew; }
  17805. pNew->prev = 0;
  17806. pH->first = pNew;
  17807. }
  17808. pEntry->count++;
  17809. pEntry->chain = pNew;
  17810. }
  17811. /* Resize the hash table so that it cantains "new_size" buckets.
  17812. ** "new_size" must be a power of 2. The hash table might fail
  17813. ** to resize if sqlite3_malloc() fails.
  17814. */
  17815. static void rehash(Hash *pH, int new_size){
  17816. struct _ht *new_ht; /* The new hash table */
  17817. HashElem *elem, *next_elem; /* For looping over existing elements */
  17818. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  17819. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  17820. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  17821. }
  17822. if( new_size==pH->htsize ) return;
  17823. #endif
  17824. /* There is a call to sqlite3_malloc() inside rehash(). If there is
  17825. ** already an allocation at pH->ht, then if this malloc() fails it
  17826. ** is benign (since failing to resize a hash table is a performance
  17827. ** hit only, not a fatal error).
  17828. */
  17829. if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
  17830. new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
  17831. if( pH->htsize>0 ) sqlite3EndBenignMalloc();
  17832. if( new_ht==0 ) return;
  17833. sqlite3_free(pH->ht);
  17834. pH->ht = new_ht;
  17835. pH->htsize = new_size;
  17836. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  17837. int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
  17838. next_elem = elem->next;
  17839. insertElement(pH, &new_ht[h], elem);
  17840. }
  17841. }
  17842. /* This function (for internal use only) locates an element in an
  17843. ** hash table that matches the given key. The hash for this key has
  17844. ** already been computed and is passed as the 4th parameter.
  17845. */
  17846. static HashElem *findElementGivenHash(
  17847. const Hash *pH, /* The pH to be searched */
  17848. const void *pKey, /* The key we are searching for */
  17849. int nKey,
  17850. int h /* The hash for this key. */
  17851. ){
  17852. HashElem *elem; /* Used to loop thru the element list */
  17853. int count; /* Number of elements left to test */
  17854. if( pH->ht ){
  17855. struct _ht *pEntry = &pH->ht[h];
  17856. elem = pEntry->chain;
  17857. count = pEntry->count;
  17858. while( count-- && elem ){
  17859. if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  17860. return elem;
  17861. }
  17862. elem = elem->next;
  17863. }
  17864. }
  17865. return 0;
  17866. }
  17867. /* Remove a single entry from the hash table given a pointer to that
  17868. ** element and a hash on the element's key.
  17869. */
  17870. static void removeElementGivenHash(
  17871. Hash *pH, /* The pH containing "elem" */
  17872. HashElem* elem, /* The element to be removed from the pH */
  17873. int h /* Hash value for the element */
  17874. ){
  17875. struct _ht *pEntry;
  17876. if( elem->prev ){
  17877. elem->prev->next = elem->next;
  17878. }else{
  17879. pH->first = elem->next;
  17880. }
  17881. if( elem->next ){
  17882. elem->next->prev = elem->prev;
  17883. }
  17884. pEntry = &pH->ht[h];
  17885. if( pEntry->chain==elem ){
  17886. pEntry->chain = elem->next;
  17887. }
  17888. pEntry->count--;
  17889. if( pEntry->count<=0 ){
  17890. pEntry->chain = 0;
  17891. }
  17892. if( pH->copyKey ){
  17893. sqlite3_free(elem->pKey);
  17894. }
  17895. sqlite3_free( elem );
  17896. pH->count--;
  17897. if( pH->count<=0 ){
  17898. assert( pH->first==0 );
  17899. assert( pH->count==0 );
  17900. sqlite3HashClear(pH);
  17901. }
  17902. }
  17903. /* Attempt to locate an element of the hash table pH with a key
  17904. ** that matches pKey,nKey. Return a pointer to the corresponding
  17905. ** HashElem structure for this element if it is found, or NULL
  17906. ** otherwise.
  17907. */
  17908. SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
  17909. int h; /* A hash on key */
  17910. HashElem *elem; /* The element that matches key */
  17911. if( pH==0 || pH->ht==0 ) return 0;
  17912. h = strHash(pKey,nKey);
  17913. elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
  17914. return elem;
  17915. }
  17916. /* Attempt to locate an element of the hash table pH with a key
  17917. ** that matches pKey,nKey. Return the data for this element if it is
  17918. ** found, or NULL if there is no match.
  17919. */
  17920. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
  17921. HashElem *elem; /* The element that matches key */
  17922. elem = sqlite3HashFindElem(pH, pKey, nKey);
  17923. return elem ? elem->data : 0;
  17924. }
  17925. /* Insert an element into the hash table pH. The key is pKey,nKey
  17926. ** and the data is "data".
  17927. **
  17928. ** If no element exists with a matching key, then a new
  17929. ** element is created. A copy of the key is made if the copyKey
  17930. ** flag is set. NULL is returned.
  17931. **
  17932. ** If another element already exists with the same key, then the
  17933. ** new data replaces the old data and the old data is returned.
  17934. ** The key is not copied in this instance. If a malloc fails, then
  17935. ** the new data is returned and the hash table is unchanged.
  17936. **
  17937. ** If the "data" parameter to this function is NULL, then the
  17938. ** element corresponding to "key" is removed from the hash table.
  17939. */
  17940. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  17941. int hraw; /* Raw hash value of the key */
  17942. int h; /* the hash of the key modulo hash table size */
  17943. HashElem *elem; /* Used to loop thru the element list */
  17944. HashElem *new_elem; /* New element added to the pH */
  17945. assert( pH!=0 );
  17946. hraw = strHash(pKey, nKey);
  17947. if( pH->htsize ){
  17948. h = hraw % pH->htsize;
  17949. elem = findElementGivenHash(pH,pKey,nKey,h);
  17950. if( elem ){
  17951. void *old_data = elem->data;
  17952. if( data==0 ){
  17953. removeElementGivenHash(pH,elem,h);
  17954. }else{
  17955. elem->data = data;
  17956. if( !pH->copyKey ){
  17957. elem->pKey = (void *)pKey;
  17958. }
  17959. assert(nKey==elem->nKey);
  17960. }
  17961. return old_data;
  17962. }
  17963. }
  17964. if( data==0 ) return 0;
  17965. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  17966. if( new_elem==0 ) return data;
  17967. if( pH->copyKey && pKey!=0 ){
  17968. new_elem->pKey = sqlite3Malloc( nKey );
  17969. if( new_elem->pKey==0 ){
  17970. sqlite3_free(new_elem);
  17971. return data;
  17972. }
  17973. memcpy((void*)new_elem->pKey, pKey, nKey);
  17974. }else{
  17975. new_elem->pKey = (void*)pKey;
  17976. }
  17977. new_elem->nKey = nKey;
  17978. pH->count++;
  17979. if( pH->htsize==0 ){
  17980. rehash(pH, 128/sizeof(pH->ht[0]));
  17981. if( pH->htsize==0 ){
  17982. pH->count = 0;
  17983. if( pH->copyKey ){
  17984. sqlite3_free(new_elem->pKey);
  17985. }
  17986. sqlite3_free(new_elem);
  17987. return data;
  17988. }
  17989. }
  17990. if( pH->count > pH->htsize ){
  17991. rehash(pH,pH->htsize*2);
  17992. }
  17993. assert( pH->htsize>0 );
  17994. h = hraw % pH->htsize;
  17995. insertElement(pH, &pH->ht[h], new_elem);
  17996. new_elem->data = data;
  17997. return 0;
  17998. }
  17999. /************** End of hash.c ************************************************/
  18000. /************** Begin file opcodes.c *****************************************/
  18001. /* Automatically generated. Do not edit */
  18002. /* See the mkopcodec.awk script for details. */
  18003. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  18004. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  18005. static const char *const azName[] = { "?",
  18006. /* 1 */ "VNext",
  18007. /* 2 */ "Affinity",
  18008. /* 3 */ "Column",
  18009. /* 4 */ "SetCookie",
  18010. /* 5 */ "Seek",
  18011. /* 6 */ "Sequence",
  18012. /* 7 */ "Savepoint",
  18013. /* 8 */ "RowKey",
  18014. /* 9 */ "SCopy",
  18015. /* 10 */ "OpenWrite",
  18016. /* 11 */ "If",
  18017. /* 12 */ "VRowid",
  18018. /* 13 */ "CollSeq",
  18019. /* 14 */ "OpenRead",
  18020. /* 15 */ "Expire",
  18021. /* 16 */ "AutoCommit",
  18022. /* 17 */ "Pagecount",
  18023. /* 18 */ "IntegrityCk",
  18024. /* 19 */ "Not",
  18025. /* 20 */ "Sort",
  18026. /* 21 */ "Copy",
  18027. /* 22 */ "Trace",
  18028. /* 23 */ "Function",
  18029. /* 24 */ "IfNeg",
  18030. /* 25 */ "Noop",
  18031. /* 26 */ "Return",
  18032. /* 27 */ "NewRowid",
  18033. /* 28 */ "Variable",
  18034. /* 29 */ "String",
  18035. /* 30 */ "RealAffinity",
  18036. /* 31 */ "VRename",
  18037. /* 32 */ "ParseSchema",
  18038. /* 33 */ "VOpen",
  18039. /* 34 */ "Close",
  18040. /* 35 */ "CreateIndex",
  18041. /* 36 */ "IsUnique",
  18042. /* 37 */ "NotFound",
  18043. /* 38 */ "Int64",
  18044. /* 39 */ "MustBeInt",
  18045. /* 40 */ "Halt",
  18046. /* 41 */ "Rowid",
  18047. /* 42 */ "IdxLT",
  18048. /* 43 */ "AddImm",
  18049. /* 44 */ "Statement",
  18050. /* 45 */ "RowData",
  18051. /* 46 */ "MemMax",
  18052. /* 47 */ "NotExists",
  18053. /* 48 */ "Gosub",
  18054. /* 49 */ "Integer",
  18055. /* 50 */ "Prev",
  18056. /* 51 */ "RowSetRead",
  18057. /* 52 */ "RowSetAdd",
  18058. /* 53 */ "VColumn",
  18059. /* 54 */ "CreateTable",
  18060. /* 55 */ "Last",
  18061. /* 56 */ "SeekLe",
  18062. /* 57 */ "IncrVacuum",
  18063. /* 58 */ "IdxRowid",
  18064. /* 59 */ "ResetCount",
  18065. /* 60 */ "ContextPush",
  18066. /* 61 */ "Yield",
  18067. /* 62 */ "DropTrigger",
  18068. /* 63 */ "DropIndex",
  18069. /* 64 */ "IdxGE",
  18070. /* 65 */ "IdxDelete",
  18071. /* 66 */ "Or",
  18072. /* 67 */ "And",
  18073. /* 68 */ "Vacuum",
  18074. /* 69 */ "IfNot",
  18075. /* 70 */ "DropTable",
  18076. /* 71 */ "IsNull",
  18077. /* 72 */ "NotNull",
  18078. /* 73 */ "Ne",
  18079. /* 74 */ "Eq",
  18080. /* 75 */ "Gt",
  18081. /* 76 */ "Le",
  18082. /* 77 */ "Lt",
  18083. /* 78 */ "Ge",
  18084. /* 79 */ "SeekLt",
  18085. /* 80 */ "BitAnd",
  18086. /* 81 */ "BitOr",
  18087. /* 82 */ "ShiftLeft",
  18088. /* 83 */ "ShiftRight",
  18089. /* 84 */ "Add",
  18090. /* 85 */ "Subtract",
  18091. /* 86 */ "Multiply",
  18092. /* 87 */ "Divide",
  18093. /* 88 */ "Remainder",
  18094. /* 89 */ "Concat",
  18095. /* 90 */ "MakeRecord",
  18096. /* 91 */ "ResultRow",
  18097. /* 92 */ "Delete",
  18098. /* 93 */ "BitNot",
  18099. /* 94 */ "String8",
  18100. /* 95 */ "AggFinal",
  18101. /* 96 */ "Compare",
  18102. /* 97 */ "Goto",
  18103. /* 98 */ "TableLock",
  18104. /* 99 */ "Clear",
  18105. /* 100 */ "VerifyCookie",
  18106. /* 101 */ "AggStep",
  18107. /* 102 */ "SetNumColumns",
  18108. /* 103 */ "Transaction",
  18109. /* 104 */ "VFilter",
  18110. /* 105 */ "VDestroy",
  18111. /* 106 */ "ContextPop",
  18112. /* 107 */ "Next",
  18113. /* 108 */ "Count",
  18114. /* 109 */ "IdxInsert",
  18115. /* 110 */ "SeekGe",
  18116. /* 111 */ "Insert",
  18117. /* 112 */ "Destroy",
  18118. /* 113 */ "ReadCookie",
  18119. /* 114 */ "LoadAnalysis",
  18120. /* 115 */ "Explain",
  18121. /* 116 */ "HaltIfNull",
  18122. /* 117 */ "OpenPseudo",
  18123. /* 118 */ "OpenEphemeral",
  18124. /* 119 */ "Null",
  18125. /* 120 */ "Move",
  18126. /* 121 */ "Blob",
  18127. /* 122 */ "Rewind",
  18128. /* 123 */ "SeekGt",
  18129. /* 124 */ "VBegin",
  18130. /* 125 */ "VUpdate",
  18131. /* 126 */ "IfZero",
  18132. /* 127 */ "VCreate",
  18133. /* 128 */ "Found",
  18134. /* 129 */ "IfPos",
  18135. /* 130 */ "Real",
  18136. /* 131 */ "NullRow",
  18137. /* 132 */ "Jump",
  18138. /* 133 */ "Permutation",
  18139. /* 134 */ "NotUsed_134",
  18140. /* 135 */ "NotUsed_135",
  18141. /* 136 */ "NotUsed_136",
  18142. /* 137 */ "NotUsed_137",
  18143. /* 138 */ "NotUsed_138",
  18144. /* 139 */ "NotUsed_139",
  18145. /* 140 */ "NotUsed_140",
  18146. /* 141 */ "ToText",
  18147. /* 142 */ "ToBlob",
  18148. /* 143 */ "ToNumeric",
  18149. /* 144 */ "ToInt",
  18150. /* 145 */ "ToReal",
  18151. };
  18152. return azName[i];
  18153. }
  18154. #endif
  18155. /************** End of opcodes.c *********************************************/
  18156. /************** Begin file os_os2.c ******************************************/
  18157. /*
  18158. ** 2006 Feb 14
  18159. **
  18160. ** The author disclaims copyright to this source code. In place of
  18161. ** a legal notice, here is a blessing:
  18162. **
  18163. ** May you do good and not evil.
  18164. ** May you find forgiveness for yourself and forgive others.
  18165. ** May you share freely, never taking more than you give.
  18166. **
  18167. ******************************************************************************
  18168. **
  18169. ** This file contains code that is specific to OS/2.
  18170. **
  18171. ** $Id: os_os2.c,v 1.63 2008/12/10 19:26:24 drh Exp $
  18172. */
  18173. #if SQLITE_OS_OS2
  18174. /*
  18175. ** A Note About Memory Allocation:
  18176. **
  18177. ** This driver uses malloc()/free() directly rather than going through
  18178. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  18179. ** are designed for use on embedded systems where memory is scarce and
  18180. ** malloc failures happen frequently. OS/2 does not typically run on
  18181. ** embedded systems, and when it does the developers normally have bigger
  18182. ** problems to worry about than running out of memory. So there is not
  18183. ** a compelling need to use the wrappers.
  18184. **
  18185. ** But there is a good reason to not use the wrappers. If we use the
  18186. ** wrappers then we will get simulated malloc() failures within this
  18187. ** driver. And that causes all kinds of problems for our tests. We
  18188. ** could enhance SQLite to deal with simulated malloc failures within
  18189. ** the OS driver, but the code to deal with those failure would not
  18190. ** be exercised on Linux (which does not need to malloc() in the driver)
  18191. ** and so we would have difficulty writing coverage tests for that
  18192. ** code. Better to leave the code out, we think.
  18193. **
  18194. ** The point of this discussion is as follows: When creating a new
  18195. ** OS layer for an embedded system, if you use this file as an example,
  18196. ** avoid the use of malloc()/free(). Those routines work ok on OS/2
  18197. ** desktops but not so well in embedded systems.
  18198. */
  18199. /*
  18200. ** Macros used to determine whether or not to use threads.
  18201. */
  18202. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
  18203. # define SQLITE_OS2_THREADS 1
  18204. #endif
  18205. /*
  18206. ** Include code that is common to all os_*.c files
  18207. */
  18208. /************** Include os_common.h in the middle of os_os2.c ****************/
  18209. /************** Begin file os_common.h ***************************************/
  18210. /*
  18211. ** 2004 May 22
  18212. **
  18213. ** The author disclaims copyright to this source code. In place of
  18214. ** a legal notice, here is a blessing:
  18215. **
  18216. ** May you do good and not evil.
  18217. ** May you find forgiveness for yourself and forgive others.
  18218. ** May you share freely, never taking more than you give.
  18219. **
  18220. ******************************************************************************
  18221. **
  18222. ** This file contains macros and a little bit of code that is common to
  18223. ** all of the platform-specific files (os_*.c) and is #included into those
  18224. ** files.
  18225. **
  18226. ** This file should be #included by the os_*.c files only. It is not a
  18227. ** general purpose header file.
  18228. **
  18229. ** $Id: os_common.h,v 1.38 2009/02/24 18:40:50 danielk1977 Exp $
  18230. */
  18231. #ifndef _OS_COMMON_H_
  18232. #define _OS_COMMON_H_
  18233. /*
  18234. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  18235. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  18236. ** switch. The following code should catch this problem at compile-time.
  18237. */
  18238. #ifdef MEMORY_DEBUG
  18239. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  18240. #endif
  18241. #ifdef SQLITE_DEBUG
  18242. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  18243. #define OSTRACE1(X) if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
  18244. #define OSTRACE2(X,Y) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
  18245. #define OSTRACE3(X,Y,Z) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
  18246. #define OSTRACE4(X,Y,Z,A) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
  18247. #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
  18248. #define OSTRACE6(X,Y,Z,A,B,C) \
  18249. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
  18250. #define OSTRACE7(X,Y,Z,A,B,C,D) \
  18251. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
  18252. #else
  18253. #define OSTRACE1(X)
  18254. #define OSTRACE2(X,Y)
  18255. #define OSTRACE3(X,Y,Z)
  18256. #define OSTRACE4(X,Y,Z,A)
  18257. #define OSTRACE5(X,Y,Z,A,B)
  18258. #define OSTRACE6(X,Y,Z,A,B,C)
  18259. #define OSTRACE7(X,Y,Z,A,B,C,D)
  18260. #endif
  18261. /*
  18262. ** Macros for performance tracing. Normally turned off. Only works
  18263. ** on i486 hardware.
  18264. */
  18265. #ifdef SQLITE_PERFORMANCE_TRACE
  18266. /*
  18267. ** hwtime.h contains inline assembler code for implementing
  18268. ** high-performance timing routines.
  18269. */
  18270. /************** Include hwtime.h in the middle of os_common.h ****************/
  18271. /************** Begin file hwtime.h ******************************************/
  18272. /*
  18273. ** 2008 May 27
  18274. **
  18275. ** The author disclaims copyright to this source code. In place of
  18276. ** a legal notice, here is a blessing:
  18277. **
  18278. ** May you do good and not evil.
  18279. ** May you find forgiveness for yourself and forgive others.
  18280. ** May you share freely, never taking more than you give.
  18281. **
  18282. ******************************************************************************
  18283. **
  18284. ** This file contains inline asm code for retrieving "high-performance"
  18285. ** counters for x86 class CPUs.
  18286. **
  18287. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  18288. */
  18289. #ifndef _HWTIME_H_
  18290. #define _HWTIME_H_
  18291. /*
  18292. ** The following routine only works on pentium-class (or newer) processors.
  18293. ** It uses the RDTSC opcode to read the cycle count value out of the
  18294. ** processor and returns that value. This can be used for high-res
  18295. ** profiling.
  18296. */
  18297. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  18298. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  18299. #if defined(__GNUC__)
  18300. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18301. unsigned int lo, hi;
  18302. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  18303. return (sqlite_uint64)hi << 32 | lo;
  18304. }
  18305. #elif defined(_MSC_VER)
  18306. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  18307. __asm {
  18308. rdtsc
  18309. ret ; return value at EDX:EAX
  18310. }
  18311. }
  18312. #endif
  18313. #elif (defined(__GNUC__) && defined(__x86_64__))
  18314. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18315. unsigned long val;
  18316. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  18317. return val;
  18318. }
  18319. #elif (defined(__GNUC__) && defined(__ppc__))
  18320. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18321. unsigned long long retval;
  18322. unsigned long junk;
  18323. __asm__ __volatile__ ("\n\
  18324. 1: mftbu %1\n\
  18325. mftb %L0\n\
  18326. mftbu %0\n\
  18327. cmpw %0,%1\n\
  18328. bne 1b"
  18329. : "=r" (retval), "=r" (junk));
  18330. return retval;
  18331. }
  18332. #else
  18333. #error Need implementation of sqlite3Hwtime() for your platform.
  18334. /*
  18335. ** To compile without implementing sqlite3Hwtime() for your platform,
  18336. ** you can remove the above #error and use the following
  18337. ** stub function. You will lose timing support for many
  18338. ** of the debugging and testing utilities, but it should at
  18339. ** least compile and run.
  18340. */
  18341. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  18342. #endif
  18343. #endif /* !defined(_HWTIME_H_) */
  18344. /************** End of hwtime.h **********************************************/
  18345. /************** Continuing where we left off in os_common.h ******************/
  18346. static sqlite_uint64 g_start;
  18347. static sqlite_uint64 g_elapsed;
  18348. #define TIMER_START g_start=sqlite3Hwtime()
  18349. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  18350. #define TIMER_ELAPSED g_elapsed
  18351. #else
  18352. #define TIMER_START
  18353. #define TIMER_END
  18354. #define TIMER_ELAPSED ((sqlite_uint64)0)
  18355. #endif
  18356. /*
  18357. ** If we compile with the SQLITE_TEST macro set, then the following block
  18358. ** of code will give us the ability to simulate a disk I/O error. This
  18359. ** is used for testing the I/O recovery logic.
  18360. */
  18361. #ifdef SQLITE_TEST
  18362. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  18363. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  18364. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  18365. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  18366. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  18367. SQLITE_API int sqlite3_diskfull_pending = 0;
  18368. SQLITE_API int sqlite3_diskfull = 0;
  18369. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  18370. #define SimulateIOError(CODE) \
  18371. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  18372. || sqlite3_io_error_pending-- == 1 ) \
  18373. { local_ioerr(); CODE; }
  18374. static void local_ioerr(){
  18375. IOTRACE(("IOERR\n"));
  18376. sqlite3_io_error_hit++;
  18377. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  18378. }
  18379. #define SimulateDiskfullError(CODE) \
  18380. if( sqlite3_diskfull_pending ){ \
  18381. if( sqlite3_diskfull_pending == 1 ){ \
  18382. local_ioerr(); \
  18383. sqlite3_diskfull = 1; \
  18384. sqlite3_io_error_hit = 1; \
  18385. CODE; \
  18386. }else{ \
  18387. sqlite3_diskfull_pending--; \
  18388. } \
  18389. }
  18390. #else
  18391. #define SimulateIOErrorBenign(X)
  18392. #define SimulateIOError(A)
  18393. #define SimulateDiskfullError(A)
  18394. #endif
  18395. /*
  18396. ** When testing, keep a count of the number of open files.
  18397. */
  18398. #ifdef SQLITE_TEST
  18399. SQLITE_API int sqlite3_open_file_count = 0;
  18400. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  18401. #else
  18402. #define OpenCounter(X)
  18403. #endif
  18404. #endif /* !defined(_OS_COMMON_H_) */
  18405. /************** End of os_common.h *******************************************/
  18406. /************** Continuing where we left off in os_os2.c *********************/
  18407. /*
  18408. ** The os2File structure is subclass of sqlite3_file specific for the OS/2
  18409. ** protability layer.
  18410. */
  18411. typedef struct os2File os2File;
  18412. struct os2File {
  18413. const sqlite3_io_methods *pMethod; /* Always the first entry */
  18414. HFILE h; /* Handle for accessing the file */
  18415. char* pathToDel; /* Name of file to delete on close, NULL if not */
  18416. unsigned char locktype; /* Type of lock currently held on this file */
  18417. };
  18418. #define LOCK_TIMEOUT 10L /* the default locking timeout */
  18419. /*****************************************************************************
  18420. ** The next group of routines implement the I/O methods specified
  18421. ** by the sqlite3_io_methods object.
  18422. ******************************************************************************/
  18423. /*
  18424. ** Close a file.
  18425. */
  18426. static int os2Close( sqlite3_file *id ){
  18427. APIRET rc = NO_ERROR;
  18428. os2File *pFile;
  18429. if( id && (pFile = (os2File*)id) != 0 ){
  18430. OSTRACE2( "CLOSE %d\n", pFile->h );
  18431. rc = DosClose( pFile->h );
  18432. pFile->locktype = NO_LOCK;
  18433. if( pFile->pathToDel != NULL ){
  18434. rc = DosForceDelete( (PSZ)pFile->pathToDel );
  18435. free( pFile->pathToDel );
  18436. pFile->pathToDel = NULL;
  18437. }
  18438. id = 0;
  18439. OpenCounter( -1 );
  18440. }
  18441. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  18442. }
  18443. /*
  18444. ** Read data from a file into a buffer. Return SQLITE_OK if all
  18445. ** bytes were read successfully and SQLITE_IOERR if anything goes
  18446. ** wrong.
  18447. */
  18448. static int os2Read(
  18449. sqlite3_file *id, /* File to read from */
  18450. void *pBuf, /* Write content into this buffer */
  18451. int amt, /* Number of bytes to read */
  18452. sqlite3_int64 offset /* Begin reading at this offset */
  18453. ){
  18454. ULONG fileLocation = 0L;
  18455. ULONG got;
  18456. os2File *pFile = (os2File*)id;
  18457. assert( id!=0 );
  18458. SimulateIOError( return SQLITE_IOERR_READ );
  18459. OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
  18460. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  18461. return SQLITE_IOERR;
  18462. }
  18463. if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
  18464. return SQLITE_IOERR_READ;
  18465. }
  18466. if( got == (ULONG)amt )
  18467. return SQLITE_OK;
  18468. else {
  18469. /* Unread portions of the input buffer must be zero-filled */
  18470. memset(&((char*)pBuf)[got], 0, amt-got);
  18471. return SQLITE_IOERR_SHORT_READ;
  18472. }
  18473. }
  18474. /*
  18475. ** Write data from a buffer into a file. Return SQLITE_OK on success
  18476. ** or some other error code on failure.
  18477. */
  18478. static int os2Write(
  18479. sqlite3_file *id, /* File to write into */
  18480. const void *pBuf, /* The bytes to be written */
  18481. int amt, /* Number of bytes to write */
  18482. sqlite3_int64 offset /* Offset into the file to begin writing at */
  18483. ){
  18484. ULONG fileLocation = 0L;
  18485. APIRET rc = NO_ERROR;
  18486. ULONG wrote;
  18487. os2File *pFile = (os2File*)id;
  18488. assert( id!=0 );
  18489. SimulateIOError( return SQLITE_IOERR_WRITE );
  18490. SimulateDiskfullError( return SQLITE_FULL );
  18491. OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
  18492. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  18493. return SQLITE_IOERR;
  18494. }
  18495. assert( amt>0 );
  18496. while( amt > 0 &&
  18497. ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
  18498. wrote > 0
  18499. ){
  18500. amt -= wrote;
  18501. pBuf = &((char*)pBuf)[wrote];
  18502. }
  18503. return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
  18504. }
  18505. /*
  18506. ** Truncate an open file to a specified size
  18507. */
  18508. static int os2Truncate( sqlite3_file *id, i64 nByte ){
  18509. APIRET rc = NO_ERROR;
  18510. os2File *pFile = (os2File*)id;
  18511. OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
  18512. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  18513. rc = DosSetFileSize( pFile->h, nByte );
  18514. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
  18515. }
  18516. #ifdef SQLITE_TEST
  18517. /*
  18518. ** Count the number of fullsyncs and normal syncs. This is used to test
  18519. ** that syncs and fullsyncs are occuring at the right times.
  18520. */
  18521. SQLITE_API int sqlite3_sync_count = 0;
  18522. SQLITE_API int sqlite3_fullsync_count = 0;
  18523. #endif
  18524. /*
  18525. ** Make sure all writes to a particular file are committed to disk.
  18526. */
  18527. static int os2Sync( sqlite3_file *id, int flags ){
  18528. os2File *pFile = (os2File*)id;
  18529. OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
  18530. #ifdef SQLITE_TEST
  18531. if( flags & SQLITE_SYNC_FULL){
  18532. sqlite3_fullsync_count++;
  18533. }
  18534. sqlite3_sync_count++;
  18535. #endif
  18536. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  18537. ** no-op
  18538. */
  18539. #ifdef SQLITE_NO_SYNC
  18540. UNUSED_PARAMETER(pFile);
  18541. return SQLITE_OK;
  18542. #else
  18543. return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  18544. #endif
  18545. }
  18546. /*
  18547. ** Determine the current size of a file in bytes
  18548. */
  18549. static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
  18550. APIRET rc = NO_ERROR;
  18551. FILESTATUS3 fsts3FileInfo;
  18552. memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
  18553. assert( id!=0 );
  18554. SimulateIOError( return SQLITE_IOERR_FSTAT );
  18555. rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
  18556. if( rc == NO_ERROR ){
  18557. *pSize = fsts3FileInfo.cbFile;
  18558. return SQLITE_OK;
  18559. }else{
  18560. return SQLITE_IOERR_FSTAT;
  18561. }
  18562. }
  18563. /*
  18564. ** Acquire a reader lock.
  18565. */
  18566. static int getReadLock( os2File *pFile ){
  18567. FILELOCK LockArea,
  18568. UnlockArea;
  18569. APIRET res;
  18570. memset(&LockArea, 0, sizeof(LockArea));
  18571. memset(&UnlockArea, 0, sizeof(UnlockArea));
  18572. LockArea.lOffset = SHARED_FIRST;
  18573. LockArea.lRange = SHARED_SIZE;
  18574. UnlockArea.lOffset = 0L;
  18575. UnlockArea.lRange = 0L;
  18576. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  18577. OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
  18578. return res;
  18579. }
  18580. /*
  18581. ** Undo a readlock
  18582. */
  18583. static int unlockReadLock( os2File *id ){
  18584. FILELOCK LockArea,
  18585. UnlockArea;
  18586. APIRET res;
  18587. memset(&LockArea, 0, sizeof(LockArea));
  18588. memset(&UnlockArea, 0, sizeof(UnlockArea));
  18589. LockArea.lOffset = 0L;
  18590. LockArea.lRange = 0L;
  18591. UnlockArea.lOffset = SHARED_FIRST;
  18592. UnlockArea.lRange = SHARED_SIZE;
  18593. res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  18594. OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
  18595. return res;
  18596. }
  18597. /*
  18598. ** Lock the file with the lock specified by parameter locktype - one
  18599. ** of the following:
  18600. **
  18601. ** (1) SHARED_LOCK
  18602. ** (2) RESERVED_LOCK
  18603. ** (3) PENDING_LOCK
  18604. ** (4) EXCLUSIVE_LOCK
  18605. **
  18606. ** Sometimes when requesting one lock state, additional lock states
  18607. ** are inserted in between. The locking might fail on one of the later
  18608. ** transitions leaving the lock state different from what it started but
  18609. ** still short of its goal. The following chart shows the allowed
  18610. ** transitions and the inserted intermediate states:
  18611. **
  18612. ** UNLOCKED -> SHARED
  18613. ** SHARED -> RESERVED
  18614. ** SHARED -> (PENDING) -> EXCLUSIVE
  18615. ** RESERVED -> (PENDING) -> EXCLUSIVE
  18616. ** PENDING -> EXCLUSIVE
  18617. **
  18618. ** This routine will only increase a lock. The os2Unlock() routine
  18619. ** erases all locks at once and returns us immediately to locking level 0.
  18620. ** It is not possible to lower the locking level one step at a time. You
  18621. ** must go straight to locking level 0.
  18622. */
  18623. static int os2Lock( sqlite3_file *id, int locktype ){
  18624. int rc = SQLITE_OK; /* Return code from subroutines */
  18625. APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
  18626. int newLocktype; /* Set pFile->locktype to this value before exiting */
  18627. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  18628. FILELOCK LockArea,
  18629. UnlockArea;
  18630. os2File *pFile = (os2File*)id;
  18631. memset(&LockArea, 0, sizeof(LockArea));
  18632. memset(&UnlockArea, 0, sizeof(UnlockArea));
  18633. assert( pFile!=0 );
  18634. OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
  18635. /* If there is already a lock of this type or more restrictive on the
  18636. ** os2File, do nothing. Don't use the end_lock: exit path, as
  18637. ** sqlite3_mutex_enter() hasn't been called yet.
  18638. */
  18639. if( pFile->locktype>=locktype ){
  18640. OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
  18641. return SQLITE_OK;
  18642. }
  18643. /* Make sure the locking sequence is correct
  18644. */
  18645. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  18646. assert( locktype!=PENDING_LOCK );
  18647. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  18648. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  18649. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  18650. ** the PENDING_LOCK byte is temporary.
  18651. */
  18652. newLocktype = pFile->locktype;
  18653. if( pFile->locktype==NO_LOCK
  18654. || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  18655. ){
  18656. LockArea.lOffset = PENDING_BYTE;
  18657. LockArea.lRange = 1L;
  18658. UnlockArea.lOffset = 0L;
  18659. UnlockArea.lRange = 0L;
  18660. /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
  18661. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
  18662. if( res == NO_ERROR ){
  18663. gotPendingLock = 1;
  18664. OSTRACE3( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res );
  18665. }
  18666. }
  18667. /* Acquire a shared lock
  18668. */
  18669. if( locktype==SHARED_LOCK && res == NO_ERROR ){
  18670. assert( pFile->locktype==NO_LOCK );
  18671. res = getReadLock(pFile);
  18672. if( res == NO_ERROR ){
  18673. newLocktype = SHARED_LOCK;
  18674. }
  18675. OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
  18676. }
  18677. /* Acquire a RESERVED lock
  18678. */
  18679. if( locktype==RESERVED_LOCK && res == NO_ERROR ){
  18680. assert( pFile->locktype==SHARED_LOCK );
  18681. LockArea.lOffset = RESERVED_BYTE;
  18682. LockArea.lRange = 1L;
  18683. UnlockArea.lOffset = 0L;
  18684. UnlockArea.lRange = 0L;
  18685. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18686. if( res == NO_ERROR ){
  18687. newLocktype = RESERVED_LOCK;
  18688. }
  18689. OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
  18690. }
  18691. /* Acquire a PENDING lock
  18692. */
  18693. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  18694. newLocktype = PENDING_LOCK;
  18695. gotPendingLock = 0;
  18696. OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
  18697. }
  18698. /* Acquire an EXCLUSIVE lock
  18699. */
  18700. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  18701. assert( pFile->locktype>=SHARED_LOCK );
  18702. res = unlockReadLock(pFile);
  18703. OSTRACE2( "unreadlock = %d\n", res );
  18704. LockArea.lOffset = SHARED_FIRST;
  18705. LockArea.lRange = SHARED_SIZE;
  18706. UnlockArea.lOffset = 0L;
  18707. UnlockArea.lRange = 0L;
  18708. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18709. if( res == NO_ERROR ){
  18710. newLocktype = EXCLUSIVE_LOCK;
  18711. }else{
  18712. OSTRACE2( "OS/2 error-code = %d\n", res );
  18713. getReadLock(pFile);
  18714. }
  18715. OSTRACE3( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res );
  18716. }
  18717. /* If we are holding a PENDING lock that ought to be released, then
  18718. ** release it now.
  18719. */
  18720. if( gotPendingLock && locktype==SHARED_LOCK ){
  18721. int r;
  18722. LockArea.lOffset = 0L;
  18723. LockArea.lRange = 0L;
  18724. UnlockArea.lOffset = PENDING_BYTE;
  18725. UnlockArea.lRange = 1L;
  18726. r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18727. OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
  18728. }
  18729. /* Update the state of the lock has held in the file descriptor then
  18730. ** return the appropriate result code.
  18731. */
  18732. if( res == NO_ERROR ){
  18733. rc = SQLITE_OK;
  18734. }else{
  18735. OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  18736. locktype, newLocktype );
  18737. rc = SQLITE_BUSY;
  18738. }
  18739. pFile->locktype = newLocktype;
  18740. OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
  18741. return rc;
  18742. }
  18743. /*
  18744. ** This routine checks if there is a RESERVED lock held on the specified
  18745. ** file by this or any other process. If such a lock is held, return
  18746. ** non-zero, otherwise zero.
  18747. */
  18748. static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
  18749. int r = 0;
  18750. os2File *pFile = (os2File*)id;
  18751. assert( pFile!=0 );
  18752. if( pFile->locktype>=RESERVED_LOCK ){
  18753. r = 1;
  18754. OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
  18755. }else{
  18756. FILELOCK LockArea,
  18757. UnlockArea;
  18758. APIRET rc = NO_ERROR;
  18759. memset(&LockArea, 0, sizeof(LockArea));
  18760. memset(&UnlockArea, 0, sizeof(UnlockArea));
  18761. LockArea.lOffset = RESERVED_BYTE;
  18762. LockArea.lRange = 1L;
  18763. UnlockArea.lOffset = 0L;
  18764. UnlockArea.lRange = 0L;
  18765. rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18766. OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
  18767. if( rc == NO_ERROR ){
  18768. APIRET rcu = NO_ERROR; /* return code for unlocking */
  18769. LockArea.lOffset = 0L;
  18770. LockArea.lRange = 0L;
  18771. UnlockArea.lOffset = RESERVED_BYTE;
  18772. UnlockArea.lRange = 1L;
  18773. rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18774. OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
  18775. }
  18776. r = !(rc == NO_ERROR);
  18777. OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
  18778. }
  18779. *pOut = r;
  18780. return SQLITE_OK;
  18781. }
  18782. /*
  18783. ** Lower the locking level on file descriptor id to locktype. locktype
  18784. ** must be either NO_LOCK or SHARED_LOCK.
  18785. **
  18786. ** If the locking level of the file descriptor is already at or below
  18787. ** the requested locking level, this routine is a no-op.
  18788. **
  18789. ** It is not possible for this routine to fail if the second argument
  18790. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  18791. ** might return SQLITE_IOERR;
  18792. */
  18793. static int os2Unlock( sqlite3_file *id, int locktype ){
  18794. int type;
  18795. os2File *pFile = (os2File*)id;
  18796. APIRET rc = SQLITE_OK;
  18797. APIRET res = NO_ERROR;
  18798. FILELOCK LockArea,
  18799. UnlockArea;
  18800. memset(&LockArea, 0, sizeof(LockArea));
  18801. memset(&UnlockArea, 0, sizeof(UnlockArea));
  18802. assert( pFile!=0 );
  18803. assert( locktype<=SHARED_LOCK );
  18804. OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
  18805. type = pFile->locktype;
  18806. if( type>=EXCLUSIVE_LOCK ){
  18807. LockArea.lOffset = 0L;
  18808. LockArea.lRange = 0L;
  18809. UnlockArea.lOffset = SHARED_FIRST;
  18810. UnlockArea.lRange = SHARED_SIZE;
  18811. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18812. OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
  18813. if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
  18814. /* This should never happen. We should always be able to
  18815. ** reacquire the read lock */
  18816. OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
  18817. rc = SQLITE_IOERR_UNLOCK;
  18818. }
  18819. }
  18820. if( type>=RESERVED_LOCK ){
  18821. LockArea.lOffset = 0L;
  18822. LockArea.lRange = 0L;
  18823. UnlockArea.lOffset = RESERVED_BYTE;
  18824. UnlockArea.lRange = 1L;
  18825. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18826. OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
  18827. }
  18828. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  18829. res = unlockReadLock(pFile);
  18830. OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
  18831. }
  18832. if( type>=PENDING_LOCK ){
  18833. LockArea.lOffset = 0L;
  18834. LockArea.lRange = 0L;
  18835. UnlockArea.lOffset = PENDING_BYTE;
  18836. UnlockArea.lRange = 1L;
  18837. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  18838. OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
  18839. }
  18840. pFile->locktype = locktype;
  18841. OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
  18842. return rc;
  18843. }
  18844. /*
  18845. ** Control and query of the open file handle.
  18846. */
  18847. static int os2FileControl(sqlite3_file *id, int op, void *pArg){
  18848. switch( op ){
  18849. case SQLITE_FCNTL_LOCKSTATE: {
  18850. *(int*)pArg = ((os2File*)id)->locktype;
  18851. OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
  18852. return SQLITE_OK;
  18853. }
  18854. }
  18855. return SQLITE_ERROR;
  18856. }
  18857. /*
  18858. ** Return the sector size in bytes of the underlying block device for
  18859. ** the specified file. This is almost always 512 bytes, but may be
  18860. ** larger for some devices.
  18861. **
  18862. ** SQLite code assumes this function cannot fail. It also assumes that
  18863. ** if two files are created in the same file-system directory (i.e.
  18864. ** a database and its journal file) that the sector size will be the
  18865. ** same for both.
  18866. */
  18867. static int os2SectorSize(sqlite3_file *id){
  18868. return SQLITE_DEFAULT_SECTOR_SIZE;
  18869. }
  18870. /*
  18871. ** Return a vector of device characteristics.
  18872. */
  18873. static int os2DeviceCharacteristics(sqlite3_file *id){
  18874. return 0;
  18875. }
  18876. /*
  18877. ** Character set conversion objects used by conversion routines.
  18878. */
  18879. static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
  18880. static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
  18881. /*
  18882. ** Helper function to initialize the conversion objects from and to UTF-8.
  18883. */
  18884. static void initUconvObjects( void ){
  18885. if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
  18886. ucUtf8 = NULL;
  18887. if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
  18888. uclCp = NULL;
  18889. }
  18890. /*
  18891. ** Helper function to free the conversion objects from and to UTF-8.
  18892. */
  18893. static void freeUconvObjects( void ){
  18894. if ( ucUtf8 )
  18895. UniFreeUconvObject( ucUtf8 );
  18896. if ( uclCp )
  18897. UniFreeUconvObject( uclCp );
  18898. ucUtf8 = NULL;
  18899. uclCp = NULL;
  18900. }
  18901. /*
  18902. ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
  18903. ** The two-step process: first convert the incoming UTF-8 string
  18904. ** into UCS-2 and then from UCS-2 to the current codepage.
  18905. ** The returned char pointer has to be freed.
  18906. */
  18907. static char *convertUtf8PathToCp( const char *in ){
  18908. UniChar tempPath[CCHMAXPATH];
  18909. char *out = (char *)calloc( CCHMAXPATH, 1 );
  18910. if( !out )
  18911. return NULL;
  18912. if( !ucUtf8 || !uclCp )
  18913. initUconvObjects();
  18914. /* determine string for the conversion of UTF-8 which is CP1208 */
  18915. if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  18916. return out; /* if conversion fails, return the empty string */
  18917. /* conversion for current codepage which can be used for paths */
  18918. UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
  18919. return out;
  18920. }
  18921. /*
  18922. ** Helper function to convert filenames from local codepage to UTF-8.
  18923. ** The two-step process: first convert the incoming codepage-specific
  18924. ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
  18925. ** The returned char pointer has to be freed.
  18926. **
  18927. ** This function is non-static to be able to use this in shell.c and
  18928. ** similar applications that take command line arguments.
  18929. */
  18930. char *convertCpPathToUtf8( const char *in ){
  18931. UniChar tempPath[CCHMAXPATH];
  18932. char *out = (char *)calloc( CCHMAXPATH, 1 );
  18933. if( !out )
  18934. return NULL;
  18935. if( !ucUtf8 || !uclCp )
  18936. initUconvObjects();
  18937. /* conversion for current codepage which can be used for paths */
  18938. if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  18939. return out; /* if conversion fails, return the empty string */
  18940. /* determine string for the conversion of UTF-8 which is CP1208 */
  18941. UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
  18942. return out;
  18943. }
  18944. /*
  18945. ** This vector defines all the methods that can operate on an
  18946. ** sqlite3_file for os2.
  18947. */
  18948. static const sqlite3_io_methods os2IoMethod = {
  18949. 1, /* iVersion */
  18950. os2Close,
  18951. os2Read,
  18952. os2Write,
  18953. os2Truncate,
  18954. os2Sync,
  18955. os2FileSize,
  18956. os2Lock,
  18957. os2Unlock,
  18958. os2CheckReservedLock,
  18959. os2FileControl,
  18960. os2SectorSize,
  18961. os2DeviceCharacteristics
  18962. };
  18963. /***************************************************************************
  18964. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  18965. **
  18966. ** The next block of code implements the VFS methods.
  18967. ****************************************************************************/
  18968. /*
  18969. ** Create a temporary file name in zBuf. zBuf must be big enough to
  18970. ** hold at pVfs->mxPathname characters.
  18971. */
  18972. static int getTempname(int nBuf, char *zBuf ){
  18973. static const unsigned char zChars[] =
  18974. "abcdefghijklmnopqrstuvwxyz"
  18975. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  18976. "0123456789";
  18977. int i, j;
  18978. char zTempPathBuf[3];
  18979. PSZ zTempPath = (PSZ)&zTempPathBuf;
  18980. if( sqlite3_temp_directory ){
  18981. zTempPath = sqlite3_temp_directory;
  18982. }else{
  18983. if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
  18984. if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
  18985. if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
  18986. ULONG ulDriveNum = 0, ulDriveMap = 0;
  18987. DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
  18988. sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
  18989. }
  18990. }
  18991. }
  18992. }
  18993. /* Strip off a trailing slashes or backslashes, otherwise we would get *
  18994. * multiple (back)slashes which causes DosOpen() to fail. *
  18995. * Trailing spaces are not allowed, either. */
  18996. j = sqlite3Strlen30(zTempPath);
  18997. while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
  18998. || zTempPath[j-1] == ' ' ) ){
  18999. j--;
  19000. }
  19001. zTempPath[j] = '\0';
  19002. if( !sqlite3_temp_directory ){
  19003. char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
  19004. sqlite3_snprintf( nBuf-30, zBuf,
  19005. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
  19006. free( zTempPathUTF );
  19007. }else{
  19008. sqlite3_snprintf( nBuf-30, zBuf,
  19009. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
  19010. }
  19011. j = sqlite3Strlen30( zBuf );
  19012. sqlite3_randomness( 20, &zBuf[j] );
  19013. for( i = 0; i < 20; i++, j++ ){
  19014. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  19015. }
  19016. zBuf[j] = 0;
  19017. OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
  19018. return SQLITE_OK;
  19019. }
  19020. /*
  19021. ** Turn a relative pathname into a full pathname. Write the full
  19022. ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
  19023. ** bytes in size.
  19024. */
  19025. static int os2FullPathname(
  19026. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  19027. const char *zRelative, /* Possibly relative input path */
  19028. int nFull, /* Size of output buffer in bytes */
  19029. char *zFull /* Output buffer */
  19030. ){
  19031. char *zRelativeCp = convertUtf8PathToCp( zRelative );
  19032. char zFullCp[CCHMAXPATH] = "\0";
  19033. char *zFullUTF;
  19034. APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
  19035. CCHMAXPATH );
  19036. free( zRelativeCp );
  19037. zFullUTF = convertCpPathToUtf8( zFullCp );
  19038. sqlite3_snprintf( nFull, zFull, zFullUTF );
  19039. free( zFullUTF );
  19040. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  19041. }
  19042. /*
  19043. ** Open a file.
  19044. */
  19045. static int os2Open(
  19046. sqlite3_vfs *pVfs, /* Not used */
  19047. const char *zName, /* Name of the file */
  19048. sqlite3_file *id, /* Write the SQLite file handle here */
  19049. int flags, /* Open mode flags */
  19050. int *pOutFlags /* Status return flags */
  19051. ){
  19052. HFILE h;
  19053. ULONG ulFileAttribute = FILE_NORMAL;
  19054. ULONG ulOpenFlags = 0;
  19055. ULONG ulOpenMode = 0;
  19056. os2File *pFile = (os2File*)id;
  19057. APIRET rc = NO_ERROR;
  19058. ULONG ulAction;
  19059. char *zNameCp;
  19060. char zTmpname[CCHMAXPATH+1]; /* Buffer to hold name of temp file */
  19061. /* If the second argument to this function is NULL, generate a
  19062. ** temporary file name to use
  19063. */
  19064. if( !zName ){
  19065. int rc = getTempname(CCHMAXPATH+1, zTmpname);
  19066. if( rc!=SQLITE_OK ){
  19067. return rc;
  19068. }
  19069. zName = zTmpname;
  19070. }
  19071. memset( pFile, 0, sizeof(*pFile) );
  19072. OSTRACE2( "OPEN want %d\n", flags );
  19073. if( flags & SQLITE_OPEN_READWRITE ){
  19074. ulOpenMode |= OPEN_ACCESS_READWRITE;
  19075. OSTRACE1( "OPEN read/write\n" );
  19076. }else{
  19077. ulOpenMode |= OPEN_ACCESS_READONLY;
  19078. OSTRACE1( "OPEN read only\n" );
  19079. }
  19080. if( flags & SQLITE_OPEN_CREATE ){
  19081. ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
  19082. OSTRACE1( "OPEN open new/create\n" );
  19083. }else{
  19084. ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
  19085. OSTRACE1( "OPEN open existing\n" );
  19086. }
  19087. if( flags & SQLITE_OPEN_MAIN_DB ){
  19088. ulOpenMode |= OPEN_SHARE_DENYNONE;
  19089. OSTRACE1( "OPEN share read/write\n" );
  19090. }else{
  19091. ulOpenMode |= OPEN_SHARE_DENYWRITE;
  19092. OSTRACE1( "OPEN share read only\n" );
  19093. }
  19094. if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  19095. char pathUtf8[CCHMAXPATH];
  19096. #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
  19097. ulFileAttribute = FILE_HIDDEN;
  19098. #endif
  19099. os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
  19100. pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
  19101. OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
  19102. }else{
  19103. pFile->pathToDel = NULL;
  19104. OSTRACE1( "OPEN normal file attribute\n" );
  19105. }
  19106. /* always open in random access mode for possibly better speed */
  19107. ulOpenMode |= OPEN_FLAGS_RANDOM;
  19108. ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
  19109. ulOpenMode |= OPEN_FLAGS_NOINHERIT;
  19110. zNameCp = convertUtf8PathToCp( zName );
  19111. rc = DosOpen( (PSZ)zNameCp,
  19112. &h,
  19113. &ulAction,
  19114. 0L,
  19115. ulFileAttribute,
  19116. ulOpenFlags,
  19117. ulOpenMode,
  19118. (PEAOP2)NULL );
  19119. free( zNameCp );
  19120. if( rc != NO_ERROR ){
  19121. OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
  19122. rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
  19123. if( pFile->pathToDel )
  19124. free( pFile->pathToDel );
  19125. pFile->pathToDel = NULL;
  19126. if( flags & SQLITE_OPEN_READWRITE ){
  19127. OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
  19128. return os2Open( pVfs, zName, id,
  19129. ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
  19130. pOutFlags );
  19131. }else{
  19132. return SQLITE_CANTOPEN;
  19133. }
  19134. }
  19135. if( pOutFlags ){
  19136. *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
  19137. }
  19138. pFile->pMethod = &os2IoMethod;
  19139. pFile->h = h;
  19140. OpenCounter(+1);
  19141. OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
  19142. return SQLITE_OK;
  19143. }
  19144. /*
  19145. ** Delete the named file.
  19146. */
  19147. static int os2Delete(
  19148. sqlite3_vfs *pVfs, /* Not used on os2 */
  19149. const char *zFilename, /* Name of file to delete */
  19150. int syncDir /* Not used on os2 */
  19151. ){
  19152. APIRET rc = NO_ERROR;
  19153. char *zFilenameCp = convertUtf8PathToCp( zFilename );
  19154. SimulateIOError( return SQLITE_IOERR_DELETE );
  19155. rc = DosDelete( (PSZ)zFilenameCp );
  19156. free( zFilenameCp );
  19157. OSTRACE2( "DELETE \"%s\"\n", zFilename );
  19158. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
  19159. }
  19160. /*
  19161. ** Check the existance and status of a file.
  19162. */
  19163. static int os2Access(
  19164. sqlite3_vfs *pVfs, /* Not used on os2 */
  19165. const char *zFilename, /* Name of file to check */
  19166. int flags, /* Type of test to make on this file */
  19167. int *pOut /* Write results here */
  19168. ){
  19169. FILESTATUS3 fsts3ConfigInfo;
  19170. APIRET rc = NO_ERROR;
  19171. char *zFilenameCp = convertUtf8PathToCp( zFilename );
  19172. memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
  19173. rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
  19174. &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  19175. free( zFilenameCp );
  19176. OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
  19177. fsts3ConfigInfo.attrFile, flags, rc );
  19178. switch( flags ){
  19179. case SQLITE_ACCESS_READ:
  19180. case SQLITE_ACCESS_EXISTS:
  19181. rc = (rc == NO_ERROR);
  19182. OSTRACE3( "ACCESS %s access of read and exists rc=%d\n", zFilename, rc );
  19183. break;
  19184. case SQLITE_ACCESS_READWRITE:
  19185. rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
  19186. OSTRACE3( "ACCESS %s access of read/write rc=%d\n", zFilename, rc );
  19187. break;
  19188. default:
  19189. assert( !"Invalid flags argument" );
  19190. }
  19191. *pOut = rc;
  19192. return SQLITE_OK;
  19193. }
  19194. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  19195. /*
  19196. ** Interfaces for opening a shared library, finding entry points
  19197. ** within the shared library, and closing the shared library.
  19198. */
  19199. /*
  19200. ** Interfaces for opening a shared library, finding entry points
  19201. ** within the shared library, and closing the shared library.
  19202. */
  19203. static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  19204. UCHAR loadErr[256];
  19205. HMODULE hmod;
  19206. APIRET rc;
  19207. char *zFilenameCp = convertUtf8PathToCp(zFilename);
  19208. rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
  19209. free(zFilenameCp);
  19210. return rc != NO_ERROR ? 0 : (void*)hmod;
  19211. }
  19212. /*
  19213. ** A no-op since the error code is returned on the DosLoadModule call.
  19214. ** os2Dlopen returns zero if DosLoadModule is not successful.
  19215. */
  19216. static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  19217. /* no-op */
  19218. }
  19219. static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
  19220. PFN pfn;
  19221. APIRET rc;
  19222. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
  19223. if( rc != NO_ERROR ){
  19224. /* if the symbol itself was not found, search again for the same
  19225. * symbol with an extra underscore, that might be needed depending
  19226. * on the calling convention */
  19227. char _zSymbol[256] = "_";
  19228. strncat(_zSymbol, zSymbol, 255);
  19229. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
  19230. }
  19231. return rc != NO_ERROR ? 0 : (void*)pfn;
  19232. }
  19233. static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
  19234. DosFreeModule((HMODULE)pHandle);
  19235. }
  19236. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  19237. #define os2DlOpen 0
  19238. #define os2DlError 0
  19239. #define os2DlSym 0
  19240. #define os2DlClose 0
  19241. #endif
  19242. /*
  19243. ** Write up to nBuf bytes of randomness into zBuf.
  19244. */
  19245. static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
  19246. int n = 0;
  19247. #if defined(SQLITE_TEST)
  19248. n = nBuf;
  19249. memset(zBuf, 0, nBuf);
  19250. #else
  19251. int sizeofULong = sizeof(ULONG);
  19252. if( (int)sizeof(DATETIME) <= nBuf - n ){
  19253. DATETIME x;
  19254. DosGetDateTime(&x);
  19255. memcpy(&zBuf[n], &x, sizeof(x));
  19256. n += sizeof(x);
  19257. }
  19258. if( sizeofULong <= nBuf - n ){
  19259. PPIB ppib;
  19260. DosGetInfoBlocks(NULL, &ppib);
  19261. memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
  19262. n += sizeofULong;
  19263. }
  19264. if( sizeofULong <= nBuf - n ){
  19265. PTIB ptib;
  19266. DosGetInfoBlocks(&ptib, NULL);
  19267. memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
  19268. n += sizeofULong;
  19269. }
  19270. /* if we still haven't filled the buffer yet the following will */
  19271. /* grab everything once instead of making several calls for a single item */
  19272. if( sizeofULong <= nBuf - n ){
  19273. ULONG ulSysInfo[QSV_MAX];
  19274. DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
  19275. memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
  19276. n += sizeofULong;
  19277. if( sizeofULong <= nBuf - n ){
  19278. memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
  19279. n += sizeofULong;
  19280. }
  19281. if( sizeofULong <= nBuf - n ){
  19282. memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
  19283. n += sizeofULong;
  19284. }
  19285. if( sizeofULong <= nBuf - n ){
  19286. memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
  19287. n += sizeofULong;
  19288. }
  19289. if( sizeofULong <= nBuf - n ){
  19290. memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
  19291. n += sizeofULong;
  19292. }
  19293. }
  19294. #endif
  19295. return n;
  19296. }
  19297. /*
  19298. ** Sleep for a little while. Return the amount of time slept.
  19299. ** The argument is the number of microseconds we want to sleep.
  19300. ** The return value is the number of microseconds of sleep actually
  19301. ** requested from the underlying operating system, a number which
  19302. ** might be greater than or equal to the argument, but not less
  19303. ** than the argument.
  19304. */
  19305. static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
  19306. DosSleep( (microsec/1000) );
  19307. return microsec;
  19308. }
  19309. /*
  19310. ** The following variable, if set to a non-zero value, becomes the result
  19311. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  19312. */
  19313. #ifdef SQLITE_TEST
  19314. SQLITE_API int sqlite3_current_time = 0;
  19315. #endif
  19316. /*
  19317. ** Find the current time (in Universal Coordinated Time). Write the
  19318. ** current time and date as a Julian Day number into *prNow and
  19319. ** return 0. Return 1 if the time and date cannot be found.
  19320. */
  19321. int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
  19322. double now;
  19323. SHORT minute; /* needs to be able to cope with negative timezone offset */
  19324. USHORT second, hour,
  19325. day, month, year;
  19326. DATETIME dt;
  19327. DosGetDateTime( &dt );
  19328. second = (USHORT)dt.seconds;
  19329. minute = (SHORT)dt.minutes + dt.timezone;
  19330. hour = (USHORT)dt.hours;
  19331. day = (USHORT)dt.day;
  19332. month = (USHORT)dt.month;
  19333. year = (USHORT)dt.year;
  19334. /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
  19335. http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
  19336. /* Calculate the Julian days */
  19337. now = day - 32076 +
  19338. 1461*(year + 4800 + (month - 14)/12)/4 +
  19339. 367*(month - 2 - (month - 14)/12*12)/12 -
  19340. 3*((year + 4900 + (month - 14)/12)/100)/4;
  19341. /* Add the fractional hours, mins and seconds */
  19342. now += (hour + 12.0)/24.0;
  19343. now += minute/1440.0;
  19344. now += second/86400.0;
  19345. *prNow = now;
  19346. #ifdef SQLITE_TEST
  19347. if( sqlite3_current_time ){
  19348. *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  19349. }
  19350. #endif
  19351. return 0;
  19352. }
  19353. static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  19354. return 0;
  19355. }
  19356. /*
  19357. ** Initialize and deinitialize the operating system interface.
  19358. */
  19359. SQLITE_API int sqlite3_os_init(void){
  19360. static sqlite3_vfs os2Vfs = {
  19361. 1, /* iVersion */
  19362. sizeof(os2File), /* szOsFile */
  19363. CCHMAXPATH, /* mxPathname */
  19364. 0, /* pNext */
  19365. "os2", /* zName */
  19366. 0, /* pAppData */
  19367. os2Open, /* xOpen */
  19368. os2Delete, /* xDelete */
  19369. os2Access, /* xAccess */
  19370. os2FullPathname, /* xFullPathname */
  19371. os2DlOpen, /* xDlOpen */
  19372. os2DlError, /* xDlError */
  19373. os2DlSym, /* xDlSym */
  19374. os2DlClose, /* xDlClose */
  19375. os2Randomness, /* xRandomness */
  19376. os2Sleep, /* xSleep */
  19377. os2CurrentTime, /* xCurrentTime */
  19378. os2GetLastError /* xGetLastError */
  19379. };
  19380. sqlite3_vfs_register(&os2Vfs, 1);
  19381. initUconvObjects();
  19382. return SQLITE_OK;
  19383. }
  19384. SQLITE_API int sqlite3_os_end(void){
  19385. freeUconvObjects();
  19386. return SQLITE_OK;
  19387. }
  19388. #endif /* SQLITE_OS_OS2 */
  19389. /************** End of os_os2.c **********************************************/
  19390. /************** Begin file os_unix.c *****************************************/
  19391. /*
  19392. ** 2004 May 22
  19393. **
  19394. ** The author disclaims copyright to this source code. In place of
  19395. ** a legal notice, here is a blessing:
  19396. **
  19397. ** May you do good and not evil.
  19398. ** May you find forgiveness for yourself and forgive others.
  19399. ** May you share freely, never taking more than you give.
  19400. **
  19401. ******************************************************************************
  19402. **
  19403. ** This file contains the VFS implementation for unix-like operating systems
  19404. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  19405. **
  19406. ** There are actually several different VFS implementations in this file.
  19407. ** The differences are in the way that file locking is done. The default
  19408. ** implementation uses Posix Advisory Locks. Alternative implementations
  19409. ** use flock(), dot-files, various proprietary locking schemas, or simply
  19410. ** skip locking all together.
  19411. **
  19412. ** This source file is organized into divisions where the logic for various
  19413. ** subfunctions is contained within the appropriate division. PLEASE
  19414. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  19415. ** in the correct division and should be clearly labeled.
  19416. **
  19417. ** The layout of divisions is as follows:
  19418. **
  19419. ** * General-purpose declarations and utility functions.
  19420. ** * Unique file ID logic used by VxWorks.
  19421. ** * Various locking primitive implementations (all except proxy locking):
  19422. ** + for Posix Advisory Locks
  19423. ** + for no-op locks
  19424. ** + for dot-file locks
  19425. ** + for flock() locking
  19426. ** + for named semaphore locks (VxWorks only)
  19427. ** + for AFP filesystem locks (MacOSX only)
  19428. ** * sqlite3_file methods not associated with locking.
  19429. ** * Definitions of sqlite3_io_methods objects for all locking
  19430. ** methods plus "finder" functions for each locking method.
  19431. ** * sqlite3_vfs method implementations.
  19432. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  19433. ** * Definitions of sqlite3_vfs objects for all locking methods
  19434. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  19435. **
  19436. ** $Id: os_unix.c,v 1.250 2009/04/07 05:35:04 chw Exp $
  19437. */
  19438. #if SQLITE_OS_UNIX /* This file is used on unix only */
  19439. /*
  19440. ** There are various methods for file locking used for concurrency
  19441. ** control:
  19442. **
  19443. ** 1. POSIX locking (the default),
  19444. ** 2. No locking,
  19445. ** 3. Dot-file locking,
  19446. ** 4. flock() locking,
  19447. ** 5. AFP locking (OSX only),
  19448. ** 6. Named POSIX semaphores (VXWorks only),
  19449. ** 7. proxy locking. (OSX only)
  19450. **
  19451. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  19452. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  19453. ** selection of the appropriate locking style based on the filesystem
  19454. ** where the database is located.
  19455. */
  19456. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  19457. # if defined(__APPLE__)
  19458. # define SQLITE_ENABLE_LOCKING_STYLE 1
  19459. # else
  19460. # define SQLITE_ENABLE_LOCKING_STYLE 0
  19461. # endif
  19462. #endif
  19463. /*
  19464. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  19465. ** vxworks, or 0 otherwise.
  19466. */
  19467. #ifndef OS_VXWORKS
  19468. # if defined(__RTP__) || defined(_WRS_KERNEL)
  19469. # define OS_VXWORKS 1
  19470. # else
  19471. # define OS_VXWORKS 0
  19472. # endif
  19473. #endif
  19474. /*
  19475. ** These #defines should enable >2GB file support on Posix if the
  19476. ** underlying operating system supports it. If the OS lacks
  19477. ** large file support, these should be no-ops.
  19478. **
  19479. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  19480. ** on the compiler command line. This is necessary if you are compiling
  19481. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  19482. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  19483. ** without this option, LFS is enable. But LFS does not exist in the kernel
  19484. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  19485. ** portability you should omit LFS.
  19486. **
  19487. ** The previous paragraph was written in 2005. (This paragraph is written
  19488. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  19489. ** you should probably leave LFS enabled. But some embedded platforms might
  19490. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  19491. */
  19492. #ifndef SQLITE_DISABLE_LFS
  19493. # define _LARGE_FILE 1
  19494. # ifndef _FILE_OFFSET_BITS
  19495. # define _FILE_OFFSET_BITS 64
  19496. # endif
  19497. # define _LARGEFILE_SOURCE 1
  19498. #endif
  19499. /*
  19500. ** standard include files.
  19501. */
  19502. #include <sys/types.h>
  19503. #include <sys/stat.h>
  19504. #include <fcntl.h>
  19505. #include <unistd.h>
  19506. #include <sys/time.h>
  19507. #include <errno.h>
  19508. #if SQLITE_ENABLE_LOCKING_STYLE
  19509. # include <sys/ioctl.h>
  19510. # if OS_VXWORKS
  19511. # include <semaphore.h>
  19512. # include <limits.h>
  19513. # else
  19514. # include <sys/file.h>
  19515. # include <sys/param.h>
  19516. # include <sys/mount.h>
  19517. # endif
  19518. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  19519. /*
  19520. ** If we are to be thread-safe, include the pthreads header and define
  19521. ** the SQLITE_UNIX_THREADS macro.
  19522. */
  19523. #if SQLITE_THREADSAFE
  19524. # define SQLITE_UNIX_THREADS 1
  19525. #endif
  19526. /*
  19527. ** Default permissions when creating a new file
  19528. */
  19529. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  19530. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  19531. #endif
  19532. /*
  19533. ** Default permissions when creating auto proxy dir
  19534. */
  19535. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  19536. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  19537. #endif
  19538. /*
  19539. ** Maximum supported path-length.
  19540. */
  19541. #define MAX_PATHNAME 512
  19542. /*
  19543. ** Only set the lastErrno if the error code is a real error and not
  19544. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  19545. */
  19546. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  19547. /*
  19548. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  19549. ** VFS implementations.
  19550. */
  19551. typedef struct unixFile unixFile;
  19552. struct unixFile {
  19553. sqlite3_io_methods const *pMethod; /* Always the first entry */
  19554. struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
  19555. struct unixLockInfo *pLock; /* Info about locks on this inode */
  19556. int h; /* The file descriptor */
  19557. int dirfd; /* File descriptor for the directory */
  19558. unsigned char locktype; /* The type of lock held on this fd */
  19559. int lastErrno; /* The unix errno from the last I/O error */
  19560. void *lockingContext; /* Locking style specific state */
  19561. #if SQLITE_ENABLE_LOCKING_STYLE
  19562. int openFlags; /* The flags specified at open() */
  19563. #endif
  19564. #if SQLITE_THREADSAFE && defined(__linux__)
  19565. pthread_t tid; /* The thread that "owns" this unixFile */
  19566. #endif
  19567. #if OS_VXWORKS
  19568. int isDelete; /* Delete on close if true */
  19569. struct vxworksFileId *pId; /* Unique file ID */
  19570. #endif
  19571. #ifndef NDEBUG
  19572. /* The next group of variables are used to track whether or not the
  19573. ** transaction counter in bytes 24-27 of database files are updated
  19574. ** whenever any part of the database changes. An assertion fault will
  19575. ** occur if a file is updated without also updating the transaction
  19576. ** counter. This test is made to avoid new problems similar to the
  19577. ** one described by ticket #3584.
  19578. */
  19579. unsigned char transCntrChng; /* True if the transaction counter changed */
  19580. unsigned char dbUpdate; /* True if any part of database file changed */
  19581. unsigned char inNormalWrite; /* True if in a normal write operation */
  19582. /* If true, that means we are dealing with a database file that has
  19583. ** a range of locking bytes from PENDING_BYTE through PENDING_BYTE+511
  19584. ** which should never be read or written. Asserts() will verify this */
  19585. unsigned char isLockable; /* True if file might be locked */
  19586. #endif
  19587. #ifdef SQLITE_TEST
  19588. /* In test mode, increase the size of this structure a bit so that
  19589. ** it is larger than the struct CrashFile defined in test6.c.
  19590. */
  19591. char aPadding[32];
  19592. #endif
  19593. };
  19594. /*
  19595. ** Include code that is common to all os_*.c files
  19596. */
  19597. /************** Include os_common.h in the middle of os_unix.c ***************/
  19598. /************** Begin file os_common.h ***************************************/
  19599. /*
  19600. ** 2004 May 22
  19601. **
  19602. ** The author disclaims copyright to this source code. In place of
  19603. ** a legal notice, here is a blessing:
  19604. **
  19605. ** May you do good and not evil.
  19606. ** May you find forgiveness for yourself and forgive others.
  19607. ** May you share freely, never taking more than you give.
  19608. **
  19609. ******************************************************************************
  19610. **
  19611. ** This file contains macros and a little bit of code that is common to
  19612. ** all of the platform-specific files (os_*.c) and is #included into those
  19613. ** files.
  19614. **
  19615. ** This file should be #included by the os_*.c files only. It is not a
  19616. ** general purpose header file.
  19617. **
  19618. ** $Id: os_common.h,v 1.38 2009/02/24 18:40:50 danielk1977 Exp $
  19619. */
  19620. #ifndef _OS_COMMON_H_
  19621. #define _OS_COMMON_H_
  19622. /*
  19623. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  19624. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  19625. ** switch. The following code should catch this problem at compile-time.
  19626. */
  19627. #ifdef MEMORY_DEBUG
  19628. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  19629. #endif
  19630. #ifdef SQLITE_DEBUG
  19631. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  19632. #define OSTRACE1(X) if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
  19633. #define OSTRACE2(X,Y) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
  19634. #define OSTRACE3(X,Y,Z) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
  19635. #define OSTRACE4(X,Y,Z,A) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
  19636. #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
  19637. #define OSTRACE6(X,Y,Z,A,B,C) \
  19638. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
  19639. #define OSTRACE7(X,Y,Z,A,B,C,D) \
  19640. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
  19641. #else
  19642. #define OSTRACE1(X)
  19643. #define OSTRACE2(X,Y)
  19644. #define OSTRACE3(X,Y,Z)
  19645. #define OSTRACE4(X,Y,Z,A)
  19646. #define OSTRACE5(X,Y,Z,A,B)
  19647. #define OSTRACE6(X,Y,Z,A,B,C)
  19648. #define OSTRACE7(X,Y,Z,A,B,C,D)
  19649. #endif
  19650. /*
  19651. ** Macros for performance tracing. Normally turned off. Only works
  19652. ** on i486 hardware.
  19653. */
  19654. #ifdef SQLITE_PERFORMANCE_TRACE
  19655. /*
  19656. ** hwtime.h contains inline assembler code for implementing
  19657. ** high-performance timing routines.
  19658. */
  19659. /************** Include hwtime.h in the middle of os_common.h ****************/
  19660. /************** Begin file hwtime.h ******************************************/
  19661. /*
  19662. ** 2008 May 27
  19663. **
  19664. ** The author disclaims copyright to this source code. In place of
  19665. ** a legal notice, here is a blessing:
  19666. **
  19667. ** May you do good and not evil.
  19668. ** May you find forgiveness for yourself and forgive others.
  19669. ** May you share freely, never taking more than you give.
  19670. **
  19671. ******************************************************************************
  19672. **
  19673. ** This file contains inline asm code for retrieving "high-performance"
  19674. ** counters for x86 class CPUs.
  19675. **
  19676. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  19677. */
  19678. #ifndef _HWTIME_H_
  19679. #define _HWTIME_H_
  19680. /*
  19681. ** The following routine only works on pentium-class (or newer) processors.
  19682. ** It uses the RDTSC opcode to read the cycle count value out of the
  19683. ** processor and returns that value. This can be used for high-res
  19684. ** profiling.
  19685. */
  19686. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  19687. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  19688. #if defined(__GNUC__)
  19689. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19690. unsigned int lo, hi;
  19691. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  19692. return (sqlite_uint64)hi << 32 | lo;
  19693. }
  19694. #elif defined(_MSC_VER)
  19695. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  19696. __asm {
  19697. rdtsc
  19698. ret ; return value at EDX:EAX
  19699. }
  19700. }
  19701. #endif
  19702. #elif (defined(__GNUC__) && defined(__x86_64__))
  19703. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19704. unsigned long val;
  19705. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  19706. return val;
  19707. }
  19708. #elif (defined(__GNUC__) && defined(__ppc__))
  19709. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19710. unsigned long long retval;
  19711. unsigned long junk;
  19712. __asm__ __volatile__ ("\n\
  19713. 1: mftbu %1\n\
  19714. mftb %L0\n\
  19715. mftbu %0\n\
  19716. cmpw %0,%1\n\
  19717. bne 1b"
  19718. : "=r" (retval), "=r" (junk));
  19719. return retval;
  19720. }
  19721. #else
  19722. #error Need implementation of sqlite3Hwtime() for your platform.
  19723. /*
  19724. ** To compile without implementing sqlite3Hwtime() for your platform,
  19725. ** you can remove the above #error and use the following
  19726. ** stub function. You will lose timing support for many
  19727. ** of the debugging and testing utilities, but it should at
  19728. ** least compile and run.
  19729. */
  19730. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  19731. #endif
  19732. #endif /* !defined(_HWTIME_H_) */
  19733. /************** End of hwtime.h **********************************************/
  19734. /************** Continuing where we left off in os_common.h ******************/
  19735. static sqlite_uint64 g_start;
  19736. static sqlite_uint64 g_elapsed;
  19737. #define TIMER_START g_start=sqlite3Hwtime()
  19738. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  19739. #define TIMER_ELAPSED g_elapsed
  19740. #else
  19741. #define TIMER_START
  19742. #define TIMER_END
  19743. #define TIMER_ELAPSED ((sqlite_uint64)0)
  19744. #endif
  19745. /*
  19746. ** If we compile with the SQLITE_TEST macro set, then the following block
  19747. ** of code will give us the ability to simulate a disk I/O error. This
  19748. ** is used for testing the I/O recovery logic.
  19749. */
  19750. #ifdef SQLITE_TEST
  19751. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19752. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19753. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19754. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19755. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19756. SQLITE_API int sqlite3_diskfull_pending = 0;
  19757. SQLITE_API int sqlite3_diskfull = 0;
  19758. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  19759. #define SimulateIOError(CODE) \
  19760. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  19761. || sqlite3_io_error_pending-- == 1 ) \
  19762. { local_ioerr(); CODE; }
  19763. static void local_ioerr(){
  19764. IOTRACE(("IOERR\n"));
  19765. sqlite3_io_error_hit++;
  19766. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  19767. }
  19768. #define SimulateDiskfullError(CODE) \
  19769. if( sqlite3_diskfull_pending ){ \
  19770. if( sqlite3_diskfull_pending == 1 ){ \
  19771. local_ioerr(); \
  19772. sqlite3_diskfull = 1; \
  19773. sqlite3_io_error_hit = 1; \
  19774. CODE; \
  19775. }else{ \
  19776. sqlite3_diskfull_pending--; \
  19777. } \
  19778. }
  19779. #else
  19780. #define SimulateIOErrorBenign(X)
  19781. #define SimulateIOError(A)
  19782. #define SimulateDiskfullError(A)
  19783. #endif
  19784. /*
  19785. ** When testing, keep a count of the number of open files.
  19786. */
  19787. #ifdef SQLITE_TEST
  19788. SQLITE_API int sqlite3_open_file_count = 0;
  19789. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  19790. #else
  19791. #define OpenCounter(X)
  19792. #endif
  19793. #endif /* !defined(_OS_COMMON_H_) */
  19794. /************** End of os_common.h *******************************************/
  19795. /************** Continuing where we left off in os_unix.c ********************/
  19796. /*
  19797. ** Define various macros that are missing from some systems.
  19798. */
  19799. #ifndef O_LARGEFILE
  19800. # define O_LARGEFILE 0
  19801. #endif
  19802. #ifdef SQLITE_DISABLE_LFS
  19803. # undef O_LARGEFILE
  19804. # define O_LARGEFILE 0
  19805. #endif
  19806. #ifndef O_NOFOLLOW
  19807. # define O_NOFOLLOW 0
  19808. #endif
  19809. #ifndef O_BINARY
  19810. # define O_BINARY 0
  19811. #endif
  19812. /*
  19813. ** The DJGPP compiler environment looks mostly like Unix, but it
  19814. ** lacks the fcntl() system call. So redefine fcntl() to be something
  19815. ** that always succeeds. This means that locking does not occur under
  19816. ** DJGPP. But it is DOS - what did you expect?
  19817. */
  19818. #ifdef __DJGPP__
  19819. # define fcntl(A,B,C) 0
  19820. #endif
  19821. /*
  19822. ** The threadid macro resolves to the thread-id or to 0. Used for
  19823. ** testing and debugging only.
  19824. */
  19825. #if SQLITE_THREADSAFE
  19826. #define threadid pthread_self()
  19827. #else
  19828. #define threadid 0
  19829. #endif
  19830. /*
  19831. ** Helper functions to obtain and relinquish the global mutex.
  19832. */
  19833. static void unixEnterMutex(void){
  19834. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19835. }
  19836. static void unixLeaveMutex(void){
  19837. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19838. }
  19839. #ifdef SQLITE_DEBUG
  19840. /*
  19841. ** Helper function for printing out trace information from debugging
  19842. ** binaries. This returns the string represetation of the supplied
  19843. ** integer lock-type.
  19844. */
  19845. static const char *locktypeName(int locktype){
  19846. switch( locktype ){
  19847. case NO_LOCK: return "NONE";
  19848. case SHARED_LOCK: return "SHARED";
  19849. case RESERVED_LOCK: return "RESERVED";
  19850. case PENDING_LOCK: return "PENDING";
  19851. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  19852. }
  19853. return "ERROR";
  19854. }
  19855. #endif
  19856. #ifdef SQLITE_LOCK_TRACE
  19857. /*
  19858. ** Print out information about all locking operations.
  19859. **
  19860. ** This routine is used for troubleshooting locks on multithreaded
  19861. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  19862. ** command-line option on the compiler. This code is normally
  19863. ** turned off.
  19864. */
  19865. static int lockTrace(int fd, int op, struct flock *p){
  19866. char *zOpName, *zType;
  19867. int s;
  19868. int savedErrno;
  19869. if( op==F_GETLK ){
  19870. zOpName = "GETLK";
  19871. }else if( op==F_SETLK ){
  19872. zOpName = "SETLK";
  19873. }else{
  19874. s = fcntl(fd, op, p);
  19875. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  19876. return s;
  19877. }
  19878. if( p->l_type==F_RDLCK ){
  19879. zType = "RDLCK";
  19880. }else if( p->l_type==F_WRLCK ){
  19881. zType = "WRLCK";
  19882. }else if( p->l_type==F_UNLCK ){
  19883. zType = "UNLCK";
  19884. }else{
  19885. assert( 0 );
  19886. }
  19887. assert( p->l_whence==SEEK_SET );
  19888. s = fcntl(fd, op, p);
  19889. savedErrno = errno;
  19890. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  19891. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  19892. (int)p->l_pid, s);
  19893. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  19894. struct flock l2;
  19895. l2 = *p;
  19896. fcntl(fd, F_GETLK, &l2);
  19897. if( l2.l_type==F_RDLCK ){
  19898. zType = "RDLCK";
  19899. }else if( l2.l_type==F_WRLCK ){
  19900. zType = "WRLCK";
  19901. }else if( l2.l_type==F_UNLCK ){
  19902. zType = "UNLCK";
  19903. }else{
  19904. assert( 0 );
  19905. }
  19906. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  19907. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  19908. }
  19909. errno = savedErrno;
  19910. return s;
  19911. }
  19912. #define fcntl lockTrace
  19913. #endif /* SQLITE_LOCK_TRACE */
  19914. /*
  19915. ** This routine translates a standard POSIX errno code into something
  19916. ** useful to the clients of the sqlite3 functions. Specifically, it is
  19917. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  19918. ** and a variety of "please close the file descriptor NOW" errors into
  19919. ** SQLITE_IOERR
  19920. **
  19921. ** Errors during initialization of locks, or file system support for locks,
  19922. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  19923. */
  19924. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  19925. switch (posixError) {
  19926. case 0:
  19927. return SQLITE_OK;
  19928. case EAGAIN:
  19929. case ETIMEDOUT:
  19930. case EBUSY:
  19931. case EINTR:
  19932. case ENOLCK:
  19933. /* random NFS retry error, unless during file system support
  19934. * introspection, in which it actually means what it says */
  19935. return SQLITE_BUSY;
  19936. case EACCES:
  19937. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  19938. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  19939. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  19940. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  19941. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  19942. return SQLITE_BUSY;
  19943. }
  19944. /* else fall through */
  19945. case EPERM:
  19946. return SQLITE_PERM;
  19947. case EDEADLK:
  19948. return SQLITE_IOERR_BLOCKED;
  19949. #if EOPNOTSUPP!=ENOTSUP
  19950. case EOPNOTSUPP:
  19951. /* something went terribly awry, unless during file system support
  19952. * introspection, in which it actually means what it says */
  19953. #endif
  19954. #ifdef ENOTSUP
  19955. case ENOTSUP:
  19956. /* invalid fd, unless during file system support introspection, in which
  19957. * it actually means what it says */
  19958. #endif
  19959. case EIO:
  19960. case EBADF:
  19961. case EINVAL:
  19962. case ENOTCONN:
  19963. case ENODEV:
  19964. case ENXIO:
  19965. case ENOENT:
  19966. case ESTALE:
  19967. case ENOSYS:
  19968. /* these should force the client to close the file and reconnect */
  19969. default:
  19970. return sqliteIOErr;
  19971. }
  19972. }
  19973. /******************************************************************************
  19974. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  19975. **
  19976. ** On most versions of unix, we can get a unique ID for a file by concatenating
  19977. ** the device number and the inode number. But this does not work on VxWorks.
  19978. ** On VxWorks, a unique file id must be based on the canonical filename.
  19979. **
  19980. ** A pointer to an instance of the following structure can be used as a
  19981. ** unique file ID in VxWorks. Each instance of this structure contains
  19982. ** a copy of the canonical filename. There is also a reference count.
  19983. ** The structure is reclaimed when the number of pointers to it drops to
  19984. ** zero.
  19985. **
  19986. ** There are never very many files open at one time and lookups are not
  19987. ** a performance-critical path, so it is sufficient to put these
  19988. ** structures on a linked list.
  19989. */
  19990. struct vxworksFileId {
  19991. struct vxworksFileId *pNext; /* Next in a list of them all */
  19992. int nRef; /* Number of references to this one */
  19993. int nName; /* Length of the zCanonicalName[] string */
  19994. char *zCanonicalName; /* Canonical filename */
  19995. };
  19996. #if OS_VXWORKS
  19997. /*
  19998. ** All unique filenames are held on a linked list headed by this
  19999. ** variable:
  20000. */
  20001. static struct vxworksFileId *vxworksFileList = 0;
  20002. /*
  20003. ** Simplify a filename into its canonical form
  20004. ** by making the following changes:
  20005. **
  20006. ** * removing any trailing and duplicate /
  20007. ** * convert /./ into just /
  20008. ** * convert /A/../ where A is any simple name into just /
  20009. **
  20010. ** Changes are made in-place. Return the new name length.
  20011. **
  20012. ** The original filename is in z[0..n-1]. Return the number of
  20013. ** characters in the simplified name.
  20014. */
  20015. static int vxworksSimplifyName(char *z, int n){
  20016. int i, j;
  20017. while( n>1 && z[n-1]=='/' ){ n--; }
  20018. for(i=j=0; i<n; i++){
  20019. if( z[i]=='/' ){
  20020. if( z[i+1]=='/' ) continue;
  20021. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  20022. i += 1;
  20023. continue;
  20024. }
  20025. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  20026. while( j>0 && z[j-1]!='/' ){ j--; }
  20027. if( j>0 ){ j--; }
  20028. i += 2;
  20029. continue;
  20030. }
  20031. }
  20032. z[j++] = z[i];
  20033. }
  20034. z[j] = 0;
  20035. return j;
  20036. }
  20037. /*
  20038. ** Find a unique file ID for the given absolute pathname. Return
  20039. ** a pointer to the vxworksFileId object. This pointer is the unique
  20040. ** file ID.
  20041. **
  20042. ** The nRef field of the vxworksFileId object is incremented before
  20043. ** the object is returned. A new vxworksFileId object is created
  20044. ** and added to the global list if necessary.
  20045. **
  20046. ** If a memory allocation error occurs, return NULL.
  20047. */
  20048. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  20049. struct vxworksFileId *pNew; /* search key and new file ID */
  20050. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  20051. int n; /* Length of zAbsoluteName string */
  20052. assert( zAbsoluteName[0]=='/' );
  20053. n = (int)strlen(zAbsoluteName);
  20054. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  20055. if( pNew==0 ) return 0;
  20056. pNew->zCanonicalName = (char*)&pNew[1];
  20057. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  20058. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  20059. /* Search for an existing entry that matching the canonical name.
  20060. ** If found, increment the reference count and return a pointer to
  20061. ** the existing file ID.
  20062. */
  20063. unixEnterMutex();
  20064. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  20065. if( pCandidate->nName==n
  20066. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  20067. ){
  20068. sqlite3_free(pNew);
  20069. pCandidate->nRef++;
  20070. unixLeaveMutex();
  20071. return pCandidate;
  20072. }
  20073. }
  20074. /* No match was found. We will make a new file ID */
  20075. pNew->nRef = 1;
  20076. pNew->nName = n;
  20077. pNew->pNext = vxworksFileList;
  20078. vxworksFileList = pNew;
  20079. unixLeaveMutex();
  20080. return pNew;
  20081. }
  20082. /*
  20083. ** Decrement the reference count on a vxworksFileId object. Free
  20084. ** the object when the reference count reaches zero.
  20085. */
  20086. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  20087. unixEnterMutex();
  20088. assert( pId->nRef>0 );
  20089. pId->nRef--;
  20090. if( pId->nRef==0 ){
  20091. struct vxworksFileId **pp;
  20092. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  20093. assert( *pp==pId );
  20094. *pp = pId->pNext;
  20095. sqlite3_free(pId);
  20096. }
  20097. unixLeaveMutex();
  20098. }
  20099. #endif /* OS_VXWORKS */
  20100. /*************** End of Unique File ID Utility Used By VxWorks ****************
  20101. ******************************************************************************/
  20102. /******************************************************************************
  20103. *************************** Posix Advisory Locking ****************************
  20104. **
  20105. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  20106. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  20107. ** sets or clears a lock, that operation overrides any prior locks set
  20108. ** by the same process. It does not explicitly say so, but this implies
  20109. ** that it overrides locks set by the same process using a different
  20110. ** file descriptor. Consider this test case:
  20111. **
  20112. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  20113. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  20114. **
  20115. ** Suppose ./file1 and ./file2 are really the same file (because
  20116. ** one is a hard or symbolic link to the other) then if you set
  20117. ** an exclusive lock on fd1, then try to get an exclusive lock
  20118. ** on fd2, it works. I would have expected the second lock to
  20119. ** fail since there was already a lock on the file due to fd1.
  20120. ** But not so. Since both locks came from the same process, the
  20121. ** second overrides the first, even though they were on different
  20122. ** file descriptors opened on different file names.
  20123. **
  20124. ** This means that we cannot use POSIX locks to synchronize file access
  20125. ** among competing threads of the same process. POSIX locks will work fine
  20126. ** to synchronize access for threads in separate processes, but not
  20127. ** threads within the same process.
  20128. **
  20129. ** To work around the problem, SQLite has to manage file locks internally
  20130. ** on its own. Whenever a new database is opened, we have to find the
  20131. ** specific inode of the database file (the inode is determined by the
  20132. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  20133. ** and check for locks already existing on that inode. When locks are
  20134. ** created or removed, we have to look at our own internal record of the
  20135. ** locks to see if another thread has previously set a lock on that same
  20136. ** inode.
  20137. **
  20138. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  20139. ** For VxWorks, we have to use the alternative unique ID system based on
  20140. ** canonical filename and implemented in the previous division.)
  20141. **
  20142. ** The sqlite3_file structure for POSIX is no longer just an integer file
  20143. ** descriptor. It is now a structure that holds the integer file
  20144. ** descriptor and a pointer to a structure that describes the internal
  20145. ** locks on the corresponding inode. There is one locking structure
  20146. ** per inode, so if the same inode is opened twice, both unixFile structures
  20147. ** point to the same locking structure. The locking structure keeps
  20148. ** a reference count (so we will know when to delete it) and a "cnt"
  20149. ** field that tells us its internal lock status. cnt==0 means the
  20150. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  20151. ** cnt>0 means there are cnt shared locks on the file.
  20152. **
  20153. ** Any attempt to lock or unlock a file first checks the locking
  20154. ** structure. The fcntl() system call is only invoked to set a
  20155. ** POSIX lock if the internal lock structure transitions between
  20156. ** a locked and an unlocked state.
  20157. **
  20158. ** But wait: there are yet more problems with POSIX advisory locks.
  20159. **
  20160. ** If you close a file descriptor that points to a file that has locks,
  20161. ** all locks on that file that are owned by the current process are
  20162. ** released. To work around this problem, each unixFile structure contains
  20163. ** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
  20164. ** per open inode, which means that multiple unixFile can point to a single
  20165. ** unixOpenCnt. When an attempt is made to close an unixFile, if there are
  20166. ** other unixFile open on the same inode that are holding locks, the call
  20167. ** to close() the file descriptor is deferred until all of the locks clear.
  20168. ** The unixOpenCnt structure keeps a list of file descriptors that need to
  20169. ** be closed and that list is walked (and cleared) when the last lock
  20170. ** clears.
  20171. **
  20172. ** Yet another problem: LinuxThreads do not play well with posix locks.
  20173. **
  20174. ** Many older versions of linux use the LinuxThreads library which is
  20175. ** not posix compliant. Under LinuxThreads, a lock created by thread
  20176. ** A cannot be modified or overridden by a different thread B.
  20177. ** Only thread A can modify the lock. Locking behavior is correct
  20178. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  20179. ** on linux - with NPTL a lock created by thread A can override locks
  20180. ** in thread B. But there is no way to know at compile-time which
  20181. ** threading library is being used. So there is no way to know at
  20182. ** compile-time whether or not thread A can override locks on thread B.
  20183. ** We have to do a run-time check to discover the behavior of the
  20184. ** current process.
  20185. **
  20186. ** On systems where thread A is unable to modify locks created by
  20187. ** thread B, we have to keep track of which thread created each
  20188. ** lock. Hence there is an extra field in the key to the unixLockInfo
  20189. ** structure to record this information. And on those systems it
  20190. ** is illegal to begin a transaction in one thread and finish it
  20191. ** in another. For this latter restriction, there is no work-around.
  20192. ** It is a limitation of LinuxThreads.
  20193. */
  20194. /*
  20195. ** Set or check the unixFile.tid field. This field is set when an unixFile
  20196. ** is first opened. All subsequent uses of the unixFile verify that the
  20197. ** same thread is operating on the unixFile. Some operating systems do
  20198. ** not allow locks to be overridden by other threads and that restriction
  20199. ** means that sqlite3* database handles cannot be moved from one thread
  20200. ** to another while locks are held.
  20201. **
  20202. ** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
  20203. ** another as long as we are running on a system that supports threads
  20204. ** overriding each others locks (which is now the most common behavior)
  20205. ** or if no locks are held. But the unixFile.pLock field needs to be
  20206. ** recomputed because its key includes the thread-id. See the
  20207. ** transferOwnership() function below for additional information
  20208. */
  20209. #if SQLITE_THREADSAFE && defined(__linux__)
  20210. # define SET_THREADID(X) (X)->tid = pthread_self()
  20211. # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
  20212. !pthread_equal((X)->tid, pthread_self()))
  20213. #else
  20214. # define SET_THREADID(X)
  20215. # define CHECK_THREADID(X) 0
  20216. #endif
  20217. /*
  20218. ** An instance of the following structure serves as the key used
  20219. ** to locate a particular unixOpenCnt structure given its inode. This
  20220. ** is the same as the unixLockKey except that the thread ID is omitted.
  20221. */
  20222. struct unixFileId {
  20223. dev_t dev; /* Device number */
  20224. #if OS_VXWORKS
  20225. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  20226. #else
  20227. ino_t ino; /* Inode number */
  20228. #endif
  20229. };
  20230. /*
  20231. ** An instance of the following structure serves as the key used
  20232. ** to locate a particular unixLockInfo structure given its inode.
  20233. **
  20234. ** If threads cannot override each others locks (LinuxThreads), then we
  20235. ** set the unixLockKey.tid field to the thread ID. If threads can override
  20236. ** each others locks (Posix and NPTL) then tid is always set to zero.
  20237. ** tid is omitted if we compile without threading support or on an OS
  20238. ** other than linux.
  20239. */
  20240. struct unixLockKey {
  20241. struct unixFileId fid; /* Unique identifier for the file */
  20242. #if SQLITE_THREADSAFE && defined(__linux__)
  20243. pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
  20244. #endif
  20245. };
  20246. /*
  20247. ** An instance of the following structure is allocated for each open
  20248. ** inode. Or, on LinuxThreads, there is one of these structures for
  20249. ** each inode opened by each thread.
  20250. **
  20251. ** A single inode can have multiple file descriptors, so each unixFile
  20252. ** structure contains a pointer to an instance of this object and this
  20253. ** object keeps a count of the number of unixFile pointing to it.
  20254. */
  20255. struct unixLockInfo {
  20256. struct unixLockKey lockKey; /* The lookup key */
  20257. int cnt; /* Number of SHARED locks held */
  20258. int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  20259. int nRef; /* Number of pointers to this structure */
  20260. struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
  20261. struct unixLockInfo *pPrev; /* .... doubly linked */
  20262. };
  20263. /*
  20264. ** An instance of the following structure is allocated for each open
  20265. ** inode. This structure keeps track of the number of locks on that
  20266. ** inode. If a close is attempted against an inode that is holding
  20267. ** locks, the close is deferred until all locks clear by adding the
  20268. ** file descriptor to be closed to the pending list.
  20269. **
  20270. ** TODO: Consider changing this so that there is only a single file
  20271. ** descriptor for each open file, even when it is opened multiple times.
  20272. ** The close() system call would only occur when the last database
  20273. ** using the file closes.
  20274. */
  20275. struct unixOpenCnt {
  20276. struct unixFileId fileId; /* The lookup key */
  20277. int nRef; /* Number of pointers to this structure */
  20278. int nLock; /* Number of outstanding locks */
  20279. int nPending; /* Number of pending close() operations */
  20280. int *aPending; /* Malloced space holding fd's awaiting a close() */
  20281. #if OS_VXWORKS
  20282. sem_t *pSem; /* Named POSIX semaphore */
  20283. char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
  20284. #endif
  20285. struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
  20286. };
  20287. /*
  20288. ** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
  20289. ** tables. But the number of objects is rarely more than a dozen and
  20290. ** never exceeds a few thousand. And lookup is not on a critical
  20291. ** path so a simple linked list will suffice.
  20292. */
  20293. static struct unixLockInfo *lockList = 0;
  20294. static struct unixOpenCnt *openList = 0;
  20295. /*
  20296. ** This variable remembers whether or not threads can override each others
  20297. ** locks.
  20298. **
  20299. ** 0: No. Threads cannot override each others locks. (LinuxThreads)
  20300. ** 1: Yes. Threads can override each others locks. (Posix & NLPT)
  20301. ** -1: We don't know yet.
  20302. **
  20303. ** On some systems, we know at compile-time if threads can override each
  20304. ** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
  20305. ** will be set appropriately. On other systems, we have to check at
  20306. ** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
  20307. ** undefined.
  20308. **
  20309. ** This variable normally has file scope only. But during testing, we make
  20310. ** it a global so that the test code can change its value in order to verify
  20311. ** that the right stuff happens in either case.
  20312. */
  20313. #if SQLITE_THREADSAFE && defined(__linux__)
  20314. # ifndef SQLITE_THREAD_OVERRIDE_LOCK
  20315. # define SQLITE_THREAD_OVERRIDE_LOCK -1
  20316. # endif
  20317. # ifdef SQLITE_TEST
  20318. int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
  20319. # else
  20320. static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
  20321. # endif
  20322. #endif
  20323. /*
  20324. ** This structure holds information passed into individual test
  20325. ** threads by the testThreadLockingBehavior() routine.
  20326. */
  20327. struct threadTestData {
  20328. int fd; /* File to be locked */
  20329. struct flock lock; /* The locking operation */
  20330. int result; /* Result of the locking operation */
  20331. };
  20332. #if SQLITE_THREADSAFE && defined(__linux__)
  20333. /*
  20334. ** This function is used as the main routine for a thread launched by
  20335. ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
  20336. ** by the main thread in testThreadLockingBehavior() conflicts with a
  20337. ** hypothetical write-lock obtained by this thread on the same file.
  20338. **
  20339. ** The write-lock is not actually acquired, as this is not possible if
  20340. ** the file is open in read-only mode (see ticket #3472).
  20341. */
  20342. static void *threadLockingTest(void *pArg){
  20343. struct threadTestData *pData = (struct threadTestData*)pArg;
  20344. pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
  20345. return pArg;
  20346. }
  20347. #endif /* SQLITE_THREADSAFE && defined(__linux__) */
  20348. #if SQLITE_THREADSAFE && defined(__linux__)
  20349. /*
  20350. ** This procedure attempts to determine whether or not threads
  20351. ** can override each others locks then sets the
  20352. ** threadsOverrideEachOthersLocks variable appropriately.
  20353. */
  20354. static void testThreadLockingBehavior(int fd_orig){
  20355. int fd;
  20356. int rc;
  20357. struct threadTestData d;
  20358. struct flock l;
  20359. pthread_t t;
  20360. fd = dup(fd_orig);
  20361. if( fd<0 ) return;
  20362. memset(&l, 0, sizeof(l));
  20363. l.l_type = F_RDLCK;
  20364. l.l_len = 1;
  20365. l.l_start = 0;
  20366. l.l_whence = SEEK_SET;
  20367. rc = fcntl(fd_orig, F_SETLK, &l);
  20368. if( rc!=0 ) return;
  20369. memset(&d, 0, sizeof(d));
  20370. d.fd = fd;
  20371. d.lock = l;
  20372. d.lock.l_type = F_WRLCK;
  20373. pthread_create(&t, 0, threadLockingTest, &d);
  20374. pthread_join(t, 0);
  20375. close(fd);
  20376. if( d.result!=0 ) return;
  20377. threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
  20378. }
  20379. #endif /* SQLITE_THERADSAFE && defined(__linux__) */
  20380. /*
  20381. ** Release a unixLockInfo structure previously allocated by findLockInfo().
  20382. */
  20383. static void releaseLockInfo(struct unixLockInfo *pLock){
  20384. if( pLock ){
  20385. pLock->nRef--;
  20386. if( pLock->nRef==0 ){
  20387. if( pLock->pPrev ){
  20388. assert( pLock->pPrev->pNext==pLock );
  20389. pLock->pPrev->pNext = pLock->pNext;
  20390. }else{
  20391. assert( lockList==pLock );
  20392. lockList = pLock->pNext;
  20393. }
  20394. if( pLock->pNext ){
  20395. assert( pLock->pNext->pPrev==pLock );
  20396. pLock->pNext->pPrev = pLock->pPrev;
  20397. }
  20398. sqlite3_free(pLock);
  20399. }
  20400. }
  20401. }
  20402. /*
  20403. ** Release a unixOpenCnt structure previously allocated by findLockInfo().
  20404. */
  20405. static void releaseOpenCnt(struct unixOpenCnt *pOpen){
  20406. if( pOpen ){
  20407. pOpen->nRef--;
  20408. if( pOpen->nRef==0 ){
  20409. if( pOpen->pPrev ){
  20410. assert( pOpen->pPrev->pNext==pOpen );
  20411. pOpen->pPrev->pNext = pOpen->pNext;
  20412. }else{
  20413. assert( openList==pOpen );
  20414. openList = pOpen->pNext;
  20415. }
  20416. if( pOpen->pNext ){
  20417. assert( pOpen->pNext->pPrev==pOpen );
  20418. pOpen->pNext->pPrev = pOpen->pPrev;
  20419. }
  20420. sqlite3_free(pOpen->aPending);
  20421. sqlite3_free(pOpen);
  20422. }
  20423. }
  20424. }
  20425. /*
  20426. ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
  20427. ** describes that file descriptor. Create new ones if necessary. The
  20428. ** return values might be uninitialized if an error occurs.
  20429. **
  20430. ** Return an appropriate error code.
  20431. */
  20432. static int findLockInfo(
  20433. unixFile *pFile, /* Unix file with file desc used in the key */
  20434. struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
  20435. struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
  20436. ){
  20437. int rc; /* System call return code */
  20438. int fd; /* The file descriptor for pFile */
  20439. struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
  20440. struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
  20441. struct stat statbuf; /* Low-level file information */
  20442. struct unixLockInfo *pLock; /* Candidate unixLockInfo object */
  20443. struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
  20444. /* Get low-level information about the file that we can used to
  20445. ** create a unique name for the file.
  20446. */
  20447. fd = pFile->h;
  20448. rc = fstat(fd, &statbuf);
  20449. if( rc!=0 ){
  20450. pFile->lastErrno = errno;
  20451. #ifdef EOVERFLOW
  20452. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  20453. #endif
  20454. return SQLITE_IOERR;
  20455. }
  20456. #ifdef __APPLE__
  20457. /* On OS X on an msdos filesystem, the inode number is reported
  20458. ** incorrectly for zero-size files. See ticket #3260. To work
  20459. ** around this problem (we consider it a bug in OS X, not SQLite)
  20460. ** we always increase the file size to 1 by writing a single byte
  20461. ** prior to accessing the inode number. The one byte written is
  20462. ** an ASCII 'S' character which also happens to be the first byte
  20463. ** in the header of every SQLite database. In this way, if there
  20464. ** is a race condition such that another thread has already populated
  20465. ** the first page of the database, no damage is done.
  20466. */
  20467. if( statbuf.st_size==0 ){
  20468. rc = write(fd, "S", 1);
  20469. if( rc!=1 ){
  20470. return SQLITE_IOERR;
  20471. }
  20472. rc = fstat(fd, &statbuf);
  20473. if( rc!=0 ){
  20474. pFile->lastErrno = errno;
  20475. return SQLITE_IOERR;
  20476. }
  20477. }
  20478. #endif
  20479. memset(&lockKey, 0, sizeof(lockKey));
  20480. lockKey.fid.dev = statbuf.st_dev;
  20481. #if OS_VXWORKS
  20482. lockKey.fid.pId = pFile->pId;
  20483. #else
  20484. lockKey.fid.ino = statbuf.st_ino;
  20485. #endif
  20486. #if SQLITE_THREADSAFE && defined(__linux__)
  20487. if( threadsOverrideEachOthersLocks<0 ){
  20488. testThreadLockingBehavior(fd);
  20489. }
  20490. lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
  20491. #endif
  20492. fileId = lockKey.fid;
  20493. if( ppLock!=0 ){
  20494. pLock = lockList;
  20495. while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
  20496. pLock = pLock->pNext;
  20497. }
  20498. if( pLock==0 ){
  20499. pLock = sqlite3_malloc( sizeof(*pLock) );
  20500. if( pLock==0 ){
  20501. rc = SQLITE_NOMEM;
  20502. goto exit_findlockinfo;
  20503. }
  20504. pLock->lockKey = lockKey;
  20505. pLock->nRef = 1;
  20506. pLock->cnt = 0;
  20507. pLock->locktype = 0;
  20508. pLock->pNext = lockList;
  20509. pLock->pPrev = 0;
  20510. if( lockList ) lockList->pPrev = pLock;
  20511. lockList = pLock;
  20512. }else{
  20513. pLock->nRef++;
  20514. }
  20515. *ppLock = pLock;
  20516. }
  20517. if( ppOpen!=0 ){
  20518. pOpen = openList;
  20519. while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
  20520. pOpen = pOpen->pNext;
  20521. }
  20522. if( pOpen==0 ){
  20523. pOpen = sqlite3_malloc( sizeof(*pOpen) );
  20524. if( pOpen==0 ){
  20525. releaseLockInfo(pLock);
  20526. rc = SQLITE_NOMEM;
  20527. goto exit_findlockinfo;
  20528. }
  20529. pOpen->fileId = fileId;
  20530. pOpen->nRef = 1;
  20531. pOpen->nLock = 0;
  20532. pOpen->nPending = 0;
  20533. pOpen->aPending = 0;
  20534. pOpen->pNext = openList;
  20535. pOpen->pPrev = 0;
  20536. if( openList ) openList->pPrev = pOpen;
  20537. openList = pOpen;
  20538. #if OS_VXWORKS
  20539. pOpen->pSem = NULL;
  20540. pOpen->aSemName[0] = '\0';
  20541. #endif
  20542. }else{
  20543. pOpen->nRef++;
  20544. }
  20545. *ppOpen = pOpen;
  20546. }
  20547. exit_findlockinfo:
  20548. return rc;
  20549. }
  20550. /*
  20551. ** If we are currently in a different thread than the thread that the
  20552. ** unixFile argument belongs to, then transfer ownership of the unixFile
  20553. ** over to the current thread.
  20554. **
  20555. ** A unixFile is only owned by a thread on systems that use LinuxThreads.
  20556. **
  20557. ** Ownership transfer is only allowed if the unixFile is currently unlocked.
  20558. ** If the unixFile is locked and an ownership is wrong, then return
  20559. ** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
  20560. */
  20561. #if SQLITE_THREADSAFE && defined(__linux__)
  20562. static int transferOwnership(unixFile *pFile){
  20563. int rc;
  20564. pthread_t hSelf;
  20565. if( threadsOverrideEachOthersLocks ){
  20566. /* Ownership transfers not needed on this system */
  20567. return SQLITE_OK;
  20568. }
  20569. hSelf = pthread_self();
  20570. if( pthread_equal(pFile->tid, hSelf) ){
  20571. /* We are still in the same thread */
  20572. OSTRACE1("No-transfer, same thread\n");
  20573. return SQLITE_OK;
  20574. }
  20575. if( pFile->locktype!=NO_LOCK ){
  20576. /* We cannot change ownership while we are holding a lock! */
  20577. return SQLITE_MISUSE;
  20578. }
  20579. OSTRACE4("Transfer ownership of %d from %d to %d\n",
  20580. pFile->h, pFile->tid, hSelf);
  20581. pFile->tid = hSelf;
  20582. if (pFile->pLock != NULL) {
  20583. releaseLockInfo(pFile->pLock);
  20584. rc = findLockInfo(pFile, &pFile->pLock, 0);
  20585. OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
  20586. locktypeName(pFile->locktype),
  20587. locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
  20588. return rc;
  20589. } else {
  20590. return SQLITE_OK;
  20591. }
  20592. }
  20593. #else /* if not SQLITE_THREADSAFE */
  20594. /* On single-threaded builds, ownership transfer is a no-op */
  20595. # define transferOwnership(X) SQLITE_OK
  20596. #endif /* SQLITE_THREADSAFE */
  20597. /*
  20598. ** This routine checks if there is a RESERVED lock held on the specified
  20599. ** file by this or any other process. If such a lock is held, set *pResOut
  20600. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  20601. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  20602. */
  20603. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  20604. int rc = SQLITE_OK;
  20605. int reserved = 0;
  20606. unixFile *pFile = (unixFile*)id;
  20607. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  20608. assert( pFile );
  20609. unixEnterMutex(); /* Because pFile->pLock is shared across threads */
  20610. /* Check if a thread in this process holds such a lock */
  20611. if( pFile->pLock->locktype>SHARED_LOCK ){
  20612. reserved = 1;
  20613. }
  20614. /* Otherwise see if some other process holds it.
  20615. */
  20616. #ifndef __DJGPP__
  20617. if( !reserved ){
  20618. struct flock lock;
  20619. lock.l_whence = SEEK_SET;
  20620. lock.l_start = RESERVED_BYTE;
  20621. lock.l_len = 1;
  20622. lock.l_type = F_WRLCK;
  20623. if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
  20624. int tErrno = errno;
  20625. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  20626. pFile->lastErrno = tErrno;
  20627. } else if( lock.l_type!=F_UNLCK ){
  20628. reserved = 1;
  20629. }
  20630. }
  20631. #endif
  20632. unixLeaveMutex();
  20633. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  20634. *pResOut = reserved;
  20635. return rc;
  20636. }
  20637. /*
  20638. ** Lock the file with the lock specified by parameter locktype - one
  20639. ** of the following:
  20640. **
  20641. ** (1) SHARED_LOCK
  20642. ** (2) RESERVED_LOCK
  20643. ** (3) PENDING_LOCK
  20644. ** (4) EXCLUSIVE_LOCK
  20645. **
  20646. ** Sometimes when requesting one lock state, additional lock states
  20647. ** are inserted in between. The locking might fail on one of the later
  20648. ** transitions leaving the lock state different from what it started but
  20649. ** still short of its goal. The following chart shows the allowed
  20650. ** transitions and the inserted intermediate states:
  20651. **
  20652. ** UNLOCKED -> SHARED
  20653. ** SHARED -> RESERVED
  20654. ** SHARED -> (PENDING) -> EXCLUSIVE
  20655. ** RESERVED -> (PENDING) -> EXCLUSIVE
  20656. ** PENDING -> EXCLUSIVE
  20657. **
  20658. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  20659. ** routine to lower a locking level.
  20660. */
  20661. static int unixLock(sqlite3_file *id, int locktype){
  20662. /* The following describes the implementation of the various locks and
  20663. ** lock transitions in terms of the POSIX advisory shared and exclusive
  20664. ** lock primitives (called read-locks and write-locks below, to avoid
  20665. ** confusion with SQLite lock names). The algorithms are complicated
  20666. ** slightly in order to be compatible with windows systems simultaneously
  20667. ** accessing the same database file, in case that is ever required.
  20668. **
  20669. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  20670. ** byte', each single bytes at well known offsets, and the 'shared byte
  20671. ** range', a range of 510 bytes at a well known offset.
  20672. **
  20673. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  20674. ** byte'. If this is successful, a random byte from the 'shared byte
  20675. ** range' is read-locked and the lock on the 'pending byte' released.
  20676. **
  20677. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  20678. ** A RESERVED lock is implemented by grabbing a write-lock on the
  20679. ** 'reserved byte'.
  20680. **
  20681. ** A process may only obtain a PENDING lock after it has obtained a
  20682. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  20683. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  20684. ** obtained, but existing SHARED locks are allowed to persist. A process
  20685. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  20686. ** This property is used by the algorithm for rolling back a journal file
  20687. ** after a crash.
  20688. **
  20689. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  20690. ** implemented by obtaining a write-lock on the entire 'shared byte
  20691. ** range'. Since all other locks require a read-lock on one of the bytes
  20692. ** within this range, this ensures that no other locks are held on the
  20693. ** database.
  20694. **
  20695. ** The reason a single byte cannot be used instead of the 'shared byte
  20696. ** range' is that some versions of windows do not support read-locks. By
  20697. ** locking a random byte from a range, concurrent SHARED locks may exist
  20698. ** even if the locking primitive used is always a write-lock.
  20699. */
  20700. int rc = SQLITE_OK;
  20701. unixFile *pFile = (unixFile*)id;
  20702. struct unixLockInfo *pLock = pFile->pLock;
  20703. struct flock lock;
  20704. int s;
  20705. assert( pFile );
  20706. OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
  20707. locktypeName(locktype), locktypeName(pFile->locktype),
  20708. locktypeName(pLock->locktype), pLock->cnt , getpid());
  20709. /* If there is already a lock of this type or more restrictive on the
  20710. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  20711. ** unixEnterMutex() hasn't been called yet.
  20712. */
  20713. if( pFile->locktype>=locktype ){
  20714. OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
  20715. locktypeName(locktype));
  20716. return SQLITE_OK;
  20717. }
  20718. /* Make sure the locking sequence is correct
  20719. */
  20720. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  20721. assert( locktype!=PENDING_LOCK );
  20722. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  20723. /* This mutex is needed because pFile->pLock is shared across threads
  20724. */
  20725. unixEnterMutex();
  20726. /* Make sure the current thread owns the pFile.
  20727. */
  20728. rc = transferOwnership(pFile);
  20729. if( rc!=SQLITE_OK ){
  20730. unixLeaveMutex();
  20731. return rc;
  20732. }
  20733. pLock = pFile->pLock;
  20734. /* If some thread using this PID has a lock via a different unixFile*
  20735. ** handle that precludes the requested lock, return BUSY.
  20736. */
  20737. if( (pFile->locktype!=pLock->locktype &&
  20738. (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
  20739. ){
  20740. rc = SQLITE_BUSY;
  20741. goto end_lock;
  20742. }
  20743. /* If a SHARED lock is requested, and some thread using this PID already
  20744. ** has a SHARED or RESERVED lock, then increment reference counts and
  20745. ** return SQLITE_OK.
  20746. */
  20747. if( locktype==SHARED_LOCK &&
  20748. (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
  20749. assert( locktype==SHARED_LOCK );
  20750. assert( pFile->locktype==0 );
  20751. assert( pLock->cnt>0 );
  20752. pFile->locktype = SHARED_LOCK;
  20753. pLock->cnt++;
  20754. pFile->pOpen->nLock++;
  20755. goto end_lock;
  20756. }
  20757. lock.l_len = 1L;
  20758. lock.l_whence = SEEK_SET;
  20759. /* A PENDING lock is needed before acquiring a SHARED lock and before
  20760. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  20761. ** be released.
  20762. */
  20763. if( locktype==SHARED_LOCK
  20764. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  20765. ){
  20766. lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
  20767. lock.l_start = PENDING_BYTE;
  20768. s = fcntl(pFile->h, F_SETLK, &lock);
  20769. if( s==(-1) ){
  20770. int tErrno = errno;
  20771. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  20772. if( IS_LOCK_ERROR(rc) ){
  20773. pFile->lastErrno = tErrno;
  20774. }
  20775. goto end_lock;
  20776. }
  20777. }
  20778. /* If control gets to this point, then actually go ahead and make
  20779. ** operating system calls for the specified lock.
  20780. */
  20781. if( locktype==SHARED_LOCK ){
  20782. int tErrno = 0;
  20783. assert( pLock->cnt==0 );
  20784. assert( pLock->locktype==0 );
  20785. /* Now get the read-lock */
  20786. lock.l_start = SHARED_FIRST;
  20787. lock.l_len = SHARED_SIZE;
  20788. if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
  20789. tErrno = errno;
  20790. }
  20791. /* Drop the temporary PENDING lock */
  20792. lock.l_start = PENDING_BYTE;
  20793. lock.l_len = 1L;
  20794. lock.l_type = F_UNLCK;
  20795. if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
  20796. if( s != -1 ){
  20797. /* This could happen with a network mount */
  20798. tErrno = errno;
  20799. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  20800. if( IS_LOCK_ERROR(rc) ){
  20801. pFile->lastErrno = tErrno;
  20802. }
  20803. goto end_lock;
  20804. }
  20805. }
  20806. if( s==(-1) ){
  20807. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  20808. if( IS_LOCK_ERROR(rc) ){
  20809. pFile->lastErrno = tErrno;
  20810. }
  20811. }else{
  20812. pFile->locktype = SHARED_LOCK;
  20813. pFile->pOpen->nLock++;
  20814. pLock->cnt = 1;
  20815. }
  20816. }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
  20817. /* We are trying for an exclusive lock but another thread in this
  20818. ** same process is still holding a shared lock. */
  20819. rc = SQLITE_BUSY;
  20820. }else{
  20821. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  20822. ** assumed that there is a SHARED or greater lock on the file
  20823. ** already.
  20824. */
  20825. assert( 0!=pFile->locktype );
  20826. lock.l_type = F_WRLCK;
  20827. switch( locktype ){
  20828. case RESERVED_LOCK:
  20829. lock.l_start = RESERVED_BYTE;
  20830. break;
  20831. case EXCLUSIVE_LOCK:
  20832. lock.l_start = SHARED_FIRST;
  20833. lock.l_len = SHARED_SIZE;
  20834. break;
  20835. default:
  20836. assert(0);
  20837. }
  20838. s = fcntl(pFile->h, F_SETLK, &lock);
  20839. if( s==(-1) ){
  20840. int tErrno = errno;
  20841. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  20842. if( IS_LOCK_ERROR(rc) ){
  20843. pFile->lastErrno = tErrno;
  20844. }
  20845. }
  20846. }
  20847. #ifndef NDEBUG
  20848. /* Set up the transaction-counter change checking flags when
  20849. ** transitioning from a SHARED to a RESERVED lock. The change
  20850. ** from SHARED to RESERVED marks the beginning of a normal
  20851. ** write operation (not a hot journal rollback).
  20852. */
  20853. if( rc==SQLITE_OK
  20854. && pFile->locktype<=SHARED_LOCK
  20855. && locktype==RESERVED_LOCK
  20856. ){
  20857. pFile->transCntrChng = 0;
  20858. pFile->dbUpdate = 0;
  20859. pFile->inNormalWrite = 1;
  20860. }
  20861. #endif
  20862. if( rc==SQLITE_OK ){
  20863. pFile->locktype = locktype;
  20864. pLock->locktype = locktype;
  20865. }else if( locktype==EXCLUSIVE_LOCK ){
  20866. pFile->locktype = PENDING_LOCK;
  20867. pLock->locktype = PENDING_LOCK;
  20868. }
  20869. end_lock:
  20870. unixLeaveMutex();
  20871. OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
  20872. rc==SQLITE_OK ? "ok" : "failed");
  20873. return rc;
  20874. }
  20875. /*
  20876. ** Lower the locking level on file descriptor pFile to locktype. locktype
  20877. ** must be either NO_LOCK or SHARED_LOCK.
  20878. **
  20879. ** If the locking level of the file descriptor is already at or below
  20880. ** the requested locking level, this routine is a no-op.
  20881. */
  20882. static int unixUnlock(sqlite3_file *id, int locktype){
  20883. struct unixLockInfo *pLock;
  20884. struct flock lock;
  20885. int rc = SQLITE_OK;
  20886. unixFile *pFile = (unixFile*)id;
  20887. int h;
  20888. assert( pFile );
  20889. OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
  20890. pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
  20891. assert( locktype<=SHARED_LOCK );
  20892. if( pFile->locktype<=locktype ){
  20893. return SQLITE_OK;
  20894. }
  20895. if( CHECK_THREADID(pFile) ){
  20896. return SQLITE_MISUSE;
  20897. }
  20898. unixEnterMutex();
  20899. h = pFile->h;
  20900. pLock = pFile->pLock;
  20901. assert( pLock->cnt!=0 );
  20902. if( pFile->locktype>SHARED_LOCK ){
  20903. assert( pLock->locktype==pFile->locktype );
  20904. SimulateIOErrorBenign(1);
  20905. SimulateIOError( h=(-1) )
  20906. SimulateIOErrorBenign(0);
  20907. #ifndef NDEBUG
  20908. /* When reducing a lock such that other processes can start
  20909. ** reading the database file again, make sure that the
  20910. ** transaction counter was updated if any part of the database
  20911. ** file changed. If the transaction counter is not updated,
  20912. ** other connections to the same file might not realize that
  20913. ** the file has changed and hence might not know to flush their
  20914. ** cache. The use of a stale cache can lead to database corruption.
  20915. */
  20916. assert( pFile->inNormalWrite==0
  20917. || pFile->dbUpdate==0
  20918. || pFile->transCntrChng==1 );
  20919. pFile->inNormalWrite = 0;
  20920. #endif
  20921. if( locktype==SHARED_LOCK ){
  20922. lock.l_type = F_RDLCK;
  20923. lock.l_whence = SEEK_SET;
  20924. lock.l_start = SHARED_FIRST;
  20925. lock.l_len = SHARED_SIZE;
  20926. if( fcntl(h, F_SETLK, &lock)==(-1) ){
  20927. int tErrno = errno;
  20928. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  20929. if( IS_LOCK_ERROR(rc) ){
  20930. pFile->lastErrno = tErrno;
  20931. }
  20932. goto end_unlock;
  20933. }
  20934. }
  20935. lock.l_type = F_UNLCK;
  20936. lock.l_whence = SEEK_SET;
  20937. lock.l_start = PENDING_BYTE;
  20938. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  20939. if( fcntl(h, F_SETLK, &lock)!=(-1) ){
  20940. pLock->locktype = SHARED_LOCK;
  20941. }else{
  20942. int tErrno = errno;
  20943. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  20944. if( IS_LOCK_ERROR(rc) ){
  20945. pFile->lastErrno = tErrno;
  20946. }
  20947. goto end_unlock;
  20948. }
  20949. }
  20950. if( locktype==NO_LOCK ){
  20951. struct unixOpenCnt *pOpen;
  20952. int rc2 = SQLITE_OK;
  20953. /* Decrement the shared lock counter. Release the lock using an
  20954. ** OS call only when all threads in this same process have released
  20955. ** the lock.
  20956. */
  20957. pLock->cnt--;
  20958. if( pLock->cnt==0 ){
  20959. lock.l_type = F_UNLCK;
  20960. lock.l_whence = SEEK_SET;
  20961. lock.l_start = lock.l_len = 0L;
  20962. SimulateIOErrorBenign(1);
  20963. SimulateIOError( h=(-1) )
  20964. SimulateIOErrorBenign(0);
  20965. if( fcntl(h, F_SETLK, &lock)!=(-1) ){
  20966. pLock->locktype = NO_LOCK;
  20967. }else{
  20968. int tErrno = errno;
  20969. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  20970. if( IS_LOCK_ERROR(rc) ){
  20971. pFile->lastErrno = tErrno;
  20972. }
  20973. pLock->locktype = NO_LOCK;
  20974. pFile->locktype = NO_LOCK;
  20975. }
  20976. }
  20977. /* Decrement the count of locks against this same file. When the
  20978. ** count reaches zero, close any other file descriptors whose close
  20979. ** was deferred because of outstanding locks.
  20980. */
  20981. pOpen = pFile->pOpen;
  20982. pOpen->nLock--;
  20983. assert( pOpen->nLock>=0 );
  20984. if( pOpen->nLock==0 && pOpen->nPending>0 ){
  20985. int i;
  20986. for(i=0; i<pOpen->nPending; i++){
  20987. /* close pending fds, but if closing fails don't free the array
  20988. ** assign -1 to the successfully closed descriptors and record the
  20989. ** error. The next attempt to unlock will try again. */
  20990. if( pOpen->aPending[i] < 0 ) continue;
  20991. if( close(pOpen->aPending[i]) ){
  20992. pFile->lastErrno = errno;
  20993. rc2 = SQLITE_IOERR_CLOSE;
  20994. }else{
  20995. pOpen->aPending[i] = -1;
  20996. }
  20997. }
  20998. if( rc2==SQLITE_OK ){
  20999. sqlite3_free(pOpen->aPending);
  21000. pOpen->nPending = 0;
  21001. pOpen->aPending = 0;
  21002. }
  21003. }
  21004. if( rc==SQLITE_OK ){
  21005. rc = rc2;
  21006. }
  21007. }
  21008. end_unlock:
  21009. unixLeaveMutex();
  21010. if( rc==SQLITE_OK ) pFile->locktype = locktype;
  21011. return rc;
  21012. }
  21013. /*
  21014. ** This function performs the parts of the "close file" operation
  21015. ** common to all locking schemes. It closes the directory and file
  21016. ** handles, if they are valid, and sets all fields of the unixFile
  21017. ** structure to 0.
  21018. **
  21019. ** It is *not* necessary to hold the mutex when this routine is called,
  21020. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  21021. ** vxworksReleaseFileId() routine.
  21022. */
  21023. static int closeUnixFile(sqlite3_file *id){
  21024. unixFile *pFile = (unixFile*)id;
  21025. if( pFile ){
  21026. if( pFile->dirfd>=0 ){
  21027. int err = close(pFile->dirfd);
  21028. if( err ){
  21029. pFile->lastErrno = errno;
  21030. return SQLITE_IOERR_DIR_CLOSE;
  21031. }else{
  21032. pFile->dirfd=-1;
  21033. }
  21034. }
  21035. if( pFile->h>=0 ){
  21036. int err = close(pFile->h);
  21037. if( err ){
  21038. pFile->lastErrno = errno;
  21039. return SQLITE_IOERR_CLOSE;
  21040. }
  21041. }
  21042. #if OS_VXWORKS
  21043. if( pFile->pId ){
  21044. if( pFile->isDelete ){
  21045. unlink(pFile->pId->zCanonicalName);
  21046. }
  21047. vxworksReleaseFileId(pFile->pId);
  21048. pFile->pId = 0;
  21049. }
  21050. #endif
  21051. OSTRACE2("CLOSE %-3d\n", pFile->h);
  21052. OpenCounter(-1);
  21053. memset(pFile, 0, sizeof(unixFile));
  21054. }
  21055. return SQLITE_OK;
  21056. }
  21057. /*
  21058. ** Close a file.
  21059. */
  21060. static int unixClose(sqlite3_file *id){
  21061. int rc = SQLITE_OK;
  21062. if( id ){
  21063. unixFile *pFile = (unixFile *)id;
  21064. unixUnlock(id, NO_LOCK);
  21065. unixEnterMutex();
  21066. if( pFile->pOpen && pFile->pOpen->nLock ){
  21067. /* If there are outstanding locks, do not actually close the file just
  21068. ** yet because that would clear those locks. Instead, add the file
  21069. ** descriptor to pOpen->aPending. It will be automatically closed when
  21070. ** the last lock is cleared.
  21071. */
  21072. int *aNew;
  21073. struct unixOpenCnt *pOpen = pFile->pOpen;
  21074. aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
  21075. if( aNew==0 ){
  21076. /* If a malloc fails, just leak the file descriptor */
  21077. }else{
  21078. pOpen->aPending = aNew;
  21079. pOpen->aPending[pOpen->nPending] = pFile->h;
  21080. pOpen->nPending++;
  21081. pFile->h = -1;
  21082. }
  21083. }
  21084. releaseLockInfo(pFile->pLock);
  21085. releaseOpenCnt(pFile->pOpen);
  21086. rc = closeUnixFile(id);
  21087. unixLeaveMutex();
  21088. }
  21089. return rc;
  21090. }
  21091. /************** End of the posix advisory lock implementation *****************
  21092. ******************************************************************************/
  21093. /******************************************************************************
  21094. ****************************** No-op Locking **********************************
  21095. **
  21096. ** Of the various locking implementations available, this is by far the
  21097. ** simplest: locking is ignored. No attempt is made to lock the database
  21098. ** file for reading or writing.
  21099. **
  21100. ** This locking mode is appropriate for use on read-only databases
  21101. ** (ex: databases that are burned into CD-ROM, for example.) It can
  21102. ** also be used if the application employs some external mechanism to
  21103. ** prevent simultaneous access of the same database by two or more
  21104. ** database connections. But there is a serious risk of database
  21105. ** corruption if this locking mode is used in situations where multiple
  21106. ** database connections are accessing the same database file at the same
  21107. ** time and one or more of those connections are writing.
  21108. */
  21109. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  21110. UNUSED_PARAMETER(NotUsed);
  21111. *pResOut = 0;
  21112. return SQLITE_OK;
  21113. }
  21114. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  21115. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21116. return SQLITE_OK;
  21117. }
  21118. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  21119. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21120. return SQLITE_OK;
  21121. }
  21122. /*
  21123. ** Close the file.
  21124. */
  21125. static int nolockClose(sqlite3_file *id) {
  21126. return closeUnixFile(id);
  21127. }
  21128. /******************* End of the no-op lock implementation *********************
  21129. ******************************************************************************/
  21130. /******************************************************************************
  21131. ************************* Begin dot-file Locking ******************************
  21132. **
  21133. ** The dotfile locking implementation uses the existing of separate lock
  21134. ** files in order to control access to the database. This works on just
  21135. ** about every filesystem imaginable. But there are serious downsides:
  21136. **
  21137. ** (1) There is zero concurrency. A single reader blocks all other
  21138. ** connections from reading or writing the database.
  21139. **
  21140. ** (2) An application crash or power loss can leave stale lock files
  21141. ** sitting around that need to be cleared manually.
  21142. **
  21143. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  21144. ** other locking strategy is available.
  21145. **
  21146. ** Dotfile locking works by creating a file in the same directory as the
  21147. ** database and with the same name but with a ".lock" extension added.
  21148. ** The existance of a lock file implies an EXCLUSIVE lock. All other lock
  21149. ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  21150. */
  21151. /*
  21152. ** The file suffix added to the data base filename in order to create the
  21153. ** lock file.
  21154. */
  21155. #define DOTLOCK_SUFFIX ".lock"
  21156. /*
  21157. ** This routine checks if there is a RESERVED lock held on the specified
  21158. ** file by this or any other process. If such a lock is held, set *pResOut
  21159. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  21160. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  21161. **
  21162. ** In dotfile locking, either a lock exists or it does not. So in this
  21163. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  21164. ** is held on the file and false if the file is unlocked.
  21165. */
  21166. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  21167. int rc = SQLITE_OK;
  21168. int reserved = 0;
  21169. unixFile *pFile = (unixFile*)id;
  21170. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  21171. assert( pFile );
  21172. /* Check if a thread in this process holds such a lock */
  21173. if( pFile->locktype>SHARED_LOCK ){
  21174. /* Either this connection or some other connection in the same process
  21175. ** holds a lock on the file. No need to check further. */
  21176. reserved = 1;
  21177. }else{
  21178. /* The lock is held if and only if the lockfile exists */
  21179. const char *zLockFile = (const char*)pFile->lockingContext;
  21180. reserved = access(zLockFile, 0)==0;
  21181. }
  21182. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  21183. *pResOut = reserved;
  21184. return rc;
  21185. }
  21186. /*
  21187. ** Lock the file with the lock specified by parameter locktype - one
  21188. ** of the following:
  21189. **
  21190. ** (1) SHARED_LOCK
  21191. ** (2) RESERVED_LOCK
  21192. ** (3) PENDING_LOCK
  21193. ** (4) EXCLUSIVE_LOCK
  21194. **
  21195. ** Sometimes when requesting one lock state, additional lock states
  21196. ** are inserted in between. The locking might fail on one of the later
  21197. ** transitions leaving the lock state different from what it started but
  21198. ** still short of its goal. The following chart shows the allowed
  21199. ** transitions and the inserted intermediate states:
  21200. **
  21201. ** UNLOCKED -> SHARED
  21202. ** SHARED -> RESERVED
  21203. ** SHARED -> (PENDING) -> EXCLUSIVE
  21204. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21205. ** PENDING -> EXCLUSIVE
  21206. **
  21207. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  21208. ** routine to lower a locking level.
  21209. **
  21210. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  21211. ** But we track the other locking levels internally.
  21212. */
  21213. static int dotlockLock(sqlite3_file *id, int locktype) {
  21214. unixFile *pFile = (unixFile*)id;
  21215. int fd;
  21216. char *zLockFile = (char *)pFile->lockingContext;
  21217. int rc = SQLITE_OK;
  21218. /* If we have any lock, then the lock file already exists. All we have
  21219. ** to do is adjust our internal record of the lock level.
  21220. */
  21221. if( pFile->locktype > NO_LOCK ){
  21222. pFile->locktype = locktype;
  21223. #if !OS_VXWORKS
  21224. /* Always update the timestamp on the old file */
  21225. utimes(zLockFile, NULL);
  21226. #endif
  21227. return SQLITE_OK;
  21228. }
  21229. /* grab an exclusive lock */
  21230. fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
  21231. if( fd<0 ){
  21232. /* failed to open/create the file, someone else may have stolen the lock */
  21233. int tErrno = errno;
  21234. if( EEXIST == tErrno ){
  21235. rc = SQLITE_BUSY;
  21236. } else {
  21237. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  21238. if( IS_LOCK_ERROR(rc) ){
  21239. pFile->lastErrno = tErrno;
  21240. }
  21241. }
  21242. return rc;
  21243. }
  21244. if( close(fd) ){
  21245. pFile->lastErrno = errno;
  21246. rc = SQLITE_IOERR_CLOSE;
  21247. }
  21248. /* got it, set the type and return ok */
  21249. pFile->locktype = locktype;
  21250. return rc;
  21251. }
  21252. /*
  21253. ** Lower the locking level on file descriptor pFile to locktype. locktype
  21254. ** must be either NO_LOCK or SHARED_LOCK.
  21255. **
  21256. ** If the locking level of the file descriptor is already at or below
  21257. ** the requested locking level, this routine is a no-op.
  21258. **
  21259. ** When the locking level reaches NO_LOCK, delete the lock file.
  21260. */
  21261. static int dotlockUnlock(sqlite3_file *id, int locktype) {
  21262. unixFile *pFile = (unixFile*)id;
  21263. char *zLockFile = (char *)pFile->lockingContext;
  21264. assert( pFile );
  21265. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  21266. pFile->locktype, getpid());
  21267. assert( locktype<=SHARED_LOCK );
  21268. /* no-op if possible */
  21269. if( pFile->locktype==locktype ){
  21270. return SQLITE_OK;
  21271. }
  21272. /* To downgrade to shared, simply update our internal notion of the
  21273. ** lock state. No need to mess with the file on disk.
  21274. */
  21275. if( locktype==SHARED_LOCK ){
  21276. pFile->locktype = SHARED_LOCK;
  21277. return SQLITE_OK;
  21278. }
  21279. /* To fully unlock the database, delete the lock file */
  21280. assert( locktype==NO_LOCK );
  21281. if( unlink(zLockFile) ){
  21282. int rc, tErrno = errno;
  21283. if( ENOENT != tErrno ){
  21284. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  21285. }
  21286. if( IS_LOCK_ERROR(rc) ){
  21287. pFile->lastErrno = tErrno;
  21288. }
  21289. return rc;
  21290. }
  21291. pFile->locktype = NO_LOCK;
  21292. return SQLITE_OK;
  21293. }
  21294. /*
  21295. ** Close a file. Make sure the lock has been released before closing.
  21296. */
  21297. static int dotlockClose(sqlite3_file *id) {
  21298. int rc;
  21299. if( id ){
  21300. unixFile *pFile = (unixFile*)id;
  21301. dotlockUnlock(id, NO_LOCK);
  21302. sqlite3_free(pFile->lockingContext);
  21303. }
  21304. rc = closeUnixFile(id);
  21305. return rc;
  21306. }
  21307. /****************** End of the dot-file lock implementation *******************
  21308. ******************************************************************************/
  21309. /******************************************************************************
  21310. ************************** Begin flock Locking ********************************
  21311. **
  21312. ** Use the flock() system call to do file locking.
  21313. **
  21314. ** flock() locking is like dot-file locking in that the various
  21315. ** fine-grain locking levels supported by SQLite are collapsed into
  21316. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  21317. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  21318. ** still works when you do this, but concurrency is reduced since
  21319. ** only a single process can be reading the database at a time.
  21320. **
  21321. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  21322. ** compiling for VXWORKS.
  21323. */
  21324. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  21325. /*
  21326. ** This routine checks if there is a RESERVED lock held on the specified
  21327. ** file by this or any other process. If such a lock is held, set *pResOut
  21328. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  21329. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  21330. */
  21331. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  21332. int rc = SQLITE_OK;
  21333. int reserved = 0;
  21334. unixFile *pFile = (unixFile*)id;
  21335. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  21336. assert( pFile );
  21337. /* Check if a thread in this process holds such a lock */
  21338. if( pFile->locktype>SHARED_LOCK ){
  21339. reserved = 1;
  21340. }
  21341. /* Otherwise see if some other process holds it. */
  21342. if( !reserved ){
  21343. /* attempt to get the lock */
  21344. int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
  21345. if( !lrc ){
  21346. /* got the lock, unlock it */
  21347. lrc = flock(pFile->h, LOCK_UN);
  21348. if ( lrc ) {
  21349. int tErrno = errno;
  21350. /* unlock failed with an error */
  21351. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  21352. if( IS_LOCK_ERROR(lrc) ){
  21353. pFile->lastErrno = tErrno;
  21354. rc = lrc;
  21355. }
  21356. }
  21357. } else {
  21358. int tErrno = errno;
  21359. reserved = 1;
  21360. /* someone else might have it reserved */
  21361. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  21362. if( IS_LOCK_ERROR(lrc) ){
  21363. pFile->lastErrno = tErrno;
  21364. rc = lrc;
  21365. }
  21366. }
  21367. }
  21368. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  21369. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  21370. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  21371. rc = SQLITE_OK;
  21372. reserved=1;
  21373. }
  21374. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  21375. *pResOut = reserved;
  21376. return rc;
  21377. }
  21378. /*
  21379. ** Lock the file with the lock specified by parameter locktype - one
  21380. ** of the following:
  21381. **
  21382. ** (1) SHARED_LOCK
  21383. ** (2) RESERVED_LOCK
  21384. ** (3) PENDING_LOCK
  21385. ** (4) EXCLUSIVE_LOCK
  21386. **
  21387. ** Sometimes when requesting one lock state, additional lock states
  21388. ** are inserted in between. The locking might fail on one of the later
  21389. ** transitions leaving the lock state different from what it started but
  21390. ** still short of its goal. The following chart shows the allowed
  21391. ** transitions and the inserted intermediate states:
  21392. **
  21393. ** UNLOCKED -> SHARED
  21394. ** SHARED -> RESERVED
  21395. ** SHARED -> (PENDING) -> EXCLUSIVE
  21396. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21397. ** PENDING -> EXCLUSIVE
  21398. **
  21399. ** flock() only really support EXCLUSIVE locks. We track intermediate
  21400. ** lock states in the sqlite3_file structure, but all locks SHARED or
  21401. ** above are really EXCLUSIVE locks and exclude all other processes from
  21402. ** access the file.
  21403. **
  21404. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  21405. ** routine to lower a locking level.
  21406. */
  21407. static int flockLock(sqlite3_file *id, int locktype) {
  21408. int rc = SQLITE_OK;
  21409. unixFile *pFile = (unixFile*)id;
  21410. assert( pFile );
  21411. /* if we already have a lock, it is exclusive.
  21412. ** Just adjust level and punt on outta here. */
  21413. if (pFile->locktype > NO_LOCK) {
  21414. pFile->locktype = locktype;
  21415. return SQLITE_OK;
  21416. }
  21417. /* grab an exclusive lock */
  21418. if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
  21419. int tErrno = errno;
  21420. /* didn't get, must be busy */
  21421. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  21422. if( IS_LOCK_ERROR(rc) ){
  21423. pFile->lastErrno = tErrno;
  21424. }
  21425. } else {
  21426. /* got it, set the type and return ok */
  21427. pFile->locktype = locktype;
  21428. }
  21429. OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
  21430. rc==SQLITE_OK ? "ok" : "failed");
  21431. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  21432. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  21433. rc = SQLITE_BUSY;
  21434. }
  21435. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  21436. return rc;
  21437. }
  21438. /*
  21439. ** Lower the locking level on file descriptor pFile to locktype. locktype
  21440. ** must be either NO_LOCK or SHARED_LOCK.
  21441. **
  21442. ** If the locking level of the file descriptor is already at or below
  21443. ** the requested locking level, this routine is a no-op.
  21444. */
  21445. static int flockUnlock(sqlite3_file *id, int locktype) {
  21446. unixFile *pFile = (unixFile*)id;
  21447. assert( pFile );
  21448. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  21449. pFile->locktype, getpid());
  21450. assert( locktype<=SHARED_LOCK );
  21451. /* no-op if possible */
  21452. if( pFile->locktype==locktype ){
  21453. return SQLITE_OK;
  21454. }
  21455. /* shared can just be set because we always have an exclusive */
  21456. if (locktype==SHARED_LOCK) {
  21457. pFile->locktype = locktype;
  21458. return SQLITE_OK;
  21459. }
  21460. /* no, really, unlock. */
  21461. int rc = flock(pFile->h, LOCK_UN);
  21462. if (rc) {
  21463. int r, tErrno = errno;
  21464. r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  21465. if( IS_LOCK_ERROR(r) ){
  21466. pFile->lastErrno = tErrno;
  21467. }
  21468. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  21469. if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
  21470. r = SQLITE_BUSY;
  21471. }
  21472. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  21473. return r;
  21474. } else {
  21475. pFile->locktype = NO_LOCK;
  21476. return SQLITE_OK;
  21477. }
  21478. }
  21479. /*
  21480. ** Close a file.
  21481. */
  21482. static int flockClose(sqlite3_file *id) {
  21483. if( id ){
  21484. flockUnlock(id, NO_LOCK);
  21485. }
  21486. return closeUnixFile(id);
  21487. }
  21488. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  21489. /******************* End of the flock lock implementation *********************
  21490. ******************************************************************************/
  21491. /******************************************************************************
  21492. ************************ Begin Named Semaphore Locking ************************
  21493. **
  21494. ** Named semaphore locking is only supported on VxWorks.
  21495. **
  21496. ** Semaphore locking is like dot-lock and flock in that it really only
  21497. ** supports EXCLUSIVE locking. Only a single process can read or write
  21498. ** the database file at a time. This reduces potential concurrency, but
  21499. ** makes the lock implementation much easier.
  21500. */
  21501. #if OS_VXWORKS
  21502. /*
  21503. ** This routine checks if there is a RESERVED lock held on the specified
  21504. ** file by this or any other process. If such a lock is held, set *pResOut
  21505. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  21506. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  21507. */
  21508. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  21509. int rc = SQLITE_OK;
  21510. int reserved = 0;
  21511. unixFile *pFile = (unixFile*)id;
  21512. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  21513. assert( pFile );
  21514. /* Check if a thread in this process holds such a lock */
  21515. if( pFile->locktype>SHARED_LOCK ){
  21516. reserved = 1;
  21517. }
  21518. /* Otherwise see if some other process holds it. */
  21519. if( !reserved ){
  21520. sem_t *pSem = pFile->pOpen->pSem;
  21521. struct stat statBuf;
  21522. if( sem_trywait(pSem)==-1 ){
  21523. int tErrno = errno;
  21524. if( EAGAIN != tErrno ){
  21525. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  21526. pFile->lastErrno = tErrno;
  21527. } else {
  21528. /* someone else has the lock when we are in NO_LOCK */
  21529. reserved = (pFile->locktype < SHARED_LOCK);
  21530. }
  21531. }else{
  21532. /* we could have it if we want it */
  21533. sem_post(pSem);
  21534. }
  21535. }
  21536. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  21537. *pResOut = reserved;
  21538. return rc;
  21539. }
  21540. /*
  21541. ** Lock the file with the lock specified by parameter locktype - one
  21542. ** of the following:
  21543. **
  21544. ** (1) SHARED_LOCK
  21545. ** (2) RESERVED_LOCK
  21546. ** (3) PENDING_LOCK
  21547. ** (4) EXCLUSIVE_LOCK
  21548. **
  21549. ** Sometimes when requesting one lock state, additional lock states
  21550. ** are inserted in between. The locking might fail on one of the later
  21551. ** transitions leaving the lock state different from what it started but
  21552. ** still short of its goal. The following chart shows the allowed
  21553. ** transitions and the inserted intermediate states:
  21554. **
  21555. ** UNLOCKED -> SHARED
  21556. ** SHARED -> RESERVED
  21557. ** SHARED -> (PENDING) -> EXCLUSIVE
  21558. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21559. ** PENDING -> EXCLUSIVE
  21560. **
  21561. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  21562. ** lock states in the sqlite3_file structure, but all locks SHARED or
  21563. ** above are really EXCLUSIVE locks and exclude all other processes from
  21564. ** access the file.
  21565. **
  21566. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  21567. ** routine to lower a locking level.
  21568. */
  21569. static int semLock(sqlite3_file *id, int locktype) {
  21570. unixFile *pFile = (unixFile*)id;
  21571. int fd;
  21572. sem_t *pSem = pFile->pOpen->pSem;
  21573. int rc = SQLITE_OK;
  21574. /* if we already have a lock, it is exclusive.
  21575. ** Just adjust level and punt on outta here. */
  21576. if (pFile->locktype > NO_LOCK) {
  21577. pFile->locktype = locktype;
  21578. rc = SQLITE_OK;
  21579. goto sem_end_lock;
  21580. }
  21581. /* lock semaphore now but bail out when already locked. */
  21582. if( sem_trywait(pSem)==-1 ){
  21583. rc = SQLITE_BUSY;
  21584. goto sem_end_lock;
  21585. }
  21586. /* got it, set the type and return ok */
  21587. pFile->locktype = locktype;
  21588. sem_end_lock:
  21589. return rc;
  21590. }
  21591. /*
  21592. ** Lower the locking level on file descriptor pFile to locktype. locktype
  21593. ** must be either NO_LOCK or SHARED_LOCK.
  21594. **
  21595. ** If the locking level of the file descriptor is already at or below
  21596. ** the requested locking level, this routine is a no-op.
  21597. */
  21598. static int semUnlock(sqlite3_file *id, int locktype) {
  21599. unixFile *pFile = (unixFile*)id;
  21600. sem_t *pSem = pFile->pOpen->pSem;
  21601. assert( pFile );
  21602. assert( pSem );
  21603. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  21604. pFile->locktype, getpid());
  21605. assert( locktype<=SHARED_LOCK );
  21606. /* no-op if possible */
  21607. if( pFile->locktype==locktype ){
  21608. return SQLITE_OK;
  21609. }
  21610. /* shared can just be set because we always have an exclusive */
  21611. if (locktype==SHARED_LOCK) {
  21612. pFile->locktype = locktype;
  21613. return SQLITE_OK;
  21614. }
  21615. /* no, really unlock. */
  21616. if ( sem_post(pSem)==-1 ) {
  21617. int rc, tErrno = errno;
  21618. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  21619. if( IS_LOCK_ERROR(rc) ){
  21620. pFile->lastErrno = tErrno;
  21621. }
  21622. return rc;
  21623. }
  21624. pFile->locktype = NO_LOCK;
  21625. return SQLITE_OK;
  21626. }
  21627. /*
  21628. ** Close a file.
  21629. */
  21630. static int semClose(sqlite3_file *id) {
  21631. if( id ){
  21632. unixFile *pFile = (unixFile*)id;
  21633. semUnlock(id, NO_LOCK);
  21634. assert( pFile );
  21635. unixEnterMutex();
  21636. releaseLockInfo(pFile->pLock);
  21637. releaseOpenCnt(pFile->pOpen);
  21638. unixLeaveMutex();
  21639. closeUnixFile(id);
  21640. }
  21641. return SQLITE_OK;
  21642. }
  21643. #endif /* OS_VXWORKS */
  21644. /*
  21645. ** Named semaphore locking is only available on VxWorks.
  21646. **
  21647. *************** End of the named semaphore lock implementation ****************
  21648. ******************************************************************************/
  21649. /******************************************************************************
  21650. *************************** Begin AFP Locking *********************************
  21651. **
  21652. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  21653. ** on Apple Macintosh computers - both OS9 and OSX.
  21654. **
  21655. ** Third-party implementations of AFP are available. But this code here
  21656. ** only works on OSX.
  21657. */
  21658. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  21659. /*
  21660. ** The afpLockingContext structure contains all afp lock specific state
  21661. */
  21662. typedef struct afpLockingContext afpLockingContext;
  21663. struct afpLockingContext {
  21664. unsigned long long sharedByte;
  21665. const char *dbPath; /* Name of the open file */
  21666. };
  21667. struct ByteRangeLockPB2
  21668. {
  21669. unsigned long long offset; /* offset to first byte to lock */
  21670. unsigned long long length; /* nbr of bytes to lock */
  21671. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  21672. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  21673. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  21674. int fd; /* file desc to assoc this lock with */
  21675. };
  21676. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  21677. /*
  21678. ** This is a utility for setting or clearing a bit-range lock on an
  21679. ** AFP filesystem.
  21680. **
  21681. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  21682. */
  21683. static int afpSetLock(
  21684. const char *path, /* Name of the file to be locked or unlocked */
  21685. unixFile *pFile, /* Open file descriptor on path */
  21686. unsigned long long offset, /* First byte to be locked */
  21687. unsigned long long length, /* Number of bytes to lock */
  21688. int setLockFlag /* True to set lock. False to clear lock */
  21689. ){
  21690. struct ByteRangeLockPB2 pb;
  21691. int err;
  21692. pb.unLockFlag = setLockFlag ? 0 : 1;
  21693. pb.startEndFlag = 0;
  21694. pb.offset = offset;
  21695. pb.length = length;
  21696. pb.fd = pFile->h;
  21697. OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  21698. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  21699. offset, length);
  21700. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  21701. if ( err==-1 ) {
  21702. int rc;
  21703. int tErrno = errno;
  21704. OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  21705. path, tErrno, strerror(tErrno));
  21706. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  21707. rc = SQLITE_BUSY;
  21708. #else
  21709. rc = sqliteErrorFromPosixError(tErrno,
  21710. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  21711. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  21712. if( IS_LOCK_ERROR(rc) ){
  21713. pFile->lastErrno = tErrno;
  21714. }
  21715. return rc;
  21716. } else {
  21717. return SQLITE_OK;
  21718. }
  21719. }
  21720. /*
  21721. ** This routine checks if there is a RESERVED lock held on the specified
  21722. ** file by this or any other process. If such a lock is held, set *pResOut
  21723. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  21724. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  21725. */
  21726. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  21727. int rc = SQLITE_OK;
  21728. int reserved = 0;
  21729. unixFile *pFile = (unixFile*)id;
  21730. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  21731. assert( pFile );
  21732. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  21733. /* Check if a thread in this process holds such a lock */
  21734. if( pFile->locktype>SHARED_LOCK ){
  21735. reserved = 1;
  21736. }
  21737. /* Otherwise see if some other process holds it.
  21738. */
  21739. if( !reserved ){
  21740. /* lock the RESERVED byte */
  21741. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  21742. if( SQLITE_OK==lrc ){
  21743. /* if we succeeded in taking the reserved lock, unlock it to restore
  21744. ** the original state */
  21745. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  21746. } else {
  21747. /* if we failed to get the lock then someone else must have it */
  21748. reserved = 1;
  21749. }
  21750. if( IS_LOCK_ERROR(lrc) ){
  21751. rc=lrc;
  21752. }
  21753. }
  21754. OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
  21755. *pResOut = reserved;
  21756. return rc;
  21757. }
  21758. /*
  21759. ** Lock the file with the lock specified by parameter locktype - one
  21760. ** of the following:
  21761. **
  21762. ** (1) SHARED_LOCK
  21763. ** (2) RESERVED_LOCK
  21764. ** (3) PENDING_LOCK
  21765. ** (4) EXCLUSIVE_LOCK
  21766. **
  21767. ** Sometimes when requesting one lock state, additional lock states
  21768. ** are inserted in between. The locking might fail on one of the later
  21769. ** transitions leaving the lock state different from what it started but
  21770. ** still short of its goal. The following chart shows the allowed
  21771. ** transitions and the inserted intermediate states:
  21772. **
  21773. ** UNLOCKED -> SHARED
  21774. ** SHARED -> RESERVED
  21775. ** SHARED -> (PENDING) -> EXCLUSIVE
  21776. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21777. ** PENDING -> EXCLUSIVE
  21778. **
  21779. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  21780. ** routine to lower a locking level.
  21781. */
  21782. static int afpLock(sqlite3_file *id, int locktype){
  21783. int rc = SQLITE_OK;
  21784. unixFile *pFile = (unixFile*)id;
  21785. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  21786. assert( pFile );
  21787. OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
  21788. locktypeName(locktype), locktypeName(pFile->locktype), getpid());
  21789. /* If there is already a lock of this type or more restrictive on the
  21790. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  21791. ** unixEnterMutex() hasn't been called yet.
  21792. */
  21793. if( pFile->locktype>=locktype ){
  21794. OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
  21795. locktypeName(locktype));
  21796. return SQLITE_OK;
  21797. }
  21798. /* Make sure the locking sequence is correct
  21799. */
  21800. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  21801. assert( locktype!=PENDING_LOCK );
  21802. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  21803. /* This mutex is needed because pFile->pLock is shared across threads
  21804. */
  21805. unixEnterMutex();
  21806. /* Make sure the current thread owns the pFile.
  21807. */
  21808. rc = transferOwnership(pFile);
  21809. if( rc!=SQLITE_OK ){
  21810. unixLeaveMutex();
  21811. return rc;
  21812. }
  21813. /* A PENDING lock is needed before acquiring a SHARED lock and before
  21814. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  21815. ** be released.
  21816. */
  21817. if( locktype==SHARED_LOCK
  21818. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
  21819. ){
  21820. int failed;
  21821. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  21822. if (failed) {
  21823. rc = failed;
  21824. goto afp_end_lock;
  21825. }
  21826. }
  21827. /* If control gets to this point, then actually go ahead and make
  21828. ** operating system calls for the specified lock.
  21829. */
  21830. if( locktype==SHARED_LOCK ){
  21831. int lk, lrc1, lrc2, lrc1Errno;
  21832. /* Now get the read-lock SHARED_LOCK */
  21833. /* note that the quality of the randomness doesn't matter that much */
  21834. lk = random();
  21835. context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
  21836. lrc1 = afpSetLock(context->dbPath, pFile,
  21837. SHARED_FIRST+context->sharedByte, 1, 1);
  21838. if( IS_LOCK_ERROR(lrc1) ){
  21839. lrc1Errno = pFile->lastErrno;
  21840. }
  21841. /* Drop the temporary PENDING lock */
  21842. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  21843. if( IS_LOCK_ERROR(lrc1) ) {
  21844. pFile->lastErrno = lrc1Errno;
  21845. rc = lrc1;
  21846. goto afp_end_lock;
  21847. } else if( IS_LOCK_ERROR(lrc2) ){
  21848. rc = lrc2;
  21849. goto afp_end_lock;
  21850. } else if( lrc1 != SQLITE_OK ) {
  21851. rc = lrc1;
  21852. } else {
  21853. pFile->locktype = SHARED_LOCK;
  21854. pFile->pOpen->nLock++;
  21855. }
  21856. }else{
  21857. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  21858. ** assumed that there is a SHARED or greater lock on the file
  21859. ** already.
  21860. */
  21861. int failed = 0;
  21862. assert( 0!=pFile->locktype );
  21863. if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
  21864. /* Acquire a RESERVED lock */
  21865. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  21866. }
  21867. if (!failed && locktype == EXCLUSIVE_LOCK) {
  21868. /* Acquire an EXCLUSIVE lock */
  21869. /* Remove the shared lock before trying the range. we'll need to
  21870. ** reestablish the shared lock if we can't get the afpUnlock
  21871. */
  21872. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  21873. context->sharedByte, 1, 0)) ){
  21874. int failed2 = SQLITE_OK;
  21875. /* now attemmpt to get the exclusive lock range */
  21876. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  21877. SHARED_SIZE, 1);
  21878. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  21879. SHARED_FIRST + context->sharedByte, 1, 1)) ){
  21880. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  21881. ** a critical I/O error
  21882. */
  21883. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  21884. SQLITE_IOERR_LOCK;
  21885. goto afp_end_lock;
  21886. }
  21887. }else{
  21888. rc = failed;
  21889. }
  21890. }
  21891. if( failed ){
  21892. rc = failed;
  21893. }
  21894. }
  21895. if( rc==SQLITE_OK ){
  21896. pFile->locktype = locktype;
  21897. }else if( locktype==EXCLUSIVE_LOCK ){
  21898. pFile->locktype = PENDING_LOCK;
  21899. }
  21900. afp_end_lock:
  21901. unixLeaveMutex();
  21902. OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
  21903. rc==SQLITE_OK ? "ok" : "failed");
  21904. return rc;
  21905. }
  21906. /*
  21907. ** Lower the locking level on file descriptor pFile to locktype. locktype
  21908. ** must be either NO_LOCK or SHARED_LOCK.
  21909. **
  21910. ** If the locking level of the file descriptor is already at or below
  21911. ** the requested locking level, this routine is a no-op.
  21912. */
  21913. static int afpUnlock(sqlite3_file *id, int locktype) {
  21914. int rc = SQLITE_OK;
  21915. unixFile *pFile = (unixFile*)id;
  21916. afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
  21917. assert( pFile );
  21918. OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
  21919. pFile->locktype, getpid());
  21920. assert( locktype<=SHARED_LOCK );
  21921. if( pFile->locktype<=locktype ){
  21922. return SQLITE_OK;
  21923. }
  21924. if( CHECK_THREADID(pFile) ){
  21925. return SQLITE_MISUSE;
  21926. }
  21927. unixEnterMutex();
  21928. if( pFile->locktype>SHARED_LOCK ){
  21929. if( pFile->locktype==EXCLUSIVE_LOCK ){
  21930. rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  21931. if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
  21932. /* only re-establish the shared lock if necessary */
  21933. int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
  21934. rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
  21935. }
  21936. }
  21937. if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
  21938. rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
  21939. }
  21940. if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
  21941. rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
  21942. }
  21943. }else if( locktype==NO_LOCK ){
  21944. /* clear the shared lock */
  21945. int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
  21946. rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
  21947. }
  21948. if( rc==SQLITE_OK ){
  21949. if( locktype==NO_LOCK ){
  21950. struct unixOpenCnt *pOpen = pFile->pOpen;
  21951. pOpen->nLock--;
  21952. assert( pOpen->nLock>=0 );
  21953. if( pOpen->nLock==0 && pOpen->nPending>0 ){
  21954. int i;
  21955. for(i=0; i<pOpen->nPending; i++){
  21956. if( pOpen->aPending[i] < 0 ) continue;
  21957. if( close(pOpen->aPending[i]) ){
  21958. pFile->lastErrno = errno;
  21959. rc = SQLITE_IOERR_CLOSE;
  21960. }else{
  21961. pOpen->aPending[i] = -1;
  21962. }
  21963. }
  21964. if( rc==SQLITE_OK ){
  21965. sqlite3_free(pOpen->aPending);
  21966. pOpen->nPending = 0;
  21967. pOpen->aPending = 0;
  21968. }
  21969. }
  21970. }
  21971. }
  21972. unixLeaveMutex();
  21973. if( rc==SQLITE_OK ) pFile->locktype = locktype;
  21974. return rc;
  21975. }
  21976. /*
  21977. ** Close a file & cleanup AFP specific locking context
  21978. */
  21979. static int afpClose(sqlite3_file *id) {
  21980. if( id ){
  21981. unixFile *pFile = (unixFile*)id;
  21982. afpUnlock(id, NO_LOCK);
  21983. unixEnterMutex();
  21984. if( pFile->pOpen && pFile->pOpen->nLock ){
  21985. /* If there are outstanding locks, do not actually close the file just
  21986. ** yet because that would clear those locks. Instead, add the file
  21987. ** descriptor to pOpen->aPending. It will be automatically closed when
  21988. ** the last lock is cleared.
  21989. */
  21990. int *aNew;
  21991. struct unixOpenCnt *pOpen = pFile->pOpen;
  21992. aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
  21993. if( aNew==0 ){
  21994. /* If a malloc fails, just leak the file descriptor */
  21995. }else{
  21996. pOpen->aPending = aNew;
  21997. pOpen->aPending[pOpen->nPending] = pFile->h;
  21998. pOpen->nPending++;
  21999. pFile->h = -1;
  22000. }
  22001. }
  22002. releaseOpenCnt(pFile->pOpen);
  22003. sqlite3_free(pFile->lockingContext);
  22004. closeUnixFile(id);
  22005. unixLeaveMutex();
  22006. }
  22007. return SQLITE_OK;
  22008. }
  22009. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  22010. /*
  22011. ** The code above is the AFP lock implementation. The code is specific
  22012. ** to MacOSX and does not work on other unix platforms. No alternative
  22013. ** is available. If you don't compile for a mac, then the "unix-afp"
  22014. ** VFS is not available.
  22015. **
  22016. ********************* End of the AFP lock implementation **********************
  22017. ******************************************************************************/
  22018. /******************************************************************************
  22019. **************** Non-locking sqlite3_file methods *****************************
  22020. **
  22021. ** The next division contains implementations for all methods of the
  22022. ** sqlite3_file object other than the locking methods. The locking
  22023. ** methods were defined in divisions above (one locking method per
  22024. ** division). Those methods that are common to all locking modes
  22025. ** are gather together into this division.
  22026. */
  22027. /*
  22028. ** Seek to the offset passed as the second argument, then read cnt
  22029. ** bytes into pBuf. Return the number of bytes actually read.
  22030. **
  22031. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  22032. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  22033. ** one system to another. Since SQLite does not define USE_PREAD
  22034. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  22035. ** See tickets #2741 and #2681.
  22036. **
  22037. ** To avoid stomping the errno value on a failed read the lastErrno value
  22038. ** is set before returning.
  22039. */
  22040. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  22041. int got;
  22042. i64 newOffset;
  22043. TIMER_START;
  22044. #if defined(USE_PREAD)
  22045. got = pread(id->h, pBuf, cnt, offset);
  22046. SimulateIOError( got = -1 );
  22047. #elif defined(USE_PREAD64)
  22048. got = pread64(id->h, pBuf, cnt, offset);
  22049. SimulateIOError( got = -1 );
  22050. #else
  22051. newOffset = lseek(id->h, offset, SEEK_SET);
  22052. SimulateIOError( newOffset-- );
  22053. if( newOffset!=offset ){
  22054. if( newOffset == -1 ){
  22055. ((unixFile*)id)->lastErrno = errno;
  22056. }else{
  22057. ((unixFile*)id)->lastErrno = 0;
  22058. }
  22059. return -1;
  22060. }
  22061. got = read(id->h, pBuf, cnt);
  22062. #endif
  22063. TIMER_END;
  22064. if( got<0 ){
  22065. ((unixFile*)id)->lastErrno = errno;
  22066. }
  22067. OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
  22068. return got;
  22069. }
  22070. /*
  22071. ** Read data from a file into a buffer. Return SQLITE_OK if all
  22072. ** bytes were read successfully and SQLITE_IOERR if anything goes
  22073. ** wrong.
  22074. */
  22075. static int unixRead(
  22076. sqlite3_file *id,
  22077. void *pBuf,
  22078. int amt,
  22079. sqlite3_int64 offset
  22080. ){
  22081. int got;
  22082. assert( id );
  22083. /* Never read or write any of the bytes in the locking range */
  22084. assert( ((unixFile*)id)->isLockable==0
  22085. || offset>=PENDING_BYTE+512
  22086. || offset+amt<=PENDING_BYTE );
  22087. got = seekAndRead((unixFile*)id, offset, pBuf, amt);
  22088. if( got==amt ){
  22089. return SQLITE_OK;
  22090. }else if( got<0 ){
  22091. /* lastErrno set by seekAndRead */
  22092. return SQLITE_IOERR_READ;
  22093. }else{
  22094. ((unixFile*)id)->lastErrno = 0; /* not a system error */
  22095. /* Unread parts of the buffer must be zero-filled */
  22096. memset(&((char*)pBuf)[got], 0, amt-got);
  22097. return SQLITE_IOERR_SHORT_READ;
  22098. }
  22099. }
  22100. /*
  22101. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  22102. ** Return the number of bytes actually read. Update the offset.
  22103. **
  22104. ** To avoid stomping the errno value on a failed write the lastErrno value
  22105. ** is set before returning.
  22106. */
  22107. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  22108. int got;
  22109. i64 newOffset;
  22110. TIMER_START;
  22111. #if defined(USE_PREAD)
  22112. got = pwrite(id->h, pBuf, cnt, offset);
  22113. #elif defined(USE_PREAD64)
  22114. got = pwrite64(id->h, pBuf, cnt, offset);
  22115. #else
  22116. newOffset = lseek(id->h, offset, SEEK_SET);
  22117. if( newOffset!=offset ){
  22118. if( newOffset == -1 ){
  22119. ((unixFile*)id)->lastErrno = errno;
  22120. }else{
  22121. ((unixFile*)id)->lastErrno = 0;
  22122. }
  22123. return -1;
  22124. }
  22125. got = write(id->h, pBuf, cnt);
  22126. #endif
  22127. TIMER_END;
  22128. if( got<0 ){
  22129. ((unixFile*)id)->lastErrno = errno;
  22130. }
  22131. OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
  22132. return got;
  22133. }
  22134. /*
  22135. ** Write data from a buffer into a file. Return SQLITE_OK on success
  22136. ** or some other error code on failure.
  22137. */
  22138. static int unixWrite(
  22139. sqlite3_file *id,
  22140. const void *pBuf,
  22141. int amt,
  22142. sqlite3_int64 offset
  22143. ){
  22144. int wrote = 0;
  22145. assert( id );
  22146. assert( amt>0 );
  22147. /* Never read or write any of the bytes in the locking range */
  22148. assert( ((unixFile*)id)->isLockable==0
  22149. || offset>=PENDING_BYTE+512
  22150. || offset+amt<=PENDING_BYTE );
  22151. #ifndef NDEBUG
  22152. /* If we are doing a normal write to a database file (as opposed to
  22153. ** doing a hot-journal rollback or a write to some file other than a
  22154. ** normal database file) then record the fact that the database
  22155. ** has changed. If the transaction counter is modified, record that
  22156. ** fact too.
  22157. */
  22158. if( ((unixFile*)id)->inNormalWrite ){
  22159. unixFile *pFile = (unixFile*)id;
  22160. pFile->dbUpdate = 1; /* The database has been modified */
  22161. if( offset<=24 && offset+amt>=27 ){
  22162. int rc;
  22163. char oldCntr[4];
  22164. SimulateIOErrorBenign(1);
  22165. rc = seekAndRead(pFile, 24, oldCntr, 4);
  22166. SimulateIOErrorBenign(0);
  22167. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  22168. pFile->transCntrChng = 1; /* The transaction counter has changed */
  22169. }
  22170. }
  22171. }
  22172. #endif
  22173. while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
  22174. amt -= wrote;
  22175. offset += wrote;
  22176. pBuf = &((char*)pBuf)[wrote];
  22177. }
  22178. SimulateIOError(( wrote=(-1), amt=1 ));
  22179. SimulateDiskfullError(( wrote=0, amt=1 ));
  22180. if( amt>0 ){
  22181. if( wrote<0 ){
  22182. /* lastErrno set by seekAndWrite */
  22183. return SQLITE_IOERR_WRITE;
  22184. }else{
  22185. ((unixFile*)id)->lastErrno = 0; /* not a system error */
  22186. return SQLITE_FULL;
  22187. }
  22188. }
  22189. return SQLITE_OK;
  22190. }
  22191. #ifdef SQLITE_TEST
  22192. /*
  22193. ** Count the number of fullsyncs and normal syncs. This is used to test
  22194. ** that syncs and fullsyncs are occurring at the right times.
  22195. */
  22196. SQLITE_API int sqlite3_sync_count = 0;
  22197. SQLITE_API int sqlite3_fullsync_count = 0;
  22198. #endif
  22199. /*
  22200. ** We do not trust systems to provide a working fdatasync(). Some do.
  22201. ** Others do no. To be safe, we will stick with the (slower) fsync().
  22202. ** If you know that your system does support fdatasync() correctly,
  22203. ** then simply compile with -Dfdatasync=fdatasync
  22204. */
  22205. #if !defined(fdatasync) && !defined(__linux__)
  22206. # define fdatasync fsync
  22207. #endif
  22208. /*
  22209. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  22210. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  22211. ** only available on Mac OS X. But that could change.
  22212. */
  22213. #ifdef F_FULLFSYNC
  22214. # define HAVE_FULLFSYNC 1
  22215. #else
  22216. # define HAVE_FULLFSYNC 0
  22217. #endif
  22218. /*
  22219. ** The fsync() system call does not work as advertised on many
  22220. ** unix systems. The following procedure is an attempt to make
  22221. ** it work better.
  22222. **
  22223. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  22224. ** for testing when we want to run through the test suite quickly.
  22225. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  22226. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  22227. ** or power failure will likely corrupt the database file.
  22228. **
  22229. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  22230. ** The idea behind dataOnly is that it should only write the file content
  22231. ** to disk, not the inode. We only set dataOnly if the file size is
  22232. ** unchanged since the file size is part of the inode. However,
  22233. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  22234. ** file size has changed. The only real difference between fdatasync()
  22235. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  22236. ** inode if the mtime or owner or other inode attributes have changed.
  22237. ** We only care about the file size, not the other file attributes, so
  22238. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  22239. ** So, we always use fdatasync() if it is available, regardless of
  22240. ** the value of the dataOnly flag.
  22241. */
  22242. static int full_fsync(int fd, int fullSync, int dataOnly){
  22243. int rc;
  22244. /* The following "ifdef/elif/else/" block has the same structure as
  22245. ** the one below. It is replicated here solely to avoid cluttering
  22246. ** up the real code with the UNUSED_PARAMETER() macros.
  22247. */
  22248. #ifdef SQLITE_NO_SYNC
  22249. UNUSED_PARAMETER(fd);
  22250. UNUSED_PARAMETER(fullSync);
  22251. UNUSED_PARAMETER(dataOnly);
  22252. #elif HAVE_FULLFSYNC
  22253. UNUSED_PARAMETER(dataOnly);
  22254. #else
  22255. UNUSED_PARAMETER(fullSync);
  22256. UNUSED_PARAMETER(dataOnly);
  22257. #endif
  22258. /* Record the number of times that we do a normal fsync() and
  22259. ** FULLSYNC. This is used during testing to verify that this procedure
  22260. ** gets called with the correct arguments.
  22261. */
  22262. #ifdef SQLITE_TEST
  22263. if( fullSync ) sqlite3_fullsync_count++;
  22264. sqlite3_sync_count++;
  22265. #endif
  22266. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  22267. ** no-op
  22268. */
  22269. #ifdef SQLITE_NO_SYNC
  22270. rc = SQLITE_OK;
  22271. #elif HAVE_FULLFSYNC
  22272. if( fullSync ){
  22273. rc = fcntl(fd, F_FULLFSYNC, 0);
  22274. }else{
  22275. rc = 1;
  22276. }
  22277. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  22278. ** It shouldn't be possible for fullfsync to fail on the local
  22279. ** file system (on OSX), so failure indicates that FULLFSYNC
  22280. ** isn't supported for this file system. So, attempt an fsync
  22281. ** and (for now) ignore the overhead of a superfluous fcntl call.
  22282. ** It'd be better to detect fullfsync support once and avoid
  22283. ** the fcntl call every time sync is called.
  22284. */
  22285. if( rc ) rc = fsync(fd);
  22286. #else
  22287. rc = fdatasync(fd);
  22288. #if OS_VXWORKS
  22289. if( rc==-1 && errno==ENOTSUP ){
  22290. rc = fsync(fd);
  22291. }
  22292. #endif /* OS_VXWORKS */
  22293. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  22294. if( OS_VXWORKS && rc!= -1 ){
  22295. rc = 0;
  22296. }
  22297. return rc;
  22298. }
  22299. /*
  22300. ** Make sure all writes to a particular file are committed to disk.
  22301. **
  22302. ** If dataOnly==0 then both the file itself and its metadata (file
  22303. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  22304. ** file data is synced.
  22305. **
  22306. ** Under Unix, also make sure that the directory entry for the file
  22307. ** has been created by fsync-ing the directory that contains the file.
  22308. ** If we do not do this and we encounter a power failure, the directory
  22309. ** entry for the journal might not exist after we reboot. The next
  22310. ** SQLite to access the file will not know that the journal exists (because
  22311. ** the directory entry for the journal was never created) and the transaction
  22312. ** will not roll back - possibly leading to database corruption.
  22313. */
  22314. static int unixSync(sqlite3_file *id, int flags){
  22315. int rc;
  22316. unixFile *pFile = (unixFile*)id;
  22317. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  22318. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  22319. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  22320. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  22321. || (flags&0x0F)==SQLITE_SYNC_FULL
  22322. );
  22323. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  22324. ** line is to test that doing so does not cause any problems.
  22325. */
  22326. SimulateDiskfullError( return SQLITE_FULL );
  22327. assert( pFile );
  22328. OSTRACE2("SYNC %-3d\n", pFile->h);
  22329. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  22330. SimulateIOError( rc=1 );
  22331. if( rc ){
  22332. pFile->lastErrno = errno;
  22333. return SQLITE_IOERR_FSYNC;
  22334. }
  22335. if( pFile->dirfd>=0 ){
  22336. int err;
  22337. OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
  22338. HAVE_FULLFSYNC, isFullsync);
  22339. #ifndef SQLITE_DISABLE_DIRSYNC
  22340. /* The directory sync is only attempted if full_fsync is
  22341. ** turned off or unavailable. If a full_fsync occurred above,
  22342. ** then the directory sync is superfluous.
  22343. */
  22344. if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
  22345. /*
  22346. ** We have received multiple reports of fsync() returning
  22347. ** errors when applied to directories on certain file systems.
  22348. ** A failed directory sync is not a big deal. So it seems
  22349. ** better to ignore the error. Ticket #1657
  22350. */
  22351. /* pFile->lastErrno = errno; */
  22352. /* return SQLITE_IOERR; */
  22353. }
  22354. #endif
  22355. err = close(pFile->dirfd); /* Only need to sync once, so close the */
  22356. if( err==0 ){ /* directory when we are done */
  22357. pFile->dirfd = -1;
  22358. }else{
  22359. pFile->lastErrno = errno;
  22360. rc = SQLITE_IOERR_DIR_CLOSE;
  22361. }
  22362. }
  22363. return rc;
  22364. }
  22365. /*
  22366. ** Truncate an open file to a specified size
  22367. */
  22368. static int unixTruncate(sqlite3_file *id, i64 nByte){
  22369. int rc;
  22370. assert( id );
  22371. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  22372. rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  22373. if( rc ){
  22374. ((unixFile*)id)->lastErrno = errno;
  22375. return SQLITE_IOERR_TRUNCATE;
  22376. }else{
  22377. return SQLITE_OK;
  22378. }
  22379. }
  22380. /*
  22381. ** Determine the current size of a file in bytes
  22382. */
  22383. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  22384. int rc;
  22385. struct stat buf;
  22386. assert( id );
  22387. rc = fstat(((unixFile*)id)->h, &buf);
  22388. SimulateIOError( rc=1 );
  22389. if( rc!=0 ){
  22390. ((unixFile*)id)->lastErrno = errno;
  22391. return SQLITE_IOERR_FSTAT;
  22392. }
  22393. *pSize = buf.st_size;
  22394. /* When opening a zero-size database, the findLockInfo() procedure
  22395. ** writes a single byte into that file in order to work around a bug
  22396. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  22397. ** layers, we need to report this file size as zero even though it is
  22398. ** really 1. Ticket #3260.
  22399. */
  22400. if( *pSize==1 ) *pSize = 0;
  22401. return SQLITE_OK;
  22402. }
  22403. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  22404. /*
  22405. ** Handler for proxy-locking file-control verbs. Defined below in the
  22406. ** proxying locking division.
  22407. */
  22408. static int proxyFileControl(sqlite3_file*,int,void*);
  22409. #endif
  22410. /*
  22411. ** Information and control of an open file handle.
  22412. */
  22413. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  22414. switch( op ){
  22415. case SQLITE_FCNTL_LOCKSTATE: {
  22416. *(int*)pArg = ((unixFile*)id)->locktype;
  22417. return SQLITE_OK;
  22418. }
  22419. case SQLITE_LAST_ERRNO: {
  22420. *(int*)pArg = ((unixFile*)id)->lastErrno;
  22421. return SQLITE_OK;
  22422. }
  22423. #ifndef NDEBUG
  22424. /* The pager calls this method to signal that it has done
  22425. ** a rollback and that the database is therefore unchanged and
  22426. ** it hence it is OK for the transaction change counter to be
  22427. ** unchanged.
  22428. */
  22429. case SQLITE_FCNTL_DB_UNCHANGED: {
  22430. ((unixFile*)id)->dbUpdate = 0;
  22431. return SQLITE_OK;
  22432. }
  22433. #endif
  22434. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  22435. case SQLITE_SET_LOCKPROXYFILE:
  22436. case SQLITE_GET_LOCKPROXYFILE: {
  22437. return proxyFileControl(id,op,pArg);
  22438. }
  22439. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  22440. }
  22441. return SQLITE_ERROR;
  22442. }
  22443. /*
  22444. ** Return the sector size in bytes of the underlying block device for
  22445. ** the specified file. This is almost always 512 bytes, but may be
  22446. ** larger for some devices.
  22447. **
  22448. ** SQLite code assumes this function cannot fail. It also assumes that
  22449. ** if two files are created in the same file-system directory (i.e.
  22450. ** a database and its journal file) that the sector size will be the
  22451. ** same for both.
  22452. */
  22453. static int unixSectorSize(sqlite3_file *NotUsed){
  22454. UNUSED_PARAMETER(NotUsed);
  22455. return SQLITE_DEFAULT_SECTOR_SIZE;
  22456. }
  22457. /*
  22458. ** Return the device characteristics for the file. This is always 0 for unix.
  22459. */
  22460. static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
  22461. UNUSED_PARAMETER(NotUsed);
  22462. return 0;
  22463. }
  22464. /*
  22465. ** Here ends the implementation of all sqlite3_file methods.
  22466. **
  22467. ********************** End sqlite3_file Methods *******************************
  22468. ******************************************************************************/
  22469. /*
  22470. ** This division contains definitions of sqlite3_io_methods objects that
  22471. ** implement various file locking strategies. It also contains definitions
  22472. ** of "finder" functions. A finder-function is used to locate the appropriate
  22473. ** sqlite3_io_methods object for a particular database file. The pAppData
  22474. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  22475. ** the correct finder-function for that VFS.
  22476. **
  22477. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  22478. ** object. The only interesting finder-function is autolockIoFinder, which
  22479. ** looks at the filesystem type and tries to guess the best locking
  22480. ** strategy from that.
  22481. **
  22482. ** For finder-funtion F, two objects are created:
  22483. **
  22484. ** (1) The real finder-function named "FImpt()".
  22485. **
  22486. ** (2) A constant pointer to this functio named just "F".
  22487. **
  22488. **
  22489. ** A pointer to the F pointer is used as the pAppData value for VFS
  22490. ** objects. We have to do this instead of letting pAppData point
  22491. ** directly at the finder-function since C90 rules prevent a void*
  22492. ** from be cast into a function pointer.
  22493. **
  22494. **
  22495. ** Each instance of this macro generates two objects:
  22496. **
  22497. ** * A constant sqlite3_io_methods object call METHOD that has locking
  22498. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  22499. **
  22500. ** * An I/O method finder function called FINDER that returns a pointer
  22501. ** to the METHOD object in the previous bullet.
  22502. */
  22503. #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
  22504. static const sqlite3_io_methods METHOD = { \
  22505. 1, /* iVersion */ \
  22506. CLOSE, /* xClose */ \
  22507. unixRead, /* xRead */ \
  22508. unixWrite, /* xWrite */ \
  22509. unixTruncate, /* xTruncate */ \
  22510. unixSync, /* xSync */ \
  22511. unixFileSize, /* xFileSize */ \
  22512. LOCK, /* xLock */ \
  22513. UNLOCK, /* xUnlock */ \
  22514. CKLOCK, /* xCheckReservedLock */ \
  22515. unixFileControl, /* xFileControl */ \
  22516. unixSectorSize, /* xSectorSize */ \
  22517. unixDeviceCharacteristics /* xDeviceCapabilities */ \
  22518. }; \
  22519. static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
  22520. UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
  22521. return &METHOD; \
  22522. } \
  22523. static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
  22524. = FINDER##Impl;
  22525. /*
  22526. ** Here are all of the sqlite3_io_methods objects for each of the
  22527. ** locking strategies. Functions that return pointers to these methods
  22528. ** are also created.
  22529. */
  22530. IOMETHODS(
  22531. posixIoFinder, /* Finder function name */
  22532. posixIoMethods, /* sqlite3_io_methods object name */
  22533. unixClose, /* xClose method */
  22534. unixLock, /* xLock method */
  22535. unixUnlock, /* xUnlock method */
  22536. unixCheckReservedLock /* xCheckReservedLock method */
  22537. )
  22538. IOMETHODS(
  22539. nolockIoFinder, /* Finder function name */
  22540. nolockIoMethods, /* sqlite3_io_methods object name */
  22541. nolockClose, /* xClose method */
  22542. nolockLock, /* xLock method */
  22543. nolockUnlock, /* xUnlock method */
  22544. nolockCheckReservedLock /* xCheckReservedLock method */
  22545. )
  22546. IOMETHODS(
  22547. dotlockIoFinder, /* Finder function name */
  22548. dotlockIoMethods, /* sqlite3_io_methods object name */
  22549. dotlockClose, /* xClose method */
  22550. dotlockLock, /* xLock method */
  22551. dotlockUnlock, /* xUnlock method */
  22552. dotlockCheckReservedLock /* xCheckReservedLock method */
  22553. )
  22554. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  22555. IOMETHODS(
  22556. flockIoFinder, /* Finder function name */
  22557. flockIoMethods, /* sqlite3_io_methods object name */
  22558. flockClose, /* xClose method */
  22559. flockLock, /* xLock method */
  22560. flockUnlock, /* xUnlock method */
  22561. flockCheckReservedLock /* xCheckReservedLock method */
  22562. )
  22563. #endif
  22564. #if OS_VXWORKS
  22565. IOMETHODS(
  22566. semIoFinder, /* Finder function name */
  22567. semIoMethods, /* sqlite3_io_methods object name */
  22568. semClose, /* xClose method */
  22569. semLock, /* xLock method */
  22570. semUnlock, /* xUnlock method */
  22571. semCheckReservedLock /* xCheckReservedLock method */
  22572. )
  22573. #endif
  22574. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  22575. IOMETHODS(
  22576. afpIoFinder, /* Finder function name */
  22577. afpIoMethods, /* sqlite3_io_methods object name */
  22578. afpClose, /* xClose method */
  22579. afpLock, /* xLock method */
  22580. afpUnlock, /* xUnlock method */
  22581. afpCheckReservedLock /* xCheckReservedLock method */
  22582. )
  22583. #endif
  22584. /*
  22585. ** The proxy locking method is a "super-method" in the sense that it
  22586. ** opens secondary file descriptors for the conch and lock files and
  22587. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  22588. ** secondary files. For this reason, the division that implements
  22589. ** proxy locking is located much further down in the file. But we need
  22590. ** to go ahead and define the sqlite3_io_methods and finder function
  22591. ** for proxy locking here. So we forward declare the I/O methods.
  22592. */
  22593. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  22594. static int proxyClose(sqlite3_file*);
  22595. static int proxyLock(sqlite3_file*, int);
  22596. static int proxyUnlock(sqlite3_file*, int);
  22597. static int proxyCheckReservedLock(sqlite3_file*, int*);
  22598. IOMETHODS(
  22599. proxyIoFinder, /* Finder function name */
  22600. proxyIoMethods, /* sqlite3_io_methods object name */
  22601. proxyClose, /* xClose method */
  22602. proxyLock, /* xLock method */
  22603. proxyUnlock, /* xUnlock method */
  22604. proxyCheckReservedLock /* xCheckReservedLock method */
  22605. )
  22606. #endif
  22607. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  22608. /*
  22609. ** This "finder" function attempts to determine the best locking strategy
  22610. ** for the database file "filePath". It then returns the sqlite3_io_methods
  22611. ** object that implements that strategy.
  22612. **
  22613. ** This is for MacOSX only.
  22614. */
  22615. static const sqlite3_io_methods *autolockIoFinderImpl(
  22616. const char *filePath, /* name of the database file */
  22617. int fd /* file descriptor open on the database file */
  22618. ){
  22619. static const struct Mapping {
  22620. const char *zFilesystem; /* Filesystem type name */
  22621. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  22622. } aMap[] = {
  22623. { "hfs", &posixIoMethods },
  22624. { "ufs", &posixIoMethods },
  22625. { "afpfs", &afpIoMethods },
  22626. #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
  22627. { "smbfs", &afpIoMethods },
  22628. #else
  22629. { "smbfs", &flockIoMethods },
  22630. #endif
  22631. { "webdav", &nolockIoMethods },
  22632. { 0, 0 }
  22633. };
  22634. int i;
  22635. struct statfs fsInfo;
  22636. struct flock lockInfo;
  22637. if( !filePath ){
  22638. /* If filePath==NULL that means we are dealing with a transient file
  22639. ** that does not need to be locked. */
  22640. return &nolockIoMethods;
  22641. }
  22642. if( statfs(filePath, &fsInfo) != -1 ){
  22643. if( fsInfo.f_flags & MNT_RDONLY ){
  22644. return &nolockIoMethods;
  22645. }
  22646. for(i=0; aMap[i].zFilesystem; i++){
  22647. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  22648. return aMap[i].pMethods;
  22649. }
  22650. }
  22651. }
  22652. /* Default case. Handles, amongst others, "nfs".
  22653. ** Test byte-range lock using fcntl(). If the call succeeds,
  22654. ** assume that the file-system supports POSIX style locks.
  22655. */
  22656. lockInfo.l_len = 1;
  22657. lockInfo.l_start = 0;
  22658. lockInfo.l_whence = SEEK_SET;
  22659. lockInfo.l_type = F_RDLCK;
  22660. if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
  22661. return &posixIoMethods;
  22662. }else{
  22663. return &dotlockIoMethods;
  22664. }
  22665. }
  22666. static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
  22667. = autolockIoFinderImpl;
  22668. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  22669. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  22670. /*
  22671. ** This "finder" function attempts to determine the best locking strategy
  22672. ** for the database file "filePath". It then returns the sqlite3_io_methods
  22673. ** object that implements that strategy.
  22674. **
  22675. ** This is for VXWorks only.
  22676. */
  22677. static const sqlite3_io_methods *autolockIoFinderImpl(
  22678. const char *filePath, /* name of the database file */
  22679. int fd /* file descriptor open on the database file */
  22680. ){
  22681. struct flock lockInfo;
  22682. if( !filePath ){
  22683. /* If filePath==NULL that means we are dealing with a transient file
  22684. ** that does not need to be locked. */
  22685. return &nolockIoMethods;
  22686. }
  22687. /* Test if fcntl() is supported and use POSIX style locks.
  22688. ** Otherwise fall back to the named semaphore method.
  22689. */
  22690. lockInfo.l_len = 1;
  22691. lockInfo.l_start = 0;
  22692. lockInfo.l_whence = SEEK_SET;
  22693. lockInfo.l_type = F_RDLCK;
  22694. if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
  22695. return &posixIoMethods;
  22696. }else{
  22697. return &semIoMethods;
  22698. }
  22699. }
  22700. static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
  22701. = autolockIoFinderImpl;
  22702. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  22703. /*
  22704. ** An abstract type for a pointer to a IO method finder function:
  22705. */
  22706. typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
  22707. /****************************************************************************
  22708. **************************** sqlite3_vfs methods ****************************
  22709. **
  22710. ** This division contains the implementation of methods on the
  22711. ** sqlite3_vfs object.
  22712. */
  22713. /*
  22714. ** Initialize the contents of the unixFile structure pointed to by pId.
  22715. */
  22716. static int fillInUnixFile(
  22717. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  22718. int h, /* Open file descriptor of file being opened */
  22719. int dirfd, /* Directory file descriptor */
  22720. sqlite3_file *pId, /* Write to the unixFile structure here */
  22721. const char *zFilename, /* Name of the file being opened */
  22722. int noLock, /* Omit locking if true */
  22723. int isDelete /* Delete on close if true */
  22724. ){
  22725. const sqlite3_io_methods *pLockingStyle;
  22726. unixFile *pNew = (unixFile *)pId;
  22727. int rc = SQLITE_OK;
  22728. assert( pNew->pLock==NULL );
  22729. assert( pNew->pOpen==NULL );
  22730. /* Parameter isDelete is only used on vxworks.
  22731. ** Express this explicitly here to prevent compiler warnings
  22732. ** about unused parameters.
  22733. */
  22734. #if !OS_VXWORKS
  22735. UNUSED_PARAMETER(isDelete);
  22736. #endif
  22737. OSTRACE3("OPEN %-3d %s\n", h, zFilename);
  22738. pNew->h = h;
  22739. pNew->dirfd = dirfd;
  22740. SET_THREADID(pNew);
  22741. #if OS_VXWORKS
  22742. pNew->pId = vxworksFindFileId(zFilename);
  22743. if( pNew->pId==0 ){
  22744. noLock = 1;
  22745. rc = SQLITE_NOMEM;
  22746. }
  22747. #endif
  22748. if( noLock ){
  22749. pLockingStyle = &nolockIoMethods;
  22750. }else{
  22751. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
  22752. #if SQLITE_ENABLE_LOCKING_STYLE
  22753. /* Cache zFilename in the locking context (AFP and dotlock override) for
  22754. ** proxyLock activation is possible (remote proxy is based on db name)
  22755. ** zFilename remains valid until file is closed, to support */
  22756. pNew->lockingContext = (void*)zFilename;
  22757. #endif
  22758. }
  22759. if( pLockingStyle == &posixIoMethods ){
  22760. unixEnterMutex();
  22761. rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
  22762. unixLeaveMutex();
  22763. }
  22764. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  22765. else if( pLockingStyle == &afpIoMethods ){
  22766. /* AFP locking uses the file path so it needs to be included in
  22767. ** the afpLockingContext.
  22768. */
  22769. afpLockingContext *pCtx;
  22770. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  22771. if( pCtx==0 ){
  22772. rc = SQLITE_NOMEM;
  22773. }else{
  22774. /* NB: zFilename exists and remains valid until the file is closed
  22775. ** according to requirement F11141. So we do not need to make a
  22776. ** copy of the filename. */
  22777. pCtx->dbPath = zFilename;
  22778. srandomdev();
  22779. unixEnterMutex();
  22780. rc = findLockInfo(pNew, NULL, &pNew->pOpen);
  22781. unixLeaveMutex();
  22782. }
  22783. }
  22784. #endif
  22785. else if( pLockingStyle == &dotlockIoMethods ){
  22786. /* Dotfile locking uses the file path so it needs to be included in
  22787. ** the dotlockLockingContext
  22788. */
  22789. char *zLockFile;
  22790. int nFilename;
  22791. nFilename = (int)strlen(zFilename) + 6;
  22792. zLockFile = (char *)sqlite3_malloc(nFilename);
  22793. if( zLockFile==0 ){
  22794. rc = SQLITE_NOMEM;
  22795. }else{
  22796. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  22797. }
  22798. pNew->lockingContext = zLockFile;
  22799. }
  22800. #if OS_VXWORKS
  22801. else if( pLockingStyle == &semIoMethods ){
  22802. /* Named semaphore locking uses the file path so it needs to be
  22803. ** included in the semLockingContext
  22804. */
  22805. unixEnterMutex();
  22806. rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
  22807. if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
  22808. char *zSemName = pNew->pOpen->aSemName;
  22809. int n;
  22810. sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
  22811. pNew->pId->zCanonicalName);
  22812. for( n=0; zSemName[n]; n++ )
  22813. if( zSemName[n]=='/' ) zSemName[n] = '_';
  22814. pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  22815. if( pNew->pOpen->pSem == SEM_FAILED ){
  22816. rc = SQLITE_NOMEM;
  22817. pNew->pOpen->aSemName[0] = '\0';
  22818. }
  22819. }
  22820. unixLeaveMutex();
  22821. }
  22822. #endif
  22823. pNew->lastErrno = 0;
  22824. #if OS_VXWORKS
  22825. if( rc!=SQLITE_OK ){
  22826. unlink(zFilename);
  22827. isDelete = 0;
  22828. }
  22829. pNew->isDelete = isDelete;
  22830. #endif
  22831. if( rc!=SQLITE_OK ){
  22832. if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
  22833. close(h);
  22834. }else{
  22835. pNew->pMethod = pLockingStyle;
  22836. OpenCounter(+1);
  22837. }
  22838. return rc;
  22839. }
  22840. /*
  22841. ** Open a file descriptor to the directory containing file zFilename.
  22842. ** If successful, *pFd is set to the opened file descriptor and
  22843. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  22844. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  22845. ** value.
  22846. **
  22847. ** If SQLITE_OK is returned, the caller is responsible for closing
  22848. ** the file descriptor *pFd using close().
  22849. */
  22850. static int openDirectory(const char *zFilename, int *pFd){
  22851. int ii;
  22852. int fd = -1;
  22853. char zDirname[MAX_PATHNAME+1];
  22854. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  22855. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  22856. if( ii>0 ){
  22857. zDirname[ii] = '\0';
  22858. fd = open(zDirname, O_RDONLY|O_BINARY, 0);
  22859. if( fd>=0 ){
  22860. #ifdef FD_CLOEXEC
  22861. fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  22862. #endif
  22863. OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
  22864. }
  22865. }
  22866. *pFd = fd;
  22867. return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
  22868. }
  22869. /*
  22870. ** Create a temporary file name in zBuf. zBuf must be allocated
  22871. ** by the calling process and must be big enough to hold at least
  22872. ** pVfs->mxPathname bytes.
  22873. */
  22874. static int getTempname(int nBuf, char *zBuf){
  22875. static const char *azDirs[] = {
  22876. 0,
  22877. 0,
  22878. "/var/tmp",
  22879. "/usr/tmp",
  22880. "/tmp",
  22881. ".",
  22882. };
  22883. static const unsigned char zChars[] =
  22884. "abcdefghijklmnopqrstuvwxyz"
  22885. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  22886. "0123456789";
  22887. unsigned int i, j;
  22888. struct stat buf;
  22889. const char *zDir = ".";
  22890. /* It's odd to simulate an io-error here, but really this is just
  22891. ** using the io-error infrastructure to test that SQLite handles this
  22892. ** function failing.
  22893. */
  22894. SimulateIOError( return SQLITE_IOERR );
  22895. azDirs[0] = sqlite3_temp_directory;
  22896. if (NULL == azDirs[1]) {
  22897. azDirs[1] = getenv("TMPDIR");
  22898. }
  22899. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
  22900. if( azDirs[i]==0 ) continue;
  22901. if( stat(azDirs[i], &buf) ) continue;
  22902. if( !S_ISDIR(buf.st_mode) ) continue;
  22903. if( access(azDirs[i], 07) ) continue;
  22904. zDir = azDirs[i];
  22905. break;
  22906. }
  22907. /* Check that the output buffer is large enough for the temporary file
  22908. ** name. If it is not, return SQLITE_ERROR.
  22909. */
  22910. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
  22911. return SQLITE_ERROR;
  22912. }
  22913. do{
  22914. sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  22915. j = (int)strlen(zBuf);
  22916. sqlite3_randomness(15, &zBuf[j]);
  22917. for(i=0; i<15; i++, j++){
  22918. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  22919. }
  22920. zBuf[j] = 0;
  22921. }while( access(zBuf,0)==0 );
  22922. return SQLITE_OK;
  22923. }
  22924. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  22925. /*
  22926. ** Routine to transform a unixFile into a proxy-locking unixFile.
  22927. ** Implementation in the proxy-lock division, but used by unixOpen()
  22928. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  22929. */
  22930. static int proxyTransformUnixFile(unixFile*, const char*);
  22931. #endif
  22932. /*
  22933. ** Open the file zPath.
  22934. **
  22935. ** Previously, the SQLite OS layer used three functions in place of this
  22936. ** one:
  22937. **
  22938. ** sqlite3OsOpenReadWrite();
  22939. ** sqlite3OsOpenReadOnly();
  22940. ** sqlite3OsOpenExclusive();
  22941. **
  22942. ** These calls correspond to the following combinations of flags:
  22943. **
  22944. ** ReadWrite() -> (READWRITE | CREATE)
  22945. ** ReadOnly() -> (READONLY)
  22946. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  22947. **
  22948. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  22949. ** true, the file was configured to be automatically deleted when the
  22950. ** file handle closed. To achieve the same effect using this new
  22951. ** interface, add the DELETEONCLOSE flag to those specified above for
  22952. ** OpenExclusive().
  22953. */
  22954. static int unixOpen(
  22955. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  22956. const char *zPath, /* Pathname of file to be opened */
  22957. sqlite3_file *pFile, /* The file descriptor to be filled in */
  22958. int flags, /* Input flags to control the opening */
  22959. int *pOutFlags /* Output flags returned to SQLite core */
  22960. ){
  22961. int fd = -1; /* File descriptor returned by open() */
  22962. int dirfd = -1; /* Directory file descriptor */
  22963. int openFlags = 0; /* Flags to pass to open() */
  22964. int eType = flags&0xFFFFFF00; /* Type of file to open */
  22965. int noLock; /* True to omit locking primitives */
  22966. int rc = SQLITE_OK;
  22967. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  22968. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  22969. int isCreate = (flags & SQLITE_OPEN_CREATE);
  22970. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  22971. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  22972. /* If creating a master or main-file journal, this function will open
  22973. ** a file-descriptor on the directory too. The first time unixSync()
  22974. ** is called the directory file descriptor will be fsync()ed and close()d.
  22975. */
  22976. int isOpenDirectory = (isCreate &&
  22977. (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
  22978. );
  22979. /* If argument zPath is a NULL pointer, this function is required to open
  22980. ** a temporary file. Use this buffer to store the file name in.
  22981. */
  22982. char zTmpname[MAX_PATHNAME+1];
  22983. const char *zName = zPath;
  22984. /* Check the following statements are true:
  22985. **
  22986. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  22987. ** (b) if CREATE is set, then READWRITE must also be set, and
  22988. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  22989. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  22990. */
  22991. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  22992. assert(isCreate==0 || isReadWrite);
  22993. assert(isExclusive==0 || isCreate);
  22994. assert(isDelete==0 || isCreate);
  22995. /* The main DB, main journal, and master journal are never automatically
  22996. ** deleted
  22997. */
  22998. assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
  22999. assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
  23000. assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
  23001. /* Assert that the upper layer has set one of the "file-type" flags. */
  23002. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  23003. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  23004. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  23005. || eType==SQLITE_OPEN_TRANSIENT_DB
  23006. );
  23007. memset(pFile, 0, sizeof(unixFile));
  23008. if( !zName ){
  23009. assert(isDelete && !isOpenDirectory);
  23010. rc = getTempname(MAX_PATHNAME+1, zTmpname);
  23011. if( rc!=SQLITE_OK ){
  23012. return rc;
  23013. }
  23014. zName = zTmpname;
  23015. }
  23016. if( isReadonly ) openFlags |= O_RDONLY;
  23017. if( isReadWrite ) openFlags |= O_RDWR;
  23018. if( isCreate ) openFlags |= O_CREAT;
  23019. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  23020. openFlags |= (O_LARGEFILE|O_BINARY);
  23021. fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
  23022. OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
  23023. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  23024. /* Failed to open the file for read/write access. Try read-only. */
  23025. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  23026. flags |= SQLITE_OPEN_READONLY;
  23027. return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
  23028. }
  23029. if( fd<0 ){
  23030. return SQLITE_CANTOPEN;
  23031. }
  23032. if( isDelete ){
  23033. #if OS_VXWORKS
  23034. zPath = zName;
  23035. #else
  23036. unlink(zName);
  23037. #endif
  23038. }
  23039. #if SQLITE_ENABLE_LOCKING_STYLE
  23040. else{
  23041. ((unixFile*)pFile)->openFlags = openFlags;
  23042. }
  23043. #endif
  23044. if( pOutFlags ){
  23045. *pOutFlags = flags;
  23046. }
  23047. #ifndef NDEBUG
  23048. if( (flags & SQLITE_OPEN_MAIN_DB)!=0 ){
  23049. ((unixFile*)pFile)->isLockable = 1;
  23050. }
  23051. #endif
  23052. assert( fd>=0 );
  23053. if( isOpenDirectory ){
  23054. rc = openDirectory(zPath, &dirfd);
  23055. if( rc!=SQLITE_OK ){
  23056. close(fd); /* silently leak if fail, already in error */
  23057. return rc;
  23058. }
  23059. }
  23060. #ifdef FD_CLOEXEC
  23061. fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  23062. #endif
  23063. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  23064. #if SQLITE_PREFER_PROXY_LOCKING
  23065. if( zPath!=NULL && !noLock ){
  23066. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  23067. int useProxy = 0;
  23068. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
  23069. ** 0 means never use proxy, NULL means use proxy for non-local files only
  23070. */
  23071. if( envforce!=NULL ){
  23072. useProxy = atoi(envforce)>0;
  23073. }else{
  23074. struct statfs fsInfo;
  23075. if( statfs(zPath, &fsInfo) == -1 ){
  23076. ((unixFile*)pFile)->lastErrno = errno;
  23077. if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
  23078. close(fd); /* silently leak if fail, in error */
  23079. return SQLITE_IOERR_ACCESS;
  23080. }
  23081. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  23082. }
  23083. if( useProxy ){
  23084. rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
  23085. if( rc==SQLITE_OK ){
  23086. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  23087. }
  23088. return rc;
  23089. }
  23090. }
  23091. #endif
  23092. return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
  23093. }
  23094. /*
  23095. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  23096. ** the directory after deleting the file.
  23097. */
  23098. static int unixDelete(
  23099. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  23100. const char *zPath, /* Name of file to be deleted */
  23101. int dirSync /* If true, fsync() directory after deleting file */
  23102. ){
  23103. int rc = SQLITE_OK;
  23104. UNUSED_PARAMETER(NotUsed);
  23105. SimulateIOError(return SQLITE_IOERR_DELETE);
  23106. unlink(zPath);
  23107. #ifndef SQLITE_DISABLE_DIRSYNC
  23108. if( dirSync ){
  23109. int fd;
  23110. rc = openDirectory(zPath, &fd);
  23111. if( rc==SQLITE_OK ){
  23112. #if OS_VXWORKS
  23113. if( fsync(fd)==-1 )
  23114. #else
  23115. if( fsync(fd) )
  23116. #endif
  23117. {
  23118. rc = SQLITE_IOERR_DIR_FSYNC;
  23119. }
  23120. if( close(fd)&&!rc ){
  23121. rc = SQLITE_IOERR_DIR_CLOSE;
  23122. }
  23123. }
  23124. }
  23125. #endif
  23126. return rc;
  23127. }
  23128. /*
  23129. ** Test the existance of or access permissions of file zPath. The
  23130. ** test performed depends on the value of flags:
  23131. **
  23132. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  23133. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  23134. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  23135. **
  23136. ** Otherwise return 0.
  23137. */
  23138. static int unixAccess(
  23139. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  23140. const char *zPath, /* Path of the file to examine */
  23141. int flags, /* What do we want to learn about the zPath file? */
  23142. int *pResOut /* Write result boolean here */
  23143. ){
  23144. int amode = 0;
  23145. UNUSED_PARAMETER(NotUsed);
  23146. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  23147. switch( flags ){
  23148. case SQLITE_ACCESS_EXISTS:
  23149. amode = F_OK;
  23150. break;
  23151. case SQLITE_ACCESS_READWRITE:
  23152. amode = W_OK|R_OK;
  23153. break;
  23154. case SQLITE_ACCESS_READ:
  23155. amode = R_OK;
  23156. break;
  23157. default:
  23158. assert(!"Invalid flags argument");
  23159. }
  23160. *pResOut = (access(zPath, amode)==0);
  23161. return SQLITE_OK;
  23162. }
  23163. /*
  23164. ** Turn a relative pathname into a full pathname. The relative path
  23165. ** is stored as a nul-terminated string in the buffer pointed to by
  23166. ** zPath.
  23167. **
  23168. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  23169. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  23170. ** this buffer before returning.
  23171. */
  23172. static int unixFullPathname(
  23173. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  23174. const char *zPath, /* Possibly relative input path */
  23175. int nOut, /* Size of output buffer in bytes */
  23176. char *zOut /* Output buffer */
  23177. ){
  23178. /* It's odd to simulate an io-error here, but really this is just
  23179. ** using the io-error infrastructure to test that SQLite handles this
  23180. ** function failing. This function could fail if, for example, the
  23181. ** current working directory has been unlinked.
  23182. */
  23183. SimulateIOError( return SQLITE_ERROR );
  23184. assert( pVfs->mxPathname==MAX_PATHNAME );
  23185. UNUSED_PARAMETER(pVfs);
  23186. zOut[nOut-1] = '\0';
  23187. if( zPath[0]=='/' ){
  23188. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  23189. }else{
  23190. int nCwd;
  23191. if( getcwd(zOut, nOut-1)==0 ){
  23192. return SQLITE_CANTOPEN;
  23193. }
  23194. nCwd = (int)strlen(zOut);
  23195. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  23196. }
  23197. return SQLITE_OK;
  23198. }
  23199. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  23200. /*
  23201. ** Interfaces for opening a shared library, finding entry points
  23202. ** within the shared library, and closing the shared library.
  23203. */
  23204. #include <dlfcn.h>
  23205. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  23206. UNUSED_PARAMETER(NotUsed);
  23207. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  23208. }
  23209. /*
  23210. ** SQLite calls this function immediately after a call to unixDlSym() or
  23211. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  23212. ** message is available, it is written to zBufOut. If no error message
  23213. ** is available, zBufOut is left unmodified and SQLite uses a default
  23214. ** error message.
  23215. */
  23216. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  23217. char *zErr;
  23218. UNUSED_PARAMETER(NotUsed);
  23219. unixEnterMutex();
  23220. zErr = dlerror();
  23221. if( zErr ){
  23222. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  23223. }
  23224. unixLeaveMutex();
  23225. }
  23226. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  23227. /*
  23228. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  23229. ** cast into a pointer to a function. And yet the library dlsym() routine
  23230. ** returns a void* which is really a pointer to a function. So how do we
  23231. ** use dlsym() with -pedantic-errors?
  23232. **
  23233. ** Variable x below is defined to be a pointer to a function taking
  23234. ** parameters void* and const char* and returning a pointer to a function.
  23235. ** We initialize x by assigning it a pointer to the dlsym() function.
  23236. ** (That assignment requires a cast.) Then we call the function that
  23237. ** x points to.
  23238. **
  23239. ** This work-around is unlikely to work correctly on any system where
  23240. ** you really cannot cast a function pointer into void*. But then, on the
  23241. ** other hand, dlsym() will not work on such a system either, so we have
  23242. ** not really lost anything.
  23243. */
  23244. void (*(*x)(void*,const char*))(void);
  23245. UNUSED_PARAMETER(NotUsed);
  23246. x = (void(*(*)(void*,const char*))(void))dlsym;
  23247. return (*x)(p, zSym);
  23248. }
  23249. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  23250. UNUSED_PARAMETER(NotUsed);
  23251. dlclose(pHandle);
  23252. }
  23253. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  23254. #define unixDlOpen 0
  23255. #define unixDlError 0
  23256. #define unixDlSym 0
  23257. #define unixDlClose 0
  23258. #endif
  23259. /*
  23260. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  23261. */
  23262. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  23263. UNUSED_PARAMETER(NotUsed);
  23264. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  23265. /* We have to initialize zBuf to prevent valgrind from reporting
  23266. ** errors. The reports issued by valgrind are incorrect - we would
  23267. ** prefer that the randomness be increased by making use of the
  23268. ** uninitialized space in zBuf - but valgrind errors tend to worry
  23269. ** some users. Rather than argue, it seems easier just to initialize
  23270. ** the whole array and silence valgrind, even if that means less randomness
  23271. ** in the random seed.
  23272. **
  23273. ** When testing, initializing zBuf[] to zero is all we do. That means
  23274. ** that we always use the same random number sequence. This makes the
  23275. ** tests repeatable.
  23276. */
  23277. memset(zBuf, 0, nBuf);
  23278. #if !defined(SQLITE_TEST)
  23279. {
  23280. int pid, fd;
  23281. fd = open("/dev/urandom", O_RDONLY);
  23282. if( fd<0 ){
  23283. time_t t;
  23284. time(&t);
  23285. memcpy(zBuf, &t, sizeof(t));
  23286. pid = getpid();
  23287. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  23288. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  23289. nBuf = sizeof(t) + sizeof(pid);
  23290. }else{
  23291. nBuf = read(fd, zBuf, nBuf);
  23292. close(fd);
  23293. }
  23294. }
  23295. #endif
  23296. return nBuf;
  23297. }
  23298. /*
  23299. ** Sleep for a little while. Return the amount of time slept.
  23300. ** The argument is the number of microseconds we want to sleep.
  23301. ** The return value is the number of microseconds of sleep actually
  23302. ** requested from the underlying operating system, a number which
  23303. ** might be greater than or equal to the argument, but not less
  23304. ** than the argument.
  23305. */
  23306. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  23307. #if OS_VXWORKS
  23308. struct timespec sp;
  23309. sp.tv_sec = microseconds / 1000000;
  23310. sp.tv_nsec = (microseconds % 1000000) * 1000;
  23311. nanosleep(&sp, NULL);
  23312. UNUSED_PARAMETER(NotUsed);
  23313. return microseconds;
  23314. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  23315. usleep(microseconds);
  23316. UNUSED_PARAMETER(NotUsed);
  23317. return microseconds;
  23318. #else
  23319. int seconds = (microseconds+999999)/1000000;
  23320. sleep(seconds);
  23321. UNUSED_PARAMETER(NotUsed);
  23322. return seconds*1000000;
  23323. #endif
  23324. }
  23325. /*
  23326. ** The following variable, if set to a non-zero value, is interpreted as
  23327. ** the number of seconds since 1970 and is used to set the result of
  23328. ** sqlite3OsCurrentTime() during testing.
  23329. */
  23330. #ifdef SQLITE_TEST
  23331. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  23332. #endif
  23333. /*
  23334. ** Find the current time (in Universal Coordinated Time). Write the
  23335. ** current time and date as a Julian Day number into *prNow and
  23336. ** return 0. Return 1 if the time and date cannot be found.
  23337. */
  23338. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  23339. #if defined(NO_GETTOD)
  23340. time_t t;
  23341. time(&t);
  23342. *prNow = t/86400.0 + 2440587.5;
  23343. #elif OS_VXWORKS
  23344. struct timespec sNow;
  23345. clock_gettime(CLOCK_REALTIME, &sNow);
  23346. *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
  23347. #else
  23348. struct timeval sNow;
  23349. gettimeofday(&sNow, 0);
  23350. *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
  23351. #endif
  23352. #ifdef SQLITE_TEST
  23353. if( sqlite3_current_time ){
  23354. *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  23355. }
  23356. #endif
  23357. UNUSED_PARAMETER(NotUsed);
  23358. return 0;
  23359. }
  23360. /*
  23361. ** We added the xGetLastError() method with the intention of providing
  23362. ** better low-level error messages when operating-system problems come up
  23363. ** during SQLite operation. But so far, none of that has been implemented
  23364. ** in the core. So this routine is never called. For now, it is merely
  23365. ** a place-holder.
  23366. */
  23367. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  23368. UNUSED_PARAMETER(NotUsed);
  23369. UNUSED_PARAMETER(NotUsed2);
  23370. UNUSED_PARAMETER(NotUsed3);
  23371. return 0;
  23372. }
  23373. /*
  23374. ************************ End of sqlite3_vfs methods ***************************
  23375. ******************************************************************************/
  23376. /******************************************************************************
  23377. ************************** Begin Proxy Locking ********************************
  23378. **
  23379. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  23380. ** other locking methods on secondary lock files. Proxy locking is a
  23381. ** meta-layer over top of the primitive locking implemented above. For
  23382. ** this reason, the division that implements of proxy locking is deferred
  23383. ** until late in the file (here) after all of the other I/O methods have
  23384. ** been defined - so that the primitive locking methods are available
  23385. ** as services to help with the implementation of proxy locking.
  23386. **
  23387. ****
  23388. **
  23389. ** The default locking schemes in SQLite use byte-range locks on the
  23390. ** database file to coordinate safe, concurrent access by multiple readers
  23391. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  23392. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  23393. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  23394. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  23395. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  23396. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  23397. ** address in the shared range is taken for a SHARED lock, the entire
  23398. ** shared range is taken for an EXCLUSIVE lock):
  23399. **
  23400. ** PENDING_BYTE 0x40000000
  23401. ** RESERVED_BYTE 0x40000001
  23402. ** SHARED_RANGE 0x40000002 -> 0x40000200
  23403. **
  23404. ** This works well on the local file system, but shows a nearly 100x
  23405. ** slowdown in read performance on AFP because the AFP client disables
  23406. ** the read cache when byte-range locks are present. Enabling the read
  23407. ** cache exposes a cache coherency problem that is present on all OS X
  23408. ** supported network file systems. NFS and AFP both observe the
  23409. ** close-to-open semantics for ensuring cache coherency
  23410. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  23411. ** address the requirements for concurrent database access by multiple
  23412. ** readers and writers
  23413. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  23414. **
  23415. ** To address the performance and cache coherency issues, proxy file locking
  23416. ** changes the way database access is controlled by limiting access to a
  23417. ** single host at a time and moving file locks off of the database file
  23418. ** and onto a proxy file on the local file system.
  23419. **
  23420. **
  23421. ** Using proxy locks
  23422. ** -----------------
  23423. **
  23424. ** C APIs
  23425. **
  23426. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  23427. ** <proxy_path> | ":auto:");
  23428. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  23429. **
  23430. **
  23431. ** SQL pragmas
  23432. **
  23433. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  23434. ** PRAGMA [database.]lock_proxy_file
  23435. **
  23436. ** Specifying ":auto:" means that if there is a conch file with a matching
  23437. ** host ID in it, the proxy path in the conch file will be used, otherwise
  23438. ** a proxy path based on the user's temp dir
  23439. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  23440. ** actual proxy file name is generated from the name and path of the
  23441. ** database file. For example:
  23442. **
  23443. ** For database path "/Users/me/foo.db"
  23444. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  23445. **
  23446. ** Once a lock proxy is configured for a database connection, it can not
  23447. ** be removed, however it may be switched to a different proxy path via
  23448. ** the above APIs (assuming the conch file is not being held by another
  23449. ** connection or process).
  23450. **
  23451. **
  23452. ** How proxy locking works
  23453. ** -----------------------
  23454. **
  23455. ** Proxy file locking relies primarily on two new supporting files:
  23456. **
  23457. ** * conch file to limit access to the database file to a single host
  23458. ** at a time
  23459. **
  23460. ** * proxy file to act as a proxy for the advisory locks normally
  23461. ** taken on the database
  23462. **
  23463. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  23464. ** by taking an sqlite-style shared lock on the conch file, reading the
  23465. ** contents and comparing the host's unique host ID (see below) and lock
  23466. ** proxy path against the values stored in the conch. The conch file is
  23467. ** stored in the same directory as the database file and the file name
  23468. ** is patterned after the database file name as ".<databasename>-conch".
  23469. ** If the conch file does not exist, or it's contents do not match the
  23470. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  23471. ** lock and the conch file contents is updated with the host ID and proxy
  23472. ** path and the lock is downgraded to a shared lock again. If the conch
  23473. ** is held by another process (with a shared lock), the exclusive lock
  23474. ** will fail and SQLITE_BUSY is returned.
  23475. **
  23476. ** The proxy file - a single-byte file used for all advisory file locks
  23477. ** normally taken on the database file. This allows for safe sharing
  23478. ** of the database file for multiple readers and writers on the same
  23479. ** host (the conch ensures that they all use the same local lock file).
  23480. **
  23481. ** There is a third file - the host ID file - used as a persistent record
  23482. ** of a unique identifier for the host, a 128-byte unique host id file
  23483. ** in the path defined by the HOSTIDPATH macro (default value is
  23484. ** /Library/Caches/.com.apple.sqliteConchHostId).
  23485. **
  23486. ** Requesting the lock proxy does not immediately take the conch, it is
  23487. ** only taken when the first request to lock database file is made.
  23488. ** This matches the semantics of the traditional locking behavior, where
  23489. ** opening a connection to a database file does not take a lock on it.
  23490. ** The shared lock and an open file descriptor are maintained until
  23491. ** the connection to the database is closed.
  23492. **
  23493. ** The proxy file and the lock file are never deleted so they only need
  23494. ** to be created the first time they are used.
  23495. **
  23496. ** Configuration options
  23497. ** ---------------------
  23498. **
  23499. ** SQLITE_PREFER_PROXY_LOCKING
  23500. **
  23501. ** Database files accessed on non-local file systems are
  23502. ** automatically configured for proxy locking, lock files are
  23503. ** named automatically using the same logic as
  23504. ** PRAGMA lock_proxy_file=":auto:"
  23505. **
  23506. ** SQLITE_PROXY_DEBUG
  23507. **
  23508. ** Enables the logging of error messages during host id file
  23509. ** retrieval and creation
  23510. **
  23511. ** HOSTIDPATH
  23512. **
  23513. ** Overrides the default host ID file path location
  23514. **
  23515. ** LOCKPROXYDIR
  23516. **
  23517. ** Overrides the default directory used for lock proxy files that
  23518. ** are named automatically via the ":auto:" setting
  23519. **
  23520. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  23521. **
  23522. ** Permissions to use when creating a directory for storing the
  23523. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  23524. **
  23525. **
  23526. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  23527. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  23528. ** force proxy locking to be used for every database file opened, and 0
  23529. ** will force automatic proxy locking to be disabled for all database
  23530. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  23531. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  23532. */
  23533. /*
  23534. ** Proxy locking is only available on MacOSX
  23535. */
  23536. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23537. #ifdef SQLITE_TEST
  23538. /* simulate multiple hosts by creating unique hostid file paths */
  23539. SQLITE_API int sqlite3_hostid_num = 0;
  23540. #endif
  23541. /*
  23542. ** The proxyLockingContext has the path and file structures for the remote
  23543. ** and local proxy files in it
  23544. */
  23545. typedef struct proxyLockingContext proxyLockingContext;
  23546. struct proxyLockingContext {
  23547. unixFile *conchFile; /* Open conch file */
  23548. char *conchFilePath; /* Name of the conch file */
  23549. unixFile *lockProxy; /* Open proxy lock file */
  23550. char *lockProxyPath; /* Name of the proxy lock file */
  23551. char *dbPath; /* Name of the open file */
  23552. int conchHeld; /* True if the conch is currently held */
  23553. void *oldLockingContext; /* Original lockingcontext to restore on close */
  23554. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  23555. };
  23556. /* HOSTIDLEN and CONCHLEN both include space for the string
  23557. ** terminating nul
  23558. */
  23559. #define HOSTIDLEN 128
  23560. #define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
  23561. #ifndef HOSTIDPATH
  23562. # define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
  23563. #endif
  23564. /* basically a copy of unixRandomness with different
  23565. ** test behavior built in */
  23566. static int proxyGenerateHostID(char *pHostID){
  23567. int pid, fd, len;
  23568. unsigned char *key = (unsigned char *)pHostID;
  23569. memset(key, 0, HOSTIDLEN);
  23570. len = 0;
  23571. fd = open("/dev/urandom", O_RDONLY);
  23572. if( fd>=0 ){
  23573. len = read(fd, key, HOSTIDLEN);
  23574. close(fd); /* silently leak the fd if it fails */
  23575. }
  23576. if( len < HOSTIDLEN ){
  23577. time_t t;
  23578. time(&t);
  23579. memcpy(key, &t, sizeof(t));
  23580. pid = getpid();
  23581. memcpy(&key[sizeof(t)], &pid, sizeof(pid));
  23582. }
  23583. #ifdef MAKE_PRETTY_HOSTID
  23584. {
  23585. int i;
  23586. /* filter the bytes into printable ascii characters and NUL terminate */
  23587. key[(HOSTIDLEN-1)] = 0x00;
  23588. for( i=0; i<(HOSTIDLEN-1); i++ ){
  23589. unsigned char pa = key[i]&0x7F;
  23590. if( pa<0x20 ){
  23591. key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
  23592. }else if( pa==0x7F ){
  23593. key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
  23594. }
  23595. }
  23596. }
  23597. #endif
  23598. return SQLITE_OK;
  23599. }
  23600. /* writes the host id path to path, path should be an pre-allocated buffer
  23601. ** with enough space for a path
  23602. */
  23603. static void proxyGetHostIDPath(char *path, size_t len){
  23604. strlcpy(path, HOSTIDPATH, len);
  23605. #ifdef SQLITE_TEST
  23606. if( sqlite3_hostid_num>0 ){
  23607. char suffix[2] = "1";
  23608. suffix[0] = suffix[0] + sqlite3_hostid_num;
  23609. strlcat(path, suffix, len);
  23610. }
  23611. #endif
  23612. OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
  23613. }
  23614. /* get the host ID from a sqlite hostid file stored in the
  23615. ** user-specific tmp directory, create the ID if it's not there already
  23616. */
  23617. static int proxyGetHostID(char *pHostID, int *pError){
  23618. int fd;
  23619. char path[MAXPATHLEN];
  23620. size_t len;
  23621. int rc=SQLITE_OK;
  23622. proxyGetHostIDPath(path, MAXPATHLEN);
  23623. /* try to create the host ID file, if it already exists read the contents */
  23624. fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
  23625. if( fd<0 ){
  23626. int err=errno;
  23627. if( err!=EEXIST ){
  23628. #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
  23629. fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
  23630. path, strerror(err));
  23631. #endif
  23632. return SQLITE_PERM;
  23633. }
  23634. /* couldn't create the file, read it instead */
  23635. fd = open(path, O_RDONLY|O_EXCL);
  23636. if( fd<0 ){
  23637. #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
  23638. int err = errno;
  23639. fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
  23640. path, strerror(err));
  23641. #endif
  23642. return SQLITE_PERM;
  23643. }
  23644. len = pread(fd, pHostID, HOSTIDLEN, 0);
  23645. if( len<0 ){
  23646. *pError = errno;
  23647. rc = SQLITE_IOERR_READ;
  23648. }else if( len<HOSTIDLEN ){
  23649. *pError = 0;
  23650. rc = SQLITE_IOERR_SHORT_READ;
  23651. }
  23652. close(fd); /* silently leak the fd if it fails */
  23653. OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
  23654. return rc;
  23655. }else{
  23656. /* we're creating the host ID file (use a random string of bytes) */
  23657. proxyGenerateHostID(pHostID);
  23658. len = pwrite(fd, pHostID, HOSTIDLEN, 0);
  23659. if( len<0 ){
  23660. *pError = errno;
  23661. rc = SQLITE_IOERR_WRITE;
  23662. }else if( len<HOSTIDLEN ){
  23663. *pError = 0;
  23664. rc = SQLITE_IOERR_WRITE;
  23665. }
  23666. close(fd); /* silently leak the fd if it fails */
  23667. OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
  23668. return rc;
  23669. }
  23670. }
  23671. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  23672. int len;
  23673. int dbLen;
  23674. int i;
  23675. #ifdef LOCKPROXYDIR
  23676. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  23677. #else
  23678. # ifdef _CS_DARWIN_USER_TEMP_DIR
  23679. {
  23680. confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
  23681. len = strlcat(lPath, "sqliteplocks", maxLen);
  23682. if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  23683. /* if mkdir fails, handle as lock file creation failure */
  23684. int err = errno;
  23685. # ifdef SQLITE_DEBUG
  23686. if( err!=EEXIST ){
  23687. fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
  23688. SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
  23689. }
  23690. # endif
  23691. }else{
  23692. OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
  23693. }
  23694. }
  23695. # else
  23696. len = strlcpy(lPath, "/tmp/", maxLen);
  23697. # endif
  23698. #endif
  23699. if( lPath[len-1]!='/' ){
  23700. len = strlcat(lPath, "/", maxLen);
  23701. }
  23702. /* transform the db path to a unique cache name */
  23703. dbLen = (int)strlen(dbPath);
  23704. for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
  23705. char c = dbPath[i];
  23706. lPath[i+len] = (c=='/')?'_':c;
  23707. }
  23708. lPath[i+len]='\0';
  23709. strlcat(lPath, ":auto:", maxLen);
  23710. return SQLITE_OK;
  23711. }
  23712. /*
  23713. ** Create a new VFS file descriptor (stored in memory obtained from
  23714. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  23715. **
  23716. ** The caller is responsible not only for closing the file descriptor
  23717. ** but also for freeing the memory associated with the file descriptor.
  23718. */
  23719. static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
  23720. int fd;
  23721. int dirfd = -1;
  23722. unixFile *pNew;
  23723. int rc = SQLITE_OK;
  23724. sqlite3_vfs dummyVfs;
  23725. fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
  23726. if( fd<0 ){
  23727. return SQLITE_CANTOPEN;
  23728. }
  23729. pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
  23730. if( pNew==NULL ){
  23731. rc = SQLITE_NOMEM;
  23732. goto end_create_proxy;
  23733. }
  23734. memset(pNew, 0, sizeof(unixFile));
  23735. dummyVfs.pAppData = (void*)&autolockIoFinder;
  23736. rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
  23737. if( rc==SQLITE_OK ){
  23738. *ppFile = pNew;
  23739. return SQLITE_OK;
  23740. }
  23741. end_create_proxy:
  23742. close(fd); /* silently leak fd if error, we're already in error */
  23743. sqlite3_free(pNew);
  23744. return rc;
  23745. }
  23746. /* takes the conch by taking a shared lock and read the contents conch, if
  23747. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  23748. ** lockPath means that the lockPath in the conch file will be used if the
  23749. ** host IDs match, or a new lock path will be generated automatically
  23750. ** and written to the conch file.
  23751. */
  23752. static int proxyTakeConch(unixFile *pFile){
  23753. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  23754. if( pCtx->conchHeld>0 ){
  23755. return SQLITE_OK;
  23756. }else{
  23757. unixFile *conchFile = pCtx->conchFile;
  23758. char testValue[CONCHLEN];
  23759. char conchValue[CONCHLEN];
  23760. char lockPath[MAXPATHLEN];
  23761. char *tLockPath = NULL;
  23762. int rc = SQLITE_OK;
  23763. int readRc = SQLITE_OK;
  23764. int syncPerms = 0;
  23765. OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  23766. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
  23767. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  23768. if( rc==SQLITE_OK ){
  23769. int pError = 0;
  23770. memset(testValue, 0, CONCHLEN); /* conch is fixed size */
  23771. rc = proxyGetHostID(testValue, &pError);
  23772. if( (rc&0xff)==SQLITE_IOERR ){
  23773. pFile->lastErrno = pError;
  23774. }
  23775. if( pCtx->lockProxyPath ){
  23776. strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
  23777. }
  23778. }
  23779. if( rc!=SQLITE_OK ){
  23780. goto end_takeconch;
  23781. }
  23782. readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
  23783. if( readRc!=SQLITE_IOERR_SHORT_READ ){
  23784. if( readRc!=SQLITE_OK ){
  23785. if( (rc&0xff)==SQLITE_IOERR ){
  23786. pFile->lastErrno = conchFile->lastErrno;
  23787. }
  23788. rc = readRc;
  23789. goto end_takeconch;
  23790. }
  23791. /* if the conch has data compare the contents */
  23792. if( !pCtx->lockProxyPath ){
  23793. /* for auto-named local lock file, just check the host ID and we'll
  23794. ** use the local lock file path that's already in there */
  23795. if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
  23796. tLockPath = (char *)&conchValue[HOSTIDLEN];
  23797. goto end_takeconch;
  23798. }
  23799. }else{
  23800. /* we've got the conch if conchValue matches our path and host ID */
  23801. if( !memcmp(testValue, conchValue, CONCHLEN) ){
  23802. goto end_takeconch;
  23803. }
  23804. }
  23805. }else{
  23806. /* a short read means we're "creating" the conch (even though it could
  23807. ** have been user-intervention), if we acquire the exclusive lock,
  23808. ** we'll try to match the current on-disk permissions of the database
  23809. */
  23810. syncPerms = 1;
  23811. }
  23812. /* either conch was emtpy or didn't match */
  23813. if( !pCtx->lockProxyPath ){
  23814. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  23815. tLockPath = lockPath;
  23816. strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
  23817. }
  23818. /* update conch with host and path (this will fail if other process
  23819. ** has a shared lock already) */
  23820. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  23821. if( rc==SQLITE_OK ){
  23822. rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
  23823. if( rc==SQLITE_OK && syncPerms ){
  23824. struct stat buf;
  23825. int err = fstat(pFile->h, &buf);
  23826. if( err==0 ){
  23827. /* try to match the database file permissions, ignore failure */
  23828. #ifndef SQLITE_PROXY_DEBUG
  23829. fchmod(conchFile->h, buf.st_mode);
  23830. #else
  23831. if( fchmod(conchFile->h, buf.st_mode)!=0 ){
  23832. int code = errno;
  23833. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  23834. buf.st_mode, code, strerror(code));
  23835. } else {
  23836. fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
  23837. }
  23838. }else{
  23839. int code = errno;
  23840. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  23841. err, code, strerror(code));
  23842. #endif
  23843. }
  23844. }
  23845. }
  23846. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  23847. end_takeconch:
  23848. OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
  23849. if( rc==SQLITE_OK && pFile->openFlags ){
  23850. if( pFile->h>=0 ){
  23851. #ifdef STRICT_CLOSE_ERROR
  23852. if( close(pFile->h) ){
  23853. pFile->lastErrno = errno;
  23854. return SQLITE_IOERR_CLOSE;
  23855. }
  23856. #else
  23857. close(pFile->h); /* silently leak fd if fail */
  23858. #endif
  23859. }
  23860. pFile->h = -1;
  23861. int fd = open(pCtx->dbPath, pFile->openFlags,
  23862. SQLITE_DEFAULT_FILE_PERMISSIONS);
  23863. OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
  23864. if( fd>=0 ){
  23865. pFile->h = fd;
  23866. }else{
  23867. rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
  23868. during locking */
  23869. }
  23870. }
  23871. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  23872. char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
  23873. /* ACS: Need to make a copy of path sometimes */
  23874. rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
  23875. }
  23876. if( rc==SQLITE_OK ){
  23877. pCtx->conchHeld = 1;
  23878. if( tLockPath ){
  23879. pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
  23880. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  23881. ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
  23882. pCtx->lockProxyPath;
  23883. }
  23884. }
  23885. } else {
  23886. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  23887. }
  23888. OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
  23889. return rc;
  23890. }
  23891. }
  23892. /*
  23893. ** If pFile holds a lock on a conch file, then release that lock.
  23894. */
  23895. static int proxyReleaseConch(unixFile *pFile){
  23896. int rc; /* Subroutine return code */
  23897. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  23898. unixFile *conchFile; /* Name of the conch file */
  23899. pCtx = (proxyLockingContext *)pFile->lockingContext;
  23900. conchFile = pCtx->conchFile;
  23901. OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  23902. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  23903. getpid());
  23904. pCtx->conchHeld = 0;
  23905. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  23906. OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
  23907. (rc==SQLITE_OK ? "ok" : "failed"));
  23908. return rc;
  23909. }
  23910. /*
  23911. ** Given the name of a database file, compute the name of its conch file.
  23912. ** Store the conch filename in memory obtained from sqlite3_malloc().
  23913. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  23914. ** or SQLITE_NOMEM if unable to obtain memory.
  23915. **
  23916. ** The caller is responsible for ensuring that the allocated memory
  23917. ** space is eventually freed.
  23918. **
  23919. ** *pConchPath is set to NULL if a memory allocation error occurs.
  23920. */
  23921. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  23922. int i; /* Loop counter */
  23923. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  23924. char *conchPath; /* buffer in which to construct conch name */
  23925. /* Allocate space for the conch filename and initialize the name to
  23926. ** the name of the original database file. */
  23927. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  23928. if( conchPath==0 ){
  23929. return SQLITE_NOMEM;
  23930. }
  23931. memcpy(conchPath, dbPath, len+1);
  23932. /* now insert a "." before the last / character */
  23933. for( i=(len-1); i>=0; i-- ){
  23934. if( conchPath[i]=='/' ){
  23935. i++;
  23936. break;
  23937. }
  23938. }
  23939. conchPath[i]='.';
  23940. while ( i<len ){
  23941. conchPath[i+1]=dbPath[i];
  23942. i++;
  23943. }
  23944. /* append the "-conch" suffix to the file */
  23945. memcpy(&conchPath[i+1], "-conch", 7);
  23946. assert( (int)strlen(conchPath) == len+7 );
  23947. return SQLITE_OK;
  23948. }
  23949. /* Takes a fully configured proxy locking-style unix file and switches
  23950. ** the local lock file path
  23951. */
  23952. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  23953. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  23954. char *oldPath = pCtx->lockProxyPath;
  23955. int rc = SQLITE_OK;
  23956. if( pFile->locktype!=NO_LOCK ){
  23957. return SQLITE_BUSY;
  23958. }
  23959. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  23960. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  23961. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  23962. return SQLITE_OK;
  23963. }else{
  23964. unixFile *lockProxy = pCtx->lockProxy;
  23965. pCtx->lockProxy=NULL;
  23966. pCtx->conchHeld = 0;
  23967. if( lockProxy!=NULL ){
  23968. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  23969. if( rc ) return rc;
  23970. sqlite3_free(lockProxy);
  23971. }
  23972. sqlite3_free(oldPath);
  23973. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  23974. }
  23975. return rc;
  23976. }
  23977. /*
  23978. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  23979. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  23980. **
  23981. ** This routine find the filename associated with pFile and writes it
  23982. ** int dbPath.
  23983. */
  23984. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  23985. #if defined(__APPLE__)
  23986. if( pFile->pMethod == &afpIoMethods ){
  23987. /* afp style keeps a reference to the db path in the filePath field
  23988. ** of the struct */
  23989. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  23990. strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
  23991. }else
  23992. #endif
  23993. if( pFile->pMethod == &dotlockIoMethods ){
  23994. /* dot lock style uses the locking context to store the dot lock
  23995. ** file path */
  23996. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  23997. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  23998. }else{
  23999. /* all other styles use the locking context to store the db file path */
  24000. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  24001. strcpy(dbPath, (char *)pFile->lockingContext);
  24002. }
  24003. return SQLITE_OK;
  24004. }
  24005. /*
  24006. ** Takes an already filled in unix file and alters it so all file locking
  24007. ** will be performed on the local proxy lock file. The following fields
  24008. ** are preserved in the locking context so that they can be restored and
  24009. ** the unix structure properly cleaned up at close time:
  24010. ** ->lockingContext
  24011. ** ->pMethod
  24012. */
  24013. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  24014. proxyLockingContext *pCtx;
  24015. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  24016. char *lockPath=NULL;
  24017. int rc = SQLITE_OK;
  24018. if( pFile->locktype!=NO_LOCK ){
  24019. return SQLITE_BUSY;
  24020. }
  24021. proxyGetDbPathForUnixFile(pFile, dbPath);
  24022. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  24023. lockPath=NULL;
  24024. }else{
  24025. lockPath=(char *)path;
  24026. }
  24027. OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  24028. (lockPath ? lockPath : ":auto:"), getpid());
  24029. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  24030. if( pCtx==0 ){
  24031. return SQLITE_NOMEM;
  24032. }
  24033. memset(pCtx, 0, sizeof(*pCtx));
  24034. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  24035. if( rc==SQLITE_OK ){
  24036. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
  24037. }
  24038. if( rc==SQLITE_OK && lockPath ){
  24039. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  24040. }
  24041. if( rc==SQLITE_OK ){
  24042. /* all memory is allocated, proxys are created and assigned,
  24043. ** switch the locking context and pMethod then return.
  24044. */
  24045. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  24046. pCtx->oldLockingContext = pFile->lockingContext;
  24047. pFile->lockingContext = pCtx;
  24048. pCtx->pOldMethod = pFile->pMethod;
  24049. pFile->pMethod = &proxyIoMethods;
  24050. }else{
  24051. if( pCtx->conchFile ){
  24052. rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  24053. if( rc ) return rc;
  24054. sqlite3_free(pCtx->conchFile);
  24055. }
  24056. sqlite3_free(pCtx->conchFilePath);
  24057. sqlite3_free(pCtx);
  24058. }
  24059. OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
  24060. (rc==SQLITE_OK ? "ok" : "failed"));
  24061. return rc;
  24062. }
  24063. /*
  24064. ** This routine handles sqlite3_file_control() calls that are specific
  24065. ** to proxy locking.
  24066. */
  24067. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  24068. switch( op ){
  24069. case SQLITE_GET_LOCKPROXYFILE: {
  24070. unixFile *pFile = (unixFile*)id;
  24071. if( pFile->pMethod == &proxyIoMethods ){
  24072. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  24073. proxyTakeConch(pFile);
  24074. if( pCtx->lockProxyPath ){
  24075. *(const char **)pArg = pCtx->lockProxyPath;
  24076. }else{
  24077. *(const char **)pArg = ":auto: (not held)";
  24078. }
  24079. } else {
  24080. *(const char **)pArg = NULL;
  24081. }
  24082. return SQLITE_OK;
  24083. }
  24084. case SQLITE_SET_LOCKPROXYFILE: {
  24085. unixFile *pFile = (unixFile*)id;
  24086. int rc = SQLITE_OK;
  24087. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  24088. if( pArg==NULL || (const char *)pArg==0 ){
  24089. if( isProxyStyle ){
  24090. /* turn off proxy locking - not supported */
  24091. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  24092. }else{
  24093. /* turn off proxy locking - already off - NOOP */
  24094. rc = SQLITE_OK;
  24095. }
  24096. }else{
  24097. const char *proxyPath = (const char *)pArg;
  24098. if( isProxyStyle ){
  24099. proxyLockingContext *pCtx =
  24100. (proxyLockingContext*)pFile->lockingContext;
  24101. if( !strcmp(pArg, ":auto:")
  24102. || (pCtx->lockProxyPath &&
  24103. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  24104. ){
  24105. rc = SQLITE_OK;
  24106. }else{
  24107. rc = switchLockProxyPath(pFile, proxyPath);
  24108. }
  24109. }else{
  24110. /* turn on proxy file locking */
  24111. rc = proxyTransformUnixFile(pFile, proxyPath);
  24112. }
  24113. }
  24114. return rc;
  24115. }
  24116. default: {
  24117. assert( 0 ); /* The call assures that only valid opcodes are sent */
  24118. }
  24119. }
  24120. /*NOTREACHED*/
  24121. return SQLITE_ERROR;
  24122. }
  24123. /*
  24124. ** Within this division (the proxying locking implementation) the procedures
  24125. ** above this point are all utilities. The lock-related methods of the
  24126. ** proxy-locking sqlite3_io_method object follow.
  24127. */
  24128. /*
  24129. ** This routine checks if there is a RESERVED lock held on the specified
  24130. ** file by this or any other process. If such a lock is held, set *pResOut
  24131. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24132. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24133. */
  24134. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24135. unixFile *pFile = (unixFile*)id;
  24136. int rc = proxyTakeConch(pFile);
  24137. if( rc==SQLITE_OK ){
  24138. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  24139. unixFile *proxy = pCtx->lockProxy;
  24140. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  24141. }
  24142. return rc;
  24143. }
  24144. /*
  24145. ** Lock the file with the lock specified by parameter locktype - one
  24146. ** of the following:
  24147. **
  24148. ** (1) SHARED_LOCK
  24149. ** (2) RESERVED_LOCK
  24150. ** (3) PENDING_LOCK
  24151. ** (4) EXCLUSIVE_LOCK
  24152. **
  24153. ** Sometimes when requesting one lock state, additional lock states
  24154. ** are inserted in between. The locking might fail on one of the later
  24155. ** transitions leaving the lock state different from what it started but
  24156. ** still short of its goal. The following chart shows the allowed
  24157. ** transitions and the inserted intermediate states:
  24158. **
  24159. ** UNLOCKED -> SHARED
  24160. ** SHARED -> RESERVED
  24161. ** SHARED -> (PENDING) -> EXCLUSIVE
  24162. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24163. ** PENDING -> EXCLUSIVE
  24164. **
  24165. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24166. ** routine to lower a locking level.
  24167. */
  24168. static int proxyLock(sqlite3_file *id, int locktype) {
  24169. unixFile *pFile = (unixFile*)id;
  24170. int rc = proxyTakeConch(pFile);
  24171. if( rc==SQLITE_OK ){
  24172. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  24173. unixFile *proxy = pCtx->lockProxy;
  24174. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
  24175. pFile->locktype = proxy->locktype;
  24176. }
  24177. return rc;
  24178. }
  24179. /*
  24180. ** Lower the locking level on file descriptor pFile to locktype. locktype
  24181. ** must be either NO_LOCK or SHARED_LOCK.
  24182. **
  24183. ** If the locking level of the file descriptor is already at or below
  24184. ** the requested locking level, this routine is a no-op.
  24185. */
  24186. static int proxyUnlock(sqlite3_file *id, int locktype) {
  24187. unixFile *pFile = (unixFile*)id;
  24188. int rc = proxyTakeConch(pFile);
  24189. if( rc==SQLITE_OK ){
  24190. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  24191. unixFile *proxy = pCtx->lockProxy;
  24192. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
  24193. pFile->locktype = proxy->locktype;
  24194. }
  24195. return rc;
  24196. }
  24197. /*
  24198. ** Close a file that uses proxy locks.
  24199. */
  24200. static int proxyClose(sqlite3_file *id) {
  24201. if( id ){
  24202. unixFile *pFile = (unixFile*)id;
  24203. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  24204. unixFile *lockProxy = pCtx->lockProxy;
  24205. unixFile *conchFile = pCtx->conchFile;
  24206. int rc = SQLITE_OK;
  24207. if( lockProxy ){
  24208. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  24209. if( rc ) return rc;
  24210. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  24211. if( rc ) return rc;
  24212. sqlite3_free(lockProxy);
  24213. pCtx->lockProxy = 0;
  24214. }
  24215. if( conchFile ){
  24216. if( pCtx->conchHeld ){
  24217. rc = proxyReleaseConch(pFile);
  24218. if( rc ) return rc;
  24219. }
  24220. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  24221. if( rc ) return rc;
  24222. sqlite3_free(conchFile);
  24223. }
  24224. sqlite3_free(pCtx->lockProxyPath);
  24225. sqlite3_free(pCtx->conchFilePath);
  24226. sqlite3_free(pCtx->dbPath);
  24227. /* restore the original locking context and pMethod then close it */
  24228. pFile->lockingContext = pCtx->oldLockingContext;
  24229. pFile->pMethod = pCtx->pOldMethod;
  24230. sqlite3_free(pCtx);
  24231. return pFile->pMethod->xClose(id);
  24232. }
  24233. return SQLITE_OK;
  24234. }
  24235. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24236. /*
  24237. ** The proxy locking style is intended for use with AFP filesystems.
  24238. ** And since AFP is only supported on MacOSX, the proxy locking is also
  24239. ** restricted to MacOSX.
  24240. **
  24241. **
  24242. ******************* End of the proxy lock implementation **********************
  24243. ******************************************************************************/
  24244. /*
  24245. ** Initialize the operating system interface.
  24246. **
  24247. ** This routine registers all VFS implementations for unix-like operating
  24248. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  24249. ** should be the only routines in this file that are visible from other
  24250. ** files.
  24251. **
  24252. ** This routine is called once during SQLite initialization and by a
  24253. ** single thread. The memory allocation and mutex subsystems have not
  24254. ** necessarily been initialized when this routine is called, and so they
  24255. ** should not be used.
  24256. */
  24257. SQLITE_API int sqlite3_os_init(void){
  24258. /*
  24259. ** The following macro defines an initializer for an sqlite3_vfs object.
  24260. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  24261. ** to the "finder" function. (pAppData is a pointer to a pointer because
  24262. ** silly C90 rules prohibit a void* from being cast to a function pointer
  24263. ** and so we have to go through the intermediate pointer to avoid problems
  24264. ** when compiling with -pedantic-errors on GCC.)
  24265. **
  24266. ** The FINDER parameter to this macro is the name of the pointer to the
  24267. ** finder-function. The finder-function returns a pointer to the
  24268. ** sqlite_io_methods object that implements the desired locking
  24269. ** behaviors. See the division above that contains the IOMETHODS
  24270. ** macro for addition information on finder-functions.
  24271. **
  24272. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  24273. ** object. But the "autolockIoFinder" available on MacOSX does a little
  24274. ** more than that; it looks at the filesystem type that hosts the
  24275. ** database file and tries to choose an locking method appropriate for
  24276. ** that filesystem time.
  24277. */
  24278. #define UNIXVFS(VFSNAME, FINDER) { \
  24279. 1, /* iVersion */ \
  24280. sizeof(unixFile), /* szOsFile */ \
  24281. MAX_PATHNAME, /* mxPathname */ \
  24282. 0, /* pNext */ \
  24283. VFSNAME, /* zName */ \
  24284. (void*)&FINDER, /* pAppData */ \
  24285. unixOpen, /* xOpen */ \
  24286. unixDelete, /* xDelete */ \
  24287. unixAccess, /* xAccess */ \
  24288. unixFullPathname, /* xFullPathname */ \
  24289. unixDlOpen, /* xDlOpen */ \
  24290. unixDlError, /* xDlError */ \
  24291. unixDlSym, /* xDlSym */ \
  24292. unixDlClose, /* xDlClose */ \
  24293. unixRandomness, /* xRandomness */ \
  24294. unixSleep, /* xSleep */ \
  24295. unixCurrentTime, /* xCurrentTime */ \
  24296. unixGetLastError /* xGetLastError */ \
  24297. }
  24298. /*
  24299. ** All default VFSes for unix are contained in the following array.
  24300. **
  24301. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  24302. ** by the SQLite core when the VFS is registered. So the following
  24303. ** array cannot be const.
  24304. */
  24305. static sqlite3_vfs aVfs[] = {
  24306. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  24307. UNIXVFS("unix", autolockIoFinder ),
  24308. #else
  24309. UNIXVFS("unix", posixIoFinder ),
  24310. #endif
  24311. UNIXVFS("unix-none", nolockIoFinder ),
  24312. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  24313. #if OS_VXWORKS
  24314. UNIXVFS("unix-namedsem", semIoFinder ),
  24315. #endif
  24316. #if SQLITE_ENABLE_LOCKING_STYLE
  24317. UNIXVFS("unix-posix", posixIoFinder ),
  24318. #if !OS_VXWORKS
  24319. UNIXVFS("unix-flock", flockIoFinder ),
  24320. #endif
  24321. #endif
  24322. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  24323. UNIXVFS("unix-afp", afpIoFinder ),
  24324. UNIXVFS("unix-proxy", proxyIoFinder ),
  24325. #endif
  24326. };
  24327. unsigned int i; /* Loop counter */
  24328. /* Register all VFSes defined in the aVfs[] array */
  24329. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  24330. sqlite3_vfs_register(&aVfs[i], i==0);
  24331. }
  24332. return SQLITE_OK;
  24333. }
  24334. /*
  24335. ** Shutdown the operating system interface.
  24336. **
  24337. ** Some operating systems might need to do some cleanup in this routine,
  24338. ** to release dynamically allocated objects. But not on unix.
  24339. ** This routine is a no-op for unix.
  24340. */
  24341. SQLITE_API int sqlite3_os_end(void){
  24342. return SQLITE_OK;
  24343. }
  24344. #endif /* SQLITE_OS_UNIX */
  24345. /************** End of os_unix.c *********************************************/
  24346. /************** Begin file os_win.c ******************************************/
  24347. /*
  24348. ** 2004 May 22
  24349. **
  24350. ** The author disclaims copyright to this source code. In place of
  24351. ** a legal notice, here is a blessing:
  24352. **
  24353. ** May you do good and not evil.
  24354. ** May you find forgiveness for yourself and forgive others.
  24355. ** May you share freely, never taking more than you give.
  24356. **
  24357. ******************************************************************************
  24358. **
  24359. ** This file contains code that is specific to windows.
  24360. **
  24361. ** $Id: os_win.c,v 1.154 2009/04/09 14:27:07 chw Exp $
  24362. */
  24363. #if SQLITE_OS_WIN /* This file is used for windows only */
  24364. /*
  24365. ** A Note About Memory Allocation:
  24366. **
  24367. ** This driver uses malloc()/free() directly rather than going through
  24368. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  24369. ** are designed for use on embedded systems where memory is scarce and
  24370. ** malloc failures happen frequently. Win32 does not typically run on
  24371. ** embedded systems, and when it does the developers normally have bigger
  24372. ** problems to worry about than running out of memory. So there is not
  24373. ** a compelling need to use the wrappers.
  24374. **
  24375. ** But there is a good reason to not use the wrappers. If we use the
  24376. ** wrappers then we will get simulated malloc() failures within this
  24377. ** driver. And that causes all kinds of problems for our tests. We
  24378. ** could enhance SQLite to deal with simulated malloc failures within
  24379. ** the OS driver, but the code to deal with those failure would not
  24380. ** be exercised on Linux (which does not need to malloc() in the driver)
  24381. ** and so we would have difficulty writing coverage tests for that
  24382. ** code. Better to leave the code out, we think.
  24383. **
  24384. ** The point of this discussion is as follows: When creating a new
  24385. ** OS layer for an embedded system, if you use this file as an example,
  24386. ** avoid the use of malloc()/free(). Those routines work ok on windows
  24387. ** desktops but not so well in embedded systems.
  24388. */
  24389. #include <winbase.h>
  24390. #ifdef __CYGWIN__
  24391. # include <sys/cygwin.h>
  24392. #endif
  24393. /*
  24394. ** Macros used to determine whether or not to use threads.
  24395. */
  24396. #if defined(THREADSAFE) && THREADSAFE
  24397. # define SQLITE_W32_THREADS 1
  24398. #endif
  24399. /*
  24400. ** Include code that is common to all os_*.c files
  24401. */
  24402. /************** Include os_common.h in the middle of os_win.c ****************/
  24403. /************** Begin file os_common.h ***************************************/
  24404. /*
  24405. ** 2004 May 22
  24406. **
  24407. ** The author disclaims copyright to this source code. In place of
  24408. ** a legal notice, here is a blessing:
  24409. **
  24410. ** May you do good and not evil.
  24411. ** May you find forgiveness for yourself and forgive others.
  24412. ** May you share freely, never taking more than you give.
  24413. **
  24414. ******************************************************************************
  24415. **
  24416. ** This file contains macros and a little bit of code that is common to
  24417. ** all of the platform-specific files (os_*.c) and is #included into those
  24418. ** files.
  24419. **
  24420. ** This file should be #included by the os_*.c files only. It is not a
  24421. ** general purpose header file.
  24422. **
  24423. ** $Id: os_common.h,v 1.38 2009/02/24 18:40:50 danielk1977 Exp $
  24424. */
  24425. #ifndef _OS_COMMON_H_
  24426. #define _OS_COMMON_H_
  24427. /*
  24428. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24429. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24430. ** switch. The following code should catch this problem at compile-time.
  24431. */
  24432. #ifdef MEMORY_DEBUG
  24433. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24434. #endif
  24435. #ifdef SQLITE_DEBUG
  24436. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  24437. #define OSTRACE1(X) if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
  24438. #define OSTRACE2(X,Y) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
  24439. #define OSTRACE3(X,Y,Z) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
  24440. #define OSTRACE4(X,Y,Z,A) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
  24441. #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
  24442. #define OSTRACE6(X,Y,Z,A,B,C) \
  24443. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
  24444. #define OSTRACE7(X,Y,Z,A,B,C,D) \
  24445. if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
  24446. #else
  24447. #define OSTRACE1(X)
  24448. #define OSTRACE2(X,Y)
  24449. #define OSTRACE3(X,Y,Z)
  24450. #define OSTRACE4(X,Y,Z,A)
  24451. #define OSTRACE5(X,Y,Z,A,B)
  24452. #define OSTRACE6(X,Y,Z,A,B,C)
  24453. #define OSTRACE7(X,Y,Z,A,B,C,D)
  24454. #endif
  24455. /*
  24456. ** Macros for performance tracing. Normally turned off. Only works
  24457. ** on i486 hardware.
  24458. */
  24459. #ifdef SQLITE_PERFORMANCE_TRACE
  24460. /*
  24461. ** hwtime.h contains inline assembler code for implementing
  24462. ** high-performance timing routines.
  24463. */
  24464. /************** Include hwtime.h in the middle of os_common.h ****************/
  24465. /************** Begin file hwtime.h ******************************************/
  24466. /*
  24467. ** 2008 May 27
  24468. **
  24469. ** The author disclaims copyright to this source code. In place of
  24470. ** a legal notice, here is a blessing:
  24471. **
  24472. ** May you do good and not evil.
  24473. ** May you find forgiveness for yourself and forgive others.
  24474. ** May you share freely, never taking more than you give.
  24475. **
  24476. ******************************************************************************
  24477. **
  24478. ** This file contains inline asm code for retrieving "high-performance"
  24479. ** counters for x86 class CPUs.
  24480. **
  24481. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  24482. */
  24483. #ifndef _HWTIME_H_
  24484. #define _HWTIME_H_
  24485. /*
  24486. ** The following routine only works on pentium-class (or newer) processors.
  24487. ** It uses the RDTSC opcode to read the cycle count value out of the
  24488. ** processor and returns that value. This can be used for high-res
  24489. ** profiling.
  24490. */
  24491. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24492. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24493. #if defined(__GNUC__)
  24494. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24495. unsigned int lo, hi;
  24496. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24497. return (sqlite_uint64)hi << 32 | lo;
  24498. }
  24499. #elif defined(_MSC_VER)
  24500. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24501. __asm {
  24502. rdtsc
  24503. ret ; return value at EDX:EAX
  24504. }
  24505. }
  24506. #endif
  24507. #elif (defined(__GNUC__) && defined(__x86_64__))
  24508. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24509. unsigned long val;
  24510. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24511. return val;
  24512. }
  24513. #elif (defined(__GNUC__) && defined(__ppc__))
  24514. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24515. unsigned long long retval;
  24516. unsigned long junk;
  24517. __asm__ __volatile__ ("\n\
  24518. 1: mftbu %1\n\
  24519. mftb %L0\n\
  24520. mftbu %0\n\
  24521. cmpw %0,%1\n\
  24522. bne 1b"
  24523. : "=r" (retval), "=r" (junk));
  24524. return retval;
  24525. }
  24526. #else
  24527. #error Need implementation of sqlite3Hwtime() for your platform.
  24528. /*
  24529. ** To compile without implementing sqlite3Hwtime() for your platform,
  24530. ** you can remove the above #error and use the following
  24531. ** stub function. You will lose timing support for many
  24532. ** of the debugging and testing utilities, but it should at
  24533. ** least compile and run.
  24534. */
  24535. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24536. #endif
  24537. #endif /* !defined(_HWTIME_H_) */
  24538. /************** End of hwtime.h **********************************************/
  24539. /************** Continuing where we left off in os_common.h ******************/
  24540. static sqlite_uint64 g_start;
  24541. static sqlite_uint64 g_elapsed;
  24542. #define TIMER_START g_start=sqlite3Hwtime()
  24543. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24544. #define TIMER_ELAPSED g_elapsed
  24545. #else
  24546. #define TIMER_START
  24547. #define TIMER_END
  24548. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24549. #endif
  24550. /*
  24551. ** If we compile with the SQLITE_TEST macro set, then the following block
  24552. ** of code will give us the ability to simulate a disk I/O error. This
  24553. ** is used for testing the I/O recovery logic.
  24554. */
  24555. #ifdef SQLITE_TEST
  24556. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  24557. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  24558. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  24559. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  24560. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  24561. SQLITE_API int sqlite3_diskfull_pending = 0;
  24562. SQLITE_API int sqlite3_diskfull = 0;
  24563. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24564. #define SimulateIOError(CODE) \
  24565. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24566. || sqlite3_io_error_pending-- == 1 ) \
  24567. { local_ioerr(); CODE; }
  24568. static void local_ioerr(){
  24569. IOTRACE(("IOERR\n"));
  24570. sqlite3_io_error_hit++;
  24571. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24572. }
  24573. #define SimulateDiskfullError(CODE) \
  24574. if( sqlite3_diskfull_pending ){ \
  24575. if( sqlite3_diskfull_pending == 1 ){ \
  24576. local_ioerr(); \
  24577. sqlite3_diskfull = 1; \
  24578. sqlite3_io_error_hit = 1; \
  24579. CODE; \
  24580. }else{ \
  24581. sqlite3_diskfull_pending--; \
  24582. } \
  24583. }
  24584. #else
  24585. #define SimulateIOErrorBenign(X)
  24586. #define SimulateIOError(A)
  24587. #define SimulateDiskfullError(A)
  24588. #endif
  24589. /*
  24590. ** When testing, keep a count of the number of open files.
  24591. */
  24592. #ifdef SQLITE_TEST
  24593. SQLITE_API int sqlite3_open_file_count = 0;
  24594. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24595. #else
  24596. #define OpenCounter(X)
  24597. #endif
  24598. #endif /* !defined(_OS_COMMON_H_) */
  24599. /************** End of os_common.h *******************************************/
  24600. /************** Continuing where we left off in os_win.c *********************/
  24601. /*
  24602. ** Some microsoft compilers lack this definition.
  24603. */
  24604. #ifndef INVALID_FILE_ATTRIBUTES
  24605. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  24606. #endif
  24607. /*
  24608. ** Determine if we are dealing with WindowsCE - which has a much
  24609. ** reduced API.
  24610. */
  24611. #if SQLITE_OS_WINCE
  24612. # define AreFileApisANSI() 1
  24613. # define GetDiskFreeSpaceW() 0
  24614. #endif
  24615. /*
  24616. ** WinCE lacks native support for file locking so we have to fake it
  24617. ** with some code of our own.
  24618. */
  24619. #if SQLITE_OS_WINCE
  24620. typedef struct winceLock {
  24621. int nReaders; /* Number of reader locks obtained */
  24622. BOOL bPending; /* Indicates a pending lock has been obtained */
  24623. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  24624. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  24625. } winceLock;
  24626. #endif
  24627. /*
  24628. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  24629. ** portability layer.
  24630. */
  24631. typedef struct winFile winFile;
  24632. struct winFile {
  24633. const sqlite3_io_methods *pMethod;/* Must be first */
  24634. HANDLE h; /* Handle for accessing the file */
  24635. unsigned char locktype; /* Type of lock currently held on this file */
  24636. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  24637. DWORD lastErrno; /* The Windows errno from the last I/O error */
  24638. DWORD sectorSize; /* Sector size of the device file is on */
  24639. #if SQLITE_OS_WINCE
  24640. WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
  24641. HANDLE hMutex; /* Mutex used to control access to shared lock */
  24642. HANDLE hShared; /* Shared memory segment used for locking */
  24643. winceLock local; /* Locks obtained by this instance of winFile */
  24644. winceLock *shared; /* Global shared lock memory for the file */
  24645. #endif
  24646. };
  24647. /*
  24648. ** Forward prototypes.
  24649. */
  24650. static int getSectorSize(
  24651. sqlite3_vfs *pVfs,
  24652. const char *zRelative /* UTF-8 file name */
  24653. );
  24654. /*
  24655. ** The following variable is (normally) set once and never changes
  24656. ** thereafter. It records whether the operating system is Win95
  24657. ** or WinNT.
  24658. **
  24659. ** 0: Operating system unknown.
  24660. ** 1: Operating system is Win95.
  24661. ** 2: Operating system is WinNT.
  24662. **
  24663. ** In order to facilitate testing on a WinNT system, the test fixture
  24664. ** can manually set this value to 1 to emulate Win98 behavior.
  24665. */
  24666. #ifdef SQLITE_TEST
  24667. SQLITE_API int sqlite3_os_type = 0;
  24668. #else
  24669. static int sqlite3_os_type = 0;
  24670. #endif
  24671. /*
  24672. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  24673. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  24674. **
  24675. ** Here is an interesting observation: Win95, Win98, and WinME lack
  24676. ** the LockFileEx() API. But we can still statically link against that
  24677. ** API as long as we don't call it when running Win95/98/ME. A call to
  24678. ** this routine is used to determine if the host is Win95/98/ME or
  24679. ** WinNT/2K/XP so that we will know whether or not we can safely call
  24680. ** the LockFileEx() API.
  24681. */
  24682. #if SQLITE_OS_WINCE
  24683. # define isNT() (1)
  24684. #else
  24685. static int isNT(void){
  24686. if( sqlite3_os_type==0 ){
  24687. OSVERSIONINFO sInfo;
  24688. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  24689. GetVersionEx(&sInfo);
  24690. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  24691. }
  24692. return sqlite3_os_type==2;
  24693. }
  24694. #endif /* SQLITE_OS_WINCE */
  24695. /*
  24696. ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
  24697. **
  24698. ** Space to hold the returned string is obtained from malloc.
  24699. */
  24700. static WCHAR *utf8ToUnicode(const char *zFilename){
  24701. int nChar;
  24702. WCHAR *zWideFilename;
  24703. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  24704. zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
  24705. if( zWideFilename==0 ){
  24706. return 0;
  24707. }
  24708. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
  24709. if( nChar==0 ){
  24710. free(zWideFilename);
  24711. zWideFilename = 0;
  24712. }
  24713. return zWideFilename;
  24714. }
  24715. /*
  24716. ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
  24717. ** obtained from malloc().
  24718. */
  24719. static char *unicodeToUtf8(const WCHAR *zWideFilename){
  24720. int nByte;
  24721. char *zFilename;
  24722. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  24723. zFilename = malloc( nByte );
  24724. if( zFilename==0 ){
  24725. return 0;
  24726. }
  24727. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  24728. 0, 0);
  24729. if( nByte == 0 ){
  24730. free(zFilename);
  24731. zFilename = 0;
  24732. }
  24733. return zFilename;
  24734. }
  24735. /*
  24736. ** Convert an ansi string to microsoft unicode, based on the
  24737. ** current codepage settings for file apis.
  24738. **
  24739. ** Space to hold the returned string is obtained
  24740. ** from malloc.
  24741. */
  24742. static WCHAR *mbcsToUnicode(const char *zFilename){
  24743. int nByte;
  24744. WCHAR *zMbcsFilename;
  24745. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  24746. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
  24747. zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
  24748. if( zMbcsFilename==0 ){
  24749. return 0;
  24750. }
  24751. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
  24752. if( nByte==0 ){
  24753. free(zMbcsFilename);
  24754. zMbcsFilename = 0;
  24755. }
  24756. return zMbcsFilename;
  24757. }
  24758. /*
  24759. ** Convert microsoft unicode to multibyte character string, based on the
  24760. ** user's Ansi codepage.
  24761. **
  24762. ** Space to hold the returned string is obtained from
  24763. ** malloc().
  24764. */
  24765. static char *unicodeToMbcs(const WCHAR *zWideFilename){
  24766. int nByte;
  24767. char *zFilename;
  24768. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  24769. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  24770. zFilename = malloc( nByte );
  24771. if( zFilename==0 ){
  24772. return 0;
  24773. }
  24774. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
  24775. 0, 0);
  24776. if( nByte == 0 ){
  24777. free(zFilename);
  24778. zFilename = 0;
  24779. }
  24780. return zFilename;
  24781. }
  24782. /*
  24783. ** Convert multibyte character string to UTF-8. Space to hold the
  24784. ** returned string is obtained from malloc().
  24785. */
  24786. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  24787. char *zFilenameUtf8;
  24788. WCHAR *zTmpWide;
  24789. zTmpWide = mbcsToUnicode(zFilename);
  24790. if( zTmpWide==0 ){
  24791. return 0;
  24792. }
  24793. zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  24794. free(zTmpWide);
  24795. return zFilenameUtf8;
  24796. }
  24797. /*
  24798. ** Convert UTF-8 to multibyte character string. Space to hold the
  24799. ** returned string is obtained from malloc().
  24800. */
  24801. static char *utf8ToMbcs(const char *zFilename){
  24802. char *zFilenameMbcs;
  24803. WCHAR *zTmpWide;
  24804. zTmpWide = utf8ToUnicode(zFilename);
  24805. if( zTmpWide==0 ){
  24806. return 0;
  24807. }
  24808. zFilenameMbcs = unicodeToMbcs(zTmpWide);
  24809. free(zTmpWide);
  24810. return zFilenameMbcs;
  24811. }
  24812. #if SQLITE_OS_WINCE
  24813. /*************************************************************************
  24814. ** This section contains code for WinCE only.
  24815. */
  24816. /*
  24817. ** WindowsCE does not have a localtime() function. So create a
  24818. ** substitute.
  24819. */
  24820. struct tm *__cdecl localtime(const time_t *t)
  24821. {
  24822. static struct tm y;
  24823. FILETIME uTm, lTm;
  24824. SYSTEMTIME pTm;
  24825. sqlite3_int64 t64;
  24826. t64 = *t;
  24827. t64 = (t64 + 11644473600)*10000000;
  24828. uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
  24829. uTm.dwHighDateTime= t64 >> 32;
  24830. FileTimeToLocalFileTime(&uTm,&lTm);
  24831. FileTimeToSystemTime(&lTm,&pTm);
  24832. y.tm_year = pTm.wYear - 1900;
  24833. y.tm_mon = pTm.wMonth - 1;
  24834. y.tm_wday = pTm.wDayOfWeek;
  24835. y.tm_mday = pTm.wDay;
  24836. y.tm_hour = pTm.wHour;
  24837. y.tm_min = pTm.wMinute;
  24838. y.tm_sec = pTm.wSecond;
  24839. return &y;
  24840. }
  24841. /* This will never be called, but defined to make the code compile */
  24842. #define GetTempPathA(a,b)
  24843. #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
  24844. #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
  24845. #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
  24846. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
  24847. /*
  24848. ** Acquire a lock on the handle h
  24849. */
  24850. static void winceMutexAcquire(HANDLE h){
  24851. DWORD dwErr;
  24852. do {
  24853. dwErr = WaitForSingleObject(h, INFINITE);
  24854. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  24855. }
  24856. /*
  24857. ** Release a lock acquired by winceMutexAcquire()
  24858. */
  24859. #define winceMutexRelease(h) ReleaseMutex(h)
  24860. /*
  24861. ** Create the mutex and shared memory used for locking in the file
  24862. ** descriptor pFile
  24863. */
  24864. static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
  24865. WCHAR *zTok;
  24866. WCHAR *zName = utf8ToUnicode(zFilename);
  24867. BOOL bInit = TRUE;
  24868. /* Initialize the local lockdata */
  24869. ZeroMemory(&pFile->local, sizeof(pFile->local));
  24870. /* Replace the backslashes from the filename and lowercase it
  24871. ** to derive a mutex name. */
  24872. zTok = CharLowerW(zName);
  24873. for (;*zTok;zTok++){
  24874. if (*zTok == '\\') *zTok = '_';
  24875. }
  24876. /* Create/open the named mutex */
  24877. pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  24878. if (!pFile->hMutex){
  24879. pFile->lastErrno = GetLastError();
  24880. free(zName);
  24881. return FALSE;
  24882. }
  24883. /* Acquire the mutex before continuing */
  24884. winceMutexAcquire(pFile->hMutex);
  24885. /* Since the names of named mutexes, semaphores, file mappings etc are
  24886. ** case-sensitive, take advantage of that by uppercasing the mutex name
  24887. ** and using that as the shared filemapping name.
  24888. */
  24889. CharUpperW(zName);
  24890. pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  24891. PAGE_READWRITE, 0, sizeof(winceLock),
  24892. zName);
  24893. /* Set a flag that indicates we're the first to create the memory so it
  24894. ** must be zero-initialized */
  24895. if (GetLastError() == ERROR_ALREADY_EXISTS){
  24896. bInit = FALSE;
  24897. }
  24898. free(zName);
  24899. /* If we succeeded in making the shared memory handle, map it. */
  24900. if (pFile->hShared){
  24901. pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
  24902. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  24903. /* If mapping failed, close the shared memory handle and erase it */
  24904. if (!pFile->shared){
  24905. pFile->lastErrno = GetLastError();
  24906. CloseHandle(pFile->hShared);
  24907. pFile->hShared = NULL;
  24908. }
  24909. }
  24910. /* If shared memory could not be created, then close the mutex and fail */
  24911. if (pFile->hShared == NULL){
  24912. winceMutexRelease(pFile->hMutex);
  24913. CloseHandle(pFile->hMutex);
  24914. pFile->hMutex = NULL;
  24915. return FALSE;
  24916. }
  24917. /* Initialize the shared memory if we're supposed to */
  24918. if (bInit) {
  24919. ZeroMemory(pFile->shared, sizeof(winceLock));
  24920. }
  24921. winceMutexRelease(pFile->hMutex);
  24922. return TRUE;
  24923. }
  24924. /*
  24925. ** Destroy the part of winFile that deals with wince locks
  24926. */
  24927. static void winceDestroyLock(winFile *pFile){
  24928. if (pFile->hMutex){
  24929. /* Acquire the mutex */
  24930. winceMutexAcquire(pFile->hMutex);
  24931. /* The following blocks should probably assert in debug mode, but they
  24932. are to cleanup in case any locks remained open */
  24933. if (pFile->local.nReaders){
  24934. pFile->shared->nReaders --;
  24935. }
  24936. if (pFile->local.bReserved){
  24937. pFile->shared->bReserved = FALSE;
  24938. }
  24939. if (pFile->local.bPending){
  24940. pFile->shared->bPending = FALSE;
  24941. }
  24942. if (pFile->local.bExclusive){
  24943. pFile->shared->bExclusive = FALSE;
  24944. }
  24945. /* De-reference and close our copy of the shared memory handle */
  24946. UnmapViewOfFile(pFile->shared);
  24947. CloseHandle(pFile->hShared);
  24948. /* Done with the mutex */
  24949. winceMutexRelease(pFile->hMutex);
  24950. CloseHandle(pFile->hMutex);
  24951. pFile->hMutex = NULL;
  24952. }
  24953. }
  24954. /*
  24955. ** An implementation of the LockFile() API of windows for wince
  24956. */
  24957. static BOOL winceLockFile(
  24958. HANDLE *phFile,
  24959. DWORD dwFileOffsetLow,
  24960. DWORD dwFileOffsetHigh,
  24961. DWORD nNumberOfBytesToLockLow,
  24962. DWORD nNumberOfBytesToLockHigh
  24963. ){
  24964. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  24965. BOOL bReturn = FALSE;
  24966. if (!pFile->hMutex) return TRUE;
  24967. winceMutexAcquire(pFile->hMutex);
  24968. /* Wanting an exclusive lock? */
  24969. if (dwFileOffsetLow == SHARED_FIRST
  24970. && nNumberOfBytesToLockLow == SHARED_SIZE){
  24971. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  24972. pFile->shared->bExclusive = TRUE;
  24973. pFile->local.bExclusive = TRUE;
  24974. bReturn = TRUE;
  24975. }
  24976. }
  24977. /* Want a read-only lock? */
  24978. else if ((dwFileOffsetLow >= SHARED_FIRST &&
  24979. dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
  24980. nNumberOfBytesToLockLow == 1){
  24981. if (pFile->shared->bExclusive == 0){
  24982. pFile->local.nReaders ++;
  24983. if (pFile->local.nReaders == 1){
  24984. pFile->shared->nReaders ++;
  24985. }
  24986. bReturn = TRUE;
  24987. }
  24988. }
  24989. /* Want a pending lock? */
  24990. else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
  24991. /* If no pending lock has been acquired, then acquire it */
  24992. if (pFile->shared->bPending == 0) {
  24993. pFile->shared->bPending = TRUE;
  24994. pFile->local.bPending = TRUE;
  24995. bReturn = TRUE;
  24996. }
  24997. }
  24998. /* Want a reserved lock? */
  24999. else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
  25000. if (pFile->shared->bReserved == 0) {
  25001. pFile->shared->bReserved = TRUE;
  25002. pFile->local.bReserved = TRUE;
  25003. bReturn = TRUE;
  25004. }
  25005. }
  25006. winceMutexRelease(pFile->hMutex);
  25007. return bReturn;
  25008. }
  25009. /*
  25010. ** An implementation of the UnlockFile API of windows for wince
  25011. */
  25012. static BOOL winceUnlockFile(
  25013. HANDLE *phFile,
  25014. DWORD dwFileOffsetLow,
  25015. DWORD dwFileOffsetHigh,
  25016. DWORD nNumberOfBytesToUnlockLow,
  25017. DWORD nNumberOfBytesToUnlockHigh
  25018. ){
  25019. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  25020. BOOL bReturn = FALSE;
  25021. if (!pFile->hMutex) return TRUE;
  25022. winceMutexAcquire(pFile->hMutex);
  25023. /* Releasing a reader lock or an exclusive lock */
  25024. if (dwFileOffsetLow >= SHARED_FIRST &&
  25025. dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
  25026. /* Did we have an exclusive lock? */
  25027. if (pFile->local.bExclusive){
  25028. pFile->local.bExclusive = FALSE;
  25029. pFile->shared->bExclusive = FALSE;
  25030. bReturn = TRUE;
  25031. }
  25032. /* Did we just have a reader lock? */
  25033. else if (pFile->local.nReaders){
  25034. pFile->local.nReaders --;
  25035. if (pFile->local.nReaders == 0)
  25036. {
  25037. pFile->shared->nReaders --;
  25038. }
  25039. bReturn = TRUE;
  25040. }
  25041. }
  25042. /* Releasing a pending lock */
  25043. else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
  25044. if (pFile->local.bPending){
  25045. pFile->local.bPending = FALSE;
  25046. pFile->shared->bPending = FALSE;
  25047. bReturn = TRUE;
  25048. }
  25049. }
  25050. /* Releasing a reserved lock */
  25051. else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
  25052. if (pFile->local.bReserved) {
  25053. pFile->local.bReserved = FALSE;
  25054. pFile->shared->bReserved = FALSE;
  25055. bReturn = TRUE;
  25056. }
  25057. }
  25058. winceMutexRelease(pFile->hMutex);
  25059. return bReturn;
  25060. }
  25061. /*
  25062. ** An implementation of the LockFileEx() API of windows for wince
  25063. */
  25064. static BOOL winceLockFileEx(
  25065. HANDLE *phFile,
  25066. DWORD dwFlags,
  25067. DWORD dwReserved,
  25068. DWORD nNumberOfBytesToLockLow,
  25069. DWORD nNumberOfBytesToLockHigh,
  25070. LPOVERLAPPED lpOverlapped
  25071. ){
  25072. /* If the caller wants a shared read lock, forward this call
  25073. ** to winceLockFile */
  25074. if (lpOverlapped->Offset == SHARED_FIRST &&
  25075. dwFlags == 1 &&
  25076. nNumberOfBytesToLockLow == SHARED_SIZE){
  25077. return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
  25078. }
  25079. return FALSE;
  25080. }
  25081. /*
  25082. ** End of the special code for wince
  25083. *****************************************************************************/
  25084. #endif /* SQLITE_OS_WINCE */
  25085. /*****************************************************************************
  25086. ** The next group of routines implement the I/O methods specified
  25087. ** by the sqlite3_io_methods object.
  25088. ******************************************************************************/
  25089. /*
  25090. ** Close a file.
  25091. **
  25092. ** It is reported that an attempt to close a handle might sometimes
  25093. ** fail. This is a very unreasonable result, but windows is notorious
  25094. ** for being unreasonable so I do not doubt that it might happen. If
  25095. ** the close fails, we pause for 100 milliseconds and try again. As
  25096. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  25097. ** giving up and returning an error.
  25098. */
  25099. #define MX_CLOSE_ATTEMPT 3
  25100. static int winClose(sqlite3_file *id){
  25101. int rc, cnt = 0;
  25102. winFile *pFile = (winFile*)id;
  25103. assert( id!=0 );
  25104. OSTRACE2("CLOSE %d\n", pFile->h);
  25105. do{
  25106. rc = CloseHandle(pFile->h);
  25107. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
  25108. #if SQLITE_OS_WINCE
  25109. #define WINCE_DELETION_ATTEMPTS 3
  25110. winceDestroyLock(pFile);
  25111. if( pFile->zDeleteOnClose ){
  25112. int cnt = 0;
  25113. while(
  25114. DeleteFileW(pFile->zDeleteOnClose)==0
  25115. && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  25116. && cnt++ < WINCE_DELETION_ATTEMPTS
  25117. ){
  25118. Sleep(100); /* Wait a little before trying again */
  25119. }
  25120. free(pFile->zDeleteOnClose);
  25121. }
  25122. #endif
  25123. OpenCounter(-1);
  25124. return rc ? SQLITE_OK : SQLITE_IOERR;
  25125. }
  25126. /*
  25127. ** Some microsoft compilers lack this definition.
  25128. */
  25129. #ifndef INVALID_SET_FILE_POINTER
  25130. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  25131. #endif
  25132. /*
  25133. ** Read data from a file into a buffer. Return SQLITE_OK if all
  25134. ** bytes were read successfully and SQLITE_IOERR if anything goes
  25135. ** wrong.
  25136. */
  25137. static int winRead(
  25138. sqlite3_file *id, /* File to read from */
  25139. void *pBuf, /* Write content into this buffer */
  25140. int amt, /* Number of bytes to read */
  25141. sqlite3_int64 offset /* Begin reading at this offset */
  25142. ){
  25143. LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  25144. LONG lowerBits = (LONG)(offset & 0xffffffff);
  25145. DWORD rc;
  25146. winFile *pFile = (winFile*)id;
  25147. DWORD error;
  25148. DWORD got;
  25149. assert( id!=0 );
  25150. SimulateIOError(return SQLITE_IOERR_READ);
  25151. OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  25152. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  25153. if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
  25154. pFile->lastErrno = error;
  25155. return SQLITE_FULL;
  25156. }
  25157. if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
  25158. pFile->lastErrno = GetLastError();
  25159. return SQLITE_IOERR_READ;
  25160. }
  25161. if( got==(DWORD)amt ){
  25162. return SQLITE_OK;
  25163. }else{
  25164. /* Unread parts of the buffer must be zero-filled */
  25165. memset(&((char*)pBuf)[got], 0, amt-got);
  25166. return SQLITE_IOERR_SHORT_READ;
  25167. }
  25168. }
  25169. /*
  25170. ** Write data from a buffer into a file. Return SQLITE_OK on success
  25171. ** or some other error code on failure.
  25172. */
  25173. static int winWrite(
  25174. sqlite3_file *id, /* File to write into */
  25175. const void *pBuf, /* The bytes to be written */
  25176. int amt, /* Number of bytes to write */
  25177. sqlite3_int64 offset /* Offset into the file to begin writing at */
  25178. ){
  25179. LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  25180. LONG lowerBits = (LONG)(offset & 0xffffffff);
  25181. DWORD rc;
  25182. winFile *pFile = (winFile*)id;
  25183. DWORD error;
  25184. DWORD wrote = 0;
  25185. assert( id!=0 );
  25186. SimulateIOError(return SQLITE_IOERR_WRITE);
  25187. SimulateDiskfullError(return SQLITE_FULL);
  25188. OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
  25189. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  25190. if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
  25191. pFile->lastErrno = error;
  25192. return SQLITE_FULL;
  25193. }
  25194. assert( amt>0 );
  25195. while(
  25196. amt>0
  25197. && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
  25198. && wrote>0
  25199. ){
  25200. amt -= wrote;
  25201. pBuf = &((char*)pBuf)[wrote];
  25202. }
  25203. if( !rc || amt>(int)wrote ){
  25204. pFile->lastErrno = GetLastError();
  25205. return SQLITE_FULL;
  25206. }
  25207. return SQLITE_OK;
  25208. }
  25209. /*
  25210. ** Truncate an open file to a specified size
  25211. */
  25212. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  25213. LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
  25214. LONG lowerBits = (LONG)(nByte & 0xffffffff);
  25215. DWORD rc;
  25216. winFile *pFile = (winFile*)id;
  25217. DWORD error;
  25218. assert( id!=0 );
  25219. OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
  25220. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  25221. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  25222. if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
  25223. pFile->lastErrno = error;
  25224. return SQLITE_IOERR_TRUNCATE;
  25225. }
  25226. /* SetEndOfFile will fail if nByte is negative */
  25227. if( !SetEndOfFile(pFile->h) ){
  25228. pFile->lastErrno = GetLastError();
  25229. return SQLITE_IOERR_TRUNCATE;
  25230. }
  25231. return SQLITE_OK;
  25232. }
  25233. #ifdef SQLITE_TEST
  25234. /*
  25235. ** Count the number of fullsyncs and normal syncs. This is used to test
  25236. ** that syncs and fullsyncs are occuring at the right times.
  25237. */
  25238. SQLITE_API int sqlite3_sync_count = 0;
  25239. SQLITE_API int sqlite3_fullsync_count = 0;
  25240. #endif
  25241. /*
  25242. ** Make sure all writes to a particular file are committed to disk.
  25243. */
  25244. static int winSync(sqlite3_file *id, int flags){
  25245. #ifndef SQLITE_NO_SYNC
  25246. winFile *pFile = (winFile*)id;
  25247. assert( id!=0 );
  25248. OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
  25249. #else
  25250. UNUSED_PARAMETER(id);
  25251. #endif
  25252. #ifndef SQLITE_TEST
  25253. UNUSED_PARAMETER(flags);
  25254. #else
  25255. if( flags & SQLITE_SYNC_FULL ){
  25256. sqlite3_fullsync_count++;
  25257. }
  25258. sqlite3_sync_count++;
  25259. #endif
  25260. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  25261. ** no-op
  25262. */
  25263. #ifdef SQLITE_NO_SYNC
  25264. return SQLITE_OK;
  25265. #else
  25266. if( FlushFileBuffers(pFile->h) ){
  25267. return SQLITE_OK;
  25268. }else{
  25269. pFile->lastErrno = GetLastError();
  25270. return SQLITE_IOERR;
  25271. }
  25272. #endif
  25273. }
  25274. /*
  25275. ** Determine the current size of a file in bytes
  25276. */
  25277. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  25278. DWORD upperBits;
  25279. DWORD lowerBits;
  25280. winFile *pFile = (winFile*)id;
  25281. DWORD error;
  25282. assert( id!=0 );
  25283. SimulateIOError(return SQLITE_IOERR_FSTAT);
  25284. lowerBits = GetFileSize(pFile->h, &upperBits);
  25285. if( (lowerBits == INVALID_FILE_SIZE)
  25286. && ((error = GetLastError()) != NO_ERROR) )
  25287. {
  25288. pFile->lastErrno = error;
  25289. return SQLITE_IOERR_FSTAT;
  25290. }
  25291. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  25292. return SQLITE_OK;
  25293. }
  25294. /*
  25295. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  25296. */
  25297. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  25298. # define LOCKFILE_FAIL_IMMEDIATELY 1
  25299. #endif
  25300. /*
  25301. ** Acquire a reader lock.
  25302. ** Different API routines are called depending on whether or not this
  25303. ** is Win95 or WinNT.
  25304. */
  25305. static int getReadLock(winFile *pFile){
  25306. int res;
  25307. if( isNT() ){
  25308. OVERLAPPED ovlp;
  25309. ovlp.Offset = SHARED_FIRST;
  25310. ovlp.OffsetHigh = 0;
  25311. ovlp.hEvent = 0;
  25312. res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
  25313. 0, SHARED_SIZE, 0, &ovlp);
  25314. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25315. */
  25316. #if SQLITE_OS_WINCE==0
  25317. }else{
  25318. int lk;
  25319. sqlite3_randomness(sizeof(lk), &lk);
  25320. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  25321. res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  25322. #endif
  25323. }
  25324. if( res == 0 ){
  25325. pFile->lastErrno = GetLastError();
  25326. }
  25327. return res;
  25328. }
  25329. /*
  25330. ** Undo a readlock
  25331. */
  25332. static int unlockReadLock(winFile *pFile){
  25333. int res;
  25334. if( isNT() ){
  25335. res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  25336. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25337. */
  25338. #if SQLITE_OS_WINCE==0
  25339. }else{
  25340. res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
  25341. #endif
  25342. }
  25343. if( res == 0 ){
  25344. pFile->lastErrno = GetLastError();
  25345. }
  25346. return res;
  25347. }
  25348. /*
  25349. ** Lock the file with the lock specified by parameter locktype - one
  25350. ** of the following:
  25351. **
  25352. ** (1) SHARED_LOCK
  25353. ** (2) RESERVED_LOCK
  25354. ** (3) PENDING_LOCK
  25355. ** (4) EXCLUSIVE_LOCK
  25356. **
  25357. ** Sometimes when requesting one lock state, additional lock states
  25358. ** are inserted in between. The locking might fail on one of the later
  25359. ** transitions leaving the lock state different from what it started but
  25360. ** still short of its goal. The following chart shows the allowed
  25361. ** transitions and the inserted intermediate states:
  25362. **
  25363. ** UNLOCKED -> SHARED
  25364. ** SHARED -> RESERVED
  25365. ** SHARED -> (PENDING) -> EXCLUSIVE
  25366. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25367. ** PENDING -> EXCLUSIVE
  25368. **
  25369. ** This routine will only increase a lock. The winUnlock() routine
  25370. ** erases all locks at once and returns us immediately to locking level 0.
  25371. ** It is not possible to lower the locking level one step at a time. You
  25372. ** must go straight to locking level 0.
  25373. */
  25374. static int winLock(sqlite3_file *id, int locktype){
  25375. int rc = SQLITE_OK; /* Return code from subroutines */
  25376. int res = 1; /* Result of a windows lock call */
  25377. int newLocktype; /* Set pFile->locktype to this value before exiting */
  25378. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  25379. winFile *pFile = (winFile*)id;
  25380. DWORD error = NO_ERROR;
  25381. assert( id!=0 );
  25382. OSTRACE5("LOCK %d %d was %d(%d)\n",
  25383. pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
  25384. /* If there is already a lock of this type or more restrictive on the
  25385. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  25386. ** sqlite3OsEnterMutex() hasn't been called yet.
  25387. */
  25388. if( pFile->locktype>=locktype ){
  25389. return SQLITE_OK;
  25390. }
  25391. /* Make sure the locking sequence is correct
  25392. */
  25393. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  25394. assert( locktype!=PENDING_LOCK );
  25395. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  25396. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  25397. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  25398. ** the PENDING_LOCK byte is temporary.
  25399. */
  25400. newLocktype = pFile->locktype;
  25401. if( (pFile->locktype==NO_LOCK)
  25402. || ( (locktype==EXCLUSIVE_LOCK)
  25403. && (pFile->locktype==RESERVED_LOCK))
  25404. ){
  25405. int cnt = 3;
  25406. while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
  25407. /* Try 3 times to get the pending lock. The pending lock might be
  25408. ** held by another reader process who will release it momentarily.
  25409. */
  25410. OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
  25411. Sleep(1);
  25412. }
  25413. gotPendingLock = res;
  25414. if( !res ){
  25415. error = GetLastError();
  25416. }
  25417. }
  25418. /* Acquire a shared lock
  25419. */
  25420. if( locktype==SHARED_LOCK && res ){
  25421. assert( pFile->locktype==NO_LOCK );
  25422. res = getReadLock(pFile);
  25423. if( res ){
  25424. newLocktype = SHARED_LOCK;
  25425. }else{
  25426. error = GetLastError();
  25427. }
  25428. }
  25429. /* Acquire a RESERVED lock
  25430. */
  25431. if( locktype==RESERVED_LOCK && res ){
  25432. assert( pFile->locktype==SHARED_LOCK );
  25433. res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  25434. if( res ){
  25435. newLocktype = RESERVED_LOCK;
  25436. }else{
  25437. error = GetLastError();
  25438. }
  25439. }
  25440. /* Acquire a PENDING lock
  25441. */
  25442. if( locktype==EXCLUSIVE_LOCK && res ){
  25443. newLocktype = PENDING_LOCK;
  25444. gotPendingLock = 0;
  25445. }
  25446. /* Acquire an EXCLUSIVE lock
  25447. */
  25448. if( locktype==EXCLUSIVE_LOCK && res ){
  25449. assert( pFile->locktype>=SHARED_LOCK );
  25450. res = unlockReadLock(pFile);
  25451. OSTRACE2("unreadlock = %d\n", res);
  25452. res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  25453. if( res ){
  25454. newLocktype = EXCLUSIVE_LOCK;
  25455. }else{
  25456. error = GetLastError();
  25457. OSTRACE2("error-code = %d\n", error);
  25458. getReadLock(pFile);
  25459. }
  25460. }
  25461. /* If we are holding a PENDING lock that ought to be released, then
  25462. ** release it now.
  25463. */
  25464. if( gotPendingLock && locktype==SHARED_LOCK ){
  25465. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  25466. }
  25467. /* Update the state of the lock has held in the file descriptor then
  25468. ** return the appropriate result code.
  25469. */
  25470. if( res ){
  25471. rc = SQLITE_OK;
  25472. }else{
  25473. OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  25474. locktype, newLocktype);
  25475. pFile->lastErrno = error;
  25476. rc = SQLITE_BUSY;
  25477. }
  25478. pFile->locktype = (u8)newLocktype;
  25479. return rc;
  25480. }
  25481. /*
  25482. ** This routine checks if there is a RESERVED lock held on the specified
  25483. ** file by this or any other process. If such a lock is held, return
  25484. ** non-zero, otherwise zero.
  25485. */
  25486. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  25487. int rc;
  25488. winFile *pFile = (winFile*)id;
  25489. assert( id!=0 );
  25490. if( pFile->locktype>=RESERVED_LOCK ){
  25491. rc = 1;
  25492. OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
  25493. }else{
  25494. rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  25495. if( rc ){
  25496. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  25497. }
  25498. rc = !rc;
  25499. OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
  25500. }
  25501. *pResOut = rc;
  25502. return SQLITE_OK;
  25503. }
  25504. /*
  25505. ** Lower the locking level on file descriptor id to locktype. locktype
  25506. ** must be either NO_LOCK or SHARED_LOCK.
  25507. **
  25508. ** If the locking level of the file descriptor is already at or below
  25509. ** the requested locking level, this routine is a no-op.
  25510. **
  25511. ** It is not possible for this routine to fail if the second argument
  25512. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  25513. ** might return SQLITE_IOERR;
  25514. */
  25515. static int winUnlock(sqlite3_file *id, int locktype){
  25516. int type;
  25517. winFile *pFile = (winFile*)id;
  25518. int rc = SQLITE_OK;
  25519. assert( pFile!=0 );
  25520. assert( locktype<=SHARED_LOCK );
  25521. OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
  25522. pFile->locktype, pFile->sharedLockByte);
  25523. type = pFile->locktype;
  25524. if( type>=EXCLUSIVE_LOCK ){
  25525. UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  25526. if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  25527. /* This should never happen. We should always be able to
  25528. ** reacquire the read lock */
  25529. rc = SQLITE_IOERR_UNLOCK;
  25530. }
  25531. }
  25532. if( type>=RESERVED_LOCK ){
  25533. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  25534. }
  25535. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  25536. unlockReadLock(pFile);
  25537. }
  25538. if( type>=PENDING_LOCK ){
  25539. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  25540. }
  25541. pFile->locktype = (u8)locktype;
  25542. return rc;
  25543. }
  25544. /*
  25545. ** Control and query of the open file handle.
  25546. */
  25547. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  25548. switch( op ){
  25549. case SQLITE_FCNTL_LOCKSTATE: {
  25550. *(int*)pArg = ((winFile*)id)->locktype;
  25551. return SQLITE_OK;
  25552. }
  25553. case SQLITE_LAST_ERRNO: {
  25554. *(int*)pArg = (int)((winFile*)id)->lastErrno;
  25555. return SQLITE_OK;
  25556. }
  25557. }
  25558. return SQLITE_ERROR;
  25559. }
  25560. /*
  25561. ** Return the sector size in bytes of the underlying block device for
  25562. ** the specified file. This is almost always 512 bytes, but may be
  25563. ** larger for some devices.
  25564. **
  25565. ** SQLite code assumes this function cannot fail. It also assumes that
  25566. ** if two files are created in the same file-system directory (i.e.
  25567. ** a database and its journal file) that the sector size will be the
  25568. ** same for both.
  25569. */
  25570. static int winSectorSize(sqlite3_file *id){
  25571. assert( id!=0 );
  25572. return (int)(((winFile*)id)->sectorSize);
  25573. }
  25574. /*
  25575. ** Return a vector of device characteristics.
  25576. */
  25577. static int winDeviceCharacteristics(sqlite3_file *id){
  25578. UNUSED_PARAMETER(id);
  25579. return 0;
  25580. }
  25581. /*
  25582. ** This vector defines all the methods that can operate on an
  25583. ** sqlite3_file for win32.
  25584. */
  25585. static const sqlite3_io_methods winIoMethod = {
  25586. 1, /* iVersion */
  25587. winClose,
  25588. winRead,
  25589. winWrite,
  25590. winTruncate,
  25591. winSync,
  25592. winFileSize,
  25593. winLock,
  25594. winUnlock,
  25595. winCheckReservedLock,
  25596. winFileControl,
  25597. winSectorSize,
  25598. winDeviceCharacteristics
  25599. };
  25600. /***************************************************************************
  25601. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  25602. **
  25603. ** The next block of code implements the VFS methods.
  25604. ****************************************************************************/
  25605. /*
  25606. ** Convert a UTF-8 filename into whatever form the underlying
  25607. ** operating system wants filenames in. Space to hold the result
  25608. ** is obtained from malloc and must be freed by the calling
  25609. ** function.
  25610. */
  25611. static void *convertUtf8Filename(const char *zFilename){
  25612. void *zConverted = 0;
  25613. if( isNT() ){
  25614. zConverted = utf8ToUnicode(zFilename);
  25615. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25616. */
  25617. #if SQLITE_OS_WINCE==0
  25618. }else{
  25619. zConverted = utf8ToMbcs(zFilename);
  25620. #endif
  25621. }
  25622. /* caller will handle out of memory */
  25623. return zConverted;
  25624. }
  25625. /*
  25626. ** Create a temporary file name in zBuf. zBuf must be big enough to
  25627. ** hold at pVfs->mxPathname characters.
  25628. */
  25629. static int getTempname(int nBuf, char *zBuf){
  25630. static char zChars[] =
  25631. "abcdefghijklmnopqrstuvwxyz"
  25632. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  25633. "0123456789";
  25634. size_t i, j;
  25635. char zTempPath[MAX_PATH+1];
  25636. if( sqlite3_temp_directory ){
  25637. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  25638. }else if( isNT() ){
  25639. char *zMulti;
  25640. WCHAR zWidePath[MAX_PATH];
  25641. GetTempPathW(MAX_PATH-30, zWidePath);
  25642. zMulti = unicodeToUtf8(zWidePath);
  25643. if( zMulti ){
  25644. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  25645. free(zMulti);
  25646. }else{
  25647. return SQLITE_NOMEM;
  25648. }
  25649. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25650. ** Since the ASCII version of these Windows API do not exist for WINCE,
  25651. ** it's important to not reference them for WINCE builds.
  25652. */
  25653. #if SQLITE_OS_WINCE==0
  25654. }else{
  25655. char *zUtf8;
  25656. char zMbcsPath[MAX_PATH];
  25657. GetTempPathA(MAX_PATH-30, zMbcsPath);
  25658. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  25659. if( zUtf8 ){
  25660. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  25661. free(zUtf8);
  25662. }else{
  25663. return SQLITE_NOMEM;
  25664. }
  25665. #endif
  25666. }
  25667. for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
  25668. zTempPath[i] = 0;
  25669. sqlite3_snprintf(nBuf-30, zBuf,
  25670. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  25671. j = sqlite3Strlen30(zBuf);
  25672. sqlite3_randomness(20, &zBuf[j]);
  25673. for(i=0; i<20; i++, j++){
  25674. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  25675. }
  25676. zBuf[j] = 0;
  25677. OSTRACE2("TEMP FILENAME: %s\n", zBuf);
  25678. return SQLITE_OK;
  25679. }
  25680. /*
  25681. ** The return value of getLastErrorMsg
  25682. ** is zero if the error message fits in the buffer, or non-zero
  25683. ** otherwise (if the message was truncated).
  25684. */
  25685. static int getLastErrorMsg(int nBuf, char *zBuf){
  25686. DWORD error = GetLastError();
  25687. #if SQLITE_OS_WINCE
  25688. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
  25689. #else
  25690. /* FormatMessage returns 0 on failure. Otherwise it
  25691. ** returns the number of TCHARs written to the output
  25692. ** buffer, excluding the terminating null char.
  25693. */
  25694. if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  25695. NULL,
  25696. error,
  25697. 0,
  25698. zBuf,
  25699. nBuf-1,
  25700. 0))
  25701. {
  25702. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
  25703. }
  25704. #endif
  25705. return 0;
  25706. }
  25707. /*
  25708. ** Open a file.
  25709. */
  25710. static int winOpen(
  25711. sqlite3_vfs *pVfs, /* Not used */
  25712. const char *zName, /* Name of the file (UTF-8) */
  25713. sqlite3_file *id, /* Write the SQLite file handle here */
  25714. int flags, /* Open mode flags */
  25715. int *pOutFlags /* Status return flags */
  25716. ){
  25717. HANDLE h;
  25718. DWORD dwDesiredAccess;
  25719. DWORD dwShareMode;
  25720. DWORD dwCreationDisposition;
  25721. DWORD dwFlagsAndAttributes = 0;
  25722. #if SQLITE_OS_WINCE
  25723. int isTemp = 0;
  25724. #endif
  25725. winFile *pFile = (winFile*)id;
  25726. void *zConverted; /* Filename in OS encoding */
  25727. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  25728. char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
  25729. assert( id!=0 );
  25730. UNUSED_PARAMETER(pVfs);
  25731. /* If the second argument to this function is NULL, generate a
  25732. ** temporary file name to use
  25733. */
  25734. if( !zUtf8Name ){
  25735. int rc = getTempname(MAX_PATH+1, zTmpname);
  25736. if( rc!=SQLITE_OK ){
  25737. return rc;
  25738. }
  25739. zUtf8Name = zTmpname;
  25740. }
  25741. /* Convert the filename to the system encoding. */
  25742. zConverted = convertUtf8Filename(zUtf8Name);
  25743. if( zConverted==0 ){
  25744. return SQLITE_NOMEM;
  25745. }
  25746. if( flags & SQLITE_OPEN_READWRITE ){
  25747. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  25748. }else{
  25749. dwDesiredAccess = GENERIC_READ;
  25750. }
  25751. if( flags & SQLITE_OPEN_CREATE ){
  25752. dwCreationDisposition = OPEN_ALWAYS;
  25753. }else{
  25754. dwCreationDisposition = OPEN_EXISTING;
  25755. }
  25756. if( flags & SQLITE_OPEN_MAIN_DB ){
  25757. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  25758. }else{
  25759. dwShareMode = 0;
  25760. }
  25761. if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  25762. #if SQLITE_OS_WINCE
  25763. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  25764. isTemp = 1;
  25765. #else
  25766. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  25767. | FILE_ATTRIBUTE_HIDDEN
  25768. | FILE_FLAG_DELETE_ON_CLOSE;
  25769. #endif
  25770. }else{
  25771. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  25772. }
  25773. /* Reports from the internet are that performance is always
  25774. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  25775. #if SQLITE_OS_WINCE
  25776. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  25777. #endif
  25778. if( isNT() ){
  25779. h = CreateFileW((WCHAR*)zConverted,
  25780. dwDesiredAccess,
  25781. dwShareMode,
  25782. NULL,
  25783. dwCreationDisposition,
  25784. dwFlagsAndAttributes,
  25785. NULL
  25786. );
  25787. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25788. ** Since the ASCII version of these Windows API do not exist for WINCE,
  25789. ** it's important to not reference them for WINCE builds.
  25790. */
  25791. #if SQLITE_OS_WINCE==0
  25792. }else{
  25793. h = CreateFileA((char*)zConverted,
  25794. dwDesiredAccess,
  25795. dwShareMode,
  25796. NULL,
  25797. dwCreationDisposition,
  25798. dwFlagsAndAttributes,
  25799. NULL
  25800. );
  25801. #endif
  25802. }
  25803. if( h==INVALID_HANDLE_VALUE ){
  25804. free(zConverted);
  25805. if( flags & SQLITE_OPEN_READWRITE ){
  25806. return winOpen(pVfs, zName, id,
  25807. ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
  25808. }else{
  25809. return SQLITE_CANTOPEN;
  25810. }
  25811. }
  25812. if( pOutFlags ){
  25813. if( flags & SQLITE_OPEN_READWRITE ){
  25814. *pOutFlags = SQLITE_OPEN_READWRITE;
  25815. }else{
  25816. *pOutFlags = SQLITE_OPEN_READONLY;
  25817. }
  25818. }
  25819. memset(pFile, 0, sizeof(*pFile));
  25820. pFile->pMethod = &winIoMethod;
  25821. pFile->h = h;
  25822. pFile->lastErrno = NO_ERROR;
  25823. pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
  25824. #if SQLITE_OS_WINCE
  25825. if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
  25826. (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
  25827. && !winceCreateLock(zName, pFile)
  25828. ){
  25829. CloseHandle(h);
  25830. free(zConverted);
  25831. return SQLITE_CANTOPEN;
  25832. }
  25833. if( isTemp ){
  25834. pFile->zDeleteOnClose = zConverted;
  25835. }else
  25836. #endif
  25837. {
  25838. free(zConverted);
  25839. }
  25840. OpenCounter(+1);
  25841. return SQLITE_OK;
  25842. }
  25843. /*
  25844. ** Delete the named file.
  25845. **
  25846. ** Note that windows does not allow a file to be deleted if some other
  25847. ** process has it open. Sometimes a virus scanner or indexing program
  25848. ** will open a journal file shortly after it is created in order to do
  25849. ** whatever it does. While this other process is holding the
  25850. ** file open, we will be unable to delete it. To work around this
  25851. ** problem, we delay 100 milliseconds and try to delete again. Up
  25852. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  25853. ** up and returning an error.
  25854. */
  25855. #define MX_DELETION_ATTEMPTS 5
  25856. static int winDelete(
  25857. sqlite3_vfs *pVfs, /* Not used on win32 */
  25858. const char *zFilename, /* Name of file to delete */
  25859. int syncDir /* Not used on win32 */
  25860. ){
  25861. int cnt = 0;
  25862. DWORD rc;
  25863. DWORD error = 0;
  25864. void *zConverted = convertUtf8Filename(zFilename);
  25865. UNUSED_PARAMETER(pVfs);
  25866. UNUSED_PARAMETER(syncDir);
  25867. if( zConverted==0 ){
  25868. return SQLITE_NOMEM;
  25869. }
  25870. SimulateIOError(return SQLITE_IOERR_DELETE);
  25871. if( isNT() ){
  25872. do{
  25873. DeleteFileW(zConverted);
  25874. }while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
  25875. || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
  25876. && (++cnt < MX_DELETION_ATTEMPTS)
  25877. && (Sleep(100), 1) );
  25878. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25879. ** Since the ASCII version of these Windows API do not exist for WINCE,
  25880. ** it's important to not reference them for WINCE builds.
  25881. */
  25882. #if SQLITE_OS_WINCE==0
  25883. }else{
  25884. do{
  25885. DeleteFileA(zConverted);
  25886. }while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
  25887. || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
  25888. && (++cnt < MX_DELETION_ATTEMPTS)
  25889. && (Sleep(100), 1) );
  25890. #endif
  25891. }
  25892. free(zConverted);
  25893. OSTRACE2("DELETE \"%s\"\n", zFilename);
  25894. return ( (rc == INVALID_FILE_ATTRIBUTES)
  25895. && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
  25896. }
  25897. /*
  25898. ** Check the existance and status of a file.
  25899. */
  25900. static int winAccess(
  25901. sqlite3_vfs *pVfs, /* Not used on win32 */
  25902. const char *zFilename, /* Name of file to check */
  25903. int flags, /* Type of test to make on this file */
  25904. int *pResOut /* OUT: Result */
  25905. ){
  25906. DWORD attr;
  25907. int rc = 0;
  25908. void *zConverted = convertUtf8Filename(zFilename);
  25909. UNUSED_PARAMETER(pVfs);
  25910. if( zConverted==0 ){
  25911. return SQLITE_NOMEM;
  25912. }
  25913. if( isNT() ){
  25914. attr = GetFileAttributesW((WCHAR*)zConverted);
  25915. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25916. ** Since the ASCII version of these Windows API do not exist for WINCE,
  25917. ** it's important to not reference them for WINCE builds.
  25918. */
  25919. #if SQLITE_OS_WINCE==0
  25920. }else{
  25921. attr = GetFileAttributesA((char*)zConverted);
  25922. #endif
  25923. }
  25924. free(zConverted);
  25925. switch( flags ){
  25926. case SQLITE_ACCESS_READ:
  25927. case SQLITE_ACCESS_EXISTS:
  25928. rc = attr!=INVALID_FILE_ATTRIBUTES;
  25929. break;
  25930. case SQLITE_ACCESS_READWRITE:
  25931. rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
  25932. break;
  25933. default:
  25934. assert(!"Invalid flags argument");
  25935. }
  25936. *pResOut = rc;
  25937. return SQLITE_OK;
  25938. }
  25939. /*
  25940. ** Turn a relative pathname into a full pathname. Write the full
  25941. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  25942. ** bytes in size.
  25943. */
  25944. static int winFullPathname(
  25945. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  25946. const char *zRelative, /* Possibly relative input path */
  25947. int nFull, /* Size of output buffer in bytes */
  25948. char *zFull /* Output buffer */
  25949. ){
  25950. #if defined(__CYGWIN__)
  25951. UNUSED_PARAMETER(nFull);
  25952. cygwin_conv_to_full_win32_path(zRelative, zFull);
  25953. return SQLITE_OK;
  25954. #endif
  25955. #if SQLITE_OS_WINCE
  25956. UNUSED_PARAMETER(nFull);
  25957. /* WinCE has no concept of a relative pathname, or so I am told. */
  25958. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
  25959. return SQLITE_OK;
  25960. #endif
  25961. #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
  25962. int nByte;
  25963. void *zConverted;
  25964. char *zOut;
  25965. UNUSED_PARAMETER(nFull);
  25966. zConverted = convertUtf8Filename(zRelative);
  25967. if( isNT() ){
  25968. WCHAR *zTemp;
  25969. nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
  25970. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  25971. if( zTemp==0 ){
  25972. free(zConverted);
  25973. return SQLITE_NOMEM;
  25974. }
  25975. GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
  25976. free(zConverted);
  25977. zOut = unicodeToUtf8(zTemp);
  25978. free(zTemp);
  25979. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  25980. ** Since the ASCII version of these Windows API do not exist for WINCE,
  25981. ** it's important to not reference them for WINCE builds.
  25982. */
  25983. #if SQLITE_OS_WINCE==0
  25984. }else{
  25985. char *zTemp;
  25986. nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
  25987. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  25988. if( zTemp==0 ){
  25989. free(zConverted);
  25990. return SQLITE_NOMEM;
  25991. }
  25992. GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  25993. free(zConverted);
  25994. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  25995. free(zTemp);
  25996. #endif
  25997. }
  25998. if( zOut ){
  25999. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
  26000. free(zOut);
  26001. return SQLITE_OK;
  26002. }else{
  26003. return SQLITE_NOMEM;
  26004. }
  26005. #endif
  26006. }
  26007. /*
  26008. ** Get the sector size of the device used to store
  26009. ** file.
  26010. */
  26011. static int getSectorSize(
  26012. sqlite3_vfs *pVfs,
  26013. const char *zRelative /* UTF-8 file name */
  26014. ){
  26015. DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  26016. char zFullpath[MAX_PATH+1];
  26017. int rc;
  26018. DWORD dwRet = 0, dwDummy;
  26019. /*
  26020. ** We need to get the full path name of the file
  26021. ** to get the drive letter to look up the sector
  26022. ** size.
  26023. */
  26024. rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
  26025. if( rc == SQLITE_OK )
  26026. {
  26027. void *zConverted = convertUtf8Filename(zFullpath);
  26028. if( zConverted ){
  26029. if( isNT() ){
  26030. int i;
  26031. /* trim path to just drive reference */
  26032. WCHAR *p = zConverted;
  26033. for(i=0;i<MAX_PATH;i++){
  26034. if( p[i] == '\\' ){
  26035. i++;
  26036. p[i] = '\0';
  26037. break;
  26038. }
  26039. }
  26040. dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
  26041. &dwDummy,
  26042. &bytesPerSector,
  26043. &dwDummy,
  26044. &dwDummy);
  26045. #if SQLITE_OS_WINCE==0
  26046. }else{
  26047. int i;
  26048. /* trim path to just drive reference */
  26049. CHAR *p = (CHAR *)zConverted;
  26050. for(i=0;i<MAX_PATH;i++){
  26051. if( p[i] == '\\' ){
  26052. i++;
  26053. p[i] = '\0';
  26054. break;
  26055. }
  26056. }
  26057. dwRet = GetDiskFreeSpaceA((CHAR*)zConverted,
  26058. &dwDummy,
  26059. &bytesPerSector,
  26060. &dwDummy,
  26061. &dwDummy);
  26062. #endif
  26063. }
  26064. free(zConverted);
  26065. }
  26066. if( !dwRet ){
  26067. bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  26068. }
  26069. }
  26070. return (int) bytesPerSector;
  26071. }
  26072. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  26073. /*
  26074. ** Interfaces for opening a shared library, finding entry points
  26075. ** within the shared library, and closing the shared library.
  26076. */
  26077. /*
  26078. ** Interfaces for opening a shared library, finding entry points
  26079. ** within the shared library, and closing the shared library.
  26080. */
  26081. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  26082. HANDLE h;
  26083. void *zConverted = convertUtf8Filename(zFilename);
  26084. UNUSED_PARAMETER(pVfs);
  26085. if( zConverted==0 ){
  26086. return 0;
  26087. }
  26088. if( isNT() ){
  26089. h = LoadLibraryW((WCHAR*)zConverted);
  26090. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  26091. ** Since the ASCII version of these Windows API do not exist for WINCE,
  26092. ** it's important to not reference them for WINCE builds.
  26093. */
  26094. #if SQLITE_OS_WINCE==0
  26095. }else{
  26096. h = LoadLibraryA((char*)zConverted);
  26097. #endif
  26098. }
  26099. free(zConverted);
  26100. return (void*)h;
  26101. }
  26102. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  26103. UNUSED_PARAMETER(pVfs);
  26104. getLastErrorMsg(nBuf, zBufOut);
  26105. }
  26106. void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  26107. UNUSED_PARAMETER(pVfs);
  26108. #if SQLITE_OS_WINCE
  26109. /* The GetProcAddressA() routine is only available on wince. */
  26110. return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
  26111. #else
  26112. /* All other windows platforms expect GetProcAddress() to take
  26113. ** an Ansi string regardless of the _UNICODE setting */
  26114. return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
  26115. #endif
  26116. }
  26117. void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  26118. UNUSED_PARAMETER(pVfs);
  26119. FreeLibrary((HANDLE)pHandle);
  26120. }
  26121. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  26122. #define winDlOpen 0
  26123. #define winDlError 0
  26124. #define winDlSym 0
  26125. #define winDlClose 0
  26126. #endif
  26127. /*
  26128. ** Write up to nBuf bytes of randomness into zBuf.
  26129. */
  26130. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  26131. int n = 0;
  26132. UNUSED_PARAMETER(pVfs);
  26133. #if defined(SQLITE_TEST)
  26134. n = nBuf;
  26135. memset(zBuf, 0, nBuf);
  26136. #else
  26137. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  26138. SYSTEMTIME x;
  26139. GetSystemTime(&x);
  26140. memcpy(&zBuf[n], &x, sizeof(x));
  26141. n += sizeof(x);
  26142. }
  26143. if( sizeof(DWORD)<=nBuf-n ){
  26144. DWORD pid = GetCurrentProcessId();
  26145. memcpy(&zBuf[n], &pid, sizeof(pid));
  26146. n += sizeof(pid);
  26147. }
  26148. if( sizeof(DWORD)<=nBuf-n ){
  26149. DWORD cnt = GetTickCount();
  26150. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  26151. n += sizeof(cnt);
  26152. }
  26153. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  26154. LARGE_INTEGER i;
  26155. QueryPerformanceCounter(&i);
  26156. memcpy(&zBuf[n], &i, sizeof(i));
  26157. n += sizeof(i);
  26158. }
  26159. #endif
  26160. return n;
  26161. }
  26162. /*
  26163. ** Sleep for a little while. Return the amount of time slept.
  26164. */
  26165. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  26166. Sleep((microsec+999)/1000);
  26167. UNUSED_PARAMETER(pVfs);
  26168. return ((microsec+999)/1000)*1000;
  26169. }
  26170. /*
  26171. ** The following variable, if set to a non-zero value, becomes the result
  26172. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  26173. */
  26174. #ifdef SQLITE_TEST
  26175. SQLITE_API int sqlite3_current_time = 0;
  26176. #endif
  26177. /*
  26178. ** Find the current time (in Universal Coordinated Time). Write the
  26179. ** current time and date as a Julian Day number into *prNow and
  26180. ** return 0. Return 1 if the time and date cannot be found.
  26181. */
  26182. int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  26183. FILETIME ft;
  26184. /* FILETIME structure is a 64-bit value representing the number of
  26185. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  26186. */
  26187. sqlite3_int64 timeW; /* Whole days */
  26188. sqlite3_int64 timeF; /* Fractional Days */
  26189. /* Number of 100-nanosecond intervals in a single day */
  26190. static const sqlite3_int64 ntuPerDay =
  26191. 10000000*(sqlite3_int64)86400;
  26192. /* Number of 100-nanosecond intervals in half of a day */
  26193. static const sqlite3_int64 ntuPerHalfDay =
  26194. 10000000*(sqlite3_int64)43200;
  26195. /* 2^32 - to avoid use of LL and warnings in gcc */
  26196. static const sqlite3_int64 max32BitValue =
  26197. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
  26198. #if SQLITE_OS_WINCE
  26199. SYSTEMTIME time;
  26200. GetSystemTime(&time);
  26201. /* if SystemTimeToFileTime() fails, it returns zero. */
  26202. if (!SystemTimeToFileTime(&time,&ft)){
  26203. return 1;
  26204. }
  26205. #else
  26206. GetSystemTimeAsFileTime( &ft );
  26207. #endif
  26208. UNUSED_PARAMETER(pVfs);
  26209. timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
  26210. timeF = timeW % ntuPerDay; /* fractional days (100-nanoseconds) */
  26211. timeW = timeW / ntuPerDay; /* whole days */
  26212. timeW = timeW + 2305813; /* add whole days (from 2305813.5) */
  26213. timeF = timeF + ntuPerHalfDay; /* add half a day (from 2305813.5) */
  26214. timeW = timeW + (timeF/ntuPerDay); /* add whole day if half day made one */
  26215. timeF = timeF % ntuPerDay; /* compute new fractional days */
  26216. *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
  26217. #ifdef SQLITE_TEST
  26218. if( sqlite3_current_time ){
  26219. *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
  26220. }
  26221. #endif
  26222. return 0;
  26223. }
  26224. /*
  26225. ** The idea is that this function works like a combination of
  26226. ** GetLastError() and FormatMessage() on windows (or errno and
  26227. ** strerror_r() on unix). After an error is returned by an OS
  26228. ** function, SQLite calls this function with zBuf pointing to
  26229. ** a buffer of nBuf bytes. The OS layer should populate the
  26230. ** buffer with a nul-terminated UTF-8 encoded error message
  26231. ** describing the last IO error to have occurred within the calling
  26232. ** thread.
  26233. **
  26234. ** If the error message is too large for the supplied buffer,
  26235. ** it should be truncated. The return value of xGetLastError
  26236. ** is zero if the error message fits in the buffer, or non-zero
  26237. ** otherwise (if the message was truncated). If non-zero is returned,
  26238. ** then it is not necessary to include the nul-terminator character
  26239. ** in the output buffer.
  26240. **
  26241. ** Not supplying an error message will have no adverse effect
  26242. ** on SQLite. It is fine to have an implementation that never
  26243. ** returns an error message:
  26244. **
  26245. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  26246. ** assert(zBuf[0]=='\0');
  26247. ** return 0;
  26248. ** }
  26249. **
  26250. ** However if an error message is supplied, it will be incorporated
  26251. ** by sqlite into the error message available to the user using
  26252. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  26253. */
  26254. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  26255. UNUSED_PARAMETER(pVfs);
  26256. return getLastErrorMsg(nBuf, zBuf);
  26257. }
  26258. /*
  26259. ** Initialize and deinitialize the operating system interface.
  26260. */
  26261. SQLITE_API int sqlite3_os_init(void){
  26262. static sqlite3_vfs winVfs = {
  26263. 1, /* iVersion */
  26264. sizeof(winFile), /* szOsFile */
  26265. MAX_PATH, /* mxPathname */
  26266. 0, /* pNext */
  26267. "win32", /* zName */
  26268. 0, /* pAppData */
  26269. winOpen, /* xOpen */
  26270. winDelete, /* xDelete */
  26271. winAccess, /* xAccess */
  26272. winFullPathname, /* xFullPathname */
  26273. winDlOpen, /* xDlOpen */
  26274. winDlError, /* xDlError */
  26275. winDlSym, /* xDlSym */
  26276. winDlClose, /* xDlClose */
  26277. winRandomness, /* xRandomness */
  26278. winSleep, /* xSleep */
  26279. winCurrentTime, /* xCurrentTime */
  26280. winGetLastError /* xGetLastError */
  26281. };
  26282. sqlite3_vfs_register(&winVfs, 1);
  26283. return SQLITE_OK;
  26284. }
  26285. SQLITE_API int sqlite3_os_end(void){
  26286. return SQLITE_OK;
  26287. }
  26288. #endif /* SQLITE_OS_WIN */
  26289. /************** End of os_win.c **********************************************/
  26290. /************** Begin file bitvec.c ******************************************/
  26291. /*
  26292. ** 2008 February 16
  26293. **
  26294. ** The author disclaims copyright to this source code. In place of
  26295. ** a legal notice, here is a blessing:
  26296. **
  26297. ** May you do good and not evil.
  26298. ** May you find forgiveness for yourself and forgive others.
  26299. ** May you share freely, never taking more than you give.
  26300. **
  26301. *************************************************************************
  26302. ** This file implements an object that represents a fixed-length
  26303. ** bitmap. Bits are numbered starting with 1.
  26304. **
  26305. ** A bitmap is used to record which pages of a database file have been
  26306. ** journalled during a transaction, or which pages have the "dont-write"
  26307. ** property. Usually only a few pages are meet either condition.
  26308. ** So the bitmap is usually sparse and has low cardinality.
  26309. ** But sometimes (for example when during a DROP of a large table) most
  26310. ** or all of the pages in a database can get journalled. In those cases,
  26311. ** the bitmap becomes dense with high cardinality. The algorithm needs
  26312. ** to handle both cases well.
  26313. **
  26314. ** The size of the bitmap is fixed when the object is created.
  26315. **
  26316. ** All bits are clear when the bitmap is created. Individual bits
  26317. ** may be set or cleared one at a time.
  26318. **
  26319. ** Test operations are about 100 times more common that set operations.
  26320. ** Clear operations are exceedingly rare. There are usually between
  26321. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  26322. ** sometimes grow into tens of thousands or larger. The size of the
  26323. ** Bitvec object is the number of pages in the database file at the
  26324. ** start of a transaction, and is thus usually less than a few thousand,
  26325. ** but can be as large as 2 billion for a really big database.
  26326. **
  26327. ** @(#) $Id: bitvec.c,v 1.14 2009/04/01 23:49:04 drh Exp $
  26328. */
  26329. /* Size of the Bitvec structure in bytes. */
  26330. #define BITVEC_SZ 512
  26331. /* Round the union size down to the nearest pointer boundary, since that's how
  26332. ** it will be aligned within the Bitvec struct. */
  26333. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  26334. /* Type of the array "element" for the bitmap representation.
  26335. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  26336. ** Setting this to the "natural word" size of your CPU may improve
  26337. ** performance. */
  26338. #define BITVEC_TELEM u8
  26339. /* Size, in bits, of the bitmap element. */
  26340. #define BITVEC_SZELEM 8
  26341. /* Number of elements in a bitmap array. */
  26342. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  26343. /* Number of bits in the bitmap array. */
  26344. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  26345. /* Number of u32 values in hash table. */
  26346. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  26347. /* Maximum number of entries in hash table before
  26348. ** sub-dividing and re-hashing. */
  26349. #define BITVEC_MXHASH (BITVEC_NINT/2)
  26350. /* Hashing function for the aHash representation.
  26351. ** Empirical testing showed that the *37 multiplier
  26352. ** (an arbitrary prime)in the hash function provided
  26353. ** no fewer collisions than the no-op *1. */
  26354. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  26355. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  26356. /*
  26357. ** A bitmap is an instance of the following structure.
  26358. **
  26359. ** This bitmap records the existance of zero or more bits
  26360. ** with values between 1 and iSize, inclusive.
  26361. **
  26362. ** There are three possible representations of the bitmap.
  26363. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  26364. ** bitmap. The least significant bit is bit 1.
  26365. **
  26366. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  26367. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  26368. **
  26369. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  26370. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  26371. ** handles up to iDivisor separate values of i. apSub[0] holds
  26372. ** values between 1 and iDivisor. apSub[1] holds values between
  26373. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  26374. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  26375. ** to hold deal with values between 1 and iDivisor.
  26376. */
  26377. struct Bitvec {
  26378. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  26379. u32 nSet; /* Number of bits that are set - only valid for aHash
  26380. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  26381. ** this would be 125. */
  26382. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  26383. /* Should >=0 for apSub element. */
  26384. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  26385. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  26386. union {
  26387. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  26388. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  26389. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  26390. } u;
  26391. };
  26392. /*
  26393. ** Create a new bitmap object able to handle bits between 0 and iSize,
  26394. ** inclusive. Return a pointer to the new object. Return NULL if
  26395. ** malloc fails.
  26396. */
  26397. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  26398. Bitvec *p;
  26399. assert( sizeof(*p)==BITVEC_SZ );
  26400. p = sqlite3MallocZero( sizeof(*p) );
  26401. if( p ){
  26402. p->iSize = iSize;
  26403. }
  26404. return p;
  26405. }
  26406. /*
  26407. ** Check to see if the i-th bit is set. Return true or false.
  26408. ** If p is NULL (if the bitmap has not been created) or if
  26409. ** i is out of range, then return false.
  26410. */
  26411. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  26412. if( p==0 ) return 0;
  26413. if( i>p->iSize || i==0 ) return 0;
  26414. i--;
  26415. while( p->iDivisor ){
  26416. u32 bin = i/p->iDivisor;
  26417. i = i%p->iDivisor;
  26418. p = p->u.apSub[bin];
  26419. if (!p) {
  26420. return 0;
  26421. }
  26422. }
  26423. if( p->iSize<=BITVEC_NBIT ){
  26424. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  26425. } else{
  26426. u32 h = BITVEC_HASH(i++);
  26427. while( p->u.aHash[h] ){
  26428. if( p->u.aHash[h]==i ) return 1;
  26429. h++;
  26430. if( h>=BITVEC_NINT ) h = 0;
  26431. }
  26432. return 0;
  26433. }
  26434. }
  26435. /*
  26436. ** Set the i-th bit. Return 0 on success and an error code if
  26437. ** anything goes wrong.
  26438. **
  26439. ** This routine might cause sub-bitmaps to be allocated. Failing
  26440. ** to get the memory needed to hold the sub-bitmap is the only
  26441. ** that can go wrong with an insert, assuming p and i are valid.
  26442. **
  26443. ** The calling function must ensure that p is a valid Bitvec object
  26444. ** and that the value for "i" is within range of the Bitvec object.
  26445. ** Otherwise the behavior is undefined.
  26446. */
  26447. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  26448. u32 h;
  26449. assert( p!=0 );
  26450. assert( i>0 );
  26451. assert( i<=p->iSize );
  26452. i--;
  26453. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  26454. u32 bin = i/p->iDivisor;
  26455. i = i%p->iDivisor;
  26456. if( p->u.apSub[bin]==0 ){
  26457. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  26458. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  26459. }
  26460. p = p->u.apSub[bin];
  26461. }
  26462. if( p->iSize<=BITVEC_NBIT ){
  26463. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  26464. return SQLITE_OK;
  26465. }
  26466. h = BITVEC_HASH(i++);
  26467. /* if there wasn't a hash collision, and this doesn't */
  26468. /* completely fill the hash, then just add it without */
  26469. /* worring about sub-dividing and re-hashing. */
  26470. if( !p->u.aHash[h] ){
  26471. if (p->nSet<(BITVEC_NINT-1)) {
  26472. goto bitvec_set_end;
  26473. } else {
  26474. goto bitvec_set_rehash;
  26475. }
  26476. }
  26477. /* there was a collision, check to see if it's already */
  26478. /* in hash, if not, try to find a spot for it */
  26479. do {
  26480. if( p->u.aHash[h]==i ) return SQLITE_OK;
  26481. h++;
  26482. if( h>=BITVEC_NINT ) h = 0;
  26483. } while( p->u.aHash[h] );
  26484. /* we didn't find it in the hash. h points to the first */
  26485. /* available free spot. check to see if this is going to */
  26486. /* make our hash too "full". */
  26487. bitvec_set_rehash:
  26488. if( p->nSet>=BITVEC_MXHASH ){
  26489. unsigned int j;
  26490. int rc;
  26491. u32 aiValues[BITVEC_NINT];
  26492. memcpy(aiValues, p->u.aHash, sizeof(aiValues));
  26493. memset(p->u.apSub, 0, sizeof(aiValues));
  26494. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  26495. rc = sqlite3BitvecSet(p, i);
  26496. for(j=0; j<BITVEC_NINT; j++){
  26497. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  26498. }
  26499. return rc;
  26500. }
  26501. bitvec_set_end:
  26502. p->nSet++;
  26503. p->u.aHash[h] = i;
  26504. return SQLITE_OK;
  26505. }
  26506. /*
  26507. ** Clear the i-th bit.
  26508. */
  26509. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
  26510. assert( p!=0 );
  26511. assert( i>0 );
  26512. i--;
  26513. while( p->iDivisor ){
  26514. u32 bin = i/p->iDivisor;
  26515. i = i%p->iDivisor;
  26516. p = p->u.apSub[bin];
  26517. if (!p) {
  26518. return;
  26519. }
  26520. }
  26521. if( p->iSize<=BITVEC_NBIT ){
  26522. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  26523. }else{
  26524. unsigned int j;
  26525. u32 aiValues[BITVEC_NINT];
  26526. memcpy(aiValues, p->u.aHash, sizeof(aiValues));
  26527. memset(p->u.aHash, 0, sizeof(aiValues));
  26528. p->nSet = 0;
  26529. for(j=0; j<BITVEC_NINT; j++){
  26530. if( aiValues[j] && aiValues[j]!=(i+1) ){
  26531. u32 h = BITVEC_HASH(aiValues[j]-1);
  26532. p->nSet++;
  26533. while( p->u.aHash[h] ){
  26534. h++;
  26535. if( h>=BITVEC_NINT ) h = 0;
  26536. }
  26537. p->u.aHash[h] = aiValues[j];
  26538. }
  26539. }
  26540. }
  26541. }
  26542. /*
  26543. ** Destroy a bitmap object. Reclaim all memory used.
  26544. */
  26545. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  26546. if( p==0 ) return;
  26547. if( p->iDivisor ){
  26548. unsigned int i;
  26549. for(i=0; i<BITVEC_NPTR; i++){
  26550. sqlite3BitvecDestroy(p->u.apSub[i]);
  26551. }
  26552. }
  26553. sqlite3_free(p);
  26554. }
  26555. /*
  26556. ** Return the value of the iSize parameter specified when Bitvec *p
  26557. ** was created.
  26558. */
  26559. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  26560. return p->iSize;
  26561. }
  26562. #ifndef SQLITE_OMIT_BUILTIN_TEST
  26563. /*
  26564. ** Let V[] be an array of unsigned characters sufficient to hold
  26565. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  26566. ** Then the following macros can be used to set, clear, or test
  26567. ** individual bits within V.
  26568. */
  26569. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  26570. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  26571. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  26572. /*
  26573. ** This routine runs an extensive test of the Bitvec code.
  26574. **
  26575. ** The input is an array of integers that acts as a program
  26576. ** to test the Bitvec. The integers are opcodes followed
  26577. ** by 0, 1, or 3 operands, depending on the opcode. Another
  26578. ** opcode follows immediately after the last operand.
  26579. **
  26580. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  26581. ** "halt" opcode and causes the test to end.
  26582. **
  26583. ** 0 Halt and return the number of errors
  26584. ** 1 N S X Set N bits beginning with S and incrementing by X
  26585. ** 2 N S X Clear N bits beginning with S and incrementing by X
  26586. ** 3 N Set N randomly chosen bits
  26587. ** 4 N Clear N randomly chosen bits
  26588. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  26589. **
  26590. ** The opcodes 1 through 4 perform set and clear operations are performed
  26591. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  26592. ** Opcode 5 works on the linear array only, not on the Bitvec.
  26593. ** Opcode 5 is used to deliberately induce a fault in order to
  26594. ** confirm that error detection works.
  26595. **
  26596. ** At the conclusion of the test the linear array is compared
  26597. ** against the Bitvec object. If there are any differences,
  26598. ** an error is returned. If they are the same, zero is returned.
  26599. **
  26600. ** If a memory allocation error occurs, return -1.
  26601. */
  26602. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  26603. Bitvec *pBitvec = 0;
  26604. unsigned char *pV = 0;
  26605. int rc = -1;
  26606. int i, nx, pc, op;
  26607. /* Allocate the Bitvec to be tested and a linear array of
  26608. ** bits to act as the reference */
  26609. pBitvec = sqlite3BitvecCreate( sz );
  26610. pV = sqlite3_malloc( (sz+7)/8 + 1 );
  26611. if( pBitvec==0 || pV==0 ) goto bitvec_end;
  26612. memset(pV, 0, (sz+7)/8 + 1);
  26613. /* Run the program */
  26614. pc = 0;
  26615. while( (op = aOp[pc])!=0 ){
  26616. switch( op ){
  26617. case 1:
  26618. case 2:
  26619. case 5: {
  26620. nx = 4;
  26621. i = aOp[pc+2] - 1;
  26622. aOp[pc+2] += aOp[pc+3];
  26623. break;
  26624. }
  26625. case 3:
  26626. case 4:
  26627. default: {
  26628. nx = 2;
  26629. sqlite3_randomness(sizeof(i), &i);
  26630. break;
  26631. }
  26632. }
  26633. if( (--aOp[pc+1]) > 0 ) nx = 0;
  26634. pc += nx;
  26635. i = (i & 0x7fffffff)%sz;
  26636. if( (op & 1)!=0 ){
  26637. SETBIT(pV, (i+1));
  26638. if( op!=5 ){
  26639. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  26640. }
  26641. }else{
  26642. CLEARBIT(pV, (i+1));
  26643. sqlite3BitvecClear(pBitvec, i+1);
  26644. }
  26645. }
  26646. /* Test to make sure the linear array exactly matches the
  26647. ** Bitvec object. Start with the assumption that they do
  26648. ** match (rc==0). Change rc to non-zero if a discrepancy
  26649. ** is found.
  26650. */
  26651. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  26652. + sqlite3BitvecTest(pBitvec, 0)
  26653. + (sqlite3BitvecSize(pBitvec) - sz);
  26654. for(i=1; i<=sz; i++){
  26655. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  26656. rc = i;
  26657. break;
  26658. }
  26659. }
  26660. /* Free allocated structure */
  26661. bitvec_end:
  26662. sqlite3_free(pV);
  26663. sqlite3BitvecDestroy(pBitvec);
  26664. return rc;
  26665. }
  26666. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  26667. /************** End of bitvec.c **********************************************/
  26668. /************** Begin file pcache.c ******************************************/
  26669. /*
  26670. ** 2008 August 05
  26671. **
  26672. ** The author disclaims copyright to this source code. In place of
  26673. ** a legal notice, here is a blessing:
  26674. **
  26675. ** May you do good and not evil.
  26676. ** May you find forgiveness for yourself and forgive others.
  26677. ** May you share freely, never taking more than you give.
  26678. **
  26679. *************************************************************************
  26680. ** This file implements that page cache.
  26681. **
  26682. ** @(#) $Id: pcache.c,v 1.44 2009/03/31 01:32:18 drh Exp $
  26683. */
  26684. /*
  26685. ** A complete page cache is an instance of this structure.
  26686. */
  26687. struct PCache {
  26688. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  26689. PgHdr *pSynced; /* Last synced page in dirty page list */
  26690. int nRef; /* Number of referenced pages */
  26691. int nMax; /* Configured cache size */
  26692. int szPage; /* Size of every page in this cache */
  26693. int szExtra; /* Size of extra space for each page */
  26694. int bPurgeable; /* True if pages are on backing store */
  26695. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  26696. void *pStress; /* Argument to xStress */
  26697. sqlite3_pcache *pCache; /* Pluggable cache module */
  26698. PgHdr *pPage1; /* Reference to page 1 */
  26699. };
  26700. /*
  26701. ** Some of the assert() macros in this code are too expensive to run
  26702. ** even during normal debugging. Use them only rarely on long-running
  26703. ** tests. Enable the expensive asserts using the
  26704. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  26705. */
  26706. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  26707. # define expensive_assert(X) assert(X)
  26708. #else
  26709. # define expensive_assert(X)
  26710. #endif
  26711. /********************************** Linked List Management ********************/
  26712. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  26713. /*
  26714. ** Check that the pCache->pSynced variable is set correctly. If it
  26715. ** is not, either fail an assert or return zero. Otherwise, return
  26716. ** non-zero. This is only used in debugging builds, as follows:
  26717. **
  26718. ** expensive_assert( pcacheCheckSynced(pCache) );
  26719. */
  26720. static int pcacheCheckSynced(PCache *pCache){
  26721. PgHdr *p;
  26722. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  26723. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  26724. }
  26725. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  26726. }
  26727. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  26728. /*
  26729. ** Remove page pPage from the list of dirty pages.
  26730. */
  26731. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  26732. PCache *p = pPage->pCache;
  26733. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  26734. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  26735. /* Update the PCache1.pSynced variable if necessary. */
  26736. if( p->pSynced==pPage ){
  26737. PgHdr *pSynced = pPage->pDirtyPrev;
  26738. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  26739. pSynced = pSynced->pDirtyPrev;
  26740. }
  26741. p->pSynced = pSynced;
  26742. }
  26743. if( pPage->pDirtyNext ){
  26744. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  26745. }else{
  26746. assert( pPage==p->pDirtyTail );
  26747. p->pDirtyTail = pPage->pDirtyPrev;
  26748. }
  26749. if( pPage->pDirtyPrev ){
  26750. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  26751. }else{
  26752. assert( pPage==p->pDirty );
  26753. p->pDirty = pPage->pDirtyNext;
  26754. }
  26755. pPage->pDirtyNext = 0;
  26756. pPage->pDirtyPrev = 0;
  26757. expensive_assert( pcacheCheckSynced(p) );
  26758. }
  26759. /*
  26760. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  26761. ** pPage).
  26762. */
  26763. static void pcacheAddToDirtyList(PgHdr *pPage){
  26764. PCache *p = pPage->pCache;
  26765. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  26766. pPage->pDirtyNext = p->pDirty;
  26767. if( pPage->pDirtyNext ){
  26768. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  26769. pPage->pDirtyNext->pDirtyPrev = pPage;
  26770. }
  26771. p->pDirty = pPage;
  26772. if( !p->pDirtyTail ){
  26773. p->pDirtyTail = pPage;
  26774. }
  26775. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  26776. p->pSynced = pPage;
  26777. }
  26778. expensive_assert( pcacheCheckSynced(p) );
  26779. }
  26780. /*
  26781. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  26782. ** being used for an in-memory database, this function is a no-op.
  26783. */
  26784. static void pcacheUnpin(PgHdr *p){
  26785. PCache *pCache = p->pCache;
  26786. if( pCache->bPurgeable ){
  26787. if( p->pgno==1 ){
  26788. pCache->pPage1 = 0;
  26789. }
  26790. sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
  26791. }
  26792. }
  26793. /*************************************************** General Interfaces ******
  26794. **
  26795. ** Initialize and shutdown the page cache subsystem. Neither of these
  26796. ** functions are threadsafe.
  26797. */
  26798. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  26799. if( sqlite3GlobalConfig.pcache.xInit==0 ){
  26800. sqlite3PCacheSetDefault();
  26801. }
  26802. return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
  26803. }
  26804. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  26805. if( sqlite3GlobalConfig.pcache.xShutdown ){
  26806. sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
  26807. }
  26808. }
  26809. /*
  26810. ** Return the size in bytes of a PCache object.
  26811. */
  26812. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  26813. /*
  26814. ** Create a new PCache object. Storage space to hold the object
  26815. ** has already been allocated and is passed in as the p pointer.
  26816. ** The caller discovers how much space needs to be allocated by
  26817. ** calling sqlite3PcacheSize().
  26818. */
  26819. SQLITE_PRIVATE void sqlite3PcacheOpen(
  26820. int szPage, /* Size of every page */
  26821. int szExtra, /* Extra space associated with each page */
  26822. int bPurgeable, /* True if pages are on backing store */
  26823. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  26824. void *pStress, /* Argument to xStress */
  26825. PCache *p /* Preallocated space for the PCache */
  26826. ){
  26827. memset(p, 0, sizeof(PCache));
  26828. p->szPage = szPage;
  26829. p->szExtra = szExtra;
  26830. p->bPurgeable = bPurgeable;
  26831. p->xStress = xStress;
  26832. p->pStress = pStress;
  26833. p->nMax = 100;
  26834. }
  26835. /*
  26836. ** Change the page size for PCache object. The caller must ensure that there
  26837. ** are no outstanding page references when this function is called.
  26838. */
  26839. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  26840. assert( pCache->nRef==0 && pCache->pDirty==0 );
  26841. if( pCache->pCache ){
  26842. sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  26843. pCache->pCache = 0;
  26844. }
  26845. pCache->szPage = szPage;
  26846. }
  26847. /*
  26848. ** Try to obtain a page from the cache.
  26849. */
  26850. SQLITE_PRIVATE int sqlite3PcacheFetch(
  26851. PCache *pCache, /* Obtain the page from this cache */
  26852. Pgno pgno, /* Page number to obtain */
  26853. int createFlag, /* If true, create page if it does not exist already */
  26854. PgHdr **ppPage /* Write the page here */
  26855. ){
  26856. PgHdr *pPage = 0;
  26857. int eCreate;
  26858. assert( pCache!=0 );
  26859. assert( pgno>0 );
  26860. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  26861. ** allocate it now.
  26862. */
  26863. if( !pCache->pCache && createFlag ){
  26864. sqlite3_pcache *p;
  26865. int nByte;
  26866. nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
  26867. p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
  26868. if( !p ){
  26869. return SQLITE_NOMEM;
  26870. }
  26871. sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
  26872. pCache->pCache = p;
  26873. }
  26874. eCreate = createFlag ? 1 : 0;
  26875. if( eCreate && (!pCache->bPurgeable || !pCache->pDirty) ){
  26876. eCreate = 2;
  26877. }
  26878. if( pCache->pCache ){
  26879. pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
  26880. }
  26881. if( !pPage && eCreate==1 ){
  26882. PgHdr *pPg;
  26883. /* Find a dirty page to write-out and recycle. First try to find a
  26884. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  26885. ** cleared), but if that is not possible settle for any other
  26886. ** unreferenced dirty page.
  26887. */
  26888. expensive_assert( pcacheCheckSynced(pCache) );
  26889. for(pPg=pCache->pSynced;
  26890. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  26891. pPg=pPg->pDirtyPrev
  26892. );
  26893. if( !pPg ){
  26894. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  26895. }
  26896. if( pPg ){
  26897. int rc;
  26898. rc = pCache->xStress(pCache->pStress, pPg);
  26899. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  26900. return rc;
  26901. }
  26902. }
  26903. pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
  26904. }
  26905. if( pPage ){
  26906. if( !pPage->pData ){
  26907. memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
  26908. pPage->pExtra = (void*)&pPage[1];
  26909. pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
  26910. pPage->pCache = pCache;
  26911. pPage->pgno = pgno;
  26912. }
  26913. assert( pPage->pCache==pCache );
  26914. assert( pPage->pgno==pgno );
  26915. assert( pPage->pExtra==(void *)&pPage[1] );
  26916. if( 0==pPage->nRef ){
  26917. pCache->nRef++;
  26918. }
  26919. pPage->nRef++;
  26920. if( pgno==1 ){
  26921. pCache->pPage1 = pPage;
  26922. }
  26923. }
  26924. *ppPage = pPage;
  26925. return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  26926. }
  26927. /*
  26928. ** Decrement the reference count on a page. If the page is clean and the
  26929. ** reference count drops to 0, then it is made elible for recycling.
  26930. */
  26931. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  26932. assert( p->nRef>0 );
  26933. p->nRef--;
  26934. if( p->nRef==0 ){
  26935. PCache *pCache = p->pCache;
  26936. pCache->nRef--;
  26937. if( (p->flags&PGHDR_DIRTY)==0 ){
  26938. pcacheUnpin(p);
  26939. }else{
  26940. /* Move the page to the head of the dirty list. */
  26941. pcacheRemoveFromDirtyList(p);
  26942. pcacheAddToDirtyList(p);
  26943. }
  26944. }
  26945. }
  26946. /*
  26947. ** Increase the reference count of a supplied page by 1.
  26948. */
  26949. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  26950. assert(p->nRef>0);
  26951. p->nRef++;
  26952. }
  26953. /*
  26954. ** Drop a page from the cache. There must be exactly one reference to the
  26955. ** page. This function deletes that reference, so after it returns the
  26956. ** page pointed to by p is invalid.
  26957. */
  26958. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  26959. PCache *pCache;
  26960. assert( p->nRef==1 );
  26961. if( p->flags&PGHDR_DIRTY ){
  26962. pcacheRemoveFromDirtyList(p);
  26963. }
  26964. pCache = p->pCache;
  26965. pCache->nRef--;
  26966. if( p->pgno==1 ){
  26967. pCache->pPage1 = 0;
  26968. }
  26969. sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
  26970. }
  26971. /*
  26972. ** Make sure the page is marked as dirty. If it isn't dirty already,
  26973. ** make it so.
  26974. */
  26975. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  26976. p->flags &= ~PGHDR_DONT_WRITE;
  26977. assert( p->nRef>0 );
  26978. if( 0==(p->flags & PGHDR_DIRTY) ){
  26979. p->flags |= PGHDR_DIRTY;
  26980. pcacheAddToDirtyList( p);
  26981. }
  26982. }
  26983. /*
  26984. ** Make sure the page is marked as clean. If it isn't clean already,
  26985. ** make it so.
  26986. */
  26987. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  26988. if( (p->flags & PGHDR_DIRTY) ){
  26989. pcacheRemoveFromDirtyList(p);
  26990. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  26991. if( p->nRef==0 ){
  26992. pcacheUnpin(p);
  26993. }
  26994. }
  26995. }
  26996. /*
  26997. ** Make every page in the cache clean.
  26998. */
  26999. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  27000. PgHdr *p;
  27001. while( (p = pCache->pDirty)!=0 ){
  27002. sqlite3PcacheMakeClean(p);
  27003. }
  27004. }
  27005. /*
  27006. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  27007. */
  27008. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  27009. PgHdr *p;
  27010. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  27011. p->flags &= ~PGHDR_NEED_SYNC;
  27012. }
  27013. pCache->pSynced = pCache->pDirtyTail;
  27014. }
  27015. /*
  27016. ** Change the page number of page p to newPgno.
  27017. */
  27018. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  27019. PCache *pCache = p->pCache;
  27020. assert( p->nRef>0 );
  27021. assert( newPgno>0 );
  27022. sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
  27023. p->pgno = newPgno;
  27024. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  27025. pcacheRemoveFromDirtyList(p);
  27026. pcacheAddToDirtyList(p);
  27027. }
  27028. }
  27029. /*
  27030. ** Drop every cache entry whose page number is greater than "pgno". The
  27031. ** caller must ensure that there are no outstanding references to any pages
  27032. ** other than page 1 with a page number greater than pgno.
  27033. **
  27034. ** If there is a reference to page 1 and the pgno parameter passed to this
  27035. ** function is 0, then the data area associated with page 1 is zeroed, but
  27036. ** the page object is not dropped.
  27037. */
  27038. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  27039. if( pCache->pCache ){
  27040. PgHdr *p;
  27041. PgHdr *pNext;
  27042. for(p=pCache->pDirty; p; p=pNext){
  27043. pNext = p->pDirtyNext;
  27044. if( p->pgno>pgno ){
  27045. assert( p->flags&PGHDR_DIRTY );
  27046. sqlite3PcacheMakeClean(p);
  27047. }
  27048. }
  27049. if( pgno==0 && pCache->pPage1 ){
  27050. memset(pCache->pPage1->pData, 0, pCache->szPage);
  27051. pgno = 1;
  27052. }
  27053. sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
  27054. }
  27055. }
  27056. /*
  27057. ** Close a cache.
  27058. */
  27059. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  27060. if( pCache->pCache ){
  27061. sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  27062. }
  27063. }
  27064. /*
  27065. ** Discard the contents of the cache.
  27066. */
  27067. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  27068. sqlite3PcacheTruncate(pCache, 0);
  27069. }
  27070. /*
  27071. ** Merge two lists of pages connected by pDirty and in pgno order.
  27072. ** Do not both fixing the pDirtyPrev pointers.
  27073. */
  27074. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  27075. PgHdr result, *pTail;
  27076. pTail = &result;
  27077. while( pA && pB ){
  27078. if( pA->pgno<pB->pgno ){
  27079. pTail->pDirty = pA;
  27080. pTail = pA;
  27081. pA = pA->pDirty;
  27082. }else{
  27083. pTail->pDirty = pB;
  27084. pTail = pB;
  27085. pB = pB->pDirty;
  27086. }
  27087. }
  27088. if( pA ){
  27089. pTail->pDirty = pA;
  27090. }else if( pB ){
  27091. pTail->pDirty = pB;
  27092. }else{
  27093. pTail->pDirty = 0;
  27094. }
  27095. return result.pDirty;
  27096. }
  27097. /*
  27098. ** Sort the list of pages in accending order by pgno. Pages are
  27099. ** connected by pDirty pointers. The pDirtyPrev pointers are
  27100. ** corrupted by this sort.
  27101. */
  27102. #define N_SORT_BUCKET_ALLOC 25
  27103. #define N_SORT_BUCKET 25
  27104. #ifdef SQLITE_TEST
  27105. int sqlite3_pager_n_sort_bucket = 0;
  27106. #undef N_SORT_BUCKET
  27107. #define N_SORT_BUCKET \
  27108. (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
  27109. #endif
  27110. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  27111. PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
  27112. int i;
  27113. memset(a, 0, sizeof(a));
  27114. while( pIn ){
  27115. p = pIn;
  27116. pIn = p->pDirty;
  27117. p->pDirty = 0;
  27118. for(i=0; i<N_SORT_BUCKET-1; i++){
  27119. if( a[i]==0 ){
  27120. a[i] = p;
  27121. break;
  27122. }else{
  27123. p = pcacheMergeDirtyList(a[i], p);
  27124. a[i] = 0;
  27125. }
  27126. }
  27127. if( i==N_SORT_BUCKET-1 ){
  27128. /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET)
  27129. ** elements in the input list. This is possible, but impractical.
  27130. ** Testing this line is the point of global variable
  27131. ** sqlite3_pager_n_sort_bucket.
  27132. */
  27133. a[i] = pcacheMergeDirtyList(a[i], p);
  27134. }
  27135. }
  27136. p = a[0];
  27137. for(i=1; i<N_SORT_BUCKET; i++){
  27138. p = pcacheMergeDirtyList(p, a[i]);
  27139. }
  27140. return p;
  27141. }
  27142. /*
  27143. ** Return a list of all dirty pages in the cache, sorted by page number.
  27144. */
  27145. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  27146. PgHdr *p;
  27147. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  27148. p->pDirty = p->pDirtyNext;
  27149. }
  27150. return pcacheSortDirtyList(pCache->pDirty);
  27151. }
  27152. /*
  27153. ** Return the total number of referenced pages held by the cache.
  27154. */
  27155. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  27156. return pCache->nRef;
  27157. }
  27158. /*
  27159. ** Return the number of references to the page supplied as an argument.
  27160. */
  27161. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  27162. return p->nRef;
  27163. }
  27164. /*
  27165. ** Return the total number of pages in the cache.
  27166. */
  27167. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  27168. int nPage = 0;
  27169. if( pCache->pCache ){
  27170. nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
  27171. }
  27172. return nPage;
  27173. }
  27174. #ifdef SQLITE_TEST
  27175. /*
  27176. ** Get the suggested cache-size value.
  27177. */
  27178. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  27179. return pCache->nMax;
  27180. }
  27181. #endif
  27182. /*
  27183. ** Set the suggested cache-size value.
  27184. */
  27185. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  27186. pCache->nMax = mxPage;
  27187. if( pCache->pCache ){
  27188. sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
  27189. }
  27190. }
  27191. #ifdef SQLITE_CHECK_PAGES
  27192. /*
  27193. ** For all dirty pages currently in the cache, invoke the specified
  27194. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  27195. ** defined.
  27196. */
  27197. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  27198. PgHdr *pDirty;
  27199. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  27200. xIter(pDirty);
  27201. }
  27202. }
  27203. #endif
  27204. /************** End of pcache.c **********************************************/
  27205. /************** Begin file pcache1.c *****************************************/
  27206. /*
  27207. ** 2008 November 05
  27208. **
  27209. ** The author disclaims copyright to this source code. In place of
  27210. ** a legal notice, here is a blessing:
  27211. **
  27212. ** May you do good and not evil.
  27213. ** May you find forgiveness for yourself and forgive others.
  27214. ** May you share freely, never taking more than you give.
  27215. **
  27216. *************************************************************************
  27217. **
  27218. ** This file implements the default page cache implementation (the
  27219. ** sqlite3_pcache interface). It also contains part of the implementation
  27220. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  27221. ** If the default page cache implementation is overriden, then neither of
  27222. ** these two features are available.
  27223. **
  27224. ** @(#) $Id: pcache1.c,v 1.10 2009/03/23 04:33:33 danielk1977 Exp $
  27225. */
  27226. typedef struct PCache1 PCache1;
  27227. typedef struct PgHdr1 PgHdr1;
  27228. typedef struct PgFreeslot PgFreeslot;
  27229. /* Pointers to structures of this type are cast and returned as
  27230. ** opaque sqlite3_pcache* handles
  27231. */
  27232. struct PCache1 {
  27233. /* Cache configuration parameters. Page size (szPage) and the purgeable
  27234. ** flag (bPurgeable) are set when the cache is created. nMax may be
  27235. ** modified at any time by a call to the pcache1CacheSize() method.
  27236. ** The global mutex must be held when accessing nMax.
  27237. */
  27238. int szPage; /* Size of allocated pages in bytes */
  27239. int bPurgeable; /* True if cache is purgeable */
  27240. unsigned int nMin; /* Minimum number of pages reserved */
  27241. unsigned int nMax; /* Configured "cache_size" value */
  27242. /* Hash table of all pages. The following variables may only be accessed
  27243. ** when the accessor is holding the global mutex (see pcache1EnterMutex()
  27244. ** and pcache1LeaveMutex()).
  27245. */
  27246. unsigned int nRecyclable; /* Number of pages in the LRU list */
  27247. unsigned int nPage; /* Total number of pages in apHash */
  27248. unsigned int nHash; /* Number of slots in apHash[] */
  27249. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  27250. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  27251. };
  27252. /*
  27253. ** Each cache entry is represented by an instance of the following
  27254. ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
  27255. ** directly after the structure in memory (see the PGHDR1_TO_PAGE()
  27256. ** macro below).
  27257. */
  27258. struct PgHdr1 {
  27259. unsigned int iKey; /* Key value (page number) */
  27260. PgHdr1 *pNext; /* Next in hash table chain */
  27261. PCache1 *pCache; /* Cache that currently owns this page */
  27262. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  27263. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  27264. };
  27265. /*
  27266. ** Free slots in the allocator used to divide up the buffer provided using
  27267. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  27268. */
  27269. struct PgFreeslot {
  27270. PgFreeslot *pNext; /* Next free slot */
  27271. };
  27272. /*
  27273. ** Global data used by this cache.
  27274. */
  27275. static SQLITE_WSD struct PCacheGlobal {
  27276. sqlite3_mutex *mutex; /* static mutex MUTEX_STATIC_LRU */
  27277. int nMaxPage; /* Sum of nMaxPage for purgeable caches */
  27278. int nMinPage; /* Sum of nMinPage for purgeable caches */
  27279. int nCurrentPage; /* Number of purgeable pages allocated */
  27280. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  27281. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
  27282. int szSlot; /* Size of each free slot */
  27283. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  27284. PgFreeslot *pFree; /* Free page blocks */
  27285. } pcache1_g;
  27286. /*
  27287. ** All code in this file should access the global structure above via the
  27288. ** alias "pcache1". This ensures that the WSD emulation is used when
  27289. ** compiling for systems that do not support real WSD.
  27290. */
  27291. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  27292. /*
  27293. ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
  27294. ** bytes of data are located directly after it in memory (i.e. the total
  27295. ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
  27296. ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
  27297. ** an argument and returns a pointer to the associated block of szPage
  27298. ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
  27299. ** a pointer to a block of szPage bytes of data and the return value is
  27300. ** a pointer to the associated PgHdr1 structure.
  27301. **
  27302. ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(X))==X );
  27303. */
  27304. #define PGHDR1_TO_PAGE(p) (void *)(&((unsigned char *)p)[sizeof(PgHdr1)])
  27305. #define PAGE_TO_PGHDR1(p) (PgHdr1 *)(&((unsigned char *)p)[-1*(int)sizeof(PgHdr1)])
  27306. /*
  27307. ** Macros to enter and leave the global LRU mutex.
  27308. */
  27309. #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
  27310. #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
  27311. /******************************************************************************/
  27312. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  27313. /*
  27314. ** This function is called during initialization if a static buffer is
  27315. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  27316. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  27317. ** enough to contain 'n' buffers of 'sz' bytes each.
  27318. */
  27319. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  27320. PgFreeslot *p;
  27321. sz = ROUNDDOWN8(sz);
  27322. pcache1.szSlot = sz;
  27323. pcache1.pStart = pBuf;
  27324. pcache1.pFree = 0;
  27325. while( n-- ){
  27326. p = (PgFreeslot*)pBuf;
  27327. p->pNext = pcache1.pFree;
  27328. pcache1.pFree = p;
  27329. pBuf = (void*)&((char*)pBuf)[sz];
  27330. }
  27331. pcache1.pEnd = pBuf;
  27332. }
  27333. /*
  27334. ** Malloc function used within this file to allocate space from the buffer
  27335. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  27336. ** such buffer exists or there is no space left in it, this function falls
  27337. ** back to sqlite3Malloc().
  27338. */
  27339. static void *pcache1Alloc(int nByte){
  27340. void *p;
  27341. assert( sqlite3_mutex_held(pcache1.mutex) );
  27342. if( nByte<=pcache1.szSlot && pcache1.pFree ){
  27343. p = (PgHdr1 *)pcache1.pFree;
  27344. pcache1.pFree = pcache1.pFree->pNext;
  27345. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  27346. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  27347. }else{
  27348. /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
  27349. ** global pcache mutex and unlock the pager-cache object pCache. This is
  27350. ** so that if the attempt to allocate a new buffer causes the the
  27351. ** configured soft-heap-limit to be breached, it will be possible to
  27352. ** reclaim memory from this pager-cache.
  27353. */
  27354. pcache1LeaveMutex();
  27355. p = sqlite3Malloc(nByte);
  27356. pcache1EnterMutex();
  27357. if( p ){
  27358. int sz = sqlite3MallocSize(p);
  27359. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  27360. }
  27361. }
  27362. return p;
  27363. }
  27364. /*
  27365. ** Free an allocated buffer obtained from pcache1Alloc().
  27366. */
  27367. static void pcache1Free(void *p){
  27368. assert( sqlite3_mutex_held(pcache1.mutex) );
  27369. if( p==0 ) return;
  27370. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  27371. PgFreeslot *pSlot;
  27372. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  27373. pSlot = (PgFreeslot*)p;
  27374. pSlot->pNext = pcache1.pFree;
  27375. pcache1.pFree = pSlot;
  27376. }else{
  27377. int iSize = sqlite3MallocSize(p);
  27378. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
  27379. sqlite3_free(p);
  27380. }
  27381. }
  27382. /*
  27383. ** Allocate a new page object initially associated with cache pCache.
  27384. */
  27385. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  27386. int nByte = sizeof(PgHdr1) + pCache->szPage;
  27387. PgHdr1 *p = (PgHdr1 *)pcache1Alloc(nByte);
  27388. if( p ){
  27389. if( pCache->bPurgeable ){
  27390. pcache1.nCurrentPage++;
  27391. }
  27392. }
  27393. return p;
  27394. }
  27395. /*
  27396. ** Free a page object allocated by pcache1AllocPage().
  27397. */
  27398. static void pcache1FreePage(PgHdr1 *p){
  27399. if( p ){
  27400. if( p->pCache->bPurgeable ){
  27401. pcache1.nCurrentPage--;
  27402. }
  27403. pcache1Free(p);
  27404. }
  27405. }
  27406. /*
  27407. ** Malloc function used by SQLite to obtain space from the buffer configured
  27408. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  27409. ** exists, this function falls back to sqlite3Malloc().
  27410. */
  27411. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  27412. void *p;
  27413. pcache1EnterMutex();
  27414. p = pcache1Alloc(sz);
  27415. pcache1LeaveMutex();
  27416. return p;
  27417. }
  27418. /*
  27419. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  27420. */
  27421. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  27422. pcache1EnterMutex();
  27423. pcache1Free(p);
  27424. pcache1LeaveMutex();
  27425. }
  27426. /******************************************************************************/
  27427. /******** General Implementation Functions ************************************/
  27428. /*
  27429. ** This function is used to resize the hash table used by the cache passed
  27430. ** as the first argument.
  27431. **
  27432. ** The global mutex must be held when this function is called.
  27433. */
  27434. static int pcache1ResizeHash(PCache1 *p){
  27435. PgHdr1 **apNew;
  27436. unsigned int nNew;
  27437. unsigned int i;
  27438. assert( sqlite3_mutex_held(pcache1.mutex) );
  27439. nNew = p->nHash*2;
  27440. if( nNew<256 ){
  27441. nNew = 256;
  27442. }
  27443. pcache1LeaveMutex();
  27444. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  27445. apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
  27446. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  27447. pcache1EnterMutex();
  27448. if( apNew ){
  27449. memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
  27450. for(i=0; i<p->nHash; i++){
  27451. PgHdr1 *pPage;
  27452. PgHdr1 *pNext = p->apHash[i];
  27453. while( (pPage = pNext)!=0 ){
  27454. unsigned int h = pPage->iKey % nNew;
  27455. pNext = pPage->pNext;
  27456. pPage->pNext = apNew[h];
  27457. apNew[h] = pPage;
  27458. }
  27459. }
  27460. sqlite3_free(p->apHash);
  27461. p->apHash = apNew;
  27462. p->nHash = nNew;
  27463. }
  27464. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  27465. }
  27466. /*
  27467. ** This function is used internally to remove the page pPage from the
  27468. ** global LRU list, if is part of it. If pPage is not part of the global
  27469. ** LRU list, then this function is a no-op.
  27470. **
  27471. ** The global mutex must be held when this function is called.
  27472. */
  27473. static void pcache1PinPage(PgHdr1 *pPage){
  27474. assert( sqlite3_mutex_held(pcache1.mutex) );
  27475. if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
  27476. if( pPage->pLruPrev ){
  27477. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  27478. }
  27479. if( pPage->pLruNext ){
  27480. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  27481. }
  27482. if( pcache1.pLruHead==pPage ){
  27483. pcache1.pLruHead = pPage->pLruNext;
  27484. }
  27485. if( pcache1.pLruTail==pPage ){
  27486. pcache1.pLruTail = pPage->pLruPrev;
  27487. }
  27488. pPage->pLruNext = 0;
  27489. pPage->pLruPrev = 0;
  27490. pPage->pCache->nRecyclable--;
  27491. }
  27492. }
  27493. /*
  27494. ** Remove the page supplied as an argument from the hash table
  27495. ** (PCache1.apHash structure) that it is currently stored in.
  27496. **
  27497. ** The global mutex must be held when this function is called.
  27498. */
  27499. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  27500. unsigned int h;
  27501. PCache1 *pCache = pPage->pCache;
  27502. PgHdr1 **pp;
  27503. h = pPage->iKey % pCache->nHash;
  27504. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  27505. *pp = (*pp)->pNext;
  27506. pCache->nPage--;
  27507. }
  27508. /*
  27509. ** If there are currently more than pcache.nMaxPage pages allocated, try
  27510. ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
  27511. */
  27512. static void pcache1EnforceMaxPage(void){
  27513. assert( sqlite3_mutex_held(pcache1.mutex) );
  27514. while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
  27515. PgHdr1 *p = pcache1.pLruTail;
  27516. pcache1PinPage(p);
  27517. pcache1RemoveFromHash(p);
  27518. pcache1FreePage(p);
  27519. }
  27520. }
  27521. /*
  27522. ** Discard all pages from cache pCache with a page number (key value)
  27523. ** greater than or equal to iLimit. Any pinned pages that meet this
  27524. ** criteria are unpinned before they are discarded.
  27525. **
  27526. ** The global mutex must be held when this function is called.
  27527. */
  27528. static void pcache1TruncateUnsafe(
  27529. PCache1 *pCache,
  27530. unsigned int iLimit
  27531. ){
  27532. unsigned int h;
  27533. assert( sqlite3_mutex_held(pcache1.mutex) );
  27534. for(h=0; h<pCache->nHash; h++){
  27535. PgHdr1 **pp = &pCache->apHash[h];
  27536. PgHdr1 *pPage;
  27537. while( (pPage = *pp)!=0 ){
  27538. if( pPage->iKey>=iLimit ){
  27539. pcache1PinPage(pPage);
  27540. *pp = pPage->pNext;
  27541. pcache1FreePage(pPage);
  27542. }else{
  27543. pp = &pPage->pNext;
  27544. }
  27545. }
  27546. }
  27547. }
  27548. /******************************************************************************/
  27549. /******** sqlite3_pcache Methods **********************************************/
  27550. /*
  27551. ** Implementation of the sqlite3_pcache.xInit method.
  27552. */
  27553. static int pcache1Init(void *NotUsed){
  27554. UNUSED_PARAMETER(NotUsed);
  27555. memset(&pcache1, 0, sizeof(pcache1));
  27556. if( sqlite3GlobalConfig.bCoreMutex ){
  27557. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  27558. }
  27559. return SQLITE_OK;
  27560. }
  27561. /*
  27562. ** Implementation of the sqlite3_pcache.xShutdown method.
  27563. */
  27564. static void pcache1Shutdown(void *NotUsed){
  27565. UNUSED_PARAMETER(NotUsed);
  27566. /* no-op */
  27567. }
  27568. /*
  27569. ** Implementation of the sqlite3_pcache.xCreate method.
  27570. **
  27571. ** Allocate a new cache.
  27572. */
  27573. static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
  27574. PCache1 *pCache;
  27575. pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
  27576. if( pCache ){
  27577. memset(pCache, 0, sizeof(PCache1));
  27578. pCache->szPage = szPage;
  27579. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  27580. if( bPurgeable ){
  27581. pCache->nMin = 10;
  27582. pcache1EnterMutex();
  27583. pcache1.nMinPage += pCache->nMin;
  27584. pcache1LeaveMutex();
  27585. }
  27586. }
  27587. return (sqlite3_pcache *)pCache;
  27588. }
  27589. /*
  27590. ** Implementation of the sqlite3_pcache.xCachesize method.
  27591. **
  27592. ** Configure the cache_size limit for a cache.
  27593. */
  27594. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  27595. PCache1 *pCache = (PCache1 *)p;
  27596. if( pCache->bPurgeable ){
  27597. pcache1EnterMutex();
  27598. pcache1.nMaxPage += (nMax - pCache->nMax);
  27599. pCache->nMax = nMax;
  27600. pcache1EnforceMaxPage();
  27601. pcache1LeaveMutex();
  27602. }
  27603. }
  27604. /*
  27605. ** Implementation of the sqlite3_pcache.xPagecount method.
  27606. */
  27607. static int pcache1Pagecount(sqlite3_pcache *p){
  27608. int n;
  27609. pcache1EnterMutex();
  27610. n = ((PCache1 *)p)->nPage;
  27611. pcache1LeaveMutex();
  27612. return n;
  27613. }
  27614. /*
  27615. ** Implementation of the sqlite3_pcache.xFetch method.
  27616. **
  27617. ** Fetch a page by key value.
  27618. **
  27619. ** Whether or not a new page may be allocated by this function depends on
  27620. ** the value of the createFlag argument.
  27621. **
  27622. ** There are three different approaches to obtaining space for a page,
  27623. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  27624. **
  27625. ** 1. Regardless of the value of createFlag, the cache is searched for a
  27626. ** copy of the requested page. If one is found, it is returned.
  27627. **
  27628. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  27629. ** returned.
  27630. **
  27631. ** 3. If createFlag is 1, the cache is marked as purgeable and the page is
  27632. ** not already in the cache, and if either of the following are true,
  27633. ** return NULL:
  27634. **
  27635. ** (a) the number of pages pinned by the cache is greater than
  27636. ** PCache1.nMax, or
  27637. ** (b) the number of pages pinned by the cache is greater than
  27638. ** the sum of nMax for all purgeable caches, less the sum of
  27639. ** nMin for all other purgeable caches.
  27640. **
  27641. ** 4. If none of the first three conditions apply and the cache is marked
  27642. ** as purgeable, and if one of the following is true:
  27643. **
  27644. ** (a) The number of pages allocated for the cache is already
  27645. ** PCache1.nMax, or
  27646. **
  27647. ** (b) The number of pages allocated for all purgeable caches is
  27648. ** already equal to or greater than the sum of nMax for all
  27649. ** purgeable caches,
  27650. **
  27651. ** then attempt to recycle a page from the LRU list. If it is the right
  27652. ** size, return the recycled buffer. Otherwise, free the buffer and
  27653. ** proceed to step 5.
  27654. **
  27655. ** 5. Otherwise, allocate and return a new page buffer.
  27656. */
  27657. static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
  27658. unsigned int nPinned;
  27659. PCache1 *pCache = (PCache1 *)p;
  27660. PgHdr1 *pPage = 0;
  27661. pcache1EnterMutex();
  27662. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  27663. /* Search the hash table for an existing entry. */
  27664. if( pCache->nHash>0 ){
  27665. unsigned int h = iKey % pCache->nHash;
  27666. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  27667. }
  27668. if( pPage || createFlag==0 ){
  27669. pcache1PinPage(pPage);
  27670. goto fetch_out;
  27671. }
  27672. /* Step 3 of header comment. */
  27673. nPinned = pCache->nPage - pCache->nRecyclable;
  27674. if( createFlag==1 && pCache->bPurgeable && (
  27675. nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
  27676. || nPinned>=(pCache->nMax * 9 / 10)
  27677. )){
  27678. goto fetch_out;
  27679. }
  27680. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  27681. goto fetch_out;
  27682. }
  27683. /* Step 4. Try to recycle a page buffer if appropriate. */
  27684. if( pCache->bPurgeable && pcache1.pLruTail && (
  27685. pCache->nPage>=pCache->nMax-1 || pcache1.nCurrentPage>=pcache1.nMaxPage
  27686. )){
  27687. pPage = pcache1.pLruTail;
  27688. pcache1RemoveFromHash(pPage);
  27689. pcache1PinPage(pPage);
  27690. if( pPage->pCache->szPage!=pCache->szPage ){
  27691. pcache1FreePage(pPage);
  27692. pPage = 0;
  27693. }else{
  27694. pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
  27695. }
  27696. }
  27697. /* Step 5. If a usable page buffer has still not been found,
  27698. ** attempt to allocate a new one.
  27699. */
  27700. if( !pPage ){
  27701. pPage = pcache1AllocPage(pCache);
  27702. }
  27703. if( pPage ){
  27704. unsigned int h = iKey % pCache->nHash;
  27705. *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
  27706. pCache->nPage++;
  27707. pPage->iKey = iKey;
  27708. pPage->pNext = pCache->apHash[h];
  27709. pPage->pCache = pCache;
  27710. pPage->pLruPrev = 0;
  27711. pPage->pLruNext = 0;
  27712. pCache->apHash[h] = pPage;
  27713. }
  27714. fetch_out:
  27715. if( pPage && iKey>pCache->iMaxKey ){
  27716. pCache->iMaxKey = iKey;
  27717. }
  27718. if( createFlag==1 ) sqlite3EndBenignMalloc();
  27719. pcache1LeaveMutex();
  27720. return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
  27721. }
  27722. /*
  27723. ** Implementation of the sqlite3_pcache.xUnpin method.
  27724. **
  27725. ** Mark a page as unpinned (eligible for asynchronous recycling).
  27726. */
  27727. static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
  27728. PCache1 *pCache = (PCache1 *)p;
  27729. PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
  27730. pcache1EnterMutex();
  27731. /* It is an error to call this function if the page is already
  27732. ** part of the global LRU list.
  27733. */
  27734. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  27735. assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
  27736. if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
  27737. pcache1RemoveFromHash(pPage);
  27738. pcache1FreePage(pPage);
  27739. }else{
  27740. /* Add the page to the global LRU list. Normally, the page is added to
  27741. ** the head of the list (last page to be recycled). However, if the
  27742. ** reuseUnlikely flag passed to this function is true, the page is added
  27743. ** to the tail of the list (first page to be recycled).
  27744. */
  27745. if( pcache1.pLruHead ){
  27746. pcache1.pLruHead->pLruPrev = pPage;
  27747. pPage->pLruNext = pcache1.pLruHead;
  27748. pcache1.pLruHead = pPage;
  27749. }else{
  27750. pcache1.pLruTail = pPage;
  27751. pcache1.pLruHead = pPage;
  27752. }
  27753. pCache->nRecyclable++;
  27754. }
  27755. pcache1LeaveMutex();
  27756. }
  27757. /*
  27758. ** Implementation of the sqlite3_pcache.xRekey method.
  27759. */
  27760. static void pcache1Rekey(
  27761. sqlite3_pcache *p,
  27762. void *pPg,
  27763. unsigned int iOld,
  27764. unsigned int iNew
  27765. ){
  27766. PCache1 *pCache = (PCache1 *)p;
  27767. PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
  27768. PgHdr1 **pp;
  27769. unsigned int h;
  27770. assert( pPage->iKey==iOld );
  27771. pcache1EnterMutex();
  27772. h = iOld%pCache->nHash;
  27773. pp = &pCache->apHash[h];
  27774. while( (*pp)!=pPage ){
  27775. pp = &(*pp)->pNext;
  27776. }
  27777. *pp = pPage->pNext;
  27778. h = iNew%pCache->nHash;
  27779. pPage->iKey = iNew;
  27780. pPage->pNext = pCache->apHash[h];
  27781. pCache->apHash[h] = pPage;
  27782. if( iNew>pCache->iMaxKey ){
  27783. pCache->iMaxKey = iNew;
  27784. }
  27785. pcache1LeaveMutex();
  27786. }
  27787. /*
  27788. ** Implementation of the sqlite3_pcache.xTruncate method.
  27789. **
  27790. ** Discard all unpinned pages in the cache with a page number equal to
  27791. ** or greater than parameter iLimit. Any pinned pages with a page number
  27792. ** equal to or greater than iLimit are implicitly unpinned.
  27793. */
  27794. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  27795. PCache1 *pCache = (PCache1 *)p;
  27796. pcache1EnterMutex();
  27797. if( iLimit<=pCache->iMaxKey ){
  27798. pcache1TruncateUnsafe(pCache, iLimit);
  27799. pCache->iMaxKey = iLimit-1;
  27800. }
  27801. pcache1LeaveMutex();
  27802. }
  27803. /*
  27804. ** Implementation of the sqlite3_pcache.xDestroy method.
  27805. **
  27806. ** Destroy a cache allocated using pcache1Create().
  27807. */
  27808. static void pcache1Destroy(sqlite3_pcache *p){
  27809. PCache1 *pCache = (PCache1 *)p;
  27810. pcache1EnterMutex();
  27811. pcache1TruncateUnsafe(pCache, 0);
  27812. pcache1.nMaxPage -= pCache->nMax;
  27813. pcache1.nMinPage -= pCache->nMin;
  27814. pcache1EnforceMaxPage();
  27815. pcache1LeaveMutex();
  27816. sqlite3_free(pCache->apHash);
  27817. sqlite3_free(pCache);
  27818. }
  27819. /*
  27820. ** This function is called during initialization (sqlite3_initialize()) to
  27821. ** install the default pluggable cache module, assuming the user has not
  27822. ** already provided an alternative.
  27823. */
  27824. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  27825. static sqlite3_pcache_methods defaultMethods = {
  27826. 0, /* pArg */
  27827. pcache1Init, /* xInit */
  27828. pcache1Shutdown, /* xShutdown */
  27829. pcache1Create, /* xCreate */
  27830. pcache1Cachesize, /* xCachesize */
  27831. pcache1Pagecount, /* xPagecount */
  27832. pcache1Fetch, /* xFetch */
  27833. pcache1Unpin, /* xUnpin */
  27834. pcache1Rekey, /* xRekey */
  27835. pcache1Truncate, /* xTruncate */
  27836. pcache1Destroy /* xDestroy */
  27837. };
  27838. sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
  27839. }
  27840. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  27841. /*
  27842. ** This function is called to free superfluous dynamically allocated memory
  27843. ** held by the pager system. Memory in use by any SQLite pager allocated
  27844. ** by the current thread may be sqlite3_free()ed.
  27845. **
  27846. ** nReq is the number of bytes of memory required. Once this much has
  27847. ** been released, the function returns. The return value is the total number
  27848. ** of bytes of memory released.
  27849. */
  27850. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  27851. int nFree = 0;
  27852. if( pcache1.pStart==0 ){
  27853. PgHdr1 *p;
  27854. pcache1EnterMutex();
  27855. while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
  27856. nFree += sqlite3MallocSize(p);
  27857. pcache1PinPage(p);
  27858. pcache1RemoveFromHash(p);
  27859. pcache1FreePage(p);
  27860. }
  27861. pcache1LeaveMutex();
  27862. }
  27863. return nFree;
  27864. }
  27865. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  27866. #ifdef SQLITE_TEST
  27867. /*
  27868. ** This function is used by test procedures to inspect the internal state
  27869. ** of the global cache.
  27870. */
  27871. SQLITE_PRIVATE void sqlite3PcacheStats(
  27872. int *pnCurrent, /* OUT: Total number of pages cached */
  27873. int *pnMax, /* OUT: Global maximum cache size */
  27874. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  27875. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  27876. ){
  27877. PgHdr1 *p;
  27878. int nRecyclable = 0;
  27879. for(p=pcache1.pLruHead; p; p=p->pLruNext){
  27880. nRecyclable++;
  27881. }
  27882. *pnCurrent = pcache1.nCurrentPage;
  27883. *pnMax = pcache1.nMaxPage;
  27884. *pnMin = pcache1.nMinPage;
  27885. *pnRecyclable = nRecyclable;
  27886. }
  27887. #endif
  27888. /************** End of pcache1.c *********************************************/
  27889. /************** Begin file rowset.c ******************************************/
  27890. /*
  27891. ** 2008 December 3
  27892. **
  27893. ** The author disclaims copyright to this source code. In place of
  27894. ** a legal notice, here is a blessing:
  27895. **
  27896. ** May you do good and not evil.
  27897. ** May you find forgiveness for yourself and forgive others.
  27898. ** May you share freely, never taking more than you give.
  27899. **
  27900. *************************************************************************
  27901. **
  27902. ** This module implements an object we call a "Row Set".
  27903. **
  27904. ** The RowSet object is a bag of rowids. Rowids
  27905. ** are inserted into the bag in an arbitrary order. Then they are
  27906. ** pulled from the bag in sorted order. Rowids only appear in the
  27907. ** bag once. If the same rowid is inserted multiple times, the
  27908. ** second and subsequent inserts make no difference on the output.
  27909. **
  27910. ** This implementation accumulates rowids in a linked list. For
  27911. ** output, it first sorts the linked list (removing duplicates during
  27912. ** the sort) then returns elements one by one by walking the list.
  27913. **
  27914. ** Big chunks of rowid/next-ptr pairs are allocated at a time, to
  27915. ** reduce the malloc overhead.
  27916. **
  27917. ** $Id: rowset.c,v 1.4 2009/04/01 19:35:55 drh Exp $
  27918. */
  27919. /*
  27920. ** The number of rowset entries per allocation chunk.
  27921. */
  27922. #define ROWSET_ENTRY_PER_CHUNK 63
  27923. /*
  27924. ** Each entry in a RowSet is an instance of the following
  27925. ** structure:
  27926. */
  27927. struct RowSetEntry {
  27928. i64 v; /* ROWID value for this entry */
  27929. struct RowSetEntry *pNext; /* Next entry on a list of all entries */
  27930. };
  27931. /*
  27932. ** Index entries are allocated in large chunks (instances of the
  27933. ** following structure) to reduce memory allocation overhead. The
  27934. ** chunks are kept on a linked list so that they can be deallocated
  27935. ** when the RowSet is destroyed.
  27936. */
  27937. struct RowSetChunk {
  27938. struct RowSetChunk *pNext; /* Next chunk on list of them all */
  27939. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  27940. };
  27941. /*
  27942. ** A RowSet in an instance of the following structure.
  27943. **
  27944. ** A typedef of this structure if found in sqliteInt.h.
  27945. */
  27946. struct RowSet {
  27947. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  27948. sqlite3 *db; /* The database connection */
  27949. struct RowSetEntry *pEntry; /* List of entries in the rowset */
  27950. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  27951. struct RowSetEntry *pFresh; /* Source of new entry objects */
  27952. u16 nFresh; /* Number of objects on pFresh */
  27953. u8 isSorted; /* True if content is sorted */
  27954. };
  27955. /*
  27956. ** Turn bulk memory into a RowSet object. N bytes of memory
  27957. ** are available at pSpace. The db pointer is used as a memory context
  27958. ** for any subsequent allocations that need to occur.
  27959. ** Return a pointer to the new RowSet object.
  27960. **
  27961. ** It must be the case that N is sufficient to make a Rowset. If not
  27962. ** an assertion fault occurs.
  27963. **
  27964. ** If N is larger than the minimum, use the surplus as an initial
  27965. ** allocation of entries available to be filled.
  27966. */
  27967. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  27968. RowSet *p;
  27969. assert( N >= sizeof(*p) );
  27970. p = pSpace;
  27971. p->pChunk = 0;
  27972. p->db = db;
  27973. p->pEntry = 0;
  27974. p->pLast = 0;
  27975. p->pFresh = (struct RowSetEntry*)&p[1];
  27976. p->nFresh = (u16)((N - sizeof(*p))/sizeof(struct RowSetEntry));
  27977. p->isSorted = 1;
  27978. return p;
  27979. }
  27980. /*
  27981. ** Deallocate all chunks from a RowSet.
  27982. */
  27983. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  27984. struct RowSetChunk *pChunk, *pNextChunk;
  27985. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  27986. pNextChunk = pChunk->pNext;
  27987. sqlite3DbFree(p->db, pChunk);
  27988. }
  27989. p->pChunk = 0;
  27990. p->nFresh = 0;
  27991. p->pEntry = 0;
  27992. p->pLast = 0;
  27993. p->isSorted = 1;
  27994. }
  27995. /*
  27996. ** Insert a new value into a RowSet.
  27997. **
  27998. ** The mallocFailed flag of the database connection is set if a
  27999. ** memory allocation fails.
  28000. */
  28001. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  28002. struct RowSetEntry *pEntry;
  28003. struct RowSetEntry *pLast;
  28004. assert( p!=0 );
  28005. if( p->nFresh==0 ){
  28006. struct RowSetChunk *pNew;
  28007. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  28008. if( pNew==0 ){
  28009. return;
  28010. }
  28011. pNew->pNext = p->pChunk;
  28012. p->pChunk = pNew;
  28013. p->pFresh = pNew->aEntry;
  28014. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  28015. }
  28016. pEntry = p->pFresh++;
  28017. p->nFresh--;
  28018. pEntry->v = rowid;
  28019. pEntry->pNext = 0;
  28020. pLast = p->pLast;
  28021. if( pLast ){
  28022. if( p->isSorted && rowid<=pLast->v ){
  28023. p->isSorted = 0;
  28024. }
  28025. pLast->pNext = pEntry;
  28026. }else{
  28027. assert( p->pEntry==0 );
  28028. p->pEntry = pEntry;
  28029. }
  28030. p->pLast = pEntry;
  28031. }
  28032. /*
  28033. ** Merge two lists of RowSet entries. Remove duplicates.
  28034. **
  28035. ** The input lists are assumed to be in sorted order.
  28036. */
  28037. static struct RowSetEntry *boolidxMerge(
  28038. struct RowSetEntry *pA, /* First sorted list to be merged */
  28039. struct RowSetEntry *pB /* Second sorted list to be merged */
  28040. ){
  28041. struct RowSetEntry head;
  28042. struct RowSetEntry *pTail;
  28043. pTail = &head;
  28044. while( pA && pB ){
  28045. assert( pA->pNext==0 || pA->v<=pA->pNext->v );
  28046. assert( pB->pNext==0 || pB->v<=pB->pNext->v );
  28047. if( pA->v<pB->v ){
  28048. pTail->pNext = pA;
  28049. pA = pA->pNext;
  28050. pTail = pTail->pNext;
  28051. }else if( pB->v<pA->v ){
  28052. pTail->pNext = pB;
  28053. pB = pB->pNext;
  28054. pTail = pTail->pNext;
  28055. }else{
  28056. pA = pA->pNext;
  28057. }
  28058. }
  28059. if( pA ){
  28060. assert( pA->pNext==0 || pA->v<=pA->pNext->v );
  28061. pTail->pNext = pA;
  28062. }else{
  28063. assert( pB==0 || pB->pNext==0 || pB->v<=pB->pNext->v );
  28064. pTail->pNext = pB;
  28065. }
  28066. return head.pNext;
  28067. }
  28068. /*
  28069. ** Sort all elements of the RowSet into ascending order.
  28070. */
  28071. static void sqlite3RowSetSort(RowSet *p){
  28072. unsigned int i;
  28073. struct RowSetEntry *pEntry;
  28074. struct RowSetEntry *aBucket[40];
  28075. assert( p->isSorted==0 );
  28076. memset(aBucket, 0, sizeof(aBucket));
  28077. while( p->pEntry ){
  28078. pEntry = p->pEntry;
  28079. p->pEntry = pEntry->pNext;
  28080. pEntry->pNext = 0;
  28081. for(i=0; aBucket[i]; i++){
  28082. pEntry = boolidxMerge(aBucket[i],pEntry);
  28083. aBucket[i] = 0;
  28084. }
  28085. aBucket[i] = pEntry;
  28086. }
  28087. pEntry = 0;
  28088. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  28089. pEntry = boolidxMerge(pEntry,aBucket[i]);
  28090. }
  28091. p->pEntry = pEntry;
  28092. p->pLast = 0;
  28093. p->isSorted = 1;
  28094. }
  28095. /*
  28096. ** Extract the next (smallest) element from the RowSet.
  28097. ** Write the element into *pRowid. Return 1 on success. Return
  28098. ** 0 if the RowSet is already empty.
  28099. */
  28100. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  28101. if( !p->isSorted ){
  28102. sqlite3RowSetSort(p);
  28103. }
  28104. if( p->pEntry ){
  28105. *pRowid = p->pEntry->v;
  28106. p->pEntry = p->pEntry->pNext;
  28107. if( p->pEntry==0 ){
  28108. sqlite3RowSetClear(p);
  28109. }
  28110. return 1;
  28111. }else{
  28112. return 0;
  28113. }
  28114. }
  28115. /************** End of rowset.c **********************************************/
  28116. /************** Begin file pager.c *******************************************/
  28117. /*
  28118. ** 2001 September 15
  28119. **
  28120. ** The author disclaims copyright to this source code. In place of
  28121. ** a legal notice, here is a blessing:
  28122. **
  28123. ** May you do good and not evil.
  28124. ** May you find forgiveness for yourself and forgive others.
  28125. ** May you share freely, never taking more than you give.
  28126. **
  28127. *************************************************************************
  28128. ** This is the implementation of the page cache subsystem or "pager".
  28129. **
  28130. ** The pager is used to access a database disk file. It implements
  28131. ** atomic commit and rollback through the use of a journal file that
  28132. ** is separate from the database file. The pager also implements file
  28133. ** locking to prevent two processes from writing the same database
  28134. ** file simultaneously, or one process from reading the database while
  28135. ** another is writing.
  28136. **
  28137. ** @(#) $Id: pager.c,v 1.580 2009/04/11 16:27:50 drh Exp $
  28138. */
  28139. #ifndef SQLITE_OMIT_DISKIO
  28140. /*
  28141. ** Macros for troubleshooting. Normally turned off
  28142. */
  28143. #if 0
  28144. int sqlite3PagerTrace=1; /* True to enable tracing */
  28145. #define sqlite3DebugPrintf printf
  28146. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  28147. #else
  28148. #define PAGERTRACE(X)
  28149. #endif
  28150. /*
  28151. ** The following two macros are used within the PAGERTRACE() macros above
  28152. ** to print out file-descriptors.
  28153. **
  28154. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  28155. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  28156. ** struct as its argument.
  28157. */
  28158. #define PAGERID(p) ((int)(p->fd))
  28159. #define FILEHANDLEID(fd) ((int)fd)
  28160. /*
  28161. ** The page cache as a whole is always in one of the following
  28162. ** states:
  28163. **
  28164. ** PAGER_UNLOCK The page cache is not currently reading or
  28165. ** writing the database file. There is no
  28166. ** data held in memory. This is the initial
  28167. ** state.
  28168. **
  28169. ** PAGER_SHARED The page cache is reading the database.
  28170. ** Writing is not permitted. There can be
  28171. ** multiple readers accessing the same database
  28172. ** file at the same time.
  28173. **
  28174. ** PAGER_RESERVED This process has reserved the database for writing
  28175. ** but has not yet made any changes. Only one process
  28176. ** at a time can reserve the database. The original
  28177. ** database file has not been modified so other
  28178. ** processes may still be reading the on-disk
  28179. ** database file.
  28180. **
  28181. ** PAGER_EXCLUSIVE The page cache is writing the database.
  28182. ** Access is exclusive. No other processes or
  28183. ** threads can be reading or writing while one
  28184. ** process is writing.
  28185. **
  28186. ** PAGER_SYNCED The pager moves to this state from PAGER_EXCLUSIVE
  28187. ** after all dirty pages have been written to the
  28188. ** database file and the file has been synced to
  28189. ** disk. All that remains to do is to remove or
  28190. ** truncate the journal file and the transaction
  28191. ** will be committed.
  28192. **
  28193. ** The page cache comes up in PAGER_UNLOCK. The first time a
  28194. ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
  28195. ** After all pages have been released using sqlite_page_unref(),
  28196. ** the state transitions back to PAGER_UNLOCK. The first time
  28197. ** that sqlite3PagerWrite() is called, the state transitions to
  28198. ** PAGER_RESERVED. (Note that sqlite3PagerWrite() can only be
  28199. ** called on an outstanding page which means that the pager must
  28200. ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
  28201. ** PAGER_RESERVED means that there is an open rollback journal.
  28202. ** The transition to PAGER_EXCLUSIVE occurs before any changes
  28203. ** are made to the database file, though writes to the rollback
  28204. ** journal occurs with just PAGER_RESERVED. After an sqlite3PagerRollback()
  28205. ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
  28206. ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
  28207. */
  28208. #define PAGER_UNLOCK 0
  28209. #define PAGER_SHARED 1 /* same as SHARED_LOCK */
  28210. #define PAGER_RESERVED 2 /* same as RESERVED_LOCK */
  28211. #define PAGER_EXCLUSIVE 4 /* same as EXCLUSIVE_LOCK */
  28212. #define PAGER_SYNCED 5
  28213. /*
  28214. ** A macro used for invoking the codec if there is one
  28215. */
  28216. #ifdef SQLITE_HAS_CODEC
  28217. # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
  28218. # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
  28219. #else
  28220. # define CODEC1(P,D,N,X) /* NO-OP */
  28221. # define CODEC2(P,D,N,X) ((char*)D)
  28222. #endif
  28223. /*
  28224. ** The maximum allowed sector size. 16MB. If the xSectorsize() method
  28225. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  28226. ** This could conceivably cause corruption following a power failure on
  28227. ** such a system. This is currently an undocumented limit.
  28228. */
  28229. #define MAX_SECTOR_SIZE 0x0100000
  28230. /*
  28231. ** An instance of the following structure is allocated for each active
  28232. ** savepoint and statement transaction in the system. All such structures
  28233. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  28234. ** resized using sqlite3Realloc().
  28235. **
  28236. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  28237. ** set to 0. If a journal-header is written into the main journal while
  28238. ** the savepoint is active, then iHdrOffset is set to the byte offset
  28239. ** immediately following the last journal record written into the main
  28240. ** journal before the journal-header. This is required during savepoint
  28241. ** rollback (see pagerPlaybackSavepoint()).
  28242. */
  28243. typedef struct PagerSavepoint PagerSavepoint;
  28244. struct PagerSavepoint {
  28245. i64 iOffset; /* Starting offset in main journal */
  28246. i64 iHdrOffset; /* See above */
  28247. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  28248. Pgno nOrig; /* Original number of pages in file */
  28249. Pgno iSubRec; /* Index of first record in sub-journal */
  28250. };
  28251. /*
  28252. ** A open page cache is an instance of the following structure.
  28253. **
  28254. ** errCode
  28255. **
  28256. ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
  28257. ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
  28258. ** and is returned as the result of every major pager API call. The
  28259. ** SQLITE_FULL return code is slightly different. It persists only until the
  28260. ** next successful rollback is performed on the pager cache. Also,
  28261. ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
  28262. ** APIs, they may still be used successfully.
  28263. **
  28264. ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
  28265. **
  28266. ** Managing the size of the database file in pages is a little complicated.
  28267. ** The variable Pager.dbSize contains the number of pages that the database
  28268. ** image currently contains. As the database image grows or shrinks this
  28269. ** variable is updated. The variable Pager.dbFileSize contains the number
  28270. ** of pages in the database file. This may be different from Pager.dbSize
  28271. ** if some pages have been appended to the database image but not yet written
  28272. ** out from the cache to the actual file on disk. Or if the image has been
  28273. ** truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
  28274. ** contains the number of pages in the database image when the current
  28275. ** transaction was opened. The contents of all three of these variables is
  28276. ** only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
  28277. **
  28278. ** TODO: Under what conditions is dbSizeValid set? Cleared?
  28279. **
  28280. ** changeCountDone
  28281. **
  28282. ** This boolean variable is used to make sure that the change-counter
  28283. ** (the 4-byte header field at byte offset 24 of the database file) is
  28284. ** not updated more often than necessary.
  28285. **
  28286. ** It is set to true when the change-counter field is updated, which
  28287. ** can only happen if an exclusive lock is held on the database file.
  28288. ** It is cleared (set to false) whenever an exclusive lock is
  28289. ** relinquished on the database file. Each time a transaction is committed,
  28290. ** The changeCountDone flag is inspected. If it is true, the work of
  28291. ** updating the change-counter is omitted for the current transaction.
  28292. **
  28293. ** This mechanism means that when running in exclusive mode, a connection
  28294. ** need only update the change-counter once, for the first transaction
  28295. ** committed.
  28296. **
  28297. ** dbModified
  28298. **
  28299. ** The dbModified flag is set whenever a database page is dirtied.
  28300. ** It is cleared at the end of each transaction.
  28301. **
  28302. ** It is used when committing or otherwise ending a transaction. If
  28303. ** the dbModified flag is clear then less work has to be done.
  28304. **
  28305. ** journalStarted
  28306. **
  28307. ** This flag is set whenever the the main journal is synced.
  28308. **
  28309. ** The point of this flag is that it must be set after the
  28310. ** first journal header in a journal file has been synced to disk.
  28311. ** After this has happened, new pages appended to the database
  28312. ** do not need the PGHDR_NEED_SYNC flag set, as they do not need
  28313. ** to wait for a journal sync before they can be written out to
  28314. ** the database file (see function pager_write()).
  28315. **
  28316. ** setMaster
  28317. **
  28318. ** This variable is used to ensure that the master journal file name
  28319. ** (if any) is only written into the journal file once.
  28320. **
  28321. ** When committing a transaction, the master journal file name (if any)
  28322. ** may be written into the journal file while the pager is still in
  28323. ** PAGER_RESERVED state (see CommitPhaseOne() for the action). It
  28324. ** then attempts to upgrade to an exclusive lock. If this attempt
  28325. ** fails, then SQLITE_BUSY may be returned to the user and the user
  28326. ** may attempt to commit the transaction again later (calling
  28327. ** CommitPhaseOne() again). This flag is used to ensure that the
  28328. ** master journal name is only written to the journal file the first
  28329. ** time CommitPhaseOne() is called.
  28330. **
  28331. ** doNotSync
  28332. **
  28333. ** This variable is set and cleared by sqlite3PagerWrite().
  28334. **
  28335. ** needSync
  28336. **
  28337. ** TODO: It might be easier to set this variable in writeJournalHdr()
  28338. ** and writeMasterJournal() only. Change its meaning to "unsynced data
  28339. ** has been written to the journal".
  28340. */
  28341. struct Pager {
  28342. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  28343. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  28344. u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */
  28345. u8 useJournal; /* Use a rollback journal on this file */
  28346. u8 noReadlock; /* Do not bother to obtain readlocks */
  28347. u8 noSync; /* Do not sync the journal if true */
  28348. u8 fullSync; /* Do extra syncs of the journal for robustness */
  28349. u8 sync_flags; /* One of SYNC_NORMAL or SYNC_FULL */
  28350. u8 tempFile; /* zFilename is a temporary file */
  28351. u8 readOnly; /* True for a read-only database */
  28352. u8 memDb; /* True to inhibit all file I/O */
  28353. /* The following block contains those class members that are dynamically
  28354. ** modified during normal operations. The other variables in this structure
  28355. ** are either constant throughout the lifetime of the pager, or else
  28356. ** used to store configuration parameters that affect the way the pager
  28357. ** operates.
  28358. **
  28359. ** The 'state' variable is described in more detail along with the
  28360. ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
  28361. ** other variables in this block are described in the comment directly
  28362. ** above this class definition.
  28363. */
  28364. u8 state; /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
  28365. u8 dbModified; /* True if there are any changes to the Db */
  28366. u8 needSync; /* True if an fsync() is needed on the journal */
  28367. u8 journalStarted; /* True if header of journal is synced */
  28368. u8 changeCountDone; /* Set after incrementing the change-counter */
  28369. u8 setMaster; /* True if a m-j name has been written to jrnl */
  28370. u8 doNotSync; /* Boolean. While true, do not spill the cache */
  28371. u8 dbSizeValid; /* Set when dbSize is correct */
  28372. Pgno dbSize; /* Number of pages in the database */
  28373. Pgno dbOrigSize; /* dbSize before the current transaction */
  28374. Pgno dbFileSize; /* Number of pages in the database file */
  28375. int errCode; /* One of several kinds of errors */
  28376. int nRec; /* Pages journalled since last j-header written */
  28377. u32 cksumInit; /* Quasi-random value added to every checksum */
  28378. u32 nSubRec; /* Number of records written to sub-journal */
  28379. Bitvec *pInJournal; /* One bit for each page in the database file */
  28380. sqlite3_file *fd; /* File descriptor for database */
  28381. sqlite3_file *jfd; /* File descriptor for main journal */
  28382. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  28383. i64 journalOff; /* Current write offset in the journal file */
  28384. i64 journalHdr; /* Byte offset to previous journal header */
  28385. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  28386. int nSavepoint; /* Number of elements in aSavepoint[] */
  28387. char dbFileVers[16]; /* Changes whenever database file changes */
  28388. u32 sectorSize; /* Assumed sector size during rollback */
  28389. int nExtra; /* Add this many bytes to each in-memory page */
  28390. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  28391. int pageSize; /* Number of bytes in a page */
  28392. Pgno mxPgno; /* Maximum allowed size of the database */
  28393. char *zFilename; /* Name of the database file */
  28394. char *zJournal; /* Name of the journal file */
  28395. int (*xBusyHandler)(void*); /* Function to call when busy */
  28396. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  28397. #ifdef SQLITE_TEST
  28398. int nHit, nMiss; /* Cache hits and missing */
  28399. int nRead, nWrite; /* Database pages read/written */
  28400. #endif
  28401. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  28402. #ifdef SQLITE_HAS_CODEC
  28403. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  28404. void *pCodecArg; /* First argument to xCodec() */
  28405. #endif
  28406. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  28407. i64 journalSizeLimit; /* Size limit for persistent journal files */
  28408. PCache *pPCache; /* Pointer to page cache object */
  28409. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  28410. };
  28411. /*
  28412. ** The following global variables hold counters used for
  28413. ** testing purposes only. These variables do not exist in
  28414. ** a non-testing build. These variables are not thread-safe.
  28415. */
  28416. #ifdef SQLITE_TEST
  28417. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  28418. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  28419. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  28420. # define PAGER_INCR(v) v++
  28421. #else
  28422. # define PAGER_INCR(v)
  28423. #endif
  28424. /*
  28425. ** Journal files begin with the following magic string. The data
  28426. ** was obtained from /dev/random. It is used only as a sanity check.
  28427. **
  28428. ** Since version 2.8.0, the journal format contains additional sanity
  28429. ** checking information. If the power fails while the journal is being
  28430. ** written, semi-random garbage data might appear in the journal
  28431. ** file after power is restored. If an attempt is then made
  28432. ** to roll the journal back, the database could be corrupted. The additional
  28433. ** sanity checking data is an attempt to discover the garbage in the
  28434. ** journal and ignore it.
  28435. **
  28436. ** The sanity checking information for the new journal format consists
  28437. ** of a 32-bit checksum on each page of data. The checksum covers both
  28438. ** the page number and the pPager->pageSize bytes of data for the page.
  28439. ** This cksum is initialized to a 32-bit random value that appears in the
  28440. ** journal file right after the header. The random initializer is important,
  28441. ** because garbage data that appears at the end of a journal is likely
  28442. ** data that was once in other files that have now been deleted. If the
  28443. ** garbage data came from an obsolete journal file, the checksums might
  28444. ** be correct. But by initializing the checksum to random value which
  28445. ** is different for every journal, we minimize that risk.
  28446. */
  28447. static const unsigned char aJournalMagic[] = {
  28448. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  28449. };
  28450. /*
  28451. ** The size of the of each page record in the journal is given by
  28452. ** the following macro.
  28453. */
  28454. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  28455. /*
  28456. ** The journal header size for this pager. This is usually the same
  28457. ** size as a single disk sector. See also setSectorSize().
  28458. */
  28459. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  28460. /*
  28461. ** The macro MEMDB is true if we are dealing with an in-memory database.
  28462. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  28463. ** the value of MEMDB will be a constant and the compiler will optimize
  28464. ** out code that would never execute.
  28465. */
  28466. #ifdef SQLITE_OMIT_MEMORYDB
  28467. # define MEMDB 0
  28468. #else
  28469. # define MEMDB pPager->memDb
  28470. #endif
  28471. /*
  28472. ** The maximum legal page number is (2^31 - 1).
  28473. */
  28474. #define PAGER_MAX_PGNO 2147483647
  28475. #ifndef NDEBUG
  28476. /*
  28477. ** Usage:
  28478. **
  28479. ** assert( assert_pager_state(pPager) );
  28480. */
  28481. static int assert_pager_state(Pager *pPager){
  28482. /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
  28483. assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
  28484. /* The changeCountDone flag is always set for temp-files */
  28485. assert( pPager->tempFile==0 || pPager->changeCountDone );
  28486. return 1;
  28487. }
  28488. #endif
  28489. /*
  28490. ** Return true if it is necessary to write page *pPg into the sub-journal.
  28491. ** A page needs to be written into the sub-journal if there exists one
  28492. ** or more open savepoints for which:
  28493. **
  28494. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  28495. ** * The bit corresponding to the page-number is not set in
  28496. ** PagerSavepoint.pInSavepoint.
  28497. */
  28498. static int subjRequiresPage(PgHdr *pPg){
  28499. Pgno pgno = pPg->pgno;
  28500. Pager *pPager = pPg->pPager;
  28501. int i;
  28502. for(i=0; i<pPager->nSavepoint; i++){
  28503. PagerSavepoint *p = &pPager->aSavepoint[i];
  28504. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  28505. return 1;
  28506. }
  28507. }
  28508. return 0;
  28509. }
  28510. /*
  28511. ** Return true if the page is already in the journal file.
  28512. */
  28513. static int pageInJournal(PgHdr *pPg){
  28514. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  28515. }
  28516. /*
  28517. ** Read a 32-bit integer from the given file descriptor. Store the integer
  28518. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  28519. ** error code is something goes wrong.
  28520. **
  28521. ** All values are stored on disk as big-endian.
  28522. */
  28523. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  28524. unsigned char ac[4];
  28525. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  28526. if( rc==SQLITE_OK ){
  28527. *pRes = sqlite3Get4byte(ac);
  28528. }
  28529. return rc;
  28530. }
  28531. /*
  28532. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  28533. */
  28534. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  28535. /*
  28536. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  28537. ** on success or an error code is something goes wrong.
  28538. */
  28539. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  28540. char ac[4];
  28541. put32bits(ac, val);
  28542. return sqlite3OsWrite(fd, ac, 4, offset);
  28543. }
  28544. /*
  28545. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  28546. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  28547. **
  28548. ** This is so that expressions can be written as:
  28549. **
  28550. ** if( isOpen(pPager->jfd) ){ ...
  28551. **
  28552. ** instead of
  28553. **
  28554. ** if( pPager->jfd->pMethods ){ ...
  28555. */
  28556. #define isOpen(pFd) ((pFd)->pMethods)
  28557. /*
  28558. ** If file pFd is open, call sqlite3OsUnlock() on it.
  28559. */
  28560. static int osUnlock(sqlite3_file *pFd, int eLock){
  28561. if( !isOpen(pFd) ){
  28562. return SQLITE_OK;
  28563. }
  28564. return sqlite3OsUnlock(pFd, eLock);
  28565. }
  28566. /*
  28567. ** This function determines whether or not the atomic-write optimization
  28568. ** can be used with this pager. The optimization can be used if:
  28569. **
  28570. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  28571. ** a database page may be written atomically, and
  28572. ** (b) the value returned by OsSectorSize() is less than or equal
  28573. ** to the page size.
  28574. **
  28575. ** The optimization is also always enabled for temporary files. It is
  28576. ** an error to call this function if pPager is opened on an in-memory
  28577. ** database.
  28578. **
  28579. ** If the optimization cannot be used, 0 is returned. If it can be used,
  28580. ** then the value returned is the size of the journal file when it
  28581. ** contains rollback data for exactly one page.
  28582. */
  28583. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  28584. static int jrnlBufferSize(Pager *pPager){
  28585. assert( !MEMDB );
  28586. if( !pPager->tempFile ){
  28587. int dc; /* Device characteristics */
  28588. int nSector; /* Sector size */
  28589. int szPage; /* Page size */
  28590. assert( isOpen(pPager->fd) );
  28591. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  28592. nSector = pPager->sectorSize;
  28593. szPage = pPager->pageSize;
  28594. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  28595. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  28596. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  28597. return 0;
  28598. }
  28599. }
  28600. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  28601. }
  28602. #endif
  28603. /*
  28604. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  28605. ** on the cache using a hash function. This is used for testing
  28606. ** and debugging only.
  28607. */
  28608. #ifdef SQLITE_CHECK_PAGES
  28609. /*
  28610. ** Return a 32-bit hash of the page data for pPage.
  28611. */
  28612. static u32 pager_datahash(int nByte, unsigned char *pData){
  28613. u32 hash = 0;
  28614. int i;
  28615. for(i=0; i<nByte; i++){
  28616. hash = (hash*1039) + pData[i];
  28617. }
  28618. return hash;
  28619. }
  28620. static u32 pager_pagehash(PgHdr *pPage){
  28621. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  28622. }
  28623. static void pager_set_pagehash(PgHdr *pPage){
  28624. pPage->pageHash = pager_pagehash(pPage);
  28625. }
  28626. /*
  28627. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  28628. ** is defined, and NDEBUG is not defined, an assert() statement checks
  28629. ** that the page is either dirty or still matches the calculated page-hash.
  28630. */
  28631. #define CHECK_PAGE(x) checkPage(x)
  28632. static void checkPage(PgHdr *pPg){
  28633. Pager *pPager = pPg->pPager;
  28634. assert( !pPg->pageHash || pPager->errCode
  28635. || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  28636. }
  28637. #else
  28638. #define pager_datahash(X,Y) 0
  28639. #define pager_pagehash(X) 0
  28640. #define CHECK_PAGE(x)
  28641. #endif /* SQLITE_CHECK_PAGES */
  28642. /*
  28643. ** When this is called the journal file for pager pPager must be open.
  28644. ** This function attempts to read a master journal file name from the
  28645. ** end of the file and, if successful, copies it into memory supplied
  28646. ** by the caller. See comments above writeMasterJournal() for the format
  28647. ** used to store a master journal file name at the end of a journal file.
  28648. **
  28649. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  28650. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  28651. ** enough space to write the master journal name). If the master journal
  28652. ** name in the journal is longer than nMaster bytes (including a
  28653. ** nul-terminator), then this is handled as if no master journal name
  28654. ** were present in the journal.
  28655. **
  28656. ** If a master journal file name is present at the end of the journal
  28657. ** file, then it is copied into the buffer pointed to by zMaster. A
  28658. ** nul-terminator byte is appended to the buffer following the master
  28659. ** journal file name.
  28660. **
  28661. ** If it is determined that no master journal file name is present
  28662. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  28663. **
  28664. ** If an error occurs while reading from the journal file, an SQLite
  28665. ** error code is returned.
  28666. */
  28667. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  28668. int rc; /* Return code */
  28669. u32 len; /* Length in bytes of master journal name */
  28670. i64 szJ; /* Total size in bytes of journal file pJrnl */
  28671. u32 cksum; /* MJ checksum value read from journal */
  28672. u32 u; /* Unsigned loop counter */
  28673. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  28674. zMaster[0] = '\0';
  28675. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  28676. || szJ<16
  28677. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  28678. || len>=nMaster
  28679. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  28680. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  28681. || memcmp(aMagic, aJournalMagic, 8)
  28682. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  28683. ){
  28684. return rc;
  28685. }
  28686. /* See if the checksum matches the master journal name */
  28687. for(u=0; u<len; u++){
  28688. cksum -= zMaster[u];
  28689. }
  28690. if( cksum ){
  28691. /* If the checksum doesn't add up, then one or more of the disk sectors
  28692. ** containing the master journal filename is corrupted. This means
  28693. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  28694. ** master-journal filename.
  28695. */
  28696. len = 0;
  28697. }
  28698. zMaster[len] = '\0';
  28699. return SQLITE_OK;
  28700. }
  28701. /*
  28702. ** Return the offset of the sector boundary at or immediately
  28703. ** following the value in pPager->journalOff, assuming a sector
  28704. ** size of pPager->sectorSize bytes.
  28705. **
  28706. ** i.e for a sector size of 512:
  28707. **
  28708. ** Pager.journalOff Return value
  28709. ** ---------------------------------------
  28710. ** 0 0
  28711. ** 512 512
  28712. ** 100 512
  28713. ** 2000 2048
  28714. **
  28715. */
  28716. static i64 journalHdrOffset(Pager *pPager){
  28717. i64 offset = 0;
  28718. i64 c = pPager->journalOff;
  28719. if( c ){
  28720. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  28721. }
  28722. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  28723. assert( offset>=c );
  28724. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  28725. return offset;
  28726. }
  28727. /*
  28728. ** The journal file must be open when this function is called.
  28729. **
  28730. ** This function is a no-op if the journal file has not been written to
  28731. ** within the current transaction (i.e. if Pager.journalOff==0).
  28732. **
  28733. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  28734. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  28735. ** zero the 28-byte header at the start of the journal file. In either case,
  28736. ** if the pager is not in no-sync mode, sync the journal file immediately
  28737. ** after writing or truncating it.
  28738. **
  28739. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  28740. ** following the truncation or zeroing described above the size of the
  28741. ** journal file in bytes is larger than this value, then truncate the
  28742. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  28743. ** not need to be synced following this operation.
  28744. **
  28745. ** If an IO error occurs, abandon processing and return the IO error code.
  28746. ** Otherwise, return SQLITE_OK.
  28747. */
  28748. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  28749. int rc = SQLITE_OK; /* Return code */
  28750. assert( isOpen(pPager->jfd) );
  28751. if( pPager->journalOff ){
  28752. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  28753. IOTRACE(("JZEROHDR %p\n", pPager))
  28754. if( doTruncate || iLimit==0 ){
  28755. rc = sqlite3OsTruncate(pPager->jfd, 0);
  28756. }else{
  28757. static const char zeroHdr[28] = {0};
  28758. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  28759. }
  28760. if( rc==SQLITE_OK && !pPager->noSync ){
  28761. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
  28762. }
  28763. /* At this point the transaction is committed but the write lock
  28764. ** is still held on the file. If there is a size limit configured for
  28765. ** the persistent journal and the journal file currently consumes more
  28766. ** space than that limit allows for, truncate it now. There is no need
  28767. ** to sync the file following this operation.
  28768. */
  28769. if( rc==SQLITE_OK && iLimit>0 ){
  28770. i64 sz;
  28771. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  28772. if( rc==SQLITE_OK && sz>iLimit ){
  28773. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  28774. }
  28775. }
  28776. }
  28777. return rc;
  28778. }
  28779. /*
  28780. ** The journal file must be open when this routine is called. A journal
  28781. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  28782. ** current location.
  28783. **
  28784. ** The format for the journal header is as follows:
  28785. ** - 8 bytes: Magic identifying journal format.
  28786. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  28787. ** - 4 bytes: Random number used for page hash.
  28788. ** - 4 bytes: Initial database page count.
  28789. ** - 4 bytes: Sector size used by the process that wrote this journal.
  28790. ** - 4 bytes: Database page size.
  28791. **
  28792. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  28793. */
  28794. static int writeJournalHdr(Pager *pPager){
  28795. int rc = SQLITE_OK; /* Return code */
  28796. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  28797. u32 nHeader = pPager->pageSize; /* Size of buffer pointed to by zHeader */
  28798. u32 nWrite; /* Bytes of header sector written */
  28799. int ii; /* Loop counter */
  28800. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  28801. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  28802. nHeader = JOURNAL_HDR_SZ(pPager);
  28803. }
  28804. /* If there are active savepoints and any of them were created
  28805. ** since the most recent journal header was written, update the
  28806. ** PagerSavepoint.iHdrOffset fields now.
  28807. */
  28808. for(ii=0; ii<pPager->nSavepoint; ii++){
  28809. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  28810. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  28811. }
  28812. }
  28813. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  28814. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  28815. /*
  28816. ** Write the nRec Field - the number of page records that follow this
  28817. ** journal header. Normally, zero is written to this value at this time.
  28818. ** After the records are added to the journal (and the journal synced,
  28819. ** if in full-sync mode), the zero is overwritten with the true number
  28820. ** of records (see syncJournal()).
  28821. **
  28822. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  28823. ** reading the journal this value tells SQLite to assume that the
  28824. ** rest of the journal file contains valid page records. This assumption
  28825. ** is dangerous, as if a failure occurred whilst writing to the journal
  28826. ** file it may contain some garbage data. There are two scenarios
  28827. ** where this risk can be ignored:
  28828. **
  28829. ** * When the pager is in no-sync mode. Corruption can follow a
  28830. ** power failure in this case anyway.
  28831. **
  28832. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  28833. ** that garbage data is never appended to the journal file.
  28834. */
  28835. assert( isOpen(pPager->fd) || pPager->noSync );
  28836. if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  28837. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  28838. ){
  28839. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  28840. }else{
  28841. put32bits(&zHeader[sizeof(aJournalMagic)], 0);
  28842. }
  28843. /* The random check-hash initialiser */
  28844. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  28845. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  28846. /* The initial database size */
  28847. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  28848. /* The assumed sector size for this process */
  28849. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  28850. /* The page size */
  28851. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  28852. /* Initializing the tail of the buffer is not necessary. Everything
  28853. ** works find if the following memset() is omitted. But initializing
  28854. ** the memory prevents valgrind from complaining, so we are willing to
  28855. ** take the performance hit.
  28856. */
  28857. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  28858. nHeader-(sizeof(aJournalMagic)+20));
  28859. /* In theory, it is only necessary to write the 28 bytes that the
  28860. ** journal header consumes to the journal file here. Then increment the
  28861. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  28862. ** record is written to the following sector (leaving a gap in the file
  28863. ** that will be implicitly filled in by the OS).
  28864. **
  28865. ** However it has been discovered that on some systems this pattern can
  28866. ** be significantly slower than contiguously writing data to the file,
  28867. ** even if that means explicitly writing data to the block of
  28868. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  28869. ** is done.
  28870. **
  28871. ** The loop is required here in case the sector-size is larger than the
  28872. ** database page size. Since the zHeader buffer is only Pager.pageSize
  28873. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  28874. ** to populate the entire journal header sector.
  28875. */
  28876. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  28877. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  28878. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  28879. pPager->journalOff += nHeader;
  28880. }
  28881. return rc;
  28882. }
  28883. /*
  28884. ** The journal file must be open when this is called. A journal header file
  28885. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  28886. ** file. The current location in the journal file is given by
  28887. ** pPager->journalOff. See comments above function writeJournalHdr() for
  28888. ** a description of the journal header format.
  28889. **
  28890. ** If the header is read successfully, *pNRec is set to the number of
  28891. ** page records following this header and *pDbSize is set to the size of the
  28892. ** database before the transaction began, in pages. Also, pPager->cksumInit
  28893. ** is set to the value read from the journal header. SQLITE_OK is returned
  28894. ** in this case.
  28895. **
  28896. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  28897. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  28898. ** cannot be read from the journal file an error code is returned.
  28899. */
  28900. static int readJournalHdr(
  28901. Pager *pPager, /* Pager object */
  28902. i64 journalSize, /* Size of the open journal file in bytes */
  28903. u32 *pNRec, /* OUT: Value read from the nRec field */
  28904. u32 *pDbSize /* OUT: Value of original database size field */
  28905. ){
  28906. int rc; /* Return code */
  28907. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  28908. i64 iHdrOff; /* Offset of journal header being read */
  28909. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  28910. /* Advance Pager.journalOff to the start of the next sector. If the
  28911. ** journal file is too small for there to be a header stored at this
  28912. ** point, return SQLITE_DONE.
  28913. */
  28914. pPager->journalOff = journalHdrOffset(pPager);
  28915. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  28916. return SQLITE_DONE;
  28917. }
  28918. iHdrOff = pPager->journalOff;
  28919. /* Read in the first 8 bytes of the journal header. If they do not match
  28920. ** the magic string found at the start of each journal header, return
  28921. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  28922. ** proceed.
  28923. */
  28924. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  28925. if( rc ){
  28926. return rc;
  28927. }
  28928. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  28929. return SQLITE_DONE;
  28930. }
  28931. /* Read the first three 32-bit fields of the journal header: The nRec
  28932. ** field, the checksum-initializer and the database size at the start
  28933. ** of the transaction. Return an error code if anything goes wrong.
  28934. */
  28935. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  28936. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  28937. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  28938. ){
  28939. return rc;
  28940. }
  28941. if( pPager->journalOff==0 ){
  28942. u32 iPageSize; /* Page-size field of journal header */
  28943. u32 iSectorSize; /* Sector-size field of journal header */
  28944. u16 iPageSize16; /* Copy of iPageSize in 16-bit variable */
  28945. /* Read the page-size and sector-size journal header fields. */
  28946. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  28947. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  28948. ){
  28949. return rc;
  28950. }
  28951. /* Check that the values read from the page-size and sector-size fields
  28952. ** are within range. To be 'in range', both values need to be a power
  28953. ** of two greater than or equal to 512, and not greater than their
  28954. ** respective compile time maximum limits.
  28955. */
  28956. if( iPageSize<512 || iSectorSize<512
  28957. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  28958. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  28959. ){
  28960. /* If the either the page-size or sector-size in the journal-header is
  28961. ** invalid, then the process that wrote the journal-header must have
  28962. ** crashed before the header was synced. In this case stop reading
  28963. ** the journal file here.
  28964. */
  28965. return SQLITE_DONE;
  28966. }
  28967. /* Update the page-size to match the value read from the journal.
  28968. ** Use a testcase() macro to make sure that malloc failure within
  28969. ** PagerSetPagesize() is tested.
  28970. */
  28971. iPageSize16 = (u16)iPageSize;
  28972. rc = sqlite3PagerSetPagesize(pPager, &iPageSize16);
  28973. testcase( rc!=SQLITE_OK );
  28974. assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
  28975. /* Update the assumed sector-size to match the value used by
  28976. ** the process that created this journal. If this journal was
  28977. ** created by a process other than this one, then this routine
  28978. ** is being called from within pager_playback(). The local value
  28979. ** of Pager.sectorSize is restored at the end of that routine.
  28980. */
  28981. pPager->sectorSize = iSectorSize;
  28982. }
  28983. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  28984. return rc;
  28985. }
  28986. /*
  28987. ** Write the supplied master journal name into the journal file for pager
  28988. ** pPager at the current location. The master journal name must be the last
  28989. ** thing written to a journal file. If the pager is in full-sync mode, the
  28990. ** journal file descriptor is advanced to the next sector boundary before
  28991. ** anything is written. The format is:
  28992. **
  28993. ** + 4 bytes: PAGER_MJ_PGNO.
  28994. ** + N bytes: Master journal filename in utf-8.
  28995. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  28996. ** + 4 bytes: Master journal name checksum.
  28997. ** + 8 bytes: aJournalMagic[].
  28998. **
  28999. ** The master journal page checksum is the sum of the bytes in the master
  29000. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  29001. **
  29002. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  29003. ** this call is a no-op.
  29004. */
  29005. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  29006. int rc; /* Return code */
  29007. int nMaster; /* Length of string zMaster */
  29008. i64 iHdrOff; /* Offset of header in journal file */
  29009. i64 jrnlSize; /* Size of journal file on disk */
  29010. u32 cksum = 0; /* Checksum of string zMaster */
  29011. if( !zMaster || pPager->setMaster
  29012. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  29013. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  29014. ){
  29015. return SQLITE_OK;
  29016. }
  29017. pPager->setMaster = 1;
  29018. assert( isOpen(pPager->jfd) );
  29019. /* Calculate the length in bytes and the checksum of zMaster */
  29020. for(nMaster=0; zMaster[nMaster]; nMaster++){
  29021. cksum += zMaster[nMaster];
  29022. }
  29023. /* If in full-sync mode, advance to the next disk sector before writing
  29024. ** the master journal name. This is in case the previous page written to
  29025. ** the journal has already been synced.
  29026. */
  29027. if( pPager->fullSync ){
  29028. pPager->journalOff = journalHdrOffset(pPager);
  29029. }
  29030. iHdrOff = pPager->journalOff;
  29031. /* Write the master journal data to the end of the journal file. If
  29032. ** an error occurs, return the error code to the caller.
  29033. */
  29034. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  29035. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  29036. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  29037. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  29038. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  29039. ){
  29040. return rc;
  29041. }
  29042. pPager->journalOff += (nMaster+20);
  29043. pPager->needSync = !pPager->noSync;
  29044. /* If the pager is in peristent-journal mode, then the physical
  29045. ** journal-file may extend past the end of the master-journal name
  29046. ** and 8 bytes of magic data just written to the file. This is
  29047. ** dangerous because the code to rollback a hot-journal file
  29048. ** will not be able to find the master-journal name to determine
  29049. ** whether or not the journal is hot.
  29050. **
  29051. ** Easiest thing to do in this scenario is to truncate the journal
  29052. ** file to the required size.
  29053. */
  29054. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  29055. && jrnlSize>pPager->journalOff
  29056. ){
  29057. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  29058. }
  29059. return rc;
  29060. }
  29061. /*
  29062. ** Find a page in the hash table given its page number. Return
  29063. ** a pointer to the page or NULL if the requested page is not
  29064. ** already in memory.
  29065. */
  29066. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  29067. PgHdr *p; /* Return value */
  29068. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  29069. ** fail, since no attempt to allocate dynamic memory will be made.
  29070. */
  29071. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  29072. return p;
  29073. }
  29074. /*
  29075. ** Unless the pager is in error-state, discard all in-memory pages. If
  29076. ** the pager is in error-state, then this call is a no-op.
  29077. **
  29078. ** TODO: Why can we not reset the pager while in error state?
  29079. */
  29080. static void pager_reset(Pager *pPager){
  29081. if( SQLITE_OK==pPager->errCode ){
  29082. sqlite3BackupRestart(pPager->pBackup);
  29083. sqlite3PcacheClear(pPager->pPCache);
  29084. }
  29085. }
  29086. /*
  29087. ** Free all structures in the Pager.aSavepoint[] array and set both
  29088. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  29089. ** if it is open and the pager is not in exclusive mode.
  29090. */
  29091. static void releaseAllSavepoints(Pager *pPager){
  29092. int ii; /* Iterator for looping through Pager.aSavepoint */
  29093. for(ii=0; ii<pPager->nSavepoint; ii++){
  29094. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  29095. }
  29096. if( !pPager->exclusiveMode ){
  29097. sqlite3OsClose(pPager->sjfd);
  29098. }
  29099. sqlite3_free(pPager->aSavepoint);
  29100. pPager->aSavepoint = 0;
  29101. pPager->nSavepoint = 0;
  29102. pPager->nSubRec = 0;
  29103. }
  29104. /*
  29105. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  29106. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  29107. ** or SQLITE_NOMEM if a malloc failure occurs.
  29108. */
  29109. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  29110. int ii; /* Loop counter */
  29111. int rc = SQLITE_OK; /* Result code */
  29112. for(ii=0; ii<pPager->nSavepoint; ii++){
  29113. PagerSavepoint *p = &pPager->aSavepoint[ii];
  29114. if( pgno<=p->nOrig ){
  29115. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  29116. testcase( rc==SQLITE_NOMEM );
  29117. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  29118. }
  29119. }
  29120. return rc;
  29121. }
  29122. /*
  29123. ** Unlock the database file. This function is a no-op if the pager
  29124. ** is in exclusive mode.
  29125. **
  29126. ** If the pager is currently in error state, discard the contents of
  29127. ** the cache and reset the Pager structure internal state. If there is
  29128. ** an open journal-file, then the next time a shared-lock is obtained
  29129. ** on the pager file (by this or any other process), it will be
  29130. ** treated as a hot-journal and rolled back.
  29131. */
  29132. static void pager_unlock(Pager *pPager){
  29133. if( !pPager->exclusiveMode ){
  29134. int rc; /* Return code */
  29135. /* Always close the journal file when dropping the database lock.
  29136. ** Otherwise, another connection with journal_mode=delete might
  29137. ** delete the file out from under us.
  29138. */
  29139. sqlite3OsClose(pPager->jfd);
  29140. sqlite3BitvecDestroy(pPager->pInJournal);
  29141. pPager->pInJournal = 0;
  29142. releaseAllSavepoints(pPager);
  29143. /* If the file is unlocked, somebody else might change it. The
  29144. ** values stored in Pager.dbSize etc. might become invalid if
  29145. ** this happens. TODO: Really, this doesn't need to be cleared
  29146. ** until the change-counter check fails in pagerSharedLock().
  29147. */
  29148. pPager->dbSizeValid = 0;
  29149. rc = osUnlock(pPager->fd, NO_LOCK);
  29150. if( rc ){
  29151. pPager->errCode = rc;
  29152. }
  29153. IOTRACE(("UNLOCK %p\n", pPager))
  29154. /* If Pager.errCode is set, the contents of the pager cache cannot be
  29155. ** trusted. Now that the pager file is unlocked, the contents of the
  29156. ** cache can be discarded and the error code safely cleared.
  29157. */
  29158. if( pPager->errCode ){
  29159. if( rc==SQLITE_OK ){
  29160. pPager->errCode = SQLITE_OK;
  29161. }
  29162. pager_reset(pPager);
  29163. }
  29164. pPager->changeCountDone = 0;
  29165. pPager->state = PAGER_UNLOCK;
  29166. }
  29167. }
  29168. /*
  29169. ** This function should be called when an IOERR, CORRUPT or FULL error
  29170. ** may have occurred. The first argument is a pointer to the pager
  29171. ** structure, the second the error-code about to be returned by a pager
  29172. ** API function. The value returned is a copy of the second argument
  29173. ** to this function.
  29174. **
  29175. ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
  29176. ** the error becomes persistent. Until the persisten error is cleared,
  29177. ** subsequent API calls on this Pager will immediately return the same
  29178. ** error code.
  29179. **
  29180. ** A persistent error indicates that the contents of the pager-cache
  29181. ** cannot be trusted. This state can be cleared by completely discarding
  29182. ** the contents of the pager-cache. If a transaction was active when
  29183. ** the persistent error occurred, then the rollback journal may need
  29184. ** to be replayed to restore the contents of the database file (as if
  29185. ** it were a hot-journal).
  29186. */
  29187. static int pager_error(Pager *pPager, int rc){
  29188. int rc2 = rc & 0xff;
  29189. assert(
  29190. pPager->errCode==SQLITE_FULL ||
  29191. pPager->errCode==SQLITE_OK ||
  29192. (pPager->errCode & 0xff)==SQLITE_IOERR
  29193. );
  29194. if(
  29195. rc2==SQLITE_FULL ||
  29196. rc2==SQLITE_IOERR ||
  29197. rc2==SQLITE_CORRUPT
  29198. ){
  29199. pPager->errCode = rc;
  29200. if( pPager->state==PAGER_UNLOCK
  29201. && sqlite3PcacheRefCount(pPager->pPCache)==0
  29202. ){
  29203. /* If the pager is already unlocked, call pager_unlock() now to
  29204. ** clear the error state and ensure that the pager-cache is
  29205. ** completely empty.
  29206. */
  29207. pager_unlock(pPager);
  29208. }
  29209. }
  29210. return rc;
  29211. }
  29212. /*
  29213. ** Execute a rollback if a transaction is active and unlock the
  29214. ** database file.
  29215. **
  29216. ** If the pager has already entered the error state, do not attempt
  29217. ** the rollback at this time. Instead, pager_unlock() is called. The
  29218. ** call to pager_unlock() will discard all in-memory pages, unlock
  29219. ** the database file and clear the error state. If this means that
  29220. ** there is a hot-journal left in the file-system, the next connection
  29221. ** to obtain a shared lock on the pager (which may be this one) will
  29222. ** roll it back.
  29223. **
  29224. ** If the pager has not already entered the error state, but an IO or
  29225. ** malloc error occurs during a rollback, then this will itself cause
  29226. ** the pager to enter the error state. Which will be cleared by the
  29227. ** call to pager_unlock(), as described above.
  29228. */
  29229. static void pagerUnlockAndRollback(Pager *pPager){
  29230. if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
  29231. sqlite3BeginBenignMalloc();
  29232. sqlite3PagerRollback(pPager);
  29233. sqlite3EndBenignMalloc();
  29234. }
  29235. pager_unlock(pPager);
  29236. }
  29237. /*
  29238. ** This routine ends a transaction. A transaction is usually ended by
  29239. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  29240. ** after rollback of a hot-journal, or if an error occurs while opening
  29241. ** the journal file or writing the very first journal-header of a
  29242. ** database transaction.
  29243. **
  29244. ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
  29245. ** routine is called, it is a no-op (returns SQLITE_OK).
  29246. **
  29247. ** Otherwise, any active savepoints are released.
  29248. **
  29249. ** If the journal file is open, then it is "finalized". Once a journal
  29250. ** file has been finalized it is not possible to use it to roll back a
  29251. ** transaction. Nor will it be considered to be a hot-journal by this
  29252. ** or any other database connection. Exactly how a journal is finalized
  29253. ** depends on whether or not the pager is running in exclusive mode and
  29254. ** the current journal-mode (Pager.journalMode value), as follows:
  29255. **
  29256. ** journalMode==MEMORY
  29257. ** Journal file descriptor is simply closed. This destroys an
  29258. ** in-memory journal.
  29259. **
  29260. ** journalMode==TRUNCATE
  29261. ** Journal file is truncated to zero bytes in size.
  29262. **
  29263. ** journalMode==PERSIST
  29264. ** The first 28 bytes of the journal file are zeroed. This invalidates
  29265. ** the first journal header in the file, and hence the entire journal
  29266. ** file. An invalid journal file cannot be rolled back.
  29267. **
  29268. ** journalMode==DELETE
  29269. ** The journal file is closed and deleted using sqlite3OsDelete().
  29270. **
  29271. ** If the pager is running in exclusive mode, this method of finalizing
  29272. ** the journal file is never used. Instead, if the journalMode is
  29273. ** DELETE and the pager is in exclusive mode, the method described under
  29274. ** journalMode==PERSIST is used instead.
  29275. **
  29276. ** After the journal is finalized, if running in non-exclusive mode, the
  29277. ** pager moves to PAGER_SHARED state (and downgrades the lock on the
  29278. ** database file accordingly).
  29279. **
  29280. ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
  29281. ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
  29282. ** exclusive mode.
  29283. **
  29284. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  29285. ** any of the IO operations to finalize the journal file or unlock the
  29286. ** database then the IO error code is returned to the user. If the
  29287. ** operation to finalize the journal file fails, then the code still
  29288. ** tries to unlock the database file if not in exclusive mode. If the
  29289. ** unlock operation fails as well, then the first error code related
  29290. ** to the first error encountered (the journal finalization one) is
  29291. ** returned.
  29292. */
  29293. static int pager_end_transaction(Pager *pPager, int hasMaster){
  29294. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  29295. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  29296. if( pPager->state<PAGER_RESERVED ){
  29297. return SQLITE_OK;
  29298. }
  29299. releaseAllSavepoints(pPager);
  29300. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  29301. if( isOpen(pPager->jfd) ){
  29302. /* TODO: There's a problem here if a journal-file was opened in MEMORY
  29303. ** mode and then the journal-mode is changed to TRUNCATE or PERSIST
  29304. ** during the transaction. This code should be changed to assume
  29305. ** that the journal mode has not changed since the transaction was
  29306. ** started. And the sqlite3PagerJournalMode() function should be
  29307. ** changed to make sure that this is the case too.
  29308. */
  29309. /* Finalize the journal file. */
  29310. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  29311. int isMemoryJournal = sqlite3IsMemJournal(pPager->jfd);
  29312. sqlite3OsClose(pPager->jfd);
  29313. if( !isMemoryJournal ){
  29314. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  29315. }
  29316. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  29317. rc = sqlite3OsTruncate(pPager->jfd, 0);
  29318. pPager->journalOff = 0;
  29319. pPager->journalStarted = 0;
  29320. }else if( pPager->exclusiveMode
  29321. || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  29322. ){
  29323. rc = zeroJournalHdr(pPager, hasMaster);
  29324. pager_error(pPager, rc);
  29325. pPager->journalOff = 0;
  29326. pPager->journalStarted = 0;
  29327. }else{
  29328. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
  29329. sqlite3OsClose(pPager->jfd);
  29330. if( rc==SQLITE_OK && !pPager->tempFile ){
  29331. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  29332. }
  29333. }
  29334. #ifdef SQLITE_CHECK_PAGES
  29335. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  29336. #endif
  29337. sqlite3PcacheCleanAll(pPager->pPCache);
  29338. sqlite3BitvecDestroy(pPager->pInJournal);
  29339. pPager->pInJournal = 0;
  29340. pPager->nRec = 0;
  29341. }
  29342. if( !pPager->exclusiveMode ){
  29343. rc2 = osUnlock(pPager->fd, SHARED_LOCK);
  29344. pPager->state = PAGER_SHARED;
  29345. pPager->changeCountDone = 0;
  29346. }else if( pPager->state==PAGER_SYNCED ){
  29347. pPager->state = PAGER_EXCLUSIVE;
  29348. }
  29349. pPager->setMaster = 0;
  29350. pPager->needSync = 0;
  29351. pPager->dbModified = 0;
  29352. /* TODO: Is this optimal? Why is the db size invalidated here
  29353. ** when the database file is not unlocked? */
  29354. pPager->dbOrigSize = 0;
  29355. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  29356. if( !MEMDB ){
  29357. pPager->dbSizeValid = 0;
  29358. }
  29359. return (rc==SQLITE_OK?rc2:rc);
  29360. }
  29361. /*
  29362. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  29363. ** of data. Compute and return a checksum based ont the contents of the
  29364. ** page of data and the current value of pPager->cksumInit.
  29365. **
  29366. ** This is not a real checksum. It is really just the sum of the
  29367. ** random initial value (pPager->cksumInit) and every 200th byte
  29368. ** of the page data, starting with byte offset (pPager->pageSize%200).
  29369. ** Each byte is interpreted as an 8-bit unsigned integer.
  29370. **
  29371. ** Changing the formula used to compute this checksum results in an
  29372. ** incompatible journal file format.
  29373. **
  29374. ** If journal corruption occurs due to a power failure, the most likely
  29375. ** scenario is that one end or the other of the record will be changed.
  29376. ** It is much less likely that the two ends of the journal record will be
  29377. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  29378. ** though fast and simple, catches the mostly likely kind of corruption.
  29379. */
  29380. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  29381. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  29382. int i = pPager->pageSize-200; /* Loop counter */
  29383. while( i>0 ){
  29384. cksum += aData[i];
  29385. i -= 200;
  29386. }
  29387. return cksum;
  29388. }
  29389. /*
  29390. ** Read a single page from either the journal file (if isMainJrnl==1) or
  29391. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  29392. ** The page begins at offset *pOffset into the file. The *pOffset
  29393. ** value is increased to the start of the next page in the journal.
  29394. **
  29395. ** The isMainJrnl flag is true if this is the main rollback journal and
  29396. ** false for the statement journal. The main rollback journal uses
  29397. ** checksums - the statement journal does not.
  29398. **
  29399. ** If the page number of the page record read from the (sub-)journal file
  29400. ** is greater than the current value of Pager.dbSize, then playback is
  29401. ** skipped and SQLITE_OK is returned.
  29402. **
  29403. ** If pDone is not NULL, then it is a record of pages that have already
  29404. ** been played back. If the page at *pOffset has already been played back
  29405. ** (if the corresponding pDone bit is set) then skip the playback.
  29406. ** Make sure the pDone bit corresponding to the *pOffset page is set
  29407. ** prior to returning.
  29408. **
  29409. ** If the page record is successfully read from the (sub-)journal file
  29410. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  29411. ** while reading the record from the (sub-)journal file or while writing
  29412. ** to the database file, then the IO error code is returned. If data
  29413. ** is successfully read from the (sub-)journal file but appears to be
  29414. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  29415. ** two circumstances:
  29416. **
  29417. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  29418. ** * If the record is being rolled back from the main journal file
  29419. ** and the checksum field does not match the record content.
  29420. **
  29421. ** Neither of these two scenarios are possible during a savepoint rollback.
  29422. **
  29423. ** If this is a savepoint rollback, then memory may have to be dynamically
  29424. ** allocated by this function. If this is the case and an allocation fails,
  29425. ** SQLITE_NOMEM is returned.
  29426. */
  29427. static int pager_playback_one_page(
  29428. Pager *pPager, /* The pager being played back */
  29429. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  29430. int isUnsync, /* True if reading from unsynced main journal */
  29431. i64 *pOffset, /* Offset of record to playback */
  29432. int isSavepnt, /* True for a savepoint rollback */
  29433. Bitvec *pDone /* Bitvec of pages already played back */
  29434. ){
  29435. int rc;
  29436. PgHdr *pPg; /* An existing page in the cache */
  29437. Pgno pgno; /* The page number of a page in journal */
  29438. u32 cksum; /* Checksum used for sanity checking */
  29439. u8 *aData; /* Temporary storage for the page */
  29440. sqlite3_file *jfd; /* The file descriptor for the journal file */
  29441. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  29442. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  29443. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  29444. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  29445. aData = (u8*)pPager->pTmpSpace;
  29446. assert( aData ); /* Temp storage must have already been allocated */
  29447. /* Read the page number and page data from the journal or sub-journal
  29448. ** file. Return an error code to the caller if an IO error occurs.
  29449. */
  29450. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  29451. rc = read32bits(jfd, *pOffset, &pgno);
  29452. if( rc!=SQLITE_OK ) return rc;
  29453. rc = sqlite3OsRead(jfd, aData, pPager->pageSize, (*pOffset)+4);
  29454. if( rc!=SQLITE_OK ) return rc;
  29455. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  29456. /* Sanity checking on the page. This is more important that I originally
  29457. ** thought. If a power failure occurs while the journal is being written,
  29458. ** it could cause invalid data to be written into the journal. We need to
  29459. ** detect this invalid data (with high probability) and ignore it.
  29460. */
  29461. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  29462. assert( !isSavepnt );
  29463. return SQLITE_DONE;
  29464. }
  29465. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  29466. return SQLITE_OK;
  29467. }
  29468. if( isMainJrnl ){
  29469. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  29470. if( rc ) return rc;
  29471. if( !isSavepnt && pager_cksum(pPager, aData)!=cksum ){
  29472. return SQLITE_DONE;
  29473. }
  29474. }
  29475. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  29476. return rc;
  29477. }
  29478. assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
  29479. /* If the pager is in RESERVED state, then there must be a copy of this
  29480. ** page in the pager cache. In this case just update the pager cache,
  29481. ** not the database file. The page is left marked dirty in this case.
  29482. **
  29483. ** An exception to the above rule: If the database is in no-sync mode
  29484. ** and a page is moved during an incremental vacuum then the page may
  29485. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  29486. ** during a Movepage() call, then the page may not be in the cache
  29487. ** either. So the condition described in the above paragraph is not
  29488. ** assert()able.
  29489. **
  29490. ** If in EXCLUSIVE state, then we update the pager cache if it exists
  29491. ** and the main file. The page is then marked not dirty.
  29492. **
  29493. ** Ticket #1171: The statement journal might contain page content that is
  29494. ** different from the page content at the start of the transaction.
  29495. ** This occurs when a page is changed prior to the start of a statement
  29496. ** then changed again within the statement. When rolling back such a
  29497. ** statement we must not write to the original database unless we know
  29498. ** for certain that original page contents are synced into the main rollback
  29499. ** journal. Otherwise, a power loss might leave modified data in the
  29500. ** database file without an entry in the rollback journal that can
  29501. ** restore the database to its original form. Two conditions must be
  29502. ** met before writing to the database files. (1) the database must be
  29503. ** locked. (2) we know that the original page content is fully synced
  29504. ** in the main journal either because the page is not in cache or else
  29505. ** the page is marked as needSync==0.
  29506. **
  29507. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  29508. ** is possible to fail a statement on a database that does not yet exist.
  29509. ** Do not attempt to write if database file has never been opened.
  29510. */
  29511. pPg = pager_lookup(pPager, pgno);
  29512. assert( pPg || !MEMDB );
  29513. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  29514. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData),
  29515. (isMainJrnl?"main-journal":"sub-journal")
  29516. ));
  29517. if( (pPager->state>=PAGER_EXCLUSIVE)
  29518. && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
  29519. && isOpen(pPager->fd)
  29520. && !isUnsync
  29521. ){
  29522. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  29523. rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
  29524. if( pgno>pPager->dbFileSize ){
  29525. pPager->dbFileSize = pgno;
  29526. }
  29527. sqlite3BackupUpdate(pPager->pBackup, pgno, aData);
  29528. }else if( !isMainJrnl && pPg==0 ){
  29529. /* If this is a rollback of a savepoint and data was not written to
  29530. ** the database and the page is not in-memory, there is a potential
  29531. ** problem. When the page is next fetched by the b-tree layer, it
  29532. ** will be read from the database file, which may or may not be
  29533. ** current.
  29534. **
  29535. ** There are a couple of different ways this can happen. All are quite
  29536. ** obscure. When running in synchronous mode, this can only happen
  29537. ** if the page is on the free-list at the start of the transaction, then
  29538. ** populated, then moved using sqlite3PagerMovepage().
  29539. **
  29540. ** The solution is to add an in-memory page to the cache containing
  29541. ** the data just read from the sub-journal. Mark the page as dirty
  29542. ** and if the pager requires a journal-sync, then mark the page as
  29543. ** requiring a journal-sync before it is written.
  29544. */
  29545. assert( isSavepnt );
  29546. if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
  29547. return rc;
  29548. }
  29549. pPg->flags &= ~PGHDR_NEED_READ;
  29550. sqlite3PcacheMakeDirty(pPg);
  29551. }
  29552. if( pPg ){
  29553. /* No page should ever be explicitly rolled back that is in use, except
  29554. ** for page 1 which is held in use in order to keep the lock on the
  29555. ** database active. However such a page may be rolled back as a result
  29556. ** of an internal error resulting in an automatic call to
  29557. ** sqlite3PagerRollback().
  29558. */
  29559. void *pData;
  29560. pData = pPg->pData;
  29561. memcpy(pData, aData, pPager->pageSize);
  29562. if( pPager->xReiniter ){
  29563. pPager->xReiniter(pPg);
  29564. }
  29565. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  29566. /* If the contents of this page were just restored from the main
  29567. ** journal file, then its content must be as they were when the
  29568. ** transaction was first opened. In this case we can mark the page
  29569. ** as clean, since there will be no need to write it out to the.
  29570. **
  29571. ** There is one exception to this rule. If the page is being rolled
  29572. ** back as part of a savepoint (or statement) rollback from an
  29573. ** unsynced portion of the main journal file, then it is not safe
  29574. ** to mark the page as clean. This is because marking the page as
  29575. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  29576. ** already in the journal file (recorded in Pager.pInJournal) and
  29577. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  29578. ** again within this transaction, it will be marked as dirty but
  29579. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  29580. ** be written out into the database file before its journal file
  29581. ** segment is synced. If a crash occurs during or following this,
  29582. ** database corruption may ensue.
  29583. */
  29584. sqlite3PcacheMakeClean(pPg);
  29585. }
  29586. #ifdef SQLITE_CHECK_PAGES
  29587. pPg->pageHash = pager_pagehash(pPg);
  29588. #endif
  29589. /* If this was page 1, then restore the value of Pager.dbFileVers.
  29590. ** Do this before any decoding. */
  29591. if( pgno==1 ){
  29592. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  29593. }
  29594. /* Decode the page just read from disk */
  29595. CODEC1(pPager, pData, pPg->pgno, 3);
  29596. sqlite3PcacheRelease(pPg);
  29597. }
  29598. return rc;
  29599. }
  29600. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  29601. /*
  29602. ** This routine looks ahead into the main journal file and determines
  29603. ** whether or not the next record (the record that begins at file
  29604. ** offset pPager->journalOff) is a well-formed page record consisting
  29605. ** of a valid page number, pPage->pageSize bytes of content, followed
  29606. ** by a valid checksum.
  29607. **
  29608. ** The pager never needs to know this in order to do its job. This
  29609. ** routine is only used from with assert() and testcase() macros.
  29610. */
  29611. static int pagerNextJournalPageIsValid(Pager *pPager){
  29612. Pgno pgno; /* The page number of the page */
  29613. u32 cksum; /* The page checksum */
  29614. int rc; /* Return code from read operations */
  29615. sqlite3_file *fd; /* The file descriptor from which we are reading */
  29616. u8 *aData; /* Content of the page */
  29617. /* Read the page number header */
  29618. fd = pPager->jfd;
  29619. rc = read32bits(fd, pPager->journalOff, &pgno);
  29620. if( rc!=SQLITE_OK ){ return 0; } /*NO_TEST*/
  29621. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ return 0; } /*NO_TEST*/
  29622. if( pgno>(Pgno)pPager->dbSize ){ return 0; } /*NO_TEST*/
  29623. /* Read the checksum */
  29624. rc = read32bits(fd, pPager->journalOff+pPager->pageSize+4, &cksum);
  29625. if( rc!=SQLITE_OK ){ return 0; } /*NO_TEST*/
  29626. /* Read the data and verify the checksum */
  29627. aData = (u8*)pPager->pTmpSpace;
  29628. rc = sqlite3OsRead(fd, aData, pPager->pageSize, pPager->journalOff+4);
  29629. if( rc!=SQLITE_OK ){ return 0; } /*NO_TEST*/
  29630. if( pager_cksum(pPager, aData)!=cksum ){ return 0; } /*NO_TEST*/
  29631. /* Reach this point only if the page is valid */
  29632. return 1;
  29633. }
  29634. #endif /* !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) */
  29635. /*
  29636. ** Parameter zMaster is the name of a master journal file. A single journal
  29637. ** file that referred to the master journal file has just been rolled back.
  29638. ** This routine checks if it is possible to delete the master journal file,
  29639. ** and does so if it is.
  29640. **
  29641. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  29642. ** available for use within this function.
  29643. **
  29644. ** When a master journal file is created, it is populated with the names
  29645. ** of all of its child journals, one after another, formatted as utf-8
  29646. ** encoded text. The end of each child journal file is marked with a
  29647. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  29648. ** file for a transaction involving two databases might be:
  29649. **
  29650. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  29651. **
  29652. ** A master journal file may only be deleted once all of its child
  29653. ** journals have been rolled back.
  29654. **
  29655. ** This function reads the contents of the master-journal file into
  29656. ** memory and loops through each of the child journal names. For
  29657. ** each child journal, it checks if:
  29658. **
  29659. ** * if the child journal exists, and if so
  29660. ** * if the child journal contains a reference to master journal
  29661. ** file zMaster
  29662. **
  29663. ** If a child journal can be found that matches both of the criteria
  29664. ** above, this function returns without doing anything. Otherwise, if
  29665. ** no such child journal can be found, file zMaster is deleted from
  29666. ** the file-system using sqlite3OsDelete().
  29667. **
  29668. ** If an IO error within this function, an error code is returned. This
  29669. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  29670. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  29671. ** occur, SQLITE_OK is returned.
  29672. **
  29673. ** TODO: This function allocates a single block of memory to load
  29674. ** the entire contents of the master journal file. This could be
  29675. ** a couple of kilobytes or so - potentially larger than the page
  29676. ** size.
  29677. */
  29678. static int pager_delmaster(Pager *pPager, const char *zMaster){
  29679. sqlite3_vfs *pVfs = pPager->pVfs;
  29680. int rc; /* Return code */
  29681. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  29682. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  29683. char *zMasterJournal = 0; /* Contents of master journal file */
  29684. i64 nMasterJournal; /* Size of master journal file */
  29685. /* Allocate space for both the pJournal and pMaster file descriptors.
  29686. ** If successful, open the master journal file for reading.
  29687. */
  29688. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  29689. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  29690. if( !pMaster ){
  29691. rc = SQLITE_NOMEM;
  29692. }else{
  29693. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  29694. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  29695. }
  29696. if( rc!=SQLITE_OK ) goto delmaster_out;
  29697. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  29698. if( rc!=SQLITE_OK ) goto delmaster_out;
  29699. if( nMasterJournal>0 ){
  29700. char *zJournal;
  29701. char *zMasterPtr = 0;
  29702. int nMasterPtr = pVfs->mxPathname+1;
  29703. /* Load the entire master journal file into space obtained from
  29704. ** sqlite3_malloc() and pointed to by zMasterJournal.
  29705. */
  29706. zMasterJournal = (char *)sqlite3Malloc((int)nMasterJournal + nMasterPtr);
  29707. if( !zMasterJournal ){
  29708. rc = SQLITE_NOMEM;
  29709. goto delmaster_out;
  29710. }
  29711. zMasterPtr = &zMasterJournal[nMasterJournal];
  29712. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  29713. if( rc!=SQLITE_OK ) goto delmaster_out;
  29714. zJournal = zMasterJournal;
  29715. while( (zJournal-zMasterJournal)<nMasterJournal ){
  29716. int exists;
  29717. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  29718. if( rc!=SQLITE_OK ){
  29719. goto delmaster_out;
  29720. }
  29721. if( exists ){
  29722. /* One of the journals pointed to by the master journal exists.
  29723. ** Open it and check if it points at the master journal. If
  29724. ** so, return without deleting the master journal file.
  29725. */
  29726. int c;
  29727. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  29728. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  29729. if( rc!=SQLITE_OK ){
  29730. goto delmaster_out;
  29731. }
  29732. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  29733. sqlite3OsClose(pJournal);
  29734. if( rc!=SQLITE_OK ){
  29735. goto delmaster_out;
  29736. }
  29737. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  29738. if( c ){
  29739. /* We have a match. Do not delete the master journal file. */
  29740. goto delmaster_out;
  29741. }
  29742. }
  29743. zJournal += (sqlite3Strlen30(zJournal)+1);
  29744. }
  29745. }
  29746. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  29747. delmaster_out:
  29748. if( zMasterJournal ){
  29749. sqlite3_free(zMasterJournal);
  29750. }
  29751. if( pMaster ){
  29752. sqlite3OsClose(pMaster);
  29753. assert( !isOpen(pJournal) );
  29754. }
  29755. sqlite3_free(pMaster);
  29756. return rc;
  29757. }
  29758. /*
  29759. ** This function is used to change the actual size of the database
  29760. ** file in the file-system. This only happens when committing a transaction,
  29761. ** or rolling back a transaction (including rolling back a hot-journal).
  29762. **
  29763. ** If the main database file is not open, or an exclusive lock is not
  29764. ** held, this function is a no-op. Otherwise, the size of the file is
  29765. ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
  29766. ** on disk is currently larger than nPage pages, then use the VFS
  29767. ** xTruncate() method to truncate it.
  29768. **
  29769. ** Or, it might might be the case that the file on disk is smaller than
  29770. ** nPage pages. Some operating system implementations can get confused if
  29771. ** you try to truncate a file to some size that is larger than it
  29772. ** currently is, so detect this case and write a single zero byte to
  29773. ** the end of the new file instead.
  29774. **
  29775. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  29776. ** the database file, return the error code to the caller.
  29777. */
  29778. static int pager_truncate(Pager *pPager, Pgno nPage){
  29779. int rc = SQLITE_OK;
  29780. if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
  29781. i64 currentSize, newSize;
  29782. /* TODO: Is it safe to use Pager.dbFileSize here? */
  29783. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  29784. newSize = pPager->pageSize*(i64)nPage;
  29785. if( rc==SQLITE_OK && currentSize!=newSize ){
  29786. if( currentSize>newSize ){
  29787. rc = sqlite3OsTruncate(pPager->fd, newSize);
  29788. }else{
  29789. rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
  29790. }
  29791. if( rc==SQLITE_OK ){
  29792. pPager->dbFileSize = nPage;
  29793. }
  29794. }
  29795. }
  29796. return rc;
  29797. }
  29798. /*
  29799. ** Set the value of the Pager.sectorSize variable for the given
  29800. ** pager based on the value returned by the xSectorSize method
  29801. ** of the open database file. The sector size will be used used
  29802. ** to determine the size and alignment of journal header and
  29803. ** master journal pointers within created journal files.
  29804. **
  29805. ** For temporary files the effective sector size is always 512 bytes.
  29806. **
  29807. ** Otherwise, for non-temporary files, the effective sector size is
  29808. ** the value returned by the xSectorSize() method rounded up to 512 if
  29809. ** it is less than 512, or rounded down to MAX_SECTOR_SIZE if it
  29810. ** is greater than MAX_SECTOR_SIZE.
  29811. */
  29812. static void setSectorSize(Pager *pPager){
  29813. assert( isOpen(pPager->fd) || pPager->tempFile );
  29814. if( !pPager->tempFile ){
  29815. /* Sector size doesn't matter for temporary files. Also, the file
  29816. ** may not have been opened yet, in which case the OsSectorSize()
  29817. ** call will segfault.
  29818. */
  29819. pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  29820. }
  29821. if( pPager->sectorSize<512 ){
  29822. pPager->sectorSize = 512;
  29823. }
  29824. if( pPager->sectorSize>MAX_SECTOR_SIZE ){
  29825. assert( MAX_SECTOR_SIZE>=512 );
  29826. pPager->sectorSize = MAX_SECTOR_SIZE;
  29827. }
  29828. }
  29829. /*
  29830. ** Playback the journal and thus restore the database file to
  29831. ** the state it was in before we started making changes.
  29832. **
  29833. ** The journal file format is as follows:
  29834. **
  29835. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  29836. ** (2) 4 byte big-endian integer which is the number of valid page records
  29837. ** in the journal. If this value is 0xffffffff, then compute the
  29838. ** number of page records from the journal size.
  29839. ** (3) 4 byte big-endian integer which is the initial value for the
  29840. ** sanity checksum.
  29841. ** (4) 4 byte integer which is the number of pages to truncate the
  29842. ** database to during a rollback.
  29843. ** (5) 4 byte big-endian integer which is the sector size. The header
  29844. ** is this many bytes in size.
  29845. ** (6) 4 byte big-endian integer which is the page case.
  29846. ** (7) 4 byte integer which is the number of bytes in the master journal
  29847. ** name. The value may be zero (indicate that there is no master
  29848. ** journal.)
  29849. ** (8) N bytes of the master journal name. The name will be nul-terminated
  29850. ** and might be shorter than the value read from (5). If the first byte
  29851. ** of the name is \000 then there is no master journal. The master
  29852. ** journal name is stored in UTF-8.
  29853. ** (9) Zero or more pages instances, each as follows:
  29854. ** + 4 byte page number.
  29855. ** + pPager->pageSize bytes of data.
  29856. ** + 4 byte checksum
  29857. **
  29858. ** When we speak of the journal header, we mean the first 8 items above.
  29859. ** Each entry in the journal is an instance of the 9th item.
  29860. **
  29861. ** Call the value from the second bullet "nRec". nRec is the number of
  29862. ** valid page entries in the journal. In most cases, you can compute the
  29863. ** value of nRec from the size of the journal file. But if a power
  29864. ** failure occurred while the journal was being written, it could be the
  29865. ** case that the size of the journal file had already been increased but
  29866. ** the extra entries had not yet made it safely to disk. In such a case,
  29867. ** the value of nRec computed from the file size would be too large. For
  29868. ** that reason, we always use the nRec value in the header.
  29869. **
  29870. ** If the nRec value is 0xffffffff it means that nRec should be computed
  29871. ** from the file size. This value is used when the user selects the
  29872. ** no-sync option for the journal. A power failure could lead to corruption
  29873. ** in this case. But for things like temporary table (which will be
  29874. ** deleted when the power is restored) we don't care.
  29875. **
  29876. ** If the file opened as the journal file is not a well-formed
  29877. ** journal file then all pages up to the first corrupted page are rolled
  29878. ** back (or no pages if the journal header is corrupted). The journal file
  29879. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  29880. ** been encountered.
  29881. **
  29882. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  29883. ** and an error code is returned.
  29884. **
  29885. ** The isHot parameter indicates that we are trying to rollback a journal
  29886. ** that might be a hot journal. Or, it could be that the journal is
  29887. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  29888. ** If the journal really is hot, reset the pager cache prior rolling
  29889. ** back any content. If the journal is merely persistent, no reset is
  29890. ** needed.
  29891. */
  29892. static int pager_playback(Pager *pPager, int isHot){
  29893. sqlite3_vfs *pVfs = pPager->pVfs;
  29894. i64 szJ; /* Size of the journal file in bytes */
  29895. u32 nRec; /* Number of Records in the journal */
  29896. u32 u; /* Unsigned loop counter */
  29897. Pgno mxPg = 0; /* Size of the original file in pages */
  29898. int rc; /* Result code of a subroutine */
  29899. int res = 1; /* Value returned by sqlite3OsAccess() */
  29900. char *zMaster = 0; /* Name of master journal file if any */
  29901. int needPagerReset; /* True to reset page prior to first page rollback */
  29902. /* Figure out how many records are in the journal. Abort early if
  29903. ** the journal is empty.
  29904. */
  29905. assert( isOpen(pPager->jfd) );
  29906. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  29907. if( rc!=SQLITE_OK || szJ==0 ){
  29908. goto end_playback;
  29909. }
  29910. /* Read the master journal name from the journal, if it is present.
  29911. ** If a master journal file name is specified, but the file is not
  29912. ** present on disk, then the journal is not hot and does not need to be
  29913. ** played back.
  29914. **
  29915. ** TODO: Technically the following is an error because it assumes that
  29916. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  29917. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  29918. ** mxPathname is 512, which is the same as the minimum allowable value
  29919. ** for pageSize.
  29920. */
  29921. zMaster = pPager->pTmpSpace;
  29922. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  29923. if( rc==SQLITE_OK && zMaster[0] ){
  29924. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  29925. }
  29926. zMaster = 0;
  29927. if( rc!=SQLITE_OK || !res ){
  29928. goto end_playback;
  29929. }
  29930. pPager->journalOff = 0;
  29931. needPagerReset = isHot;
  29932. /* This loop terminates either when a readJournalHdr() or
  29933. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  29934. ** occurs.
  29935. */
  29936. while( 1 ){
  29937. int isUnsync = 0;
  29938. /* Read the next journal header from the journal file. If there are
  29939. ** not enough bytes left in the journal file for a complete header, or
  29940. ** it is corrupted, then a process must of failed while writing it.
  29941. ** This indicates nothing more needs to be rolled back.
  29942. */
  29943. rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
  29944. if( rc!=SQLITE_OK ){
  29945. if( rc==SQLITE_DONE ){
  29946. rc = SQLITE_OK;
  29947. }
  29948. goto end_playback;
  29949. }
  29950. /* If nRec is 0xffffffff, then this journal was created by a process
  29951. ** working in no-sync mode. This means that the rest of the journal
  29952. ** file consists of pages, there are no more journal headers. Compute
  29953. ** the value of nRec based on this assumption.
  29954. */
  29955. if( nRec==0xffffffff ){
  29956. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  29957. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  29958. }
  29959. /* If nRec is 0 and this rollback is of a transaction created by this
  29960. ** process and if this is the final header in the journal, then it means
  29961. ** that this part of the journal was being filled but has not yet been
  29962. ** synced to disk. Compute the number of pages based on the remaining
  29963. ** size of the file.
  29964. **
  29965. ** The third term of the test was added to fix ticket #2565.
  29966. ** When rolling back a hot journal, nRec==0 always means that the next
  29967. ** chunk of the journal contains zero pages to be rolled back. But
  29968. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  29969. ** the journal, it means that the journal might contain additional
  29970. ** pages that need to be rolled back and that the number of pages
  29971. ** should be computed based on the journal file size.
  29972. */
  29973. testcase( nRec==0 && !isHot
  29974. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
  29975. && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
  29976. && pagerNextJournalPageIsValid(pPager)
  29977. );
  29978. if( nRec==0 && !isHot &&
  29979. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  29980. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  29981. isUnsync = 1;
  29982. }
  29983. /* If this is the first header read from the journal, truncate the
  29984. ** database file back to its original size.
  29985. */
  29986. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  29987. rc = pager_truncate(pPager, mxPg);
  29988. if( rc!=SQLITE_OK ){
  29989. goto end_playback;
  29990. }
  29991. pPager->dbSize = mxPg;
  29992. }
  29993. /* Copy original pages out of the journal and back into the
  29994. ** database file and/or page cache.
  29995. */
  29996. for(u=0; u<nRec; u++){
  29997. if( needPagerReset ){
  29998. pager_reset(pPager);
  29999. needPagerReset = 0;
  30000. }
  30001. rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
  30002. if( rc!=SQLITE_OK ){
  30003. if( rc==SQLITE_DONE ){
  30004. rc = SQLITE_OK;
  30005. pPager->journalOff = szJ;
  30006. break;
  30007. }else{
  30008. /* If we are unable to rollback, quit and return the error
  30009. ** code. This will cause the pager to enter the error state
  30010. ** so that no further harm will be done. Perhaps the next
  30011. ** process to come along will be able to rollback the database.
  30012. */
  30013. goto end_playback;
  30014. }
  30015. }
  30016. }
  30017. }
  30018. /*NOTREACHED*/
  30019. assert( 0 );
  30020. end_playback:
  30021. /* Following a rollback, the database file should be back in its original
  30022. ** state prior to the start of the transaction, so invoke the
  30023. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  30024. ** assertion that the transaction counter was modified.
  30025. */
  30026. assert(
  30027. pPager->fd->pMethods==0 ||
  30028. sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
  30029. );
  30030. /* If this playback is happening automatically as a result of an IO or
  30031. ** malloc error that occurred after the change-counter was updated but
  30032. ** before the transaction was committed, then the change-counter
  30033. ** modification may just have been reverted. If this happens in exclusive
  30034. ** mode, then subsequent transactions performed by the connection will not
  30035. ** update the change-counter at all. This may lead to cache inconsistency
  30036. ** problems for other processes at some point in the future. So, just
  30037. ** in case this has happened, clear the changeCountDone flag now.
  30038. */
  30039. pPager->changeCountDone = pPager->tempFile;
  30040. if( rc==SQLITE_OK ){
  30041. zMaster = pPager->pTmpSpace;
  30042. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  30043. testcase( rc!=SQLITE_OK );
  30044. }
  30045. if( rc==SQLITE_OK ){
  30046. rc = pager_end_transaction(pPager, zMaster[0]!='\0');
  30047. testcase( rc!=SQLITE_OK );
  30048. }
  30049. if( rc==SQLITE_OK && zMaster[0] && res ){
  30050. /* If there was a master journal and this routine will return success,
  30051. ** see if it is possible to delete the master journal.
  30052. */
  30053. rc = pager_delmaster(pPager, zMaster);
  30054. testcase( rc!=SQLITE_OK );
  30055. }
  30056. /* The Pager.sectorSize variable may have been updated while rolling
  30057. ** back a journal created by a process with a different sector size
  30058. ** value. Reset it to the correct value for this process.
  30059. */
  30060. setSectorSize(pPager);
  30061. return rc;
  30062. }
  30063. /*
  30064. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  30065. ** the entire master journal file. The case pSavepoint==NULL occurs when
  30066. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  30067. ** savepoint.
  30068. **
  30069. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  30070. ** being rolled back), then the rollback consists of up to three stages,
  30071. ** performed in the order specified:
  30072. **
  30073. ** * Pages are played back from the main journal starting at byte
  30074. ** offset PagerSavepoint.iOffset and continuing to
  30075. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  30076. ** file if PagerSavepoint.iHdrOffset is zero.
  30077. **
  30078. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  30079. ** back starting from the journal header immediately following
  30080. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  30081. **
  30082. ** * Pages are then played back from the sub-journal file, starting
  30083. ** with the PagerSavepoint.iSubRec and continuing to the end of
  30084. ** the journal file.
  30085. **
  30086. ** Throughout the rollback process, each time a page is rolled back, the
  30087. ** corresponding bit is set in a bitvec structure (variable pDone in the
  30088. ** implementation below). This is used to ensure that a page is only
  30089. ** rolled back the first time it is encountered in either journal.
  30090. **
  30091. ** If pSavepoint is NULL, then pages are only played back from the main
  30092. ** journal file. There is no need for a bitvec in this case.
  30093. **
  30094. ** In either case, before playback commences the Pager.dbSize variable
  30095. ** is reset to the value that it held at the start of the savepoint
  30096. ** (or transaction). No page with a page-number greater than this value
  30097. ** is played back. If one is encountered it is simply skipped.
  30098. */
  30099. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  30100. i64 szJ; /* Effective size of the main journal */
  30101. i64 iHdrOff; /* End of first segment of main-journal records */
  30102. int rc = SQLITE_OK; /* Return code */
  30103. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  30104. assert( pPager->state>=PAGER_SHARED );
  30105. /* Allocate a bitvec to use to store the set of pages rolled back */
  30106. if( pSavepoint ){
  30107. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  30108. if( !pDone ){
  30109. return SQLITE_NOMEM;
  30110. }
  30111. }
  30112. /* Set the database size back to the value it was before the savepoint
  30113. ** being reverted was opened.
  30114. */
  30115. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  30116. /* Use pPager->journalOff as the effective size of the main rollback
  30117. ** journal. The actual file might be larger than this in
  30118. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  30119. ** past pPager->journalOff is off-limits to us.
  30120. */
  30121. szJ = pPager->journalOff;
  30122. /* Begin by rolling back records from the main journal starting at
  30123. ** PagerSavepoint.iOffset and continuing to the next journal header.
  30124. ** There might be records in the main journal that have a page number
  30125. ** greater than the current database size (pPager->dbSize) but those
  30126. ** will be skipped automatically. Pages are added to pDone as they
  30127. ** are played back.
  30128. */
  30129. if( pSavepoint ){
  30130. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  30131. pPager->journalOff = pSavepoint->iOffset;
  30132. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  30133. rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
  30134. }
  30135. assert( rc!=SQLITE_DONE );
  30136. }else{
  30137. pPager->journalOff = 0;
  30138. }
  30139. /* Continue rolling back records out of the main journal starting at
  30140. ** the first journal header seen and continuing until the effective end
  30141. ** of the main journal file. Continue to skip out-of-range pages and
  30142. ** continue adding pages rolled back to pDone.
  30143. */
  30144. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  30145. u32 ii; /* Loop counter */
  30146. u32 nJRec = 0; /* Number of Journal Records */
  30147. u32 dummy;
  30148. rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
  30149. assert( rc!=SQLITE_DONE );
  30150. /*
  30151. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  30152. ** test is related to ticket #2565. See the discussion in the
  30153. ** pager_playback() function for additional information.
  30154. */
  30155. assert( !(nJRec==0
  30156. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
  30157. && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
  30158. && pagerNextJournalPageIsValid(pPager))
  30159. );
  30160. if( nJRec==0
  30161. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  30162. ){
  30163. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  30164. }
  30165. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  30166. rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
  30167. }
  30168. assert( rc!=SQLITE_DONE );
  30169. }
  30170. assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
  30171. /* Finally, rollback pages from the sub-journal. Page that were
  30172. ** previously rolled back out of the main journal (and are hence in pDone)
  30173. ** will be skipped. Out-of-range pages are also skipped.
  30174. */
  30175. if( pSavepoint ){
  30176. u32 ii; /* Loop counter */
  30177. i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
  30178. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  30179. assert( offset==ii*(4+pPager->pageSize) );
  30180. rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
  30181. }
  30182. assert( rc!=SQLITE_DONE );
  30183. }
  30184. sqlite3BitvecDestroy(pDone);
  30185. if( rc==SQLITE_OK ){
  30186. pPager->journalOff = szJ;
  30187. }
  30188. return rc;
  30189. }
  30190. /*
  30191. ** Change the maximum number of in-memory pages that are allowed.
  30192. */
  30193. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  30194. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  30195. }
  30196. /*
  30197. ** Adjust the robustness of the database to damage due to OS crashes
  30198. ** or power failures by changing the number of syncs()s when writing
  30199. ** the rollback journal. There are three levels:
  30200. **
  30201. ** OFF sqlite3OsSync() is never called. This is the default
  30202. ** for temporary and transient files.
  30203. **
  30204. ** NORMAL The journal is synced once before writes begin on the
  30205. ** database. This is normally adequate protection, but
  30206. ** it is theoretically possible, though very unlikely,
  30207. ** that an inopertune power failure could leave the journal
  30208. ** in a state which would cause damage to the database
  30209. ** when it is rolled back.
  30210. **
  30211. ** FULL The journal is synced twice before writes begin on the
  30212. ** database (with some additional information - the nRec field
  30213. ** of the journal header - being written in between the two
  30214. ** syncs). If we assume that writing a
  30215. ** single disk sector is atomic, then this mode provides
  30216. ** assurance that the journal will not be corrupted to the
  30217. ** point of causing damage to the database during rollback.
  30218. **
  30219. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  30220. ** and FULL=3.
  30221. */
  30222. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  30223. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
  30224. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  30225. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  30226. pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
  30227. if( pPager->noSync ) pPager->needSync = 0;
  30228. }
  30229. #endif
  30230. /*
  30231. ** The following global variable is incremented whenever the library
  30232. ** attempts to open a temporary file. This information is used for
  30233. ** testing and analysis only.
  30234. */
  30235. #ifdef SQLITE_TEST
  30236. SQLITE_API int sqlite3_opentemp_count = 0;
  30237. #endif
  30238. /*
  30239. ** Open a temporary file.
  30240. **
  30241. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  30242. ** or some other error code if we fail. The OS will automatically
  30243. ** delete the temporary file when it is closed.
  30244. **
  30245. ** The flags passed to the VFS layer xOpen() call are those specified
  30246. ** by parameter vfsFlags ORed with the following:
  30247. **
  30248. ** SQLITE_OPEN_READWRITE
  30249. ** SQLITE_OPEN_CREATE
  30250. ** SQLITE_OPEN_EXCLUSIVE
  30251. ** SQLITE_OPEN_DELETEONCLOSE
  30252. */
  30253. static int pagerOpentemp(
  30254. Pager *pPager, /* The pager object */
  30255. sqlite3_file *pFile, /* Write the file descriptor here */
  30256. int vfsFlags /* Flags passed through to the VFS */
  30257. ){
  30258. int rc; /* Return code */
  30259. #ifdef SQLITE_TEST
  30260. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  30261. #endif
  30262. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  30263. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  30264. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  30265. assert( rc!=SQLITE_OK || isOpen(pFile) );
  30266. return rc;
  30267. }
  30268. /*
  30269. ** Set the busy handler function.
  30270. **
  30271. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  30272. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  30273. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  30274. ** lock. It does *not* invoke the busy handler when upgrading from
  30275. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  30276. ** (which occurs during hot-journal rollback). Summary:
  30277. **
  30278. ** Transition | Invokes xBusyHandler
  30279. ** --------------------------------------------------------
  30280. ** NO_LOCK -> SHARED_LOCK | Yes
  30281. ** SHARED_LOCK -> RESERVED_LOCK | No
  30282. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  30283. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  30284. **
  30285. ** If the busy-handler callback returns non-zero, the lock is
  30286. ** retried. If it returns zero, then the SQLITE_BUSY error is
  30287. ** returned to the caller of the pager API function.
  30288. */
  30289. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  30290. Pager *pPager, /* Pager object */
  30291. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  30292. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  30293. ){
  30294. pPager->xBusyHandler = xBusyHandler;
  30295. pPager->pBusyHandlerArg = pBusyHandlerArg;
  30296. }
  30297. /*
  30298. ** Set the reinitializer for this pager. If not NULL, the reinitializer
  30299. ** is called when the content of a page in cache is modified (restored)
  30300. ** as part of a transaction or savepoint rollback. The callback gives
  30301. ** higher-level code an opportunity to restore the EXTRA section to
  30302. ** agree with the restored page data.
  30303. */
  30304. SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
  30305. pPager->xReiniter = xReinit;
  30306. }
  30307. /*
  30308. ** Change the page size used by the Pager object. The new page size
  30309. ** is passed in *pPageSize.
  30310. **
  30311. ** If the pager is in the error state when this function is called, it
  30312. ** is a no-op. The value returned is the error state error code (i.e.
  30313. ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
  30314. **
  30315. ** Otherwise, if all of the following are true:
  30316. **
  30317. ** * the new page size (value of *pPageSize) is valid (a power
  30318. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  30319. **
  30320. ** * there are no outstanding page references, and
  30321. **
  30322. ** * the database is either not an in-memory database or it is
  30323. ** an in-memory database that currently consists of zero pages.
  30324. **
  30325. ** then the pager object page size is set to *pPageSize.
  30326. **
  30327. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  30328. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  30329. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  30330. ** In all other cases, SQLITE_OK is returned.
  30331. **
  30332. ** If the page size is not changed, either because one of the enumerated
  30333. ** conditions above is not true, the pager was in error state when this
  30334. ** function was called, or because the memory allocation attempt failed,
  30335. ** then *pPageSize is set to the old, retained page size before returning.
  30336. */
  30337. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
  30338. int rc = pPager->errCode;
  30339. if( rc==SQLITE_OK ){
  30340. u16 pageSize = *pPageSize;
  30341. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  30342. if( pageSize && pageSize!=pPager->pageSize
  30343. && (pPager->memDb==0 || pPager->dbSize==0)
  30344. && sqlite3PcacheRefCount(pPager->pPCache)==0
  30345. ){
  30346. char *pNew = (char *)sqlite3PageMalloc(pageSize);
  30347. if( !pNew ){
  30348. rc = SQLITE_NOMEM;
  30349. }else{
  30350. pager_reset(pPager);
  30351. pPager->pageSize = pageSize;
  30352. sqlite3PageFree(pPager->pTmpSpace);
  30353. pPager->pTmpSpace = pNew;
  30354. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  30355. }
  30356. }
  30357. *pPageSize = (u16)pPager->pageSize;
  30358. }
  30359. return rc;
  30360. }
  30361. /*
  30362. ** Return a pointer to the "temporary page" buffer held internally
  30363. ** by the pager. This is a buffer that is big enough to hold the
  30364. ** entire content of a database page. This buffer is used internally
  30365. ** during rollback and will be overwritten whenever a rollback
  30366. ** occurs. But other modules are free to use it too, as long as
  30367. ** no rollbacks are happening.
  30368. */
  30369. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  30370. return pPager->pTmpSpace;
  30371. }
  30372. /*
  30373. ** Attempt to set the maximum database page count if mxPage is positive.
  30374. ** Make no changes if mxPage is zero or negative. And never reduce the
  30375. ** maximum page count below the current size of the database.
  30376. **
  30377. ** Regardless of mxPage, return the current maximum page count.
  30378. */
  30379. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  30380. if( mxPage>0 ){
  30381. pPager->mxPgno = mxPage;
  30382. }
  30383. sqlite3PagerPagecount(pPager, 0);
  30384. return pPager->mxPgno;
  30385. }
  30386. /*
  30387. ** The following set of routines are used to disable the simulated
  30388. ** I/O error mechanism. These routines are used to avoid simulated
  30389. ** errors in places where we do not care about errors.
  30390. **
  30391. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  30392. ** and generate no code.
  30393. */
  30394. #ifdef SQLITE_TEST
  30395. SQLITE_API extern int sqlite3_io_error_pending;
  30396. SQLITE_API extern int sqlite3_io_error_hit;
  30397. static int saved_cnt;
  30398. void disable_simulated_io_errors(void){
  30399. saved_cnt = sqlite3_io_error_pending;
  30400. sqlite3_io_error_pending = -1;
  30401. }
  30402. void enable_simulated_io_errors(void){
  30403. sqlite3_io_error_pending = saved_cnt;
  30404. }
  30405. #else
  30406. # define disable_simulated_io_errors()
  30407. # define enable_simulated_io_errors()
  30408. #endif
  30409. /*
  30410. ** Read the first N bytes from the beginning of the file into memory
  30411. ** that pDest points to.
  30412. **
  30413. ** If the pager was opened on a transient file (zFilename==""), or
  30414. ** opened on a file less than N bytes in size, the output buffer is
  30415. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  30416. ** function is used to read database headers, and a new transient or
  30417. ** zero sized database has a header than consists entirely of zeroes.
  30418. **
  30419. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  30420. ** the error code is returned to the caller and the contents of the
  30421. ** output buffer undefined.
  30422. */
  30423. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  30424. int rc = SQLITE_OK;
  30425. memset(pDest, 0, N);
  30426. assert( isOpen(pPager->fd) || pPager->tempFile );
  30427. if( isOpen(pPager->fd) ){
  30428. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  30429. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  30430. if( rc==SQLITE_IOERR_SHORT_READ ){
  30431. rc = SQLITE_OK;
  30432. }
  30433. }
  30434. return rc;
  30435. }
  30436. /*
  30437. ** Return the total number of pages in the database file associated
  30438. ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
  30439. ** However, if the file is between 1 and <page-size> bytes in size, then
  30440. ** this is considered a 1 page file.
  30441. **
  30442. ** If the pager is in error state when this function is called, then the
  30443. ** error state error code is returned and *pnPage left unchanged. Or,
  30444. ** if the file system has to be queried for the size of the file and
  30445. ** the query attempt returns an IO error, the IO error code is returned
  30446. ** and *pnPage is left unchanged.
  30447. **
  30448. ** Otherwise, if everything is successful, then SQLITE_OK is returned
  30449. ** and *pnPage is set to the number of pages in the database.
  30450. */
  30451. SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  30452. Pgno nPage; /* Value to return via *pnPage */
  30453. /* If the pager is already in the error state, return the error code. */
  30454. if( pPager->errCode ){
  30455. return pPager->errCode;
  30456. }
  30457. /* Determine the number of pages in the file. Store this in nPage. */
  30458. if( pPager->dbSizeValid ){
  30459. nPage = pPager->dbSize;
  30460. }else{
  30461. int rc; /* Error returned by OsFileSize() */
  30462. i64 n = 0; /* File size in bytes returned by OsFileSize() */
  30463. assert( isOpen(pPager->fd) || pPager->tempFile );
  30464. if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
  30465. pager_error(pPager, rc);
  30466. return rc;
  30467. }
  30468. if( n>0 && n<pPager->pageSize ){
  30469. nPage = 1;
  30470. }else{
  30471. nPage = (Pgno)(n / pPager->pageSize);
  30472. }
  30473. if( pPager->state!=PAGER_UNLOCK ){
  30474. pPager->dbSize = nPage;
  30475. pPager->dbFileSize = nPage;
  30476. pPager->dbSizeValid = 1;
  30477. }
  30478. }
  30479. /* If the current number of pages in the file is greater than the
  30480. ** configured maximum pager number, increase the allowed limit so
  30481. ** that the file can be read.
  30482. */
  30483. if( nPage>pPager->mxPgno ){
  30484. pPager->mxPgno = (Pgno)nPage;
  30485. }
  30486. /* Set the output variable and return SQLITE_OK */
  30487. if( pnPage ){
  30488. *pnPage = nPage;
  30489. }
  30490. return SQLITE_OK;
  30491. }
  30492. /*
  30493. ** Try to obtain a lock of type locktype on the database file. If
  30494. ** a similar or greater lock is already held, this function is a no-op
  30495. ** (returning SQLITE_OK immediately).
  30496. **
  30497. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  30498. ** the busy callback if the lock is currently not available. Repeat
  30499. ** until the busy callback returns false or until the attempt to
  30500. ** obtain the lock succeeds.
  30501. **
  30502. ** Return SQLITE_OK on success and an error code if we cannot obtain
  30503. ** the lock. If the lock is obtained successfully, set the Pager.state
  30504. ** variable to locktype before returning.
  30505. */
  30506. static int pager_wait_on_lock(Pager *pPager, int locktype){
  30507. int rc; /* Return code */
  30508. /* The OS lock values must be the same as the Pager lock values */
  30509. assert( PAGER_SHARED==SHARED_LOCK );
  30510. assert( PAGER_RESERVED==RESERVED_LOCK );
  30511. assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
  30512. /* If the file is currently unlocked then the size must be unknown */
  30513. assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
  30514. /* Check that this is either a no-op (because the requested lock is
  30515. ** already held, or one of the transistions that the busy-handler
  30516. ** may be invoked during, according to the comment above
  30517. ** sqlite3PagerSetBusyhandler().
  30518. */
  30519. assert( (pPager->state>=locktype)
  30520. || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
  30521. || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
  30522. );
  30523. if( pPager->state>=locktype ){
  30524. rc = SQLITE_OK;
  30525. }else{
  30526. do {
  30527. rc = sqlite3OsLock(pPager->fd, locktype);
  30528. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  30529. if( rc==SQLITE_OK ){
  30530. pPager->state = (u8)locktype;
  30531. IOTRACE(("LOCK %p %d\n", pPager, locktype))
  30532. }
  30533. }
  30534. return rc;
  30535. }
  30536. /*
  30537. ** Truncate the in-memory database file image to nPage pages. This
  30538. ** function does not actually modify the database file on disk. It
  30539. ** just sets the internal state of the pager object so that the
  30540. ** truncation will be done when the current transaction is committed.
  30541. */
  30542. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  30543. assert( pPager->dbSizeValid );
  30544. assert( pPager->dbSize>=nPage );
  30545. assert( pPager->state>=PAGER_RESERVED );
  30546. pPager->dbSize = nPage;
  30547. }
  30548. /*
  30549. ** Shutdown the page cache. Free all memory and close all files.
  30550. **
  30551. ** If a transaction was in progress when this routine is called, that
  30552. ** transaction is rolled back. All outstanding pages are invalidated
  30553. ** and their memory is freed. Any attempt to use a page associated
  30554. ** with this page cache after this function returns will likely
  30555. ** result in a coredump.
  30556. **
  30557. ** This function always succeeds. If a transaction is active an attempt
  30558. ** is made to roll it back. If an error occurs during the rollback
  30559. ** a hot journal may be left in the filesystem but no error is returned
  30560. ** to the caller.
  30561. */
  30562. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  30563. disable_simulated_io_errors();
  30564. sqlite3BeginBenignMalloc();
  30565. pPager->errCode = 0;
  30566. pPager->exclusiveMode = 0;
  30567. pager_reset(pPager);
  30568. if( MEMDB ){
  30569. pager_unlock(pPager);
  30570. }else{
  30571. /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
  30572. ** call which may be made from within pagerUnlockAndRollback(). If it
  30573. ** is not -1, then the unsynced portion of an open journal file may
  30574. ** be played back into the database. If a power failure occurs while
  30575. ** this is happening, the database may become corrupt.
  30576. */
  30577. pPager->journalHdr = -1;
  30578. pagerUnlockAndRollback(pPager);
  30579. }
  30580. sqlite3EndBenignMalloc();
  30581. enable_simulated_io_errors();
  30582. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  30583. IOTRACE(("CLOSE %p\n", pPager))
  30584. sqlite3OsClose(pPager->fd);
  30585. sqlite3PageFree(pPager->pTmpSpace);
  30586. sqlite3PcacheClose(pPager->pPCache);
  30587. assert( !pPager->aSavepoint && !pPager->pInJournal );
  30588. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  30589. sqlite3_free(pPager);
  30590. return SQLITE_OK;
  30591. }
  30592. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  30593. /*
  30594. ** Return the page number for page pPg.
  30595. */
  30596. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  30597. return pPg->pgno;
  30598. }
  30599. #endif
  30600. /*
  30601. ** Increment the reference count for page pPg.
  30602. */
  30603. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  30604. sqlite3PcacheRef(pPg);
  30605. }
  30606. /*
  30607. ** Sync the journal. In other words, make sure all the pages that have
  30608. ** been written to the journal have actually reached the surface of the
  30609. ** disk and can be restored in the event of a hot-journal rollback.
  30610. **
  30611. ** If the Pager.needSync flag is not set, then this function is a
  30612. ** no-op. Otherwise, the actions required depend on the journal-mode
  30613. ** and the device characteristics of the the file-system, as follows:
  30614. **
  30615. ** * If the journal file is an in-memory journal file, no action need
  30616. ** be taken.
  30617. **
  30618. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  30619. ** then the nRec field of the most recently written journal header
  30620. ** is updated to contain the number of journal records that have
  30621. ** been written following it. If the pager is operating in full-sync
  30622. ** mode, then the journal file is synced before this field is updated.
  30623. **
  30624. ** * If the device does not support the SEQUENTIAL property, then
  30625. ** journal file is synced.
  30626. **
  30627. ** Or, in pseudo-code:
  30628. **
  30629. ** if( NOT <in-memory journal> ){
  30630. ** if( NOT SAFE_APPEND ){
  30631. ** if( <full-sync mode> ) xSync(<journal file>);
  30632. ** <update nRec field>
  30633. ** }
  30634. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  30635. ** }
  30636. **
  30637. ** The Pager.needSync flag is never be set for temporary files, or any
  30638. ** file operating in no-sync mode (Pager.noSync set to non-zero).
  30639. **
  30640. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  30641. ** page currently held in memory before returning SQLITE_OK. If an IO
  30642. ** error is encountered, then the IO error code is returned to the caller.
  30643. */
  30644. static int syncJournal(Pager *pPager){
  30645. if( pPager->needSync ){
  30646. assert( !pPager->tempFile );
  30647. if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  30648. int rc; /* Return code */
  30649. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  30650. assert( isOpen(pPager->jfd) );
  30651. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  30652. /* Variable iNRecOffset is set to the offset in the journal file
  30653. ** of the nRec field of the most recently written journal header.
  30654. ** This field will be updated following the xSync() operation
  30655. ** on the journal file. */
  30656. i64 iNRecOffset = pPager->journalHdr + sizeof(aJournalMagic);
  30657. /* This block deals with an obscure problem. If the last connection
  30658. ** that wrote to this database was operating in persistent-journal
  30659. ** mode, then the journal file may at this point actually be larger
  30660. ** than Pager.journalOff bytes. If the next thing in the journal
  30661. ** file happens to be a journal-header (written as part of the
  30662. ** previous connections transaction), and a crash or power-failure
  30663. ** occurs after nRec is updated but before this connection writes
  30664. ** anything else to the journal file (or commits/rolls back its
  30665. ** transaction), then SQLite may become confused when doing the
  30666. ** hot-journal rollback following recovery. It may roll back all
  30667. ** of this connections data, then proceed to rolling back the old,
  30668. ** out-of-date data that follows it. Database corruption.
  30669. **
  30670. ** To work around this, if the journal file does appear to contain
  30671. ** a valid header following Pager.journalOff, then write a 0x00
  30672. ** byte to the start of it to prevent it from being recognized.
  30673. **
  30674. ** Variable iNextHdrOffset is set to the offset at which this
  30675. ** problematic header will occur, if it exists. aMagic is used
  30676. ** as a temporary buffer to inspect the first couple of bytes of
  30677. ** the potential journal header.
  30678. */
  30679. i64 iNextHdrOffset = journalHdrOffset(pPager);
  30680. u8 aMagic[8];
  30681. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  30682. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  30683. static const u8 zerobyte = 0;
  30684. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  30685. }
  30686. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  30687. return rc;
  30688. }
  30689. /* Write the nRec value into the journal file header. If in
  30690. ** full-synchronous mode, sync the journal first. This ensures that
  30691. ** all data has really hit the disk before nRec is updated to mark
  30692. ** it as a candidate for rollback.
  30693. **
  30694. ** This is not required if the persistent media supports the
  30695. ** SAFE_APPEND property. Because in this case it is not possible
  30696. ** for garbage data to be appended to the file, the nRec field
  30697. ** is populated with 0xFFFFFFFF when the journal header is written
  30698. ** and never needs to be updated.
  30699. */
  30700. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  30701. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  30702. IOTRACE(("JSYNC %p\n", pPager))
  30703. rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
  30704. if( rc!=SQLITE_OK ) return rc;
  30705. }
  30706. IOTRACE(("JHDR %p %lld %d\n", pPager, iNRecOffset, 4));
  30707. rc = write32bits(pPager->jfd, iNRecOffset, pPager->nRec);
  30708. if( rc!=SQLITE_OK ) return rc;
  30709. }
  30710. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  30711. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  30712. IOTRACE(("JSYNC %p\n", pPager))
  30713. rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
  30714. (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  30715. );
  30716. if( rc!=SQLITE_OK ) return rc;
  30717. }
  30718. }
  30719. /* The journal file was just successfully synced. Set Pager.needSync
  30720. ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
  30721. */
  30722. pPager->needSync = 0;
  30723. pPager->journalStarted = 1;
  30724. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  30725. }
  30726. return SQLITE_OK;
  30727. }
  30728. /*
  30729. ** The argument is the first in a linked list of dirty pages connected
  30730. ** by the PgHdr.pDirty pointer. This function writes each one of the
  30731. ** in-memory pages in the list to the database file. The argument may
  30732. ** be NULL, representing an empty list. In this case this function is
  30733. ** a no-op.
  30734. **
  30735. ** The pager must hold at least a RESERVED lock when this function
  30736. ** is called. Before writing anything to the database file, this lock
  30737. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  30738. ** SQLITE_BUSY is returned and no data is written to the database file.
  30739. **
  30740. ** If the pager is a temp-file pager and the actual file-system file
  30741. ** is not yet open, it is created and opened before any data is
  30742. ** written out.
  30743. **
  30744. ** Once the lock has been upgraded and, if necessary, the file opened,
  30745. ** the pages are written out to the database file in list order. Writing
  30746. ** a page is skipped if it meets either of the following criteria:
  30747. **
  30748. ** * The page number is greater than Pager.dbSize, or
  30749. ** * The PGHDR_DONT_WRITE flag is set on the page.
  30750. **
  30751. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  30752. ** is updated accordingly. If page 1 is written out, then the value cached
  30753. ** in Pager.dbFileVers[] is updated to match the new value stored in
  30754. ** the database file.
  30755. **
  30756. ** If everything is successful, SQLITE_OK is returned. If an IO error
  30757. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  30758. ** be obtained, SQLITE_BUSY is returned.
  30759. */
  30760. static int pager_write_pagelist(PgHdr *pList){
  30761. Pager *pPager; /* Pager object */
  30762. int rc; /* Return code */
  30763. if( pList==0 ) return SQLITE_OK;
  30764. pPager = pList->pPager;
  30765. /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
  30766. ** database file. If there is already an EXCLUSIVE lock, the following
  30767. ** call is a no-op.
  30768. **
  30769. ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
  30770. ** through an intermediate state PENDING. A PENDING lock prevents new
  30771. ** readers from attaching to the database but is unsufficient for us to
  30772. ** write. The idea of a PENDING lock is to prevent new readers from
  30773. ** coming in while we wait for existing readers to clear.
  30774. **
  30775. ** While the pager is in the RESERVED state, the original database file
  30776. ** is unchanged and we can rollback without having to playback the
  30777. ** journal into the original database file. Once we transition to
  30778. ** EXCLUSIVE, it means the database file has been changed and any rollback
  30779. ** will require a journal playback.
  30780. */
  30781. assert( pPager->state>=PAGER_RESERVED );
  30782. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  30783. /* If the file is a temp-file has not yet been opened, open it now. It
  30784. ** is not possible for rc to be other than SQLITE_OK if this branch
  30785. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  30786. */
  30787. if( !isOpen(pPager->fd) ){
  30788. assert( pPager->tempFile && rc==SQLITE_OK );
  30789. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  30790. }
  30791. while( rc==SQLITE_OK && pList ){
  30792. Pgno pgno = pList->pgno;
  30793. /* If there are dirty pages in the page cache with page numbers greater
  30794. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  30795. ** make the file smaller (presumably by auto-vacuum code). Do not write
  30796. ** any such pages to the file.
  30797. **
  30798. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  30799. ** set (set by sqlite3PagerDontWrite()).
  30800. */
  30801. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  30802. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  30803. char *pData = CODEC2(pPager, pList->pData, pgno, 6); /* Data to write */
  30804. /* Write out the page data. */
  30805. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  30806. /* If page 1 was just written, update Pager.dbFileVers to match
  30807. ** the value now stored in the database file. If writing this
  30808. ** page caused the database file to grow, update dbFileSize.
  30809. */
  30810. if( pgno==1 ){
  30811. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  30812. }
  30813. if( pgno>pPager->dbFileSize ){
  30814. pPager->dbFileSize = pgno;
  30815. }
  30816. /* Update any backup objects copying the contents of this pager. */
  30817. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8 *)pData);
  30818. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  30819. PAGERID(pPager), pgno, pager_pagehash(pList)));
  30820. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  30821. PAGER_INCR(sqlite3_pager_writedb_count);
  30822. PAGER_INCR(pPager->nWrite);
  30823. }else{
  30824. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  30825. }
  30826. #ifdef SQLITE_CHECK_PAGES
  30827. pList->pageHash = pager_pagehash(pList);
  30828. #endif
  30829. pList = pList->pDirty;
  30830. }
  30831. return rc;
  30832. }
  30833. /*
  30834. ** Append a record of the current state of page pPg to the sub-journal.
  30835. ** It is the callers responsibility to use subjRequiresPage() to check
  30836. ** that it is really required before calling this function.
  30837. **
  30838. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  30839. ** for all open savepoints before returning.
  30840. **
  30841. ** This function returns SQLITE_OK if everything is successful, an IO
  30842. ** error code if the attempt to write to the sub-journal fails, or
  30843. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  30844. ** bitvec.
  30845. */
  30846. static int subjournalPage(PgHdr *pPg){
  30847. int rc = SQLITE_OK;
  30848. Pager *pPager = pPg->pPager;
  30849. if( isOpen(pPager->sjfd) ){
  30850. void *pData = pPg->pData;
  30851. i64 offset = pPager->nSubRec*(4+pPager->pageSize);
  30852. char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
  30853. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  30854. assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  30855. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  30856. if( rc==SQLITE_OK ){
  30857. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  30858. }
  30859. }
  30860. if( rc==SQLITE_OK ){
  30861. pPager->nSubRec++;
  30862. assert( pPager->nSavepoint>0 );
  30863. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  30864. testcase( rc!=SQLITE_OK );
  30865. }
  30866. return rc;
  30867. }
  30868. /*
  30869. ** This function is called by the pcache layer when it has reached some
  30870. ** soft memory limit. The first argument is a pointer to a Pager object
  30871. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  30872. ** database). The second argument is a reference to a page that is
  30873. ** currently dirty but has no outstanding references. The page
  30874. ** is always associated with the Pager object passed as the first
  30875. ** argument.
  30876. **
  30877. ** The job of this function is to make pPg clean by writing its contents
  30878. ** out to the database file, if possible. This may involve syncing the
  30879. ** journal file.
  30880. **
  30881. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  30882. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  30883. ** page clean, the IO error code is returned. If the page cannot be
  30884. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  30885. ** is returned by sqlite3PcacheMakeClean() is not called.
  30886. */
  30887. static int pagerStress(void *p, PgHdr *pPg){
  30888. Pager *pPager = (Pager *)p;
  30889. int rc = SQLITE_OK;
  30890. assert( pPg->pPager==pPager );
  30891. assert( pPg->flags&PGHDR_DIRTY );
  30892. /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
  30893. ** is journalling a set of two or more database pages that are stored
  30894. ** on the same disk sector. Syncing the journal is not allowed while
  30895. ** this is happening as it is important that all members of such a
  30896. ** set of pages are synced to disk together. So, if the page this function
  30897. ** is trying to make clean will require a journal sync and the doNotSync
  30898. ** flag is set, return without doing anything. The pcache layer will
  30899. ** just have to go ahead and allocate a new page buffer instead of
  30900. ** reusing pPg.
  30901. **
  30902. ** Similarly, if the pager has already entered the error state, do not
  30903. ** try to write the contents of pPg to disk.
  30904. */
  30905. if( pPager->errCode || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC) ){
  30906. return SQLITE_OK;
  30907. }
  30908. /* Sync the journal file if required. */
  30909. if( pPg->flags&PGHDR_NEED_SYNC ){
  30910. rc = syncJournal(pPager);
  30911. if( rc==SQLITE_OK && pPager->fullSync &&
  30912. !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
  30913. !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  30914. ){
  30915. pPager->nRec = 0;
  30916. rc = writeJournalHdr(pPager);
  30917. }
  30918. }
  30919. /* If the page number of this page is larger than the current size of
  30920. ** the database image, it may need to be written to the sub-journal.
  30921. ** This is because the call to pager_write_pagelist() below will not
  30922. ** actually write data to the file in this case.
  30923. **
  30924. ** Consider the following sequence of events:
  30925. **
  30926. ** BEGIN;
  30927. ** <journal page X>
  30928. ** <modify page X>
  30929. ** SAVEPOINT sp;
  30930. ** <shrink database file to Y pages>
  30931. ** pagerStress(page X)
  30932. ** ROLLBACK TO sp;
  30933. **
  30934. ** If (X>Y), then when pagerStress is called page X will not be written
  30935. ** out to the database file, but will be dropped from the cache. Then,
  30936. ** following the "ROLLBACK TO sp" statement, reading page X will read
  30937. ** data from the database file. This will be the copy of page X as it
  30938. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  30939. ** was executed.
  30940. **
  30941. ** The solution is to write the current data for page X into the
  30942. ** sub-journal file now (if it is not already there), so that it will
  30943. ** be restored to its current value when the "ROLLBACK TO sp" is
  30944. ** executed.
  30945. */
  30946. if( rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) ){
  30947. rc = subjournalPage(pPg);
  30948. }
  30949. /* Write the contents of the page out to the database file. */
  30950. if( rc==SQLITE_OK ){
  30951. pPg->pDirty = 0;
  30952. rc = pager_write_pagelist(pPg);
  30953. }
  30954. /* Mark the page as clean. */
  30955. if( rc==SQLITE_OK ){
  30956. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  30957. sqlite3PcacheMakeClean(pPg);
  30958. }
  30959. return pager_error(pPager, rc);
  30960. }
  30961. /*
  30962. ** Allocate and initialize a new Pager object and put a pointer to it
  30963. ** in *ppPager. The pager should eventually be freed by passing it
  30964. ** to sqlite3PagerClose().
  30965. **
  30966. ** The zFilename argument is the path to the database file to open.
  30967. ** If zFilename is NULL then a randomly-named temporary file is created
  30968. ** and used as the file to be cached. Temporary files are be deleted
  30969. ** automatically when they are closed. If zFilename is ":memory:" then
  30970. ** all information is held in cache. It is never written to disk.
  30971. ** This can be used to implement an in-memory database.
  30972. **
  30973. ** The nExtra parameter specifies the number of bytes of space allocated
  30974. ** along with each page reference. This space is available to the user
  30975. ** via the sqlite3PagerGetExtra() API.
  30976. **
  30977. ** The flags argument is used to specify properties that affect the
  30978. ** operation of the pager. It should be passed some bitwise combination
  30979. ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
  30980. **
  30981. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  30982. ** of the xOpen() method of the supplied VFS when opening files.
  30983. **
  30984. ** If the pager object is allocated and the specified file opened
  30985. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  30986. ** the new pager object. If an error occurs, *ppPager is set to NULL
  30987. ** and error code returned. This function may return SQLITE_NOMEM
  30988. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  30989. ** various SQLITE_IO_XXX errors.
  30990. */
  30991. SQLITE_PRIVATE int sqlite3PagerOpen(
  30992. sqlite3_vfs *pVfs, /* The virtual file system to use */
  30993. Pager **ppPager, /* OUT: Return the Pager structure here */
  30994. const char *zFilename, /* Name of the database file to open */
  30995. int nExtra, /* Extra bytes append to each in-memory page */
  30996. int flags, /* flags controlling this file */
  30997. int vfsFlags /* flags passed through to sqlite3_vfs.xOpen() */
  30998. ){
  30999. u8 *pPtr;
  31000. Pager *pPager = 0; /* Pager object to allocate and return */
  31001. int rc = SQLITE_OK; /* Return code */
  31002. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  31003. int memDb = 0; /* True if this is an in-memory file */
  31004. int readOnly = 0; /* True if this is a read-only file */
  31005. int journalFileSize; /* Bytes to allocate for each journal fd */
  31006. char *zPathname = 0; /* Full path to database file */
  31007. int nPathname = 0; /* Number of bytes in zPathname */
  31008. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  31009. int noReadlock = (flags & PAGER_NO_READLOCK)!=0; /* True to omit read-lock */
  31010. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  31011. u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  31012. /* Figure out how much space is required for each journal file-handle
  31013. ** (there are two of them, the main journal and the sub-journal). This
  31014. ** is the maximum space required for an in-memory journal file handle
  31015. ** and a regular journal file-handle. Note that a "regular journal-handle"
  31016. ** may be a wrapper capable of caching the first portion of the journal
  31017. ** file in memory to implement the atomic-write optimization (see
  31018. ** source file journal.c).
  31019. */
  31020. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  31021. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  31022. }else{
  31023. journalFileSize = ROUND8(sqlite3MemJournalSize());
  31024. }
  31025. /* Set the output variable to NULL in case an error occurs. */
  31026. *ppPager = 0;
  31027. /* Compute and store the full pathname in an allocated buffer pointed
  31028. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  31029. ** leave both nPathname and zPathname set to 0.
  31030. */
  31031. if( zFilename && zFilename[0] ){
  31032. nPathname = pVfs->mxPathname+1;
  31033. zPathname = sqlite3Malloc(nPathname*2);
  31034. if( zPathname==0 ){
  31035. return SQLITE_NOMEM;
  31036. }
  31037. #ifndef SQLITE_OMIT_MEMORYDB
  31038. if( strcmp(zFilename,":memory:")==0 ){
  31039. memDb = 1;
  31040. zPathname[0] = 0;
  31041. }else
  31042. #endif
  31043. {
  31044. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  31045. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  31046. }
  31047. nPathname = sqlite3Strlen30(zPathname);
  31048. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  31049. /* This branch is taken when the journal path required by
  31050. ** the database being opened will be more than pVfs->mxPathname
  31051. ** bytes in length. This means the database cannot be opened,
  31052. ** as it will not be possible to open the journal file or even
  31053. ** check for a hot-journal before reading.
  31054. */
  31055. rc = SQLITE_CANTOPEN;
  31056. }
  31057. if( rc!=SQLITE_OK ){
  31058. sqlite3_free(zPathname);
  31059. return rc;
  31060. }
  31061. }
  31062. /* Allocate memory for the Pager structure, PCache object, the
  31063. ** three file descriptors, the database file name and the journal
  31064. ** file name. The layout in memory is as follows:
  31065. **
  31066. ** Pager object (sizeof(Pager) bytes)
  31067. ** PCache object (sqlite3PcacheSize() bytes)
  31068. ** Database file handle (pVfs->szOsFile bytes)
  31069. ** Sub-journal file handle (journalFileSize bytes)
  31070. ** Main journal file handle (journalFileSize bytes)
  31071. ** Database file name (nPathname+1 bytes)
  31072. ** Journal file name (nPathname+8+1 bytes)
  31073. */
  31074. pPtr = (u8 *)sqlite3MallocZero(
  31075. ROUND8(sizeof(*pPager)) + /* Pager structure */
  31076. ROUND8(pcacheSize) + /* PCache object */
  31077. ROUND8(pVfs->szOsFile) + /* The main db file */
  31078. journalFileSize * 2 + /* The two journal files */
  31079. nPathname + 1 + /* zFilename */
  31080. nPathname + 8 + 1 /* zJournal */
  31081. );
  31082. assert( EIGHT_BYTE_ALIGNMENT(journalFileSize) );
  31083. if( !pPtr ){
  31084. sqlite3_free(zPathname);
  31085. return SQLITE_NOMEM;
  31086. }
  31087. pPager = (Pager*)(pPtr);
  31088. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  31089. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  31090. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  31091. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  31092. pPager->zFilename = (char*)(pPtr += journalFileSize);
  31093. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  31094. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  31095. if( zPathname ){
  31096. pPager->zJournal = (char*)(pPtr += nPathname + 1);
  31097. memcpy(pPager->zFilename, zPathname, nPathname);
  31098. memcpy(pPager->zJournal, zPathname, nPathname);
  31099. memcpy(&pPager->zJournal[nPathname], "-journal", 8);
  31100. sqlite3_free(zPathname);
  31101. }
  31102. pPager->pVfs = pVfs;
  31103. pPager->vfsFlags = vfsFlags;
  31104. /* Open the pager file.
  31105. */
  31106. if( zFilename && zFilename[0] && !memDb ){
  31107. int fout = 0; /* VFS flags returned by xOpen() */
  31108. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  31109. readOnly = (fout&SQLITE_OPEN_READONLY);
  31110. /* If the file was successfully opened for read/write access,
  31111. ** choose a default page size in case we have to create the
  31112. ** database file. The default page size is the maximum of:
  31113. **
  31114. ** + SQLITE_DEFAULT_PAGE_SIZE,
  31115. ** + The value returned by sqlite3OsSectorSize()
  31116. ** + The largest page size that can be written atomically.
  31117. */
  31118. if( rc==SQLITE_OK && !readOnly ){
  31119. setSectorSize(pPager);
  31120. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  31121. if( szPageDflt<pPager->sectorSize ){
  31122. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  31123. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  31124. }else{
  31125. szPageDflt = (u16)pPager->sectorSize;
  31126. }
  31127. }
  31128. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31129. {
  31130. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  31131. int ii;
  31132. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  31133. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  31134. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  31135. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  31136. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  31137. szPageDflt = ii;
  31138. }
  31139. }
  31140. }
  31141. #endif
  31142. }
  31143. }else{
  31144. /* If a temporary file is requested, it is not opened immediately.
  31145. ** In this case we accept the default page size and delay actually
  31146. ** opening the file until the first call to OsWrite().
  31147. **
  31148. ** This branch is also run for an in-memory database. An in-memory
  31149. ** database is the same as a temp-file that is never written out to
  31150. ** disk and uses an in-memory rollback journal.
  31151. */
  31152. tempFile = 1;
  31153. pPager->state = PAGER_EXCLUSIVE;
  31154. }
  31155. /* The following call to PagerSetPagesize() serves to set the value of
  31156. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  31157. */
  31158. if( rc==SQLITE_OK ){
  31159. assert( pPager->memDb==0 );
  31160. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt);
  31161. testcase( rc!=SQLITE_OK );
  31162. }
  31163. /* If an error occurred in either of the blocks above, free the
  31164. ** Pager structure and close the file.
  31165. */
  31166. if( rc!=SQLITE_OK ){
  31167. assert( !pPager->pTmpSpace );
  31168. sqlite3OsClose(pPager->fd);
  31169. sqlite3_free(pPager);
  31170. return rc;
  31171. }
  31172. /* Initialize the PCache object. */
  31173. nExtra = ROUND8(nExtra);
  31174. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  31175. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  31176. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  31177. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  31178. pPager->useJournal = (u8)useJournal;
  31179. pPager->noReadlock = (noReadlock && readOnly) ?1:0;
  31180. /* pPager->stmtOpen = 0; */
  31181. /* pPager->stmtInUse = 0; */
  31182. /* pPager->nRef = 0; */
  31183. pPager->dbSizeValid = (u8)memDb;
  31184. /* pPager->stmtSize = 0; */
  31185. /* pPager->stmtJSize = 0; */
  31186. /* pPager->nPage = 0; */
  31187. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  31188. /* pPager->state = PAGER_UNLOCK; */
  31189. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  31190. /* pPager->errMask = 0; */
  31191. pPager->tempFile = (u8)tempFile;
  31192. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  31193. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  31194. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  31195. pPager->exclusiveMode = (u8)tempFile;
  31196. pPager->changeCountDone = pPager->tempFile;
  31197. pPager->memDb = (u8)memDb;
  31198. pPager->readOnly = (u8)readOnly;
  31199. /* pPager->needSync = 0; */
  31200. pPager->noSync = (pPager->tempFile || !useJournal) ?1:0;
  31201. pPager->fullSync = pPager->noSync ?0:1;
  31202. pPager->sync_flags = SQLITE_SYNC_NORMAL;
  31203. /* pPager->pFirst = 0; */
  31204. /* pPager->pFirstSynced = 0; */
  31205. /* pPager->pLast = 0; */
  31206. pPager->nExtra = nExtra;
  31207. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  31208. assert( isOpen(pPager->fd) || tempFile );
  31209. setSectorSize(pPager);
  31210. if( memDb ){
  31211. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  31212. }
  31213. /* pPager->xBusyHandler = 0; */
  31214. /* pPager->pBusyHandlerArg = 0; */
  31215. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  31216. *ppPager = pPager;
  31217. return SQLITE_OK;
  31218. }
  31219. /*
  31220. ** This function is called after transitioning from PAGER_UNLOCK to
  31221. ** PAGER_SHARED state. It tests if there is a hot journal present in
  31222. ** the file-system for the given pager. A hot journal is one that
  31223. ** needs to be played back. According to this function, a hot-journal
  31224. ** file exists if the following criteria are met:
  31225. **
  31226. ** * The journal file exists in the file system, and
  31227. ** * No process holds a RESERVED or greater lock on the database file, and
  31228. ** * The database file itself is greater than 0 bytes in size, and
  31229. ** * The first byte of the journal file exists and is not 0x00.
  31230. **
  31231. ** If the current size of the database file is 0 but a journal file
  31232. ** exists, that is probably an old journal left over from a prior
  31233. ** database with the same name. In this case the journal file is
  31234. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  31235. ** is returned.
  31236. **
  31237. ** This routine does not check if there is a master journal filename
  31238. ** at the end of the file. If there is, and that master journal file
  31239. ** does not exist, then the journal file is not really hot. In this
  31240. ** case this routine will return a false-positive. The pager_playback()
  31241. ** routine will discover that the journal file is not really hot and
  31242. ** will not roll it back.
  31243. **
  31244. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  31245. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  31246. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  31247. ** to determine whether or not a hot-journal file exists, the IO error
  31248. ** code is returned and the value of *pExists is undefined.
  31249. */
  31250. static int hasHotJournal(Pager *pPager, int *pExists){
  31251. sqlite3_vfs * const pVfs = pPager->pVfs;
  31252. int rc; /* Return code */
  31253. int exists; /* True if a journal file is present */
  31254. assert( pPager!=0 );
  31255. assert( pPager->useJournal );
  31256. assert( isOpen(pPager->fd) );
  31257. assert( !isOpen(pPager->jfd) );
  31258. *pExists = 0;
  31259. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  31260. if( rc==SQLITE_OK && exists ){
  31261. int locked; /* True if some process holds a RESERVED lock */
  31262. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  31263. if( rc==SQLITE_OK && !locked ){
  31264. int nPage;
  31265. /* Check the size of the database file. If it consists of 0 pages,
  31266. ** then delete the journal file. See the header comment above for
  31267. ** the reasoning here.
  31268. */
  31269. rc = sqlite3PagerPagecount(pPager, &nPage);
  31270. if( rc==SQLITE_OK ){
  31271. if( nPage==0 ){
  31272. rc = sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  31273. }else{
  31274. /* The journal file exists and no other connection has a reserved
  31275. ** or greater lock on the database file. Now check that there is
  31276. ** at least one non-zero bytes at the start of the journal file.
  31277. ** If there is, then we consider this journal to be hot. If not,
  31278. ** it can be ignored.
  31279. */
  31280. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  31281. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  31282. if( rc==SQLITE_OK ){
  31283. u8 first = 0;
  31284. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  31285. if( rc==SQLITE_IOERR_SHORT_READ ){
  31286. rc = SQLITE_OK;
  31287. }
  31288. sqlite3OsClose(pPager->jfd);
  31289. *pExists = (first!=0);
  31290. }
  31291. }
  31292. }
  31293. }
  31294. }
  31295. return rc;
  31296. }
  31297. /*
  31298. ** Read the content for page pPg out of the database file and into
  31299. ** pPg->pData. A shared lock or greater must be held on the database
  31300. ** file before this function is called.
  31301. **
  31302. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  31303. ** the value read from the database file.
  31304. **
  31305. ** If an IO error occurs, then the IO error is returned to the caller.
  31306. ** Otherwise, SQLITE_OK is returned.
  31307. */
  31308. static int readDbPage(PgHdr *pPg){
  31309. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  31310. Pgno pgno = pPg->pgno; /* Page number to read */
  31311. int rc; /* Return code */
  31312. i64 iOffset; /* Byte offset of file to read from */
  31313. assert( pPager->state>=PAGER_SHARED && !MEMDB );
  31314. if( !isOpen(pPager->fd) ){
  31315. assert( pPager->tempFile );
  31316. memset(pPg->pData, 0, pPager->pageSize);
  31317. return SQLITE_OK;
  31318. }
  31319. iOffset = (pgno-1)*(i64)pPager->pageSize;
  31320. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  31321. if( rc==SQLITE_IOERR_SHORT_READ ){
  31322. rc = SQLITE_OK;
  31323. }
  31324. if( pgno==1 ){
  31325. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  31326. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  31327. }
  31328. CODEC1(pPager, pPg->pData, pgno, 3);
  31329. PAGER_INCR(sqlite3_pager_readdb_count);
  31330. PAGER_INCR(pPager->nRead);
  31331. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  31332. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  31333. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  31334. return rc;
  31335. }
  31336. /*
  31337. ** This function is called whenever the upper layer requests a database
  31338. ** page is requested, before the cache is checked for a suitable page
  31339. ** or any data is read from the database. It performs the following
  31340. ** two functions:
  31341. **
  31342. ** 1) If the pager is currently in PAGER_UNLOCK state (no lock held
  31343. ** on the database file), then an attempt is made to obtain a
  31344. ** SHARED lock on the database file. Immediately after obtaining
  31345. ** the SHARED lock, the file-system is checked for a hot-journal,
  31346. ** which is played back if present. Following any hot-journal
  31347. ** rollback, the contents of the cache are validated by checking
  31348. ** the 'change-counter' field of the database file header and
  31349. ** discarded if they are found to be invalid.
  31350. **
  31351. ** 2) If the pager is running in exclusive-mode, and there are currently
  31352. ** no outstanding references to any pages, and is in the error state,
  31353. ** then an attempt is made to clear the error state by discarding
  31354. ** the contents of the page cache and rolling back any open journal
  31355. ** file.
  31356. **
  31357. ** If the operation described by (2) above is not attempted, and if the
  31358. ** pager is in an error state other than SQLITE_FULL when this is called,
  31359. ** the error state error code is returned. It is permitted to read the
  31360. ** database when in SQLITE_FULL error state.
  31361. **
  31362. ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
  31363. ** IO error occurs while locking the database, checking for a hot-journal
  31364. ** file or rolling back a journal file, the IO error code is returned.
  31365. */
  31366. static int pagerSharedLock(Pager *pPager){
  31367. int rc = SQLITE_OK; /* Return code */
  31368. int isErrorReset = 0; /* True if recovering from error state */
  31369. /* If this database is opened for exclusive access, has no outstanding
  31370. ** page references and is in an error-state, this is a chance to clear
  31371. ** the error. Discard the contents of the pager-cache and treat any
  31372. ** open journal file as a hot-journal.
  31373. */
  31374. if( !MEMDB && pPager->exclusiveMode
  31375. && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode
  31376. ){
  31377. if( isOpen(pPager->jfd) ){
  31378. isErrorReset = 1;
  31379. }
  31380. pPager->errCode = SQLITE_OK;
  31381. pager_reset(pPager);
  31382. }
  31383. /* If the pager is still in an error state, do not proceed. The error
  31384. ** state will be cleared at some point in the future when all page
  31385. ** references are dropped and the cache can be discarded.
  31386. */
  31387. if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
  31388. return pPager->errCode;
  31389. }
  31390. if( pPager->state==PAGER_UNLOCK || isErrorReset ){
  31391. sqlite3_vfs * const pVfs = pPager->pVfs;
  31392. int isHotJournal = 0;
  31393. assert( !MEMDB );
  31394. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  31395. if( !pPager->noReadlock ){
  31396. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  31397. if( rc!=SQLITE_OK ){
  31398. assert( pPager->state==PAGER_UNLOCK );
  31399. return pager_error(pPager, rc);
  31400. }
  31401. }else if( pPager->state==PAGER_UNLOCK ){
  31402. pPager->state = PAGER_SHARED;
  31403. }
  31404. assert( pPager->state>=SHARED_LOCK );
  31405. /* If a journal file exists, and there is no RESERVED lock on the
  31406. ** database file, then it either needs to be played back or deleted.
  31407. */
  31408. if( !isErrorReset ){
  31409. rc = hasHotJournal(pPager, &isHotJournal);
  31410. if( rc!=SQLITE_OK ){
  31411. goto failed;
  31412. }
  31413. }
  31414. if( isErrorReset || isHotJournal ){
  31415. /* Get an EXCLUSIVE lock on the database file. At this point it is
  31416. ** important that a RESERVED lock is not obtained on the way to the
  31417. ** EXCLUSIVE lock. If it were, another process might open the
  31418. ** database file, detect the RESERVED lock, and conclude that the
  31419. ** database is safe to read while this process is still rolling the
  31420. ** hot-journal back.
  31421. **
  31422. ** Because the intermediate RESERVED lock is not requested, any
  31423. ** other process attempting to access the database file will get to
  31424. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  31425. ** on the database file.
  31426. */
  31427. if( pPager->state<EXCLUSIVE_LOCK ){
  31428. rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
  31429. if( rc!=SQLITE_OK ){
  31430. rc = pager_error(pPager, rc);
  31431. goto failed;
  31432. }
  31433. pPager->state = PAGER_EXCLUSIVE;
  31434. }
  31435. /* Open the journal for read/write access. This is because in
  31436. ** exclusive-access mode the file descriptor will be kept open and
  31437. ** possibly used for a transaction later on. On some systems, the
  31438. ** OsTruncate() call used in exclusive-access mode also requires
  31439. ** a read/write file handle.
  31440. */
  31441. if( !isOpen(pPager->jfd) ){
  31442. int res;
  31443. rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
  31444. if( rc==SQLITE_OK ){
  31445. if( res ){
  31446. int fout = 0;
  31447. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  31448. assert( !pPager->tempFile );
  31449. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  31450. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  31451. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  31452. rc = SQLITE_CANTOPEN;
  31453. sqlite3OsClose(pPager->jfd);
  31454. }
  31455. }else{
  31456. /* If the journal does not exist, that means some other process
  31457. ** has already rolled it back */
  31458. rc = SQLITE_BUSY;
  31459. }
  31460. }
  31461. }
  31462. if( rc!=SQLITE_OK ){
  31463. goto failed;
  31464. }
  31465. /* TODO: Why are these cleared here? Is it necessary? */
  31466. pPager->journalStarted = 0;
  31467. pPager->journalOff = 0;
  31468. pPager->setMaster = 0;
  31469. pPager->journalHdr = 0;
  31470. /* Playback and delete the journal. Drop the database write
  31471. ** lock and reacquire the read lock. Purge the cache before
  31472. ** playing back the hot-journal so that we don't end up with
  31473. ** an inconsistent cache.
  31474. */
  31475. rc = pager_playback(pPager, 1);
  31476. if( rc!=SQLITE_OK ){
  31477. rc = pager_error(pPager, rc);
  31478. goto failed;
  31479. }
  31480. assert( (pPager->state==PAGER_SHARED)
  31481. || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
  31482. );
  31483. }
  31484. if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
  31485. /* The shared-lock has just been acquired on the database file
  31486. ** and there are already pages in the cache (from a previous
  31487. ** read or write transaction). Check to see if the database
  31488. ** has been modified. If the database has changed, flush the
  31489. ** cache.
  31490. **
  31491. ** Database changes is detected by looking at 15 bytes beginning
  31492. ** at offset 24 into the file. The first 4 of these 16 bytes are
  31493. ** a 32-bit counter that is incremented with each change. The
  31494. ** other bytes change randomly with each file change when
  31495. ** a codec is in use.
  31496. **
  31497. ** There is a vanishingly small chance that a change will not be
  31498. ** detected. The chance of an undetected change is so small that
  31499. ** it can be neglected.
  31500. */
  31501. char dbFileVers[sizeof(pPager->dbFileVers)];
  31502. sqlite3PagerPagecount(pPager, 0);
  31503. if( pPager->errCode ){
  31504. rc = pPager->errCode;
  31505. goto failed;
  31506. }
  31507. assert( pPager->dbSizeValid );
  31508. if( pPager->dbSize>0 ){
  31509. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  31510. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  31511. if( rc!=SQLITE_OK ){
  31512. goto failed;
  31513. }
  31514. }else{
  31515. memset(dbFileVers, 0, sizeof(dbFileVers));
  31516. }
  31517. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  31518. pager_reset(pPager);
  31519. }
  31520. }
  31521. assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
  31522. }
  31523. failed:
  31524. if( rc!=SQLITE_OK ){
  31525. /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
  31526. pager_unlock(pPager);
  31527. }
  31528. return rc;
  31529. }
  31530. /*
  31531. ** If the reference count has reached zero, rollback any active
  31532. ** transaction and unlock the pager.
  31533. */
  31534. static void pagerUnlockIfUnused(Pager *pPager){
  31535. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  31536. pagerUnlockAndRollback(pPager);
  31537. }
  31538. }
  31539. /*
  31540. ** Drop a page from the cache using sqlite3PcacheDrop().
  31541. **
  31542. ** If this means there are now no pages with references to them, a rollback
  31543. ** occurs and the lock on the database is removed.
  31544. */
  31545. static void pagerDropPage(DbPage *pPg){
  31546. Pager *pPager = pPg->pPager;
  31547. sqlite3PcacheDrop(pPg);
  31548. pagerUnlockIfUnused(pPager);
  31549. }
  31550. /*
  31551. ** Acquire a reference to page number pgno in pager pPager (a page
  31552. ** reference has type DbPage*). If the requested reference is
  31553. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  31554. **
  31555. ** This function calls pagerSharedLock() to obtain a SHARED lock on
  31556. ** the database file if such a lock or greater is not already held.
  31557. ** This may cause hot-journal rollback or a cache purge. See comments
  31558. ** above function pagerSharedLock() for details.
  31559. **
  31560. ** If the requested page is already in the cache, it is returned.
  31561. ** Otherwise, a new page object is allocated and populated with data
  31562. ** read from the database file. In some cases, the pcache module may
  31563. ** choose not to allocate a new page object and may reuse an existing
  31564. ** object with no outstanding references.
  31565. **
  31566. ** The extra data appended to a page is always initialized to zeros the
  31567. ** first time a page is loaded into memory. If the page requested is
  31568. ** already in the cache when this function is called, then the extra
  31569. ** data is left as it was when the page object was last used.
  31570. **
  31571. ** If the database image is smaller than the requested page or if a
  31572. ** non-zero value is passed as the noContent parameter and the
  31573. ** requested page is not already stored in the cache, then no
  31574. ** actual disk read occurs. In this case the memory image of the
  31575. ** page is initialized to all zeros.
  31576. **
  31577. ** If noContent is true, it means that we do not care about the contents
  31578. ** of the page. This occurs in two seperate scenarios:
  31579. **
  31580. ** a) When reading a free-list leaf page from the database, and
  31581. **
  31582. ** b) When a savepoint is being rolled back and we need to load
  31583. ** a new page into the cache to populate with the data read
  31584. ** from the savepoint journal.
  31585. **
  31586. ** If noContent is true, then the data returned is zeroed instead of
  31587. ** being read from the database. Additionally, the bits corresponding
  31588. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  31589. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  31590. ** savepoints are set. This means if the page is made writable at any
  31591. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  31592. ** will not be journaled. This saves IO.
  31593. **
  31594. ** The acquisition might fail for several reasons. In all cases,
  31595. ** an appropriate error code is returned and *ppPage is set to NULL.
  31596. **
  31597. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  31598. ** to find a page in the in-memory cache first. If the page is not already
  31599. ** in memory, this routine goes to disk to read it in whereas Lookup()
  31600. ** just returns 0. This routine acquires a read-lock the first time it
  31601. ** has to go to disk, and could also playback an old journal if necessary.
  31602. ** Since Lookup() never goes to disk, it never has to deal with locks
  31603. ** or journal files.
  31604. */
  31605. SQLITE_PRIVATE int sqlite3PagerAcquire(
  31606. Pager *pPager, /* The pager open on the database file */
  31607. Pgno pgno, /* Page number to fetch */
  31608. DbPage **ppPage, /* Write a pointer to the page here */
  31609. int noContent /* Do not bother reading content from disk if true */
  31610. ){
  31611. PgHdr *pPg = 0;
  31612. int rc;
  31613. assert( assert_pager_state(pPager) );
  31614. assert( pPager->state==PAGER_UNLOCK
  31615. || sqlite3PcacheRefCount(pPager->pPCache)>0
  31616. || pgno==1
  31617. );
  31618. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  31619. ** number greater than this, or zero, is requested.
  31620. */
  31621. if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  31622. return SQLITE_CORRUPT_BKPT;
  31623. }
  31624. /* Make sure we have not hit any critical errors.
  31625. */
  31626. assert( pPager!=0 );
  31627. *ppPage = 0;
  31628. /* If this is the first page accessed, then get a SHARED lock
  31629. ** on the database file. pagerSharedLock() is a no-op if
  31630. ** a database lock is already held.
  31631. */
  31632. rc = pagerSharedLock(pPager);
  31633. if( rc!=SQLITE_OK ){
  31634. return rc;
  31635. }
  31636. assert( pPager->state!=PAGER_UNLOCK );
  31637. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
  31638. if( rc!=SQLITE_OK ){
  31639. return rc;
  31640. }
  31641. assert( pPg->pgno==pgno );
  31642. assert( pPg->pPager==pPager || pPg->pPager==0 );
  31643. if( pPg->pPager==0 ){
  31644. /* The pager cache has created a new page. Its content needs to
  31645. ** be initialized.
  31646. */
  31647. int nMax;
  31648. PAGER_INCR(pPager->nMiss);
  31649. pPg->pPager = pPager;
  31650. rc = sqlite3PagerPagecount(pPager, &nMax);
  31651. if( rc!=SQLITE_OK ){
  31652. sqlite3PagerUnref(pPg);
  31653. return rc;
  31654. }
  31655. if( nMax<(int)pgno || MEMDB || noContent ){
  31656. if( pgno>pPager->mxPgno ){
  31657. sqlite3PagerUnref(pPg);
  31658. return SQLITE_FULL;
  31659. }
  31660. if( noContent ){
  31661. /* Failure to set the bits in the InJournal bit-vectors is benign.
  31662. ** It merely means that we might do some extra work to journal a
  31663. ** page that does not need to be journaled. Nevertheless, be sure
  31664. ** to test the case where a malloc error occurs while trying to set
  31665. ** a bit in a bit vector.
  31666. */
  31667. sqlite3BeginBenignMalloc();
  31668. if( pgno<=pPager->dbOrigSize ){
  31669. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  31670. testcase( rc==SQLITE_NOMEM );
  31671. }
  31672. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  31673. testcase( rc==SQLITE_NOMEM );
  31674. sqlite3EndBenignMalloc();
  31675. }else{
  31676. memset(pPg->pData, 0, pPager->pageSize);
  31677. }
  31678. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  31679. }else{
  31680. assert( pPg->pPager==pPager );
  31681. rc = readDbPage(pPg);
  31682. if( rc!=SQLITE_OK ){
  31683. pagerDropPage(pPg);
  31684. return rc;
  31685. }
  31686. }
  31687. #ifdef SQLITE_CHECK_PAGES
  31688. pPg->pageHash = pager_pagehash(pPg);
  31689. #endif
  31690. }else{
  31691. /* The requested page is in the page cache. */
  31692. PAGER_INCR(pPager->nHit);
  31693. }
  31694. *ppPage = pPg;
  31695. return SQLITE_OK;
  31696. }
  31697. /*
  31698. ** Acquire a page if it is already in the in-memory cache. Do
  31699. ** not read the page from disk. Return a pointer to the page,
  31700. ** or 0 if the page is not in cache. Also, return 0 if the
  31701. ** pager is in PAGER_UNLOCK state when this function is called,
  31702. ** or if the pager is in an error state other than SQLITE_FULL.
  31703. **
  31704. ** See also sqlite3PagerGet(). The difference between this routine
  31705. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  31706. ** in the page if the page is not already in cache. This routine
  31707. ** returns NULL if the page is not in cache or if a disk I/O error
  31708. ** has ever happened.
  31709. */
  31710. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  31711. PgHdr *pPg = 0;
  31712. assert( pPager!=0 );
  31713. assert( pgno!=0 );
  31714. if( (pPager->state!=PAGER_UNLOCK)
  31715. && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
  31716. ){
  31717. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  31718. }
  31719. return pPg;
  31720. }
  31721. /*
  31722. ** Release a page reference.
  31723. **
  31724. ** If the number of references to the page drop to zero, then the
  31725. ** page is added to the LRU list. When all references to all pages
  31726. ** are released, a rollback occurs and the lock on the database is
  31727. ** removed.
  31728. */
  31729. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  31730. if( pPg ){
  31731. Pager *pPager = pPg->pPager;
  31732. sqlite3PcacheRelease(pPg);
  31733. pagerUnlockIfUnused(pPager);
  31734. }
  31735. }
  31736. /*
  31737. ** If the main journal file has already been opened, ensure that the
  31738. ** sub-journal file is open too. If the main journal is not open,
  31739. ** this function is a no-op.
  31740. **
  31741. ** SQLITE_OK is returned if everything goes according to plan.
  31742. ** An SQLITE_IOERR_XXX error code is returned if a call to
  31743. ** sqlite3OsOpen() fails.
  31744. */
  31745. static int openSubJournal(Pager *pPager){
  31746. int rc = SQLITE_OK;
  31747. if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
  31748. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  31749. sqlite3MemJournalOpen(pPager->sjfd);
  31750. }else{
  31751. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  31752. }
  31753. }
  31754. return rc;
  31755. }
  31756. /*
  31757. ** This function is called at the start of every write transaction.
  31758. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  31759. ** file when this routine is called.
  31760. **
  31761. ** Open the journal file for pager pPager and write a journal header
  31762. ** to the start of it. If there are active savepoints, open the sub-journal
  31763. ** as well. This function is only used when the journal file is being
  31764. ** opened to write a rollback log for a transaction. It is not used
  31765. ** when opening a hot journal file to roll it back.
  31766. **
  31767. ** If the journal file is already open (as it may be in exclusive mode),
  31768. ** then this function just writes a journal header to the start of the
  31769. ** already open file.
  31770. **
  31771. ** Whether or not the journal file is opened by this function, the
  31772. ** Pager.pInJournal bitvec structure is allocated.
  31773. **
  31774. ** Return SQLITE_OK if everything is successful. Otherwise, return
  31775. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  31776. ** an IO error code if opening or writing the journal file fails.
  31777. */
  31778. static int pager_open_journal(Pager *pPager){
  31779. int rc = SQLITE_OK; /* Return code */
  31780. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  31781. assert( pPager->state>=PAGER_RESERVED );
  31782. assert( pPager->useJournal );
  31783. assert( pPager->pInJournal==0 );
  31784. /* If already in the error state, this function is a no-op. */
  31785. if( pPager->errCode ){
  31786. return pPager->errCode;
  31787. }
  31788. /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
  31789. ** the call to PagerPagecount() can be removed.
  31790. */
  31791. testcase( pPager->dbSizeValid==0 );
  31792. sqlite3PagerPagecount(pPager, 0);
  31793. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  31794. if( pPager->pInJournal==0 ){
  31795. return SQLITE_NOMEM;
  31796. }
  31797. /* Open the journal file if it is not already open. */
  31798. if( !isOpen(pPager->jfd) ){
  31799. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  31800. sqlite3MemJournalOpen(pPager->jfd);
  31801. }else{
  31802. const int flags = /* VFS flags to open journal file */
  31803. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  31804. (pPager->tempFile ?
  31805. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  31806. (SQLITE_OPEN_MAIN_JOURNAL)
  31807. );
  31808. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31809. rc = sqlite3JournalOpen(
  31810. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  31811. );
  31812. #else
  31813. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  31814. #endif
  31815. }
  31816. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  31817. }
  31818. /* Write the first journal header to the journal file and open
  31819. ** the sub-journal if necessary.
  31820. */
  31821. if( rc==SQLITE_OK ){
  31822. /* TODO: Check if all of these are really required. */
  31823. pPager->dbOrigSize = pPager->dbSize;
  31824. pPager->journalStarted = 0;
  31825. pPager->needSync = 0;
  31826. pPager->nRec = 0;
  31827. pPager->journalOff = 0;
  31828. pPager->setMaster = 0;
  31829. pPager->journalHdr = 0;
  31830. rc = writeJournalHdr(pPager);
  31831. }
  31832. if( rc==SQLITE_OK && pPager->nSavepoint ){
  31833. rc = openSubJournal(pPager);
  31834. }
  31835. if( rc!=SQLITE_OK ){
  31836. sqlite3BitvecDestroy(pPager->pInJournal);
  31837. pPager->pInJournal = 0;
  31838. }
  31839. return rc;
  31840. }
  31841. /*
  31842. ** Begin a write-transaction on the specified pager object. If a
  31843. ** write-transaction has already been opened, this function is a no-op.
  31844. **
  31845. ** If the exFlag argument is false, then acquire at least a RESERVED
  31846. ** lock on the database file. If exFlag is true, then acquire at least
  31847. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  31848. ** functions need be called.
  31849. **
  31850. ** If this is not a temporary or in-memory file and, the journal file is
  31851. ** opened if it has not been already. For a temporary file, the opening
  31852. ** of the journal file is deferred until there is an actual need to
  31853. ** write to the journal. TODO: Why handle temporary files differently?
  31854. **
  31855. ** If the journal file is opened (or if it is already open), then a
  31856. ** journal-header is written to the start of it.
  31857. */
  31858. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag){
  31859. int rc = SQLITE_OK;
  31860. assert( pPager->state!=PAGER_UNLOCK );
  31861. if( pPager->state==PAGER_SHARED ){
  31862. assert( pPager->pInJournal==0 );
  31863. assert( !MEMDB && !pPager->tempFile );
  31864. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  31865. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  31866. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  31867. ** lock, but not when obtaining the RESERVED lock.
  31868. */
  31869. rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
  31870. if( rc==SQLITE_OK ){
  31871. pPager->state = PAGER_RESERVED;
  31872. if( exFlag ){
  31873. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  31874. }
  31875. }
  31876. /* If the required locks were successfully obtained, open the journal
  31877. ** file and write the first journal-header to it.
  31878. */
  31879. if( rc==SQLITE_OK && pPager->useJournal
  31880. && pPager->journalMode!=PAGER_JOURNALMODE_OFF
  31881. ){
  31882. rc = pager_open_journal(pPager);
  31883. }
  31884. }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
  31885. /* This happens when the pager was in exclusive-access mode the last
  31886. ** time a (read or write) transaction was successfully concluded
  31887. ** by this connection. Instead of deleting the journal file it was
  31888. ** kept open and either was truncated to 0 bytes or its header was
  31889. ** overwritten with zeros.
  31890. */
  31891. assert( pPager->nRec==0 );
  31892. assert( pPager->dbOrigSize==0 );
  31893. assert( pPager->pInJournal==0 );
  31894. rc = pager_open_journal(pPager);
  31895. }
  31896. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  31897. assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
  31898. return rc;
  31899. }
  31900. /*
  31901. ** Mark a single data page as writeable. The page is written into the
  31902. ** main journal or sub-journal as required. If the page is written into
  31903. ** one of the journals, the corresponding bit is set in the
  31904. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  31905. ** of any open savepoints as appropriate.
  31906. */
  31907. static int pager_write(PgHdr *pPg){
  31908. void *pData = pPg->pData;
  31909. Pager *pPager = pPg->pPager;
  31910. int rc = SQLITE_OK;
  31911. /* Check for errors
  31912. */
  31913. if( pPager->errCode ){
  31914. return pPager->errCode;
  31915. }
  31916. if( pPager->readOnly ){
  31917. return SQLITE_PERM;
  31918. }
  31919. assert( !pPager->setMaster );
  31920. CHECK_PAGE(pPg);
  31921. /* Mark the page as dirty. If the page has already been written
  31922. ** to the journal then we can return right away.
  31923. */
  31924. sqlite3PcacheMakeDirty(pPg);
  31925. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  31926. pPager->dbModified = 1;
  31927. }else{
  31928. /* If we get this far, it means that the page needs to be
  31929. ** written to the transaction journal or the ckeckpoint journal
  31930. ** or both.
  31931. **
  31932. ** First check to see that the transaction journal exists and
  31933. ** create it if it does not.
  31934. */
  31935. assert( pPager->state!=PAGER_UNLOCK );
  31936. rc = sqlite3PagerBegin(pPager, 0);
  31937. if( rc!=SQLITE_OK ){
  31938. return rc;
  31939. }
  31940. assert( pPager->state>=PAGER_RESERVED );
  31941. if( !isOpen(pPager->jfd) && pPager->useJournal
  31942. && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  31943. rc = pager_open_journal(pPager);
  31944. if( rc!=SQLITE_OK ) return rc;
  31945. }
  31946. pPager->dbModified = 1;
  31947. /* The transaction journal now exists and we have a RESERVED or an
  31948. ** EXCLUSIVE lock on the main database file. Write the current page to
  31949. ** the transaction journal if it is not there already.
  31950. */
  31951. if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
  31952. if( pPg->pgno<=pPager->dbOrigSize ){
  31953. u32 cksum;
  31954. char *pData2;
  31955. /* We should never write to the journal file the page that
  31956. ** contains the database locks. The following assert verifies
  31957. ** that we do not. */
  31958. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  31959. pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
  31960. cksum = pager_cksum(pPager, (u8*)pData2);
  31961. rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
  31962. if( rc==SQLITE_OK ){
  31963. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
  31964. pPager->journalOff + 4);
  31965. pPager->journalOff += pPager->pageSize+4;
  31966. }
  31967. if( rc==SQLITE_OK ){
  31968. rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
  31969. pPager->journalOff += 4;
  31970. }
  31971. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  31972. pPager->journalOff, pPager->pageSize));
  31973. PAGER_INCR(sqlite3_pager_writej_count);
  31974. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  31975. PAGERID(pPager), pPg->pgno,
  31976. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  31977. /* Even if an IO or diskfull error occurred while journalling the
  31978. ** page in the block above, set the need-sync flag for the page.
  31979. ** Otherwise, when the transaction is rolled back, the logic in
  31980. ** playback_one_page() will think that the page needs to be restored
  31981. ** in the database file. And if an IO error occurs while doing so,
  31982. ** then corruption may follow.
  31983. */
  31984. if( !pPager->noSync ){
  31985. pPg->flags |= PGHDR_NEED_SYNC;
  31986. pPager->needSync = 1;
  31987. }
  31988. /* An error has occurred writing to the journal file. The
  31989. ** transaction will be rolled back by the layer above.
  31990. */
  31991. if( rc!=SQLITE_OK ){
  31992. return rc;
  31993. }
  31994. pPager->nRec++;
  31995. assert( pPager->pInJournal!=0 );
  31996. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  31997. testcase( rc==SQLITE_NOMEM );
  31998. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  31999. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  32000. if( rc!=SQLITE_OK ){
  32001. assert( rc==SQLITE_NOMEM );
  32002. return rc;
  32003. }
  32004. }else{
  32005. if( !pPager->journalStarted && !pPager->noSync ){
  32006. pPg->flags |= PGHDR_NEED_SYNC;
  32007. pPager->needSync = 1;
  32008. }
  32009. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  32010. PAGERID(pPager), pPg->pgno,
  32011. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  32012. }
  32013. }
  32014. /* If the statement journal is open and the page is not in it,
  32015. ** then write the current page to the statement journal. Note that
  32016. ** the statement journal format differs from the standard journal format
  32017. ** in that it omits the checksums and the header.
  32018. */
  32019. if( subjRequiresPage(pPg) ){
  32020. rc = subjournalPage(pPg);
  32021. }
  32022. }
  32023. /* Update the database size and return.
  32024. */
  32025. assert( pPager->state>=PAGER_SHARED );
  32026. if( pPager->dbSize<pPg->pgno ){
  32027. pPager->dbSize = pPg->pgno;
  32028. }
  32029. return rc;
  32030. }
  32031. /*
  32032. ** Mark a data page as writeable. This routine must be called before
  32033. ** making changes to a page. The caller must check the return value
  32034. ** of this function and be careful not to change any page data unless
  32035. ** this routine returns SQLITE_OK.
  32036. **
  32037. ** The difference between this function and pager_write() is that this
  32038. ** function also deals with the special case where 2 or more pages
  32039. ** fit on a single disk sector. In this case all co-resident pages
  32040. ** must have been written to the journal file before returning.
  32041. **
  32042. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  32043. ** as appropriate. Otherwise, SQLITE_OK.
  32044. */
  32045. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  32046. int rc = SQLITE_OK;
  32047. PgHdr *pPg = pDbPage;
  32048. Pager *pPager = pPg->pPager;
  32049. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  32050. if( nPagePerSector>1 ){
  32051. Pgno nPageCount; /* Total number of pages in database file */
  32052. Pgno pg1; /* First page of the sector pPg is located on. */
  32053. int nPage; /* Number of pages starting at pg1 to journal */
  32054. int ii; /* Loop counter */
  32055. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  32056. /* Set the doNotSync flag to 1. This is because we cannot allow a journal
  32057. ** header to be written between the pages journaled by this function.
  32058. */
  32059. assert( !MEMDB );
  32060. assert( pPager->doNotSync==0 );
  32061. pPager->doNotSync = 1;
  32062. /* This trick assumes that both the page-size and sector-size are
  32063. ** an integer power of 2. It sets variable pg1 to the identifier
  32064. ** of the first page of the sector pPg is located on.
  32065. */
  32066. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  32067. sqlite3PagerPagecount(pPager, (int *)&nPageCount);
  32068. if( pPg->pgno>nPageCount ){
  32069. nPage = (pPg->pgno - pg1)+1;
  32070. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  32071. nPage = nPageCount+1-pg1;
  32072. }else{
  32073. nPage = nPagePerSector;
  32074. }
  32075. assert(nPage>0);
  32076. assert(pg1<=pPg->pgno);
  32077. assert((pg1+nPage)>pPg->pgno);
  32078. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  32079. Pgno pg = pg1+ii;
  32080. PgHdr *pPage;
  32081. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  32082. if( pg!=PAGER_MJ_PGNO(pPager) ){
  32083. rc = sqlite3PagerGet(pPager, pg, &pPage);
  32084. if( rc==SQLITE_OK ){
  32085. rc = pager_write(pPage);
  32086. if( pPage->flags&PGHDR_NEED_SYNC ){
  32087. needSync = 1;
  32088. assert(pPager->needSync);
  32089. }
  32090. sqlite3PagerUnref(pPage);
  32091. }
  32092. }
  32093. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  32094. if( pPage->flags&PGHDR_NEED_SYNC ){
  32095. needSync = 1;
  32096. }
  32097. sqlite3PagerUnref(pPage);
  32098. }
  32099. }
  32100. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  32101. ** starting at pg1, then it needs to be set for all of them. Because
  32102. ** writing to any of these nPage pages may damage the others, the
  32103. ** journal file must contain sync()ed copies of all of them
  32104. ** before any of them can be written out to the database file.
  32105. */
  32106. if( needSync ){
  32107. assert( !MEMDB && pPager->noSync==0 );
  32108. for(ii=0; ii<nPage && needSync; ii++){
  32109. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  32110. if( pPage ){
  32111. pPage->flags |= PGHDR_NEED_SYNC;
  32112. sqlite3PagerUnref(pPage);
  32113. }
  32114. }
  32115. assert(pPager->needSync);
  32116. }
  32117. assert( pPager->doNotSync==1 );
  32118. pPager->doNotSync = 0;
  32119. }else{
  32120. rc = pager_write(pDbPage);
  32121. }
  32122. return rc;
  32123. }
  32124. /*
  32125. ** Return TRUE if the page given in the argument was previously passed
  32126. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  32127. ** to change the content of the page.
  32128. */
  32129. #ifndef NDEBUG
  32130. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  32131. return pPg->flags&PGHDR_DIRTY;
  32132. }
  32133. #endif
  32134. /*
  32135. ** A call to this routine tells the pager that it is not necessary to
  32136. ** write the information on page pPg back to the disk, even though
  32137. ** that page might be marked as dirty. This happens, for example, when
  32138. ** the page has been added as a leaf of the freelist and so its
  32139. ** content no longer matters.
  32140. **
  32141. ** The overlying software layer calls this routine when all of the data
  32142. ** on the given page is unused. The pager marks the page as clean so
  32143. ** that it does not get written to disk.
  32144. **
  32145. ** Tests show that this optimization can quadruple the speed of large
  32146. ** DELETE operations.
  32147. */
  32148. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  32149. Pager *pPager = pPg->pPager;
  32150. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  32151. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  32152. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  32153. pPg->flags |= PGHDR_DONT_WRITE;
  32154. #ifdef SQLITE_CHECK_PAGES
  32155. pPg->pageHash = pager_pagehash(pPg);
  32156. #endif
  32157. }
  32158. }
  32159. /*
  32160. ** This routine is called to increment the value of the database file
  32161. ** change-counter, stored as a 4-byte big-endian integer starting at
  32162. ** byte offset 24 of the pager file.
  32163. **
  32164. ** If the isDirect flag is zero, then this is done by calling
  32165. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  32166. ** page data. In this case the file will be updated when the current
  32167. ** transaction is committed.
  32168. **
  32169. ** The isDirect flag may only be non-zero if the library was compiled
  32170. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  32171. ** if isDirect is non-zero, then the database file is updated directly
  32172. ** by writing an updated version of page 1 using a call to the
  32173. ** sqlite3OsWrite() function.
  32174. */
  32175. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  32176. int rc = SQLITE_OK;
  32177. /* Declare and initialize constant integer 'isDirect'. If the
  32178. ** atomic-write optimization is enabled in this build, then isDirect
  32179. ** is initialized to the value passed as the isDirectMode parameter
  32180. ** to this function. Otherwise, it is always set to zero.
  32181. **
  32182. ** The idea is that if the atomic-write optimization is not
  32183. ** enabled at compile time, the compiler can omit the tests of
  32184. ** 'isDirect' below, as well as the block enclosed in the
  32185. ** "if( isDirect )" condition.
  32186. */
  32187. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  32188. const int isDirect = 0;
  32189. assert( isDirectMode==0 );
  32190. UNUSED_PARAMETER(isDirectMode);
  32191. #else
  32192. const int isDirect = isDirectMode;
  32193. #endif
  32194. assert( pPager->state>=PAGER_RESERVED );
  32195. if( !pPager->changeCountDone && pPager->dbSize>0 ){
  32196. PgHdr *pPgHdr; /* Reference to page 1 */
  32197. u32 change_counter; /* Initial value of change-counter field */
  32198. assert( !pPager->tempFile && isOpen(pPager->fd) );
  32199. /* Open page 1 of the file for writing. */
  32200. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  32201. assert( pPgHdr==0 || rc==SQLITE_OK );
  32202. /* If page one was fetched successfully, and this function is not
  32203. ** operating in direct-mode, make page 1 writable.
  32204. */
  32205. if( rc==SQLITE_OK && !isDirect ){
  32206. rc = sqlite3PagerWrite(pPgHdr);
  32207. }
  32208. if( rc==SQLITE_OK ){
  32209. /* Increment the value just read and write it back to byte 24. */
  32210. change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
  32211. change_counter++;
  32212. put32bits(((char*)pPgHdr->pData)+24, change_counter);
  32213. /* If running in direct mode, write the contents of page 1 to the file. */
  32214. if( isDirect ){
  32215. const void *zBuf = pPgHdr->pData;
  32216. assert( pPager->dbFileSize>0 );
  32217. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  32218. }
  32219. /* If everything worked, set the changeCountDone flag. */
  32220. if( rc==SQLITE_OK ){
  32221. pPager->changeCountDone = 1;
  32222. }
  32223. }
  32224. /* Release the page reference. */
  32225. sqlite3PagerUnref(pPgHdr);
  32226. }
  32227. return rc;
  32228. }
  32229. /*
  32230. ** Sync the pager file to disk. This is a no-op for in-memory files
  32231. ** or pages with the Pager.noSync flag set.
  32232. **
  32233. ** If successful, or called on a pager for which it is a no-op, this
  32234. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  32235. */
  32236. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  32237. int rc; /* Return code */
  32238. if( MEMDB || pPager->noSync ){
  32239. rc = SQLITE_OK;
  32240. }else{
  32241. rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  32242. }
  32243. return rc;
  32244. }
  32245. /*
  32246. ** Sync the database file for the pager pPager. zMaster points to the name
  32247. ** of a master journal file that should be written into the individual
  32248. ** journal file. zMaster may be NULL, which is interpreted as no master
  32249. ** journal (a single database transaction).
  32250. **
  32251. ** This routine ensures that:
  32252. **
  32253. ** * The database file change-counter is updated,
  32254. ** * the journal is synced (unless the atomic-write optimization is used),
  32255. ** * all dirty pages are written to the database file,
  32256. ** * the database file is truncated (if required), and
  32257. ** * the database file synced.
  32258. **
  32259. ** The only thing that remains to commit the transaction is to finalize
  32260. ** (delete, truncate or zero the first part of) the journal file (or
  32261. ** delete the master journal file if specified).
  32262. **
  32263. ** Note that if zMaster==NULL, this does not overwrite a previous value
  32264. ** passed to an sqlite3PagerCommitPhaseOne() call.
  32265. **
  32266. ** If the final parameter - noSync - is true, then the database file itself
  32267. ** is not synced. The caller must call sqlite3PagerSync() directly to
  32268. ** sync the database file before calling CommitPhaseTwo() to delete the
  32269. ** journal file in this case.
  32270. */
  32271. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  32272. Pager *pPager, /* Pager object */
  32273. const char *zMaster, /* If not NULL, the master journal name */
  32274. int noSync /* True to omit the xSync on the db file */
  32275. ){
  32276. int rc = SQLITE_OK; /* Return code */
  32277. if( pPager->errCode ){
  32278. return pPager->errCode;
  32279. }
  32280. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  32281. pPager->zFilename, zMaster, pPager->dbSize));
  32282. /* If this is an in-memory db, or no pages have been written to, or this
  32283. ** function has already been called, it is a no-op.
  32284. */
  32285. if( MEMDB && pPager->dbModified ){
  32286. sqlite3BackupRestart(pPager->pBackup);
  32287. }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
  32288. /* The following block updates the change-counter. Exactly how it
  32289. ** does this depends on whether or not the atomic-update optimization
  32290. ** was enabled at compile time, and if this transaction meets the
  32291. ** runtime criteria to use the operation:
  32292. **
  32293. ** * The file-system supports the atomic-write property for
  32294. ** blocks of size page-size, and
  32295. ** * This commit is not part of a multi-file transaction, and
  32296. ** * Exactly one page has been modified and store in the journal file.
  32297. **
  32298. ** If the optimization was not enabled at compile time, then the
  32299. ** pager_incr_changecounter() function is called to update the change
  32300. ** counter in 'indirect-mode'. If the optimization is compiled in but
  32301. ** is not applicable to this transaction, call sqlite3JournalCreate()
  32302. ** to make sure the journal file has actually been created, then call
  32303. ** pager_incr_changecounter() to update the change-counter in indirect
  32304. ** mode.
  32305. **
  32306. ** Otherwise, if the optimization is both enabled and applicable,
  32307. ** then call pager_incr_changecounter() to update the change-counter
  32308. ** in 'direct' mode. In this case the journal file will never be
  32309. ** created for this transaction.
  32310. */
  32311. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  32312. PgHdr *pPg;
  32313. assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
  32314. if( !zMaster && isOpen(pPager->jfd)
  32315. && pPager->journalOff==jrnlBufferSize(pPager)
  32316. && pPager->dbSize>=pPager->dbFileSize
  32317. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  32318. ){
  32319. /* Update the db file change counter via the direct-write method. The
  32320. ** following call will modify the in-memory representation of page 1
  32321. ** to include the updated change counter and then write page 1
  32322. ** directly to the database file. Because of the atomic-write
  32323. ** property of the host file-system, this is safe.
  32324. */
  32325. rc = pager_incr_changecounter(pPager, 1);
  32326. }else{
  32327. rc = sqlite3JournalCreate(pPager->jfd);
  32328. if( rc==SQLITE_OK ){
  32329. rc = pager_incr_changecounter(pPager, 0);
  32330. }
  32331. }
  32332. #else
  32333. rc = pager_incr_changecounter(pPager, 0);
  32334. #endif
  32335. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32336. /* If this transaction has made the database smaller, then all pages
  32337. ** being discarded by the truncation must be written to the journal
  32338. ** file. This can only happen in auto-vacuum mode.
  32339. **
  32340. ** Before reading the pages with page numbers larger than the
  32341. ** current value of Pager.dbSize, set dbSize back to the value
  32342. ** that it took at the start of the transaction. Otherwise, the
  32343. ** calls to sqlite3PagerGet() return zeroed pages instead of
  32344. ** reading data from the database file.
  32345. */
  32346. #ifndef SQLITE_OMIT_AUTOVACUUM
  32347. if( pPager->dbSize<pPager->dbOrigSize
  32348. && pPager->journalMode!=PAGER_JOURNALMODE_OFF
  32349. ){
  32350. Pgno i; /* Iterator variable */
  32351. const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
  32352. const Pgno dbSize = pPager->dbSize; /* Database image size */
  32353. pPager->dbSize = pPager->dbOrigSize;
  32354. for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
  32355. if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
  32356. PgHdr *pPage; /* Page to journal */
  32357. rc = sqlite3PagerGet(pPager, i, &pPage);
  32358. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32359. rc = sqlite3PagerWrite(pPage);
  32360. sqlite3PagerUnref(pPage);
  32361. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32362. }
  32363. }
  32364. pPager->dbSize = dbSize;
  32365. }
  32366. #endif
  32367. /* Write the master journal name into the journal file. If a master
  32368. ** journal file name has already been written to the journal file,
  32369. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  32370. */
  32371. rc = writeMasterJournal(pPager, zMaster);
  32372. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32373. /* Sync the journal file. If the atomic-update optimization is being
  32374. ** used, this call will not create the journal file or perform any
  32375. ** real IO.
  32376. */
  32377. rc = syncJournal(pPager);
  32378. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32379. /* Write all dirty pages to the database file. */
  32380. rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
  32381. if( rc!=SQLITE_OK ){
  32382. assert( rc!=SQLITE_IOERR_BLOCKED );
  32383. goto commit_phase_one_exit;
  32384. }
  32385. sqlite3PcacheCleanAll(pPager->pPCache);
  32386. /* If the file on disk is not the same size as the database image,
  32387. ** then use pager_truncate to grow or shrink the file here.
  32388. */
  32389. if( pPager->dbSize!=pPager->dbFileSize ){
  32390. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  32391. assert( pPager->state>=PAGER_EXCLUSIVE );
  32392. rc = pager_truncate(pPager, nNew);
  32393. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32394. }
  32395. /* Finally, sync the database file. */
  32396. if( !pPager->noSync && !noSync ){
  32397. rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  32398. }
  32399. IOTRACE(("DBSYNC %p\n", pPager))
  32400. pPager->state = PAGER_SYNCED;
  32401. }
  32402. commit_phase_one_exit:
  32403. if( rc==SQLITE_IOERR_BLOCKED ){
  32404. /* pager_incr_changecounter() may attempt to obtain an exclusive
  32405. ** lock to spill the cache and return IOERR_BLOCKED. But since
  32406. ** there is no chance the cache is inconsistent, it is
  32407. ** better to return SQLITE_BUSY.
  32408. **/
  32409. rc = SQLITE_BUSY;
  32410. }
  32411. return rc;
  32412. }
  32413. /*
  32414. ** When this function is called, the database file has been completely
  32415. ** updated to reflect the changes made by the current transaction and
  32416. ** synced to disk. The journal file still exists in the file-system
  32417. ** though, and if a failure occurs at this point it will eventually
  32418. ** be used as a hot-journal and the current transaction rolled back.
  32419. **
  32420. ** This function finalizes the journal file, either by deleting,
  32421. ** truncating or partially zeroing it, so that it cannot be used
  32422. ** for hot-journal rollback. Once this is done the transaction is
  32423. ** irrevocably committed.
  32424. **
  32425. ** If an error occurs, an IO error code is returned and the pager
  32426. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  32427. */
  32428. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  32429. int rc = SQLITE_OK; /* Return code */
  32430. /* Do not proceed if the pager is already in the error state. */
  32431. if( pPager->errCode ){
  32432. return pPager->errCode;
  32433. }
  32434. /* This function should not be called if the pager is not in at least
  32435. ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
  32436. ** nice to have this defensive block here anyway.
  32437. */
  32438. if( NEVER(pPager->state<PAGER_RESERVED) ){
  32439. return SQLITE_ERROR;
  32440. }
  32441. /* An optimization. If the database was not actually modified during
  32442. ** this transaction, the pager is running in exclusive-mode and is
  32443. ** using persistent journals, then this function is a no-op.
  32444. **
  32445. ** The start of the journal file currently contains a single journal
  32446. ** header with the nRec field set to 0. If such a journal is used as
  32447. ** a hot-journal during hot-journal rollback, 0 changes will be made
  32448. ** to the database file. So there is no need to zero the journal
  32449. ** header. Since the pager is in exclusive mode, there is no need
  32450. ** to drop any locks either.
  32451. */
  32452. if( pPager->dbModified==0 && pPager->exclusiveMode
  32453. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  32454. ){
  32455. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  32456. return SQLITE_OK;
  32457. }
  32458. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  32459. assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
  32460. rc = pager_end_transaction(pPager, pPager->setMaster);
  32461. return pager_error(pPager, rc);
  32462. }
  32463. /*
  32464. ** Rollback all changes. The database falls back to PAGER_SHARED mode.
  32465. **
  32466. ** This function performs two tasks:
  32467. **
  32468. ** 1) It rolls back the journal file, restoring all database file and
  32469. ** in-memory cache pages to the state they were in when the transaction
  32470. ** was opened, and
  32471. ** 2) It finalizes the journal file, so that it is not used for hot
  32472. ** rollback at any point in the future.
  32473. **
  32474. ** subject to the following qualifications:
  32475. **
  32476. ** * If the journal file is not yet open when this function is called,
  32477. ** then only (2) is performed. In this case there is no journal file
  32478. ** to roll back.
  32479. **
  32480. ** * If in an error state other than SQLITE_FULL, then task (1) is
  32481. ** performed. If successful, task (2). Regardless of the outcome
  32482. ** of either, the error state error code is returned to the caller
  32483. ** (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
  32484. **
  32485. ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
  32486. ** or not (1) is succussful, also attempt (2). If successful, return
  32487. ** SQLITE_OK. Otherwise, enter the error state and return the first
  32488. ** error code encountered.
  32489. **
  32490. ** In this case there is no chance that the database was written to.
  32491. ** So is safe to finalize the journal file even if the playback
  32492. ** (operation 1) failed. However the pager must enter the error state
  32493. ** as the contents of the in-memory cache are now suspect.
  32494. **
  32495. ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
  32496. ** attempt (2) if (1) is successful. Return SQLITE_OK if successful,
  32497. ** otherwise enter the error state and return the error code from the
  32498. ** failing operation.
  32499. **
  32500. ** In this case the database file may have been written to. So if the
  32501. ** playback operation did not succeed it would not be safe to finalize
  32502. ** the journal file. It needs to be left in the file-system so that
  32503. ** some other process can use it to restore the database state (by
  32504. ** hot-journal rollback).
  32505. */
  32506. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  32507. int rc = SQLITE_OK; /* Return code */
  32508. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  32509. if( !pPager->dbModified || !isOpen(pPager->jfd) ){
  32510. rc = pager_end_transaction(pPager, pPager->setMaster);
  32511. }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
  32512. if( pPager->state>=PAGER_EXCLUSIVE ){
  32513. pager_playback(pPager, 0);
  32514. }
  32515. rc = pPager->errCode;
  32516. }else{
  32517. if( pPager->state==PAGER_RESERVED ){
  32518. int rc2;
  32519. rc = pager_playback(pPager, 0);
  32520. rc2 = pager_end_transaction(pPager, pPager->setMaster);
  32521. if( rc==SQLITE_OK ){
  32522. rc = rc2;
  32523. }
  32524. }else{
  32525. rc = pager_playback(pPager, 0);
  32526. }
  32527. if( !MEMDB ){
  32528. pPager->dbSizeValid = 0;
  32529. }
  32530. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  32531. ** cache. So call pager_error() on the way out to make any error
  32532. ** persistent.
  32533. */
  32534. rc = pager_error(pPager, rc);
  32535. }
  32536. return rc;
  32537. }
  32538. /*
  32539. ** Return TRUE if the database file is opened read-only. Return FALSE
  32540. ** if the database is (in theory) writable.
  32541. */
  32542. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  32543. return pPager->readOnly;
  32544. }
  32545. /*
  32546. ** Return the number of references to the pager.
  32547. */
  32548. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  32549. return sqlite3PcacheRefCount(pPager->pPCache);
  32550. }
  32551. /*
  32552. ** Return the number of references to the specified page.
  32553. */
  32554. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  32555. return sqlite3PcachePageRefcount(pPage);
  32556. }
  32557. #ifdef SQLITE_TEST
  32558. /*
  32559. ** This routine is used for testing and analysis only.
  32560. */
  32561. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  32562. static int a[11];
  32563. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  32564. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  32565. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  32566. a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
  32567. a[4] = pPager->state;
  32568. a[5] = pPager->errCode;
  32569. a[6] = pPager->nHit;
  32570. a[7] = pPager->nMiss;
  32571. a[8] = 0; /* Used to be pPager->nOvfl */
  32572. a[9] = pPager->nRead;
  32573. a[10] = pPager->nWrite;
  32574. return a;
  32575. }
  32576. #endif
  32577. /*
  32578. ** Return true if this is an in-memory pager.
  32579. */
  32580. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  32581. return MEMDB;
  32582. }
  32583. /*
  32584. ** Check that there are at least nSavepoint savepoints open. If there are
  32585. ** currently less than nSavepoints open, then open one or more savepoints
  32586. ** to make up the difference. If the number of savepoints is already
  32587. ** equal to nSavepoint, then this function is a no-op.
  32588. **
  32589. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  32590. ** occurs while opening the sub-journal file, then an IO error code is
  32591. ** returned. Otherwise, SQLITE_OK.
  32592. */
  32593. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  32594. int rc = SQLITE_OK; /* Return code */
  32595. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  32596. if( nSavepoint>nCurrent && pPager->useJournal ){
  32597. int ii; /* Iterator variable */
  32598. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  32599. /* Either there is no active journal or the sub-journal is open or
  32600. ** the journal is always stored in memory */
  32601. assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
  32602. pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  32603. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  32604. ** if the allocation fails. Otherwise, zero the new portion in case a
  32605. ** malloc failure occurs while populating it in the for(...) loop below.
  32606. */
  32607. aNew = (PagerSavepoint *)sqlite3Realloc(
  32608. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  32609. );
  32610. if( !aNew ){
  32611. return SQLITE_NOMEM;
  32612. }
  32613. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  32614. pPager->aSavepoint = aNew;
  32615. pPager->nSavepoint = nSavepoint;
  32616. /* Populate the PagerSavepoint structures just allocated. */
  32617. for(ii=nCurrent; ii<nSavepoint; ii++){
  32618. assert( pPager->dbSizeValid );
  32619. aNew[ii].nOrig = pPager->dbSize;
  32620. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  32621. aNew[ii].iOffset = pPager->journalOff;
  32622. }else{
  32623. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  32624. }
  32625. aNew[ii].iSubRec = pPager->nSubRec;
  32626. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  32627. if( !aNew[ii].pInSavepoint ){
  32628. return SQLITE_NOMEM;
  32629. }
  32630. }
  32631. /* Open the sub-journal, if it is not already opened. */
  32632. rc = openSubJournal(pPager);
  32633. }
  32634. return rc;
  32635. }
  32636. /*
  32637. ** This function is called to rollback or release (commit) a savepoint.
  32638. ** The savepoint to release or rollback need not be the most recently
  32639. ** created savepoint.
  32640. **
  32641. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  32642. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  32643. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  32644. ** that have occurred since the specified savepoint was created.
  32645. **
  32646. ** The savepoint to rollback or release is identified by parameter
  32647. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  32648. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  32649. ** on the most recently created savepoint. If iSavepoint is greater than
  32650. ** (Pager.nSavepoint-1), then this function is a no-op.
  32651. **
  32652. ** If a negative value is passed to this function, then the current
  32653. ** transaction is rolled back. This is different to calling
  32654. ** sqlite3PagerRollback() because this function does not terminate
  32655. ** the transaction or unlock the database, it just restores the
  32656. ** contents of the database to its original state.
  32657. **
  32658. ** In any case, all savepoints with an index greater than iSavepoint
  32659. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  32660. ** then savepoint iSavepoint is also destroyed.
  32661. **
  32662. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  32663. ** or an IO error code if an IO error occurs while rolling back a
  32664. ** savepoint. If no errors occur, SQLITE_OK is returned.
  32665. */
  32666. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  32667. int rc = SQLITE_OK;
  32668. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  32669. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  32670. if( iSavepoint<pPager->nSavepoint ){
  32671. int ii; /* Iterator variable */
  32672. int nNew; /* Number of remaining savepoints after this op. */
  32673. /* Figure out how many savepoints will still be active after this
  32674. ** operation. Store this value in nNew. Then free resources associated
  32675. ** with any savepoints that are destroyed by this operation.
  32676. */
  32677. nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
  32678. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  32679. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  32680. }
  32681. pPager->nSavepoint = nNew;
  32682. /* If this is a rollback operation, playback the specified savepoint.
  32683. ** If this is a temp-file, it is possible that the journal file has
  32684. ** not yet been opened. In this case there have been no changes to
  32685. ** the database file, so the playback operation can be skipped.
  32686. */
  32687. if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
  32688. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  32689. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  32690. assert(rc!=SQLITE_DONE);
  32691. }
  32692. /* If this is a release of the outermost savepoint, truncate
  32693. ** the sub-journal to zero bytes in size. */
  32694. if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
  32695. assert( rc==SQLITE_OK );
  32696. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  32697. pPager->nSubRec = 0;
  32698. }
  32699. }
  32700. return rc;
  32701. }
  32702. /*
  32703. ** Return the full pathname of the database file.
  32704. */
  32705. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
  32706. return pPager->zFilename;
  32707. }
  32708. /*
  32709. ** Return the VFS structure for the pager.
  32710. */
  32711. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  32712. return pPager->pVfs;
  32713. }
  32714. /*
  32715. ** Return the file handle for the database file associated
  32716. ** with the pager. This might return NULL if the file has
  32717. ** not yet been opened.
  32718. */
  32719. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  32720. return pPager->fd;
  32721. }
  32722. /*
  32723. ** Return the full pathname of the journal file.
  32724. */
  32725. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  32726. return pPager->zJournal;
  32727. }
  32728. /*
  32729. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  32730. ** if fsync()s are executed normally.
  32731. */
  32732. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  32733. return pPager->noSync;
  32734. }
  32735. #ifdef SQLITE_HAS_CODEC
  32736. /*
  32737. ** Set the codec for this pager
  32738. */
  32739. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  32740. Pager *pPager,
  32741. void *(*xCodec)(void*,void*,Pgno,int),
  32742. void *pCodecArg
  32743. ){
  32744. pPager->xCodec = xCodec;
  32745. pPager->pCodecArg = pCodecArg;
  32746. }
  32747. #endif
  32748. #ifndef SQLITE_OMIT_AUTOVACUUM
  32749. /*
  32750. ** Move the page pPg to location pgno in the file.
  32751. **
  32752. ** There must be no references to the page previously located at
  32753. ** pgno (which we call pPgOld) though that page is allowed to be
  32754. ** in cache. If the page previously located at pgno is not already
  32755. ** in the rollback journal, it is not put there by by this routine.
  32756. **
  32757. ** References to the page pPg remain valid. Updating any
  32758. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  32759. ** allocated along with the page) is the responsibility of the caller.
  32760. **
  32761. ** A transaction must be active when this routine is called. It used to be
  32762. ** required that a statement transaction was not active, but this restriction
  32763. ** has been removed (CREATE INDEX needs to move a page when a statement
  32764. ** transaction is active).
  32765. **
  32766. ** If the fourth argument, isCommit, is non-zero, then this page is being
  32767. ** moved as part of a database reorganization just before the transaction
  32768. ** is being committed. In this case, it is guaranteed that the database page
  32769. ** pPg refers to will not be written to again within this transaction.
  32770. **
  32771. ** This function may return SQLITE_NOMEM or an IO error code if an error
  32772. ** occurs. Otherwise, it returns SQLITE_OK.
  32773. */
  32774. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  32775. PgHdr *pPgOld; /* The page being overwritten. */
  32776. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  32777. int rc; /* Return code */
  32778. Pgno origPgno; /* The original page number */
  32779. assert( pPg->nRef>0 );
  32780. /* If the page being moved is dirty and has not been saved by the latest
  32781. ** savepoint, then save the current contents of the page into the
  32782. ** sub-journal now. This is required to handle the following scenario:
  32783. **
  32784. ** BEGIN;
  32785. ** <journal page X, then modify it in memory>
  32786. ** SAVEPOINT one;
  32787. ** <Move page X to location Y>
  32788. ** ROLLBACK TO one;
  32789. **
  32790. ** If page X were not written to the sub-journal here, it would not
  32791. ** be possible to restore its contents when the "ROLLBACK TO one"
  32792. ** statement were is processed.
  32793. **
  32794. ** subjournalPage() may need to allocate space to store pPg->pgno into
  32795. ** one or more savepoint bitvecs. This is the reason this function
  32796. ** may return SQLITE_NOMEM.
  32797. */
  32798. if( pPg->flags&PGHDR_DIRTY
  32799. && subjRequiresPage(pPg)
  32800. && SQLITE_OK!=(rc = subjournalPage(pPg))
  32801. ){
  32802. return rc;
  32803. }
  32804. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  32805. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  32806. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  32807. /* If the journal needs to be sync()ed before page pPg->pgno can
  32808. ** be written to, store pPg->pgno in local variable needSyncPgno.
  32809. **
  32810. ** If the isCommit flag is set, there is no need to remember that
  32811. ** the journal needs to be sync()ed before database page pPg->pgno
  32812. ** can be written to. The caller has already promised not to write to it.
  32813. */
  32814. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  32815. needSyncPgno = pPg->pgno;
  32816. assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  32817. assert( pPg->flags&PGHDR_DIRTY );
  32818. assert( pPager->needSync );
  32819. }
  32820. /* If the cache contains a page with page-number pgno, remove it
  32821. ** from its hash chain. Also, if the PgHdr.needSync was set for
  32822. ** page pgno before the 'move' operation, it needs to be retained
  32823. ** for the page moved there.
  32824. */
  32825. pPg->flags &= ~PGHDR_NEED_SYNC;
  32826. pPgOld = pager_lookup(pPager, pgno);
  32827. assert( !pPgOld || pPgOld->nRef==1 );
  32828. if( pPgOld ){
  32829. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  32830. sqlite3PcacheDrop(pPgOld);
  32831. }
  32832. origPgno = pPg->pgno;
  32833. sqlite3PcacheMove(pPg, pgno);
  32834. sqlite3PcacheMakeDirty(pPg);
  32835. pPager->dbModified = 1;
  32836. if( needSyncPgno ){
  32837. /* If needSyncPgno is non-zero, then the journal file needs to be
  32838. ** sync()ed before any data is written to database file page needSyncPgno.
  32839. ** Currently, no such page exists in the page-cache and the
  32840. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  32841. ** loading the page into the pager-cache and setting the PgHdr.needSync
  32842. ** flag.
  32843. **
  32844. ** If the attempt to load the page into the page-cache fails, (due
  32845. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  32846. ** array. Otherwise, if the page is loaded and written again in
  32847. ** this transaction, it may be written to the database file before
  32848. ** it is synced into the journal file. This way, it may end up in
  32849. ** the journal file twice, but that is not a problem.
  32850. **
  32851. ** The sqlite3PagerGet() call may cause the journal to sync. So make
  32852. ** sure the Pager.needSync flag is set too.
  32853. */
  32854. PgHdr *pPgHdr;
  32855. assert( pPager->needSync );
  32856. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  32857. if( rc!=SQLITE_OK ){
  32858. if( pPager->pInJournal && needSyncPgno<=pPager->dbOrigSize ){
  32859. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
  32860. }
  32861. return rc;
  32862. }
  32863. pPager->needSync = 1;
  32864. assert( pPager->noSync==0 && !MEMDB );
  32865. pPgHdr->flags |= PGHDR_NEED_SYNC;
  32866. sqlite3PcacheMakeDirty(pPgHdr);
  32867. sqlite3PagerUnref(pPgHdr);
  32868. }
  32869. /*
  32870. ** For an in-memory database, make sure the original page continues
  32871. ** to exist, in case the transaction needs to roll back. We allocate
  32872. ** the page now, instead of at rollback, because we can better deal
  32873. ** with an out-of-memory error now. Ticket #3761.
  32874. */
  32875. if( MEMDB ){
  32876. DbPage *pNew;
  32877. rc = sqlite3PagerAcquire(pPager, origPgno, &pNew, 1);
  32878. if( rc!=SQLITE_OK ) return rc;
  32879. sqlite3PagerUnref(pNew);
  32880. }
  32881. return SQLITE_OK;
  32882. }
  32883. #endif
  32884. /*
  32885. ** Return a pointer to the data for the specified page.
  32886. */
  32887. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  32888. assert( pPg->nRef>0 || pPg->pPager->memDb );
  32889. return pPg->pData;
  32890. }
  32891. /*
  32892. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  32893. ** allocated along with the specified page.
  32894. */
  32895. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  32896. Pager *pPager = pPg->pPager;
  32897. return (pPager?pPg->pExtra:0);
  32898. }
  32899. /*
  32900. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  32901. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  32902. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  32903. ** the locking-mode is set to the value specified.
  32904. **
  32905. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  32906. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  32907. ** locking-mode.
  32908. */
  32909. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  32910. assert( eMode==PAGER_LOCKINGMODE_QUERY
  32911. || eMode==PAGER_LOCKINGMODE_NORMAL
  32912. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  32913. assert( PAGER_LOCKINGMODE_QUERY<0 );
  32914. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  32915. if( eMode>=0 && !pPager->tempFile ){
  32916. pPager->exclusiveMode = (u8)eMode;
  32917. }
  32918. return (int)pPager->exclusiveMode;
  32919. }
  32920. /*
  32921. ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
  32922. **
  32923. ** PAGER_JOURNALMODE_QUERY
  32924. ** PAGER_JOURNALMODE_DELETE
  32925. ** PAGER_JOURNALMODE_TRUNCATE
  32926. ** PAGER_JOURNALMODE_PERSIST
  32927. ** PAGER_JOURNALMODE_OFF
  32928. ** PAGER_JOURNALMODE_MEMORY
  32929. **
  32930. ** If the parameter is not _QUERY, then the journal-mode is set to the
  32931. ** value specified. Except, an in-memory database can only have its
  32932. ** journal mode set to _OFF or _MEMORY. Attempts to change the journal
  32933. ** mode of an in-memory database to something other than _OFF or _MEMORY
  32934. ** are silently ignored.
  32935. **
  32936. ** The returned indicate the current (possibly updated) journal-mode.
  32937. */
  32938. SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
  32939. assert( eMode==PAGER_JOURNALMODE_QUERY
  32940. || eMode==PAGER_JOURNALMODE_DELETE
  32941. || eMode==PAGER_JOURNALMODE_TRUNCATE
  32942. || eMode==PAGER_JOURNALMODE_PERSIST
  32943. || eMode==PAGER_JOURNALMODE_OFF
  32944. || eMode==PAGER_JOURNALMODE_MEMORY );
  32945. assert( PAGER_JOURNALMODE_QUERY<0 );
  32946. if( eMode>=0 && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
  32947. || eMode==PAGER_JOURNALMODE_OFF) ){
  32948. pPager->journalMode = (u8)eMode;
  32949. }
  32950. return (int)pPager->journalMode;
  32951. }
  32952. /*
  32953. ** Get/set the size-limit used for persistent journal files.
  32954. **
  32955. ** Setting the size limit to -1 means no limit is enforced.
  32956. ** An attempt to set a limit smaller than -1 is a no-op.
  32957. */
  32958. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  32959. if( iLimit>=-1 ){
  32960. pPager->journalSizeLimit = iLimit;
  32961. }
  32962. return pPager->journalSizeLimit;
  32963. }
  32964. /*
  32965. ** Return a pointer to the pPager->pBackup variable. The backup module
  32966. ** in backup.c maintains the content of this variable. This module
  32967. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  32968. ** sqlite3BackupUpdate() only.
  32969. */
  32970. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  32971. return &pPager->pBackup;
  32972. }
  32973. #endif /* SQLITE_OMIT_DISKIO */
  32974. /************** End of pager.c ***********************************************/
  32975. /************** Begin file btmutex.c *****************************************/
  32976. /*
  32977. ** 2007 August 27
  32978. **
  32979. ** The author disclaims copyright to this source code. In place of
  32980. ** a legal notice, here is a blessing:
  32981. **
  32982. ** May you do good and not evil.
  32983. ** May you find forgiveness for yourself and forgive others.
  32984. ** May you share freely, never taking more than you give.
  32985. **
  32986. *************************************************************************
  32987. **
  32988. ** $Id: btmutex.c,v 1.15 2009/04/10 12:55:17 danielk1977 Exp $
  32989. **
  32990. ** This file contains code used to implement mutexes on Btree objects.
  32991. ** This code really belongs in btree.c. But btree.c is getting too
  32992. ** big and we want to break it down some. This packaged seemed like
  32993. ** a good breakout.
  32994. */
  32995. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  32996. /************** Begin file btreeInt.h ****************************************/
  32997. /*
  32998. ** 2004 April 6
  32999. **
  33000. ** The author disclaims copyright to this source code. In place of
  33001. ** a legal notice, here is a blessing:
  33002. **
  33003. ** May you do good and not evil.
  33004. ** May you find forgiveness for yourself and forgive others.
  33005. ** May you share freely, never taking more than you give.
  33006. **
  33007. *************************************************************************
  33008. ** $Id: btreeInt.h,v 1.46 2009/03/20 14:18:52 danielk1977 Exp $
  33009. **
  33010. ** This file implements a external (disk-based) database using BTrees.
  33011. ** For a detailed discussion of BTrees, refer to
  33012. **
  33013. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  33014. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  33015. ** Publishing Company, Reading, Massachusetts.
  33016. **
  33017. ** The basic idea is that each page of the file contains N database
  33018. ** entries and N+1 pointers to subpages.
  33019. **
  33020. ** ----------------------------------------------------------------
  33021. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  33022. ** ----------------------------------------------------------------
  33023. **
  33024. ** All of the keys on the page that Ptr(0) points to have values less
  33025. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  33026. ** values greater than Key(0) and less than Key(1). All of the keys
  33027. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  33028. ** so forth.
  33029. **
  33030. ** Finding a particular key requires reading O(log(M)) pages from the
  33031. ** disk where M is the number of entries in the tree.
  33032. **
  33033. ** In this implementation, a single file can hold one or more separate
  33034. ** BTrees. Each BTree is identified by the index of its root page. The
  33035. ** key and data for any entry are combined to form the "payload". A
  33036. ** fixed amount of payload can be carried directly on the database
  33037. ** page. If the payload is larger than the preset amount then surplus
  33038. ** bytes are stored on overflow pages. The payload for an entry
  33039. ** and the preceding pointer are combined to form a "Cell". Each
  33040. ** page has a small header which contains the Ptr(N) pointer and other
  33041. ** information such as the size of key and data.
  33042. **
  33043. ** FORMAT DETAILS
  33044. **
  33045. ** The file is divided into pages. The first page is called page 1,
  33046. ** the second is page 2, and so forth. A page number of zero indicates
  33047. ** "no such page". The page size can be anything between 512 and 65536.
  33048. ** Each page can be either a btree page, a freelist page or an overflow
  33049. ** page.
  33050. **
  33051. ** The first page is always a btree page. The first 100 bytes of the first
  33052. ** page contain a special header (the "file header") that describes the file.
  33053. ** The format of the file header is as follows:
  33054. **
  33055. ** OFFSET SIZE DESCRIPTION
  33056. ** 0 16 Header string: "SQLite format 3\000"
  33057. ** 16 2 Page size in bytes.
  33058. ** 18 1 File format write version
  33059. ** 19 1 File format read version
  33060. ** 20 1 Bytes of unused space at the end of each page
  33061. ** 21 1 Max embedded payload fraction
  33062. ** 22 1 Min embedded payload fraction
  33063. ** 23 1 Min leaf payload fraction
  33064. ** 24 4 File change counter
  33065. ** 28 4 Reserved for future use
  33066. ** 32 4 First freelist page
  33067. ** 36 4 Number of freelist pages in the file
  33068. ** 40 60 15 4-byte meta values passed to higher layers
  33069. **
  33070. ** All of the integer values are big-endian (most significant byte first).
  33071. **
  33072. ** The file change counter is incremented when the database is changed
  33073. ** This counter allows other processes to know when the file has changed
  33074. ** and thus when they need to flush their cache.
  33075. **
  33076. ** The max embedded payload fraction is the amount of the total usable
  33077. ** space in a page that can be consumed by a single cell for standard
  33078. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  33079. ** is to limit the maximum cell size so that at least 4 cells will fit
  33080. ** on one page. Thus the default max embedded payload fraction is 64.
  33081. **
  33082. ** If the payload for a cell is larger than the max payload, then extra
  33083. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  33084. ** as many bytes as possible are moved into the overflow pages without letting
  33085. ** the cell size drop below the min embedded payload fraction.
  33086. **
  33087. ** The min leaf payload fraction is like the min embedded payload fraction
  33088. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  33089. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  33090. ** not specified in the header.
  33091. **
  33092. ** Each btree pages is divided into three sections: The header, the
  33093. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  33094. ** file header that occurs before the page header.
  33095. **
  33096. ** |----------------|
  33097. ** | file header | 100 bytes. Page 1 only.
  33098. ** |----------------|
  33099. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  33100. ** |----------------|
  33101. ** | cell pointer | | 2 bytes per cell. Sorted order.
  33102. ** | array | | Grows downward
  33103. ** | | v
  33104. ** |----------------|
  33105. ** | unallocated |
  33106. ** | space |
  33107. ** |----------------| ^ Grows upwards
  33108. ** | cell content | | Arbitrary order interspersed with freeblocks.
  33109. ** | area | | and free space fragments.
  33110. ** |----------------|
  33111. **
  33112. ** The page headers looks like this:
  33113. **
  33114. ** OFFSET SIZE DESCRIPTION
  33115. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  33116. ** 1 2 byte offset to the first freeblock
  33117. ** 3 2 number of cells on this page
  33118. ** 5 2 first byte of the cell content area
  33119. ** 7 1 number of fragmented free bytes
  33120. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  33121. **
  33122. ** The flags define the format of this btree page. The leaf flag means that
  33123. ** this page has no children. The zerodata flag means that this page carries
  33124. ** only keys and no data. The intkey flag means that the key is a integer
  33125. ** which is stored in the key size entry of the cell header rather than in
  33126. ** the payload area.
  33127. **
  33128. ** The cell pointer array begins on the first byte after the page header.
  33129. ** The cell pointer array contains zero or more 2-byte numbers which are
  33130. ** offsets from the beginning of the page to the cell content in the cell
  33131. ** content area. The cell pointers occur in sorted order. The system strives
  33132. ** to keep free space after the last cell pointer so that new cells can
  33133. ** be easily added without having to defragment the page.
  33134. **
  33135. ** Cell content is stored at the very end of the page and grows toward the
  33136. ** beginning of the page.
  33137. **
  33138. ** Unused space within the cell content area is collected into a linked list of
  33139. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  33140. ** to the first freeblock is given in the header. Freeblocks occur in
  33141. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  33142. ** any group of 3 or fewer unused bytes in the cell content area cannot
  33143. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  33144. ** a fragment. The total number of bytes in all fragments is recorded.
  33145. ** in the page header at offset 7.
  33146. **
  33147. ** SIZE DESCRIPTION
  33148. ** 2 Byte offset of the next freeblock
  33149. ** 2 Bytes in this freeblock
  33150. **
  33151. ** Cells are of variable length. Cells are stored in the cell content area at
  33152. ** the end of the page. Pointers to the cells are in the cell pointer array
  33153. ** that immediately follows the page header. Cells is not necessarily
  33154. ** contiguous or in order, but cell pointers are contiguous and in order.
  33155. **
  33156. ** Cell content makes use of variable length integers. A variable
  33157. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  33158. ** byte are used. The integer consists of all bytes that have bit 8 set and
  33159. ** the first byte with bit 8 clear. The most significant byte of the integer
  33160. ** appears first. A variable-length integer may not be more than 9 bytes long.
  33161. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  33162. ** allows a 64-bit integer to be encoded in 9 bytes.
  33163. **
  33164. ** 0x00 becomes 0x00000000
  33165. ** 0x7f becomes 0x0000007f
  33166. ** 0x81 0x00 becomes 0x00000080
  33167. ** 0x82 0x00 becomes 0x00000100
  33168. ** 0x80 0x7f becomes 0x0000007f
  33169. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  33170. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  33171. **
  33172. ** Variable length integers are used for rowids and to hold the number of
  33173. ** bytes of key and data in a btree cell.
  33174. **
  33175. ** The content of a cell looks like this:
  33176. **
  33177. ** SIZE DESCRIPTION
  33178. ** 4 Page number of the left child. Omitted if leaf flag is set.
  33179. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  33180. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  33181. ** * Payload
  33182. ** 4 First page of the overflow chain. Omitted if no overflow
  33183. **
  33184. ** Overflow pages form a linked list. Each page except the last is completely
  33185. ** filled with data (pagesize - 4 bytes). The last page can have as little
  33186. ** as 1 byte of data.
  33187. **
  33188. ** SIZE DESCRIPTION
  33189. ** 4 Page number of next overflow page
  33190. ** * Data
  33191. **
  33192. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  33193. ** file header points to the first in a linked list of trunk page. Each trunk
  33194. ** page points to multiple leaf pages. The content of a leaf page is
  33195. ** unspecified. A trunk page looks like this:
  33196. **
  33197. ** SIZE DESCRIPTION
  33198. ** 4 Page number of next trunk page
  33199. ** 4 Number of leaf pointers on this page
  33200. ** * zero or more pages numbers of leaves
  33201. */
  33202. /* The following value is the maximum cell size assuming a maximum page
  33203. ** size give above.
  33204. */
  33205. #define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
  33206. /* The maximum number of cells on a single page of the database. This
  33207. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  33208. ** plus 2 bytes for the index to the cell in the page header). Such
  33209. ** small cells will be rare, but they are possible.
  33210. */
  33211. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  33212. /* Forward declarations */
  33213. typedef struct MemPage MemPage;
  33214. typedef struct BtLock BtLock;
  33215. /*
  33216. ** This is a magic string that appears at the beginning of every
  33217. ** SQLite database in order to identify the file as a real database.
  33218. **
  33219. ** You can change this value at compile-time by specifying a
  33220. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  33221. ** header must be exactly 16 bytes including the zero-terminator so
  33222. ** the string itself should be 15 characters long. If you change
  33223. ** the header, then your custom library will not be able to read
  33224. ** databases generated by the standard tools and the standard tools
  33225. ** will not be able to read databases created by your custom library.
  33226. */
  33227. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  33228. # define SQLITE_FILE_HEADER "SQLite format 3"
  33229. #endif
  33230. /*
  33231. ** Page type flags. An ORed combination of these flags appear as the
  33232. ** first byte of on-disk image of every BTree page.
  33233. */
  33234. #define PTF_INTKEY 0x01
  33235. #define PTF_ZERODATA 0x02
  33236. #define PTF_LEAFDATA 0x04
  33237. #define PTF_LEAF 0x08
  33238. /*
  33239. ** As each page of the file is loaded into memory, an instance of the following
  33240. ** structure is appended and initialized to zero. This structure stores
  33241. ** information about the page that is decoded from the raw file page.
  33242. **
  33243. ** The pParent field points back to the parent page. This allows us to
  33244. ** walk up the BTree from any leaf to the root. Care must be taken to
  33245. ** unref() the parent page pointer when this page is no longer referenced.
  33246. ** The pageDestructor() routine handles that chore.
  33247. **
  33248. ** Access to all fields of this structure is controlled by the mutex
  33249. ** stored in MemPage.pBt->mutex.
  33250. */
  33251. struct MemPage {
  33252. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  33253. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  33254. u8 intKey; /* True if intkey flag is set */
  33255. u8 leaf; /* True if leaf flag is set */
  33256. u8 hasData; /* True if this page stores data */
  33257. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  33258. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  33259. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  33260. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  33261. u16 cellOffset; /* Index in aData of first cell pointer */
  33262. u16 nFree; /* Number of free bytes on the page */
  33263. u16 nCell; /* Number of cells on this page, local and ovfl */
  33264. u16 maskPage; /* Mask for page offset */
  33265. struct _OvflCell { /* Cells that will not fit on aData[] */
  33266. u8 *pCell; /* Pointers to the body of the overflow cell */
  33267. u16 idx; /* Insert this cell before idx-th non-overflow cell */
  33268. } aOvfl[5];
  33269. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  33270. u8 *aData; /* Pointer to disk image of the page data */
  33271. DbPage *pDbPage; /* Pager page handle */
  33272. Pgno pgno; /* Page number for this page */
  33273. };
  33274. /*
  33275. ** The in-memory image of a disk page has the auxiliary information appended
  33276. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  33277. ** that extra information.
  33278. */
  33279. #define EXTRA_SIZE sizeof(MemPage)
  33280. /* A Btree handle
  33281. **
  33282. ** A database connection contains a pointer to an instance of
  33283. ** this object for every database file that it has open. This structure
  33284. ** is opaque to the database connection. The database connection cannot
  33285. ** see the internals of this structure and only deals with pointers to
  33286. ** this structure.
  33287. **
  33288. ** For some database files, the same underlying database cache might be
  33289. ** shared between multiple connections. In that case, each contection
  33290. ** has it own pointer to this object. But each instance of this object
  33291. ** points to the same BtShared object. The database cache and the
  33292. ** schema associated with the database file are all contained within
  33293. ** the BtShared object.
  33294. **
  33295. ** All fields in this structure are accessed under sqlite3.mutex.
  33296. ** The pBt pointer itself may not be changed while there exists cursors
  33297. ** in the referenced BtShared that point back to this Btree since those
  33298. ** cursors have to do go through this Btree to find their BtShared and
  33299. ** they often do so without holding sqlite3.mutex.
  33300. */
  33301. struct Btree {
  33302. sqlite3 *db; /* The database connection holding this btree */
  33303. BtShared *pBt; /* Sharable content of this btree */
  33304. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  33305. u8 sharable; /* True if we can share pBt with another db */
  33306. u8 locked; /* True if db currently has pBt locked */
  33307. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  33308. int nBackup; /* Number of backup operations reading this btree */
  33309. Btree *pNext; /* List of other sharable Btrees from the same db */
  33310. Btree *pPrev; /* Back pointer of the same list */
  33311. };
  33312. /*
  33313. ** Btree.inTrans may take one of the following values.
  33314. **
  33315. ** If the shared-data extension is enabled, there may be multiple users
  33316. ** of the Btree structure. At most one of these may open a write transaction,
  33317. ** but any number may have active read transactions.
  33318. */
  33319. #define TRANS_NONE 0
  33320. #define TRANS_READ 1
  33321. #define TRANS_WRITE 2
  33322. /*
  33323. ** An instance of this object represents a single database file.
  33324. **
  33325. ** A single database file can be in use as the same time by two
  33326. ** or more database connections. When two or more connections are
  33327. ** sharing the same database file, each connection has it own
  33328. ** private Btree object for the file and each of those Btrees points
  33329. ** to this one BtShared object. BtShared.nRef is the number of
  33330. ** connections currently sharing this database file.
  33331. **
  33332. ** Fields in this structure are accessed under the BtShared.mutex
  33333. ** mutex, except for nRef and pNext which are accessed under the
  33334. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  33335. ** may not be modified once it is initially set as long as nRef>0.
  33336. ** The pSchema field may be set once under BtShared.mutex and
  33337. ** thereafter is unchanged as long as nRef>0.
  33338. **
  33339. ** isPending:
  33340. **
  33341. ** If a BtShared client fails to obtain a write-lock on a database
  33342. ** table (because there exists one or more read-locks on the table),
  33343. ** the shared-cache enters 'pending-lock' state and isPending is
  33344. ** set to true.
  33345. **
  33346. ** The shared-cache leaves the 'pending lock' state when either of
  33347. ** the following occur:
  33348. **
  33349. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  33350. ** 2) The number of locks held by other connections drops to zero.
  33351. **
  33352. ** while in the 'pending-lock' state, no connection may start a new
  33353. ** transaction.
  33354. **
  33355. ** This feature is included to help prevent writer-starvation.
  33356. */
  33357. struct BtShared {
  33358. Pager *pPager; /* The page cache */
  33359. sqlite3 *db; /* Database connection currently using this Btree */
  33360. BtCursor *pCursor; /* A list of all open cursors */
  33361. MemPage *pPage1; /* First page of the database */
  33362. u8 readOnly; /* True if the underlying file is readonly */
  33363. u8 pageSizeFixed; /* True if the page size can no longer be changed */
  33364. #ifndef SQLITE_OMIT_AUTOVACUUM
  33365. u8 autoVacuum; /* True if auto-vacuum is enabled */
  33366. u8 incrVacuum; /* True if incr-vacuum is enabled */
  33367. #endif
  33368. u16 pageSize; /* Total number of bytes on a page */
  33369. u16 usableSize; /* Number of usable bytes on each page */
  33370. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  33371. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  33372. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  33373. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  33374. u8 inTransaction; /* Transaction state */
  33375. int nTransaction; /* Number of open transactions (read + write) */
  33376. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  33377. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  33378. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
  33379. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  33380. #ifndef SQLITE_OMIT_SHARED_CACHE
  33381. int nRef; /* Number of references to this structure */
  33382. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  33383. BtLock *pLock; /* List of locks held on this shared-btree struct */
  33384. Btree *pWriter; /* Btree with currently open write transaction */
  33385. u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */
  33386. u8 isPending; /* If waiting for read-locks to clear */
  33387. #endif
  33388. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  33389. };
  33390. /*
  33391. ** An instance of the following structure is used to hold information
  33392. ** about a cell. The parseCellPtr() function fills in this structure
  33393. ** based on information extract from the raw disk page.
  33394. */
  33395. typedef struct CellInfo CellInfo;
  33396. struct CellInfo {
  33397. u8 *pCell; /* Pointer to the start of cell content */
  33398. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  33399. u32 nData; /* Number of bytes of data */
  33400. u32 nPayload; /* Total amount of payload */
  33401. u16 nHeader; /* Size of the cell content header in bytes */
  33402. u16 nLocal; /* Amount of payload held locally */
  33403. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  33404. u16 nSize; /* Size of the cell content on the main b-tree page */
  33405. };
  33406. /*
  33407. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  33408. ** this will be declared corrupt. This value is calculated based on a
  33409. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  33410. ** root-node and 3 for all other internal nodes.
  33411. **
  33412. ** If a tree that appears to be taller than this is encountered, it is
  33413. ** assumed that the database is corrupt.
  33414. */
  33415. #define BTCURSOR_MAX_DEPTH 20
  33416. /*
  33417. ** A cursor is a pointer to a particular entry within a particular
  33418. ** b-tree within a database file.
  33419. **
  33420. ** The entry is identified by its MemPage and the index in
  33421. ** MemPage.aCell[] of the entry.
  33422. **
  33423. ** When a single database file can shared by two more database connections,
  33424. ** but cursors cannot be shared. Each cursor is associated with a
  33425. ** particular database connection identified BtCursor.pBtree.db.
  33426. **
  33427. ** Fields in this structure are accessed under the BtShared.mutex
  33428. ** found at self->pBt->mutex.
  33429. */
  33430. struct BtCursor {
  33431. Btree *pBtree; /* The Btree to which this cursor belongs */
  33432. BtShared *pBt; /* The BtShared this cursor points to */
  33433. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  33434. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  33435. Pgno pgnoRoot; /* The root page of this tree */
  33436. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  33437. CellInfo info; /* A parse of the cell we are pointing at */
  33438. u8 wrFlag; /* True if writable */
  33439. u8 atLast; /* Cursor pointing to the last entry */
  33440. u8 validNKey; /* True if info.nKey is valid */
  33441. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  33442. void *pKey; /* Saved key that was cursor's last known position */
  33443. i64 nKey; /* Size of pKey, or last integer key */
  33444. int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
  33445. #ifndef SQLITE_OMIT_INCRBLOB
  33446. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  33447. Pgno *aOverflow; /* Cache of overflow page locations */
  33448. #endif
  33449. #ifndef NDEBUG
  33450. u8 pagesShuffled; /* True if Btree pages are rearranged by balance()*/
  33451. #endif
  33452. i16 iPage; /* Index of current page in apPage */
  33453. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  33454. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  33455. };
  33456. /*
  33457. ** Potential values for BtCursor.eState.
  33458. **
  33459. ** CURSOR_VALID:
  33460. ** Cursor points to a valid entry. getPayload() etc. may be called.
  33461. **
  33462. ** CURSOR_INVALID:
  33463. ** Cursor does not point to a valid entry. This can happen (for example)
  33464. ** because the table is empty or because BtreeCursorFirst() has not been
  33465. ** called.
  33466. **
  33467. ** CURSOR_REQUIRESEEK:
  33468. ** The table that this cursor was opened on still exists, but has been
  33469. ** modified since the cursor was last used. The cursor position is saved
  33470. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  33471. ** this state, restoreCursorPosition() can be called to attempt to
  33472. ** seek the cursor to the saved position.
  33473. **
  33474. ** CURSOR_FAULT:
  33475. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  33476. ** on a different connection that shares the BtShared cache with this
  33477. ** cursor. The error has left the cache in an inconsistent state.
  33478. ** Do nothing else with this cursor. Any attempt to use the cursor
  33479. ** should return the error code stored in BtCursor.skip
  33480. */
  33481. #define CURSOR_INVALID 0
  33482. #define CURSOR_VALID 1
  33483. #define CURSOR_REQUIRESEEK 2
  33484. #define CURSOR_FAULT 3
  33485. /*
  33486. ** The database page the PENDING_BYTE occupies. This page is never used.
  33487. */
  33488. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  33489. /*
  33490. ** A linked list of the following structures is stored at BtShared.pLock.
  33491. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  33492. ** is opened on the table with root page BtShared.iTable. Locks are removed
  33493. ** from this list when a transaction is committed or rolled back, or when
  33494. ** a btree handle is closed.
  33495. */
  33496. struct BtLock {
  33497. Btree *pBtree; /* Btree handle holding this lock */
  33498. Pgno iTable; /* Root page of table */
  33499. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  33500. BtLock *pNext; /* Next in BtShared.pLock list */
  33501. };
  33502. /* Candidate values for BtLock.eLock */
  33503. #define READ_LOCK 1
  33504. #define WRITE_LOCK 2
  33505. /*
  33506. ** These macros define the location of the pointer-map entry for a
  33507. ** database page. The first argument to each is the number of usable
  33508. ** bytes on each page of the database (often 1024). The second is the
  33509. ** page number to look up in the pointer map.
  33510. **
  33511. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  33512. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  33513. ** the offset of the requested map entry.
  33514. **
  33515. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  33516. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  33517. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  33518. ** this test.
  33519. */
  33520. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  33521. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  33522. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  33523. /*
  33524. ** The pointer map is a lookup table that identifies the parent page for
  33525. ** each child page in the database file. The parent page is the page that
  33526. ** contains a pointer to the child. Every page in the database contains
  33527. ** 0 or 1 parent pages. (In this context 'database page' refers
  33528. ** to any page that is not part of the pointer map itself.) Each pointer map
  33529. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  33530. ** The PTRMAP_XXX identifiers below are the valid types.
  33531. **
  33532. ** The purpose of the pointer map is to facility moving pages from one
  33533. ** position in the file to another as part of autovacuum. When a page
  33534. ** is moved, the pointer in its parent must be updated to point to the
  33535. ** new location. The pointer map is used to locate the parent page quickly.
  33536. **
  33537. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  33538. ** used in this case.
  33539. **
  33540. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  33541. ** is not used in this case.
  33542. **
  33543. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  33544. ** overflow pages. The page number identifies the page that
  33545. ** contains the cell with a pointer to this overflow page.
  33546. **
  33547. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  33548. ** overflow pages. The page-number identifies the previous
  33549. ** page in the overflow page list.
  33550. **
  33551. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  33552. ** identifies the parent page in the btree.
  33553. */
  33554. #define PTRMAP_ROOTPAGE 1
  33555. #define PTRMAP_FREEPAGE 2
  33556. #define PTRMAP_OVERFLOW1 3
  33557. #define PTRMAP_OVERFLOW2 4
  33558. #define PTRMAP_BTREE 5
  33559. /* A bunch of assert() statements to check the transaction state variables
  33560. ** of handle p (type Btree*) are internally consistent.
  33561. */
  33562. #define btreeIntegrity(p) \
  33563. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  33564. assert( p->pBt->inTransaction>=p->inTrans );
  33565. /*
  33566. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  33567. ** if the database supports auto-vacuum or not. Because it is used
  33568. ** within an expression that is an argument to another macro
  33569. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  33570. ** So, this macro is defined instead.
  33571. */
  33572. #ifndef SQLITE_OMIT_AUTOVACUUM
  33573. #define ISAUTOVACUUM (pBt->autoVacuum)
  33574. #else
  33575. #define ISAUTOVACUUM 0
  33576. #endif
  33577. /*
  33578. ** This structure is passed around through all the sanity checking routines
  33579. ** in order to keep track of some global state information.
  33580. */
  33581. typedef struct IntegrityCk IntegrityCk;
  33582. struct IntegrityCk {
  33583. BtShared *pBt; /* The tree being checked out */
  33584. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  33585. Pgno nPage; /* Number of pages in the database */
  33586. int *anRef; /* Number of times each page is referenced */
  33587. int mxErr; /* Stop accumulating errors when this reaches zero */
  33588. int nErr; /* Number of messages written to zErrMsg so far */
  33589. int mallocFailed; /* A memory allocation error has occurred */
  33590. StrAccum errMsg; /* Accumulate the error message text here */
  33591. };
  33592. /*
  33593. ** Read or write a two- and four-byte big-endian integer values.
  33594. */
  33595. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  33596. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  33597. #define get4byte sqlite3Get4byte
  33598. #define put4byte sqlite3Put4byte
  33599. /*
  33600. ** Internal routines that should be accessed by the btree layer only.
  33601. */
  33602. SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
  33603. SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage);
  33604. SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
  33605. SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
  33606. SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
  33607. SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
  33608. SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
  33609. SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
  33610. /************** End of btreeInt.h ********************************************/
  33611. /************** Continuing where we left off in btmutex.c ********************/
  33612. #ifndef SQLITE_OMIT_SHARED_CACHE
  33613. #if SQLITE_THREADSAFE
  33614. /*
  33615. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  33616. ** set BtShared.db to the database handle associated with p and the
  33617. ** p->locked boolean to true.
  33618. */
  33619. static void lockBtreeMutex(Btree *p){
  33620. assert( p->locked==0 );
  33621. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  33622. assert( sqlite3_mutex_held(p->db->mutex) );
  33623. sqlite3_mutex_enter(p->pBt->mutex);
  33624. p->pBt->db = p->db;
  33625. p->locked = 1;
  33626. }
  33627. /*
  33628. ** Release the BtShared mutex associated with B-Tree handle p and
  33629. ** clear the p->locked boolean.
  33630. */
  33631. static void unlockBtreeMutex(Btree *p){
  33632. assert( p->locked==1 );
  33633. assert( sqlite3_mutex_held(p->pBt->mutex) );
  33634. assert( sqlite3_mutex_held(p->db->mutex) );
  33635. assert( p->db==p->pBt->db );
  33636. sqlite3_mutex_leave(p->pBt->mutex);
  33637. p->locked = 0;
  33638. }
  33639. /*
  33640. ** Enter a mutex on the given BTree object.
  33641. **
  33642. ** If the object is not sharable, then no mutex is ever required
  33643. ** and this routine is a no-op. The underlying mutex is non-recursive.
  33644. ** But we keep a reference count in Btree.wantToLock so the behavior
  33645. ** of this interface is recursive.
  33646. **
  33647. ** To avoid deadlocks, multiple Btrees are locked in the same order
  33648. ** by all database connections. The p->pNext is a list of other
  33649. ** Btrees belonging to the same database connection as the p Btree
  33650. ** which need to be locked after p. If we cannot get a lock on
  33651. ** p, then first unlock all of the others on p->pNext, then wait
  33652. ** for the lock to become available on p, then relock all of the
  33653. ** subsequent Btrees that desire a lock.
  33654. */
  33655. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  33656. Btree *pLater;
  33657. /* Some basic sanity checking on the Btree. The list of Btrees
  33658. ** connected by pNext and pPrev should be in sorted order by
  33659. ** Btree.pBt value. All elements of the list should belong to
  33660. ** the same connection. Only shared Btrees are on the list. */
  33661. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  33662. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  33663. assert( p->pNext==0 || p->pNext->db==p->db );
  33664. assert( p->pPrev==0 || p->pPrev->db==p->db );
  33665. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  33666. /* Check for locking consistency */
  33667. assert( !p->locked || p->wantToLock>0 );
  33668. assert( p->sharable || p->wantToLock==0 );
  33669. /* We should already hold a lock on the database connection */
  33670. assert( sqlite3_mutex_held(p->db->mutex) );
  33671. /* Unless the database is sharable and unlocked, then BtShared.db
  33672. ** should already be set correctly. */
  33673. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  33674. if( !p->sharable ) return;
  33675. p->wantToLock++;
  33676. if( p->locked ) return;
  33677. /* In most cases, we should be able to acquire the lock we
  33678. ** want without having to go throught the ascending lock
  33679. ** procedure that follows. Just be sure not to block.
  33680. */
  33681. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  33682. p->pBt->db = p->db;
  33683. p->locked = 1;
  33684. return;
  33685. }
  33686. /* To avoid deadlock, first release all locks with a larger
  33687. ** BtShared address. Then acquire our lock. Then reacquire
  33688. ** the other BtShared locks that we used to hold in ascending
  33689. ** order.
  33690. */
  33691. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  33692. assert( pLater->sharable );
  33693. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  33694. assert( !pLater->locked || pLater->wantToLock>0 );
  33695. if( pLater->locked ){
  33696. unlockBtreeMutex(pLater);
  33697. }
  33698. }
  33699. lockBtreeMutex(p);
  33700. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  33701. if( pLater->wantToLock ){
  33702. lockBtreeMutex(pLater);
  33703. }
  33704. }
  33705. }
  33706. /*
  33707. ** Exit the recursive mutex on a Btree.
  33708. */
  33709. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  33710. if( p->sharable ){
  33711. assert( p->wantToLock>0 );
  33712. p->wantToLock--;
  33713. if( p->wantToLock==0 ){
  33714. unlockBtreeMutex(p);
  33715. }
  33716. }
  33717. }
  33718. #ifndef NDEBUG
  33719. /*
  33720. ** Return true if the BtShared mutex is held on the btree, or if the
  33721. ** B-Tree is not marked as sharable.
  33722. **
  33723. ** This routine is used only from within assert() statements.
  33724. */
  33725. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  33726. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  33727. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  33728. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  33729. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  33730. return (p->sharable==0 || p->locked);
  33731. }
  33732. #endif
  33733. #ifndef SQLITE_OMIT_INCRBLOB
  33734. /*
  33735. ** Enter and leave a mutex on a Btree given a cursor owned by that
  33736. ** Btree. These entry points are used by incremental I/O and can be
  33737. ** omitted if that module is not used.
  33738. */
  33739. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  33740. sqlite3BtreeEnter(pCur->pBtree);
  33741. }
  33742. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  33743. sqlite3BtreeLeave(pCur->pBtree);
  33744. }
  33745. #endif /* SQLITE_OMIT_INCRBLOB */
  33746. /*
  33747. ** Enter the mutex on every Btree associated with a database
  33748. ** connection. This is needed (for example) prior to parsing
  33749. ** a statement since we will be comparing table and column names
  33750. ** against all schemas and we do not want those schemas being
  33751. ** reset out from under us.
  33752. **
  33753. ** There is a corresponding leave-all procedures.
  33754. **
  33755. ** Enter the mutexes in accending order by BtShared pointer address
  33756. ** to avoid the possibility of deadlock when two threads with
  33757. ** two or more btrees in common both try to lock all their btrees
  33758. ** at the same instant.
  33759. */
  33760. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  33761. int i;
  33762. Btree *p, *pLater;
  33763. assert( sqlite3_mutex_held(db->mutex) );
  33764. for(i=0; i<db->nDb; i++){
  33765. p = db->aDb[i].pBt;
  33766. assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  33767. if( p && p->sharable ){
  33768. p->wantToLock++;
  33769. if( !p->locked ){
  33770. assert( p->wantToLock==1 );
  33771. while( p->pPrev ) p = p->pPrev;
  33772. while( p->locked && p->pNext ) p = p->pNext;
  33773. for(pLater = p->pNext; pLater; pLater=pLater->pNext){
  33774. if( pLater->locked ){
  33775. unlockBtreeMutex(pLater);
  33776. }
  33777. }
  33778. while( p ){
  33779. lockBtreeMutex(p);
  33780. p = p->pNext;
  33781. }
  33782. }
  33783. }
  33784. }
  33785. }
  33786. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  33787. int i;
  33788. Btree *p;
  33789. assert( sqlite3_mutex_held(db->mutex) );
  33790. for(i=0; i<db->nDb; i++){
  33791. p = db->aDb[i].pBt;
  33792. if( p && p->sharable ){
  33793. assert( p->wantToLock>0 );
  33794. p->wantToLock--;
  33795. if( p->wantToLock==0 ){
  33796. unlockBtreeMutex(p);
  33797. }
  33798. }
  33799. }
  33800. }
  33801. #ifndef NDEBUG
  33802. /*
  33803. ** Return true if the current thread holds the database connection
  33804. ** mutex and all required BtShared mutexes.
  33805. **
  33806. ** This routine is used inside assert() statements only.
  33807. */
  33808. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  33809. int i;
  33810. if( !sqlite3_mutex_held(db->mutex) ){
  33811. return 0;
  33812. }
  33813. for(i=0; i<db->nDb; i++){
  33814. Btree *p;
  33815. p = db->aDb[i].pBt;
  33816. if( p && p->sharable &&
  33817. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  33818. return 0;
  33819. }
  33820. }
  33821. return 1;
  33822. }
  33823. #endif /* NDEBUG */
  33824. /*
  33825. ** Add a new Btree pointer to a BtreeMutexArray.
  33826. ** if the pointer can possibly be shared with
  33827. ** another database connection.
  33828. **
  33829. ** The pointers are kept in sorted order by pBtree->pBt. That
  33830. ** way when we go to enter all the mutexes, we can enter them
  33831. ** in order without every having to backup and retry and without
  33832. ** worrying about deadlock.
  33833. **
  33834. ** The number of shared btrees will always be small (usually 0 or 1)
  33835. ** so an insertion sort is an adequate algorithm here.
  33836. */
  33837. SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
  33838. int i, j;
  33839. BtShared *pBt;
  33840. if( pBtree==0 || pBtree->sharable==0 ) return;
  33841. #ifndef NDEBUG
  33842. {
  33843. for(i=0; i<pArray->nMutex; i++){
  33844. assert( pArray->aBtree[i]!=pBtree );
  33845. }
  33846. }
  33847. #endif
  33848. assert( pArray->nMutex>=0 );
  33849. assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
  33850. pBt = pBtree->pBt;
  33851. for(i=0; i<pArray->nMutex; i++){
  33852. assert( pArray->aBtree[i]!=pBtree );
  33853. if( pArray->aBtree[i]->pBt>pBt ){
  33854. for(j=pArray->nMutex; j>i; j--){
  33855. pArray->aBtree[j] = pArray->aBtree[j-1];
  33856. }
  33857. pArray->aBtree[i] = pBtree;
  33858. pArray->nMutex++;
  33859. return;
  33860. }
  33861. }
  33862. pArray->aBtree[pArray->nMutex++] = pBtree;
  33863. }
  33864. /*
  33865. ** Enter the mutex of every btree in the array. This routine is
  33866. ** called at the beginning of sqlite3VdbeExec(). The mutexes are
  33867. ** exited at the end of the same function.
  33868. */
  33869. SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
  33870. int i;
  33871. for(i=0; i<pArray->nMutex; i++){
  33872. Btree *p = pArray->aBtree[i];
  33873. /* Some basic sanity checking */
  33874. assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
  33875. assert( !p->locked || p->wantToLock>0 );
  33876. /* We should already hold a lock on the database connection */
  33877. assert( sqlite3_mutex_held(p->db->mutex) );
  33878. p->wantToLock++;
  33879. if( !p->locked && p->sharable ){
  33880. lockBtreeMutex(p);
  33881. }
  33882. }
  33883. }
  33884. /*
  33885. ** Leave the mutex of every btree in the group.
  33886. */
  33887. SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
  33888. int i;
  33889. for(i=0; i<pArray->nMutex; i++){
  33890. Btree *p = pArray->aBtree[i];
  33891. /* Some basic sanity checking */
  33892. assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
  33893. assert( p->locked || !p->sharable );
  33894. assert( p->wantToLock>0 );
  33895. /* We should already hold a lock on the database connection */
  33896. assert( sqlite3_mutex_held(p->db->mutex) );
  33897. p->wantToLock--;
  33898. if( p->wantToLock==0 && p->locked ){
  33899. unlockBtreeMutex(p);
  33900. }
  33901. }
  33902. }
  33903. #else
  33904. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  33905. p->pBt->db = p->db;
  33906. }
  33907. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  33908. int i;
  33909. for(i=0; i<db->nDb; i++){
  33910. Btree *p = db->aDb[i].pBt;
  33911. if( p ){
  33912. p->pBt->db = p->db;
  33913. }
  33914. }
  33915. }
  33916. #endif /* if SQLITE_THREADSAFE */
  33917. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  33918. /************** End of btmutex.c *********************************************/
  33919. /************** Begin file btree.c *******************************************/
  33920. /*
  33921. ** 2004 April 6
  33922. **
  33923. ** The author disclaims copyright to this source code. In place of
  33924. ** a legal notice, here is a blessing:
  33925. **
  33926. ** May you do good and not evil.
  33927. ** May you find forgiveness for yourself and forgive others.
  33928. ** May you share freely, never taking more than you give.
  33929. **
  33930. *************************************************************************
  33931. ** $Id: btree.c,v 1.595 2009/04/11 16:06:15 danielk1977 Exp $
  33932. **
  33933. ** This file implements a external (disk-based) database using BTrees.
  33934. ** See the header comment on "btreeInt.h" for additional information.
  33935. ** Including a description of file format and an overview of operation.
  33936. */
  33937. /*
  33938. ** The header string that appears at the beginning of every
  33939. ** SQLite database.
  33940. */
  33941. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  33942. /*
  33943. ** Set this global variable to 1 to enable tracing using the TRACE
  33944. ** macro.
  33945. */
  33946. #if 0
  33947. int sqlite3BtreeTrace=0; /* True to enable tracing */
  33948. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  33949. #else
  33950. # define TRACE(X)
  33951. #endif
  33952. #ifndef SQLITE_OMIT_SHARED_CACHE
  33953. /*
  33954. ** A list of BtShared objects that are eligible for participation
  33955. ** in shared cache. This variable has file scope during normal builds,
  33956. ** but the test harness needs to access it so we make it global for
  33957. ** test builds.
  33958. **
  33959. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  33960. */
  33961. #ifdef SQLITE_TEST
  33962. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  33963. #else
  33964. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  33965. #endif
  33966. #endif /* SQLITE_OMIT_SHARED_CACHE */
  33967. #ifndef SQLITE_OMIT_SHARED_CACHE
  33968. /*
  33969. ** Enable or disable the shared pager and schema features.
  33970. **
  33971. ** This routine has no effect on existing database connections.
  33972. ** The shared cache setting effects only future calls to
  33973. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  33974. */
  33975. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  33976. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  33977. return SQLITE_OK;
  33978. }
  33979. #endif
  33980. /*
  33981. ** Forward declaration
  33982. */
  33983. static int checkForReadConflicts(Btree*, Pgno, BtCursor*, i64);
  33984. #ifdef SQLITE_OMIT_SHARED_CACHE
  33985. /*
  33986. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  33987. ** and clearAllSharedCacheTableLocks()
  33988. ** manipulate entries in the BtShared.pLock linked list used to store
  33989. ** shared-cache table level locks. If the library is compiled with the
  33990. ** shared-cache feature disabled, then there is only ever one user
  33991. ** of each BtShared structure and so this locking is not necessary.
  33992. ** So define the lock related functions as no-ops.
  33993. */
  33994. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  33995. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  33996. #define clearAllSharedCacheTableLocks(a)
  33997. #endif
  33998. #ifndef SQLITE_OMIT_SHARED_CACHE
  33999. /*
  34000. ** Query to see if btree handle p may obtain a lock of type eLock
  34001. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  34002. ** SQLITE_OK if the lock may be obtained (by calling
  34003. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  34004. */
  34005. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  34006. BtShared *pBt = p->pBt;
  34007. BtLock *pIter;
  34008. assert( sqlite3BtreeHoldsMutex(p) );
  34009. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  34010. assert( p->db!=0 );
  34011. /* If requesting a write-lock, then the Btree must have an open write
  34012. ** transaction on this file. And, obviously, for this to be so there
  34013. ** must be an open write transaction on the file itself.
  34014. */
  34015. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  34016. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  34017. /* This is a no-op if the shared-cache is not enabled */
  34018. if( !p->sharable ){
  34019. return SQLITE_OK;
  34020. }
  34021. /* If some other connection is holding an exclusive lock, the
  34022. ** requested lock may not be obtained.
  34023. */
  34024. if( pBt->pWriter!=p && pBt->isExclusive ){
  34025. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  34026. return SQLITE_LOCKED_SHAREDCACHE;
  34027. }
  34028. /* This (along with setSharedCacheTableLock()) is where
  34029. ** the ReadUncommitted flag is dealt with.
  34030. ** If the caller is querying for a read-lock on any table
  34031. ** other than the sqlite_master table (table 1) and if the ReadUncommitted
  34032. ** flag is set, then the lock granted even if there are write-locks
  34033. ** on the table. If a write-lock is requested, the ReadUncommitted flag
  34034. ** is not considered.
  34035. **
  34036. ** In function setSharedCacheTableLock(), if a read-lock is demanded and the
  34037. ** ReadUncommitted flag is set, no entry is added to the locks list
  34038. ** (BtShared.pLock).
  34039. **
  34040. ** To summarize: If the ReadUncommitted flag is set, then read cursors
  34041. ** on non-schema tables do not create or respect table locks. The locking
  34042. ** procedure for a write-cursor does not change.
  34043. */
  34044. if(
  34045. 0==(p->db->flags&SQLITE_ReadUncommitted) ||
  34046. eLock==WRITE_LOCK ||
  34047. iTab==MASTER_ROOT
  34048. ){
  34049. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  34050. /* The condition (pIter->eLock!=eLock) in the following if(...)
  34051. ** statement is a simplification of:
  34052. **
  34053. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  34054. **
  34055. ** since we know that if eLock==WRITE_LOCK, then no other connection
  34056. ** may hold a WRITE_LOCK on any table in this file (since there can
  34057. ** only be a single writer).
  34058. */
  34059. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  34060. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  34061. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  34062. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  34063. if( eLock==WRITE_LOCK ){
  34064. assert( p==pBt->pWriter );
  34065. pBt->isPending = 1;
  34066. }
  34067. return SQLITE_LOCKED_SHAREDCACHE;
  34068. }
  34069. }
  34070. }
  34071. return SQLITE_OK;
  34072. }
  34073. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  34074. #ifndef SQLITE_OMIT_SHARED_CACHE
  34075. /*
  34076. ** Add a lock on the table with root-page iTable to the shared-btree used
  34077. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  34078. ** WRITE_LOCK.
  34079. **
  34080. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
  34081. ** SQLITE_NOMEM may also be returned.
  34082. */
  34083. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  34084. BtShared *pBt = p->pBt;
  34085. BtLock *pLock = 0;
  34086. BtLock *pIter;
  34087. assert( sqlite3BtreeHoldsMutex(p) );
  34088. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  34089. assert( p->db!=0 );
  34090. /* This is a no-op if the shared-cache is not enabled */
  34091. if( !p->sharable ){
  34092. return SQLITE_OK;
  34093. }
  34094. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  34095. /* If the read-uncommitted flag is set and a read-lock is requested on
  34096. ** a non-schema table, then the lock is always granted. Return early
  34097. ** without adding an entry to the BtShared.pLock list. See
  34098. ** comment in function querySharedCacheTableLock() for more info
  34099. ** on handling the ReadUncommitted flag.
  34100. */
  34101. if(
  34102. (p->db->flags&SQLITE_ReadUncommitted) &&
  34103. (eLock==READ_LOCK) &&
  34104. iTable!=MASTER_ROOT
  34105. ){
  34106. return SQLITE_OK;
  34107. }
  34108. /* First search the list for an existing lock on this table. */
  34109. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  34110. if( pIter->iTable==iTable && pIter->pBtree==p ){
  34111. pLock = pIter;
  34112. break;
  34113. }
  34114. }
  34115. /* If the above search did not find a BtLock struct associating Btree p
  34116. ** with table iTable, allocate one and link it into the list.
  34117. */
  34118. if( !pLock ){
  34119. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  34120. if( !pLock ){
  34121. return SQLITE_NOMEM;
  34122. }
  34123. pLock->iTable = iTable;
  34124. pLock->pBtree = p;
  34125. pLock->pNext = pBt->pLock;
  34126. pBt->pLock = pLock;
  34127. }
  34128. /* Set the BtLock.eLock variable to the maximum of the current lock
  34129. ** and the requested lock. This means if a write-lock was already held
  34130. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  34131. */
  34132. assert( WRITE_LOCK>READ_LOCK );
  34133. if( eLock>pLock->eLock ){
  34134. pLock->eLock = eLock;
  34135. }
  34136. return SQLITE_OK;
  34137. }
  34138. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  34139. #ifndef SQLITE_OMIT_SHARED_CACHE
  34140. /*
  34141. ** Release all the table locks (locks obtained via calls to
  34142. ** the setSharedCacheTableLock() procedure) held by Btree handle p.
  34143. **
  34144. ** This function assumes that handle p has an open read or write
  34145. ** transaction. If it does not, then the BtShared.isPending variable
  34146. ** may be incorrectly cleared.
  34147. */
  34148. static void clearAllSharedCacheTableLocks(Btree *p){
  34149. BtShared *pBt = p->pBt;
  34150. BtLock **ppIter = &pBt->pLock;
  34151. assert( sqlite3BtreeHoldsMutex(p) );
  34152. assert( p->sharable || 0==*ppIter );
  34153. assert( p->inTrans>0 );
  34154. while( *ppIter ){
  34155. BtLock *pLock = *ppIter;
  34156. assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
  34157. assert( pLock->pBtree->inTrans>=pLock->eLock );
  34158. if( pLock->pBtree==p ){
  34159. *ppIter = pLock->pNext;
  34160. sqlite3_free(pLock);
  34161. }else{
  34162. ppIter = &pLock->pNext;
  34163. }
  34164. }
  34165. assert( pBt->isPending==0 || pBt->pWriter );
  34166. if( pBt->pWriter==p ){
  34167. pBt->pWriter = 0;
  34168. pBt->isExclusive = 0;
  34169. pBt->isPending = 0;
  34170. }else if( pBt->nTransaction==2 ){
  34171. /* This function is called when connection p is concluding its
  34172. ** transaction. If there currently exists a writer, and p is not
  34173. ** that writer, then the number of locks held by connections other
  34174. ** than the writer must be about to drop to zero. In this case
  34175. ** set the isPending flag to 0.
  34176. **
  34177. ** If there is not currently a writer, then BtShared.isPending must
  34178. ** be zero already. So this next line is harmless in that case.
  34179. */
  34180. pBt->isPending = 0;
  34181. }
  34182. }
  34183. #endif /* SQLITE_OMIT_SHARED_CACHE */
  34184. static void releasePage(MemPage *pPage); /* Forward reference */
  34185. /*
  34186. ** Verify that the cursor holds a mutex on the BtShared
  34187. */
  34188. #ifndef NDEBUG
  34189. static int cursorHoldsMutex(BtCursor *p){
  34190. return sqlite3_mutex_held(p->pBt->mutex);
  34191. }
  34192. #endif
  34193. #ifndef SQLITE_OMIT_INCRBLOB
  34194. /*
  34195. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  34196. */
  34197. static void invalidateOverflowCache(BtCursor *pCur){
  34198. assert( cursorHoldsMutex(pCur) );
  34199. sqlite3_free(pCur->aOverflow);
  34200. pCur->aOverflow = 0;
  34201. }
  34202. /*
  34203. ** Invalidate the overflow page-list cache for all cursors opened
  34204. ** on the shared btree structure pBt.
  34205. */
  34206. static void invalidateAllOverflowCache(BtShared *pBt){
  34207. BtCursor *p;
  34208. assert( sqlite3_mutex_held(pBt->mutex) );
  34209. for(p=pBt->pCursor; p; p=p->pNext){
  34210. invalidateOverflowCache(p);
  34211. }
  34212. }
  34213. #else
  34214. #define invalidateOverflowCache(x)
  34215. #define invalidateAllOverflowCache(x)
  34216. #endif
  34217. /*
  34218. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  34219. ** when a page that previously contained data becomes a free-list leaf
  34220. ** page.
  34221. **
  34222. ** The BtShared.pHasContent bitvec exists to work around an obscure
  34223. ** bug caused by the interaction of two useful IO optimizations surrounding
  34224. ** free-list leaf pages:
  34225. **
  34226. ** 1) When all data is deleted from a page and the page becomes
  34227. ** a free-list leaf page, the page is not written to the database
  34228. ** (as free-list leaf pages contain no meaningful data). Sometimes
  34229. ** such a page is not even journalled (as it will not be modified,
  34230. ** why bother journalling it?).
  34231. **
  34232. ** 2) When a free-list leaf page is reused, its content is not read
  34233. ** from the database or written to the journal file (why should it
  34234. ** be, if it is not at all meaningful?).
  34235. **
  34236. ** By themselves, these optimizations work fine and provide a handy
  34237. ** performance boost to bulk delete or insert operations. However, if
  34238. ** a page is moved to the free-list and then reused within the same
  34239. ** transaction, a problem comes up. If the page is not journalled when
  34240. ** it is moved to the free-list and it is also not journalled when it
  34241. ** is extracted from the free-list and reused, then the original data
  34242. ** may be lost. In the event of a rollback, it may not be possible
  34243. ** to restore the database to its original configuration.
  34244. **
  34245. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  34246. ** moved to become a free-list leaf page, the corresponding bit is
  34247. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  34248. ** optimization 2 above is ommitted if the corresponding bit is already
  34249. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  34250. ** at the end of every transaction.
  34251. */
  34252. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  34253. int rc = SQLITE_OK;
  34254. if( !pBt->pHasContent ){
  34255. int nPage;
  34256. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  34257. if( rc==SQLITE_OK ){
  34258. pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
  34259. if( !pBt->pHasContent ){
  34260. rc = SQLITE_NOMEM;
  34261. }
  34262. }
  34263. }
  34264. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  34265. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  34266. }
  34267. return rc;
  34268. }
  34269. /*
  34270. ** Query the BtShared.pHasContent vector.
  34271. **
  34272. ** This function is called when a free-list leaf page is removed from the
  34273. ** free-list for reuse. It returns false if it is safe to retrieve the
  34274. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  34275. */
  34276. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  34277. Bitvec *p = pBt->pHasContent;
  34278. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  34279. }
  34280. /*
  34281. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  34282. ** invoked at the conclusion of each write-transaction.
  34283. */
  34284. static void btreeClearHasContent(BtShared *pBt){
  34285. sqlite3BitvecDestroy(pBt->pHasContent);
  34286. pBt->pHasContent = 0;
  34287. }
  34288. /*
  34289. ** Save the current cursor position in the variables BtCursor.nKey
  34290. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  34291. */
  34292. static int saveCursorPosition(BtCursor *pCur){
  34293. int rc;
  34294. assert( CURSOR_VALID==pCur->eState );
  34295. assert( 0==pCur->pKey );
  34296. assert( cursorHoldsMutex(pCur) );
  34297. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  34298. /* If this is an intKey table, then the above call to BtreeKeySize()
  34299. ** stores the integer key in pCur->nKey. In this case this value is
  34300. ** all that is required. Otherwise, if pCur is not open on an intKey
  34301. ** table, then malloc space for and store the pCur->nKey bytes of key
  34302. ** data.
  34303. */
  34304. if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
  34305. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  34306. if( pKey ){
  34307. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  34308. if( rc==SQLITE_OK ){
  34309. pCur->pKey = pKey;
  34310. }else{
  34311. sqlite3_free(pKey);
  34312. }
  34313. }else{
  34314. rc = SQLITE_NOMEM;
  34315. }
  34316. }
  34317. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  34318. if( rc==SQLITE_OK ){
  34319. int i;
  34320. for(i=0; i<=pCur->iPage; i++){
  34321. releasePage(pCur->apPage[i]);
  34322. pCur->apPage[i] = 0;
  34323. }
  34324. pCur->iPage = -1;
  34325. pCur->eState = CURSOR_REQUIRESEEK;
  34326. }
  34327. invalidateOverflowCache(pCur);
  34328. return rc;
  34329. }
  34330. /*
  34331. ** Save the positions of all cursors except pExcept open on the table
  34332. ** with root-page iRoot. Usually, this is called just before cursor
  34333. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  34334. */
  34335. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  34336. BtCursor *p;
  34337. assert( sqlite3_mutex_held(pBt->mutex) );
  34338. assert( pExcept==0 || pExcept->pBt==pBt );
  34339. for(p=pBt->pCursor; p; p=p->pNext){
  34340. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
  34341. p->eState==CURSOR_VALID ){
  34342. int rc = saveCursorPosition(p);
  34343. if( SQLITE_OK!=rc ){
  34344. return rc;
  34345. }
  34346. }
  34347. }
  34348. return SQLITE_OK;
  34349. }
  34350. /*
  34351. ** Clear the current cursor position.
  34352. */
  34353. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  34354. assert( cursorHoldsMutex(pCur) );
  34355. sqlite3_free(pCur->pKey);
  34356. pCur->pKey = 0;
  34357. pCur->eState = CURSOR_INVALID;
  34358. }
  34359. /*
  34360. ** Restore the cursor to the position it was in (or as close to as possible)
  34361. ** when saveCursorPosition() was called. Note that this call deletes the
  34362. ** saved position info stored by saveCursorPosition(), so there can be
  34363. ** at most one effective restoreCursorPosition() call after each
  34364. ** saveCursorPosition().
  34365. */
  34366. SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
  34367. int rc;
  34368. assert( cursorHoldsMutex(pCur) );
  34369. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  34370. if( pCur->eState==CURSOR_FAULT ){
  34371. return pCur->skip;
  34372. }
  34373. pCur->eState = CURSOR_INVALID;
  34374. rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
  34375. if( rc==SQLITE_OK ){
  34376. sqlite3_free(pCur->pKey);
  34377. pCur->pKey = 0;
  34378. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  34379. }
  34380. return rc;
  34381. }
  34382. #define restoreCursorPosition(p) \
  34383. (p->eState>=CURSOR_REQUIRESEEK ? \
  34384. sqlite3BtreeRestoreCursorPosition(p) : \
  34385. SQLITE_OK)
  34386. /*
  34387. ** Determine whether or not a cursor has moved from the position it
  34388. ** was last placed at. Cursors can move when the row they are pointing
  34389. ** at is deleted out from under them.
  34390. **
  34391. ** This routine returns an error code if something goes wrong. The
  34392. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  34393. */
  34394. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  34395. int rc;
  34396. rc = restoreCursorPosition(pCur);
  34397. if( rc ){
  34398. *pHasMoved = 1;
  34399. return rc;
  34400. }
  34401. if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
  34402. *pHasMoved = 1;
  34403. }else{
  34404. *pHasMoved = 0;
  34405. }
  34406. return SQLITE_OK;
  34407. }
  34408. #ifndef SQLITE_OMIT_AUTOVACUUM
  34409. /*
  34410. ** Given a page number of a regular database page, return the page
  34411. ** number for the pointer-map page that contains the entry for the
  34412. ** input page number.
  34413. */
  34414. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  34415. int nPagesPerMapPage;
  34416. Pgno iPtrMap, ret;
  34417. assert( sqlite3_mutex_held(pBt->mutex) );
  34418. nPagesPerMapPage = (pBt->usableSize/5)+1;
  34419. iPtrMap = (pgno-2)/nPagesPerMapPage;
  34420. ret = (iPtrMap*nPagesPerMapPage) + 2;
  34421. if( ret==PENDING_BYTE_PAGE(pBt) ){
  34422. ret++;
  34423. }
  34424. return ret;
  34425. }
  34426. /*
  34427. ** Write an entry into the pointer map.
  34428. **
  34429. ** This routine updates the pointer map entry for page number 'key'
  34430. ** so that it maps to type 'eType' and parent page number 'pgno'.
  34431. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  34432. */
  34433. static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
  34434. DbPage *pDbPage; /* The pointer map page */
  34435. u8 *pPtrmap; /* The pointer map data */
  34436. Pgno iPtrmap; /* The pointer map page number */
  34437. int offset; /* Offset in pointer map page */
  34438. int rc;
  34439. assert( sqlite3_mutex_held(pBt->mutex) );
  34440. /* The master-journal page number must never be used as a pointer map page */
  34441. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  34442. assert( pBt->autoVacuum );
  34443. if( key==0 ){
  34444. return SQLITE_CORRUPT_BKPT;
  34445. }
  34446. iPtrmap = PTRMAP_PAGENO(pBt, key);
  34447. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  34448. if( rc!=SQLITE_OK ){
  34449. return rc;
  34450. }
  34451. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  34452. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  34453. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  34454. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  34455. rc = sqlite3PagerWrite(pDbPage);
  34456. if( rc==SQLITE_OK ){
  34457. pPtrmap[offset] = eType;
  34458. put4byte(&pPtrmap[offset+1], parent);
  34459. }
  34460. }
  34461. sqlite3PagerUnref(pDbPage);
  34462. return rc;
  34463. }
  34464. /*
  34465. ** Read an entry from the pointer map.
  34466. **
  34467. ** This routine retrieves the pointer map entry for page 'key', writing
  34468. ** the type and parent page number to *pEType and *pPgno respectively.
  34469. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  34470. */
  34471. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  34472. DbPage *pDbPage; /* The pointer map page */
  34473. int iPtrmap; /* Pointer map page index */
  34474. u8 *pPtrmap; /* Pointer map page data */
  34475. int offset; /* Offset of entry in pointer map */
  34476. int rc;
  34477. assert( sqlite3_mutex_held(pBt->mutex) );
  34478. iPtrmap = PTRMAP_PAGENO(pBt, key);
  34479. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  34480. if( rc!=0 ){
  34481. return rc;
  34482. }
  34483. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  34484. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  34485. assert( pEType!=0 );
  34486. *pEType = pPtrmap[offset];
  34487. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  34488. sqlite3PagerUnref(pDbPage);
  34489. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  34490. return SQLITE_OK;
  34491. }
  34492. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  34493. #define ptrmapPut(w,x,y,z) SQLITE_OK
  34494. #define ptrmapGet(w,x,y,z) SQLITE_OK
  34495. #define ptrmapPutOvfl(y,z) SQLITE_OK
  34496. #endif
  34497. /*
  34498. ** Given a btree page and a cell index (0 means the first cell on
  34499. ** the page, 1 means the second cell, and so forth) return a pointer
  34500. ** to the cell content.
  34501. **
  34502. ** This routine works only for pages that do not contain overflow cells.
  34503. */
  34504. #define findCell(P,I) \
  34505. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
  34506. /*
  34507. ** This a more complex version of findCell() that works for
  34508. ** pages that do contain overflow cells. See insert
  34509. */
  34510. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  34511. int i;
  34512. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34513. for(i=pPage->nOverflow-1; i>=0; i--){
  34514. int k;
  34515. struct _OvflCell *pOvfl;
  34516. pOvfl = &pPage->aOvfl[i];
  34517. k = pOvfl->idx;
  34518. if( k<=iCell ){
  34519. if( k==iCell ){
  34520. return pOvfl->pCell;
  34521. }
  34522. iCell--;
  34523. }
  34524. }
  34525. return findCell(pPage, iCell);
  34526. }
  34527. /*
  34528. ** Parse a cell content block and fill in the CellInfo structure. There
  34529. ** are two versions of this function. sqlite3BtreeParseCell() takes a
  34530. ** cell index as the second argument and sqlite3BtreeParseCellPtr()
  34531. ** takes a pointer to the body of the cell as its second argument.
  34532. **
  34533. ** Within this file, the parseCell() macro can be called instead of
  34534. ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
  34535. */
  34536. SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
  34537. MemPage *pPage, /* Page containing the cell */
  34538. u8 *pCell, /* Pointer to the cell text. */
  34539. CellInfo *pInfo /* Fill in this structure */
  34540. ){
  34541. u16 n; /* Number bytes in cell content header */
  34542. u32 nPayload; /* Number of bytes of cell payload */
  34543. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34544. pInfo->pCell = pCell;
  34545. assert( pPage->leaf==0 || pPage->leaf==1 );
  34546. n = pPage->childPtrSize;
  34547. assert( n==4-4*pPage->leaf );
  34548. if( pPage->intKey ){
  34549. if( pPage->hasData ){
  34550. n += getVarint32(&pCell[n], nPayload);
  34551. }else{
  34552. nPayload = 0;
  34553. }
  34554. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  34555. pInfo->nData = nPayload;
  34556. }else{
  34557. pInfo->nData = 0;
  34558. n += getVarint32(&pCell[n], nPayload);
  34559. pInfo->nKey = nPayload;
  34560. }
  34561. pInfo->nPayload = nPayload;
  34562. pInfo->nHeader = n;
  34563. if( likely(nPayload<=pPage->maxLocal) ){
  34564. /* This is the (easy) common case where the entire payload fits
  34565. ** on the local page. No overflow is required.
  34566. */
  34567. int nSize; /* Total size of cell content in bytes */
  34568. nSize = nPayload + n;
  34569. pInfo->nLocal = (u16)nPayload;
  34570. pInfo->iOverflow = 0;
  34571. if( (nSize & ~3)==0 ){
  34572. nSize = 4; /* Minimum cell size is 4 */
  34573. }
  34574. pInfo->nSize = (u16)nSize;
  34575. }else{
  34576. /* If the payload will not fit completely on the local page, we have
  34577. ** to decide how much to store locally and how much to spill onto
  34578. ** overflow pages. The strategy is to minimize the amount of unused
  34579. ** space on overflow pages while keeping the amount of local storage
  34580. ** in between minLocal and maxLocal.
  34581. **
  34582. ** Warning: changing the way overflow payload is distributed in any
  34583. ** way will result in an incompatible file format.
  34584. */
  34585. int minLocal; /* Minimum amount of payload held locally */
  34586. int maxLocal; /* Maximum amount of payload held locally */
  34587. int surplus; /* Overflow payload available for local storage */
  34588. minLocal = pPage->minLocal;
  34589. maxLocal = pPage->maxLocal;
  34590. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  34591. if( surplus <= maxLocal ){
  34592. pInfo->nLocal = (u16)surplus;
  34593. }else{
  34594. pInfo->nLocal = (u16)minLocal;
  34595. }
  34596. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  34597. pInfo->nSize = pInfo->iOverflow + 4;
  34598. }
  34599. }
  34600. #define parseCell(pPage, iCell, pInfo) \
  34601. sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  34602. SQLITE_PRIVATE void sqlite3BtreeParseCell(
  34603. MemPage *pPage, /* Page containing the cell */
  34604. int iCell, /* The cell index. First cell is 0 */
  34605. CellInfo *pInfo /* Fill in this structure */
  34606. ){
  34607. parseCell(pPage, iCell, pInfo);
  34608. }
  34609. /*
  34610. ** Compute the total number of bytes that a Cell needs in the cell
  34611. ** data area of the btree-page. The return number includes the cell
  34612. ** data header and the local payload, but not any overflow page or
  34613. ** the space used by the cell pointer.
  34614. */
  34615. #ifndef NDEBUG
  34616. static u16 cellSize(MemPage *pPage, int iCell){
  34617. CellInfo info;
  34618. sqlite3BtreeParseCell(pPage, iCell, &info);
  34619. return info.nSize;
  34620. }
  34621. #endif
  34622. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  34623. CellInfo info;
  34624. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  34625. return info.nSize;
  34626. }
  34627. #ifndef SQLITE_OMIT_AUTOVACUUM
  34628. /*
  34629. ** If the cell pCell, part of page pPage contains a pointer
  34630. ** to an overflow page, insert an entry into the pointer-map
  34631. ** for the overflow page.
  34632. */
  34633. static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
  34634. CellInfo info;
  34635. assert( pCell!=0 );
  34636. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  34637. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  34638. if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
  34639. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  34640. return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
  34641. }
  34642. return SQLITE_OK;
  34643. }
  34644. /*
  34645. ** If the cell with index iCell on page pPage contains a pointer
  34646. ** to an overflow page, insert an entry into the pointer-map
  34647. ** for the overflow page.
  34648. */
  34649. static int ptrmapPutOvfl(MemPage *pPage, int iCell){
  34650. u8 *pCell;
  34651. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34652. pCell = findOverflowCell(pPage, iCell);
  34653. return ptrmapPutOvflPtr(pPage, pCell);
  34654. }
  34655. #endif
  34656. /*
  34657. ** Defragment the page given. All Cells are moved to the
  34658. ** end of the page and all free space is collected into one
  34659. ** big FreeBlk that occurs in between the header and cell
  34660. ** pointer array and the cell content area.
  34661. */
  34662. static int defragmentPage(MemPage *pPage){
  34663. int i; /* Loop counter */
  34664. int pc; /* Address of a i-th cell */
  34665. int addr; /* Offset of first byte after cell pointer array */
  34666. int hdr; /* Offset to the page header */
  34667. int size; /* Size of a cell */
  34668. int usableSize; /* Number of usable bytes on a page */
  34669. int cellOffset; /* Offset to the cell pointer array */
  34670. int cbrk; /* Offset to the cell content area */
  34671. int nCell; /* Number of cells on the page */
  34672. unsigned char *data; /* The page data */
  34673. unsigned char *temp; /* Temp area for cell content */
  34674. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34675. assert( pPage->pBt!=0 );
  34676. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  34677. assert( pPage->nOverflow==0 );
  34678. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34679. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  34680. data = pPage->aData;
  34681. hdr = pPage->hdrOffset;
  34682. cellOffset = pPage->cellOffset;
  34683. nCell = pPage->nCell;
  34684. assert( nCell==get2byte(&data[hdr+3]) );
  34685. usableSize = pPage->pBt->usableSize;
  34686. cbrk = get2byte(&data[hdr+5]);
  34687. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  34688. cbrk = usableSize;
  34689. for(i=0; i<nCell; i++){
  34690. u8 *pAddr; /* The i-th cell pointer */
  34691. pAddr = &data[cellOffset + i*2];
  34692. pc = get2byte(pAddr);
  34693. if( pc>=usableSize ){
  34694. return SQLITE_CORRUPT_BKPT;
  34695. }
  34696. size = cellSizePtr(pPage, &temp[pc]);
  34697. cbrk -= size;
  34698. if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
  34699. return SQLITE_CORRUPT_BKPT;
  34700. }
  34701. assert( cbrk+size<=usableSize && cbrk>=0 );
  34702. memcpy(&data[cbrk], &temp[pc], size);
  34703. put2byte(pAddr, cbrk);
  34704. }
  34705. assert( cbrk>=cellOffset+2*nCell );
  34706. put2byte(&data[hdr+5], cbrk);
  34707. data[hdr+1] = 0;
  34708. data[hdr+2] = 0;
  34709. data[hdr+7] = 0;
  34710. addr = cellOffset+2*nCell;
  34711. memset(&data[addr], 0, cbrk-addr);
  34712. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34713. if( cbrk-addr!=pPage->nFree ){
  34714. return SQLITE_CORRUPT_BKPT;
  34715. }
  34716. return SQLITE_OK;
  34717. }
  34718. /*
  34719. ** Allocate nByte bytes of space from within the B-Tree page passed
  34720. ** as the first argument. Return the index into pPage->aData[] of the
  34721. ** first byte of allocated space.
  34722. **
  34723. ** The caller guarantees that the space between the end of the cell-offset
  34724. ** array and the start of the cell-content area is at least nByte bytes
  34725. ** in size. So this routine can never fail.
  34726. **
  34727. ** If there are already 60 or more bytes of fragments within the page,
  34728. ** the page is defragmented before returning. If this were not done there
  34729. ** is a chance that the number of fragmented bytes could eventually
  34730. ** overflow the single-byte field of the page-header in which this value
  34731. ** is stored.
  34732. */
  34733. static int allocateSpace(MemPage *pPage, int nByte){
  34734. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  34735. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  34736. int nFrag; /* Number of fragmented bytes on pPage */
  34737. int top;
  34738. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34739. assert( pPage->pBt );
  34740. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34741. assert( nByte>=0 ); /* Minimum cell size is 4 */
  34742. assert( pPage->nFree>=nByte );
  34743. assert( pPage->nOverflow==0 );
  34744. /* Assert that the space between the cell-offset array and the
  34745. ** cell-content area is greater than nByte bytes.
  34746. */
  34747. assert( nByte <= (
  34748. get2byte(&data[hdr+5])-(hdr+8+(pPage->leaf?0:4)+2*get2byte(&data[hdr+3]))
  34749. ));
  34750. pPage->nFree -= (u16)nByte;
  34751. nFrag = data[hdr+7];
  34752. if( nFrag>=60 ){
  34753. defragmentPage(pPage);
  34754. }else{
  34755. /* Search the freelist looking for a free slot big enough to satisfy
  34756. ** the request. The allocation is made from the first free slot in
  34757. ** the list that is large enough to accomadate it.
  34758. */
  34759. int pc, addr;
  34760. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  34761. int size = get2byte(&data[pc+2]); /* Size of free slot */
  34762. if( size>=nByte ){
  34763. int x = size - nByte;
  34764. if( x<4 ){
  34765. /* Remove the slot from the free-list. Update the number of
  34766. ** fragmented bytes within the page. */
  34767. memcpy(&data[addr], &data[pc], 2);
  34768. data[hdr+7] = (u8)(nFrag + x);
  34769. }else{
  34770. /* The slot remains on the free-list. Reduce its size to account
  34771. ** for the portion used by the new allocation. */
  34772. put2byte(&data[pc+2], x);
  34773. }
  34774. return pc + x;
  34775. }
  34776. }
  34777. }
  34778. /* Allocate memory from the gap in between the cell pointer array
  34779. ** and the cell content area.
  34780. */
  34781. top = get2byte(&data[hdr+5]) - nByte;
  34782. put2byte(&data[hdr+5], top);
  34783. return top;
  34784. }
  34785. /*
  34786. ** Return a section of the pPage->aData to the freelist.
  34787. ** The first byte of the new free block is pPage->aDisk[start]
  34788. ** and the size of the block is "size" bytes.
  34789. **
  34790. ** Most of the effort here is involved in coalesing adjacent
  34791. ** free blocks into a single big free block.
  34792. */
  34793. static int freeSpace(MemPage *pPage, int start, int size){
  34794. int addr, pbegin, hdr;
  34795. unsigned char *data = pPage->aData;
  34796. assert( pPage->pBt!=0 );
  34797. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34798. assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
  34799. assert( (start + size)<=pPage->pBt->usableSize );
  34800. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34801. assert( size>=0 ); /* Minimum cell size is 4 */
  34802. #ifdef SQLITE_SECURE_DELETE
  34803. /* Overwrite deleted information with zeros when the SECURE_DELETE
  34804. ** option is enabled at compile-time */
  34805. memset(&data[start], 0, size);
  34806. #endif
  34807. /* Add the space back into the linked list of freeblocks */
  34808. hdr = pPage->hdrOffset;
  34809. addr = hdr + 1;
  34810. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  34811. assert( pbegin<=pPage->pBt->usableSize-4 );
  34812. if( pbegin<=addr ) {
  34813. return SQLITE_CORRUPT_BKPT;
  34814. }
  34815. addr = pbegin;
  34816. }
  34817. if ( pbegin>pPage->pBt->usableSize-4 ) {
  34818. return SQLITE_CORRUPT_BKPT;
  34819. }
  34820. assert( pbegin>addr || pbegin==0 );
  34821. put2byte(&data[addr], start);
  34822. put2byte(&data[start], pbegin);
  34823. put2byte(&data[start+2], size);
  34824. pPage->nFree += (u16)size;
  34825. /* Coalesce adjacent free blocks */
  34826. addr = pPage->hdrOffset + 1;
  34827. while( (pbegin = get2byte(&data[addr]))>0 ){
  34828. int pnext, psize, x;
  34829. assert( pbegin>addr );
  34830. assert( pbegin<=pPage->pBt->usableSize-4 );
  34831. pnext = get2byte(&data[pbegin]);
  34832. psize = get2byte(&data[pbegin+2]);
  34833. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  34834. int frag = pnext - (pbegin+psize);
  34835. if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
  34836. return SQLITE_CORRUPT_BKPT;
  34837. }
  34838. data[pPage->hdrOffset+7] -= (u8)frag;
  34839. x = get2byte(&data[pnext]);
  34840. put2byte(&data[pbegin], x);
  34841. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  34842. put2byte(&data[pbegin+2], x);
  34843. }else{
  34844. addr = pbegin;
  34845. }
  34846. }
  34847. /* If the cell content area begins with a freeblock, remove it. */
  34848. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  34849. int top;
  34850. pbegin = get2byte(&data[hdr+1]);
  34851. memcpy(&data[hdr+1], &data[pbegin], 2);
  34852. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  34853. put2byte(&data[hdr+5], top);
  34854. }
  34855. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34856. return SQLITE_OK;
  34857. }
  34858. /*
  34859. ** Decode the flags byte (the first byte of the header) for a page
  34860. ** and initialize fields of the MemPage structure accordingly.
  34861. **
  34862. ** Only the following combinations are supported. Anything different
  34863. ** indicates a corrupt database files:
  34864. **
  34865. ** PTF_ZERODATA
  34866. ** PTF_ZERODATA | PTF_LEAF
  34867. ** PTF_LEAFDATA | PTF_INTKEY
  34868. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  34869. */
  34870. static int decodeFlags(MemPage *pPage, int flagByte){
  34871. BtShared *pBt; /* A copy of pPage->pBt */
  34872. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  34873. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34874. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  34875. flagByte &= ~PTF_LEAF;
  34876. pPage->childPtrSize = 4-4*pPage->leaf;
  34877. pBt = pPage->pBt;
  34878. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  34879. pPage->intKey = 1;
  34880. pPage->hasData = pPage->leaf;
  34881. pPage->maxLocal = pBt->maxLeaf;
  34882. pPage->minLocal = pBt->minLeaf;
  34883. }else if( flagByte==PTF_ZERODATA ){
  34884. pPage->intKey = 0;
  34885. pPage->hasData = 0;
  34886. pPage->maxLocal = pBt->maxLocal;
  34887. pPage->minLocal = pBt->minLocal;
  34888. }else{
  34889. return SQLITE_CORRUPT_BKPT;
  34890. }
  34891. return SQLITE_OK;
  34892. }
  34893. /*
  34894. ** Initialize the auxiliary information for a disk block.
  34895. **
  34896. ** Return SQLITE_OK on success. If we see that the page does
  34897. ** not contain a well-formed database page, then return
  34898. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  34899. ** guarantee that the page is well-formed. It only shows that
  34900. ** we failed to detect any corruption.
  34901. */
  34902. SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage){
  34903. assert( pPage->pBt!=0 );
  34904. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  34905. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  34906. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  34907. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  34908. if( !pPage->isInit ){
  34909. u16 pc; /* Address of a freeblock within pPage->aData[] */
  34910. u8 hdr; /* Offset to beginning of page header */
  34911. u8 *data; /* Equal to pPage->aData */
  34912. BtShared *pBt; /* The main btree structure */
  34913. u16 usableSize; /* Amount of usable space on each page */
  34914. u16 cellOffset; /* Offset from start of page to first cell pointer */
  34915. u16 nFree; /* Number of unused bytes on the page */
  34916. u16 top; /* First byte of the cell content area */
  34917. pBt = pPage->pBt;
  34918. hdr = pPage->hdrOffset;
  34919. data = pPage->aData;
  34920. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  34921. assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
  34922. pPage->maskPage = pBt->pageSize - 1;
  34923. pPage->nOverflow = 0;
  34924. usableSize = pBt->usableSize;
  34925. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  34926. top = get2byte(&data[hdr+5]);
  34927. pPage->nCell = get2byte(&data[hdr+3]);
  34928. if( pPage->nCell>MX_CELL(pBt) ){
  34929. /* To many cells for a single page. The page must be corrupt */
  34930. return SQLITE_CORRUPT_BKPT;
  34931. }
  34932. /* Compute the total free space on the page */
  34933. pc = get2byte(&data[hdr+1]);
  34934. nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
  34935. while( pc>0 ){
  34936. u16 next, size;
  34937. if( pc>usableSize-4 ){
  34938. /* Free block is off the page */
  34939. return SQLITE_CORRUPT_BKPT;
  34940. }
  34941. next = get2byte(&data[pc]);
  34942. size = get2byte(&data[pc+2]);
  34943. if( next>0 && next<=pc+size+3 ){
  34944. /* Free blocks must be in accending order */
  34945. return SQLITE_CORRUPT_BKPT;
  34946. }
  34947. nFree += size;
  34948. pc = next;
  34949. }
  34950. pPage->nFree = (u16)nFree;
  34951. if( nFree>=usableSize ){
  34952. /* Free space cannot exceed total page size */
  34953. return SQLITE_CORRUPT_BKPT;
  34954. }
  34955. #if 0
  34956. /* Check that all the offsets in the cell offset array are within range.
  34957. **
  34958. ** Omitting this consistency check and using the pPage->maskPage mask
  34959. ** to prevent overrunning the page buffer in findCell() results in a
  34960. ** 2.5% performance gain.
  34961. */
  34962. {
  34963. u8 *pOff; /* Iterator used to check all cell offsets are in range */
  34964. u8 *pEnd; /* Pointer to end of cell offset array */
  34965. u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
  34966. mask = ~(((u8)(pBt->pageSize>>8))-1);
  34967. pEnd = &data[cellOffset + pPage->nCell*2];
  34968. for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
  34969. if( pOff!=pEnd ){
  34970. return SQLITE_CORRUPT_BKPT;
  34971. }
  34972. }
  34973. #endif
  34974. pPage->isInit = 1;
  34975. }
  34976. return SQLITE_OK;
  34977. }
  34978. /*
  34979. ** Set up a raw page so that it looks like a database page holding
  34980. ** no entries.
  34981. */
  34982. static void zeroPage(MemPage *pPage, int flags){
  34983. unsigned char *data = pPage->aData;
  34984. BtShared *pBt = pPage->pBt;
  34985. u8 hdr = pPage->hdrOffset;
  34986. u16 first;
  34987. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  34988. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  34989. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  34990. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  34991. assert( sqlite3_mutex_held(pBt->mutex) );
  34992. /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
  34993. data[hdr] = (char)flags;
  34994. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  34995. memset(&data[hdr+1], 0, 4);
  34996. data[hdr+7] = 0;
  34997. put2byte(&data[hdr+5], pBt->usableSize);
  34998. pPage->nFree = pBt->usableSize - first;
  34999. decodeFlags(pPage, flags);
  35000. pPage->hdrOffset = hdr;
  35001. pPage->cellOffset = first;
  35002. pPage->nOverflow = 0;
  35003. assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
  35004. pPage->maskPage = pBt->pageSize - 1;
  35005. pPage->nCell = 0;
  35006. pPage->isInit = 1;
  35007. }
  35008. /*
  35009. ** Convert a DbPage obtained from the pager into a MemPage used by
  35010. ** the btree layer.
  35011. */
  35012. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  35013. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  35014. pPage->aData = sqlite3PagerGetData(pDbPage);
  35015. pPage->pDbPage = pDbPage;
  35016. pPage->pBt = pBt;
  35017. pPage->pgno = pgno;
  35018. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  35019. return pPage;
  35020. }
  35021. /*
  35022. ** Get a page from the pager. Initialize the MemPage.pBt and
  35023. ** MemPage.aData elements if needed.
  35024. **
  35025. ** If the noContent flag is set, it means that we do not care about
  35026. ** the content of the page at this time. So do not go to the disk
  35027. ** to fetch the content. Just fill in the content with zeros for now.
  35028. ** If in the future we call sqlite3PagerWrite() on this page, that
  35029. ** means we have started to be concerned about content and the disk
  35030. ** read should occur at that point.
  35031. */
  35032. SQLITE_PRIVATE int sqlite3BtreeGetPage(
  35033. BtShared *pBt, /* The btree */
  35034. Pgno pgno, /* Number of the page to fetch */
  35035. MemPage **ppPage, /* Return the page in this parameter */
  35036. int noContent /* Do not load page content if true */
  35037. ){
  35038. int rc;
  35039. DbPage *pDbPage;
  35040. assert( sqlite3_mutex_held(pBt->mutex) );
  35041. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  35042. if( rc ) return rc;
  35043. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  35044. return SQLITE_OK;
  35045. }
  35046. /*
  35047. ** Retrieve a page from the pager cache. If the requested page is not
  35048. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  35049. ** MemPage.aData elements if needed.
  35050. */
  35051. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  35052. DbPage *pDbPage;
  35053. assert( sqlite3_mutex_held(pBt->mutex) );
  35054. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  35055. if( pDbPage ){
  35056. return btreePageFromDbPage(pDbPage, pgno, pBt);
  35057. }
  35058. return 0;
  35059. }
  35060. /*
  35061. ** Return the size of the database file in pages. If there is any kind of
  35062. ** error, return ((unsigned int)-1).
  35063. */
  35064. static Pgno pagerPagecount(BtShared *pBt){
  35065. int nPage = -1;
  35066. int rc;
  35067. assert( pBt->pPage1 );
  35068. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  35069. assert( rc==SQLITE_OK || nPage==-1 );
  35070. return (Pgno)nPage;
  35071. }
  35072. /*
  35073. ** Get a page from the pager and initialize it. This routine
  35074. ** is just a convenience wrapper around separate calls to
  35075. ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
  35076. */
  35077. static int getAndInitPage(
  35078. BtShared *pBt, /* The database file */
  35079. Pgno pgno, /* Number of the page to get */
  35080. MemPage **ppPage /* Write the page pointer here */
  35081. ){
  35082. int rc;
  35083. MemPage *pPage;
  35084. assert( sqlite3_mutex_held(pBt->mutex) );
  35085. if( pgno==0 ){
  35086. return SQLITE_CORRUPT_BKPT;
  35087. }
  35088. /* It is often the case that the page we want is already in cache.
  35089. ** If so, get it directly. This saves us from having to call
  35090. ** pagerPagecount() to make sure pgno is within limits, which results
  35091. ** in a measureable performance improvements.
  35092. */
  35093. *ppPage = pPage = btreePageLookup(pBt, pgno);
  35094. if( pPage ){
  35095. /* Page is already in cache */
  35096. rc = SQLITE_OK;
  35097. }else{
  35098. /* Page not in cache. Acquire it. */
  35099. if( pgno>pagerPagecount(pBt) ){
  35100. return SQLITE_CORRUPT_BKPT;
  35101. }
  35102. rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
  35103. if( rc ) return rc;
  35104. pPage = *ppPage;
  35105. }
  35106. if( !pPage->isInit ){
  35107. rc = sqlite3BtreeInitPage(pPage);
  35108. }
  35109. if( rc!=SQLITE_OK ){
  35110. releasePage(pPage);
  35111. *ppPage = 0;
  35112. }
  35113. return rc;
  35114. }
  35115. /*
  35116. ** Release a MemPage. This should be called once for each prior
  35117. ** call to sqlite3BtreeGetPage.
  35118. */
  35119. static void releasePage(MemPage *pPage){
  35120. if( pPage ){
  35121. assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
  35122. assert( pPage->aData );
  35123. assert( pPage->pBt );
  35124. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  35125. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  35126. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  35127. sqlite3PagerUnref(pPage->pDbPage);
  35128. }
  35129. }
  35130. /*
  35131. ** During a rollback, when the pager reloads information into the cache
  35132. ** so that the cache is restored to its original state at the start of
  35133. ** the transaction, for each page restored this routine is called.
  35134. **
  35135. ** This routine needs to reset the extra data section at the end of the
  35136. ** page to agree with the restored data.
  35137. */
  35138. static void pageReinit(DbPage *pData){
  35139. MemPage *pPage;
  35140. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  35141. assert( sqlite3PagerPageRefcount(pData)>0 );
  35142. if( pPage->isInit ){
  35143. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  35144. pPage->isInit = 0;
  35145. if( sqlite3PagerPageRefcount(pData)>1 ){
  35146. /* pPage might not be a btree page; it might be an overflow page
  35147. ** or ptrmap page or a free page. In those cases, the following
  35148. ** call to sqlite3BtreeInitPage() will likely return SQLITE_CORRUPT.
  35149. ** But no harm is done by this. And it is very important that
  35150. ** sqlite3BtreeInitPage() be called on every btree page so we make
  35151. ** the call for every page that comes in for re-initing. */
  35152. sqlite3BtreeInitPage(pPage);
  35153. }
  35154. }
  35155. }
  35156. /*
  35157. ** Invoke the busy handler for a btree.
  35158. */
  35159. static int btreeInvokeBusyHandler(void *pArg){
  35160. BtShared *pBt = (BtShared*)pArg;
  35161. assert( pBt->db );
  35162. assert( sqlite3_mutex_held(pBt->db->mutex) );
  35163. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  35164. }
  35165. /*
  35166. ** Open a database file.
  35167. **
  35168. ** zFilename is the name of the database file. If zFilename is NULL
  35169. ** a new database with a random name is created. This randomly named
  35170. ** database file will be deleted when sqlite3BtreeClose() is called.
  35171. ** If zFilename is ":memory:" then an in-memory database is created
  35172. ** that is automatically destroyed when it is closed.
  35173. */
  35174. SQLITE_PRIVATE int sqlite3BtreeOpen(
  35175. const char *zFilename, /* Name of the file containing the BTree database */
  35176. sqlite3 *db, /* Associated database handle */
  35177. Btree **ppBtree, /* Pointer to new Btree object written here */
  35178. int flags, /* Options */
  35179. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  35180. ){
  35181. sqlite3_vfs *pVfs; /* The VFS to use for this btree */
  35182. BtShared *pBt = 0; /* Shared part of btree structure */
  35183. Btree *p; /* Handle to return */
  35184. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  35185. int rc = SQLITE_OK; /* Result code from this function */
  35186. u8 nReserve; /* Byte of unused space on each page */
  35187. unsigned char zDbHeader[100]; /* Database header content */
  35188. /* Set the variable isMemdb to true for an in-memory database, or
  35189. ** false for a file-based database. This symbol is only required if
  35190. ** either of the shared-data or autovacuum features are compiled
  35191. ** into the library.
  35192. */
  35193. #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
  35194. #ifdef SQLITE_OMIT_MEMORYDB
  35195. const int isMemdb = 0;
  35196. #else
  35197. const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
  35198. #endif
  35199. #endif
  35200. assert( db!=0 );
  35201. assert( sqlite3_mutex_held(db->mutex) );
  35202. pVfs = db->pVfs;
  35203. p = sqlite3MallocZero(sizeof(Btree));
  35204. if( !p ){
  35205. return SQLITE_NOMEM;
  35206. }
  35207. p->inTrans = TRANS_NONE;
  35208. p->db = db;
  35209. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  35210. /*
  35211. ** If this Btree is a candidate for shared cache, try to find an
  35212. ** existing BtShared object that we can share with
  35213. */
  35214. if( isMemdb==0 && zFilename && zFilename[0] ){
  35215. if( sqlite3GlobalConfig.sharedCacheEnabled ){
  35216. int nFullPathname = pVfs->mxPathname+1;
  35217. char *zFullPathname = sqlite3Malloc(nFullPathname);
  35218. sqlite3_mutex *mutexShared;
  35219. p->sharable = 1;
  35220. db->flags |= SQLITE_SharedCache;
  35221. if( !zFullPathname ){
  35222. sqlite3_free(p);
  35223. return SQLITE_NOMEM;
  35224. }
  35225. sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
  35226. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  35227. sqlite3_mutex_enter(mutexOpen);
  35228. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  35229. sqlite3_mutex_enter(mutexShared);
  35230. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  35231. assert( pBt->nRef>0 );
  35232. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
  35233. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  35234. p->pBt = pBt;
  35235. pBt->nRef++;
  35236. break;
  35237. }
  35238. }
  35239. sqlite3_mutex_leave(mutexShared);
  35240. sqlite3_free(zFullPathname);
  35241. }
  35242. #ifdef SQLITE_DEBUG
  35243. else{
  35244. /* In debug mode, we mark all persistent databases as sharable
  35245. ** even when they are not. This exercises the locking code and
  35246. ** gives more opportunity for asserts(sqlite3_mutex_held())
  35247. ** statements to find locking problems.
  35248. */
  35249. p->sharable = 1;
  35250. }
  35251. #endif
  35252. }
  35253. #endif
  35254. if( pBt==0 ){
  35255. /*
  35256. ** The following asserts make sure that structures used by the btree are
  35257. ** the right size. This is to guard against size changes that result
  35258. ** when compiling on a different architecture.
  35259. */
  35260. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  35261. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  35262. assert( sizeof(u32)==4 );
  35263. assert( sizeof(u16)==2 );
  35264. assert( sizeof(Pgno)==4 );
  35265. pBt = sqlite3MallocZero( sizeof(*pBt) );
  35266. if( pBt==0 ){
  35267. rc = SQLITE_NOMEM;
  35268. goto btree_open_out;
  35269. }
  35270. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  35271. EXTRA_SIZE, flags, vfsFlags);
  35272. if( rc==SQLITE_OK ){
  35273. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  35274. }
  35275. if( rc!=SQLITE_OK ){
  35276. goto btree_open_out;
  35277. }
  35278. pBt->db = db;
  35279. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  35280. p->pBt = pBt;
  35281. sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
  35282. pBt->pCursor = 0;
  35283. pBt->pPage1 = 0;
  35284. pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
  35285. pBt->pageSize = get2byte(&zDbHeader[16]);
  35286. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  35287. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  35288. pBt->pageSize = 0;
  35289. sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35290. #ifndef SQLITE_OMIT_AUTOVACUUM
  35291. /* If the magic name ":memory:" will create an in-memory database, then
  35292. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  35293. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  35294. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  35295. ** regular file-name. In this case the auto-vacuum applies as per normal.
  35296. */
  35297. if( zFilename && !isMemdb ){
  35298. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  35299. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  35300. }
  35301. #endif
  35302. nReserve = 0;
  35303. }else{
  35304. nReserve = zDbHeader[20];
  35305. pBt->pageSizeFixed = 1;
  35306. #ifndef SQLITE_OMIT_AUTOVACUUM
  35307. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  35308. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  35309. #endif
  35310. }
  35311. pBt->usableSize = pBt->pageSize - nReserve;
  35312. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  35313. sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35314. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  35315. /* Add the new BtShared object to the linked list sharable BtShareds.
  35316. */
  35317. if( p->sharable ){
  35318. sqlite3_mutex *mutexShared;
  35319. pBt->nRef = 1;
  35320. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  35321. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  35322. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  35323. if( pBt->mutex==0 ){
  35324. rc = SQLITE_NOMEM;
  35325. db->mallocFailed = 0;
  35326. goto btree_open_out;
  35327. }
  35328. }
  35329. sqlite3_mutex_enter(mutexShared);
  35330. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  35331. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  35332. sqlite3_mutex_leave(mutexShared);
  35333. }
  35334. #endif
  35335. }
  35336. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  35337. /* If the new Btree uses a sharable pBtShared, then link the new
  35338. ** Btree into the list of all sharable Btrees for the same connection.
  35339. ** The list is kept in ascending order by pBt address.
  35340. */
  35341. if( p->sharable ){
  35342. int i;
  35343. Btree *pSib;
  35344. for(i=0; i<db->nDb; i++){
  35345. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  35346. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  35347. if( p->pBt<pSib->pBt ){
  35348. p->pNext = pSib;
  35349. p->pPrev = 0;
  35350. pSib->pPrev = p;
  35351. }else{
  35352. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  35353. pSib = pSib->pNext;
  35354. }
  35355. p->pNext = pSib->pNext;
  35356. p->pPrev = pSib;
  35357. if( p->pNext ){
  35358. p->pNext->pPrev = p;
  35359. }
  35360. pSib->pNext = p;
  35361. }
  35362. break;
  35363. }
  35364. }
  35365. }
  35366. #endif
  35367. *ppBtree = p;
  35368. btree_open_out:
  35369. if( rc!=SQLITE_OK ){
  35370. if( pBt && pBt->pPager ){
  35371. sqlite3PagerClose(pBt->pPager);
  35372. }
  35373. sqlite3_free(pBt);
  35374. sqlite3_free(p);
  35375. *ppBtree = 0;
  35376. }
  35377. if( mutexOpen ){
  35378. assert( sqlite3_mutex_held(mutexOpen) );
  35379. sqlite3_mutex_leave(mutexOpen);
  35380. }
  35381. return rc;
  35382. }
  35383. /*
  35384. ** Decrement the BtShared.nRef counter. When it reaches zero,
  35385. ** remove the BtShared structure from the sharing list. Return
  35386. ** true if the BtShared.nRef counter reaches zero and return
  35387. ** false if it is still positive.
  35388. */
  35389. static int removeFromSharingList(BtShared *pBt){
  35390. #ifndef SQLITE_OMIT_SHARED_CACHE
  35391. sqlite3_mutex *pMaster;
  35392. BtShared *pList;
  35393. int removed = 0;
  35394. assert( sqlite3_mutex_notheld(pBt->mutex) );
  35395. pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  35396. sqlite3_mutex_enter(pMaster);
  35397. pBt->nRef--;
  35398. if( pBt->nRef<=0 ){
  35399. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  35400. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  35401. }else{
  35402. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  35403. while( ALWAYS(pList) && pList->pNext!=pBt ){
  35404. pList=pList->pNext;
  35405. }
  35406. if( ALWAYS(pList) ){
  35407. pList->pNext = pBt->pNext;
  35408. }
  35409. }
  35410. if( SQLITE_THREADSAFE ){
  35411. sqlite3_mutex_free(pBt->mutex);
  35412. }
  35413. removed = 1;
  35414. }
  35415. sqlite3_mutex_leave(pMaster);
  35416. return removed;
  35417. #else
  35418. return 1;
  35419. #endif
  35420. }
  35421. /*
  35422. ** Make sure pBt->pTmpSpace points to an allocation of
  35423. ** MX_CELL_SIZE(pBt) bytes.
  35424. */
  35425. static void allocateTempSpace(BtShared *pBt){
  35426. if( !pBt->pTmpSpace ){
  35427. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  35428. }
  35429. }
  35430. /*
  35431. ** Free the pBt->pTmpSpace allocation
  35432. */
  35433. static void freeTempSpace(BtShared *pBt){
  35434. sqlite3PageFree( pBt->pTmpSpace);
  35435. pBt->pTmpSpace = 0;
  35436. }
  35437. /*
  35438. ** Close an open database and invalidate all cursors.
  35439. */
  35440. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  35441. BtShared *pBt = p->pBt;
  35442. BtCursor *pCur;
  35443. /* Close all cursors opened via this handle. */
  35444. assert( sqlite3_mutex_held(p->db->mutex) );
  35445. sqlite3BtreeEnter(p);
  35446. pCur = pBt->pCursor;
  35447. while( pCur ){
  35448. BtCursor *pTmp = pCur;
  35449. pCur = pCur->pNext;
  35450. if( pTmp->pBtree==p ){
  35451. sqlite3BtreeCloseCursor(pTmp);
  35452. }
  35453. }
  35454. /* Rollback any active transaction and free the handle structure.
  35455. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  35456. ** this handle.
  35457. */
  35458. sqlite3BtreeRollback(p);
  35459. sqlite3BtreeLeave(p);
  35460. /* If there are still other outstanding references to the shared-btree
  35461. ** structure, return now. The remainder of this procedure cleans
  35462. ** up the shared-btree.
  35463. */
  35464. assert( p->wantToLock==0 && p->locked==0 );
  35465. if( !p->sharable || removeFromSharingList(pBt) ){
  35466. /* The pBt is no longer on the sharing list, so we can access
  35467. ** it without having to hold the mutex.
  35468. **
  35469. ** Clean out and delete the BtShared object.
  35470. */
  35471. assert( !pBt->pCursor );
  35472. sqlite3PagerClose(pBt->pPager);
  35473. if( pBt->xFreeSchema && pBt->pSchema ){
  35474. pBt->xFreeSchema(pBt->pSchema);
  35475. }
  35476. sqlite3_free(pBt->pSchema);
  35477. freeTempSpace(pBt);
  35478. sqlite3_free(pBt);
  35479. }
  35480. #ifndef SQLITE_OMIT_SHARED_CACHE
  35481. assert( p->wantToLock==0 );
  35482. assert( p->locked==0 );
  35483. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  35484. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  35485. #endif
  35486. sqlite3_free(p);
  35487. return SQLITE_OK;
  35488. }
  35489. /*
  35490. ** Change the limit on the number of pages allowed in the cache.
  35491. **
  35492. ** The maximum number of cache pages is set to the absolute
  35493. ** value of mxPage. If mxPage is negative, the pager will
  35494. ** operate asynchronously - it will not stop to do fsync()s
  35495. ** to insure data is written to the disk surface before
  35496. ** continuing. Transactions still work if synchronous is off,
  35497. ** and the database cannot be corrupted if this program
  35498. ** crashes. But if the operating system crashes or there is
  35499. ** an abrupt power failure when synchronous is off, the database
  35500. ** could be left in an inconsistent and unrecoverable state.
  35501. ** Synchronous is on by default so database corruption is not
  35502. ** normally a worry.
  35503. */
  35504. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  35505. BtShared *pBt = p->pBt;
  35506. assert( sqlite3_mutex_held(p->db->mutex) );
  35507. sqlite3BtreeEnter(p);
  35508. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  35509. sqlite3BtreeLeave(p);
  35510. return SQLITE_OK;
  35511. }
  35512. /*
  35513. ** Change the way data is synced to disk in order to increase or decrease
  35514. ** how well the database resists damage due to OS crashes and power
  35515. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  35516. ** there is a high probability of damage) Level 2 is the default. There
  35517. ** is a very low but non-zero probability of damage. Level 3 reduces the
  35518. ** probability of damage to near zero but with a write performance reduction.
  35519. */
  35520. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  35521. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
  35522. BtShared *pBt = p->pBt;
  35523. assert( sqlite3_mutex_held(p->db->mutex) );
  35524. sqlite3BtreeEnter(p);
  35525. sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
  35526. sqlite3BtreeLeave(p);
  35527. return SQLITE_OK;
  35528. }
  35529. #endif
  35530. /*
  35531. ** Return TRUE if the given btree is set to safety level 1. In other
  35532. ** words, return TRUE if no sync() occurs on the disk files.
  35533. */
  35534. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  35535. BtShared *pBt = p->pBt;
  35536. int rc;
  35537. assert( sqlite3_mutex_held(p->db->mutex) );
  35538. sqlite3BtreeEnter(p);
  35539. assert( pBt && pBt->pPager );
  35540. rc = sqlite3PagerNosync(pBt->pPager);
  35541. sqlite3BtreeLeave(p);
  35542. return rc;
  35543. }
  35544. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  35545. /*
  35546. ** Change the default pages size and the number of reserved bytes per page.
  35547. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  35548. ** without changing anything.
  35549. **
  35550. ** The page size must be a power of 2 between 512 and 65536. If the page
  35551. ** size supplied does not meet this constraint then the page size is not
  35552. ** changed.
  35553. **
  35554. ** Page sizes are constrained to be a power of two so that the region
  35555. ** of the database file used for locking (beginning at PENDING_BYTE,
  35556. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  35557. ** at the beginning of a page.
  35558. **
  35559. ** If parameter nReserve is less than zero, then the number of reserved
  35560. ** bytes per page is left unchanged.
  35561. **
  35562. ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
  35563. ** and autovacuum mode can no longer be changed.
  35564. */
  35565. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  35566. int rc = SQLITE_OK;
  35567. BtShared *pBt = p->pBt;
  35568. assert( nReserve>=-1 && nReserve<=255 );
  35569. sqlite3BtreeEnter(p);
  35570. if( pBt->pageSizeFixed ){
  35571. sqlite3BtreeLeave(p);
  35572. return SQLITE_READONLY;
  35573. }
  35574. if( nReserve<0 ){
  35575. nReserve = pBt->pageSize - pBt->usableSize;
  35576. }
  35577. assert( nReserve>=0 && nReserve<=255 );
  35578. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  35579. ((pageSize-1)&pageSize)==0 ){
  35580. assert( (pageSize & 7)==0 );
  35581. assert( !pBt->pPage1 && !pBt->pCursor );
  35582. pBt->pageSize = (u16)pageSize;
  35583. freeTempSpace(pBt);
  35584. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35585. }
  35586. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  35587. if( iFix ) pBt->pageSizeFixed = 1;
  35588. sqlite3BtreeLeave(p);
  35589. return rc;
  35590. }
  35591. /*
  35592. ** Return the currently defined page size
  35593. */
  35594. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  35595. return p->pBt->pageSize;
  35596. }
  35597. /*
  35598. ** Return the number of bytes of space at the end of every page that
  35599. ** are intentually left unused. This is the "reserved" space that is
  35600. ** sometimes used by extensions.
  35601. */
  35602. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  35603. int n;
  35604. sqlite3BtreeEnter(p);
  35605. n = p->pBt->pageSize - p->pBt->usableSize;
  35606. sqlite3BtreeLeave(p);
  35607. return n;
  35608. }
  35609. /*
  35610. ** Set the maximum page count for a database if mxPage is positive.
  35611. ** No changes are made if mxPage is 0 or negative.
  35612. ** Regardless of the value of mxPage, return the maximum page count.
  35613. */
  35614. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  35615. int n;
  35616. sqlite3BtreeEnter(p);
  35617. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  35618. sqlite3BtreeLeave(p);
  35619. return n;
  35620. }
  35621. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  35622. /*
  35623. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  35624. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  35625. ** is disabled. The default value for the auto-vacuum property is
  35626. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  35627. */
  35628. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  35629. #ifdef SQLITE_OMIT_AUTOVACUUM
  35630. return SQLITE_READONLY;
  35631. #else
  35632. BtShared *pBt = p->pBt;
  35633. int rc = SQLITE_OK;
  35634. u8 av = (u8)autoVacuum;
  35635. sqlite3BtreeEnter(p);
  35636. if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
  35637. rc = SQLITE_READONLY;
  35638. }else{
  35639. pBt->autoVacuum = av ?1:0;
  35640. pBt->incrVacuum = av==2 ?1:0;
  35641. }
  35642. sqlite3BtreeLeave(p);
  35643. return rc;
  35644. #endif
  35645. }
  35646. /*
  35647. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  35648. ** enabled 1 is returned. Otherwise 0.
  35649. */
  35650. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  35651. #ifdef SQLITE_OMIT_AUTOVACUUM
  35652. return BTREE_AUTOVACUUM_NONE;
  35653. #else
  35654. int rc;
  35655. sqlite3BtreeEnter(p);
  35656. rc = (
  35657. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  35658. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  35659. BTREE_AUTOVACUUM_INCR
  35660. );
  35661. sqlite3BtreeLeave(p);
  35662. return rc;
  35663. #endif
  35664. }
  35665. /*
  35666. ** Get a reference to pPage1 of the database file. This will
  35667. ** also acquire a readlock on that file.
  35668. **
  35669. ** SQLITE_OK is returned on success. If the file is not a
  35670. ** well-formed database file, then SQLITE_CORRUPT is returned.
  35671. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  35672. ** is returned if we run out of memory.
  35673. */
  35674. static int lockBtree(BtShared *pBt){
  35675. int rc;
  35676. MemPage *pPage1;
  35677. int nPage;
  35678. assert( sqlite3_mutex_held(pBt->mutex) );
  35679. assert( pBt->pPage1==0 );
  35680. rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
  35681. if( rc!=SQLITE_OK ) return rc;
  35682. /* Do some checking to help insure the file we opened really is
  35683. ** a valid database file.
  35684. */
  35685. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  35686. if( rc!=SQLITE_OK ){
  35687. goto page1_init_failed;
  35688. }else if( nPage>0 ){
  35689. int pageSize;
  35690. int usableSize;
  35691. u8 *page1 = pPage1->aData;
  35692. rc = SQLITE_NOTADB;
  35693. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  35694. goto page1_init_failed;
  35695. }
  35696. if( page1[18]>1 ){
  35697. pBt->readOnly = 1;
  35698. }
  35699. if( page1[19]>1 ){
  35700. goto page1_init_failed;
  35701. }
  35702. /* The maximum embedded fraction must be exactly 25%. And the minimum
  35703. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  35704. ** The original design allowed these amounts to vary, but as of
  35705. ** version 3.6.0, we require them to be fixed.
  35706. */
  35707. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  35708. goto page1_init_failed;
  35709. }
  35710. pageSize = get2byte(&page1[16]);
  35711. if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
  35712. (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
  35713. ){
  35714. goto page1_init_failed;
  35715. }
  35716. assert( (pageSize & 7)==0 );
  35717. usableSize = pageSize - page1[20];
  35718. if( pageSize!=pBt->pageSize ){
  35719. /* After reading the first page of the database assuming a page size
  35720. ** of BtShared.pageSize, we have discovered that the page-size is
  35721. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  35722. ** zero and return SQLITE_OK. The caller will call this function
  35723. ** again with the correct page-size.
  35724. */
  35725. releasePage(pPage1);
  35726. pBt->usableSize = (u16)usableSize;
  35727. pBt->pageSize = (u16)pageSize;
  35728. freeTempSpace(pBt);
  35729. sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
  35730. return SQLITE_OK;
  35731. }
  35732. if( usableSize<500 ){
  35733. goto page1_init_failed;
  35734. }
  35735. pBt->pageSize = (u16)pageSize;
  35736. pBt->usableSize = (u16)usableSize;
  35737. #ifndef SQLITE_OMIT_AUTOVACUUM
  35738. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  35739. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  35740. #endif
  35741. }
  35742. /* maxLocal is the maximum amount of payload to store locally for
  35743. ** a cell. Make sure it is small enough so that at least minFanout
  35744. ** cells can will fit on one page. We assume a 10-byte page header.
  35745. ** Besides the payload, the cell must store:
  35746. ** 2-byte pointer to the cell
  35747. ** 4-byte child pointer
  35748. ** 9-byte nKey value
  35749. ** 4-byte nData value
  35750. ** 4-byte overflow page pointer
  35751. ** So a cell consists of a 2-byte poiner, a header which is as much as
  35752. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  35753. ** page pointer.
  35754. */
  35755. pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
  35756. pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
  35757. pBt->maxLeaf = pBt->usableSize - 35;
  35758. pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
  35759. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  35760. pBt->pPage1 = pPage1;
  35761. return SQLITE_OK;
  35762. page1_init_failed:
  35763. releasePage(pPage1);
  35764. pBt->pPage1 = 0;
  35765. return rc;
  35766. }
  35767. /*
  35768. ** This routine works like lockBtree() except that it also invokes the
  35769. ** busy callback if there is lock contention.
  35770. */
  35771. static int lockBtreeWithRetry(Btree *pRef){
  35772. int rc = SQLITE_OK;
  35773. assert( sqlite3BtreeHoldsMutex(pRef) );
  35774. if( pRef->inTrans==TRANS_NONE ){
  35775. u8 inTransaction = pRef->pBt->inTransaction;
  35776. btreeIntegrity(pRef);
  35777. rc = sqlite3BtreeBeginTrans(pRef, 0);
  35778. pRef->pBt->inTransaction = inTransaction;
  35779. pRef->inTrans = TRANS_NONE;
  35780. if( rc==SQLITE_OK ){
  35781. pRef->pBt->nTransaction--;
  35782. }
  35783. btreeIntegrity(pRef);
  35784. }
  35785. return rc;
  35786. }
  35787. /*
  35788. ** If there are no outstanding cursors and we are not in the middle
  35789. ** of a transaction but there is a read lock on the database, then
  35790. ** this routine unrefs the first page of the database file which
  35791. ** has the effect of releasing the read lock.
  35792. **
  35793. ** If there are any outstanding cursors, this routine is a no-op.
  35794. **
  35795. ** If there is a transaction in progress, this routine is a no-op.
  35796. */
  35797. static void unlockBtreeIfUnused(BtShared *pBt){
  35798. assert( sqlite3_mutex_held(pBt->mutex) );
  35799. if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
  35800. if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
  35801. assert( pBt->pPage1->aData );
  35802. #if 0
  35803. if( pBt->pPage1->aData==0 ){
  35804. MemPage *pPage = pBt->pPage1;
  35805. pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
  35806. pPage->pBt = pBt;
  35807. pPage->pgno = 1;
  35808. }
  35809. #endif
  35810. releasePage(pBt->pPage1);
  35811. }
  35812. pBt->pPage1 = 0;
  35813. }
  35814. }
  35815. /*
  35816. ** Create a new database by initializing the first page of the
  35817. ** file.
  35818. */
  35819. static int newDatabase(BtShared *pBt){
  35820. MemPage *pP1;
  35821. unsigned char *data;
  35822. int rc;
  35823. int nPage;
  35824. assert( sqlite3_mutex_held(pBt->mutex) );
  35825. rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
  35826. if( rc!=SQLITE_OK || nPage>0 ){
  35827. return rc;
  35828. }
  35829. pP1 = pBt->pPage1;
  35830. assert( pP1!=0 );
  35831. data = pP1->aData;
  35832. rc = sqlite3PagerWrite(pP1->pDbPage);
  35833. if( rc ) return rc;
  35834. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  35835. assert( sizeof(zMagicHeader)==16 );
  35836. put2byte(&data[16], pBt->pageSize);
  35837. data[18] = 1;
  35838. data[19] = 1;
  35839. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  35840. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  35841. data[21] = 64;
  35842. data[22] = 32;
  35843. data[23] = 32;
  35844. memset(&data[24], 0, 100-24);
  35845. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  35846. pBt->pageSizeFixed = 1;
  35847. #ifndef SQLITE_OMIT_AUTOVACUUM
  35848. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  35849. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  35850. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  35851. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  35852. #endif
  35853. return SQLITE_OK;
  35854. }
  35855. /*
  35856. ** Attempt to start a new transaction. A write-transaction
  35857. ** is started if the second argument is nonzero, otherwise a read-
  35858. ** transaction. If the second argument is 2 or more and exclusive
  35859. ** transaction is started, meaning that no other process is allowed
  35860. ** to access the database. A preexisting transaction may not be
  35861. ** upgraded to exclusive by calling this routine a second time - the
  35862. ** exclusivity flag only works for a new transaction.
  35863. **
  35864. ** A write-transaction must be started before attempting any
  35865. ** changes to the database. None of the following routines
  35866. ** will work unless a transaction is started first:
  35867. **
  35868. ** sqlite3BtreeCreateTable()
  35869. ** sqlite3BtreeCreateIndex()
  35870. ** sqlite3BtreeClearTable()
  35871. ** sqlite3BtreeDropTable()
  35872. ** sqlite3BtreeInsert()
  35873. ** sqlite3BtreeDelete()
  35874. ** sqlite3BtreeUpdateMeta()
  35875. **
  35876. ** If an initial attempt to acquire the lock fails because of lock contention
  35877. ** and the database was previously unlocked, then invoke the busy handler
  35878. ** if there is one. But if there was previously a read-lock, do not
  35879. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  35880. ** returned when there is already a read-lock in order to avoid a deadlock.
  35881. **
  35882. ** Suppose there are two processes A and B. A has a read lock and B has
  35883. ** a reserved lock. B tries to promote to exclusive but is blocked because
  35884. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  35885. ** One or the other of the two processes must give way or there can be
  35886. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  35887. ** when A already has a read lock, we encourage A to give up and let B
  35888. ** proceed.
  35889. */
  35890. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  35891. sqlite3 *pBlock = 0;
  35892. BtShared *pBt = p->pBt;
  35893. int rc = SQLITE_OK;
  35894. sqlite3BtreeEnter(p);
  35895. btreeIntegrity(p);
  35896. /* If the btree is already in a write-transaction, or it
  35897. ** is already in a read-transaction and a read-transaction
  35898. ** is requested, this is a no-op.
  35899. */
  35900. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  35901. goto trans_begun;
  35902. }
  35903. /* Write transactions are not possible on a read-only database */
  35904. if( pBt->readOnly && wrflag ){
  35905. rc = SQLITE_READONLY;
  35906. goto trans_begun;
  35907. }
  35908. #ifndef SQLITE_OMIT_SHARED_CACHE
  35909. /* If another database handle has already opened a write transaction
  35910. ** on this shared-btree structure and a second write transaction is
  35911. ** requested, return SQLITE_LOCKED.
  35912. */
  35913. if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
  35914. pBlock = pBt->pWriter->db;
  35915. }else if( wrflag>1 ){
  35916. BtLock *pIter;
  35917. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  35918. if( pIter->pBtree!=p ){
  35919. pBlock = pIter->pBtree->db;
  35920. break;
  35921. }
  35922. }
  35923. }
  35924. if( pBlock ){
  35925. sqlite3ConnectionBlocked(p->db, pBlock);
  35926. rc = SQLITE_LOCKED_SHAREDCACHE;
  35927. goto trans_begun;
  35928. }
  35929. #endif
  35930. do {
  35931. /* Call lockBtree() until either pBt->pPage1 is populated or
  35932. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  35933. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  35934. ** reading page 1 it discovers that the page-size of the database
  35935. ** file is not pBt->pageSize. In this case lockBtree() will update
  35936. ** pBt->pageSize to the page-size of the file on disk.
  35937. */
  35938. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  35939. if( rc==SQLITE_OK && wrflag ){
  35940. if( pBt->readOnly ){
  35941. rc = SQLITE_READONLY;
  35942. }else{
  35943. rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
  35944. if( rc==SQLITE_OK ){
  35945. rc = newDatabase(pBt);
  35946. }
  35947. }
  35948. }
  35949. if( rc!=SQLITE_OK ){
  35950. unlockBtreeIfUnused(pBt);
  35951. }
  35952. }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  35953. btreeInvokeBusyHandler(pBt) );
  35954. if( rc==SQLITE_OK ){
  35955. if( p->inTrans==TRANS_NONE ){
  35956. pBt->nTransaction++;
  35957. }
  35958. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  35959. if( p->inTrans>pBt->inTransaction ){
  35960. pBt->inTransaction = p->inTrans;
  35961. }
  35962. #ifndef SQLITE_OMIT_SHARED_CACHE
  35963. if( wrflag ){
  35964. assert( !pBt->pWriter );
  35965. pBt->pWriter = p;
  35966. pBt->isExclusive = (u8)(wrflag>1);
  35967. }
  35968. #endif
  35969. }
  35970. trans_begun:
  35971. if( rc==SQLITE_OK && wrflag ){
  35972. /* This call makes sure that the pager has the correct number of
  35973. ** open savepoints. If the second parameter is greater than 0 and
  35974. ** the sub-journal is not already open, then it will be opened here.
  35975. */
  35976. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  35977. }
  35978. btreeIntegrity(p);
  35979. sqlite3BtreeLeave(p);
  35980. return rc;
  35981. }
  35982. #ifndef SQLITE_OMIT_AUTOVACUUM
  35983. /*
  35984. ** Set the pointer-map entries for all children of page pPage. Also, if
  35985. ** pPage contains cells that point to overflow pages, set the pointer
  35986. ** map entries for the overflow pages as well.
  35987. */
  35988. static int setChildPtrmaps(MemPage *pPage){
  35989. int i; /* Counter variable */
  35990. int nCell; /* Number of cells in page pPage */
  35991. int rc; /* Return code */
  35992. BtShared *pBt = pPage->pBt;
  35993. u8 isInitOrig = pPage->isInit;
  35994. Pgno pgno = pPage->pgno;
  35995. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  35996. rc = sqlite3BtreeInitPage(pPage);
  35997. if( rc!=SQLITE_OK ){
  35998. goto set_child_ptrmaps_out;
  35999. }
  36000. nCell = pPage->nCell;
  36001. for(i=0; i<nCell; i++){
  36002. u8 *pCell = findCell(pPage, i);
  36003. rc = ptrmapPutOvflPtr(pPage, pCell);
  36004. if( rc!=SQLITE_OK ){
  36005. goto set_child_ptrmaps_out;
  36006. }
  36007. if( !pPage->leaf ){
  36008. Pgno childPgno = get4byte(pCell);
  36009. rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
  36010. if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
  36011. }
  36012. }
  36013. if( !pPage->leaf ){
  36014. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  36015. rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
  36016. }
  36017. set_child_ptrmaps_out:
  36018. pPage->isInit = isInitOrig;
  36019. return rc;
  36020. }
  36021. /*
  36022. ** Somewhere on pPage, which is guaranteed to be a btree page, not an overflow
  36023. ** page, is a pointer to page iFrom. Modify this pointer so that it points to
  36024. ** iTo. Parameter eType describes the type of pointer to be modified, as
  36025. ** follows:
  36026. **
  36027. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  36028. ** page of pPage.
  36029. **
  36030. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  36031. ** page pointed to by one of the cells on pPage.
  36032. **
  36033. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  36034. ** overflow page in the list.
  36035. */
  36036. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  36037. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  36038. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  36039. if( eType==PTRMAP_OVERFLOW2 ){
  36040. /* The pointer is always the first 4 bytes of the page in this case. */
  36041. if( get4byte(pPage->aData)!=iFrom ){
  36042. return SQLITE_CORRUPT_BKPT;
  36043. }
  36044. put4byte(pPage->aData, iTo);
  36045. }else{
  36046. u8 isInitOrig = pPage->isInit;
  36047. int i;
  36048. int nCell;
  36049. sqlite3BtreeInitPage(pPage);
  36050. nCell = pPage->nCell;
  36051. for(i=0; i<nCell; i++){
  36052. u8 *pCell = findCell(pPage, i);
  36053. if( eType==PTRMAP_OVERFLOW1 ){
  36054. CellInfo info;
  36055. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  36056. if( info.iOverflow ){
  36057. if( iFrom==get4byte(&pCell[info.iOverflow]) ){
  36058. put4byte(&pCell[info.iOverflow], iTo);
  36059. break;
  36060. }
  36061. }
  36062. }else{
  36063. if( get4byte(pCell)==iFrom ){
  36064. put4byte(pCell, iTo);
  36065. break;
  36066. }
  36067. }
  36068. }
  36069. if( i==nCell ){
  36070. if( eType!=PTRMAP_BTREE ||
  36071. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  36072. return SQLITE_CORRUPT_BKPT;
  36073. }
  36074. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  36075. }
  36076. pPage->isInit = isInitOrig;
  36077. }
  36078. return SQLITE_OK;
  36079. }
  36080. /*
  36081. ** Move the open database page pDbPage to location iFreePage in the
  36082. ** database. The pDbPage reference remains valid.
  36083. */
  36084. static int relocatePage(
  36085. BtShared *pBt, /* Btree */
  36086. MemPage *pDbPage, /* Open page to move */
  36087. u8 eType, /* Pointer map 'type' entry for pDbPage */
  36088. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  36089. Pgno iFreePage, /* The location to move pDbPage to */
  36090. int isCommit
  36091. ){
  36092. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  36093. Pgno iDbPage = pDbPage->pgno;
  36094. Pager *pPager = pBt->pPager;
  36095. int rc;
  36096. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  36097. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  36098. assert( sqlite3_mutex_held(pBt->mutex) );
  36099. assert( pDbPage->pBt==pBt );
  36100. /* Move page iDbPage from its current location to page number iFreePage */
  36101. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  36102. iDbPage, iFreePage, iPtrPage, eType));
  36103. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  36104. if( rc!=SQLITE_OK ){
  36105. return rc;
  36106. }
  36107. pDbPage->pgno = iFreePage;
  36108. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  36109. ** that point to overflow pages. The pointer map entries for all these
  36110. ** pages need to be changed.
  36111. **
  36112. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  36113. ** pointer to a subsequent overflow page. If this is the case, then
  36114. ** the pointer map needs to be updated for the subsequent overflow page.
  36115. */
  36116. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  36117. rc = setChildPtrmaps(pDbPage);
  36118. if( rc!=SQLITE_OK ){
  36119. return rc;
  36120. }
  36121. }else{
  36122. Pgno nextOvfl = get4byte(pDbPage->aData);
  36123. if( nextOvfl!=0 ){
  36124. rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
  36125. if( rc!=SQLITE_OK ){
  36126. return rc;
  36127. }
  36128. }
  36129. }
  36130. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  36131. ** that it points at iFreePage. Also fix the pointer map entry for
  36132. ** iPtrPage.
  36133. */
  36134. if( eType!=PTRMAP_ROOTPAGE ){
  36135. rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  36136. if( rc!=SQLITE_OK ){
  36137. return rc;
  36138. }
  36139. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  36140. if( rc!=SQLITE_OK ){
  36141. releasePage(pPtrPage);
  36142. return rc;
  36143. }
  36144. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  36145. releasePage(pPtrPage);
  36146. if( rc==SQLITE_OK ){
  36147. rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
  36148. }
  36149. }
  36150. return rc;
  36151. }
  36152. /* Forward declaration required by incrVacuumStep(). */
  36153. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  36154. /*
  36155. ** Perform a single step of an incremental-vacuum. If successful,
  36156. ** return SQLITE_OK. If there is no work to do (and therefore no
  36157. ** point in calling this function again), return SQLITE_DONE.
  36158. **
  36159. ** More specificly, this function attempts to re-organize the
  36160. ** database so that the last page of the file currently in use
  36161. ** is no longer in use.
  36162. **
  36163. ** If the nFin parameter is non-zero, the implementation assumes
  36164. ** that the caller will keep calling incrVacuumStep() until
  36165. ** it returns SQLITE_DONE or an error, and that nFin is the
  36166. ** number of pages the database file will contain after this
  36167. ** process is complete.
  36168. */
  36169. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
  36170. Pgno nFreeList; /* Number of pages still on the free-list */
  36171. assert( sqlite3_mutex_held(pBt->mutex) );
  36172. assert( iLastPg>nFin );
  36173. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  36174. int rc;
  36175. u8 eType;
  36176. Pgno iPtrPage;
  36177. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  36178. if( nFreeList==0 ){
  36179. return SQLITE_DONE;
  36180. }
  36181. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  36182. if( rc!=SQLITE_OK ){
  36183. return rc;
  36184. }
  36185. if( eType==PTRMAP_ROOTPAGE ){
  36186. return SQLITE_CORRUPT_BKPT;
  36187. }
  36188. if( eType==PTRMAP_FREEPAGE ){
  36189. if( nFin==0 ){
  36190. /* Remove the page from the files free-list. This is not required
  36191. ** if nFin is non-zero. In that case, the free-list will be
  36192. ** truncated to zero after this function returns, so it doesn't
  36193. ** matter if it still contains some garbage entries.
  36194. */
  36195. Pgno iFreePg;
  36196. MemPage *pFreePg;
  36197. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
  36198. if( rc!=SQLITE_OK ){
  36199. return rc;
  36200. }
  36201. assert( iFreePg==iLastPg );
  36202. releasePage(pFreePg);
  36203. }
  36204. } else {
  36205. Pgno iFreePg; /* Index of free page to move pLastPg to */
  36206. MemPage *pLastPg;
  36207. rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
  36208. if( rc!=SQLITE_OK ){
  36209. return rc;
  36210. }
  36211. /* If nFin is zero, this loop runs exactly once and page pLastPg
  36212. ** is swapped with the first free page pulled off the free list.
  36213. **
  36214. ** On the other hand, if nFin is greater than zero, then keep
  36215. ** looping until a free-page located within the first nFin pages
  36216. ** of the file is found.
  36217. */
  36218. do {
  36219. MemPage *pFreePg;
  36220. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
  36221. if( rc!=SQLITE_OK ){
  36222. releasePage(pLastPg);
  36223. return rc;
  36224. }
  36225. releasePage(pFreePg);
  36226. }while( nFin!=0 && iFreePg>nFin );
  36227. assert( iFreePg<iLastPg );
  36228. rc = sqlite3PagerWrite(pLastPg->pDbPage);
  36229. if( rc==SQLITE_OK ){
  36230. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
  36231. }
  36232. releasePage(pLastPg);
  36233. if( rc!=SQLITE_OK ){
  36234. return rc;
  36235. }
  36236. }
  36237. }
  36238. if( nFin==0 ){
  36239. iLastPg--;
  36240. while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
  36241. if( PTRMAP_ISPAGE(pBt, iLastPg) ){
  36242. MemPage *pPg;
  36243. int rc = sqlite3BtreeGetPage(pBt, iLastPg, &pPg, 0);
  36244. if( rc!=SQLITE_OK ){
  36245. return rc;
  36246. }
  36247. rc = sqlite3PagerWrite(pPg->pDbPage);
  36248. releasePage(pPg);
  36249. if( rc!=SQLITE_OK ){
  36250. return rc;
  36251. }
  36252. }
  36253. iLastPg--;
  36254. }
  36255. sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
  36256. }
  36257. return SQLITE_OK;
  36258. }
  36259. /*
  36260. ** A write-transaction must be opened before calling this function.
  36261. ** It performs a single unit of work towards an incremental vacuum.
  36262. **
  36263. ** If the incremental vacuum is finished after this function has run,
  36264. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  36265. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  36266. */
  36267. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  36268. int rc;
  36269. BtShared *pBt = p->pBt;
  36270. sqlite3BtreeEnter(p);
  36271. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  36272. if( !pBt->autoVacuum ){
  36273. rc = SQLITE_DONE;
  36274. }else{
  36275. invalidateAllOverflowCache(pBt);
  36276. rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
  36277. }
  36278. sqlite3BtreeLeave(p);
  36279. return rc;
  36280. }
  36281. /*
  36282. ** This routine is called prior to sqlite3PagerCommit when a transaction
  36283. ** is commited for an auto-vacuum database.
  36284. **
  36285. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  36286. ** the database file should be truncated to during the commit process.
  36287. ** i.e. the database has been reorganized so that only the first *pnTrunc
  36288. ** pages are in use.
  36289. */
  36290. static int autoVacuumCommit(BtShared *pBt){
  36291. int rc = SQLITE_OK;
  36292. Pager *pPager = pBt->pPager;
  36293. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  36294. assert( sqlite3_mutex_held(pBt->mutex) );
  36295. invalidateAllOverflowCache(pBt);
  36296. assert(pBt->autoVacuum);
  36297. if( !pBt->incrVacuum ){
  36298. Pgno nFin;
  36299. Pgno nFree;
  36300. Pgno nPtrmap;
  36301. Pgno iFree;
  36302. const int pgsz = pBt->pageSize;
  36303. Pgno nOrig = pagerPagecount(pBt);
  36304. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  36305. /* It is not possible to create a database for which the final page
  36306. ** is either a pointer-map page or the pending-byte page. If one
  36307. ** is encountered, this indicates corruption.
  36308. */
  36309. return SQLITE_CORRUPT_BKPT;
  36310. }
  36311. nFree = get4byte(&pBt->pPage1->aData[36]);
  36312. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
  36313. nFin = nOrig - nFree - nPtrmap;
  36314. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  36315. nFin--;
  36316. }
  36317. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  36318. nFin--;
  36319. }
  36320. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  36321. rc = incrVacuumStep(pBt, nFin, iFree);
  36322. }
  36323. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  36324. rc = SQLITE_OK;
  36325. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  36326. put4byte(&pBt->pPage1->aData[32], 0);
  36327. put4byte(&pBt->pPage1->aData[36], 0);
  36328. sqlite3PagerTruncateImage(pBt->pPager, nFin);
  36329. }
  36330. if( rc!=SQLITE_OK ){
  36331. sqlite3PagerRollback(pPager);
  36332. }
  36333. }
  36334. assert( nRef==sqlite3PagerRefcount(pPager) );
  36335. return rc;
  36336. }
  36337. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  36338. /*
  36339. ** This routine does the first phase of a two-phase commit. This routine
  36340. ** causes a rollback journal to be created (if it does not already exist)
  36341. ** and populated with enough information so that if a power loss occurs
  36342. ** the database can be restored to its original state by playing back
  36343. ** the journal. Then the contents of the journal are flushed out to
  36344. ** the disk. After the journal is safely on oxide, the changes to the
  36345. ** database are written into the database file and flushed to oxide.
  36346. ** At the end of this call, the rollback journal still exists on the
  36347. ** disk and we are still holding all locks, so the transaction has not
  36348. ** committed. See sqlite3BtreeCommit() for the second phase of the
  36349. ** commit process.
  36350. **
  36351. ** This call is a no-op if no write-transaction is currently active on pBt.
  36352. **
  36353. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  36354. ** the name of a master journal file that should be written into the
  36355. ** individual journal file, or is NULL, indicating no master journal file
  36356. ** (single database transaction).
  36357. **
  36358. ** When this is called, the master journal should already have been
  36359. ** created, populated with this journal pointer and synced to disk.
  36360. **
  36361. ** Once this is routine has returned, the only thing required to commit
  36362. ** the write-transaction for this database file is to delete the journal.
  36363. */
  36364. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  36365. int rc = SQLITE_OK;
  36366. if( p->inTrans==TRANS_WRITE ){
  36367. BtShared *pBt = p->pBt;
  36368. sqlite3BtreeEnter(p);
  36369. #ifndef SQLITE_OMIT_AUTOVACUUM
  36370. if( pBt->autoVacuum ){
  36371. rc = autoVacuumCommit(pBt);
  36372. if( rc!=SQLITE_OK ){
  36373. sqlite3BtreeLeave(p);
  36374. return rc;
  36375. }
  36376. }
  36377. #endif
  36378. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  36379. sqlite3BtreeLeave(p);
  36380. }
  36381. return rc;
  36382. }
  36383. /*
  36384. ** Commit the transaction currently in progress.
  36385. **
  36386. ** This routine implements the second phase of a 2-phase commit. The
  36387. ** sqlite3BtreeSync() routine does the first phase and should be invoked
  36388. ** prior to calling this routine. The sqlite3BtreeSync() routine did
  36389. ** all the work of writing information out to disk and flushing the
  36390. ** contents so that they are written onto the disk platter. All this
  36391. ** routine has to do is delete or truncate the rollback journal
  36392. ** (which causes the transaction to commit) and drop locks.
  36393. **
  36394. ** This will release the write lock on the database file. If there
  36395. ** are no active cursors, it also releases the read lock.
  36396. */
  36397. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
  36398. BtShared *pBt = p->pBt;
  36399. sqlite3BtreeEnter(p);
  36400. btreeIntegrity(p);
  36401. /* If the handle has a write-transaction open, commit the shared-btrees
  36402. ** transaction and set the shared state to TRANS_READ.
  36403. */
  36404. if( p->inTrans==TRANS_WRITE ){
  36405. int rc;
  36406. assert( pBt->inTransaction==TRANS_WRITE );
  36407. assert( pBt->nTransaction>0 );
  36408. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  36409. if( rc!=SQLITE_OK ){
  36410. sqlite3BtreeLeave(p);
  36411. return rc;
  36412. }
  36413. pBt->inTransaction = TRANS_READ;
  36414. }
  36415. /* If the handle has any kind of transaction open, decrement the transaction
  36416. ** count of the shared btree. If the transaction count reaches 0, set
  36417. ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
  36418. ** will unlock the pager.
  36419. */
  36420. if( p->inTrans!=TRANS_NONE ){
  36421. clearAllSharedCacheTableLocks(p);
  36422. pBt->nTransaction--;
  36423. if( 0==pBt->nTransaction ){
  36424. pBt->inTransaction = TRANS_NONE;
  36425. }
  36426. }
  36427. /* Set the handles current transaction state to TRANS_NONE and unlock
  36428. ** the pager if this call closed the only read or write transaction.
  36429. */
  36430. btreeClearHasContent(pBt);
  36431. p->inTrans = TRANS_NONE;
  36432. unlockBtreeIfUnused(pBt);
  36433. btreeIntegrity(p);
  36434. sqlite3BtreeLeave(p);
  36435. return SQLITE_OK;
  36436. }
  36437. /*
  36438. ** Do both phases of a commit.
  36439. */
  36440. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  36441. int rc;
  36442. sqlite3BtreeEnter(p);
  36443. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  36444. if( rc==SQLITE_OK ){
  36445. rc = sqlite3BtreeCommitPhaseTwo(p);
  36446. }
  36447. sqlite3BtreeLeave(p);
  36448. return rc;
  36449. }
  36450. #ifndef NDEBUG
  36451. /*
  36452. ** Return the number of write-cursors open on this handle. This is for use
  36453. ** in assert() expressions, so it is only compiled if NDEBUG is not
  36454. ** defined.
  36455. **
  36456. ** For the purposes of this routine, a write-cursor is any cursor that
  36457. ** is capable of writing to the databse. That means the cursor was
  36458. ** originally opened for writing and the cursor has not be disabled
  36459. ** by having its state changed to CURSOR_FAULT.
  36460. */
  36461. static int countWriteCursors(BtShared *pBt){
  36462. BtCursor *pCur;
  36463. int r = 0;
  36464. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  36465. if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
  36466. }
  36467. return r;
  36468. }
  36469. #endif
  36470. /*
  36471. ** This routine sets the state to CURSOR_FAULT and the error
  36472. ** code to errCode for every cursor on BtShared that pBtree
  36473. ** references.
  36474. **
  36475. ** Every cursor is tripped, including cursors that belong
  36476. ** to other database connections that happen to be sharing
  36477. ** the cache with pBtree.
  36478. **
  36479. ** This routine gets called when a rollback occurs.
  36480. ** All cursors using the same cache must be tripped
  36481. ** to prevent them from trying to use the btree after
  36482. ** the rollback. The rollback may have deleted tables
  36483. ** or moved root pages, so it is not sufficient to
  36484. ** save the state of the cursor. The cursor must be
  36485. ** invalidated.
  36486. */
  36487. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  36488. BtCursor *p;
  36489. sqlite3BtreeEnter(pBtree);
  36490. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  36491. int i;
  36492. sqlite3BtreeClearCursor(p);
  36493. p->eState = CURSOR_FAULT;
  36494. p->skip = errCode;
  36495. for(i=0; i<=p->iPage; i++){
  36496. releasePage(p->apPage[i]);
  36497. p->apPage[i] = 0;
  36498. }
  36499. }
  36500. sqlite3BtreeLeave(pBtree);
  36501. }
  36502. /*
  36503. ** Rollback the transaction in progress. All cursors will be
  36504. ** invalided by this operation. Any attempt to use a cursor
  36505. ** that was open at the beginning of this operation will result
  36506. ** in an error.
  36507. **
  36508. ** This will release the write lock on the database file. If there
  36509. ** are no active cursors, it also releases the read lock.
  36510. */
  36511. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
  36512. int rc;
  36513. BtShared *pBt = p->pBt;
  36514. MemPage *pPage1;
  36515. sqlite3BtreeEnter(p);
  36516. rc = saveAllCursors(pBt, 0, 0);
  36517. #ifndef SQLITE_OMIT_SHARED_CACHE
  36518. if( rc!=SQLITE_OK ){
  36519. /* This is a horrible situation. An IO or malloc() error occurred whilst
  36520. ** trying to save cursor positions. If this is an automatic rollback (as
  36521. ** the result of a constraint, malloc() failure or IO error) then
  36522. ** the cache may be internally inconsistent (not contain valid trees) so
  36523. ** we cannot simply return the error to the caller. Instead, abort
  36524. ** all queries that may be using any of the cursors that failed to save.
  36525. */
  36526. sqlite3BtreeTripAllCursors(p, rc);
  36527. }
  36528. #endif
  36529. btreeIntegrity(p);
  36530. if( p->inTrans==TRANS_WRITE ){
  36531. int rc2;
  36532. assert( TRANS_WRITE==pBt->inTransaction );
  36533. rc2 = sqlite3PagerRollback(pBt->pPager);
  36534. if( rc2!=SQLITE_OK ){
  36535. rc = rc2;
  36536. }
  36537. /* The rollback may have destroyed the pPage1->aData value. So
  36538. ** call sqlite3BtreeGetPage() on page 1 again to make
  36539. ** sure pPage1->aData is set correctly. */
  36540. if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  36541. releasePage(pPage1);
  36542. }
  36543. assert( countWriteCursors(pBt)==0 );
  36544. pBt->inTransaction = TRANS_READ;
  36545. }
  36546. if( p->inTrans!=TRANS_NONE ){
  36547. clearAllSharedCacheTableLocks(p);
  36548. assert( pBt->nTransaction>0 );
  36549. pBt->nTransaction--;
  36550. if( 0==pBt->nTransaction ){
  36551. pBt->inTransaction = TRANS_NONE;
  36552. }
  36553. }
  36554. btreeClearHasContent(pBt);
  36555. p->inTrans = TRANS_NONE;
  36556. unlockBtreeIfUnused(pBt);
  36557. btreeIntegrity(p);
  36558. sqlite3BtreeLeave(p);
  36559. return rc;
  36560. }
  36561. /*
  36562. ** Start a statement subtransaction. The subtransaction can can be rolled
  36563. ** back independently of the main transaction. You must start a transaction
  36564. ** before starting a subtransaction. The subtransaction is ended automatically
  36565. ** if the main transaction commits or rolls back.
  36566. **
  36567. ** Statement subtransactions are used around individual SQL statements
  36568. ** that are contained within a BEGIN...COMMIT block. If a constraint
  36569. ** error occurs within the statement, the effect of that one statement
  36570. ** can be rolled back without having to rollback the entire transaction.
  36571. **
  36572. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  36573. ** value passed as the second parameter is the total number of savepoints,
  36574. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  36575. ** are no active savepoints and no other statement-transactions open,
  36576. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  36577. ** using the sqlite3BtreeSavepoint() function.
  36578. */
  36579. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  36580. int rc;
  36581. BtShared *pBt = p->pBt;
  36582. sqlite3BtreeEnter(p);
  36583. assert( p->inTrans==TRANS_WRITE );
  36584. assert( pBt->readOnly==0 );
  36585. assert( iStatement>0 );
  36586. assert( iStatement>p->db->nSavepoint );
  36587. if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
  36588. rc = SQLITE_INTERNAL;
  36589. }else{
  36590. assert( pBt->inTransaction==TRANS_WRITE );
  36591. /* At the pager level, a statement transaction is a savepoint with
  36592. ** an index greater than all savepoints created explicitly using
  36593. ** SQL statements. It is illegal to open, release or rollback any
  36594. ** such savepoints while the statement transaction savepoint is active.
  36595. */
  36596. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  36597. }
  36598. sqlite3BtreeLeave(p);
  36599. return rc;
  36600. }
  36601. /*
  36602. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  36603. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  36604. ** savepoint identified by parameter iSavepoint, depending on the value
  36605. ** of op.
  36606. **
  36607. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  36608. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  36609. ** contents of the entire transaction are rolled back. This is different
  36610. ** from a normal transaction rollback, as no locks are released and the
  36611. ** transaction remains open.
  36612. */
  36613. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  36614. int rc = SQLITE_OK;
  36615. if( p && p->inTrans==TRANS_WRITE ){
  36616. BtShared *pBt = p->pBt;
  36617. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  36618. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  36619. sqlite3BtreeEnter(p);
  36620. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  36621. if( rc==SQLITE_OK ){
  36622. rc = newDatabase(pBt);
  36623. }
  36624. sqlite3BtreeLeave(p);
  36625. }
  36626. return rc;
  36627. }
  36628. /*
  36629. ** Create a new cursor for the BTree whose root is on the page
  36630. ** iTable. The act of acquiring a cursor gets a read lock on
  36631. ** the database file.
  36632. **
  36633. ** If wrFlag==0, then the cursor can only be used for reading.
  36634. ** If wrFlag==1, then the cursor can be used for reading or for
  36635. ** writing if other conditions for writing are also met. These
  36636. ** are the conditions that must be met in order for writing to
  36637. ** be allowed:
  36638. **
  36639. ** 1: The cursor must have been opened with wrFlag==1
  36640. **
  36641. ** 2: Other database connections that share the same pager cache
  36642. ** but which are not in the READ_UNCOMMITTED state may not have
  36643. ** cursors open with wrFlag==0 on the same table. Otherwise
  36644. ** the changes made by this write cursor would be visible to
  36645. ** the read cursors in the other database connection.
  36646. **
  36647. ** 3: The database must be writable (not on read-only media)
  36648. **
  36649. ** 4: There must be an active transaction.
  36650. **
  36651. ** No checking is done to make sure that page iTable really is the
  36652. ** root page of a b-tree. If it is not, then the cursor acquired
  36653. ** will not work correctly.
  36654. **
  36655. ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
  36656. ** pointed to by pCur have been zeroed by the caller.
  36657. */
  36658. static int btreeCursor(
  36659. Btree *p, /* The btree */
  36660. int iTable, /* Root page of table to open */
  36661. int wrFlag, /* 1 to write. 0 read-only */
  36662. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  36663. BtCursor *pCur /* Space for new cursor */
  36664. ){
  36665. int rc;
  36666. Pgno nPage;
  36667. BtShared *pBt = p->pBt;
  36668. assert( sqlite3BtreeHoldsMutex(p) );
  36669. assert( wrFlag==0 || wrFlag==1 );
  36670. if( wrFlag ){
  36671. assert( !pBt->readOnly );
  36672. if( NEVER(pBt->readOnly) ){
  36673. return SQLITE_READONLY;
  36674. }
  36675. rc = checkForReadConflicts(p, iTable, 0, 0);
  36676. if( rc!=SQLITE_OK ){
  36677. assert( rc==SQLITE_LOCKED_SHAREDCACHE );
  36678. return rc;
  36679. }
  36680. }
  36681. if( pBt->pPage1==0 ){
  36682. rc = lockBtreeWithRetry(p);
  36683. if( rc!=SQLITE_OK ){
  36684. return rc;
  36685. }
  36686. }
  36687. pCur->pgnoRoot = (Pgno)iTable;
  36688. rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
  36689. if( rc!=SQLITE_OK ){
  36690. return rc;
  36691. }
  36692. if( iTable==1 && nPage==0 ){
  36693. rc = SQLITE_EMPTY;
  36694. goto create_cursor_exception;
  36695. }
  36696. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
  36697. if( rc!=SQLITE_OK ){
  36698. goto create_cursor_exception;
  36699. }
  36700. /* Now that no other errors can occur, finish filling in the BtCursor
  36701. ** variables, link the cursor into the BtShared list and set *ppCur (the
  36702. ** output argument to this function).
  36703. */
  36704. pCur->pKeyInfo = pKeyInfo;
  36705. pCur->pBtree = p;
  36706. pCur->pBt = pBt;
  36707. pCur->wrFlag = (u8)wrFlag;
  36708. pCur->pNext = pBt->pCursor;
  36709. if( pCur->pNext ){
  36710. pCur->pNext->pPrev = pCur;
  36711. }
  36712. pBt->pCursor = pCur;
  36713. pCur->eState = CURSOR_INVALID;
  36714. pCur->cachedRowid = 0;
  36715. return SQLITE_OK;
  36716. create_cursor_exception:
  36717. releasePage(pCur->apPage[0]);
  36718. unlockBtreeIfUnused(pBt);
  36719. return rc;
  36720. }
  36721. SQLITE_PRIVATE int sqlite3BtreeCursor(
  36722. Btree *p, /* The btree */
  36723. int iTable, /* Root page of table to open */
  36724. int wrFlag, /* 1 to write. 0 read-only */
  36725. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  36726. BtCursor *pCur /* Write new cursor here */
  36727. ){
  36728. int rc;
  36729. sqlite3BtreeEnter(p);
  36730. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  36731. sqlite3BtreeLeave(p);
  36732. return rc;
  36733. }
  36734. /*
  36735. ** Return the size of a BtCursor object in bytes.
  36736. **
  36737. ** This interfaces is needed so that users of cursors can preallocate
  36738. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  36739. ** to users so they cannot do the sizeof() themselves - they must call
  36740. ** this routine.
  36741. */
  36742. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  36743. return sizeof(BtCursor);
  36744. }
  36745. /*
  36746. ** Set the cached rowid value of every cursor in the same database file
  36747. ** as pCur and having the same root page number as pCur. The value is
  36748. ** set to iRowid.
  36749. **
  36750. ** Only positive rowid values are considered valid for this cache.
  36751. ** The cache is initialized to zero, indicating an invalid cache.
  36752. ** A btree will work fine with zero or negative rowids. We just cannot
  36753. ** cache zero or negative rowids, which means tables that use zero or
  36754. ** negative rowids might run a little slower. But in practice, zero
  36755. ** or negative rowids are very uncommon so this should not be a problem.
  36756. */
  36757. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  36758. BtCursor *p;
  36759. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  36760. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  36761. }
  36762. assert( pCur->cachedRowid==iRowid );
  36763. }
  36764. /*
  36765. ** Return the cached rowid for the given cursor. A negative or zero
  36766. ** return value indicates that the rowid cache is invalid and should be
  36767. ** ignored. If the rowid cache has never before been set, then a
  36768. ** zero is returned.
  36769. */
  36770. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  36771. return pCur->cachedRowid;
  36772. }
  36773. /*
  36774. ** Close a cursor. The read lock on the database file is released
  36775. ** when the last cursor is closed.
  36776. */
  36777. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  36778. Btree *pBtree = pCur->pBtree;
  36779. if( pBtree ){
  36780. int i;
  36781. BtShared *pBt = pCur->pBt;
  36782. sqlite3BtreeEnter(pBtree);
  36783. sqlite3BtreeClearCursor(pCur);
  36784. if( pCur->pPrev ){
  36785. pCur->pPrev->pNext = pCur->pNext;
  36786. }else{
  36787. pBt->pCursor = pCur->pNext;
  36788. }
  36789. if( pCur->pNext ){
  36790. pCur->pNext->pPrev = pCur->pPrev;
  36791. }
  36792. for(i=0; i<=pCur->iPage; i++){
  36793. releasePage(pCur->apPage[i]);
  36794. }
  36795. unlockBtreeIfUnused(pBt);
  36796. invalidateOverflowCache(pCur);
  36797. /* sqlite3_free(pCur); */
  36798. sqlite3BtreeLeave(pBtree);
  36799. }
  36800. return SQLITE_OK;
  36801. }
  36802. /*
  36803. ** Make a temporary cursor by filling in the fields of pTempCur.
  36804. ** The temporary cursor is not on the cursor list for the Btree.
  36805. */
  36806. SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
  36807. int i;
  36808. assert( cursorHoldsMutex(pCur) );
  36809. memcpy(pTempCur, pCur, sizeof(BtCursor));
  36810. pTempCur->pNext = 0;
  36811. pTempCur->pPrev = 0;
  36812. for(i=0; i<=pTempCur->iPage; i++){
  36813. sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
  36814. }
  36815. assert( pTempCur->pKey==0 );
  36816. }
  36817. /*
  36818. ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
  36819. ** function above.
  36820. */
  36821. SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
  36822. int i;
  36823. assert( cursorHoldsMutex(pCur) );
  36824. for(i=0; i<=pCur->iPage; i++){
  36825. sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
  36826. }
  36827. sqlite3_free(pCur->pKey);
  36828. }
  36829. /*
  36830. ** Make sure the BtCursor* given in the argument has a valid
  36831. ** BtCursor.info structure. If it is not already valid, call
  36832. ** sqlite3BtreeParseCell() to fill it in.
  36833. **
  36834. ** BtCursor.info is a cache of the information in the current cell.
  36835. ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
  36836. **
  36837. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  36838. ** compiler to crash when getCellInfo() is implemented as a macro.
  36839. ** But there is a measureable speed advantage to using the macro on gcc
  36840. ** (when less compiler optimizations like -Os or -O0 are used and the
  36841. ** compiler is not doing agressive inlining.) So we use a real function
  36842. ** for MSVC and a macro for everything else. Ticket #2457.
  36843. */
  36844. #ifndef NDEBUG
  36845. static void assertCellInfo(BtCursor *pCur){
  36846. CellInfo info;
  36847. int iPage = pCur->iPage;
  36848. memset(&info, 0, sizeof(info));
  36849. sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  36850. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  36851. }
  36852. #else
  36853. #define assertCellInfo(x)
  36854. #endif
  36855. #ifdef _MSC_VER
  36856. /* Use a real function in MSVC to work around bugs in that compiler. */
  36857. static void getCellInfo(BtCursor *pCur){
  36858. if( pCur->info.nSize==0 ){
  36859. int iPage = pCur->iPage;
  36860. sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  36861. pCur->validNKey = 1;
  36862. }else{
  36863. assertCellInfo(pCur);
  36864. }
  36865. }
  36866. #else /* if not _MSC_VER */
  36867. /* Use a macro in all other compilers so that the function is inlined */
  36868. #define getCellInfo(pCur) \
  36869. if( pCur->info.nSize==0 ){ \
  36870. int iPage = pCur->iPage; \
  36871. sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  36872. pCur->validNKey = 1; \
  36873. }else{ \
  36874. assertCellInfo(pCur); \
  36875. }
  36876. #endif /* _MSC_VER */
  36877. /*
  36878. ** Set *pSize to the size of the buffer needed to hold the value of
  36879. ** the key for the current entry. If the cursor is not pointing
  36880. ** to a valid entry, *pSize is set to 0.
  36881. **
  36882. ** For a table with the INTKEY flag set, this routine returns the key
  36883. ** itself, not the number of bytes in the key.
  36884. */
  36885. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  36886. int rc;
  36887. assert( cursorHoldsMutex(pCur) );
  36888. rc = restoreCursorPosition(pCur);
  36889. if( rc==SQLITE_OK ){
  36890. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  36891. if( pCur->eState==CURSOR_INVALID ){
  36892. *pSize = 0;
  36893. }else{
  36894. getCellInfo(pCur);
  36895. *pSize = pCur->info.nKey;
  36896. }
  36897. }
  36898. return rc;
  36899. }
  36900. /*
  36901. ** Set *pSize to the number of bytes of data in the entry the
  36902. ** cursor currently points to. Always return SQLITE_OK.
  36903. ** Failure is not possible. If the cursor is not currently
  36904. ** pointing to an entry (which can happen, for example, if
  36905. ** the database is empty) then *pSize is set to 0.
  36906. */
  36907. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  36908. int rc;
  36909. assert( cursorHoldsMutex(pCur) );
  36910. rc = restoreCursorPosition(pCur);
  36911. if( rc==SQLITE_OK ){
  36912. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  36913. if( pCur->eState==CURSOR_INVALID ){
  36914. /* Not pointing at a valid entry - set *pSize to 0. */
  36915. *pSize = 0;
  36916. }else{
  36917. getCellInfo(pCur);
  36918. *pSize = pCur->info.nData;
  36919. }
  36920. }
  36921. return rc;
  36922. }
  36923. /*
  36924. ** Given the page number of an overflow page in the database (parameter
  36925. ** ovfl), this function finds the page number of the next page in the
  36926. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  36927. ** pointer-map data instead of reading the content of page ovfl to do so.
  36928. **
  36929. ** If an error occurs an SQLite error code is returned. Otherwise:
  36930. **
  36931. ** The page number of the next overflow page in the linked list is
  36932. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  36933. ** list, *pPgnoNext is set to zero.
  36934. **
  36935. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  36936. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  36937. ** reference. It is the responsibility of the caller to call releasePage()
  36938. ** on *ppPage to free the reference. In no reference was obtained (because
  36939. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  36940. ** *ppPage is set to zero.
  36941. */
  36942. static int getOverflowPage(
  36943. BtShared *pBt,
  36944. Pgno ovfl, /* Overflow page */
  36945. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  36946. Pgno *pPgnoNext /* OUT: Next overflow page number */
  36947. ){
  36948. Pgno next = 0;
  36949. MemPage *pPage = 0;
  36950. int rc = SQLITE_OK;
  36951. assert( sqlite3_mutex_held(pBt->mutex) );
  36952. assert(pPgnoNext);
  36953. #ifndef SQLITE_OMIT_AUTOVACUUM
  36954. /* Try to find the next page in the overflow list using the
  36955. ** autovacuum pointer-map pages. Guess that the next page in
  36956. ** the overflow list is page number (ovfl+1). If that guess turns
  36957. ** out to be wrong, fall back to loading the data of page
  36958. ** number ovfl to determine the next page number.
  36959. */
  36960. if( pBt->autoVacuum ){
  36961. Pgno pgno;
  36962. Pgno iGuess = ovfl+1;
  36963. u8 eType;
  36964. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  36965. iGuess++;
  36966. }
  36967. if( iGuess<=pagerPagecount(pBt) ){
  36968. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  36969. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  36970. next = iGuess;
  36971. rc = SQLITE_DONE;
  36972. }
  36973. }
  36974. }
  36975. #endif
  36976. if( rc==SQLITE_OK ){
  36977. rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
  36978. assert(rc==SQLITE_OK || pPage==0);
  36979. if( next==0 && rc==SQLITE_OK ){
  36980. next = get4byte(pPage->aData);
  36981. }
  36982. }
  36983. *pPgnoNext = next;
  36984. if( ppPage ){
  36985. *ppPage = pPage;
  36986. }else{
  36987. releasePage(pPage);
  36988. }
  36989. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  36990. }
  36991. /*
  36992. ** Copy data from a buffer to a page, or from a page to a buffer.
  36993. **
  36994. ** pPayload is a pointer to data stored on database page pDbPage.
  36995. ** If argument eOp is false, then nByte bytes of data are copied
  36996. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  36997. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  36998. ** of data are copied from the buffer pBuf to pPayload.
  36999. **
  37000. ** SQLITE_OK is returned on success, otherwise an error code.
  37001. */
  37002. static int copyPayload(
  37003. void *pPayload, /* Pointer to page data */
  37004. void *pBuf, /* Pointer to buffer */
  37005. int nByte, /* Number of bytes to copy */
  37006. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  37007. DbPage *pDbPage /* Page containing pPayload */
  37008. ){
  37009. if( eOp ){
  37010. /* Copy data from buffer to page (a write operation) */
  37011. int rc = sqlite3PagerWrite(pDbPage);
  37012. if( rc!=SQLITE_OK ){
  37013. return rc;
  37014. }
  37015. memcpy(pPayload, pBuf, nByte);
  37016. }else{
  37017. /* Copy data from page to buffer (a read operation) */
  37018. memcpy(pBuf, pPayload, nByte);
  37019. }
  37020. return SQLITE_OK;
  37021. }
  37022. /*
  37023. ** This function is used to read or overwrite payload information
  37024. ** for the entry that the pCur cursor is pointing to. If the eOp
  37025. ** parameter is 0, this is a read operation (data copied into
  37026. ** buffer pBuf). If it is non-zero, a write (data copied from
  37027. ** buffer pBuf).
  37028. **
  37029. ** A total of "amt" bytes are read or written beginning at "offset".
  37030. ** Data is read to or from the buffer pBuf.
  37031. **
  37032. ** This routine does not make a distinction between key and data.
  37033. ** It just reads or writes bytes from the payload area. Data might
  37034. ** appear on the main page or be scattered out on multiple overflow
  37035. ** pages.
  37036. **
  37037. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  37038. ** cursor entry uses one or more overflow pages, this function
  37039. ** allocates space for and lazily popluates the overflow page-list
  37040. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  37041. ** cache to make seeking to the supplied offset more efficient.
  37042. **
  37043. ** Once an overflow page-list cache has been allocated, it may be
  37044. ** invalidated if some other cursor writes to the same table, or if
  37045. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  37046. ** mode, the following events may invalidate an overflow page-list cache.
  37047. **
  37048. ** * An incremental vacuum,
  37049. ** * A commit in auto_vacuum="full" mode,
  37050. ** * Creating a table (may require moving an overflow page).
  37051. */
  37052. static int accessPayload(
  37053. BtCursor *pCur, /* Cursor pointing to entry to read from */
  37054. u32 offset, /* Begin reading this far into payload */
  37055. u32 amt, /* Read this many bytes */
  37056. unsigned char *pBuf, /* Write the bytes into this buffer */
  37057. int skipKey, /* offset begins at data if this is true */
  37058. int eOp /* zero to read. non-zero to write. */
  37059. ){
  37060. unsigned char *aPayload;
  37061. int rc = SQLITE_OK;
  37062. u32 nKey;
  37063. int iIdx = 0;
  37064. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  37065. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  37066. assert( pPage );
  37067. assert( pCur->eState==CURSOR_VALID );
  37068. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  37069. assert( cursorHoldsMutex(pCur) );
  37070. getCellInfo(pCur);
  37071. aPayload = pCur->info.pCell + pCur->info.nHeader;
  37072. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  37073. if( skipKey ){
  37074. offset += nKey;
  37075. }
  37076. if( offset+amt > nKey+pCur->info.nData
  37077. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  37078. ){
  37079. /* Trying to read or write past the end of the data is an error */
  37080. return SQLITE_CORRUPT_BKPT;
  37081. }
  37082. /* Check if data must be read/written to/from the btree page itself. */
  37083. if( offset<pCur->info.nLocal ){
  37084. int a = amt;
  37085. if( a+offset>pCur->info.nLocal ){
  37086. a = pCur->info.nLocal - offset;
  37087. }
  37088. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  37089. offset = 0;
  37090. pBuf += a;
  37091. amt -= a;
  37092. }else{
  37093. offset -= pCur->info.nLocal;
  37094. }
  37095. if( rc==SQLITE_OK && amt>0 ){
  37096. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  37097. Pgno nextPage;
  37098. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  37099. #ifndef SQLITE_OMIT_INCRBLOB
  37100. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  37101. ** has not been allocated, allocate it now. The array is sized at
  37102. ** one entry for each overflow page in the overflow chain. The
  37103. ** page number of the first overflow page is stored in aOverflow[0],
  37104. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  37105. ** (the cache is lazily populated).
  37106. */
  37107. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  37108. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  37109. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  37110. if( nOvfl && !pCur->aOverflow ){
  37111. rc = SQLITE_NOMEM;
  37112. }
  37113. }
  37114. /* If the overflow page-list cache has been allocated and the
  37115. ** entry for the first required overflow page is valid, skip
  37116. ** directly to it.
  37117. */
  37118. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  37119. iIdx = (offset/ovflSize);
  37120. nextPage = pCur->aOverflow[iIdx];
  37121. offset = (offset%ovflSize);
  37122. }
  37123. #endif
  37124. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  37125. #ifndef SQLITE_OMIT_INCRBLOB
  37126. /* If required, populate the overflow page-list cache. */
  37127. if( pCur->aOverflow ){
  37128. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  37129. pCur->aOverflow[iIdx] = nextPage;
  37130. }
  37131. #endif
  37132. if( offset>=ovflSize ){
  37133. /* The only reason to read this page is to obtain the page
  37134. ** number for the next page in the overflow chain. The page
  37135. ** data is not required. So first try to lookup the overflow
  37136. ** page-list cache, if any, then fall back to the getOverflowPage()
  37137. ** function.
  37138. */
  37139. #ifndef SQLITE_OMIT_INCRBLOB
  37140. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  37141. nextPage = pCur->aOverflow[iIdx+1];
  37142. } else
  37143. #endif
  37144. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  37145. offset -= ovflSize;
  37146. }else{
  37147. /* Need to read this page properly. It contains some of the
  37148. ** range of data that is being read (eOp==0) or written (eOp!=0).
  37149. */
  37150. DbPage *pDbPage;
  37151. int a = amt;
  37152. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
  37153. if( rc==SQLITE_OK ){
  37154. aPayload = sqlite3PagerGetData(pDbPage);
  37155. nextPage = get4byte(aPayload);
  37156. if( a + offset > ovflSize ){
  37157. a = ovflSize - offset;
  37158. }
  37159. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  37160. sqlite3PagerUnref(pDbPage);
  37161. offset = 0;
  37162. amt -= a;
  37163. pBuf += a;
  37164. }
  37165. }
  37166. }
  37167. }
  37168. if( rc==SQLITE_OK && amt>0 ){
  37169. return SQLITE_CORRUPT_BKPT;
  37170. }
  37171. return rc;
  37172. }
  37173. /*
  37174. ** Read part of the key associated with cursor pCur. Exactly
  37175. ** "amt" bytes will be transfered into pBuf[]. The transfer
  37176. ** begins at "offset".
  37177. **
  37178. ** Return SQLITE_OK on success or an error code if anything goes
  37179. ** wrong. An error is returned if "offset+amt" is larger than
  37180. ** the available payload.
  37181. */
  37182. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  37183. int rc;
  37184. assert( cursorHoldsMutex(pCur) );
  37185. rc = restoreCursorPosition(pCur);
  37186. if( rc==SQLITE_OK ){
  37187. assert( pCur->eState==CURSOR_VALID );
  37188. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  37189. if( pCur->apPage[0]->intKey ){
  37190. return SQLITE_CORRUPT_BKPT;
  37191. }
  37192. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  37193. rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
  37194. }
  37195. return rc;
  37196. }
  37197. /*
  37198. ** Read part of the data associated with cursor pCur. Exactly
  37199. ** "amt" bytes will be transfered into pBuf[]. The transfer
  37200. ** begins at "offset".
  37201. **
  37202. ** Return SQLITE_OK on success or an error code if anything goes
  37203. ** wrong. An error is returned if "offset+amt" is larger than
  37204. ** the available payload.
  37205. */
  37206. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  37207. int rc;
  37208. #ifndef SQLITE_OMIT_INCRBLOB
  37209. if ( pCur->eState==CURSOR_INVALID ){
  37210. return SQLITE_ABORT;
  37211. }
  37212. #endif
  37213. assert( cursorHoldsMutex(pCur) );
  37214. rc = restoreCursorPosition(pCur);
  37215. if( rc==SQLITE_OK ){
  37216. assert( pCur->eState==CURSOR_VALID );
  37217. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  37218. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  37219. rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
  37220. }
  37221. return rc;
  37222. }
  37223. /*
  37224. ** Return a pointer to payload information from the entry that the
  37225. ** pCur cursor is pointing to. The pointer is to the beginning of
  37226. ** the key if skipKey==0 and it points to the beginning of data if
  37227. ** skipKey==1. The number of bytes of available key/data is written
  37228. ** into *pAmt. If *pAmt==0, then the value returned will not be
  37229. ** a valid pointer.
  37230. **
  37231. ** This routine is an optimization. It is common for the entire key
  37232. ** and data to fit on the local page and for there to be no overflow
  37233. ** pages. When that is so, this routine can be used to access the
  37234. ** key and data without making a copy. If the key and/or data spills
  37235. ** onto overflow pages, then accessPayload() must be used to reassemble
  37236. ** the key/data and copy it into a preallocated buffer.
  37237. **
  37238. ** The pointer returned by this routine looks directly into the cached
  37239. ** page of the database. The data might change or move the next time
  37240. ** any btree routine is called.
  37241. */
  37242. static const unsigned char *fetchPayload(
  37243. BtCursor *pCur, /* Cursor pointing to entry to read from */
  37244. int *pAmt, /* Write the number of available bytes here */
  37245. int skipKey /* read beginning at data if this is true */
  37246. ){
  37247. unsigned char *aPayload;
  37248. MemPage *pPage;
  37249. u32 nKey;
  37250. u32 nLocal;
  37251. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  37252. assert( pCur->eState==CURSOR_VALID );
  37253. assert( cursorHoldsMutex(pCur) );
  37254. pPage = pCur->apPage[pCur->iPage];
  37255. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  37256. getCellInfo(pCur);
  37257. aPayload = pCur->info.pCell;
  37258. aPayload += pCur->info.nHeader;
  37259. if( pPage->intKey ){
  37260. nKey = 0;
  37261. }else{
  37262. nKey = (int)pCur->info.nKey;
  37263. }
  37264. if( skipKey ){
  37265. aPayload += nKey;
  37266. nLocal = pCur->info.nLocal - nKey;
  37267. }else{
  37268. nLocal = pCur->info.nLocal;
  37269. if( nLocal>nKey ){
  37270. nLocal = nKey;
  37271. }
  37272. }
  37273. *pAmt = nLocal;
  37274. return aPayload;
  37275. }
  37276. /*
  37277. ** For the entry that cursor pCur is point to, return as
  37278. ** many bytes of the key or data as are available on the local
  37279. ** b-tree page. Write the number of available bytes into *pAmt.
  37280. **
  37281. ** The pointer returned is ephemeral. The key/data may move
  37282. ** or be destroyed on the next call to any Btree routine,
  37283. ** including calls from other threads against the same cache.
  37284. ** Hence, a mutex on the BtShared should be held prior to calling
  37285. ** this routine.
  37286. **
  37287. ** These routines is used to get quick access to key and data
  37288. ** in the common case where no overflow pages are used.
  37289. */
  37290. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  37291. assert( cursorHoldsMutex(pCur) );
  37292. if( pCur->eState==CURSOR_VALID ){
  37293. return (const void*)fetchPayload(pCur, pAmt, 0);
  37294. }
  37295. return 0;
  37296. }
  37297. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  37298. assert( cursorHoldsMutex(pCur) );
  37299. if( pCur->eState==CURSOR_VALID ){
  37300. return (const void*)fetchPayload(pCur, pAmt, 1);
  37301. }
  37302. return 0;
  37303. }
  37304. /*
  37305. ** Move the cursor down to a new child page. The newPgno argument is the
  37306. ** page number of the child page to move to.
  37307. */
  37308. static int moveToChild(BtCursor *pCur, u32 newPgno){
  37309. int rc;
  37310. int i = pCur->iPage;
  37311. MemPage *pNewPage;
  37312. BtShared *pBt = pCur->pBt;
  37313. assert( cursorHoldsMutex(pCur) );
  37314. assert( pCur->eState==CURSOR_VALID );
  37315. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  37316. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  37317. return SQLITE_CORRUPT_BKPT;
  37318. }
  37319. rc = getAndInitPage(pBt, newPgno, &pNewPage);
  37320. if( rc ) return rc;
  37321. pCur->apPage[i+1] = pNewPage;
  37322. pCur->aiIdx[i+1] = 0;
  37323. pCur->iPage++;
  37324. pCur->info.nSize = 0;
  37325. pCur->validNKey = 0;
  37326. if( pNewPage->nCell<1 ){
  37327. return SQLITE_CORRUPT_BKPT;
  37328. }
  37329. return SQLITE_OK;
  37330. }
  37331. #ifndef NDEBUG
  37332. /*
  37333. ** Page pParent is an internal (non-leaf) tree page. This function
  37334. ** asserts that page number iChild is the left-child if the iIdx'th
  37335. ** cell in page pParent. Or, if iIdx is equal to the total number of
  37336. ** cells in pParent, that page number iChild is the right-child of
  37337. ** the page.
  37338. */
  37339. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  37340. assert( iIdx<=pParent->nCell );
  37341. if( iIdx==pParent->nCell ){
  37342. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  37343. }else{
  37344. assert( get4byte(findCell(pParent, iIdx))==iChild );
  37345. }
  37346. }
  37347. #else
  37348. # define assertParentIndex(x,y,z)
  37349. #endif
  37350. /*
  37351. ** Move the cursor up to the parent page.
  37352. **
  37353. ** pCur->idx is set to the cell index that contains the pointer
  37354. ** to the page we are coming from. If we are coming from the
  37355. ** right-most child page then pCur->idx is set to one more than
  37356. ** the largest cell index.
  37357. */
  37358. SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
  37359. assert( cursorHoldsMutex(pCur) );
  37360. assert( pCur->eState==CURSOR_VALID );
  37361. assert( pCur->iPage>0 );
  37362. assert( pCur->apPage[pCur->iPage] );
  37363. assertParentIndex(
  37364. pCur->apPage[pCur->iPage-1],
  37365. pCur->aiIdx[pCur->iPage-1],
  37366. pCur->apPage[pCur->iPage]->pgno
  37367. );
  37368. releasePage(pCur->apPage[pCur->iPage]);
  37369. pCur->iPage--;
  37370. pCur->info.nSize = 0;
  37371. pCur->validNKey = 0;
  37372. }
  37373. /*
  37374. ** Move the cursor to the root page
  37375. */
  37376. static int moveToRoot(BtCursor *pCur){
  37377. MemPage *pRoot;
  37378. int rc = SQLITE_OK;
  37379. Btree *p = pCur->pBtree;
  37380. BtShared *pBt = p->pBt;
  37381. assert( cursorHoldsMutex(pCur) );
  37382. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  37383. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  37384. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  37385. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  37386. if( pCur->eState==CURSOR_FAULT ){
  37387. return pCur->skip;
  37388. }
  37389. sqlite3BtreeClearCursor(pCur);
  37390. }
  37391. if( pCur->iPage>=0 ){
  37392. int i;
  37393. for(i=1; i<=pCur->iPage; i++){
  37394. releasePage(pCur->apPage[i]);
  37395. }
  37396. }else{
  37397. if(
  37398. SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
  37399. ){
  37400. pCur->eState = CURSOR_INVALID;
  37401. return rc;
  37402. }
  37403. }
  37404. pRoot = pCur->apPage[0];
  37405. assert( pRoot->pgno==pCur->pgnoRoot );
  37406. pCur->iPage = 0;
  37407. pCur->aiIdx[0] = 0;
  37408. pCur->info.nSize = 0;
  37409. pCur->atLast = 0;
  37410. pCur->validNKey = 0;
  37411. if( pRoot->nCell==0 && !pRoot->leaf ){
  37412. Pgno subpage;
  37413. assert( pRoot->pgno==1 );
  37414. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  37415. assert( subpage>0 );
  37416. pCur->eState = CURSOR_VALID;
  37417. rc = moveToChild(pCur, subpage);
  37418. }else{
  37419. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  37420. }
  37421. return rc;
  37422. }
  37423. /*
  37424. ** Move the cursor down to the left-most leaf entry beneath the
  37425. ** entry to which it is currently pointing.
  37426. **
  37427. ** The left-most leaf is the one with the smallest key - the first
  37428. ** in ascending order.
  37429. */
  37430. static int moveToLeftmost(BtCursor *pCur){
  37431. Pgno pgno;
  37432. int rc = SQLITE_OK;
  37433. MemPage *pPage;
  37434. assert( cursorHoldsMutex(pCur) );
  37435. assert( pCur->eState==CURSOR_VALID );
  37436. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  37437. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  37438. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  37439. rc = moveToChild(pCur, pgno);
  37440. }
  37441. return rc;
  37442. }
  37443. /*
  37444. ** Move the cursor down to the right-most leaf entry beneath the
  37445. ** page to which it is currently pointing. Notice the difference
  37446. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  37447. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  37448. ** finds the right-most entry beneath the *page*.
  37449. **
  37450. ** The right-most entry is the one with the largest key - the last
  37451. ** key in ascending order.
  37452. */
  37453. static int moveToRightmost(BtCursor *pCur){
  37454. Pgno pgno;
  37455. int rc = SQLITE_OK;
  37456. MemPage *pPage = 0;
  37457. assert( cursorHoldsMutex(pCur) );
  37458. assert( pCur->eState==CURSOR_VALID );
  37459. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  37460. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  37461. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  37462. rc = moveToChild(pCur, pgno);
  37463. }
  37464. if( rc==SQLITE_OK ){
  37465. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  37466. pCur->info.nSize = 0;
  37467. pCur->validNKey = 0;
  37468. }
  37469. return rc;
  37470. }
  37471. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  37472. ** on success. Set *pRes to 0 if the cursor actually points to something
  37473. ** or set *pRes to 1 if the table is empty.
  37474. */
  37475. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  37476. int rc;
  37477. assert( cursorHoldsMutex(pCur) );
  37478. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37479. rc = moveToRoot(pCur);
  37480. if( rc==SQLITE_OK ){
  37481. if( pCur->eState==CURSOR_INVALID ){
  37482. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  37483. *pRes = 1;
  37484. rc = SQLITE_OK;
  37485. }else{
  37486. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  37487. *pRes = 0;
  37488. rc = moveToLeftmost(pCur);
  37489. }
  37490. }
  37491. return rc;
  37492. }
  37493. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  37494. ** on success. Set *pRes to 0 if the cursor actually points to something
  37495. ** or set *pRes to 1 if the table is empty.
  37496. */
  37497. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  37498. int rc;
  37499. assert( cursorHoldsMutex(pCur) );
  37500. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37501. rc = moveToRoot(pCur);
  37502. if( rc==SQLITE_OK ){
  37503. if( CURSOR_INVALID==pCur->eState ){
  37504. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  37505. *pRes = 1;
  37506. }else{
  37507. assert( pCur->eState==CURSOR_VALID );
  37508. *pRes = 0;
  37509. rc = moveToRightmost(pCur);
  37510. getCellInfo(pCur);
  37511. pCur->atLast = rc==SQLITE_OK ?1:0;
  37512. }
  37513. }
  37514. return rc;
  37515. }
  37516. /* Move the cursor so that it points to an entry near the key
  37517. ** specified by pIdxKey or intKey. Return a success code.
  37518. **
  37519. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  37520. ** must be NULL. For index tables, pIdxKey is used and intKey
  37521. ** is ignored.
  37522. **
  37523. ** If an exact match is not found, then the cursor is always
  37524. ** left pointing at a leaf page which would hold the entry if it
  37525. ** were present. The cursor might point to an entry that comes
  37526. ** before or after the key.
  37527. **
  37528. ** An integer is written into *pRes which is the result of
  37529. ** comparing the key with the entry to which the cursor is
  37530. ** pointing. The meaning of the integer written into
  37531. ** *pRes is as follows:
  37532. **
  37533. ** *pRes<0 The cursor is left pointing at an entry that
  37534. ** is smaller than intKey/pIdxKey or if the table is empty
  37535. ** and the cursor is therefore left point to nothing.
  37536. **
  37537. ** *pRes==0 The cursor is left pointing at an entry that
  37538. ** exactly matches intKey/pIdxKey.
  37539. **
  37540. ** *pRes>0 The cursor is left pointing at an entry that
  37541. ** is larger than intKey/pIdxKey.
  37542. **
  37543. */
  37544. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  37545. BtCursor *pCur, /* The cursor to be moved */
  37546. UnpackedRecord *pIdxKey, /* Unpacked index key */
  37547. i64 intKey, /* The table key */
  37548. int biasRight, /* If true, bias the search to the high end */
  37549. int *pRes /* Write search results here */
  37550. ){
  37551. int rc;
  37552. assert( cursorHoldsMutex(pCur) );
  37553. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37554. /* If the cursor is already positioned at the point we are trying
  37555. ** to move to, then just return without doing any work */
  37556. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  37557. && pCur->apPage[0]->intKey
  37558. ){
  37559. if( pCur->info.nKey==intKey ){
  37560. *pRes = 0;
  37561. return SQLITE_OK;
  37562. }
  37563. if( pCur->atLast && pCur->info.nKey<intKey ){
  37564. *pRes = -1;
  37565. return SQLITE_OK;
  37566. }
  37567. }
  37568. rc = moveToRoot(pCur);
  37569. if( rc ){
  37570. return rc;
  37571. }
  37572. assert( pCur->apPage[pCur->iPage] );
  37573. assert( pCur->apPage[pCur->iPage]->isInit );
  37574. if( pCur->eState==CURSOR_INVALID ){
  37575. *pRes = -1;
  37576. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  37577. return SQLITE_OK;
  37578. }
  37579. assert( pCur->apPage[0]->intKey || pIdxKey );
  37580. for(;;){
  37581. int lwr, upr;
  37582. Pgno chldPg;
  37583. MemPage *pPage = pCur->apPage[pCur->iPage];
  37584. int c = -1; /* pRes return if table is empty must be -1 */
  37585. lwr = 0;
  37586. upr = pPage->nCell-1;
  37587. if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
  37588. rc = SQLITE_CORRUPT_BKPT;
  37589. goto moveto_finish;
  37590. }
  37591. if( biasRight ){
  37592. pCur->aiIdx[pCur->iPage] = (u16)upr;
  37593. }else{
  37594. pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
  37595. }
  37596. for(;;){
  37597. void *pCellKey;
  37598. i64 nCellKey;
  37599. int idx = pCur->aiIdx[pCur->iPage];
  37600. pCur->info.nSize = 0;
  37601. pCur->validNKey = 1;
  37602. if( pPage->intKey ){
  37603. u8 *pCell;
  37604. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  37605. if( pPage->hasData ){
  37606. u32 dummy;
  37607. pCell += getVarint32(pCell, dummy);
  37608. }
  37609. getVarint(pCell, (u64*)&nCellKey);
  37610. if( nCellKey==intKey ){
  37611. c = 0;
  37612. }else if( nCellKey<intKey ){
  37613. c = -1;
  37614. }else{
  37615. assert( nCellKey>intKey );
  37616. c = +1;
  37617. }
  37618. }else{
  37619. int available;
  37620. pCellKey = (void *)fetchPayload(pCur, &available, 0);
  37621. nCellKey = pCur->info.nKey;
  37622. if( available>=nCellKey ){
  37623. c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
  37624. }else{
  37625. pCellKey = sqlite3Malloc( (int)nCellKey );
  37626. if( pCellKey==0 ){
  37627. rc = SQLITE_NOMEM;
  37628. goto moveto_finish;
  37629. }
  37630. rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
  37631. c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
  37632. sqlite3_free(pCellKey);
  37633. if( rc ) goto moveto_finish;
  37634. }
  37635. }
  37636. if( c==0 ){
  37637. pCur->info.nKey = nCellKey;
  37638. if( pPage->intKey && !pPage->leaf ){
  37639. lwr = idx;
  37640. upr = lwr - 1;
  37641. break;
  37642. }else{
  37643. *pRes = 0;
  37644. rc = SQLITE_OK;
  37645. goto moveto_finish;
  37646. }
  37647. }
  37648. if( c<0 ){
  37649. lwr = idx+1;
  37650. }else{
  37651. upr = idx-1;
  37652. }
  37653. if( lwr>upr ){
  37654. pCur->info.nKey = nCellKey;
  37655. break;
  37656. }
  37657. pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
  37658. }
  37659. assert( lwr==upr+1 );
  37660. assert( pPage->isInit );
  37661. if( pPage->leaf ){
  37662. chldPg = 0;
  37663. }else if( lwr>=pPage->nCell ){
  37664. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  37665. }else{
  37666. chldPg = get4byte(findCell(pPage, lwr));
  37667. }
  37668. if( chldPg==0 ){
  37669. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  37670. if( pRes ) *pRes = c;
  37671. rc = SQLITE_OK;
  37672. goto moveto_finish;
  37673. }
  37674. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  37675. pCur->info.nSize = 0;
  37676. pCur->validNKey = 0;
  37677. rc = moveToChild(pCur, chldPg);
  37678. if( rc ) goto moveto_finish;
  37679. }
  37680. moveto_finish:
  37681. return rc;
  37682. }
  37683. /*
  37684. ** In this version of BtreeMoveto, pKey is a packed index record
  37685. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  37686. ** record and then call BtreeMovetoUnpacked() to do the work.
  37687. */
  37688. SQLITE_PRIVATE int sqlite3BtreeMoveto(
  37689. BtCursor *pCur, /* Cursor open on the btree to be searched */
  37690. const void *pKey, /* Packed key if the btree is an index */
  37691. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  37692. int bias, /* Bias search to the high end */
  37693. int *pRes /* Write search results here */
  37694. ){
  37695. int rc; /* Status code */
  37696. UnpackedRecord *pIdxKey; /* Unpacked index key */
  37697. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  37698. if( pKey ){
  37699. assert( nKey==(i64)(int)nKey );
  37700. pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
  37701. aSpace, sizeof(aSpace));
  37702. if( pIdxKey==0 ) return SQLITE_NOMEM;
  37703. }else{
  37704. pIdxKey = 0;
  37705. }
  37706. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  37707. if( pKey ){
  37708. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  37709. }
  37710. return rc;
  37711. }
  37712. /*
  37713. ** Return TRUE if the cursor is not pointing at an entry of the table.
  37714. **
  37715. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  37716. ** past the last entry in the table or sqlite3BtreePrev() moves past
  37717. ** the first entry. TRUE is also returned if the table is empty.
  37718. */
  37719. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  37720. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  37721. ** have been deleted? This API will need to change to return an error code
  37722. ** as well as the boolean result value.
  37723. */
  37724. return (CURSOR_VALID!=pCur->eState);
  37725. }
  37726. /*
  37727. ** Return the database connection handle for a cursor.
  37728. */
  37729. SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
  37730. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  37731. return pCur->pBtree->db;
  37732. }
  37733. /*
  37734. ** Advance the cursor to the next entry in the database. If
  37735. ** successful then set *pRes=0. If the cursor
  37736. ** was already pointing to the last entry in the database before
  37737. ** this routine was called, then set *pRes=1.
  37738. */
  37739. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  37740. int rc;
  37741. int idx;
  37742. MemPage *pPage;
  37743. assert( cursorHoldsMutex(pCur) );
  37744. rc = restoreCursorPosition(pCur);
  37745. if( rc!=SQLITE_OK ){
  37746. return rc;
  37747. }
  37748. assert( pRes!=0 );
  37749. if( CURSOR_INVALID==pCur->eState ){
  37750. *pRes = 1;
  37751. return SQLITE_OK;
  37752. }
  37753. if( pCur->skip>0 ){
  37754. pCur->skip = 0;
  37755. *pRes = 0;
  37756. return SQLITE_OK;
  37757. }
  37758. pCur->skip = 0;
  37759. pPage = pCur->apPage[pCur->iPage];
  37760. idx = ++pCur->aiIdx[pCur->iPage];
  37761. assert( pPage->isInit );
  37762. assert( idx<=pPage->nCell );
  37763. pCur->info.nSize = 0;
  37764. pCur->validNKey = 0;
  37765. if( idx>=pPage->nCell ){
  37766. if( !pPage->leaf ){
  37767. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  37768. if( rc ) return rc;
  37769. rc = moveToLeftmost(pCur);
  37770. *pRes = 0;
  37771. return rc;
  37772. }
  37773. do{
  37774. if( pCur->iPage==0 ){
  37775. *pRes = 1;
  37776. pCur->eState = CURSOR_INVALID;
  37777. return SQLITE_OK;
  37778. }
  37779. sqlite3BtreeMoveToParent(pCur);
  37780. pPage = pCur->apPage[pCur->iPage];
  37781. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  37782. *pRes = 0;
  37783. if( pPage->intKey ){
  37784. rc = sqlite3BtreeNext(pCur, pRes);
  37785. }else{
  37786. rc = SQLITE_OK;
  37787. }
  37788. return rc;
  37789. }
  37790. *pRes = 0;
  37791. if( pPage->leaf ){
  37792. return SQLITE_OK;
  37793. }
  37794. rc = moveToLeftmost(pCur);
  37795. return rc;
  37796. }
  37797. /*
  37798. ** Step the cursor to the back to the previous entry in the database. If
  37799. ** successful then set *pRes=0. If the cursor
  37800. ** was already pointing to the first entry in the database before
  37801. ** this routine was called, then set *pRes=1.
  37802. */
  37803. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  37804. int rc;
  37805. MemPage *pPage;
  37806. assert( cursorHoldsMutex(pCur) );
  37807. rc = restoreCursorPosition(pCur);
  37808. if( rc!=SQLITE_OK ){
  37809. return rc;
  37810. }
  37811. pCur->atLast = 0;
  37812. if( CURSOR_INVALID==pCur->eState ){
  37813. *pRes = 1;
  37814. return SQLITE_OK;
  37815. }
  37816. if( pCur->skip<0 ){
  37817. pCur->skip = 0;
  37818. *pRes = 0;
  37819. return SQLITE_OK;
  37820. }
  37821. pCur->skip = 0;
  37822. pPage = pCur->apPage[pCur->iPage];
  37823. assert( pPage->isInit );
  37824. if( !pPage->leaf ){
  37825. int idx = pCur->aiIdx[pCur->iPage];
  37826. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  37827. if( rc ){
  37828. return rc;
  37829. }
  37830. rc = moveToRightmost(pCur);
  37831. }else{
  37832. while( pCur->aiIdx[pCur->iPage]==0 ){
  37833. if( pCur->iPage==0 ){
  37834. pCur->eState = CURSOR_INVALID;
  37835. *pRes = 1;
  37836. return SQLITE_OK;
  37837. }
  37838. sqlite3BtreeMoveToParent(pCur);
  37839. }
  37840. pCur->info.nSize = 0;
  37841. pCur->validNKey = 0;
  37842. pCur->aiIdx[pCur->iPage]--;
  37843. pPage = pCur->apPage[pCur->iPage];
  37844. if( pPage->intKey && !pPage->leaf ){
  37845. rc = sqlite3BtreePrevious(pCur, pRes);
  37846. }else{
  37847. rc = SQLITE_OK;
  37848. }
  37849. }
  37850. *pRes = 0;
  37851. return rc;
  37852. }
  37853. /*
  37854. ** Allocate a new page from the database file.
  37855. **
  37856. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  37857. ** has already been called on the new page.) The new page has also
  37858. ** been referenced and the calling routine is responsible for calling
  37859. ** sqlite3PagerUnref() on the new page when it is done.
  37860. **
  37861. ** SQLITE_OK is returned on success. Any other return value indicates
  37862. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  37863. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  37864. **
  37865. ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
  37866. ** locate a page close to the page number "nearby". This can be used in an
  37867. ** attempt to keep related pages close to each other in the database file,
  37868. ** which in turn can make database access faster.
  37869. **
  37870. ** If the "exact" parameter is not 0, and the page-number nearby exists
  37871. ** anywhere on the free-list, then it is guarenteed to be returned. This
  37872. ** is only used by auto-vacuum databases when allocating a new table.
  37873. */
  37874. static int allocateBtreePage(
  37875. BtShared *pBt,
  37876. MemPage **ppPage,
  37877. Pgno *pPgno,
  37878. Pgno nearby,
  37879. u8 exact
  37880. ){
  37881. MemPage *pPage1;
  37882. int rc;
  37883. int n; /* Number of pages on the freelist */
  37884. int k; /* Number of leaves on the trunk of the freelist */
  37885. MemPage *pTrunk = 0;
  37886. MemPage *pPrevTrunk = 0;
  37887. assert( sqlite3_mutex_held(pBt->mutex) );
  37888. pPage1 = pBt->pPage1;
  37889. n = get4byte(&pPage1->aData[36]);
  37890. if( n>0 ){
  37891. /* There are pages on the freelist. Reuse one of those pages. */
  37892. Pgno iTrunk;
  37893. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  37894. /* If the 'exact' parameter was true and a query of the pointer-map
  37895. ** shows that the page 'nearby' is somewhere on the free-list, then
  37896. ** the entire-list will be searched for that page.
  37897. */
  37898. #ifndef SQLITE_OMIT_AUTOVACUUM
  37899. if( exact && nearby<=pagerPagecount(pBt) ){
  37900. u8 eType;
  37901. assert( nearby>0 );
  37902. assert( pBt->autoVacuum );
  37903. rc = ptrmapGet(pBt, nearby, &eType, 0);
  37904. if( rc ) return rc;
  37905. if( eType==PTRMAP_FREEPAGE ){
  37906. searchList = 1;
  37907. }
  37908. *pPgno = nearby;
  37909. }
  37910. #endif
  37911. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  37912. ** first free-list trunk page. iPrevTrunk is initially 1.
  37913. */
  37914. rc = sqlite3PagerWrite(pPage1->pDbPage);
  37915. if( rc ) return rc;
  37916. put4byte(&pPage1->aData[36], n-1);
  37917. /* The code within this loop is run only once if the 'searchList' variable
  37918. ** is not true. Otherwise, it runs once for each trunk-page on the
  37919. ** free-list until the page 'nearby' is located.
  37920. */
  37921. do {
  37922. pPrevTrunk = pTrunk;
  37923. if( pPrevTrunk ){
  37924. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  37925. }else{
  37926. iTrunk = get4byte(&pPage1->aData[32]);
  37927. }
  37928. rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
  37929. if( rc ){
  37930. pTrunk = 0;
  37931. goto end_allocate_page;
  37932. }
  37933. k = get4byte(&pTrunk->aData[4]);
  37934. if( k==0 && !searchList ){
  37935. /* The trunk has no leaves and the list is not being searched.
  37936. ** So extract the trunk page itself and use it as the newly
  37937. ** allocated page */
  37938. assert( pPrevTrunk==0 );
  37939. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  37940. if( rc ){
  37941. goto end_allocate_page;
  37942. }
  37943. *pPgno = iTrunk;
  37944. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  37945. *ppPage = pTrunk;
  37946. pTrunk = 0;
  37947. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  37948. }else if( k>pBt->usableSize/4 - 2 ){
  37949. /* Value of k is out of range. Database corruption */
  37950. rc = SQLITE_CORRUPT_BKPT;
  37951. goto end_allocate_page;
  37952. #ifndef SQLITE_OMIT_AUTOVACUUM
  37953. }else if( searchList && nearby==iTrunk ){
  37954. /* The list is being searched and this trunk page is the page
  37955. ** to allocate, regardless of whether it has leaves.
  37956. */
  37957. assert( *pPgno==iTrunk );
  37958. *ppPage = pTrunk;
  37959. searchList = 0;
  37960. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  37961. if( rc ){
  37962. goto end_allocate_page;
  37963. }
  37964. if( k==0 ){
  37965. if( !pPrevTrunk ){
  37966. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  37967. }else{
  37968. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  37969. }
  37970. }else{
  37971. /* The trunk page is required by the caller but it contains
  37972. ** pointers to free-list leaves. The first leaf becomes a trunk
  37973. ** page in this case.
  37974. */
  37975. MemPage *pNewTrunk;
  37976. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  37977. rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  37978. if( rc!=SQLITE_OK ){
  37979. goto end_allocate_page;
  37980. }
  37981. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  37982. if( rc!=SQLITE_OK ){
  37983. releasePage(pNewTrunk);
  37984. goto end_allocate_page;
  37985. }
  37986. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  37987. put4byte(&pNewTrunk->aData[4], k-1);
  37988. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  37989. releasePage(pNewTrunk);
  37990. if( !pPrevTrunk ){
  37991. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  37992. put4byte(&pPage1->aData[32], iNewTrunk);
  37993. }else{
  37994. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  37995. if( rc ){
  37996. goto end_allocate_page;
  37997. }
  37998. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  37999. }
  38000. }
  38001. pTrunk = 0;
  38002. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  38003. #endif
  38004. }else{
  38005. /* Extract a leaf from the trunk */
  38006. int closest;
  38007. Pgno iPage;
  38008. unsigned char *aData = pTrunk->aData;
  38009. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  38010. if( rc ){
  38011. goto end_allocate_page;
  38012. }
  38013. if( nearby>0 ){
  38014. int i, dist;
  38015. closest = 0;
  38016. dist = get4byte(&aData[8]) - nearby;
  38017. if( dist<0 ) dist = -dist;
  38018. for(i=1; i<k; i++){
  38019. int d2 = get4byte(&aData[8+i*4]) - nearby;
  38020. if( d2<0 ) d2 = -d2;
  38021. if( d2<dist ){
  38022. closest = i;
  38023. dist = d2;
  38024. }
  38025. }
  38026. }else{
  38027. closest = 0;
  38028. }
  38029. iPage = get4byte(&aData[8+closest*4]);
  38030. if( !searchList || iPage==nearby ){
  38031. int noContent;
  38032. Pgno nPage;
  38033. *pPgno = iPage;
  38034. nPage = pagerPagecount(pBt);
  38035. if( *pPgno>nPage ){
  38036. /* Free page off the end of the file */
  38037. rc = SQLITE_CORRUPT_BKPT;
  38038. goto end_allocate_page;
  38039. }
  38040. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  38041. ": %d more free pages\n",
  38042. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  38043. if( closest<k-1 ){
  38044. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  38045. }
  38046. put4byte(&aData[4], k-1);
  38047. assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
  38048. noContent = !btreeGetHasContent(pBt, *pPgno);
  38049. rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
  38050. if( rc==SQLITE_OK ){
  38051. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  38052. if( rc!=SQLITE_OK ){
  38053. releasePage(*ppPage);
  38054. }
  38055. }
  38056. searchList = 0;
  38057. }
  38058. }
  38059. releasePage(pPrevTrunk);
  38060. pPrevTrunk = 0;
  38061. }while( searchList );
  38062. }else{
  38063. /* There are no pages on the freelist, so create a new page at the
  38064. ** end of the file */
  38065. int nPage = pagerPagecount(pBt);
  38066. *pPgno = nPage + 1;
  38067. if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
  38068. (*pPgno)++;
  38069. }
  38070. #ifndef SQLITE_OMIT_AUTOVACUUM
  38071. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
  38072. /* If *pPgno refers to a pointer-map page, allocate two new pages
  38073. ** at the end of the file instead of one. The first allocated page
  38074. ** becomes a new pointer-map page, the second is used by the caller.
  38075. */
  38076. MemPage *pPg = 0;
  38077. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
  38078. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  38079. rc = sqlite3BtreeGetPage(pBt, *pPgno, &pPg, 0);
  38080. if( rc==SQLITE_OK ){
  38081. rc = sqlite3PagerWrite(pPg->pDbPage);
  38082. releasePage(pPg);
  38083. }
  38084. if( rc ) return rc;
  38085. (*pPgno)++;
  38086. if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
  38087. }
  38088. #endif
  38089. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  38090. rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
  38091. if( rc ) return rc;
  38092. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  38093. if( rc!=SQLITE_OK ){
  38094. releasePage(*ppPage);
  38095. }
  38096. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  38097. }
  38098. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  38099. end_allocate_page:
  38100. releasePage(pTrunk);
  38101. releasePage(pPrevTrunk);
  38102. if( rc==SQLITE_OK ){
  38103. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  38104. releasePage(*ppPage);
  38105. return SQLITE_CORRUPT_BKPT;
  38106. }
  38107. (*ppPage)->isInit = 0;
  38108. }
  38109. return rc;
  38110. }
  38111. /*
  38112. ** This function is used to add page iPage to the database file free-list.
  38113. ** It is assumed that the page is not already a part of the free-list.
  38114. **
  38115. ** The value passed as the second argument to this function is optional.
  38116. ** If the caller happens to have a pointer to the MemPage object
  38117. ** corresponding to page iPage handy, it may pass it as the second value.
  38118. ** Otherwise, it may pass NULL.
  38119. **
  38120. ** If a pointer to a MemPage object is passed as the second argument,
  38121. ** its reference count is not altered by this function.
  38122. */
  38123. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  38124. MemPage *pTrunk = 0; /* Free-list trunk page */
  38125. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  38126. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  38127. MemPage *pPage; /* Page being freed. May be NULL. */
  38128. int rc; /* Return Code */
  38129. int nFree; /* Initial number of pages on free-list */
  38130. assert( sqlite3_mutex_held(pBt->mutex) );
  38131. assert( iPage>1 );
  38132. assert( !pMemPage || pMemPage->pgno==iPage );
  38133. if( pMemPage ){
  38134. pPage = pMemPage;
  38135. sqlite3PagerRef(pPage->pDbPage);
  38136. }else{
  38137. pPage = btreePageLookup(pBt, iPage);
  38138. }
  38139. /* Increment the free page count on pPage1 */
  38140. rc = sqlite3PagerWrite(pPage1->pDbPage);
  38141. if( rc ) goto freepage_out;
  38142. nFree = get4byte(&pPage1->aData[36]);
  38143. put4byte(&pPage1->aData[36], nFree+1);
  38144. #ifdef SQLITE_SECURE_DELETE
  38145. /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
  38146. ** always fully overwrite deleted information with zeros.
  38147. */
  38148. if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
  38149. || (rc = sqlite3PagerWrite(pPage->pDbPage))
  38150. ){
  38151. goto freepage_out;
  38152. }
  38153. memset(pPage->aData, 0, pPage->pBt->pageSize);
  38154. #endif
  38155. /* If the database supports auto-vacuum, write an entry in the pointer-map
  38156. ** to indicate that the page is free.
  38157. */
  38158. if( ISAUTOVACUUM ){
  38159. rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
  38160. if( rc ) goto freepage_out;
  38161. }
  38162. /* Now manipulate the actual database free-list structure. There are two
  38163. ** possibilities. If the free-list is currently empty, or if the first
  38164. ** trunk page in the free-list is full, then this page will become a
  38165. ** new free-list trunk page. Otherwise, it will become a leaf of the
  38166. ** first trunk page in the current free-list. This block tests if it
  38167. ** is possible to add the page as a new free-list leaf.
  38168. */
  38169. if( nFree!=0 ){
  38170. int nLeaf; /* Initial number of leaf cells on trunk page */
  38171. iTrunk = get4byte(&pPage1->aData[32]);
  38172. rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
  38173. if( rc!=SQLITE_OK ){
  38174. goto freepage_out;
  38175. }
  38176. nLeaf = get4byte(&pTrunk->aData[4]);
  38177. if( nLeaf<0 ){
  38178. rc = SQLITE_CORRUPT_BKPT;
  38179. goto freepage_out;
  38180. }
  38181. if( nLeaf<pBt->usableSize/4 - 8 ){
  38182. /* In this case there is room on the trunk page to insert the page
  38183. ** being freed as a new leaf.
  38184. **
  38185. ** Note that the trunk page is not really full until it contains
  38186. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  38187. ** coded. But due to a coding error in versions of SQLite prior to
  38188. ** 3.6.0, databases with freelist trunk pages holding more than
  38189. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  38190. ** to maintain backwards compatibility with older versions of SQLite,
  38191. ** we will contain to restrict the number of entries to usableSize/4 - 8
  38192. ** for now. At some point in the future (once everyone has upgraded
  38193. ** to 3.6.0 or later) we should consider fixing the conditional above
  38194. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  38195. */
  38196. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  38197. if( rc==SQLITE_OK ){
  38198. put4byte(&pTrunk->aData[4], nLeaf+1);
  38199. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  38200. #ifndef SQLITE_SECURE_DELETE
  38201. if( pPage ){
  38202. sqlite3PagerDontWrite(pPage->pDbPage);
  38203. }
  38204. #endif
  38205. rc = btreeSetHasContent(pBt, iPage);
  38206. }
  38207. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  38208. goto freepage_out;
  38209. }
  38210. }
  38211. /* If control flows to this point, then it was not possible to add the
  38212. ** the page being freed as a leaf page of the first trunk in the free-list.
  38213. ** Possibly because the free-list is empty, or possibly because the
  38214. ** first trunk in the free-list is full. Either way, the page being freed
  38215. ** will become the new first trunk page in the free-list.
  38216. */
  38217. if( ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
  38218. || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
  38219. ){
  38220. goto freepage_out;
  38221. }
  38222. put4byte(pPage->aData, iTrunk);
  38223. put4byte(&pPage->aData[4], 0);
  38224. put4byte(&pPage1->aData[32], iPage);
  38225. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  38226. freepage_out:
  38227. if( pPage ){
  38228. pPage->isInit = 0;
  38229. }
  38230. releasePage(pPage);
  38231. releasePage(pTrunk);
  38232. return rc;
  38233. }
  38234. static int freePage(MemPage *pPage){
  38235. return freePage2(pPage->pBt, pPage, pPage->pgno);
  38236. }
  38237. /*
  38238. ** Free any overflow pages associated with the given Cell.
  38239. */
  38240. static int clearCell(MemPage *pPage, unsigned char *pCell){
  38241. BtShared *pBt = pPage->pBt;
  38242. CellInfo info;
  38243. Pgno ovflPgno;
  38244. int rc;
  38245. int nOvfl;
  38246. u16 ovflPageSize;
  38247. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38248. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38249. if( info.iOverflow==0 ){
  38250. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  38251. }
  38252. ovflPgno = get4byte(&pCell[info.iOverflow]);
  38253. assert( pBt->usableSize > 4 );
  38254. ovflPageSize = pBt->usableSize - 4;
  38255. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  38256. assert( ovflPgno==0 || nOvfl>0 );
  38257. while( nOvfl-- ){
  38258. Pgno iNext = 0;
  38259. MemPage *pOvfl = 0;
  38260. if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
  38261. /* 0 is not a legal page number and page 1 cannot be an
  38262. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  38263. ** file the database must be corrupt. */
  38264. return SQLITE_CORRUPT_BKPT;
  38265. }
  38266. if( nOvfl ){
  38267. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  38268. if( rc ) return rc;
  38269. }
  38270. rc = freePage2(pBt, pOvfl, ovflPgno);
  38271. if( pOvfl ){
  38272. sqlite3PagerUnref(pOvfl->pDbPage);
  38273. }
  38274. if( rc ) return rc;
  38275. ovflPgno = iNext;
  38276. }
  38277. return SQLITE_OK;
  38278. }
  38279. /*
  38280. ** Create the byte sequence used to represent a cell on page pPage
  38281. ** and write that byte sequence into pCell[]. Overflow pages are
  38282. ** allocated and filled in as necessary. The calling procedure
  38283. ** is responsible for making sure sufficient space has been allocated
  38284. ** for pCell[].
  38285. **
  38286. ** Note that pCell does not necessary need to point to the pPage->aData
  38287. ** area. pCell might point to some temporary storage. The cell will
  38288. ** be constructed in this temporary area then copied into pPage->aData
  38289. ** later.
  38290. */
  38291. static int fillInCell(
  38292. MemPage *pPage, /* The page that contains the cell */
  38293. unsigned char *pCell, /* Complete text of the cell */
  38294. const void *pKey, i64 nKey, /* The key */
  38295. const void *pData,int nData, /* The data */
  38296. int nZero, /* Extra zero bytes to append to pData */
  38297. int *pnSize /* Write cell size here */
  38298. ){
  38299. int nPayload;
  38300. const u8 *pSrc;
  38301. int nSrc, n, rc;
  38302. int spaceLeft;
  38303. MemPage *pOvfl = 0;
  38304. MemPage *pToRelease = 0;
  38305. unsigned char *pPrior;
  38306. unsigned char *pPayload;
  38307. BtShared *pBt = pPage->pBt;
  38308. Pgno pgnoOvfl = 0;
  38309. int nHeader;
  38310. CellInfo info;
  38311. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38312. /* pPage is not necessarily writeable since pCell might be auxiliary
  38313. ** buffer space that is separate from the pPage buffer area */
  38314. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  38315. || sqlite3PagerIswriteable(pPage->pDbPage) );
  38316. /* Fill in the header. */
  38317. nHeader = 0;
  38318. if( !pPage->leaf ){
  38319. nHeader += 4;
  38320. }
  38321. if( pPage->hasData ){
  38322. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  38323. }else{
  38324. nData = nZero = 0;
  38325. }
  38326. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  38327. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38328. assert( info.nHeader==nHeader );
  38329. assert( info.nKey==nKey );
  38330. assert( info.nData==(u32)(nData+nZero) );
  38331. /* Fill in the payload */
  38332. nPayload = nData + nZero;
  38333. if( pPage->intKey ){
  38334. pSrc = pData;
  38335. nSrc = nData;
  38336. nData = 0;
  38337. }else{
  38338. if( nKey>0x7fffffff || pKey==0 ){
  38339. return SQLITE_CORRUPT;
  38340. }
  38341. nPayload += (int)nKey;
  38342. pSrc = pKey;
  38343. nSrc = (int)nKey;
  38344. }
  38345. *pnSize = info.nSize;
  38346. spaceLeft = info.nLocal;
  38347. pPayload = &pCell[nHeader];
  38348. pPrior = &pCell[info.iOverflow];
  38349. while( nPayload>0 ){
  38350. if( spaceLeft==0 ){
  38351. #ifndef SQLITE_OMIT_AUTOVACUUM
  38352. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  38353. if( pBt->autoVacuum ){
  38354. do{
  38355. pgnoOvfl++;
  38356. } while(
  38357. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  38358. );
  38359. }
  38360. #endif
  38361. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  38362. #ifndef SQLITE_OMIT_AUTOVACUUM
  38363. /* If the database supports auto-vacuum, and the second or subsequent
  38364. ** overflow page is being allocated, add an entry to the pointer-map
  38365. ** for that page now.
  38366. **
  38367. ** If this is the first overflow page, then write a partial entry
  38368. ** to the pointer-map. If we write nothing to this pointer-map slot,
  38369. ** then the optimistic overflow chain processing in clearCell()
  38370. ** may misinterpret the uninitialised values and delete the
  38371. ** wrong pages from the database.
  38372. */
  38373. if( pBt->autoVacuum && rc==SQLITE_OK ){
  38374. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  38375. rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
  38376. if( rc ){
  38377. releasePage(pOvfl);
  38378. }
  38379. }
  38380. #endif
  38381. if( rc ){
  38382. releasePage(pToRelease);
  38383. return rc;
  38384. }
  38385. /* If pToRelease is not zero than pPrior points into the data area
  38386. ** of pToRelease. Make sure pToRelease is still writeable. */
  38387. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  38388. /* If pPrior is part of the data area of pPage, then make sure pPage
  38389. ** is still writeable */
  38390. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  38391. || sqlite3PagerIswriteable(pPage->pDbPage) );
  38392. put4byte(pPrior, pgnoOvfl);
  38393. releasePage(pToRelease);
  38394. pToRelease = pOvfl;
  38395. pPrior = pOvfl->aData;
  38396. put4byte(pPrior, 0);
  38397. pPayload = &pOvfl->aData[4];
  38398. spaceLeft = pBt->usableSize - 4;
  38399. }
  38400. n = nPayload;
  38401. if( n>spaceLeft ) n = spaceLeft;
  38402. /* If pToRelease is not zero than pPayload points into the data area
  38403. ** of pToRelease. Make sure pToRelease is still writeable. */
  38404. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  38405. /* If pPayload is part of the data area of pPage, then make sure pPage
  38406. ** is still writeable */
  38407. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  38408. || sqlite3PagerIswriteable(pPage->pDbPage) );
  38409. if( nSrc>0 ){
  38410. if( n>nSrc ) n = nSrc;
  38411. assert( pSrc );
  38412. memcpy(pPayload, pSrc, n);
  38413. }else{
  38414. memset(pPayload, 0, n);
  38415. }
  38416. nPayload -= n;
  38417. pPayload += n;
  38418. pSrc += n;
  38419. nSrc -= n;
  38420. spaceLeft -= n;
  38421. if( nSrc==0 ){
  38422. nSrc = nData;
  38423. pSrc = pData;
  38424. }
  38425. }
  38426. releasePage(pToRelease);
  38427. return SQLITE_OK;
  38428. }
  38429. /*
  38430. ** Remove the i-th cell from pPage. This routine effects pPage only.
  38431. ** The cell content is not freed or deallocated. It is assumed that
  38432. ** the cell content has been copied someplace else. This routine just
  38433. ** removes the reference to the cell from pPage.
  38434. **
  38435. ** "sz" must be the number of bytes in the cell.
  38436. */
  38437. static int dropCell(MemPage *pPage, int idx, int sz){
  38438. int i; /* Loop counter */
  38439. int pc; /* Offset to cell content of cell being deleted */
  38440. u8 *data; /* pPage->aData */
  38441. u8 *ptr; /* Used to move bytes around within data[] */
  38442. int rc; /* The return code */
  38443. assert( idx>=0 && idx<pPage->nCell );
  38444. assert( sz==cellSize(pPage, idx) );
  38445. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38446. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38447. data = pPage->aData;
  38448. ptr = &data[pPage->cellOffset + 2*idx];
  38449. pc = get2byte(ptr);
  38450. if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
  38451. || (pc+sz>pPage->pBt->usableSize) ){
  38452. return SQLITE_CORRUPT_BKPT;
  38453. }
  38454. rc = freeSpace(pPage, pc, sz);
  38455. if( rc!=SQLITE_OK ){
  38456. return rc;
  38457. }
  38458. for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
  38459. ptr[0] = ptr[2];
  38460. ptr[1] = ptr[3];
  38461. }
  38462. pPage->nCell--;
  38463. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  38464. pPage->nFree += 2;
  38465. return SQLITE_OK;
  38466. }
  38467. /*
  38468. ** Insert a new cell on pPage at cell index "i". pCell points to the
  38469. ** content of the cell.
  38470. **
  38471. ** If the cell content will fit on the page, then put it there. If it
  38472. ** will not fit, then make a copy of the cell content into pTemp if
  38473. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  38474. ** in pPage->aOvfl[] and make it point to the cell content (either
  38475. ** in pTemp or the original pCell) and also record its index.
  38476. ** Allocating a new entry in pPage->aCell[] implies that
  38477. ** pPage->nOverflow is incremented.
  38478. **
  38479. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  38480. ** cell. The caller will overwrite them after this function returns. If
  38481. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  38482. ** (but pCell+nSkip is always valid).
  38483. */
  38484. static int insertCell(
  38485. MemPage *pPage, /* Page into which we are copying */
  38486. int i, /* New cell becomes the i-th cell of the page */
  38487. u8 *pCell, /* Content of the new cell */
  38488. int sz, /* Bytes of content in pCell */
  38489. u8 *pTemp, /* Temp storage space for pCell, if needed */
  38490. u8 nSkip /* Do not write the first nSkip bytes of the cell */
  38491. ){
  38492. int idx; /* Where to write new cell content in data[] */
  38493. int j; /* Loop counter */
  38494. int top; /* First byte of content for any cell in data[] */
  38495. int end; /* First byte past the last cell pointer in data[] */
  38496. int ins; /* Index in data[] where new cell pointer is inserted */
  38497. int hdr; /* Offset into data[] of the page header */
  38498. int cellOffset; /* Address of first cell pointer in data[] */
  38499. u8 *data; /* The content of the whole page */
  38500. u8 *ptr; /* Used for moving information around in data[] */
  38501. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  38502. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
  38503. assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
  38504. assert( sz==cellSizePtr(pPage, pCell) );
  38505. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38506. if( pPage->nOverflow || sz+2>pPage->nFree ){
  38507. if( pTemp ){
  38508. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  38509. pCell = pTemp;
  38510. }
  38511. j = pPage->nOverflow++;
  38512. assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
  38513. pPage->aOvfl[j].pCell = pCell;
  38514. pPage->aOvfl[j].idx = (u16)i;
  38515. pPage->nFree = 0;
  38516. }else{
  38517. int rc = sqlite3PagerWrite(pPage->pDbPage);
  38518. if( rc!=SQLITE_OK ){
  38519. return rc;
  38520. }
  38521. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38522. data = pPage->aData;
  38523. hdr = pPage->hdrOffset;
  38524. top = get2byte(&data[hdr+5]);
  38525. cellOffset = pPage->cellOffset;
  38526. end = cellOffset + 2*pPage->nCell + 2;
  38527. ins = cellOffset + 2*i;
  38528. if( end > top - sz ){
  38529. rc = defragmentPage(pPage);
  38530. if( rc!=SQLITE_OK ){
  38531. return rc;
  38532. }
  38533. top = get2byte(&data[hdr+5]);
  38534. assert( end + sz <= top );
  38535. }
  38536. idx = allocateSpace(pPage, sz);
  38537. assert( idx>0 );
  38538. assert( end <= get2byte(&data[hdr+5]) );
  38539. if (idx+sz > pPage->pBt->usableSize) {
  38540. return SQLITE_CORRUPT_BKPT;
  38541. }
  38542. pPage->nCell++;
  38543. pPage->nFree -= 2;
  38544. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  38545. for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
  38546. ptr[0] = ptr[-2];
  38547. ptr[1] = ptr[-1];
  38548. }
  38549. put2byte(&data[ins], idx);
  38550. put2byte(&data[hdr+3], pPage->nCell);
  38551. #ifndef SQLITE_OMIT_AUTOVACUUM
  38552. if( pPage->pBt->autoVacuum ){
  38553. /* The cell may contain a pointer to an overflow page. If so, write
  38554. ** the entry for the overflow page into the pointer map.
  38555. */
  38556. CellInfo info;
  38557. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38558. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  38559. if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
  38560. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  38561. rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
  38562. if( rc!=SQLITE_OK ) return rc;
  38563. }
  38564. }
  38565. #endif
  38566. }
  38567. return SQLITE_OK;
  38568. }
  38569. /*
  38570. ** Add a list of cells to a page. The page should be initially empty.
  38571. ** The cells are guaranteed to fit on the page.
  38572. */
  38573. static void assemblePage(
  38574. MemPage *pPage, /* The page to be assemblied */
  38575. int nCell, /* The number of cells to add to this page */
  38576. u8 **apCell, /* Pointers to cell bodies */
  38577. u16 *aSize /* Sizes of the cells */
  38578. ){
  38579. int i; /* Loop counter */
  38580. int totalSize; /* Total size of all cells */
  38581. int hdr; /* Index of page header */
  38582. int cellptr; /* Address of next cell pointer */
  38583. int cellbody; /* Address of next cell body */
  38584. u8 *data; /* Data for the page */
  38585. assert( pPage->nOverflow==0 );
  38586. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38587. assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
  38588. totalSize = 0;
  38589. for(i=0; i<nCell; i++){
  38590. totalSize += aSize[i];
  38591. }
  38592. assert( totalSize+2*nCell<=pPage->nFree );
  38593. assert( pPage->nCell==0 );
  38594. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38595. cellptr = pPage->cellOffset;
  38596. data = pPage->aData;
  38597. hdr = pPage->hdrOffset;
  38598. put2byte(&data[hdr+3], nCell);
  38599. if( nCell ){
  38600. cellbody = allocateSpace(pPage, totalSize);
  38601. assert( cellbody>0 );
  38602. assert( pPage->nFree >= 2*nCell );
  38603. pPage->nFree -= 2*nCell;
  38604. for(i=0; i<nCell; i++){
  38605. put2byte(&data[cellptr], cellbody);
  38606. memcpy(&data[cellbody], apCell[i], aSize[i]);
  38607. cellptr += 2;
  38608. cellbody += aSize[i];
  38609. }
  38610. assert( cellbody==pPage->pBt->usableSize );
  38611. }
  38612. pPage->nCell = (u16)nCell;
  38613. }
  38614. /*
  38615. ** The following parameters determine how many adjacent pages get involved
  38616. ** in a balancing operation. NN is the number of neighbors on either side
  38617. ** of the page that participate in the balancing operation. NB is the
  38618. ** total number of pages that participate, including the target page and
  38619. ** NN neighbors on either side.
  38620. **
  38621. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  38622. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  38623. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  38624. ** The value of NN appears to give the best results overall.
  38625. */
  38626. #define NN 1 /* Number of neighbors on either side of pPage */
  38627. #define NB (NN*2+1) /* Total pages involved in the balance */
  38628. /* Forward reference */
  38629. static int balance(BtCursor*, int);
  38630. #ifndef SQLITE_OMIT_QUICKBALANCE
  38631. /*
  38632. ** This version of balance() handles the common special case where
  38633. ** a new entry is being inserted on the extreme right-end of the
  38634. ** tree, in other words, when the new entry will become the largest
  38635. ** entry in the tree.
  38636. **
  38637. ** Instead of trying balance the 3 right-most leaf pages, just add
  38638. ** a new page to the right-hand side and put the one new entry in
  38639. ** that page. This leaves the right side of the tree somewhat
  38640. ** unbalanced. But odds are that we will be inserting new entries
  38641. ** at the end soon afterwards so the nearly empty page will quickly
  38642. ** fill up. On average.
  38643. **
  38644. ** pPage is the leaf page which is the right-most page in the tree.
  38645. ** pParent is its parent. pPage must have a single overflow entry
  38646. ** which is also the right-most entry on the page.
  38647. */
  38648. static int balance_quick(BtCursor *pCur){
  38649. int rc;
  38650. MemPage *pNew = 0;
  38651. Pgno pgnoNew;
  38652. u8 *pCell;
  38653. u16 szCell;
  38654. CellInfo info;
  38655. MemPage *pPage = pCur->apPage[pCur->iPage];
  38656. MemPage *pParent = pCur->apPage[pCur->iPage-1];
  38657. BtShared *pBt = pPage->pBt;
  38658. int parentIdx = pParent->nCell; /* pParent new divider cell index */
  38659. int parentSize; /* Size of new divider cell */
  38660. u8 parentCell[64]; /* Space for the new divider cell */
  38661. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38662. /* Allocate a new page. Insert the overflow cell from pPage
  38663. ** into it. Then remove the overflow cell from pPage.
  38664. */
  38665. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  38666. if( rc==SQLITE_OK ){
  38667. pCell = pPage->aOvfl[0].pCell;
  38668. szCell = cellSizePtr(pPage, pCell);
  38669. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  38670. zeroPage(pNew, pPage->aData[0]);
  38671. assemblePage(pNew, 1, &pCell, &szCell);
  38672. pPage->nOverflow = 0;
  38673. /* pPage is currently the right-child of pParent. Change this
  38674. ** so that the right-child is the new page allocated above and
  38675. ** pPage is the next-to-right child.
  38676. **
  38677. ** Ignore the return value of the call to fillInCell(). fillInCell()
  38678. ** may only return other than SQLITE_OK if it is required to allocate
  38679. ** one or more overflow pages. Since an internal table B-Tree cell
  38680. ** may never spill over onto an overflow page (it is a maximum of
  38681. ** 13 bytes in size), it is not neccessary to check the return code.
  38682. **
  38683. ** Similarly, the insertCell() function cannot fail if the page
  38684. ** being inserted into is already writable and the cell does not
  38685. ** contain an overflow pointer. So ignore this return code too.
  38686. */
  38687. assert( pPage->nCell>0 );
  38688. pCell = findCell(pPage, pPage->nCell-1);
  38689. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  38690. fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
  38691. assert( parentSize<64 );
  38692. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  38693. insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
  38694. put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
  38695. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  38696. /* If this is an auto-vacuum database, update the pointer map
  38697. ** with entries for the new page, and any pointer from the
  38698. ** cell on the page to an overflow page.
  38699. */
  38700. if( ISAUTOVACUUM ){
  38701. rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
  38702. if( rc==SQLITE_OK ){
  38703. rc = ptrmapPutOvfl(pNew, 0);
  38704. }
  38705. }
  38706. /* Release the reference to the new page. */
  38707. releasePage(pNew);
  38708. }
  38709. /* At this point the pPage->nFree variable is not set correctly with
  38710. ** respect to the content of the page (because it was set to 0 by
  38711. ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
  38712. ** correct.
  38713. **
  38714. ** This has to be done even if an error will be returned. Normally, if
  38715. ** an error occurs during tree balancing, the contents of MemPage are
  38716. ** not important, as they will be recalculated when the page is rolled
  38717. ** back. But here, in balance_quick(), it is possible that pPage has
  38718. ** not yet been marked dirty or written into the journal file. Therefore
  38719. ** it will not be rolled back and so it is important to make sure that
  38720. ** the page data and contents of MemPage are consistent.
  38721. */
  38722. pPage->isInit = 0;
  38723. sqlite3BtreeInitPage(pPage);
  38724. assert( pPage->nOverflow==0 );
  38725. /* If everything else succeeded, balance the parent page, in
  38726. ** case the divider cell inserted caused it to become overfull.
  38727. */
  38728. if( rc==SQLITE_OK ){
  38729. releasePage(pPage);
  38730. pCur->iPage--;
  38731. rc = balance(pCur, 0);
  38732. }
  38733. return rc;
  38734. }
  38735. #endif /* SQLITE_OMIT_QUICKBALANCE */
  38736. /*
  38737. ** This routine redistributes Cells on pPage and up to NN*2 siblings
  38738. ** of pPage so that all pages have about the same amount of free space.
  38739. ** Usually NN siblings on either side of pPage is used in the balancing,
  38740. ** though more siblings might come from one side if pPage is the first
  38741. ** or last child of its parent. If pPage has fewer than 2*NN siblings
  38742. ** (something which can only happen if pPage is the root page or a
  38743. ** child of root) then all available siblings participate in the balancing.
  38744. **
  38745. ** The number of siblings of pPage might be increased or decreased by one or
  38746. ** two in an effort to keep pages nearly full but not over full. The root page
  38747. ** is special and is allowed to be nearly empty. If pPage is
  38748. ** the root page, then the depth of the tree might be increased
  38749. ** or decreased by one, as necessary, to keep the root page from being
  38750. ** overfull or completely empty.
  38751. **
  38752. ** Note that when this routine is called, some of the Cells on pPage
  38753. ** might not actually be stored in pPage->aData[]. This can happen
  38754. ** if the page is overfull. Part of the job of this routine is to
  38755. ** make sure all Cells for pPage once again fit in pPage->aData[].
  38756. **
  38757. ** In the course of balancing the siblings of pPage, the parent of pPage
  38758. ** might become overfull or underfull. If that happens, then this routine
  38759. ** is called recursively on the parent.
  38760. **
  38761. ** If this routine fails for any reason, it might leave the database
  38762. ** in a corrupted state. So if this routine fails, the database should
  38763. ** be rolled back.
  38764. */
  38765. static int balance_nonroot(BtCursor *pCur){
  38766. MemPage *pPage; /* The over or underfull page to balance */
  38767. MemPage *pParent; /* The parent of pPage */
  38768. BtShared *pBt; /* The whole database */
  38769. int nCell = 0; /* Number of cells in apCell[] */
  38770. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  38771. int nOld = 0; /* Number of pages in apOld[] */
  38772. int nNew = 0; /* Number of pages in apNew[] */
  38773. int nDiv; /* Number of cells in apDiv[] */
  38774. int i, j, k; /* Loop counters */
  38775. int idx; /* Index of pPage in pParent->aCell[] */
  38776. int nxDiv; /* Next divider slot in pParent->aCell[] */
  38777. int rc; /* The return code */
  38778. int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  38779. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  38780. int usableSpace; /* Bytes in pPage beyond the header */
  38781. int pageFlags; /* Value of pPage->aData[0] */
  38782. int subtotal; /* Subtotal of bytes in cells on one page */
  38783. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  38784. int iSpace2 = 0; /* First unused byte of aSpace2[] */
  38785. int szScratch; /* Size of scratch memory requested */
  38786. MemPage *apOld[NB]; /* pPage and up to two siblings */
  38787. Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
  38788. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  38789. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  38790. Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
  38791. u8 *apDiv[NB]; /* Divider cells in pParent */
  38792. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  38793. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  38794. u8 **apCell = 0; /* All cells begin balanced */
  38795. u16 *szCell; /* Local size of all cells in apCell[] */
  38796. u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
  38797. u8 *aSpace1; /* Space for copies of dividers cells before balance */
  38798. u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
  38799. u8 *aFrom = 0;
  38800. pPage = pCur->apPage[pCur->iPage];
  38801. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38802. VVA_ONLY( pCur->pagesShuffled = 1 );
  38803. /*
  38804. ** Find the parent page.
  38805. */
  38806. assert( pCur->iPage>0 );
  38807. assert( pPage->isInit );
  38808. assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
  38809. pBt = pPage->pBt;
  38810. pParent = pCur->apPage[pCur->iPage-1];
  38811. assert( pParent );
  38812. if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
  38813. goto balance_cleanup;
  38814. }
  38815. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  38816. #ifndef SQLITE_OMIT_QUICKBALANCE
  38817. /*
  38818. ** A special case: If a new entry has just been inserted into a
  38819. ** table (that is, a btree with integer keys and all data at the leaves)
  38820. ** and the new entry is the right-most entry in the tree (it has the
  38821. ** largest key) then use the special balance_quick() routine for
  38822. ** balancing. balance_quick() is much faster and results in a tighter
  38823. ** packing of data in the common case.
  38824. */
  38825. if( pPage->leaf &&
  38826. pPage->intKey &&
  38827. pPage->nOverflow==1 &&
  38828. pPage->aOvfl[0].idx==pPage->nCell &&
  38829. pParent->pgno!=1 &&
  38830. get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
  38831. ){
  38832. assert( pPage->intKey );
  38833. /*
  38834. ** TODO: Check the siblings to the left of pPage. It may be that
  38835. ** they are not full and no new page is required.
  38836. */
  38837. return balance_quick(pCur);
  38838. }
  38839. #endif
  38840. if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
  38841. goto balance_cleanup;
  38842. }
  38843. /*
  38844. ** Find the cell in the parent page whose left child points back
  38845. ** to pPage. The "idx" variable is the index of that cell. If pPage
  38846. ** is the rightmost child of pParent then set idx to pParent->nCell
  38847. */
  38848. idx = pCur->aiIdx[pCur->iPage-1];
  38849. assertParentIndex(pParent, idx, pPage->pgno);
  38850. /*
  38851. ** Find sibling pages to pPage and the cells in pParent that divide
  38852. ** the siblings. An attempt is made to find NN siblings on either
  38853. ** side of pPage. More siblings are taken from one side, however, if
  38854. ** pPage there are fewer than NN siblings on the other side. If pParent
  38855. ** has NB or fewer children then all children of pParent are taken.
  38856. */
  38857. nxDiv = idx - NN;
  38858. if( nxDiv + NB > pParent->nCell ){
  38859. nxDiv = pParent->nCell - NB + 1;
  38860. }
  38861. if( nxDiv<0 ){
  38862. nxDiv = 0;
  38863. }
  38864. nDiv = 0;
  38865. for(i=0, k=nxDiv; i<NB; i++, k++){
  38866. if( k<pParent->nCell ){
  38867. apDiv[i] = findCell(pParent, k);
  38868. nDiv++;
  38869. assert( !pParent->leaf );
  38870. pgnoOld[i] = get4byte(apDiv[i]);
  38871. }else if( k==pParent->nCell ){
  38872. pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
  38873. }else{
  38874. break;
  38875. }
  38876. rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
  38877. if( rc ) goto balance_cleanup;
  38878. /* apOld[i]->idxParent = k; */
  38879. apCopy[i] = 0;
  38880. assert( i==nOld );
  38881. nOld++;
  38882. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  38883. }
  38884. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  38885. ** alignment */
  38886. nMaxCells = (nMaxCells + 3)&~3;
  38887. /*
  38888. ** Allocate space for memory structures
  38889. */
  38890. szScratch =
  38891. nMaxCells*sizeof(u8*) /* apCell */
  38892. + nMaxCells*sizeof(u16) /* szCell */
  38893. + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
  38894. + pBt->pageSize /* aSpace1 */
  38895. + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
  38896. apCell = sqlite3ScratchMalloc( szScratch );
  38897. if( apCell==0 ){
  38898. rc = SQLITE_NOMEM;
  38899. goto balance_cleanup;
  38900. }
  38901. szCell = (u16*)&apCell[nMaxCells];
  38902. aCopy[0] = (u8*)&szCell[nMaxCells];
  38903. assert( EIGHT_BYTE_ALIGNMENT(aCopy[0]) );
  38904. for(i=1; i<NB; i++){
  38905. aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
  38906. assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
  38907. }
  38908. aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
  38909. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  38910. if( ISAUTOVACUUM ){
  38911. aFrom = &aSpace1[pBt->pageSize];
  38912. }
  38913. aSpace2 = sqlite3PageMalloc(pBt->pageSize);
  38914. if( aSpace2==0 ){
  38915. rc = SQLITE_NOMEM;
  38916. goto balance_cleanup;
  38917. }
  38918. /*
  38919. ** Make copies of the content of pPage and its siblings into aOld[].
  38920. ** The rest of this function will use data from the copies rather
  38921. ** that the original pages since the original pages will be in the
  38922. ** process of being overwritten.
  38923. */
  38924. for(i=0; i<nOld; i++){
  38925. MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
  38926. memcpy(p, apOld[i], sizeof(MemPage));
  38927. p->aData = (void*)&p[1];
  38928. memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
  38929. }
  38930. /*
  38931. ** Load pointers to all cells on sibling pages and the divider cells
  38932. ** into the local apCell[] array. Make copies of the divider cells
  38933. ** into space obtained form aSpace1[] and remove the the divider Cells
  38934. ** from pParent.
  38935. **
  38936. ** If the siblings are on leaf pages, then the child pointers of the
  38937. ** divider cells are stripped from the cells before they are copied
  38938. ** into aSpace1[]. In this way, all cells in apCell[] are without
  38939. ** child pointers. If siblings are not leaves, then all cell in
  38940. ** apCell[] include child pointers. Either way, all cells in apCell[]
  38941. ** are alike.
  38942. **
  38943. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  38944. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  38945. */
  38946. nCell = 0;
  38947. leafCorrection = pPage->leaf*4;
  38948. leafData = pPage->hasData;
  38949. for(i=0; i<nOld; i++){
  38950. MemPage *pOld = apCopy[i];
  38951. int limit = pOld->nCell+pOld->nOverflow;
  38952. for(j=0; j<limit; j++){
  38953. assert( nCell<nMaxCells );
  38954. apCell[nCell] = findOverflowCell(pOld, j);
  38955. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  38956. if( ISAUTOVACUUM ){
  38957. int a;
  38958. aFrom[nCell] = (u8)i; assert( i>=0 && i<6 );
  38959. for(a=0; a<pOld->nOverflow; a++){
  38960. if( pOld->aOvfl[a].pCell==apCell[nCell] ){
  38961. aFrom[nCell] = 0xFF;
  38962. break;
  38963. }
  38964. }
  38965. }
  38966. nCell++;
  38967. }
  38968. if( i<nOld-1 ){
  38969. u16 sz = cellSizePtr(pParent, apDiv[i]);
  38970. if( leafData ){
  38971. /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
  38972. ** are duplicates of keys on the child pages. We need to remove
  38973. ** the divider cells from pParent, but the dividers cells are not
  38974. ** added to apCell[] because they are duplicates of child cells.
  38975. */
  38976. dropCell(pParent, nxDiv, sz);
  38977. }else{
  38978. u8 *pTemp;
  38979. assert( nCell<nMaxCells );
  38980. szCell[nCell] = sz;
  38981. pTemp = &aSpace1[iSpace1];
  38982. iSpace1 += sz;
  38983. assert( sz<=pBt->pageSize/4 );
  38984. assert( iSpace1<=pBt->pageSize );
  38985. memcpy(pTemp, apDiv[i], sz);
  38986. apCell[nCell] = pTemp+leafCorrection;
  38987. if( ISAUTOVACUUM ){
  38988. aFrom[nCell] = 0xFF;
  38989. }
  38990. dropCell(pParent, nxDiv, sz);
  38991. assert( leafCorrection==0 || leafCorrection==4 );
  38992. szCell[nCell] -= (u16)leafCorrection;
  38993. assert( get4byte(pTemp)==pgnoOld[i] );
  38994. if( !pOld->leaf ){
  38995. assert( leafCorrection==0 );
  38996. /* The right pointer of the child page pOld becomes the left
  38997. ** pointer of the divider cell */
  38998. memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
  38999. }else{
  39000. assert( leafCorrection==4 );
  39001. if( szCell[nCell]<4 ){
  39002. /* Do not allow any cells smaller than 4 bytes. */
  39003. szCell[nCell] = 4;
  39004. }
  39005. }
  39006. nCell++;
  39007. }
  39008. }
  39009. }
  39010. /*
  39011. ** Figure out the number of pages needed to hold all nCell cells.
  39012. ** Store this number in "k". Also compute szNew[] which is the total
  39013. ** size of all cells on the i-th page and cntNew[] which is the index
  39014. ** in apCell[] of the cell that divides page i from page i+1.
  39015. ** cntNew[k] should equal nCell.
  39016. **
  39017. ** Values computed by this block:
  39018. **
  39019. ** k: The total number of sibling pages
  39020. ** szNew[i]: Spaced used on the i-th sibling page.
  39021. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  39022. ** the right of the i-th sibling page.
  39023. ** usableSpace: Number of bytes of space available on each sibling.
  39024. **
  39025. */
  39026. usableSpace = pBt->usableSize - 12 + leafCorrection;
  39027. for(subtotal=k=i=0; i<nCell; i++){
  39028. assert( i<nMaxCells );
  39029. subtotal += szCell[i] + 2;
  39030. if( subtotal > usableSpace ){
  39031. szNew[k] = subtotal - szCell[i];
  39032. cntNew[k] = i;
  39033. if( leafData ){ i--; }
  39034. subtotal = 0;
  39035. k++;
  39036. }
  39037. }
  39038. szNew[k] = subtotal;
  39039. cntNew[k] = nCell;
  39040. k++;
  39041. /*
  39042. ** The packing computed by the previous block is biased toward the siblings
  39043. ** on the left side. The left siblings are always nearly full, while the
  39044. ** right-most sibling might be nearly empty. This block of code attempts
  39045. ** to adjust the packing of siblings to get a better balance.
  39046. **
  39047. ** This adjustment is more than an optimization. The packing above might
  39048. ** be so out of balance as to be illegal. For example, the right-most
  39049. ** sibling might be completely empty. This adjustment is not optional.
  39050. */
  39051. for(i=k-1; i>0; i--){
  39052. int szRight = szNew[i]; /* Size of sibling on the right */
  39053. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  39054. int r; /* Index of right-most cell in left sibling */
  39055. int d; /* Index of first cell to the left of right sibling */
  39056. r = cntNew[i-1] - 1;
  39057. d = r + 1 - leafData;
  39058. assert( d<nMaxCells );
  39059. assert( r<nMaxCells );
  39060. while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
  39061. szRight += szCell[d] + 2;
  39062. szLeft -= szCell[r] + 2;
  39063. cntNew[i-1]--;
  39064. r = cntNew[i-1] - 1;
  39065. d = r + 1 - leafData;
  39066. }
  39067. szNew[i] = szRight;
  39068. szNew[i-1] = szLeft;
  39069. }
  39070. /* Either we found one or more cells (cntnew[0])>0) or we are the
  39071. ** a virtual root page. A virtual root page is when the real root
  39072. ** page is page 1 and we are the only child of that page.
  39073. */
  39074. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  39075. /*
  39076. ** Allocate k new pages. Reuse old pages where possible.
  39077. */
  39078. assert( pPage->pgno>1 );
  39079. pageFlags = pPage->aData[0];
  39080. for(i=0; i<k; i++){
  39081. MemPage *pNew;
  39082. if( i<nOld ){
  39083. pNew = apNew[i] = apOld[i];
  39084. pgnoNew[i] = pgnoOld[i];
  39085. apOld[i] = 0;
  39086. rc = sqlite3PagerWrite(pNew->pDbPage);
  39087. nNew++;
  39088. if( rc ) goto balance_cleanup;
  39089. }else{
  39090. assert( i>0 );
  39091. rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
  39092. if( rc ) goto balance_cleanup;
  39093. apNew[i] = pNew;
  39094. nNew++;
  39095. }
  39096. }
  39097. /* Free any old pages that were not reused as new pages.
  39098. */
  39099. while( i<nOld ){
  39100. rc = freePage(apOld[i]);
  39101. if( rc ) goto balance_cleanup;
  39102. releasePage(apOld[i]);
  39103. apOld[i] = 0;
  39104. i++;
  39105. }
  39106. /*
  39107. ** Put the new pages in accending order. This helps to
  39108. ** keep entries in the disk file in order so that a scan
  39109. ** of the table is a linear scan through the file. That
  39110. ** in turn helps the operating system to deliver pages
  39111. ** from the disk more rapidly.
  39112. **
  39113. ** An O(n^2) insertion sort algorithm is used, but since
  39114. ** n is never more than NB (a small constant), that should
  39115. ** not be a problem.
  39116. **
  39117. ** When NB==3, this one optimization makes the database
  39118. ** about 25% faster for large insertions and deletions.
  39119. */
  39120. for(i=0; i<k-1; i++){
  39121. int minV = pgnoNew[i];
  39122. int minI = i;
  39123. for(j=i+1; j<k; j++){
  39124. if( pgnoNew[j]<(unsigned)minV ){
  39125. minI = j;
  39126. minV = pgnoNew[j];
  39127. }
  39128. }
  39129. if( minI>i ){
  39130. int t;
  39131. MemPage *pT;
  39132. t = pgnoNew[i];
  39133. pT = apNew[i];
  39134. pgnoNew[i] = pgnoNew[minI];
  39135. apNew[i] = apNew[minI];
  39136. pgnoNew[minI] = t;
  39137. apNew[minI] = pT;
  39138. }
  39139. }
  39140. TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  39141. pgnoOld[0],
  39142. nOld>=2 ? pgnoOld[1] : 0,
  39143. nOld>=3 ? pgnoOld[2] : 0,
  39144. pgnoNew[0], szNew[0],
  39145. nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
  39146. nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
  39147. nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
  39148. nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
  39149. /*
  39150. ** Evenly distribute the data in apCell[] across the new pages.
  39151. ** Insert divider cells into pParent as necessary.
  39152. */
  39153. j = 0;
  39154. for(i=0; i<nNew; i++){
  39155. /* Assemble the new sibling page. */
  39156. MemPage *pNew = apNew[i];
  39157. assert( j<nMaxCells );
  39158. assert( pNew->pgno==pgnoNew[i] );
  39159. zeroPage(pNew, pageFlags);
  39160. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  39161. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  39162. assert( pNew->nOverflow==0 );
  39163. /* If this is an auto-vacuum database, update the pointer map entries
  39164. ** that point to the siblings that were rearranged. These can be: left
  39165. ** children of cells, the right-child of the page, or overflow pages
  39166. ** pointed to by cells.
  39167. */
  39168. if( ISAUTOVACUUM ){
  39169. for(k=j; k<cntNew[i]; k++){
  39170. assert( k<nMaxCells );
  39171. if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
  39172. rc = ptrmapPutOvfl(pNew, k-j);
  39173. if( rc==SQLITE_OK && leafCorrection==0 ){
  39174. rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
  39175. }
  39176. if( rc!=SQLITE_OK ){
  39177. goto balance_cleanup;
  39178. }
  39179. }
  39180. }
  39181. }
  39182. j = cntNew[i];
  39183. /* If the sibling page assembled above was not the right-most sibling,
  39184. ** insert a divider cell into the parent page.
  39185. */
  39186. if( i<nNew-1 && j<nCell ){
  39187. u8 *pCell;
  39188. u8 *pTemp;
  39189. int sz;
  39190. assert( j<nMaxCells );
  39191. pCell = apCell[j];
  39192. sz = szCell[j] + leafCorrection;
  39193. pTemp = &aSpace2[iSpace2];
  39194. if( !pNew->leaf ){
  39195. memcpy(&pNew->aData[8], pCell, 4);
  39196. if( ISAUTOVACUUM
  39197. && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
  39198. ){
  39199. rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
  39200. if( rc!=SQLITE_OK ){
  39201. goto balance_cleanup;
  39202. }
  39203. }
  39204. }else if( leafData ){
  39205. /* If the tree is a leaf-data tree, and the siblings are leaves,
  39206. ** then there is no divider cell in apCell[]. Instead, the divider
  39207. ** cell consists of the integer key for the right-most cell of
  39208. ** the sibling-page assembled above only.
  39209. */
  39210. CellInfo info;
  39211. j--;
  39212. sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
  39213. pCell = pTemp;
  39214. rc = fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
  39215. if( rc!=SQLITE_OK ){
  39216. goto balance_cleanup;
  39217. }
  39218. pTemp = 0;
  39219. }else{
  39220. pCell -= 4;
  39221. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  39222. ** previously stored on a leaf node, and its reported size was 4
  39223. ** bytes, then it may actually be smaller than this
  39224. ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
  39225. ** any cell). But it is important to pass the correct size to
  39226. ** insertCell(), so reparse the cell now.
  39227. **
  39228. ** Note that this can never happen in an SQLite data file, as all
  39229. ** cells are at least 4 bytes. It only happens in b-trees used
  39230. ** to evaluate "IN (SELECT ...)" and similar clauses.
  39231. */
  39232. if( szCell[j]==4 ){
  39233. assert(leafCorrection==4);
  39234. sz = cellSizePtr(pParent, pCell);
  39235. }
  39236. }
  39237. iSpace2 += sz;
  39238. assert( sz<=pBt->pageSize/4 );
  39239. assert( iSpace2<=pBt->pageSize );
  39240. rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
  39241. if( rc!=SQLITE_OK ) goto balance_cleanup;
  39242. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  39243. put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
  39244. /* If this is an auto-vacuum database, and not a leaf-data tree,
  39245. ** then update the pointer map with an entry for the overflow page
  39246. ** that the cell just inserted points to (if any).
  39247. */
  39248. if( ISAUTOVACUUM && !leafData ){
  39249. rc = ptrmapPutOvfl(pParent, nxDiv);
  39250. if( rc!=SQLITE_OK ){
  39251. goto balance_cleanup;
  39252. }
  39253. }
  39254. j++;
  39255. nxDiv++;
  39256. }
  39257. /* Set the pointer-map entry for the new sibling page. */
  39258. if( ISAUTOVACUUM ){
  39259. rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
  39260. if( rc!=SQLITE_OK ){
  39261. goto balance_cleanup;
  39262. }
  39263. }
  39264. }
  39265. assert( j==nCell );
  39266. assert( nOld>0 );
  39267. assert( nNew>0 );
  39268. if( (pageFlags & PTF_LEAF)==0 ){
  39269. u8 *zChild = &apCopy[nOld-1]->aData[8];
  39270. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  39271. if( ISAUTOVACUUM ){
  39272. rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
  39273. if( rc!=SQLITE_OK ){
  39274. goto balance_cleanup;
  39275. }
  39276. }
  39277. }
  39278. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  39279. if( nxDiv==pParent->nCell+pParent->nOverflow ){
  39280. /* Right-most sibling is the right-most child of pParent */
  39281. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
  39282. }else{
  39283. /* Right-most sibling is the left child of the first entry in pParent
  39284. ** past the right-most divider entry */
  39285. put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
  39286. }
  39287. /*
  39288. ** Balance the parent page. Note that the current page (pPage) might
  39289. ** have been added to the freelist so it might no longer be initialized.
  39290. ** But the parent page will always be initialized.
  39291. */
  39292. assert( pParent->isInit );
  39293. sqlite3ScratchFree(apCell);
  39294. apCell = 0;
  39295. TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
  39296. pPage->pgno, nOld, nNew, nCell));
  39297. pPage->nOverflow = 0;
  39298. releasePage(pPage);
  39299. pCur->iPage--;
  39300. rc = balance(pCur, 0);
  39301. /*
  39302. ** Cleanup before returning.
  39303. */
  39304. balance_cleanup:
  39305. sqlite3PageFree(aSpace2);
  39306. sqlite3ScratchFree(apCell);
  39307. for(i=0; i<nOld; i++){
  39308. releasePage(apOld[i]);
  39309. }
  39310. for(i=0; i<nNew; i++){
  39311. releasePage(apNew[i]);
  39312. }
  39313. pCur->apPage[pCur->iPage]->nOverflow = 0;
  39314. return rc;
  39315. }
  39316. /*
  39317. ** This routine is called for the root page of a btree when the root
  39318. ** page contains no cells. This is an opportunity to make the tree
  39319. ** shallower by one level.
  39320. */
  39321. static int balance_shallower(BtCursor *pCur){
  39322. MemPage *pPage; /* Root page of B-Tree */
  39323. MemPage *pChild; /* The only child page of pPage */
  39324. Pgno pgnoChild; /* Page number for pChild */
  39325. int rc = SQLITE_OK; /* Return code from subprocedures */
  39326. BtShared *pBt; /* The main BTree structure */
  39327. int mxCellPerPage; /* Maximum number of cells per page */
  39328. u8 **apCell; /* All cells from pages being balanced */
  39329. u16 *szCell; /* Local size of all cells */
  39330. assert( pCur->iPage==0 );
  39331. pPage = pCur->apPage[0];
  39332. assert( pPage->nCell==0 );
  39333. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39334. pBt = pPage->pBt;
  39335. mxCellPerPage = MX_CELL(pBt);
  39336. apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
  39337. if( apCell==0 ) return SQLITE_NOMEM;
  39338. szCell = (u16*)&apCell[mxCellPerPage];
  39339. if( pPage->leaf ){
  39340. /* The table is completely empty */
  39341. TRACE(("BALANCE: empty table %d\n", pPage->pgno));
  39342. }else{
  39343. /* The root page is empty but has one child. Transfer the
  39344. ** information from that one child into the root page if it
  39345. ** will fit. This reduces the depth of the tree by one.
  39346. **
  39347. ** If the root page is page 1, it has less space available than
  39348. ** its child (due to the 100 byte header that occurs at the beginning
  39349. ** of the database fle), so it might not be able to hold all of the
  39350. ** information currently contained in the child. If this is the
  39351. ** case, then do not do the transfer. Leave page 1 empty except
  39352. ** for the right-pointer to the child page. The child page becomes
  39353. ** the virtual root of the tree.
  39354. */
  39355. VVA_ONLY( pCur->pagesShuffled = 1 );
  39356. pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  39357. assert( pgnoChild>0 );
  39358. assert( pgnoChild<=pagerPagecount(pPage->pBt) );
  39359. rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
  39360. if( rc ) goto end_shallow_balance;
  39361. if( pPage->pgno==1 ){
  39362. rc = sqlite3BtreeInitPage(pChild);
  39363. if( rc ) goto end_shallow_balance;
  39364. assert( pChild->nOverflow==0 );
  39365. if( pChild->nFree>=100 ){
  39366. /* The child information will fit on the root page, so do the
  39367. ** copy */
  39368. int i;
  39369. zeroPage(pPage, pChild->aData[0]);
  39370. for(i=0; i<pChild->nCell; i++){
  39371. apCell[i] = findCell(pChild,i);
  39372. szCell[i] = cellSizePtr(pChild, apCell[i]);
  39373. }
  39374. assemblePage(pPage, pChild->nCell, apCell, szCell);
  39375. /* Copy the right-pointer of the child to the parent. */
  39376. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39377. put4byte(&pPage->aData[pPage->hdrOffset+8],
  39378. get4byte(&pChild->aData[pChild->hdrOffset+8]));
  39379. rc = freePage(pChild);
  39380. TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
  39381. }else{
  39382. /* The child has more information that will fit on the root.
  39383. ** The tree is already balanced. Do nothing. */
  39384. TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
  39385. }
  39386. }else{
  39387. memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
  39388. pPage->isInit = 0;
  39389. rc = sqlite3BtreeInitPage(pPage);
  39390. assert( rc==SQLITE_OK );
  39391. freePage(pChild);
  39392. TRACE(("BALANCE: transfer child %d into root %d\n",
  39393. pChild->pgno, pPage->pgno));
  39394. }
  39395. assert( pPage->nOverflow==0 );
  39396. #ifndef SQLITE_OMIT_AUTOVACUUM
  39397. if( ISAUTOVACUUM && rc==SQLITE_OK ){
  39398. rc = setChildPtrmaps(pPage);
  39399. }
  39400. #endif
  39401. releasePage(pChild);
  39402. }
  39403. end_shallow_balance:
  39404. sqlite3_free(apCell);
  39405. return rc;
  39406. }
  39407. /*
  39408. ** The root page is overfull
  39409. **
  39410. ** When this happens, Create a new child page and copy the
  39411. ** contents of the root into the child. Then make the root
  39412. ** page an empty page with rightChild pointing to the new
  39413. ** child. Finally, call balance_internal() on the new child
  39414. ** to cause it to split.
  39415. */
  39416. static int balance_deeper(BtCursor *pCur){
  39417. int rc; /* Return value from subprocedures */
  39418. MemPage *pPage; /* Pointer to the root page */
  39419. MemPage *pChild; /* Pointer to a new child page */
  39420. Pgno pgnoChild; /* Page number of the new child page */
  39421. BtShared *pBt; /* The BTree */
  39422. int usableSize; /* Total usable size of a page */
  39423. u8 *data; /* Content of the parent page */
  39424. u8 *cdata; /* Content of the child page */
  39425. int hdr; /* Offset to page header in parent */
  39426. int cbrk; /* Offset to content of first cell in parent */
  39427. assert( pCur->iPage==0 );
  39428. assert( pCur->apPage[0]->nOverflow>0 );
  39429. VVA_ONLY( pCur->pagesShuffled = 1 );
  39430. pPage = pCur->apPage[0];
  39431. pBt = pPage->pBt;
  39432. assert( sqlite3_mutex_held(pBt->mutex) );
  39433. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39434. rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
  39435. if( rc ) return rc;
  39436. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  39437. usableSize = pBt->usableSize;
  39438. data = pPage->aData;
  39439. hdr = pPage->hdrOffset;
  39440. cbrk = get2byte(&data[hdr+5]);
  39441. cdata = pChild->aData;
  39442. memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
  39443. memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
  39444. assert( pChild->isInit==0 );
  39445. rc = sqlite3BtreeInitPage(pChild);
  39446. if( rc==SQLITE_OK ){
  39447. int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
  39448. memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
  39449. pChild->nOverflow = pPage->nOverflow;
  39450. if( pChild->nOverflow ){
  39451. pChild->nFree = 0;
  39452. }
  39453. assert( pChild->nCell==pPage->nCell );
  39454. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39455. zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
  39456. put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
  39457. TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
  39458. if( ISAUTOVACUUM ){
  39459. rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
  39460. #ifndef SQLITE_OMIT_AUTOVACUUM
  39461. if( rc==SQLITE_OK ){
  39462. rc = setChildPtrmaps(pChild);
  39463. }
  39464. if( rc ){
  39465. pChild->nOverflow = 0;
  39466. }
  39467. #endif
  39468. }
  39469. }
  39470. if( rc==SQLITE_OK ){
  39471. pCur->iPage++;
  39472. pCur->apPage[1] = pChild;
  39473. pCur->aiIdx[0] = 0;
  39474. rc = balance_nonroot(pCur);
  39475. }else{
  39476. releasePage(pChild);
  39477. }
  39478. return rc;
  39479. }
  39480. /*
  39481. ** The page that pCur currently points to has just been modified in
  39482. ** some way. This function figures out if this modification means the
  39483. ** tree needs to be balanced, and if so calls the appropriate balancing
  39484. ** routine.
  39485. **
  39486. ** Parameter isInsert is true if a new cell was just inserted into the
  39487. ** page, or false otherwise.
  39488. */
  39489. static int balance(BtCursor *pCur, int isInsert){
  39490. int rc = SQLITE_OK;
  39491. MemPage *pPage = pCur->apPage[pCur->iPage];
  39492. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39493. if( pCur->iPage==0 ){
  39494. rc = sqlite3PagerWrite(pPage->pDbPage);
  39495. if( rc==SQLITE_OK && pPage->nOverflow>0 ){
  39496. rc = balance_deeper(pCur);
  39497. assert( pCur->apPage[0]==pPage );
  39498. assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
  39499. }
  39500. if( rc==SQLITE_OK && pPage->nCell==0 ){
  39501. rc = balance_shallower(pCur);
  39502. assert( pCur->apPage[0]==pPage );
  39503. assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
  39504. }
  39505. }else{
  39506. if( pPage->nOverflow>0 ||
  39507. (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
  39508. rc = balance_nonroot(pCur);
  39509. }
  39510. }
  39511. return rc;
  39512. }
  39513. /*
  39514. ** This routine checks all cursors that point to table pgnoRoot.
  39515. ** If any of those cursors were opened with wrFlag==0 in a different
  39516. ** database connection (a database connection that shares the pager
  39517. ** cache with the current connection) and that other connection
  39518. ** is not in the ReadUncommmitted state, then this routine returns
  39519. ** SQLITE_LOCKED.
  39520. **
  39521. ** As well as cursors with wrFlag==0, cursors with
  39522. ** isIncrblobHandle==1 are also considered 'read' cursors because
  39523. ** incremental blob cursors are used for both reading and writing.
  39524. **
  39525. ** When pgnoRoot is the root page of an intkey table, this function is also
  39526. ** responsible for invalidating incremental blob cursors when the table row
  39527. ** on which they are opened is deleted or modified. Cursors are invalidated
  39528. ** according to the following rules:
  39529. **
  39530. ** 1) When BtreeClearTable() is called to completely delete the contents
  39531. ** of a B-Tree table, pExclude is set to zero and parameter iRow is
  39532. ** set to non-zero. In this case all incremental blob cursors open
  39533. ** on the table rooted at pgnoRoot are invalidated.
  39534. **
  39535. ** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
  39536. ** modify a table row via an SQL statement, pExclude is set to the
  39537. ** write cursor used to do the modification and parameter iRow is set
  39538. ** to the integer row id of the B-Tree entry being modified. Unless
  39539. ** pExclude is itself an incremental blob cursor, then all incremental
  39540. ** blob cursors open on row iRow of the B-Tree are invalidated.
  39541. **
  39542. ** 3) If both pExclude and iRow are set to zero, no incremental blob
  39543. ** cursors are invalidated.
  39544. */
  39545. static int checkForReadConflicts(
  39546. Btree *pBtree, /* The database file to check */
  39547. Pgno pgnoRoot, /* Look for read cursors on this btree */
  39548. BtCursor *pExclude, /* Ignore this cursor */
  39549. i64 iRow /* The rowid that might be changing */
  39550. ){
  39551. BtCursor *p;
  39552. BtShared *pBt = pBtree->pBt;
  39553. sqlite3 *db = pBtree->db;
  39554. assert( sqlite3BtreeHoldsMutex(pBtree) );
  39555. for(p=pBt->pCursor; p; p=p->pNext){
  39556. if( p==pExclude ) continue;
  39557. if( p->pgnoRoot!=pgnoRoot ) continue;
  39558. #ifndef SQLITE_OMIT_INCRBLOB
  39559. if( p->isIncrblobHandle && (
  39560. (!pExclude && iRow)
  39561. || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
  39562. )){
  39563. p->eState = CURSOR_INVALID;
  39564. }
  39565. #endif
  39566. if( p->eState!=CURSOR_VALID ) continue;
  39567. if( p->wrFlag==0
  39568. #ifndef SQLITE_OMIT_INCRBLOB
  39569. || p->isIncrblobHandle
  39570. #endif
  39571. ){
  39572. sqlite3 *dbOther = p->pBtree->db;
  39573. assert(dbOther);
  39574. if( dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0 ){
  39575. sqlite3ConnectionBlocked(db, dbOther);
  39576. return SQLITE_LOCKED_SHAREDCACHE;
  39577. }
  39578. }
  39579. }
  39580. return SQLITE_OK;
  39581. }
  39582. /*
  39583. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  39584. ** and the data is given by (pData,nData). The cursor is used only to
  39585. ** define what table the record should be inserted into. The cursor
  39586. ** is left pointing at a random location.
  39587. **
  39588. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  39589. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  39590. */
  39591. SQLITE_PRIVATE int sqlite3BtreeInsert(
  39592. BtCursor *pCur, /* Insert data into the table of this cursor */
  39593. const void *pKey, i64 nKey, /* The key of the new record */
  39594. const void *pData, int nData, /* The data of the new record */
  39595. int nZero, /* Number of extra 0 bytes to append to data */
  39596. int appendBias /* True if this is likely an append */
  39597. ){
  39598. int rc;
  39599. int loc;
  39600. int szNew;
  39601. int idx;
  39602. MemPage *pPage;
  39603. Btree *p = pCur->pBtree;
  39604. BtShared *pBt = p->pBt;
  39605. unsigned char *oldCell;
  39606. unsigned char *newCell = 0;
  39607. assert( cursorHoldsMutex(pCur) );
  39608. assert( pBt->inTransaction==TRANS_WRITE );
  39609. assert( !pBt->readOnly );
  39610. assert( pCur->wrFlag );
  39611. rc = checkForReadConflicts(pCur->pBtree, pCur->pgnoRoot, pCur, nKey);
  39612. if( rc ){
  39613. /* The table pCur points to has a read lock */
  39614. assert( rc==SQLITE_LOCKED_SHAREDCACHE );
  39615. return rc;
  39616. }
  39617. if( pCur->eState==CURSOR_FAULT ){
  39618. return pCur->skip;
  39619. }
  39620. /* Save the positions of any other cursors open on this table */
  39621. sqlite3BtreeClearCursor(pCur);
  39622. if(
  39623. SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
  39624. SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
  39625. ){
  39626. return rc;
  39627. }
  39628. pPage = pCur->apPage[pCur->iPage];
  39629. assert( pPage->intKey || nKey>=0 );
  39630. assert( pPage->leaf || !pPage->intKey );
  39631. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  39632. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  39633. loc==0 ? "overwrite" : "new entry"));
  39634. assert( pPage->isInit );
  39635. allocateTempSpace(pBt);
  39636. newCell = pBt->pTmpSpace;
  39637. if( newCell==0 ) return SQLITE_NOMEM;
  39638. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  39639. if( rc ) goto end_insert;
  39640. assert( szNew==cellSizePtr(pPage, newCell) );
  39641. assert( szNew<=MX_CELL_SIZE(pBt) );
  39642. idx = pCur->aiIdx[pCur->iPage];
  39643. if( loc==0 && CURSOR_VALID==pCur->eState ){
  39644. u16 szOld;
  39645. assert( idx<pPage->nCell );
  39646. rc = sqlite3PagerWrite(pPage->pDbPage);
  39647. if( rc ){
  39648. goto end_insert;
  39649. }
  39650. oldCell = findCell(pPage, idx);
  39651. if( !pPage->leaf ){
  39652. memcpy(newCell, oldCell, 4);
  39653. }
  39654. szOld = cellSizePtr(pPage, oldCell);
  39655. rc = clearCell(pPage, oldCell);
  39656. if( rc ) goto end_insert;
  39657. rc = dropCell(pPage, idx, szOld);
  39658. if( rc!=SQLITE_OK ) {
  39659. goto end_insert;
  39660. }
  39661. }else if( loc<0 && pPage->nCell>0 ){
  39662. assert( pPage->leaf );
  39663. idx = ++pCur->aiIdx[pCur->iPage];
  39664. pCur->info.nSize = 0;
  39665. pCur->validNKey = 0;
  39666. }else{
  39667. assert( pPage->leaf );
  39668. }
  39669. rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
  39670. if( rc==SQLITE_OK ){
  39671. rc = balance(pCur, 1);
  39672. }
  39673. /* Must make sure nOverflow is reset to zero even if the balance()
  39674. ** fails. Internal data structure corruption will result otherwise. */
  39675. pCur->apPage[pCur->iPage]->nOverflow = 0;
  39676. if( rc==SQLITE_OK ){
  39677. moveToRoot(pCur);
  39678. }
  39679. end_insert:
  39680. return rc;
  39681. }
  39682. /*
  39683. ** Delete the entry that the cursor is pointing to. The cursor
  39684. ** is left pointing at a arbitrary location.
  39685. */
  39686. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  39687. MemPage *pPage = pCur->apPage[pCur->iPage];
  39688. int idx;
  39689. unsigned char *pCell;
  39690. int rc;
  39691. Pgno pgnoChild = 0;
  39692. Btree *p = pCur->pBtree;
  39693. BtShared *pBt = p->pBt;
  39694. assert( cursorHoldsMutex(pCur) );
  39695. assert( pPage->isInit );
  39696. assert( pBt->inTransaction==TRANS_WRITE );
  39697. assert( !pBt->readOnly );
  39698. if( pCur->eState==CURSOR_FAULT ){
  39699. return pCur->skip;
  39700. }
  39701. if( NEVER(pCur->aiIdx[pCur->iPage]>=pPage->nCell) ){
  39702. return SQLITE_ERROR; /* The cursor is not pointing to anything */
  39703. }
  39704. assert( pCur->wrFlag );
  39705. rc = checkForReadConflicts(p, pCur->pgnoRoot, pCur, pCur->info.nKey);
  39706. if( rc!=SQLITE_OK ){
  39707. /* The table pCur points to has a read lock */
  39708. assert( rc==SQLITE_LOCKED_SHAREDCACHE );
  39709. return rc;
  39710. }
  39711. /* Restore the current cursor position (a no-op if the cursor is not in
  39712. ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
  39713. ** open on the same table. Then call sqlite3PagerWrite() on the page
  39714. ** that the entry will be deleted from.
  39715. */
  39716. if(
  39717. (rc = restoreCursorPosition(pCur))!=0 ||
  39718. (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
  39719. (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
  39720. ){
  39721. return rc;
  39722. }
  39723. /* Locate the cell within its page and leave pCell pointing to the
  39724. ** data. The clearCell() call frees any overflow pages associated with the
  39725. ** cell. The cell itself is still intact.
  39726. */
  39727. idx = pCur->aiIdx[pCur->iPage];
  39728. pCell = findCell(pPage, idx);
  39729. if( !pPage->leaf ){
  39730. pgnoChild = get4byte(pCell);
  39731. }
  39732. rc = clearCell(pPage, pCell);
  39733. if( rc ){
  39734. return rc;
  39735. }
  39736. if( !pPage->leaf ){
  39737. /*
  39738. ** The entry we are about to delete is not a leaf so if we do not
  39739. ** do something we will leave a hole on an internal page.
  39740. ** We have to fill the hole by moving in a cell from a leaf. The
  39741. ** next Cell after the one to be deleted is guaranteed to exist and
  39742. ** to be a leaf so we can use it.
  39743. */
  39744. BtCursor leafCur;
  39745. MemPage *pLeafPage = 0;
  39746. unsigned char *pNext;
  39747. int notUsed;
  39748. unsigned char *tempCell = 0;
  39749. assert( !pPage->intKey );
  39750. sqlite3BtreeGetTempCursor(pCur, &leafCur);
  39751. rc = sqlite3BtreeNext(&leafCur, &notUsed);
  39752. if( rc==SQLITE_OK ){
  39753. assert( leafCur.aiIdx[leafCur.iPage]==0 );
  39754. pLeafPage = leafCur.apPage[leafCur.iPage];
  39755. rc = sqlite3PagerWrite(pLeafPage->pDbPage);
  39756. }
  39757. if( rc==SQLITE_OK ){
  39758. int leafCursorInvalid = 0;
  39759. u16 szNext;
  39760. TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
  39761. pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
  39762. dropCell(pPage, idx, cellSizePtr(pPage, pCell));
  39763. pNext = findCell(pLeafPage, 0);
  39764. szNext = cellSizePtr(pLeafPage, pNext);
  39765. assert( MX_CELL_SIZE(pBt)>=szNext+4 );
  39766. allocateTempSpace(pBt);
  39767. tempCell = pBt->pTmpSpace;
  39768. if( tempCell==0 ){
  39769. rc = SQLITE_NOMEM;
  39770. }
  39771. if( rc==SQLITE_OK ){
  39772. rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
  39773. }
  39774. /* The "if" statement in the next code block is critical. The
  39775. ** slightest error in that statement would allow SQLite to operate
  39776. ** correctly most of the time but produce very rare failures. To
  39777. ** guard against this, the following macros help to verify that
  39778. ** the "if" statement is well tested.
  39779. */
  39780. testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
  39781. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39782. testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
  39783. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39784. testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
  39785. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39786. testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
  39787. && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
  39788. testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
  39789. && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
  39790. if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
  39791. (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
  39792. ){
  39793. /* This branch is taken if the internal node is now either overflowing
  39794. ** or underfull and the leaf node will be underfull after the just cell
  39795. ** copied to the internal node is deleted from it. This is a special
  39796. ** case because the call to balance() to correct the internal node
  39797. ** may change the tree structure and invalidate the contents of
  39798. ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
  39799. ** used by the balance() required to correct the underfull leaf
  39800. ** node.
  39801. **
  39802. ** The formula used in the expression above are based on facets of
  39803. ** the SQLite file-format that do not change over time.
  39804. */
  39805. testcase( pPage->nFree==pBt->usableSize*2/3+1 );
  39806. testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
  39807. leafCursorInvalid = 1;
  39808. }
  39809. if( rc==SQLITE_OK ){
  39810. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39811. put4byte(findOverflowCell(pPage, idx), pgnoChild);
  39812. VVA_ONLY( pCur->pagesShuffled = 0 );
  39813. rc = balance(pCur, 0);
  39814. }
  39815. if( rc==SQLITE_OK && leafCursorInvalid ){
  39816. /* The leaf-node is now underfull and so the tree needs to be
  39817. ** rebalanced. However, the balance() operation on the internal
  39818. ** node above may have modified the structure of the B-Tree and
  39819. ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
  39820. ** may not be trusted.
  39821. **
  39822. ** It is not possible to copy the ancestry from pCur, as the same
  39823. ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
  39824. ** arrays.
  39825. **
  39826. ** The call to saveCursorPosition() below internally saves the
  39827. ** key that leafCur is currently pointing to. Currently, there
  39828. ** are two copies of that key in the tree - one here on the leaf
  39829. ** page and one on some internal node in the tree. The copy on
  39830. ** the leaf node is always the next key in tree-order after the
  39831. ** copy on the internal node. So, the call to sqlite3BtreeNext()
  39832. ** calls restoreCursorPosition() to point the cursor to the copy
  39833. ** stored on the internal node, then advances to the next entry,
  39834. ** which happens to be the copy of the key on the internal node.
  39835. ** Net effect: leafCur is pointing back to the duplicate cell
  39836. ** that needs to be removed, and the leafCur.apPage[] and
  39837. ** leafCur.aiIdx[] arrays are correct.
  39838. */
  39839. VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
  39840. rc = saveCursorPosition(&leafCur);
  39841. if( rc==SQLITE_OK ){
  39842. rc = sqlite3BtreeNext(&leafCur, &notUsed);
  39843. }
  39844. pLeafPage = leafCur.apPage[leafCur.iPage];
  39845. assert( rc!=SQLITE_OK || pLeafPage->pgno==leafPgno );
  39846. assert( rc!=SQLITE_OK || leafCur.aiIdx[leafCur.iPage]==0 );
  39847. }
  39848. if( SQLITE_OK==rc
  39849. && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
  39850. ){
  39851. dropCell(pLeafPage, 0, szNext);
  39852. VVA_ONLY( leafCur.pagesShuffled = 0 );
  39853. rc = balance(&leafCur, 0);
  39854. assert( leafCursorInvalid || !leafCur.pagesShuffled
  39855. || !pCur->pagesShuffled );
  39856. }
  39857. }
  39858. sqlite3BtreeReleaseTempCursor(&leafCur);
  39859. }else{
  39860. TRACE(("DELETE: table=%d delete from leaf %d\n",
  39861. pCur->pgnoRoot, pPage->pgno));
  39862. rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
  39863. if( rc==SQLITE_OK ){
  39864. rc = balance(pCur, 0);
  39865. }
  39866. }
  39867. if( rc==SQLITE_OK ){
  39868. moveToRoot(pCur);
  39869. }
  39870. return rc;
  39871. }
  39872. /*
  39873. ** Create a new BTree table. Write into *piTable the page
  39874. ** number for the root page of the new table.
  39875. **
  39876. ** The type of type is determined by the flags parameter. Only the
  39877. ** following values of flags are currently in use. Other values for
  39878. ** flags might not work:
  39879. **
  39880. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  39881. ** BTREE_ZERODATA Used for SQL indices
  39882. */
  39883. static int btreeCreateTable(Btree *p, int *piTable, int flags){
  39884. BtShared *pBt = p->pBt;
  39885. MemPage *pRoot;
  39886. Pgno pgnoRoot;
  39887. int rc;
  39888. assert( sqlite3BtreeHoldsMutex(p) );
  39889. assert( pBt->inTransaction==TRANS_WRITE );
  39890. assert( !pBt->readOnly );
  39891. #ifdef SQLITE_OMIT_AUTOVACUUM
  39892. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  39893. if( rc ){
  39894. return rc;
  39895. }
  39896. #else
  39897. if( pBt->autoVacuum ){
  39898. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  39899. MemPage *pPageMove; /* The page to move to. */
  39900. /* Creating a new table may probably require moving an existing database
  39901. ** to make room for the new tables root page. In case this page turns
  39902. ** out to be an overflow page, delete all overflow page-map caches
  39903. ** held by open cursors.
  39904. */
  39905. invalidateAllOverflowCache(pBt);
  39906. /* Read the value of meta[3] from the database to determine where the
  39907. ** root page of the new table should go. meta[3] is the largest root-page
  39908. ** created so far, so the new root-page is (meta[3]+1).
  39909. */
  39910. rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
  39911. if( rc!=SQLITE_OK ){
  39912. return rc;
  39913. }
  39914. pgnoRoot++;
  39915. /* The new root-page may not be allocated on a pointer-map page, or the
  39916. ** PENDING_BYTE page.
  39917. */
  39918. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  39919. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  39920. pgnoRoot++;
  39921. }
  39922. assert( pgnoRoot>=3 );
  39923. /* Allocate a page. The page that currently resides at pgnoRoot will
  39924. ** be moved to the allocated page (unless the allocated page happens
  39925. ** to reside at pgnoRoot).
  39926. */
  39927. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
  39928. if( rc!=SQLITE_OK ){
  39929. return rc;
  39930. }
  39931. if( pgnoMove!=pgnoRoot ){
  39932. /* pgnoRoot is the page that will be used for the root-page of
  39933. ** the new table (assuming an error did not occur). But we were
  39934. ** allocated pgnoMove. If required (i.e. if it was not allocated
  39935. ** by extending the file), the current page at position pgnoMove
  39936. ** is already journaled.
  39937. */
  39938. u8 eType;
  39939. Pgno iPtrPage;
  39940. releasePage(pPageMove);
  39941. /* Move the page currently at pgnoRoot to pgnoMove. */
  39942. rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  39943. if( rc!=SQLITE_OK ){
  39944. return rc;
  39945. }
  39946. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  39947. if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  39948. releasePage(pRoot);
  39949. return rc;
  39950. }
  39951. assert( eType!=PTRMAP_ROOTPAGE );
  39952. assert( eType!=PTRMAP_FREEPAGE );
  39953. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  39954. releasePage(pRoot);
  39955. /* Obtain the page at pgnoRoot */
  39956. if( rc!=SQLITE_OK ){
  39957. return rc;
  39958. }
  39959. rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  39960. if( rc!=SQLITE_OK ){
  39961. return rc;
  39962. }
  39963. rc = sqlite3PagerWrite(pRoot->pDbPage);
  39964. if( rc!=SQLITE_OK ){
  39965. releasePage(pRoot);
  39966. return rc;
  39967. }
  39968. }else{
  39969. pRoot = pPageMove;
  39970. }
  39971. /* Update the pointer-map and meta-data with the new root-page number. */
  39972. rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
  39973. if( rc ){
  39974. releasePage(pRoot);
  39975. return rc;
  39976. }
  39977. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  39978. if( rc ){
  39979. releasePage(pRoot);
  39980. return rc;
  39981. }
  39982. }else{
  39983. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  39984. if( rc ) return rc;
  39985. }
  39986. #endif
  39987. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  39988. zeroPage(pRoot, flags | PTF_LEAF);
  39989. sqlite3PagerUnref(pRoot->pDbPage);
  39990. *piTable = (int)pgnoRoot;
  39991. return SQLITE_OK;
  39992. }
  39993. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  39994. int rc;
  39995. sqlite3BtreeEnter(p);
  39996. rc = btreeCreateTable(p, piTable, flags);
  39997. sqlite3BtreeLeave(p);
  39998. return rc;
  39999. }
  40000. /*
  40001. ** Erase the given database page and all its children. Return
  40002. ** the page to the freelist.
  40003. */
  40004. static int clearDatabasePage(
  40005. BtShared *pBt, /* The BTree that contains the table */
  40006. Pgno pgno, /* Page number to clear */
  40007. int freePageFlag, /* Deallocate page if true */
  40008. int *pnChange
  40009. ){
  40010. MemPage *pPage = 0;
  40011. int rc;
  40012. unsigned char *pCell;
  40013. int i;
  40014. assert( sqlite3_mutex_held(pBt->mutex) );
  40015. if( pgno>pagerPagecount(pBt) ){
  40016. return SQLITE_CORRUPT_BKPT;
  40017. }
  40018. rc = getAndInitPage(pBt, pgno, &pPage);
  40019. if( rc ) goto cleardatabasepage_out;
  40020. for(i=0; i<pPage->nCell; i++){
  40021. pCell = findCell(pPage, i);
  40022. if( !pPage->leaf ){
  40023. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  40024. if( rc ) goto cleardatabasepage_out;
  40025. }
  40026. rc = clearCell(pPage, pCell);
  40027. if( rc ) goto cleardatabasepage_out;
  40028. }
  40029. if( !pPage->leaf ){
  40030. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  40031. if( rc ) goto cleardatabasepage_out;
  40032. }else if( pnChange ){
  40033. assert( pPage->intKey );
  40034. *pnChange += pPage->nCell;
  40035. }
  40036. if( freePageFlag ){
  40037. rc = freePage(pPage);
  40038. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  40039. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  40040. }
  40041. cleardatabasepage_out:
  40042. releasePage(pPage);
  40043. return rc;
  40044. }
  40045. /*
  40046. ** Delete all information from a single table in the database. iTable is
  40047. ** the page number of the root of the table. After this routine returns,
  40048. ** the root page is empty, but still exists.
  40049. **
  40050. ** This routine will fail with SQLITE_LOCKED if there are any open
  40051. ** read cursors on the table. Open write cursors are moved to the
  40052. ** root of the table.
  40053. **
  40054. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  40055. ** integer value pointed to by pnChange is incremented by the number of
  40056. ** entries in the table.
  40057. */
  40058. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  40059. int rc;
  40060. BtShared *pBt = p->pBt;
  40061. sqlite3BtreeEnter(p);
  40062. assert( p->inTrans==TRANS_WRITE );
  40063. if( (rc = checkForReadConflicts(p, iTable, 0, 1))!=SQLITE_OK ){
  40064. /* nothing to do */
  40065. }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
  40066. /* nothing to do */
  40067. }else{
  40068. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  40069. }
  40070. sqlite3BtreeLeave(p);
  40071. return rc;
  40072. }
  40073. /*
  40074. ** Erase all information in a table and add the root of the table to
  40075. ** the freelist. Except, the root of the principle table (the one on
  40076. ** page 1) is never added to the freelist.
  40077. **
  40078. ** This routine will fail with SQLITE_LOCKED if there are any open
  40079. ** cursors on the table.
  40080. **
  40081. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  40082. ** root page in the database file, then the last root page
  40083. ** in the database file is moved into the slot formerly occupied by
  40084. ** iTable and that last slot formerly occupied by the last root page
  40085. ** is added to the freelist instead of iTable. In this say, all
  40086. ** root pages are kept at the beginning of the database file, which
  40087. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  40088. ** page number that used to be the last root page in the file before
  40089. ** the move. If no page gets moved, *piMoved is set to 0.
  40090. ** The last root page is recorded in meta[3] and the value of
  40091. ** meta[3] is updated by this procedure.
  40092. */
  40093. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  40094. int rc;
  40095. MemPage *pPage = 0;
  40096. BtShared *pBt = p->pBt;
  40097. assert( sqlite3BtreeHoldsMutex(p) );
  40098. assert( p->inTrans==TRANS_WRITE );
  40099. /* It is illegal to drop a table if any cursors are open on the
  40100. ** database. This is because in auto-vacuum mode the backend may
  40101. ** need to move another root-page to fill a gap left by the deleted
  40102. ** root page. If an open cursor was using this page a problem would
  40103. ** occur.
  40104. */
  40105. if( pBt->pCursor ){
  40106. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  40107. return SQLITE_LOCKED_SHAREDCACHE;
  40108. }
  40109. rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  40110. if( rc ) return rc;
  40111. rc = sqlite3BtreeClearTable(p, iTable, 0);
  40112. if( rc ){
  40113. releasePage(pPage);
  40114. return rc;
  40115. }
  40116. *piMoved = 0;
  40117. if( iTable>1 ){
  40118. #ifdef SQLITE_OMIT_AUTOVACUUM
  40119. rc = freePage(pPage);
  40120. releasePage(pPage);
  40121. #else
  40122. if( pBt->autoVacuum ){
  40123. Pgno maxRootPgno;
  40124. rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
  40125. if( rc!=SQLITE_OK ){
  40126. releasePage(pPage);
  40127. return rc;
  40128. }
  40129. if( iTable==maxRootPgno ){
  40130. /* If the table being dropped is the table with the largest root-page
  40131. ** number in the database, put the root page on the free list.
  40132. */
  40133. rc = freePage(pPage);
  40134. releasePage(pPage);
  40135. if( rc!=SQLITE_OK ){
  40136. return rc;
  40137. }
  40138. }else{
  40139. /* The table being dropped does not have the largest root-page
  40140. ** number in the database. So move the page that does into the
  40141. ** gap left by the deleted root-page.
  40142. */
  40143. MemPage *pMove;
  40144. releasePage(pPage);
  40145. rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
  40146. if( rc!=SQLITE_OK ){
  40147. return rc;
  40148. }
  40149. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  40150. releasePage(pMove);
  40151. if( rc!=SQLITE_OK ){
  40152. return rc;
  40153. }
  40154. rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
  40155. if( rc!=SQLITE_OK ){
  40156. return rc;
  40157. }
  40158. rc = freePage(pMove);
  40159. releasePage(pMove);
  40160. if( rc!=SQLITE_OK ){
  40161. return rc;
  40162. }
  40163. *piMoved = maxRootPgno;
  40164. }
  40165. /* Set the new 'max-root-page' value in the database header. This
  40166. ** is the old value less one, less one more if that happens to
  40167. ** be a root-page number, less one again if that is the
  40168. ** PENDING_BYTE_PAGE.
  40169. */
  40170. maxRootPgno--;
  40171. if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
  40172. maxRootPgno--;
  40173. }
  40174. if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
  40175. maxRootPgno--;
  40176. }
  40177. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  40178. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  40179. }else{
  40180. rc = freePage(pPage);
  40181. releasePage(pPage);
  40182. }
  40183. #endif
  40184. }else{
  40185. /* If sqlite3BtreeDropTable was called on page 1. */
  40186. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  40187. releasePage(pPage);
  40188. }
  40189. return rc;
  40190. }
  40191. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  40192. int rc;
  40193. sqlite3BtreeEnter(p);
  40194. rc = btreeDropTable(p, iTable, piMoved);
  40195. sqlite3BtreeLeave(p);
  40196. return rc;
  40197. }
  40198. /*
  40199. ** Read the meta-information out of a database file. Meta[0]
  40200. ** is the number of free pages currently in the database. Meta[1]
  40201. ** through meta[15] are available for use by higher layers. Meta[0]
  40202. ** is read-only, the others are read/write.
  40203. **
  40204. ** The schema layer numbers meta values differently. At the schema
  40205. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  40206. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  40207. */
  40208. SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  40209. DbPage *pDbPage = 0;
  40210. int rc;
  40211. unsigned char *pP1;
  40212. BtShared *pBt = p->pBt;
  40213. sqlite3BtreeEnter(p);
  40214. /* Reading a meta-data value requires a read-lock on page 1 (and hence
  40215. ** the sqlite_master table. We grab this lock regardless of whether or
  40216. ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
  40217. ** 1 is treated as a special case by querySharedCacheTableLock()
  40218. ** and setSharedCacheTableLock()).
  40219. */
  40220. rc = querySharedCacheTableLock(p, 1, READ_LOCK);
  40221. if( rc!=SQLITE_OK ){
  40222. sqlite3BtreeLeave(p);
  40223. return rc;
  40224. }
  40225. assert( idx>=0 && idx<=15 );
  40226. if( pBt->pPage1 ){
  40227. /* The b-tree is already holding a reference to page 1 of the database
  40228. ** file. In this case the required meta-data value can be read directly
  40229. ** from the page data of this reference. This is slightly faster than
  40230. ** requesting a new reference from the pager layer.
  40231. */
  40232. pP1 = (unsigned char *)pBt->pPage1->aData;
  40233. }else{
  40234. /* The b-tree does not have a reference to page 1 of the database file.
  40235. ** Obtain one from the pager layer.
  40236. */
  40237. rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
  40238. if( rc ){
  40239. sqlite3BtreeLeave(p);
  40240. return rc;
  40241. }
  40242. pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
  40243. }
  40244. *pMeta = get4byte(&pP1[36 + idx*4]);
  40245. /* If the b-tree is not holding a reference to page 1, then one was
  40246. ** requested from the pager layer in the above block. Release it now.
  40247. */
  40248. if( !pBt->pPage1 ){
  40249. sqlite3PagerUnref(pDbPage);
  40250. }
  40251. /* If autovacuumed is disabled in this build but we are trying to
  40252. ** access an autovacuumed database, then make the database readonly.
  40253. */
  40254. #ifdef SQLITE_OMIT_AUTOVACUUM
  40255. if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
  40256. #endif
  40257. /* If there is currently an open transaction, grab a read-lock
  40258. ** on page 1 of the database file. This is done to make sure that
  40259. ** no other connection can modify the meta value just read from
  40260. ** the database until the transaction is concluded.
  40261. */
  40262. if( p->inTrans>0 ){
  40263. rc = setSharedCacheTableLock(p, 1, READ_LOCK);
  40264. }
  40265. sqlite3BtreeLeave(p);
  40266. return rc;
  40267. }
  40268. /*
  40269. ** Write meta-information back into the database. Meta[0] is
  40270. ** read-only and may not be written.
  40271. */
  40272. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  40273. BtShared *pBt = p->pBt;
  40274. unsigned char *pP1;
  40275. int rc;
  40276. assert( idx>=1 && idx<=15 );
  40277. sqlite3BtreeEnter(p);
  40278. assert( p->inTrans==TRANS_WRITE );
  40279. assert( pBt->pPage1!=0 );
  40280. pP1 = pBt->pPage1->aData;
  40281. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  40282. if( rc==SQLITE_OK ){
  40283. put4byte(&pP1[36 + idx*4], iMeta);
  40284. #ifndef SQLITE_OMIT_AUTOVACUUM
  40285. if( idx==7 ){
  40286. assert( pBt->autoVacuum || iMeta==0 );
  40287. assert( iMeta==0 || iMeta==1 );
  40288. pBt->incrVacuum = (u8)iMeta;
  40289. }
  40290. #endif
  40291. }
  40292. sqlite3BtreeLeave(p);
  40293. return rc;
  40294. }
  40295. /*
  40296. ** Return the flag byte at the beginning of the page that the cursor
  40297. ** is currently pointing to.
  40298. */
  40299. SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
  40300. /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
  40301. ** restoreCursorPosition() here.
  40302. */
  40303. MemPage *pPage;
  40304. restoreCursorPosition(pCur);
  40305. pPage = pCur->apPage[pCur->iPage];
  40306. assert( cursorHoldsMutex(pCur) );
  40307. assert( pPage!=0 );
  40308. assert( pPage->pBt==pCur->pBt );
  40309. return pPage->aData[pPage->hdrOffset];
  40310. }
  40311. #ifndef SQLITE_OMIT_BTREECOUNT
  40312. /*
  40313. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  40314. ** number of entries in the b-tree and write the result to *pnEntry.
  40315. **
  40316. ** SQLITE_OK is returned if the operation is successfully executed.
  40317. ** Otherwise, if an error is encountered (i.e. an IO error or database
  40318. ** corruption) an SQLite error code is returned.
  40319. */
  40320. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  40321. i64 nEntry = 0; /* Value to return in *pnEntry */
  40322. int rc; /* Return code */
  40323. rc = moveToRoot(pCur);
  40324. /* Unless an error occurs, the following loop runs one iteration for each
  40325. ** page in the B-Tree structure (not including overflow pages).
  40326. */
  40327. while( rc==SQLITE_OK ){
  40328. int iIdx; /* Index of child node in parent */
  40329. MemPage *pPage; /* Current page of the b-tree */
  40330. /* If this is a leaf page or the tree is not an int-key tree, then
  40331. ** this page contains countable entries. Increment the entry counter
  40332. ** accordingly.
  40333. */
  40334. pPage = pCur->apPage[pCur->iPage];
  40335. if( pPage->leaf || !pPage->intKey ){
  40336. nEntry += pPage->nCell;
  40337. }
  40338. /* pPage is a leaf node. This loop navigates the cursor so that it
  40339. ** points to the first interior cell that it points to the parent of
  40340. ** the next page in the tree that has not yet been visited. The
  40341. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  40342. ** of the page, or to the number of cells in the page if the next page
  40343. ** to visit is the right-child of its parent.
  40344. **
  40345. ** If all pages in the tree have been visited, return SQLITE_OK to the
  40346. ** caller.
  40347. */
  40348. if( pPage->leaf ){
  40349. do {
  40350. if( pCur->iPage==0 ){
  40351. /* All pages of the b-tree have been visited. Return successfully. */
  40352. *pnEntry = nEntry;
  40353. return SQLITE_OK;
  40354. }
  40355. sqlite3BtreeMoveToParent(pCur);
  40356. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  40357. pCur->aiIdx[pCur->iPage]++;
  40358. pPage = pCur->apPage[pCur->iPage];
  40359. }
  40360. /* Descend to the child node of the cell that the cursor currently
  40361. ** points at. This is the right-child if (iIdx==pPage->nCell).
  40362. */
  40363. iIdx = pCur->aiIdx[pCur->iPage];
  40364. if( iIdx==pPage->nCell ){
  40365. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  40366. }else{
  40367. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  40368. }
  40369. }
  40370. /* An error has occurred. Return an error code. */
  40371. return rc;
  40372. }
  40373. #endif
  40374. /*
  40375. ** Return the pager associated with a BTree. This routine is used for
  40376. ** testing and debugging only.
  40377. */
  40378. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  40379. return p->pBt->pPager;
  40380. }
  40381. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40382. /*
  40383. ** Append a message to the error message string.
  40384. */
  40385. static void checkAppendMsg(
  40386. IntegrityCk *pCheck,
  40387. char *zMsg1,
  40388. const char *zFormat,
  40389. ...
  40390. ){
  40391. va_list ap;
  40392. if( !pCheck->mxErr ) return;
  40393. pCheck->mxErr--;
  40394. pCheck->nErr++;
  40395. va_start(ap, zFormat);
  40396. if( pCheck->errMsg.nChar ){
  40397. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  40398. }
  40399. if( zMsg1 ){
  40400. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  40401. }
  40402. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  40403. va_end(ap);
  40404. if( pCheck->errMsg.mallocFailed ){
  40405. pCheck->mallocFailed = 1;
  40406. }
  40407. }
  40408. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40409. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40410. /*
  40411. ** Add 1 to the reference count for page iPage. If this is the second
  40412. ** reference to the page, add an error message to pCheck->zErrMsg.
  40413. ** Return 1 if there are 2 ore more references to the page and 0 if
  40414. ** if this is the first reference to the page.
  40415. **
  40416. ** Also check that the page number is in bounds.
  40417. */
  40418. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  40419. if( iPage==0 ) return 1;
  40420. if( iPage>pCheck->nPage ){
  40421. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  40422. return 1;
  40423. }
  40424. if( pCheck->anRef[iPage]==1 ){
  40425. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  40426. return 1;
  40427. }
  40428. return (pCheck->anRef[iPage]++)>1;
  40429. }
  40430. #ifndef SQLITE_OMIT_AUTOVACUUM
  40431. /*
  40432. ** Check that the entry in the pointer-map for page iChild maps to
  40433. ** page iParent, pointer type ptrType. If not, append an error message
  40434. ** to pCheck.
  40435. */
  40436. static void checkPtrmap(
  40437. IntegrityCk *pCheck, /* Integrity check context */
  40438. Pgno iChild, /* Child page number */
  40439. u8 eType, /* Expected pointer map type */
  40440. Pgno iParent, /* Expected pointer map parent page number */
  40441. char *zContext /* Context description (used for error msg) */
  40442. ){
  40443. int rc;
  40444. u8 ePtrmapType;
  40445. Pgno iPtrmapParent;
  40446. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  40447. if( rc!=SQLITE_OK ){
  40448. if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
  40449. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  40450. return;
  40451. }
  40452. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  40453. checkAppendMsg(pCheck, zContext,
  40454. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  40455. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  40456. }
  40457. }
  40458. #endif
  40459. /*
  40460. ** Check the integrity of the freelist or of an overflow page list.
  40461. ** Verify that the number of pages on the list is N.
  40462. */
  40463. static void checkList(
  40464. IntegrityCk *pCheck, /* Integrity checking context */
  40465. int isFreeList, /* True for a freelist. False for overflow page list */
  40466. int iPage, /* Page number for first page in the list */
  40467. int N, /* Expected number of pages in the list */
  40468. char *zContext /* Context for error messages */
  40469. ){
  40470. int i;
  40471. int expected = N;
  40472. int iFirst = iPage;
  40473. while( N-- > 0 && pCheck->mxErr ){
  40474. DbPage *pOvflPage;
  40475. unsigned char *pOvflData;
  40476. if( iPage<1 ){
  40477. checkAppendMsg(pCheck, zContext,
  40478. "%d of %d pages missing from overflow list starting at %d",
  40479. N+1, expected, iFirst);
  40480. break;
  40481. }
  40482. if( checkRef(pCheck, iPage, zContext) ) break;
  40483. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  40484. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  40485. break;
  40486. }
  40487. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  40488. if( isFreeList ){
  40489. int n = get4byte(&pOvflData[4]);
  40490. #ifndef SQLITE_OMIT_AUTOVACUUM
  40491. if( pCheck->pBt->autoVacuum ){
  40492. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  40493. }
  40494. #endif
  40495. if( n>pCheck->pBt->usableSize/4-2 ){
  40496. checkAppendMsg(pCheck, zContext,
  40497. "freelist leaf count too big on page %d", iPage);
  40498. N--;
  40499. }else{
  40500. for(i=0; i<n; i++){
  40501. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  40502. #ifndef SQLITE_OMIT_AUTOVACUUM
  40503. if( pCheck->pBt->autoVacuum ){
  40504. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  40505. }
  40506. #endif
  40507. checkRef(pCheck, iFreePage, zContext);
  40508. }
  40509. N -= n;
  40510. }
  40511. }
  40512. #ifndef SQLITE_OMIT_AUTOVACUUM
  40513. else{
  40514. /* If this database supports auto-vacuum and iPage is not the last
  40515. ** page in this overflow list, check that the pointer-map entry for
  40516. ** the following page matches iPage.
  40517. */
  40518. if( pCheck->pBt->autoVacuum && N>0 ){
  40519. i = get4byte(pOvflData);
  40520. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  40521. }
  40522. }
  40523. #endif
  40524. iPage = get4byte(pOvflData);
  40525. sqlite3PagerUnref(pOvflPage);
  40526. }
  40527. }
  40528. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40529. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40530. /*
  40531. ** Do various sanity checks on a single page of a tree. Return
  40532. ** the tree depth. Root pages return 0. Parents of root pages
  40533. ** return 1, and so forth.
  40534. **
  40535. ** These checks are done:
  40536. **
  40537. ** 1. Make sure that cells and freeblocks do not overlap
  40538. ** but combine to completely cover the page.
  40539. ** NO 2. Make sure cell keys are in order.
  40540. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  40541. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  40542. ** 5. Check the integrity of overflow pages.
  40543. ** 6. Recursively call checkTreePage on all children.
  40544. ** 7. Verify that the depth of all children is the same.
  40545. ** 8. Make sure this page is at least 33% full or else it is
  40546. ** the root of the tree.
  40547. */
  40548. static int checkTreePage(
  40549. IntegrityCk *pCheck, /* Context for the sanity check */
  40550. int iPage, /* Page number of the page to check */
  40551. char *zParentContext /* Parent context */
  40552. ){
  40553. MemPage *pPage;
  40554. int i, rc, depth, d2, pgno, cnt;
  40555. int hdr, cellStart;
  40556. int nCell;
  40557. u8 *data;
  40558. BtShared *pBt;
  40559. int usableSize;
  40560. char zContext[100];
  40561. char *hit = 0;
  40562. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  40563. /* Check that the page exists
  40564. */
  40565. pBt = pCheck->pBt;
  40566. usableSize = pBt->usableSize;
  40567. if( iPage==0 ) return 0;
  40568. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  40569. if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  40570. if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
  40571. checkAppendMsg(pCheck, zContext,
  40572. "unable to get the page. error code=%d", rc);
  40573. return 0;
  40574. }
  40575. if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
  40576. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  40577. checkAppendMsg(pCheck, zContext,
  40578. "sqlite3BtreeInitPage() returns error code %d", rc);
  40579. releasePage(pPage);
  40580. return 0;
  40581. }
  40582. /* Check out all the cells.
  40583. */
  40584. depth = 0;
  40585. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  40586. u8 *pCell;
  40587. u32 sz;
  40588. CellInfo info;
  40589. /* Check payload overflow pages
  40590. */
  40591. sqlite3_snprintf(sizeof(zContext), zContext,
  40592. "On tree page %d cell %d: ", iPage, i);
  40593. pCell = findCell(pPage,i);
  40594. sqlite3BtreeParseCellPtr(pPage, pCell, &info);
  40595. sz = info.nData;
  40596. if( !pPage->intKey ) sz += (int)info.nKey;
  40597. assert( sz==info.nPayload );
  40598. if( (sz>info.nLocal)
  40599. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  40600. ){
  40601. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  40602. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  40603. #ifndef SQLITE_OMIT_AUTOVACUUM
  40604. if( pBt->autoVacuum ){
  40605. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  40606. }
  40607. #endif
  40608. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  40609. }
  40610. /* Check sanity of left child page.
  40611. */
  40612. if( !pPage->leaf ){
  40613. pgno = get4byte(pCell);
  40614. #ifndef SQLITE_OMIT_AUTOVACUUM
  40615. if( pBt->autoVacuum ){
  40616. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  40617. }
  40618. #endif
  40619. d2 = checkTreePage(pCheck, pgno, zContext);
  40620. if( i>0 && d2!=depth ){
  40621. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  40622. }
  40623. depth = d2;
  40624. }
  40625. }
  40626. if( !pPage->leaf ){
  40627. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  40628. sqlite3_snprintf(sizeof(zContext), zContext,
  40629. "On page %d at right child: ", iPage);
  40630. #ifndef SQLITE_OMIT_AUTOVACUUM
  40631. if( pBt->autoVacuum ){
  40632. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
  40633. }
  40634. #endif
  40635. checkTreePage(pCheck, pgno, zContext);
  40636. }
  40637. /* Check for complete coverage of the page
  40638. */
  40639. data = pPage->aData;
  40640. hdr = pPage->hdrOffset;
  40641. hit = sqlite3PageMalloc( pBt->pageSize );
  40642. if( hit==0 ){
  40643. pCheck->mallocFailed = 1;
  40644. }else{
  40645. u16 contentOffset = get2byte(&data[hdr+5]);
  40646. if (contentOffset > usableSize) {
  40647. checkAppendMsg(pCheck, 0,
  40648. "Corruption detected in header on page %d",iPage,0);
  40649. goto check_page_abort;
  40650. }
  40651. memset(hit+contentOffset, 0, usableSize-contentOffset);
  40652. memset(hit, 1, contentOffset);
  40653. nCell = get2byte(&data[hdr+3]);
  40654. cellStart = hdr + 12 - 4*pPage->leaf;
  40655. for(i=0; i<nCell; i++){
  40656. int pc = get2byte(&data[cellStart+i*2]);
  40657. u16 size = 1024;
  40658. int j;
  40659. if( pc<=usableSize ){
  40660. size = cellSizePtr(pPage, &data[pc]);
  40661. }
  40662. if( (pc+size-1)>=usableSize || pc<0 ){
  40663. checkAppendMsg(pCheck, 0,
  40664. "Corruption detected in cell %d on page %d",i,iPage,0);
  40665. }else{
  40666. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  40667. }
  40668. }
  40669. for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
  40670. cnt++){
  40671. int size = get2byte(&data[i+2]);
  40672. int j;
  40673. if( (i+size-1)>=usableSize || i<0 ){
  40674. checkAppendMsg(pCheck, 0,
  40675. "Corruption detected in cell %d on page %d",i,iPage,0);
  40676. }else{
  40677. for(j=i+size-1; j>=i; j--) hit[j]++;
  40678. }
  40679. i = get2byte(&data[i]);
  40680. }
  40681. for(i=cnt=0; i<usableSize; i++){
  40682. if( hit[i]==0 ){
  40683. cnt++;
  40684. }else if( hit[i]>1 ){
  40685. checkAppendMsg(pCheck, 0,
  40686. "Multiple uses for byte %d of page %d", i, iPage);
  40687. break;
  40688. }
  40689. }
  40690. if( cnt!=data[hdr+7] ){
  40691. checkAppendMsg(pCheck, 0,
  40692. "Fragmented space is %d byte reported as %d on page %d",
  40693. cnt, data[hdr+7], iPage);
  40694. }
  40695. }
  40696. check_page_abort:
  40697. if (hit) sqlite3PageFree(hit);
  40698. releasePage(pPage);
  40699. return depth+1;
  40700. }
  40701. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40702. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  40703. /*
  40704. ** This routine does a complete check of the given BTree file. aRoot[] is
  40705. ** an array of pages numbers were each page number is the root page of
  40706. ** a table. nRoot is the number of entries in aRoot.
  40707. **
  40708. ** Write the number of error seen in *pnErr. Except for some memory
  40709. ** allocation errors, an error message held in memory obtained from
  40710. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  40711. ** returned. If a memory allocation error occurs, NULL is returned.
  40712. */
  40713. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  40714. Btree *p, /* The btree to be checked */
  40715. int *aRoot, /* An array of root pages numbers for individual trees */
  40716. int nRoot, /* Number of entries in aRoot[] */
  40717. int mxErr, /* Stop reporting errors after this many */
  40718. int *pnErr /* Write number of errors seen to this variable */
  40719. ){
  40720. Pgno i;
  40721. int nRef;
  40722. IntegrityCk sCheck;
  40723. BtShared *pBt = p->pBt;
  40724. char zErr[100];
  40725. sqlite3BtreeEnter(p);
  40726. nRef = sqlite3PagerRefcount(pBt->pPager);
  40727. if( lockBtreeWithRetry(p)!=SQLITE_OK ){
  40728. *pnErr = 1;
  40729. sqlite3BtreeLeave(p);
  40730. return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
  40731. }
  40732. sCheck.pBt = pBt;
  40733. sCheck.pPager = pBt->pPager;
  40734. sCheck.nPage = pagerPagecount(sCheck.pBt);
  40735. sCheck.mxErr = mxErr;
  40736. sCheck.nErr = 0;
  40737. sCheck.mallocFailed = 0;
  40738. *pnErr = 0;
  40739. if( sCheck.nPage==0 ){
  40740. unlockBtreeIfUnused(pBt);
  40741. sqlite3BtreeLeave(p);
  40742. return 0;
  40743. }
  40744. sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
  40745. if( !sCheck.anRef ){
  40746. unlockBtreeIfUnused(pBt);
  40747. *pnErr = 1;
  40748. sqlite3BtreeLeave(p);
  40749. return 0;
  40750. }
  40751. for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
  40752. i = PENDING_BYTE_PAGE(pBt);
  40753. if( i<=sCheck.nPage ){
  40754. sCheck.anRef[i] = 1;
  40755. }
  40756. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
  40757. /* Check the integrity of the freelist
  40758. */
  40759. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  40760. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  40761. /* Check all the tables.
  40762. */
  40763. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  40764. if( aRoot[i]==0 ) continue;
  40765. #ifndef SQLITE_OMIT_AUTOVACUUM
  40766. if( pBt->autoVacuum && aRoot[i]>1 ){
  40767. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  40768. }
  40769. #endif
  40770. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
  40771. }
  40772. /* Make sure every page in the file is referenced
  40773. */
  40774. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  40775. #ifdef SQLITE_OMIT_AUTOVACUUM
  40776. if( sCheck.anRef[i]==0 ){
  40777. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  40778. }
  40779. #else
  40780. /* If the database supports auto-vacuum, make sure no tables contain
  40781. ** references to pointer-map pages.
  40782. */
  40783. if( sCheck.anRef[i]==0 &&
  40784. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  40785. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  40786. }
  40787. if( sCheck.anRef[i]!=0 &&
  40788. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  40789. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  40790. }
  40791. #endif
  40792. }
  40793. /* Make sure this analysis did not leave any unref() pages.
  40794. ** This is an internal consistency check; an integrity check
  40795. ** of the integrity check.
  40796. */
  40797. unlockBtreeIfUnused(pBt);
  40798. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  40799. checkAppendMsg(&sCheck, 0,
  40800. "Outstanding page count goes from %d to %d during this analysis",
  40801. nRef, sqlite3PagerRefcount(pBt->pPager)
  40802. );
  40803. }
  40804. /* Clean up and report errors.
  40805. */
  40806. sqlite3BtreeLeave(p);
  40807. sqlite3_free(sCheck.anRef);
  40808. if( sCheck.mallocFailed ){
  40809. sqlite3StrAccumReset(&sCheck.errMsg);
  40810. *pnErr = sCheck.nErr+1;
  40811. return 0;
  40812. }
  40813. *pnErr = sCheck.nErr;
  40814. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  40815. return sqlite3StrAccumFinish(&sCheck.errMsg);
  40816. }
  40817. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  40818. /*
  40819. ** Return the full pathname of the underlying database file.
  40820. **
  40821. ** The pager filename is invariant as long as the pager is
  40822. ** open so it is safe to access without the BtShared mutex.
  40823. */
  40824. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  40825. assert( p->pBt->pPager!=0 );
  40826. return sqlite3PagerFilename(p->pBt->pPager);
  40827. }
  40828. /*
  40829. ** Return the pathname of the journal file for this database. The return
  40830. ** value of this routine is the same regardless of whether the journal file
  40831. ** has been created or not.
  40832. **
  40833. ** The pager journal filename is invariant as long as the pager is
  40834. ** open so it is safe to access without the BtShared mutex.
  40835. */
  40836. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  40837. assert( p->pBt->pPager!=0 );
  40838. return sqlite3PagerJournalname(p->pBt->pPager);
  40839. }
  40840. /*
  40841. ** Return non-zero if a transaction is active.
  40842. */
  40843. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  40844. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  40845. return (p && (p->inTrans==TRANS_WRITE));
  40846. }
  40847. /*
  40848. ** Return non-zero if a read (or write) transaction is active.
  40849. */
  40850. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  40851. assert( p );
  40852. assert( sqlite3_mutex_held(p->db->mutex) );
  40853. return p->inTrans!=TRANS_NONE;
  40854. }
  40855. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  40856. assert( p );
  40857. assert( sqlite3_mutex_held(p->db->mutex) );
  40858. return p->nBackup!=0;
  40859. }
  40860. /*
  40861. ** This function returns a pointer to a blob of memory associated with
  40862. ** a single shared-btree. The memory is used by client code for its own
  40863. ** purposes (for example, to store a high-level schema associated with
  40864. ** the shared-btree). The btree layer manages reference counting issues.
  40865. **
  40866. ** The first time this is called on a shared-btree, nBytes bytes of memory
  40867. ** are allocated, zeroed, and returned to the caller. For each subsequent
  40868. ** call the nBytes parameter is ignored and a pointer to the same blob
  40869. ** of memory returned.
  40870. **
  40871. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  40872. ** allocated, a null pointer is returned. If the blob has already been
  40873. ** allocated, it is returned as normal.
  40874. **
  40875. ** Just before the shared-btree is closed, the function passed as the
  40876. ** xFree argument when the memory allocation was made is invoked on the
  40877. ** blob of allocated memory. This function should not call sqlite3_free()
  40878. ** on the memory, the btree layer does that.
  40879. */
  40880. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  40881. BtShared *pBt = p->pBt;
  40882. sqlite3BtreeEnter(p);
  40883. if( !pBt->pSchema && nBytes ){
  40884. pBt->pSchema = sqlite3MallocZero(nBytes);
  40885. pBt->xFreeSchema = xFree;
  40886. }
  40887. sqlite3BtreeLeave(p);
  40888. return pBt->pSchema;
  40889. }
  40890. /*
  40891. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  40892. ** btree as the argument handle holds an exclusive lock on the
  40893. ** sqlite_master table. Otherwise SQLITE_OK.
  40894. */
  40895. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  40896. int rc;
  40897. assert( sqlite3_mutex_held(p->db->mutex) );
  40898. sqlite3BtreeEnter(p);
  40899. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  40900. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  40901. sqlite3BtreeLeave(p);
  40902. return rc;
  40903. }
  40904. #ifndef SQLITE_OMIT_SHARED_CACHE
  40905. /*
  40906. ** Obtain a lock on the table whose root page is iTab. The
  40907. ** lock is a write lock if isWritelock is true or a read lock
  40908. ** if it is false.
  40909. */
  40910. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  40911. int rc = SQLITE_OK;
  40912. if( p->sharable ){
  40913. u8 lockType = READ_LOCK + isWriteLock;
  40914. assert( READ_LOCK+1==WRITE_LOCK );
  40915. assert( isWriteLock==0 || isWriteLock==1 );
  40916. sqlite3BtreeEnter(p);
  40917. rc = querySharedCacheTableLock(p, iTab, lockType);
  40918. if( rc==SQLITE_OK ){
  40919. rc = setSharedCacheTableLock(p, iTab, lockType);
  40920. }
  40921. sqlite3BtreeLeave(p);
  40922. }
  40923. return rc;
  40924. }
  40925. #endif
  40926. #ifndef SQLITE_OMIT_INCRBLOB
  40927. /*
  40928. ** Argument pCsr must be a cursor opened for writing on an
  40929. ** INTKEY table currently pointing at a valid table entry.
  40930. ** This function modifies the data stored as part of that entry.
  40931. ** Only the data content may only be modified, it is not possible
  40932. ** to change the length of the data stored.
  40933. */
  40934. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  40935. int rc;
  40936. assert( cursorHoldsMutex(pCsr) );
  40937. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  40938. assert(pCsr->isIncrblobHandle);
  40939. restoreCursorPosition(pCsr);
  40940. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  40941. if( pCsr->eState!=CURSOR_VALID ){
  40942. return SQLITE_ABORT;
  40943. }
  40944. /* Check some preconditions:
  40945. ** (a) the cursor is open for writing,
  40946. ** (b) there is no read-lock on the table being modified and
  40947. ** (c) the cursor points at a valid row of an intKey table.
  40948. */
  40949. if( !pCsr->wrFlag ){
  40950. return SQLITE_READONLY;
  40951. }
  40952. assert( !pCsr->pBt->readOnly
  40953. && pCsr->pBt->inTransaction==TRANS_WRITE );
  40954. rc = checkForReadConflicts(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0);
  40955. if( rc!=SQLITE_OK ){
  40956. /* The table pCur points to has a read lock */
  40957. assert( rc==SQLITE_LOCKED_SHAREDCACHE );
  40958. return rc;
  40959. }
  40960. if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
  40961. return SQLITE_ERROR;
  40962. }
  40963. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
  40964. }
  40965. /*
  40966. ** Set a flag on this cursor to cache the locations of pages from the
  40967. ** overflow list for the current row. This is used by cursors opened
  40968. ** for incremental blob IO only.
  40969. **
  40970. ** This function sets a flag only. The actual page location cache
  40971. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  40972. ** accessPayload() (the worker function for sqlite3BtreeData() and
  40973. ** sqlite3BtreePutData()).
  40974. */
  40975. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  40976. assert( cursorHoldsMutex(pCur) );
  40977. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  40978. assert(!pCur->isIncrblobHandle);
  40979. assert(!pCur->aOverflow);
  40980. pCur->isIncrblobHandle = 1;
  40981. }
  40982. #endif
  40983. /************** End of btree.c ***********************************************/
  40984. /************** Begin file backup.c ******************************************/
  40985. /*
  40986. ** 2009 January 28
  40987. **
  40988. ** The author disclaims copyright to this source code. In place of
  40989. ** a legal notice, here is a blessing:
  40990. **
  40991. ** May you do good and not evil.
  40992. ** May you find forgiveness for yourself and forgive others.
  40993. ** May you share freely, never taking more than you give.
  40994. **
  40995. *************************************************************************
  40996. ** This file contains the implementation of the sqlite3_backup_XXX()
  40997. ** API functions and the related features.
  40998. **
  40999. ** $Id: backup.c,v 1.13 2009/03/16 13:19:36 danielk1977 Exp $
  41000. */
  41001. /* Macro to find the minimum of two numeric values.
  41002. */
  41003. #ifndef MIN
  41004. # define MIN(x,y) ((x)<(y)?(x):(y))
  41005. #endif
  41006. /*
  41007. ** Structure allocated for each backup operation.
  41008. */
  41009. struct sqlite3_backup {
  41010. sqlite3* pDestDb; /* Destination database handle */
  41011. Btree *pDest; /* Destination b-tree file */
  41012. u32 iDestSchema; /* Original schema cookie in destination */
  41013. int bDestLocked; /* True once a write-transaction is open on pDest */
  41014. Pgno iNext; /* Page number of the next source page to copy */
  41015. sqlite3* pSrcDb; /* Source database handle */
  41016. Btree *pSrc; /* Source b-tree file */
  41017. int rc; /* Backup process error code */
  41018. /* These two variables are set by every call to backup_step(). They are
  41019. ** read by calls to backup_remaining() and backup_pagecount().
  41020. */
  41021. Pgno nRemaining; /* Number of pages left to copy */
  41022. Pgno nPagecount; /* Total number of pages to copy */
  41023. sqlite3_backup *pNext; /* Next backup associated with source pager */
  41024. };
  41025. /*
  41026. ** THREAD SAFETY NOTES:
  41027. **
  41028. ** Once it has been created using backup_init(), a single sqlite3_backup
  41029. ** structure may be accessed via two groups of thread-safe entry points:
  41030. **
  41031. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  41032. ** backup_finish(). Both these functions obtain the source database
  41033. ** handle mutex and the mutex associated with the source BtShared
  41034. ** structure, in that order.
  41035. **
  41036. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  41037. ** invoked by the pager layer to report various state changes in
  41038. ** the page cache associated with the source database. The mutex
  41039. ** associated with the source database BtShared structure will always
  41040. ** be held when either of these functions are invoked.
  41041. **
  41042. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  41043. ** backup_pagecount() are not thread-safe functions. If they are called
  41044. ** while some other thread is calling backup_step() or backup_finish(),
  41045. ** the values returned may be invalid. There is no way for a call to
  41046. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  41047. ** or backup_pagecount().
  41048. **
  41049. ** Depending on the SQLite configuration, the database handles and/or
  41050. ** the Btree objects may have their own mutexes that require locking.
  41051. ** Non-sharable Btrees (in-memory databases for example), do not have
  41052. ** associated mutexes.
  41053. */
  41054. /*
  41055. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  41056. ** in connection handle pDb. If such a database cannot be found, return
  41057. ** a NULL pointer and write an error message to pErrorDb.
  41058. **
  41059. ** If the "temp" database is requested, it may need to be opened by this
  41060. ** function. If an error occurs while doing so, return 0 and write an
  41061. ** error message to pErrorDb.
  41062. */
  41063. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  41064. int i = sqlite3FindDbName(pDb, zDb);
  41065. if( i==1 ){
  41066. Parse sParse;
  41067. memset(&sParse, 0, sizeof(sParse));
  41068. sParse.db = pDb;
  41069. if( sqlite3OpenTempDatabase(&sParse) ){
  41070. sqlite3ErrorClear(&sParse);
  41071. sqlite3Error(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  41072. return 0;
  41073. }
  41074. assert( sParse.zErrMsg==0 );
  41075. }
  41076. if( i<0 ){
  41077. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  41078. return 0;
  41079. }
  41080. return pDb->aDb[i].pBt;
  41081. }
  41082. /*
  41083. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  41084. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  41085. ** a pointer to the new sqlite3_backup object.
  41086. **
  41087. ** If an error occurs, NULL is returned and an error code and error message
  41088. ** stored in database handle pDestDb.
  41089. */
  41090. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  41091. sqlite3* pDestDb, /* Database to write to */
  41092. const char *zDestDb, /* Name of database within pDestDb */
  41093. sqlite3* pSrcDb, /* Database connection to read from */
  41094. const char *zSrcDb /* Name of database within pSrcDb */
  41095. ){
  41096. sqlite3_backup *p; /* Value to return */
  41097. /* Lock the source database handle. The destination database
  41098. ** handle is not locked in this routine, but it is locked in
  41099. ** sqlite3_backup_step(). The user is required to ensure that no
  41100. ** other thread accesses the destination handle for the duration
  41101. ** of the backup operation. Any attempt to use the destination
  41102. ** database connection while a backup is in progress may cause
  41103. ** a malfunction or a deadlock.
  41104. */
  41105. sqlite3_mutex_enter(pSrcDb->mutex);
  41106. sqlite3_mutex_enter(pDestDb->mutex);
  41107. if( pSrcDb==pDestDb ){
  41108. sqlite3Error(
  41109. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  41110. );
  41111. p = 0;
  41112. }else {
  41113. /* Allocate space for a new sqlite3_backup object */
  41114. p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
  41115. if( !p ){
  41116. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  41117. }
  41118. }
  41119. /* If the allocation succeeded, populate the new object. */
  41120. if( p ){
  41121. memset(p, 0, sizeof(sqlite3_backup));
  41122. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  41123. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  41124. p->pDestDb = pDestDb;
  41125. p->pSrcDb = pSrcDb;
  41126. p->iNext = 1;
  41127. if( 0==p->pSrc || 0==p->pDest ){
  41128. /* One (or both) of the named databases did not exist. An error has
  41129. ** already been written into the pDestDb handle. All that is left
  41130. ** to do here is free the sqlite3_backup structure.
  41131. */
  41132. sqlite3_free(p);
  41133. p = 0;
  41134. }
  41135. }
  41136. /* If everything has gone as planned, attach the backup object to the
  41137. ** source pager. The source pager calls BackupUpdate() and BackupRestart()
  41138. ** to notify this module if the source file is modified mid-backup.
  41139. */
  41140. if( p ){
  41141. sqlite3_backup **pp; /* Pointer to head of pagers backup list */
  41142. sqlite3BtreeEnter(p->pSrc);
  41143. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  41144. p->pNext = *pp;
  41145. *pp = p;
  41146. sqlite3BtreeLeave(p->pSrc);
  41147. p->pSrc->nBackup++;
  41148. }
  41149. sqlite3_mutex_leave(pDestDb->mutex);
  41150. sqlite3_mutex_leave(pSrcDb->mutex);
  41151. return p;
  41152. }
  41153. /*
  41154. ** Argument rc is an SQLite error code. Return true if this error is
  41155. ** considered fatal if encountered during a backup operation. All errors
  41156. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  41157. */
  41158. static int isFatalError(int rc){
  41159. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED);
  41160. }
  41161. /*
  41162. ** Parameter zSrcData points to a buffer containing the data for
  41163. ** page iSrcPg from the source database. Copy this data into the
  41164. ** destination database.
  41165. */
  41166. static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
  41167. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  41168. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  41169. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  41170. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  41171. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  41172. int rc = SQLITE_OK;
  41173. i64 iOff;
  41174. assert( p->bDestLocked );
  41175. assert( !isFatalError(p->rc) );
  41176. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  41177. assert( zSrcData );
  41178. /* Catch the case where the destination is an in-memory database and the
  41179. ** page sizes of the source and destination differ.
  41180. */
  41181. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
  41182. rc = SQLITE_READONLY;
  41183. }
  41184. /* This loop runs once for each destination page spanned by the source
  41185. ** page. For each iteration, variable iOff is set to the byte offset
  41186. ** of the destination page.
  41187. */
  41188. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  41189. DbPage *pDestPg = 0;
  41190. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  41191. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  41192. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  41193. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  41194. ){
  41195. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  41196. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  41197. u8 *zOut = &zDestData[iOff%nDestPgsz];
  41198. /* Copy the data from the source page into the destination page.
  41199. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  41200. ** and the pager code use this trick (clearing the first byte
  41201. ** of the page 'extra' space to invalidate the Btree layers
  41202. ** cached parse of the page). MemPage.isInit is marked
  41203. ** "MUST BE FIRST" for this purpose.
  41204. */
  41205. memcpy(zOut, zIn, nCopy);
  41206. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  41207. }
  41208. sqlite3PagerUnref(pDestPg);
  41209. }
  41210. return rc;
  41211. }
  41212. /*
  41213. ** If pFile is currently larger than iSize bytes, then truncate it to
  41214. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  41215. ** this function is a no-op.
  41216. **
  41217. ** Return SQLITE_OK if everything is successful, or an SQLite error
  41218. ** code if an error occurs.
  41219. */
  41220. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  41221. i64 iCurrent;
  41222. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  41223. if( rc==SQLITE_OK && iCurrent>iSize ){
  41224. rc = sqlite3OsTruncate(pFile, iSize);
  41225. }
  41226. return rc;
  41227. }
  41228. /*
  41229. ** Copy nPage pages from the source b-tree to the destination.
  41230. */
  41231. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  41232. int rc;
  41233. sqlite3_mutex_enter(p->pSrcDb->mutex);
  41234. sqlite3BtreeEnter(p->pSrc);
  41235. if( p->pDestDb ){
  41236. sqlite3_mutex_enter(p->pDestDb->mutex);
  41237. }
  41238. rc = p->rc;
  41239. if( !isFatalError(rc) ){
  41240. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  41241. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  41242. int ii; /* Iterator variable */
  41243. int nSrcPage = -1; /* Size of source db in pages */
  41244. int bCloseTrans = 0; /* True if src db requires unlocking */
  41245. /* If the source pager is currently in a write-transaction, return
  41246. ** SQLITE_BUSY immediately.
  41247. */
  41248. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  41249. rc = SQLITE_BUSY;
  41250. }else{
  41251. rc = SQLITE_OK;
  41252. }
  41253. /* Lock the destination database, if it is not locked already. */
  41254. if( SQLITE_OK==rc && p->bDestLocked==0
  41255. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  41256. ){
  41257. p->bDestLocked = 1;
  41258. rc = sqlite3BtreeGetMeta(p->pDest, 1, &p->iDestSchema);
  41259. }
  41260. /* If there is no open read-transaction on the source database, open
  41261. ** one now. If a transaction is opened here, then it will be closed
  41262. ** before this function exits.
  41263. */
  41264. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  41265. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  41266. bCloseTrans = 1;
  41267. }
  41268. /* Now that there is a read-lock on the source database, query the
  41269. ** source pager for the number of pages in the database.
  41270. */
  41271. if( rc==SQLITE_OK ){
  41272. rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
  41273. }
  41274. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  41275. const Pgno iSrcPg = p->iNext; /* Source page number */
  41276. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  41277. DbPage *pSrcPg; /* Source page object */
  41278. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  41279. if( rc==SQLITE_OK ){
  41280. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
  41281. sqlite3PagerUnref(pSrcPg);
  41282. }
  41283. }
  41284. p->iNext++;
  41285. }
  41286. if( rc==SQLITE_OK ){
  41287. p->nPagecount = nSrcPage;
  41288. p->nRemaining = nSrcPage+1-p->iNext;
  41289. if( p->iNext>(Pgno)nSrcPage ){
  41290. rc = SQLITE_DONE;
  41291. }
  41292. }
  41293. if( rc==SQLITE_DONE ){
  41294. const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
  41295. const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
  41296. int nDestTruncate;
  41297. /* Update the schema version field in the destination database. This
  41298. ** is to make sure that the schema-version really does change in
  41299. ** the case where the source and destination databases have the
  41300. ** same schema version.
  41301. */
  41302. sqlite3BtreeUpdateMeta(p->pDest, 1, p->iDestSchema+1);
  41303. if( p->pDestDb ){
  41304. sqlite3ResetInternalSchema(p->pDestDb, 0);
  41305. }
  41306. /* Set nDestTruncate to the final number of pages in the destination
  41307. ** database. The complication here is that the destination page
  41308. ** size may be different to the source page size.
  41309. **
  41310. ** If the source page size is smaller than the destination page size,
  41311. ** round up. In this case the call to sqlite3OsTruncate() below will
  41312. ** fix the size of the file. However it is important to call
  41313. ** sqlite3PagerTruncateImage() here so that any pages in the
  41314. ** destination file that lie beyond the nDestTruncate page mark are
  41315. ** journalled by PagerCommitPhaseOne() before they are destroyed
  41316. ** by the file truncation.
  41317. */
  41318. if( nSrcPagesize<nDestPagesize ){
  41319. int ratio = nDestPagesize/nSrcPagesize;
  41320. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  41321. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  41322. nDestTruncate--;
  41323. }
  41324. }else{
  41325. nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
  41326. }
  41327. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  41328. if( nSrcPagesize<nDestPagesize ){
  41329. /* If the source page-size is smaller than the destination page-size,
  41330. ** two extra things may need to happen:
  41331. **
  41332. ** * The destination may need to be truncated, and
  41333. **
  41334. ** * Data stored on the pages immediately following the
  41335. ** pending-byte page in the source database may need to be
  41336. ** copied into the destination database.
  41337. */
  41338. const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
  41339. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  41340. assert( pFile );
  41341. assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
  41342. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  41343. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
  41344. ));
  41345. if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
  41346. && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
  41347. && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
  41348. ){
  41349. i64 iOff;
  41350. i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
  41351. for(
  41352. iOff=PENDING_BYTE+nSrcPagesize;
  41353. rc==SQLITE_OK && iOff<iEnd;
  41354. iOff+=nSrcPagesize
  41355. ){
  41356. PgHdr *pSrcPg = 0;
  41357. const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
  41358. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  41359. if( rc==SQLITE_OK ){
  41360. u8 *zData = sqlite3PagerGetData(pSrcPg);
  41361. rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
  41362. }
  41363. sqlite3PagerUnref(pSrcPg);
  41364. }
  41365. }
  41366. }else{
  41367. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  41368. }
  41369. /* Finish committing the transaction to the destination database. */
  41370. if( SQLITE_OK==rc
  41371. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
  41372. ){
  41373. rc = SQLITE_DONE;
  41374. }
  41375. }
  41376. /* If bCloseTrans is true, then this function opened a read transaction
  41377. ** on the source database. Close the read transaction here. There is
  41378. ** no need to check the return values of the btree methods here, as
  41379. ** "committing" a read-only transaction cannot fail.
  41380. */
  41381. if( bCloseTrans ){
  41382. TESTONLY( int rc2 );
  41383. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  41384. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
  41385. assert( rc2==SQLITE_OK );
  41386. }
  41387. p->rc = rc;
  41388. }
  41389. if( p->pDestDb ){
  41390. sqlite3_mutex_leave(p->pDestDb->mutex);
  41391. }
  41392. sqlite3BtreeLeave(p->pSrc);
  41393. sqlite3_mutex_leave(p->pSrcDb->mutex);
  41394. return rc;
  41395. }
  41396. /*
  41397. ** Release all resources associated with an sqlite3_backup* handle.
  41398. */
  41399. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  41400. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  41401. sqlite3_mutex *mutex; /* Mutex to protect source database */
  41402. int rc; /* Value to return */
  41403. /* Enter the mutexes */
  41404. sqlite3_mutex_enter(p->pSrcDb->mutex);
  41405. sqlite3BtreeEnter(p->pSrc);
  41406. mutex = p->pSrcDb->mutex;
  41407. if( p->pDestDb ){
  41408. sqlite3_mutex_enter(p->pDestDb->mutex);
  41409. }
  41410. /* Detach this backup from the source pager. */
  41411. if( p->pDestDb ){
  41412. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  41413. while( *pp!=p ){
  41414. pp = &(*pp)->pNext;
  41415. }
  41416. *pp = p->pNext;
  41417. p->pSrc->nBackup--;
  41418. }
  41419. /* If a transaction is still open on the Btree, roll it back. */
  41420. sqlite3BtreeRollback(p->pDest);
  41421. /* Set the error code of the destination database handle. */
  41422. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  41423. sqlite3Error(p->pDestDb, rc, 0);
  41424. /* Exit the mutexes and free the backup context structure. */
  41425. if( p->pDestDb ){
  41426. sqlite3_mutex_leave(p->pDestDb->mutex);
  41427. }
  41428. sqlite3BtreeLeave(p->pSrc);
  41429. if( p->pDestDb ){
  41430. sqlite3_free(p);
  41431. }
  41432. sqlite3_mutex_leave(mutex);
  41433. return rc;
  41434. }
  41435. /*
  41436. ** Return the number of pages still to be backed up as of the most recent
  41437. ** call to sqlite3_backup_step().
  41438. */
  41439. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  41440. return p->nRemaining;
  41441. }
  41442. /*
  41443. ** Return the total number of pages in the source database as of the most
  41444. ** recent call to sqlite3_backup_step().
  41445. */
  41446. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  41447. return p->nPagecount;
  41448. }
  41449. /*
  41450. ** This function is called after the contents of page iPage of the
  41451. ** source database have been modified. If page iPage has already been
  41452. ** copied into the destination database, then the data written to the
  41453. ** destination is now invalidated. The destination copy of iPage needs
  41454. ** to be updated with the new data before the backup operation is
  41455. ** complete.
  41456. **
  41457. ** It is assumed that the mutex associated with the BtShared object
  41458. ** corresponding to the source database is held when this function is
  41459. ** called.
  41460. */
  41461. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  41462. sqlite3_backup *p; /* Iterator variable */
  41463. for(p=pBackup; p; p=p->pNext){
  41464. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  41465. if( !isFatalError(p->rc) && iPage<p->iNext ){
  41466. /* The backup process p has already copied page iPage. But now it
  41467. ** has been modified by a transaction on the source pager. Copy
  41468. ** the new data into the backup.
  41469. */
  41470. int rc = backupOnePage(p, iPage, aData);
  41471. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  41472. if( rc!=SQLITE_OK ){
  41473. p->rc = rc;
  41474. }
  41475. }
  41476. }
  41477. }
  41478. /*
  41479. ** Restart the backup process. This is called when the pager layer
  41480. ** detects that the database has been modified by an external database
  41481. ** connection. In this case there is no way of knowing which of the
  41482. ** pages that have been copied into the destination database are still
  41483. ** valid and which are not, so the entire process needs to be restarted.
  41484. **
  41485. ** It is assumed that the mutex associated with the BtShared object
  41486. ** corresponding to the source database is held when this function is
  41487. ** called.
  41488. */
  41489. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  41490. sqlite3_backup *p; /* Iterator variable */
  41491. for(p=pBackup; p; p=p->pNext){
  41492. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  41493. p->iNext = 1;
  41494. }
  41495. }
  41496. #ifndef SQLITE_OMIT_VACUUM
  41497. /*
  41498. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  41499. ** must be active for both files.
  41500. **
  41501. ** The size of file pTo may be reduced by this operation. If anything
  41502. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  41503. ** transaction is committed before returning.
  41504. */
  41505. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  41506. int rc;
  41507. sqlite3_backup b;
  41508. sqlite3BtreeEnter(pTo);
  41509. sqlite3BtreeEnter(pFrom);
  41510. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  41511. ** to 0. This is used by the implementations of sqlite3_backup_step()
  41512. ** and sqlite3_backup_finish() to detect that they are being called
  41513. ** from this function, not directly by the user.
  41514. */
  41515. memset(&b, 0, sizeof(b));
  41516. b.pSrcDb = pFrom->db;
  41517. b.pSrc = pFrom;
  41518. b.pDest = pTo;
  41519. b.iNext = 1;
  41520. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  41521. ** file. By passing this as the number of pages to copy to
  41522. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  41523. ** within a single call (unless an error occurs). The assert() statement
  41524. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  41525. ** or an error code.
  41526. */
  41527. sqlite3_backup_step(&b, 0x7FFFFFFF);
  41528. assert( b.rc!=SQLITE_OK );
  41529. rc = sqlite3_backup_finish(&b);
  41530. if( rc==SQLITE_OK ){
  41531. pTo->pBt->pageSizeFixed = 0;
  41532. }
  41533. sqlite3BtreeLeave(pFrom);
  41534. sqlite3BtreeLeave(pTo);
  41535. return rc;
  41536. }
  41537. #endif /* SQLITE_OMIT_VACUUM */
  41538. /************** End of backup.c **********************************************/
  41539. /************** Begin file vdbemem.c *****************************************/
  41540. /*
  41541. ** 2004 May 26
  41542. **
  41543. ** The author disclaims copyright to this source code. In place of
  41544. ** a legal notice, here is a blessing:
  41545. **
  41546. ** May you do good and not evil.
  41547. ** May you find forgiveness for yourself and forgive others.
  41548. ** May you share freely, never taking more than you give.
  41549. **
  41550. *************************************************************************
  41551. **
  41552. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  41553. ** stores a single value in the VDBE. Mem is an opaque structure visible
  41554. ** only within the VDBE. Interface routines refer to a Mem using the
  41555. ** name sqlite_value
  41556. **
  41557. ** $Id: vdbemem.c,v 1.140 2009/04/05 12:22:09 drh Exp $
  41558. */
  41559. /*
  41560. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  41561. ** P if required.
  41562. */
  41563. #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  41564. /*
  41565. ** If pMem is an object with a valid string representation, this routine
  41566. ** ensures the internal encoding for the string representation is
  41567. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  41568. **
  41569. ** If pMem is not a string object, or the encoding of the string
  41570. ** representation is already stored using the requested encoding, then this
  41571. ** routine is a no-op.
  41572. **
  41573. ** SQLITE_OK is returned if the conversion is successful (or not required).
  41574. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  41575. ** between formats.
  41576. */
  41577. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  41578. int rc;
  41579. assert( (pMem->flags&MEM_RowSet)==0 );
  41580. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  41581. || desiredEnc==SQLITE_UTF16BE );
  41582. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  41583. return SQLITE_OK;
  41584. }
  41585. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41586. #ifdef SQLITE_OMIT_UTF16
  41587. return SQLITE_ERROR;
  41588. #else
  41589. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  41590. ** then the encoding of the value may not have changed.
  41591. */
  41592. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  41593. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  41594. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  41595. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  41596. return rc;
  41597. #endif
  41598. }
  41599. /*
  41600. ** Make sure pMem->z points to a writable allocation of at least
  41601. ** n bytes.
  41602. **
  41603. ** If the memory cell currently contains string or blob data
  41604. ** and the third argument passed to this function is true, the
  41605. ** current content of the cell is preserved. Otherwise, it may
  41606. ** be discarded.
  41607. **
  41608. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  41609. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  41610. ** not set, Mem.n is zeroed.
  41611. */
  41612. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  41613. assert( 1 >=
  41614. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  41615. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  41616. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  41617. ((pMem->flags&MEM_Static) ? 1 : 0)
  41618. );
  41619. assert( (pMem->flags&MEM_RowSet)==0 );
  41620. if( n<32 ) n = 32;
  41621. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  41622. if( preserve && pMem->z==pMem->zMalloc ){
  41623. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  41624. preserve = 0;
  41625. }else{
  41626. sqlite3DbFree(pMem->db, pMem->zMalloc);
  41627. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  41628. }
  41629. }
  41630. if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  41631. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  41632. }
  41633. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  41634. pMem->xDel((void *)(pMem->z));
  41635. }
  41636. pMem->z = pMem->zMalloc;
  41637. if( pMem->z==0 ){
  41638. pMem->flags = MEM_Null;
  41639. }else{
  41640. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  41641. }
  41642. pMem->xDel = 0;
  41643. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  41644. }
  41645. /*
  41646. ** Make the given Mem object MEM_Dyn. In other words, make it so
  41647. ** that any TEXT or BLOB content is stored in memory obtained from
  41648. ** malloc(). In this way, we know that the memory is safe to be
  41649. ** overwritten or altered.
  41650. **
  41651. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  41652. */
  41653. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  41654. int f;
  41655. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41656. assert( (pMem->flags&MEM_RowSet)==0 );
  41657. expandBlob(pMem);
  41658. f = pMem->flags;
  41659. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  41660. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  41661. return SQLITE_NOMEM;
  41662. }
  41663. pMem->z[pMem->n] = 0;
  41664. pMem->z[pMem->n+1] = 0;
  41665. pMem->flags |= MEM_Term;
  41666. }
  41667. return SQLITE_OK;
  41668. }
  41669. /*
  41670. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  41671. ** blob stored in dynamically allocated space.
  41672. */
  41673. #ifndef SQLITE_OMIT_INCRBLOB
  41674. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  41675. if( pMem->flags & MEM_Zero ){
  41676. int nByte;
  41677. assert( pMem->flags&MEM_Blob );
  41678. assert( (pMem->flags&MEM_RowSet)==0 );
  41679. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41680. /* Set nByte to the number of bytes required to store the expanded blob. */
  41681. nByte = pMem->n + pMem->u.nZero;
  41682. if( nByte<=0 ){
  41683. nByte = 1;
  41684. }
  41685. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  41686. return SQLITE_NOMEM;
  41687. }
  41688. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  41689. pMem->n += pMem->u.nZero;
  41690. pMem->flags &= ~(MEM_Zero|MEM_Term);
  41691. }
  41692. return SQLITE_OK;
  41693. }
  41694. #endif
  41695. /*
  41696. ** Make sure the given Mem is \u0000 terminated.
  41697. */
  41698. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  41699. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41700. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  41701. return SQLITE_OK; /* Nothing to do */
  41702. }
  41703. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  41704. return SQLITE_NOMEM;
  41705. }
  41706. pMem->z[pMem->n] = 0;
  41707. pMem->z[pMem->n+1] = 0;
  41708. pMem->flags |= MEM_Term;
  41709. return SQLITE_OK;
  41710. }
  41711. /*
  41712. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  41713. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  41714. ** is a no-op.
  41715. **
  41716. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  41717. **
  41718. ** A MEM_Null value will never be passed to this function. This function is
  41719. ** used for converting values to text for returning to the user (i.e. via
  41720. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  41721. ** keys are strings. In the former case a NULL pointer is returned the
  41722. ** user and the later is an internal programming error.
  41723. */
  41724. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  41725. int rc = SQLITE_OK;
  41726. int fg = pMem->flags;
  41727. const int nByte = 32;
  41728. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41729. assert( !(fg&MEM_Zero) );
  41730. assert( !(fg&(MEM_Str|MEM_Blob)) );
  41731. assert( fg&(MEM_Int|MEM_Real) );
  41732. assert( (pMem->flags&MEM_RowSet)==0 );
  41733. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  41734. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  41735. return SQLITE_NOMEM;
  41736. }
  41737. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  41738. ** string representation of the value. Then, if the required encoding
  41739. ** is UTF-16le or UTF-16be do a translation.
  41740. **
  41741. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  41742. */
  41743. if( fg & MEM_Int ){
  41744. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  41745. }else{
  41746. assert( fg & MEM_Real );
  41747. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  41748. }
  41749. pMem->n = sqlite3Strlen30(pMem->z);
  41750. pMem->enc = SQLITE_UTF8;
  41751. pMem->flags |= MEM_Str|MEM_Term;
  41752. sqlite3VdbeChangeEncoding(pMem, enc);
  41753. return rc;
  41754. }
  41755. /*
  41756. ** Memory cell pMem contains the context of an aggregate function.
  41757. ** This routine calls the finalize method for that function. The
  41758. ** result of the aggregate is stored back into pMem.
  41759. **
  41760. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  41761. ** otherwise.
  41762. */
  41763. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  41764. int rc = SQLITE_OK;
  41765. if( pFunc && pFunc->xFinalize ){
  41766. sqlite3_context ctx;
  41767. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  41768. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41769. memset(&ctx, 0, sizeof(ctx));
  41770. ctx.s.flags = MEM_Null;
  41771. ctx.s.db = pMem->db;
  41772. ctx.pMem = pMem;
  41773. ctx.pFunc = pFunc;
  41774. pFunc->xFinalize(&ctx);
  41775. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  41776. sqlite3DbFree(pMem->db, pMem->zMalloc);
  41777. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  41778. rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
  41779. }
  41780. return rc;
  41781. }
  41782. /*
  41783. ** If the memory cell contains a string value that must be freed by
  41784. ** invoking an external callback, free it now. Calling this function
  41785. ** does not free any Mem.zMalloc buffer.
  41786. */
  41787. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  41788. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  41789. if( p->flags&MEM_Agg ){
  41790. sqlite3VdbeMemFinalize(p, p->u.pDef);
  41791. assert( (p->flags & MEM_Agg)==0 );
  41792. sqlite3VdbeMemRelease(p);
  41793. }else if( p->flags&MEM_Dyn && p->xDel ){
  41794. assert( (p->flags&MEM_RowSet)==0 );
  41795. p->xDel((void *)p->z);
  41796. p->xDel = 0;
  41797. }else if( p->flags&MEM_RowSet ){
  41798. sqlite3RowSetClear(p->u.pRowSet);
  41799. }
  41800. }
  41801. /*
  41802. ** Release any memory held by the Mem. This may leave the Mem in an
  41803. ** inconsistent state, for example with (Mem.z==0) and
  41804. ** (Mem.type==SQLITE_TEXT).
  41805. */
  41806. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  41807. sqlite3VdbeMemReleaseExternal(p);
  41808. sqlite3DbFree(p->db, p->zMalloc);
  41809. p->z = 0;
  41810. p->zMalloc = 0;
  41811. p->xDel = 0;
  41812. }
  41813. /*
  41814. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  41815. ** If the double is too large, return 0x8000000000000000.
  41816. **
  41817. ** Most systems appear to do this simply by assigning
  41818. ** variables and without the extra range tests. But
  41819. ** there are reports that windows throws an expection
  41820. ** if the floating point value is out of range. (See ticket #2880.)
  41821. ** Because we do not completely understand the problem, we will
  41822. ** take the conservative approach and always do range tests
  41823. ** before attempting the conversion.
  41824. */
  41825. static i64 doubleToInt64(double r){
  41826. /*
  41827. ** Many compilers we encounter do not define constants for the
  41828. ** minimum and maximum 64-bit integers, or they define them
  41829. ** inconsistently. And many do not understand the "LL" notation.
  41830. ** So we define our own static constants here using nothing
  41831. ** larger than a 32-bit integer constant.
  41832. */
  41833. static const i64 maxInt = LARGEST_INT64;
  41834. static const i64 minInt = SMALLEST_INT64;
  41835. if( r<(double)minInt ){
  41836. return minInt;
  41837. }else if( r>(double)maxInt ){
  41838. /* minInt is correct here - not maxInt. It turns out that assigning
  41839. ** a very large positive number to an integer results in a very large
  41840. ** negative integer. This makes no sense, but it is what x86 hardware
  41841. ** does so for compatibility we will do the same in software. */
  41842. return minInt;
  41843. }else{
  41844. return (i64)r;
  41845. }
  41846. }
  41847. /*
  41848. ** Return some kind of integer value which is the best we can do
  41849. ** at representing the value that *pMem describes as an integer.
  41850. ** If pMem is an integer, then the value is exact. If pMem is
  41851. ** a floating-point then the value returned is the integer part.
  41852. ** If pMem is a string or blob, then we make an attempt to convert
  41853. ** it into a integer and return that. If pMem represents an
  41854. ** an SQL-NULL value, return 0.
  41855. **
  41856. ** If pMem represents a string value, its encoding might be changed.
  41857. */
  41858. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  41859. int flags;
  41860. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41861. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  41862. flags = pMem->flags;
  41863. if( flags & MEM_Int ){
  41864. return pMem->u.i;
  41865. }else if( flags & MEM_Real ){
  41866. return doubleToInt64(pMem->r);
  41867. }else if( flags & (MEM_Str|MEM_Blob) ){
  41868. i64 value;
  41869. pMem->flags |= MEM_Str;
  41870. if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
  41871. || sqlite3VdbeMemNulTerminate(pMem) ){
  41872. return 0;
  41873. }
  41874. assert( pMem->z );
  41875. sqlite3Atoi64(pMem->z, &value);
  41876. return value;
  41877. }else{
  41878. return 0;
  41879. }
  41880. }
  41881. /*
  41882. ** Return the best representation of pMem that we can get into a
  41883. ** double. If pMem is already a double or an integer, return its
  41884. ** value. If it is a string or blob, try to convert it to a double.
  41885. ** If it is a NULL, return 0.0.
  41886. */
  41887. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  41888. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41889. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  41890. if( pMem->flags & MEM_Real ){
  41891. return pMem->r;
  41892. }else if( pMem->flags & MEM_Int ){
  41893. return (double)pMem->u.i;
  41894. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  41895. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  41896. double val = (double)0;
  41897. pMem->flags |= MEM_Str;
  41898. if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
  41899. || sqlite3VdbeMemNulTerminate(pMem) ){
  41900. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  41901. return (double)0;
  41902. }
  41903. assert( pMem->z );
  41904. sqlite3AtoF(pMem->z, &val);
  41905. return val;
  41906. }else{
  41907. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  41908. return (double)0;
  41909. }
  41910. }
  41911. /*
  41912. ** The MEM structure is already a MEM_Real. Try to also make it a
  41913. ** MEM_Int if we can.
  41914. */
  41915. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  41916. assert( pMem->flags & MEM_Real );
  41917. assert( (pMem->flags & MEM_RowSet)==0 );
  41918. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41919. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  41920. pMem->u.i = doubleToInt64(pMem->r);
  41921. if( pMem->r==(double)pMem->u.i ){
  41922. pMem->flags |= MEM_Int;
  41923. }
  41924. }
  41925. /*
  41926. ** Convert pMem to type integer. Invalidate any prior representations.
  41927. */
  41928. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  41929. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41930. assert( (pMem->flags & MEM_RowSet)==0 );
  41931. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  41932. pMem->u.i = sqlite3VdbeIntValue(pMem);
  41933. MemSetTypeFlag(pMem, MEM_Int);
  41934. return SQLITE_OK;
  41935. }
  41936. /*
  41937. ** Convert pMem so that it is of type MEM_Real.
  41938. ** Invalidate any prior representations.
  41939. */
  41940. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  41941. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41942. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  41943. pMem->r = sqlite3VdbeRealValue(pMem);
  41944. MemSetTypeFlag(pMem, MEM_Real);
  41945. return SQLITE_OK;
  41946. }
  41947. /*
  41948. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  41949. ** Invalidate any prior representations.
  41950. */
  41951. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  41952. double r1, r2;
  41953. i64 i;
  41954. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
  41955. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  41956. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  41957. r1 = sqlite3VdbeRealValue(pMem);
  41958. i = doubleToInt64(r1);
  41959. r2 = (double)i;
  41960. if( r1==r2 ){
  41961. sqlite3VdbeMemIntegerify(pMem);
  41962. }else{
  41963. pMem->r = r1;
  41964. MemSetTypeFlag(pMem, MEM_Real);
  41965. }
  41966. return SQLITE_OK;
  41967. }
  41968. /*
  41969. ** Delete any previous value and set the value stored in *pMem to NULL.
  41970. */
  41971. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  41972. if( pMem->flags & MEM_RowSet ){
  41973. sqlite3RowSetClear(pMem->u.pRowSet);
  41974. }
  41975. MemSetTypeFlag(pMem, MEM_Null);
  41976. pMem->type = SQLITE_NULL;
  41977. }
  41978. /*
  41979. ** Delete any previous value and set the value to be a BLOB of length
  41980. ** n containing all zeros.
  41981. */
  41982. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  41983. sqlite3VdbeMemRelease(pMem);
  41984. pMem->flags = MEM_Blob|MEM_Zero;
  41985. pMem->type = SQLITE_BLOB;
  41986. pMem->n = 0;
  41987. if( n<0 ) n = 0;
  41988. pMem->u.nZero = n;
  41989. pMem->enc = SQLITE_UTF8;
  41990. }
  41991. /*
  41992. ** Delete any previous value and set the value stored in *pMem to val,
  41993. ** manifest type INTEGER.
  41994. */
  41995. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  41996. sqlite3VdbeMemRelease(pMem);
  41997. pMem->u.i = val;
  41998. pMem->flags = MEM_Int;
  41999. pMem->type = SQLITE_INTEGER;
  42000. }
  42001. /*
  42002. ** Delete any previous value and set the value stored in *pMem to val,
  42003. ** manifest type REAL.
  42004. */
  42005. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  42006. if( sqlite3IsNaN(val) ){
  42007. sqlite3VdbeMemSetNull(pMem);
  42008. }else{
  42009. sqlite3VdbeMemRelease(pMem);
  42010. pMem->r = val;
  42011. pMem->flags = MEM_Real;
  42012. pMem->type = SQLITE_FLOAT;
  42013. }
  42014. }
  42015. /*
  42016. ** Delete any previous value and set the value of pMem to be an
  42017. ** empty boolean index.
  42018. */
  42019. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  42020. sqlite3 *db = pMem->db;
  42021. assert( db!=0 );
  42022. if( pMem->flags & MEM_RowSet ){
  42023. sqlite3RowSetClear(pMem->u.pRowSet);
  42024. }else{
  42025. sqlite3VdbeMemRelease(pMem);
  42026. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  42027. }
  42028. if( db->mallocFailed ){
  42029. pMem->flags = MEM_Null;
  42030. }else{
  42031. assert( pMem->zMalloc );
  42032. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  42033. sqlite3DbMallocSize(db, pMem->zMalloc));
  42034. assert( pMem->u.pRowSet!=0 );
  42035. pMem->flags = MEM_RowSet;
  42036. }
  42037. }
  42038. /*
  42039. ** Return true if the Mem object contains a TEXT or BLOB that is
  42040. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  42041. */
  42042. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  42043. assert( p->db!=0 );
  42044. if( p->flags & (MEM_Str|MEM_Blob) ){
  42045. int n = p->n;
  42046. if( p->flags & MEM_Zero ){
  42047. n += p->u.nZero;
  42048. }
  42049. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  42050. }
  42051. return 0;
  42052. }
  42053. /*
  42054. ** Size of struct Mem not including the Mem.zMalloc member.
  42055. */
  42056. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  42057. /*
  42058. ** Make an shallow copy of pFrom into pTo. Prior contents of
  42059. ** pTo are freed. The pFrom->z field is not duplicated. If
  42060. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  42061. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  42062. */
  42063. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  42064. assert( (pFrom->flags & MEM_RowSet)==0 );
  42065. sqlite3VdbeMemReleaseExternal(pTo);
  42066. memcpy(pTo, pFrom, MEMCELLSIZE);
  42067. pTo->xDel = 0;
  42068. if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
  42069. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  42070. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  42071. pTo->flags |= srcType;
  42072. }
  42073. }
  42074. /*
  42075. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  42076. ** freed before the copy is made.
  42077. */
  42078. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  42079. int rc = SQLITE_OK;
  42080. assert( (pFrom->flags & MEM_RowSet)==0 );
  42081. sqlite3VdbeMemReleaseExternal(pTo);
  42082. memcpy(pTo, pFrom, MEMCELLSIZE);
  42083. pTo->flags &= ~MEM_Dyn;
  42084. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  42085. if( 0==(pFrom->flags&MEM_Static) ){
  42086. pTo->flags |= MEM_Ephem;
  42087. rc = sqlite3VdbeMemMakeWriteable(pTo);
  42088. }
  42089. }
  42090. return rc;
  42091. }
  42092. /*
  42093. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  42094. ** freed. If pFrom contains ephemeral data, a copy is made.
  42095. **
  42096. ** pFrom contains an SQL NULL when this routine returns.
  42097. */
  42098. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  42099. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  42100. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  42101. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  42102. sqlite3VdbeMemRelease(pTo);
  42103. memcpy(pTo, pFrom, sizeof(Mem));
  42104. pFrom->flags = MEM_Null;
  42105. pFrom->xDel = 0;
  42106. pFrom->zMalloc = 0;
  42107. }
  42108. /*
  42109. ** Change the value of a Mem to be a string or a BLOB.
  42110. **
  42111. ** The memory management strategy depends on the value of the xDel
  42112. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  42113. ** string is copied into a (possibly existing) buffer managed by the
  42114. ** Mem structure. Otherwise, any existing buffer is freed and the
  42115. ** pointer copied.
  42116. */
  42117. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  42118. Mem *pMem, /* Memory cell to set to string value */
  42119. const char *z, /* String pointer */
  42120. int n, /* Bytes in string, or negative */
  42121. u8 enc, /* Encoding of z. 0 for BLOBs */
  42122. void (*xDel)(void*) /* Destructor function */
  42123. ){
  42124. int nByte = n; /* New value for pMem->n */
  42125. int iLimit; /* Maximum allowed string or blob size */
  42126. u16 flags = 0; /* New value for pMem->flags */
  42127. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  42128. assert( (pMem->flags & MEM_RowSet)==0 );
  42129. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  42130. if( !z ){
  42131. sqlite3VdbeMemSetNull(pMem);
  42132. return SQLITE_OK;
  42133. }
  42134. if( pMem->db ){
  42135. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  42136. }else{
  42137. iLimit = SQLITE_MAX_LENGTH;
  42138. }
  42139. flags = (enc==0?MEM_Blob:MEM_Str);
  42140. if( nByte<0 ){
  42141. assert( enc!=0 );
  42142. if( enc==SQLITE_UTF8 ){
  42143. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  42144. }else{
  42145. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  42146. }
  42147. flags |= MEM_Term;
  42148. }
  42149. /* The following block sets the new values of Mem.z and Mem.xDel. It
  42150. ** also sets a flag in local variable "flags" to indicate the memory
  42151. ** management (one of MEM_Dyn or MEM_Static).
  42152. */
  42153. if( xDel==SQLITE_TRANSIENT ){
  42154. int nAlloc = nByte;
  42155. if( flags&MEM_Term ){
  42156. nAlloc += (enc==SQLITE_UTF8?1:2);
  42157. }
  42158. if( nByte>iLimit ){
  42159. return SQLITE_TOOBIG;
  42160. }
  42161. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  42162. return SQLITE_NOMEM;
  42163. }
  42164. memcpy(pMem->z, z, nAlloc);
  42165. }else if( xDel==SQLITE_DYNAMIC ){
  42166. sqlite3VdbeMemRelease(pMem);
  42167. pMem->zMalloc = pMem->z = (char *)z;
  42168. pMem->xDel = 0;
  42169. }else{
  42170. sqlite3VdbeMemRelease(pMem);
  42171. pMem->z = (char *)z;
  42172. pMem->xDel = xDel;
  42173. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  42174. }
  42175. if( nByte>iLimit ){
  42176. return SQLITE_TOOBIG;
  42177. }
  42178. pMem->n = nByte;
  42179. pMem->flags = flags;
  42180. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  42181. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  42182. #ifndef SQLITE_OMIT_UTF16
  42183. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  42184. return SQLITE_NOMEM;
  42185. }
  42186. #endif
  42187. return SQLITE_OK;
  42188. }
  42189. /*
  42190. ** Compare the values contained by the two memory cells, returning
  42191. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  42192. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  42193. ** and reals) sorted numerically, followed by text ordered by the collating
  42194. ** sequence pColl and finally blob's ordered by memcmp().
  42195. **
  42196. ** Two NULL values are considered equal by this function.
  42197. */
  42198. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  42199. int rc;
  42200. int f1, f2;
  42201. int combined_flags;
  42202. /* Interchange pMem1 and pMem2 if the collating sequence specifies
  42203. ** DESC order.
  42204. */
  42205. f1 = pMem1->flags;
  42206. f2 = pMem2->flags;
  42207. combined_flags = f1|f2;
  42208. assert( (combined_flags & MEM_RowSet)==0 );
  42209. /* If one value is NULL, it is less than the other. If both values
  42210. ** are NULL, return 0.
  42211. */
  42212. if( combined_flags&MEM_Null ){
  42213. return (f2&MEM_Null) - (f1&MEM_Null);
  42214. }
  42215. /* If one value is a number and the other is not, the number is less.
  42216. ** If both are numbers, compare as reals if one is a real, or as integers
  42217. ** if both values are integers.
  42218. */
  42219. if( combined_flags&(MEM_Int|MEM_Real) ){
  42220. if( !(f1&(MEM_Int|MEM_Real)) ){
  42221. return 1;
  42222. }
  42223. if( !(f2&(MEM_Int|MEM_Real)) ){
  42224. return -1;
  42225. }
  42226. if( (f1 & f2 & MEM_Int)==0 ){
  42227. double r1, r2;
  42228. if( (f1&MEM_Real)==0 ){
  42229. r1 = (double)pMem1->u.i;
  42230. }else{
  42231. r1 = pMem1->r;
  42232. }
  42233. if( (f2&MEM_Real)==0 ){
  42234. r2 = (double)pMem2->u.i;
  42235. }else{
  42236. r2 = pMem2->r;
  42237. }
  42238. if( r1<r2 ) return -1;
  42239. if( r1>r2 ) return 1;
  42240. return 0;
  42241. }else{
  42242. assert( f1&MEM_Int );
  42243. assert( f2&MEM_Int );
  42244. if( pMem1->u.i < pMem2->u.i ) return -1;
  42245. if( pMem1->u.i > pMem2->u.i ) return 1;
  42246. return 0;
  42247. }
  42248. }
  42249. /* If one value is a string and the other is a blob, the string is less.
  42250. ** If both are strings, compare using the collating functions.
  42251. */
  42252. if( combined_flags&MEM_Str ){
  42253. if( (f1 & MEM_Str)==0 ){
  42254. return 1;
  42255. }
  42256. if( (f2 & MEM_Str)==0 ){
  42257. return -1;
  42258. }
  42259. assert( pMem1->enc==pMem2->enc );
  42260. assert( pMem1->enc==SQLITE_UTF8 ||
  42261. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  42262. /* The collation sequence must be defined at this point, even if
  42263. ** the user deletes the collation sequence after the vdbe program is
  42264. ** compiled (this was not always the case).
  42265. */
  42266. assert( !pColl || pColl->xCmp );
  42267. if( pColl ){
  42268. if( pMem1->enc==pColl->enc ){
  42269. /* The strings are already in the correct encoding. Call the
  42270. ** comparison function directly */
  42271. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  42272. }else{
  42273. const void *v1, *v2;
  42274. int n1, n2;
  42275. Mem c1;
  42276. Mem c2;
  42277. memset(&c1, 0, sizeof(c1));
  42278. memset(&c2, 0, sizeof(c2));
  42279. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  42280. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  42281. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  42282. n1 = v1==0 ? 0 : c1.n;
  42283. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  42284. n2 = v2==0 ? 0 : c2.n;
  42285. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  42286. sqlite3VdbeMemRelease(&c1);
  42287. sqlite3VdbeMemRelease(&c2);
  42288. return rc;
  42289. }
  42290. }
  42291. /* If a NULL pointer was passed as the collate function, fall through
  42292. ** to the blob case and use memcmp(). */
  42293. }
  42294. /* Both values must be blobs. Compare using memcmp(). */
  42295. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  42296. if( rc==0 ){
  42297. rc = pMem1->n - pMem2->n;
  42298. }
  42299. return rc;
  42300. }
  42301. /*
  42302. ** Move data out of a btree key or data field and into a Mem structure.
  42303. ** The data or key is taken from the entry that pCur is currently pointing
  42304. ** to. offset and amt determine what portion of the data or key to retrieve.
  42305. ** key is true to get the key or false to get data. The result is written
  42306. ** into the pMem element.
  42307. **
  42308. ** The pMem structure is assumed to be uninitialized. Any prior content
  42309. ** is overwritten without being freed.
  42310. **
  42311. ** If this routine fails for any reason (malloc returns NULL or unable
  42312. ** to read from the disk) then the pMem is left in an inconsistent state.
  42313. */
  42314. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  42315. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  42316. int offset, /* Offset from the start of data to return bytes from. */
  42317. int amt, /* Number of bytes to return. */
  42318. int key, /* If true, retrieve from the btree key, not data. */
  42319. Mem *pMem /* OUT: Return data in this Mem structure. */
  42320. ){
  42321. char *zData; /* Data from the btree layer */
  42322. int available = 0; /* Number of bytes available on the local btree page */
  42323. sqlite3 *db; /* Database connection */
  42324. int rc = SQLITE_OK;
  42325. db = sqlite3BtreeCursorDb(pCur);
  42326. assert( sqlite3_mutex_held(db->mutex) );
  42327. assert( (pMem->flags & MEM_RowSet)==0 );
  42328. if( key ){
  42329. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  42330. }else{
  42331. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  42332. }
  42333. assert( zData!=0 );
  42334. if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
  42335. sqlite3VdbeMemRelease(pMem);
  42336. pMem->z = &zData[offset];
  42337. pMem->flags = MEM_Blob|MEM_Ephem;
  42338. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  42339. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  42340. pMem->enc = 0;
  42341. pMem->type = SQLITE_BLOB;
  42342. if( key ){
  42343. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  42344. }else{
  42345. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  42346. }
  42347. pMem->z[amt] = 0;
  42348. pMem->z[amt+1] = 0;
  42349. if( rc!=SQLITE_OK ){
  42350. sqlite3VdbeMemRelease(pMem);
  42351. }
  42352. }
  42353. pMem->n = amt;
  42354. return rc;
  42355. }
  42356. /* This function is only available internally, it is not part of the
  42357. ** external API. It works in a similar way to sqlite3_value_text(),
  42358. ** except the data returned is in the encoding specified by the second
  42359. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  42360. ** SQLITE_UTF8.
  42361. **
  42362. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  42363. ** If that is the case, then the result must be aligned on an even byte
  42364. ** boundary.
  42365. */
  42366. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  42367. if( !pVal ) return 0;
  42368. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  42369. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  42370. assert( (pVal->flags & MEM_RowSet)==0 );
  42371. if( pVal->flags&MEM_Null ){
  42372. return 0;
  42373. }
  42374. assert( (MEM_Blob>>3) == MEM_Str );
  42375. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  42376. expandBlob(pVal);
  42377. if( pVal->flags&MEM_Str ){
  42378. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  42379. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  42380. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  42381. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  42382. return 0;
  42383. }
  42384. }
  42385. sqlite3VdbeMemNulTerminate(pVal);
  42386. }else{
  42387. assert( (pVal->flags&MEM_Blob)==0 );
  42388. sqlite3VdbeMemStringify(pVal, enc);
  42389. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  42390. }
  42391. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  42392. || pVal->db->mallocFailed );
  42393. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  42394. return pVal->z;
  42395. }else{
  42396. return 0;
  42397. }
  42398. }
  42399. /*
  42400. ** Create a new sqlite3_value object.
  42401. */
  42402. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  42403. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  42404. if( p ){
  42405. p->flags = MEM_Null;
  42406. p->type = SQLITE_NULL;
  42407. p->db = db;
  42408. }
  42409. return p;
  42410. }
  42411. /*
  42412. ** Create a new sqlite3_value object, containing the value of pExpr.
  42413. **
  42414. ** This only works for very simple expressions that consist of one constant
  42415. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  42416. ** be converted directly into a value, then the value is allocated and
  42417. ** a pointer written to *ppVal. The caller is responsible for deallocating
  42418. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  42419. ** cannot be converted to a value, then *ppVal is set to NULL.
  42420. */
  42421. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  42422. sqlite3 *db, /* The database connection */
  42423. Expr *pExpr, /* The expression to evaluate */
  42424. u8 enc, /* Encoding to use */
  42425. u8 affinity, /* Affinity to use */
  42426. sqlite3_value **ppVal /* Write the new value here */
  42427. ){
  42428. int op;
  42429. char *zVal = 0;
  42430. sqlite3_value *pVal = 0;
  42431. if( !pExpr ){
  42432. *ppVal = 0;
  42433. return SQLITE_OK;
  42434. }
  42435. op = pExpr->op;
  42436. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  42437. zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
  42438. pVal = sqlite3ValueNew(db);
  42439. if( !zVal || !pVal ) goto no_mem;
  42440. sqlite3Dequote(zVal);
  42441. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  42442. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  42443. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
  42444. }else{
  42445. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  42446. }
  42447. }else if( op==TK_UMINUS ) {
  42448. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
  42449. pVal->u.i = -1 * pVal->u.i;
  42450. /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
  42451. pVal->r = (double)-1 * pVal->r;
  42452. }
  42453. }
  42454. #ifndef SQLITE_OMIT_BLOB_LITERAL
  42455. else if( op==TK_BLOB ){
  42456. int nVal;
  42457. assert( pExpr->token.n>=3 );
  42458. assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
  42459. assert( pExpr->token.z[1]=='\'' );
  42460. assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
  42461. pVal = sqlite3ValueNew(db);
  42462. if( !pVal ) goto no_mem;
  42463. nVal = pExpr->token.n - 3;
  42464. zVal = (char*)pExpr->token.z + 2;
  42465. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  42466. 0, SQLITE_DYNAMIC);
  42467. }
  42468. #endif
  42469. *ppVal = pVal;
  42470. return SQLITE_OK;
  42471. no_mem:
  42472. db->mallocFailed = 1;
  42473. sqlite3DbFree(db, zVal);
  42474. sqlite3ValueFree(pVal);
  42475. *ppVal = 0;
  42476. return SQLITE_NOMEM;
  42477. }
  42478. /*
  42479. ** Change the string value of an sqlite3_value object
  42480. */
  42481. SQLITE_PRIVATE void sqlite3ValueSetStr(
  42482. sqlite3_value *v, /* Value to be set */
  42483. int n, /* Length of string z */
  42484. const void *z, /* Text of the new string */
  42485. u8 enc, /* Encoding to use */
  42486. void (*xDel)(void*) /* Destructor for the string */
  42487. ){
  42488. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  42489. }
  42490. /*
  42491. ** Free an sqlite3_value object
  42492. */
  42493. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  42494. if( !v ) return;
  42495. sqlite3VdbeMemRelease((Mem *)v);
  42496. sqlite3DbFree(((Mem*)v)->db, v);
  42497. }
  42498. /*
  42499. ** Return the number of bytes in the sqlite3_value object assuming
  42500. ** that it uses the encoding "enc"
  42501. */
  42502. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  42503. Mem *p = (Mem*)pVal;
  42504. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  42505. if( p->flags & MEM_Zero ){
  42506. return p->n + p->u.nZero;
  42507. }else{
  42508. return p->n;
  42509. }
  42510. }
  42511. return 0;
  42512. }
  42513. /************** End of vdbemem.c *********************************************/
  42514. /************** Begin file vdbeaux.c *****************************************/
  42515. /*
  42516. ** 2003 September 6
  42517. **
  42518. ** The author disclaims copyright to this source code. In place of
  42519. ** a legal notice, here is a blessing:
  42520. **
  42521. ** May you do good and not evil.
  42522. ** May you find forgiveness for yourself and forgive others.
  42523. ** May you share freely, never taking more than you give.
  42524. **
  42525. *************************************************************************
  42526. ** This file contains code used for creating, destroying, and populating
  42527. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  42528. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  42529. ** But that file was getting too big so this subroutines were split out.
  42530. **
  42531. ** $Id: vdbeaux.c,v 1.451 2009/04/10 15:42:36 shane Exp $
  42532. */
  42533. /*
  42534. ** When debugging the code generator in a symbolic debugger, one can
  42535. ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
  42536. ** as they are added to the instruction stream.
  42537. */
  42538. #ifdef SQLITE_DEBUG
  42539. SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
  42540. #endif
  42541. /*
  42542. ** Create a new virtual database engine.
  42543. */
  42544. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  42545. Vdbe *p;
  42546. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  42547. if( p==0 ) return 0;
  42548. p->db = db;
  42549. if( db->pVdbe ){
  42550. db->pVdbe->pPrev = p;
  42551. }
  42552. p->pNext = db->pVdbe;
  42553. p->pPrev = 0;
  42554. db->pVdbe = p;
  42555. p->magic = VDBE_MAGIC_INIT;
  42556. return p;
  42557. }
  42558. /*
  42559. ** Remember the SQL string for a prepared statement.
  42560. */
  42561. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  42562. if( p==0 ) return;
  42563. #ifdef SQLITE_OMIT_TRACE
  42564. if( !isPrepareV2 ) return;
  42565. #endif
  42566. assert( p->zSql==0 );
  42567. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  42568. p->isPrepareV2 = isPrepareV2 ? 1 : 0;
  42569. }
  42570. /*
  42571. ** Return the SQL associated with a prepared statement
  42572. */
  42573. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  42574. Vdbe *p = (Vdbe *)pStmt;
  42575. return (p->isPrepareV2 ? p->zSql : 0);
  42576. }
  42577. /*
  42578. ** Swap all content between two VDBE structures.
  42579. */
  42580. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  42581. Vdbe tmp, *pTmp;
  42582. char *zTmp;
  42583. tmp = *pA;
  42584. *pA = *pB;
  42585. *pB = tmp;
  42586. pTmp = pA->pNext;
  42587. pA->pNext = pB->pNext;
  42588. pB->pNext = pTmp;
  42589. pTmp = pA->pPrev;
  42590. pA->pPrev = pB->pPrev;
  42591. pB->pPrev = pTmp;
  42592. zTmp = pA->zSql;
  42593. pA->zSql = pB->zSql;
  42594. pB->zSql = zTmp;
  42595. pB->isPrepareV2 = pA->isPrepareV2;
  42596. }
  42597. #ifdef SQLITE_DEBUG
  42598. /*
  42599. ** Turn tracing on or off
  42600. */
  42601. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  42602. p->trace = trace;
  42603. }
  42604. #endif
  42605. /*
  42606. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  42607. ** it was.
  42608. **
  42609. ** If an out-of-memory error occurs while resizing the array, return
  42610. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  42611. ** unchanged (this is so that any opcodes already allocated can be
  42612. ** correctly deallocated along with the rest of the Vdbe).
  42613. */
  42614. static int growOpArray(Vdbe *p){
  42615. VdbeOp *pNew;
  42616. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  42617. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  42618. if( pNew ){
  42619. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  42620. p->aOp = pNew;
  42621. }
  42622. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  42623. }
  42624. /*
  42625. ** Add a new instruction to the list of instructions current in the
  42626. ** VDBE. Return the address of the new instruction.
  42627. **
  42628. ** Parameters:
  42629. **
  42630. ** p Pointer to the VDBE
  42631. **
  42632. ** op The opcode for this instruction
  42633. **
  42634. ** p1, p2, p3 Operands
  42635. **
  42636. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  42637. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  42638. ** operand.
  42639. */
  42640. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  42641. int i;
  42642. VdbeOp *pOp;
  42643. i = p->nOp;
  42644. assert( p->magic==VDBE_MAGIC_INIT );
  42645. assert( op>0 && op<0xff );
  42646. if( p->nOpAlloc<=i ){
  42647. if( growOpArray(p) ){
  42648. return 0;
  42649. }
  42650. }
  42651. p->nOp++;
  42652. pOp = &p->aOp[i];
  42653. pOp->opcode = (u8)op;
  42654. pOp->p5 = 0;
  42655. pOp->p1 = p1;
  42656. pOp->p2 = p2;
  42657. pOp->p3 = p3;
  42658. pOp->p4.p = 0;
  42659. pOp->p4type = P4_NOTUSED;
  42660. p->expired = 0;
  42661. #ifdef SQLITE_DEBUG
  42662. pOp->zComment = 0;
  42663. if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  42664. #endif
  42665. #ifdef VDBE_PROFILE
  42666. pOp->cycles = 0;
  42667. pOp->cnt = 0;
  42668. #endif
  42669. return i;
  42670. }
  42671. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  42672. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  42673. }
  42674. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  42675. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  42676. }
  42677. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  42678. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  42679. }
  42680. /*
  42681. ** Add an opcode that includes the p4 value as a pointer.
  42682. */
  42683. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  42684. Vdbe *p, /* Add the opcode to this VM */
  42685. int op, /* The new opcode */
  42686. int p1, /* The P1 operand */
  42687. int p2, /* The P2 operand */
  42688. int p3, /* The P3 operand */
  42689. const char *zP4, /* The P4 operand */
  42690. int p4type /* P4 operand type */
  42691. ){
  42692. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  42693. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  42694. return addr;
  42695. }
  42696. /*
  42697. ** Create a new symbolic label for an instruction that has yet to be
  42698. ** coded. The symbolic label is really just a negative number. The
  42699. ** label can be used as the P2 value of an operation. Later, when
  42700. ** the label is resolved to a specific address, the VDBE will scan
  42701. ** through its operation list and change all values of P2 which match
  42702. ** the label into the resolved address.
  42703. **
  42704. ** The VDBE knows that a P2 value is a label because labels are
  42705. ** always negative and P2 values are suppose to be non-negative.
  42706. ** Hence, a negative P2 value is a label that has yet to be resolved.
  42707. **
  42708. ** Zero is returned if a malloc() fails.
  42709. */
  42710. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  42711. int i;
  42712. i = p->nLabel++;
  42713. assert( p->magic==VDBE_MAGIC_INIT );
  42714. if( i>=p->nLabelAlloc ){
  42715. int n = p->nLabelAlloc*2 + 5;
  42716. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  42717. n*sizeof(p->aLabel[0]));
  42718. p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
  42719. }
  42720. if( p->aLabel ){
  42721. p->aLabel[i] = -1;
  42722. }
  42723. return -1-i;
  42724. }
  42725. /*
  42726. ** Resolve label "x" to be the address of the next instruction to
  42727. ** be inserted. The parameter "x" must have been obtained from
  42728. ** a prior call to sqlite3VdbeMakeLabel().
  42729. */
  42730. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  42731. int j = -1-x;
  42732. assert( p->magic==VDBE_MAGIC_INIT );
  42733. assert( j>=0 && j<p->nLabel );
  42734. if( p->aLabel ){
  42735. p->aLabel[j] = p->nOp;
  42736. }
  42737. }
  42738. /*
  42739. ** Loop through the program looking for P2 values that are negative
  42740. ** on jump instructions. Each such value is a label. Resolve the
  42741. ** label by setting the P2 value to its correct non-zero value.
  42742. **
  42743. ** This routine is called once after all opcodes have been inserted.
  42744. **
  42745. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  42746. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  42747. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  42748. **
  42749. ** This routine also does the following optimization: It scans for
  42750. ** instructions that might cause a statement rollback. Such instructions
  42751. ** are:
  42752. **
  42753. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  42754. ** * OP_Destroy
  42755. ** * OP_VUpdate
  42756. ** * OP_VRename
  42757. **
  42758. ** If no such instruction is found, then every Statement instruction
  42759. ** is changed to a Noop. In this way, we avoid creating the statement
  42760. ** journal file unnecessarily.
  42761. */
  42762. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  42763. int i;
  42764. int nMaxArgs = 0;
  42765. Op *pOp;
  42766. int *aLabel = p->aLabel;
  42767. int doesStatementRollback = 0;
  42768. int hasStatementBegin = 0;
  42769. p->readOnly = 1;
  42770. p->usesStmtJournal = 0;
  42771. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  42772. u8 opcode = pOp->opcode;
  42773. if( opcode==OP_Function || opcode==OP_AggStep ){
  42774. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  42775. #ifndef SQLITE_OMIT_VIRTUALTABLE
  42776. }else if( opcode==OP_VUpdate ){
  42777. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  42778. #endif
  42779. }
  42780. if( opcode==OP_Halt ){
  42781. if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
  42782. doesStatementRollback = 1;
  42783. }
  42784. }else if( opcode==OP_Statement ){
  42785. hasStatementBegin = 1;
  42786. p->usesStmtJournal = 1;
  42787. }else if( opcode==OP_Destroy ){
  42788. doesStatementRollback = 1;
  42789. }else if( opcode==OP_Transaction && pOp->p2!=0 ){
  42790. p->readOnly = 0;
  42791. #ifndef SQLITE_OMIT_VIRTUALTABLE
  42792. }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
  42793. doesStatementRollback = 1;
  42794. }else if( opcode==OP_VFilter ){
  42795. int n;
  42796. assert( p->nOp - i >= 3 );
  42797. assert( pOp[-1].opcode==OP_Integer );
  42798. n = pOp[-1].p1;
  42799. if( n>nMaxArgs ) nMaxArgs = n;
  42800. #endif
  42801. }
  42802. if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
  42803. assert( -1-pOp->p2<p->nLabel );
  42804. pOp->p2 = aLabel[-1-pOp->p2];
  42805. }
  42806. }
  42807. sqlite3DbFree(p->db, p->aLabel);
  42808. p->aLabel = 0;
  42809. *pMaxFuncArgs = nMaxArgs;
  42810. /* If we never rollback a statement transaction, then statement
  42811. ** transactions are not needed. So change every OP_Statement
  42812. ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
  42813. ** which can be expensive on some platforms.
  42814. */
  42815. if( hasStatementBegin && !doesStatementRollback ){
  42816. p->usesStmtJournal = 0;
  42817. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  42818. if( pOp->opcode==OP_Statement ){
  42819. pOp->opcode = OP_Noop;
  42820. }
  42821. }
  42822. }
  42823. }
  42824. /*
  42825. ** Return the address of the next instruction to be inserted.
  42826. */
  42827. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  42828. assert( p->magic==VDBE_MAGIC_INIT );
  42829. return p->nOp;
  42830. }
  42831. /*
  42832. ** Add a whole list of operations to the operation stack. Return the
  42833. ** address of the first operation added.
  42834. */
  42835. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  42836. int addr;
  42837. assert( p->magic==VDBE_MAGIC_INIT );
  42838. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  42839. return 0;
  42840. }
  42841. addr = p->nOp;
  42842. if( nOp>0 ){
  42843. int i;
  42844. VdbeOpList const *pIn = aOp;
  42845. for(i=0; i<nOp; i++, pIn++){
  42846. int p2 = pIn->p2;
  42847. VdbeOp *pOut = &p->aOp[i+addr];
  42848. pOut->opcode = pIn->opcode;
  42849. pOut->p1 = pIn->p1;
  42850. if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
  42851. pOut->p2 = addr + ADDR(p2);
  42852. }else{
  42853. pOut->p2 = p2;
  42854. }
  42855. pOut->p3 = pIn->p3;
  42856. pOut->p4type = P4_NOTUSED;
  42857. pOut->p4.p = 0;
  42858. pOut->p5 = 0;
  42859. #ifdef SQLITE_DEBUG
  42860. pOut->zComment = 0;
  42861. if( sqlite3VdbeAddopTrace ){
  42862. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  42863. }
  42864. #endif
  42865. }
  42866. p->nOp += nOp;
  42867. }
  42868. return addr;
  42869. }
  42870. /*
  42871. ** Change the value of the P1 operand for a specific instruction.
  42872. ** This routine is useful when a large program is loaded from a
  42873. ** static array using sqlite3VdbeAddOpList but we want to make a
  42874. ** few minor changes to the program.
  42875. */
  42876. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
  42877. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42878. if( p && addr>=0 && p->nOp>addr && p->aOp ){
  42879. p->aOp[addr].p1 = val;
  42880. }
  42881. }
  42882. /*
  42883. ** Change the value of the P2 operand for a specific instruction.
  42884. ** This routine is useful for setting a jump destination.
  42885. */
  42886. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
  42887. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42888. if( p && addr>=0 && p->nOp>addr && p->aOp ){
  42889. p->aOp[addr].p2 = val;
  42890. }
  42891. }
  42892. /*
  42893. ** Change the value of the P3 operand for a specific instruction.
  42894. */
  42895. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
  42896. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42897. if( p && addr>=0 && p->nOp>addr && p->aOp ){
  42898. p->aOp[addr].p3 = val;
  42899. }
  42900. }
  42901. /*
  42902. ** Change the value of the P5 operand for the most recently
  42903. ** added operation.
  42904. */
  42905. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  42906. assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  42907. if( p && p->aOp ){
  42908. assert( p->nOp>0 );
  42909. p->aOp[p->nOp-1].p5 = val;
  42910. }
  42911. }
  42912. /*
  42913. ** Change the P2 operand of instruction addr so that it points to
  42914. ** the address of the next instruction to be coded.
  42915. */
  42916. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  42917. sqlite3VdbeChangeP2(p, addr, p->nOp);
  42918. }
  42919. /*
  42920. ** If the input FuncDef structure is ephemeral, then free it. If
  42921. ** the FuncDef is not ephermal, then do nothing.
  42922. */
  42923. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  42924. if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
  42925. sqlite3DbFree(db, pDef);
  42926. }
  42927. }
  42928. /*
  42929. ** Delete a P4 value if necessary.
  42930. */
  42931. static void freeP4(sqlite3 *db, int p4type, void *p4){
  42932. if( p4 ){
  42933. switch( p4type ){
  42934. case P4_REAL:
  42935. case P4_INT64:
  42936. case P4_MPRINTF:
  42937. case P4_DYNAMIC:
  42938. case P4_KEYINFO:
  42939. case P4_INTARRAY:
  42940. case P4_KEYINFO_HANDOFF: {
  42941. sqlite3DbFree(db, p4);
  42942. break;
  42943. }
  42944. case P4_VDBEFUNC: {
  42945. VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
  42946. freeEphemeralFunction(db, pVdbeFunc->pFunc);
  42947. sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
  42948. sqlite3DbFree(db, pVdbeFunc);
  42949. break;
  42950. }
  42951. case P4_FUNCDEF: {
  42952. freeEphemeralFunction(db, (FuncDef*)p4);
  42953. break;
  42954. }
  42955. case P4_MEM: {
  42956. sqlite3ValueFree((sqlite3_value*)p4);
  42957. break;
  42958. }
  42959. }
  42960. }
  42961. }
  42962. /*
  42963. ** Change N opcodes starting at addr to No-ops.
  42964. */
  42965. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
  42966. if( p && p->aOp ){
  42967. VdbeOp *pOp = &p->aOp[addr];
  42968. sqlite3 *db = p->db;
  42969. while( N-- ){
  42970. freeP4(db, pOp->p4type, pOp->p4.p);
  42971. memset(pOp, 0, sizeof(pOp[0]));
  42972. pOp->opcode = OP_Noop;
  42973. pOp++;
  42974. }
  42975. }
  42976. }
  42977. /*
  42978. ** Change the value of the P4 operand for a specific instruction.
  42979. ** This routine is useful when a large program is loaded from a
  42980. ** static array using sqlite3VdbeAddOpList but we want to make a
  42981. ** few minor changes to the program.
  42982. **
  42983. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  42984. ** the string is made into memory obtained from sqlite3_malloc().
  42985. ** A value of n==0 means copy bytes of zP4 up to and including the
  42986. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  42987. **
  42988. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  42989. ** A copy is made of the KeyInfo structure into memory obtained from
  42990. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  42991. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  42992. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  42993. ** caller should not free the allocation, it will be freed when the Vdbe is
  42994. ** finalized.
  42995. **
  42996. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  42997. ** to a string or structure that is guaranteed to exist for the lifetime of
  42998. ** the Vdbe. In these cases we can just copy the pointer.
  42999. **
  43000. ** If addr<0 then change P4 on the most recently inserted instruction.
  43001. */
  43002. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  43003. Op *pOp;
  43004. sqlite3 *db;
  43005. assert( p!=0 );
  43006. db = p->db;
  43007. assert( p->magic==VDBE_MAGIC_INIT );
  43008. if( p->aOp==0 || db->mallocFailed ){
  43009. if (n != P4_KEYINFO) {
  43010. freeP4(db, n, (void*)*(char**)&zP4);
  43011. }
  43012. return;
  43013. }
  43014. assert( addr<p->nOp );
  43015. if( addr<0 ){
  43016. addr = p->nOp - 1;
  43017. if( addr<0 ) return;
  43018. }
  43019. pOp = &p->aOp[addr];
  43020. freeP4(db, pOp->p4type, pOp->p4.p);
  43021. pOp->p4.p = 0;
  43022. if( n==P4_INT32 ){
  43023. /* Note: this cast is safe, because the origin data point was an int
  43024. ** that was cast to a (const char *). */
  43025. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  43026. pOp->p4type = P4_INT32;
  43027. }else if( zP4==0 ){
  43028. pOp->p4.p = 0;
  43029. pOp->p4type = P4_NOTUSED;
  43030. }else if( n==P4_KEYINFO ){
  43031. KeyInfo *pKeyInfo;
  43032. int nField, nByte;
  43033. nField = ((KeyInfo*)zP4)->nField;
  43034. nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
  43035. pKeyInfo = sqlite3Malloc( nByte );
  43036. pOp->p4.pKeyInfo = pKeyInfo;
  43037. if( pKeyInfo ){
  43038. u8 *aSortOrder;
  43039. memcpy(pKeyInfo, zP4, nByte);
  43040. aSortOrder = pKeyInfo->aSortOrder;
  43041. if( aSortOrder ){
  43042. pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
  43043. memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
  43044. }
  43045. pOp->p4type = P4_KEYINFO;
  43046. }else{
  43047. p->db->mallocFailed = 1;
  43048. pOp->p4type = P4_NOTUSED;
  43049. }
  43050. }else if( n==P4_KEYINFO_HANDOFF ){
  43051. pOp->p4.p = (void*)zP4;
  43052. pOp->p4type = P4_KEYINFO;
  43053. }else if( n<0 ){
  43054. pOp->p4.p = (void*)zP4;
  43055. pOp->p4type = (signed char)n;
  43056. }else{
  43057. if( n==0 ) n = sqlite3Strlen30(zP4);
  43058. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  43059. pOp->p4type = P4_DYNAMIC;
  43060. }
  43061. }
  43062. #ifndef NDEBUG
  43063. /*
  43064. ** Change the comment on the the most recently coded instruction. Or
  43065. ** insert a No-op and add the comment to that new instruction. This
  43066. ** makes the code easier to read during debugging. None of this happens
  43067. ** in a production build.
  43068. */
  43069. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  43070. va_list ap;
  43071. assert( p->nOp>0 || p->aOp==0 );
  43072. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  43073. if( p->nOp ){
  43074. char **pz = &p->aOp[p->nOp-1].zComment;
  43075. va_start(ap, zFormat);
  43076. sqlite3DbFree(p->db, *pz);
  43077. *pz = sqlite3VMPrintf(p->db, zFormat, ap);
  43078. va_end(ap);
  43079. }
  43080. }
  43081. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  43082. va_list ap;
  43083. sqlite3VdbeAddOp0(p, OP_Noop);
  43084. assert( p->nOp>0 || p->aOp==0 );
  43085. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  43086. if( p->nOp ){
  43087. char **pz = &p->aOp[p->nOp-1].zComment;
  43088. va_start(ap, zFormat);
  43089. sqlite3DbFree(p->db, *pz);
  43090. *pz = sqlite3VMPrintf(p->db, zFormat, ap);
  43091. va_end(ap);
  43092. }
  43093. }
  43094. #endif /* NDEBUG */
  43095. /*
  43096. ** Return the opcode for a given address.
  43097. */
  43098. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  43099. assert( p->magic==VDBE_MAGIC_INIT );
  43100. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  43101. return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
  43102. }
  43103. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  43104. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  43105. /*
  43106. ** Compute a string that describes the P4 parameter for an opcode.
  43107. ** Use zTemp for any required temporary buffer space.
  43108. */
  43109. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  43110. char *zP4 = zTemp;
  43111. assert( nTemp>=20 );
  43112. switch( pOp->p4type ){
  43113. case P4_KEYINFO_STATIC:
  43114. case P4_KEYINFO: {
  43115. int i, j;
  43116. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  43117. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  43118. i = sqlite3Strlen30(zTemp);
  43119. for(j=0; j<pKeyInfo->nField; j++){
  43120. CollSeq *pColl = pKeyInfo->aColl[j];
  43121. if( pColl ){
  43122. int n = sqlite3Strlen30(pColl->zName);
  43123. if( i+n>nTemp-6 ){
  43124. memcpy(&zTemp[i],",...",4);
  43125. break;
  43126. }
  43127. zTemp[i++] = ',';
  43128. if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
  43129. zTemp[i++] = '-';
  43130. }
  43131. memcpy(&zTemp[i], pColl->zName,n+1);
  43132. i += n;
  43133. }else if( i+4<nTemp-6 ){
  43134. memcpy(&zTemp[i],",nil",4);
  43135. i += 4;
  43136. }
  43137. }
  43138. zTemp[i++] = ')';
  43139. zTemp[i] = 0;
  43140. assert( i<nTemp );
  43141. break;
  43142. }
  43143. case P4_COLLSEQ: {
  43144. CollSeq *pColl = pOp->p4.pColl;
  43145. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  43146. break;
  43147. }
  43148. case P4_FUNCDEF: {
  43149. FuncDef *pDef = pOp->p4.pFunc;
  43150. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  43151. break;
  43152. }
  43153. case P4_INT64: {
  43154. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  43155. break;
  43156. }
  43157. case P4_INT32: {
  43158. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  43159. break;
  43160. }
  43161. case P4_REAL: {
  43162. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  43163. break;
  43164. }
  43165. case P4_MEM: {
  43166. Mem *pMem = pOp->p4.pMem;
  43167. assert( (pMem->flags & MEM_Null)==0 );
  43168. if( pMem->flags & MEM_Str ){
  43169. zP4 = pMem->z;
  43170. }else if( pMem->flags & MEM_Int ){
  43171. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  43172. }else if( pMem->flags & MEM_Real ){
  43173. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  43174. }
  43175. break;
  43176. }
  43177. #ifndef SQLITE_OMIT_VIRTUALTABLE
  43178. case P4_VTAB: {
  43179. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  43180. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  43181. break;
  43182. }
  43183. #endif
  43184. case P4_INTARRAY: {
  43185. sqlite3_snprintf(nTemp, zTemp, "intarray");
  43186. break;
  43187. }
  43188. default: {
  43189. zP4 = pOp->p4.z;
  43190. if( zP4==0 ){
  43191. zP4 = zTemp;
  43192. zTemp[0] = 0;
  43193. }
  43194. }
  43195. }
  43196. assert( zP4!=0 );
  43197. return zP4;
  43198. }
  43199. #endif
  43200. /*
  43201. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  43202. **
  43203. */
  43204. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  43205. int mask;
  43206. assert( i>=0 && i<p->db->nDb );
  43207. assert( i<(int)sizeof(p->btreeMask)*8 );
  43208. mask = 1<<i;
  43209. if( (p->btreeMask & mask)==0 ){
  43210. p->btreeMask |= mask;
  43211. sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
  43212. }
  43213. }
  43214. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  43215. /*
  43216. ** Print a single opcode. This routine is used for debugging only.
  43217. */
  43218. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  43219. char *zP4;
  43220. char zPtr[50];
  43221. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  43222. if( pOut==0 ) pOut = stdout;
  43223. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  43224. fprintf(pOut, zFormat1, pc,
  43225. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  43226. #ifdef SQLITE_DEBUG
  43227. pOp->zComment ? pOp->zComment : ""
  43228. #else
  43229. ""
  43230. #endif
  43231. );
  43232. fflush(pOut);
  43233. }
  43234. #endif
  43235. /*
  43236. ** Release an array of N Mem elements
  43237. */
  43238. static void releaseMemArray(Mem *p, int N){
  43239. if( p && N ){
  43240. Mem *pEnd;
  43241. sqlite3 *db = p->db;
  43242. u8 malloc_failed = db->mallocFailed;
  43243. for(pEnd=&p[N]; p<pEnd; p++){
  43244. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  43245. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  43246. ** that takes advantage of the fact that the memory cell value is
  43247. ** being set to NULL after releasing any dynamic resources.
  43248. **
  43249. ** The justification for duplicating code is that according to
  43250. ** callgrind, this causes a certain test case to hit the CPU 4.7
  43251. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  43252. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  43253. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  43254. ** with no indexes using a single prepared INSERT statement, bind()
  43255. ** and reset(). Inserts are grouped into a transaction.
  43256. */
  43257. if( p->flags&(MEM_Agg|MEM_Dyn) ){
  43258. sqlite3VdbeMemRelease(p);
  43259. }else if( p->zMalloc ){
  43260. sqlite3DbFree(db, p->zMalloc);
  43261. p->zMalloc = 0;
  43262. }
  43263. p->flags = MEM_Null;
  43264. }
  43265. db->mallocFailed = malloc_failed;
  43266. }
  43267. }
  43268. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43269. SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
  43270. int ii;
  43271. int nFree = 0;
  43272. assert( sqlite3_mutex_held(p->db->mutex) );
  43273. for(ii=1; ii<=p->nMem; ii++){
  43274. Mem *pMem = &p->aMem[ii];
  43275. if( pMem->flags & MEM_RowSet ){
  43276. sqlite3RowSetClear(pMem->u.pRowSet);
  43277. }
  43278. if( pMem->z && pMem->flags&MEM_Dyn ){
  43279. assert( !pMem->xDel );
  43280. nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
  43281. sqlite3VdbeMemRelease(pMem);
  43282. }
  43283. }
  43284. return nFree;
  43285. }
  43286. #endif
  43287. #ifndef SQLITE_OMIT_EXPLAIN
  43288. /*
  43289. ** Give a listing of the program in the virtual machine.
  43290. **
  43291. ** The interface is the same as sqlite3VdbeExec(). But instead of
  43292. ** running the code, it invokes the callback once for each instruction.
  43293. ** This feature is used to implement "EXPLAIN".
  43294. **
  43295. ** When p->explain==1, each instruction is listed. When
  43296. ** p->explain==2, only OP_Explain instructions are listed and these
  43297. ** are shown in a different format. p->explain==2 is used to implement
  43298. ** EXPLAIN QUERY PLAN.
  43299. */
  43300. SQLITE_PRIVATE int sqlite3VdbeList(
  43301. Vdbe *p /* The VDBE */
  43302. ){
  43303. sqlite3 *db = p->db;
  43304. int i;
  43305. int rc = SQLITE_OK;
  43306. Mem *pMem = p->pResultSet = &p->aMem[1];
  43307. assert( p->explain );
  43308. if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
  43309. assert( db->magic==SQLITE_MAGIC_BUSY );
  43310. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  43311. /* Even though this opcode does not use dynamic strings for
  43312. ** the result, result columns may become dynamic if the user calls
  43313. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  43314. */
  43315. releaseMemArray(pMem, p->nMem);
  43316. if( p->rc==SQLITE_NOMEM ){
  43317. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  43318. ** sqlite3_column_text16() failed. */
  43319. db->mallocFailed = 1;
  43320. return SQLITE_ERROR;
  43321. }
  43322. do{
  43323. i = p->pc++;
  43324. }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  43325. if( i>=p->nOp ){
  43326. p->rc = SQLITE_OK;
  43327. rc = SQLITE_DONE;
  43328. }else if( db->u1.isInterrupted ){
  43329. p->rc = SQLITE_INTERRUPT;
  43330. rc = SQLITE_ERROR;
  43331. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  43332. }else{
  43333. char *z;
  43334. Op *pOp = &p->aOp[i];
  43335. if( p->explain==1 ){
  43336. pMem->flags = MEM_Int;
  43337. pMem->type = SQLITE_INTEGER;
  43338. pMem->u.i = i; /* Program counter */
  43339. pMem++;
  43340. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  43341. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  43342. assert( pMem->z!=0 );
  43343. pMem->n = sqlite3Strlen30(pMem->z);
  43344. pMem->type = SQLITE_TEXT;
  43345. pMem->enc = SQLITE_UTF8;
  43346. pMem++;
  43347. }
  43348. pMem->flags = MEM_Int;
  43349. pMem->u.i = pOp->p1; /* P1 */
  43350. pMem->type = SQLITE_INTEGER;
  43351. pMem++;
  43352. pMem->flags = MEM_Int;
  43353. pMem->u.i = pOp->p2; /* P2 */
  43354. pMem->type = SQLITE_INTEGER;
  43355. pMem++;
  43356. if( p->explain==1 ){
  43357. pMem->flags = MEM_Int;
  43358. pMem->u.i = pOp->p3; /* P3 */
  43359. pMem->type = SQLITE_INTEGER;
  43360. pMem++;
  43361. }
  43362. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  43363. assert( p->db->mallocFailed );
  43364. return SQLITE_ERROR;
  43365. }
  43366. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  43367. z = displayP4(pOp, pMem->z, 32);
  43368. if( z!=pMem->z ){
  43369. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  43370. }else{
  43371. assert( pMem->z!=0 );
  43372. pMem->n = sqlite3Strlen30(pMem->z);
  43373. pMem->enc = SQLITE_UTF8;
  43374. }
  43375. pMem->type = SQLITE_TEXT;
  43376. pMem++;
  43377. if( p->explain==1 ){
  43378. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  43379. assert( p->db->mallocFailed );
  43380. return SQLITE_ERROR;
  43381. }
  43382. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  43383. pMem->n = 2;
  43384. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  43385. pMem->type = SQLITE_TEXT;
  43386. pMem->enc = SQLITE_UTF8;
  43387. pMem++;
  43388. #ifdef SQLITE_DEBUG
  43389. if( pOp->zComment ){
  43390. pMem->flags = MEM_Str|MEM_Term;
  43391. pMem->z = pOp->zComment;
  43392. pMem->n = sqlite3Strlen30(pMem->z);
  43393. pMem->enc = SQLITE_UTF8;
  43394. pMem->type = SQLITE_TEXT;
  43395. }else
  43396. #endif
  43397. {
  43398. pMem->flags = MEM_Null; /* Comment */
  43399. pMem->type = SQLITE_NULL;
  43400. }
  43401. }
  43402. p->nResColumn = 8 - 5*(p->explain-1);
  43403. p->rc = SQLITE_OK;
  43404. rc = SQLITE_ROW;
  43405. }
  43406. return rc;
  43407. }
  43408. #endif /* SQLITE_OMIT_EXPLAIN */
  43409. #ifdef SQLITE_DEBUG
  43410. /*
  43411. ** Print the SQL that was used to generate a VDBE program.
  43412. */
  43413. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  43414. int nOp = p->nOp;
  43415. VdbeOp *pOp;
  43416. if( nOp<1 ) return;
  43417. pOp = &p->aOp[0];
  43418. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  43419. const char *z = pOp->p4.z;
  43420. while( sqlite3Isspace(*z) ) z++;
  43421. printf("SQL: [%s]\n", z);
  43422. }
  43423. }
  43424. #endif
  43425. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  43426. /*
  43427. ** Print an IOTRACE message showing SQL content.
  43428. */
  43429. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  43430. int nOp = p->nOp;
  43431. VdbeOp *pOp;
  43432. if( sqlite3IoTrace==0 ) return;
  43433. if( nOp<1 ) return;
  43434. pOp = &p->aOp[0];
  43435. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  43436. int i, j;
  43437. char z[1000];
  43438. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  43439. for(i=0; sqlite3Isspace(z[i]); i++){}
  43440. for(j=0; z[i]; i++){
  43441. if( sqlite3Isspace(z[i]) ){
  43442. if( z[i-1]!=' ' ){
  43443. z[j++] = ' ';
  43444. }
  43445. }else{
  43446. z[j++] = z[i];
  43447. }
  43448. }
  43449. z[j] = 0;
  43450. sqlite3IoTrace("SQL %s\n", z);
  43451. }
  43452. }
  43453. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  43454. /*
  43455. ** Allocate space from a fixed size buffer. Make *pp point to the
  43456. ** allocated space. (Note: pp is a char* rather than a void** to
  43457. ** work around the pointer aliasing rules of C.) *pp should initially
  43458. ** be zero. If *pp is not zero, that means that the space has already
  43459. ** been allocated and this routine is a noop.
  43460. **
  43461. ** nByte is the number of bytes of space needed.
  43462. **
  43463. ** *ppFrom point to available space and pEnd points to the end of the
  43464. ** available space.
  43465. **
  43466. ** *pnByte is a counter of the number of bytes of space that have failed
  43467. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  43468. ** request, then increment *pnByte by the amount of the request.
  43469. */
  43470. static void allocSpace(
  43471. char *pp, /* IN/OUT: Set *pp to point to allocated buffer */
  43472. int nByte, /* Number of bytes to allocate */
  43473. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  43474. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  43475. int *pnByte /* If allocation cannot be made, increment *pnByte */
  43476. ){
  43477. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  43478. if( (*(void**)pp)==0 ){
  43479. nByte = ROUND8(nByte);
  43480. if( (pEnd - *ppFrom)>=nByte ){
  43481. *(void**)pp = (void *)*ppFrom;
  43482. *ppFrom += nByte;
  43483. }else{
  43484. *pnByte += nByte;
  43485. }
  43486. }
  43487. }
  43488. /*
  43489. ** Prepare a virtual machine for execution. This involves things such
  43490. ** as allocating stack space and initializing the program counter.
  43491. ** After the VDBE has be prepped, it can be executed by one or more
  43492. ** calls to sqlite3VdbeExec().
  43493. **
  43494. ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
  43495. ** VDBE_MAGIC_RUN.
  43496. **
  43497. ** This function may be called more than once on a single virtual machine.
  43498. ** The first call is made while compiling the SQL statement. Subsequent
  43499. ** calls are made as part of the process of resetting a statement to be
  43500. ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
  43501. ** and isExplain parameters are only passed correct values the first time
  43502. ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
  43503. ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
  43504. */
  43505. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  43506. Vdbe *p, /* The VDBE */
  43507. int nVar, /* Number of '?' see in the SQL statement */
  43508. int nMem, /* Number of memory cells to allocate */
  43509. int nCursor, /* Number of cursors to allocate */
  43510. int isExplain /* True if the EXPLAIN keywords is present */
  43511. ){
  43512. int n;
  43513. sqlite3 *db = p->db;
  43514. assert( p!=0 );
  43515. assert( p->magic==VDBE_MAGIC_INIT );
  43516. /* There should be at least one opcode.
  43517. */
  43518. assert( p->nOp>0 );
  43519. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  43520. p->magic = VDBE_MAGIC_RUN;
  43521. /* For each cursor required, also allocate a memory cell. Memory
  43522. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  43523. ** the vdbe program. Instead they are used to allocate space for
  43524. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  43525. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  43526. ** stores the blob of memory associated with cursor 1, etc.
  43527. **
  43528. ** See also: allocateCursor().
  43529. */
  43530. nMem += nCursor;
  43531. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  43532. ** an array to marshal SQL function arguments in. This is only done the
  43533. ** first time this function is called for a given VDBE, not when it is
  43534. ** being called from sqlite3_reset() to reset the virtual machine.
  43535. */
  43536. if( nVar>=0 && !db->mallocFailed ){
  43537. u8 *zCsr = (u8 *)&p->aOp[p->nOp];
  43538. u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];
  43539. int nByte;
  43540. int nArg; /* Maximum number of args passed to a user function. */
  43541. resolveP2Values(p, &nArg);
  43542. if( isExplain && nMem<10 ){
  43543. nMem = 10;
  43544. }
  43545. zCsr += (zCsr - (u8*)0)&7;
  43546. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  43547. if( zEnd<zCsr ) zEnd = zCsr;
  43548. do {
  43549. memset(zCsr, 0, zEnd-zCsr);
  43550. nByte = 0;
  43551. allocSpace((char*)&p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  43552. allocSpace((char*)&p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  43553. allocSpace((char*)&p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  43554. allocSpace((char*)&p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  43555. allocSpace((char*)&p->apCsr,
  43556. nCursor*sizeof(VdbeCursor*), &zCsr, zEnd, &nByte
  43557. );
  43558. if( nByte ){
  43559. p->pFree = sqlite3DbMallocRaw(db, nByte);
  43560. }
  43561. zCsr = p->pFree;
  43562. zEnd = &zCsr[nByte];
  43563. }while( nByte && !db->mallocFailed );
  43564. p->nCursor = nCursor;
  43565. if( p->aVar ){
  43566. p->nVar = nVar;
  43567. for(n=0; n<nVar; n++){
  43568. p->aVar[n].flags = MEM_Null;
  43569. p->aVar[n].db = db;
  43570. }
  43571. }
  43572. if( p->aMem ){
  43573. p->aMem--; /* aMem[] goes from 1..nMem */
  43574. p->nMem = nMem; /* not from 0..nMem-1 */
  43575. for(n=1; n<=nMem; n++){
  43576. p->aMem[n].flags = MEM_Null;
  43577. p->aMem[n].db = db;
  43578. }
  43579. }
  43580. }
  43581. #ifdef SQLITE_DEBUG
  43582. for(n=1; n<p->nMem; n++){
  43583. assert( p->aMem[n].db==db );
  43584. }
  43585. #endif
  43586. p->pc = -1;
  43587. p->rc = SQLITE_OK;
  43588. p->errorAction = OE_Abort;
  43589. p->explain |= isExplain;
  43590. p->magic = VDBE_MAGIC_RUN;
  43591. p->nChange = 0;
  43592. p->cacheCtr = 1;
  43593. p->minWriteFileFormat = 255;
  43594. p->iStatement = 0;
  43595. #ifdef VDBE_PROFILE
  43596. {
  43597. int i;
  43598. for(i=0; i<p->nOp; i++){
  43599. p->aOp[i].cnt = 0;
  43600. p->aOp[i].cycles = 0;
  43601. }
  43602. }
  43603. #endif
  43604. }
  43605. /*
  43606. ** Close a VDBE cursor and release all the resources that cursor
  43607. ** happens to hold.
  43608. */
  43609. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  43610. if( pCx==0 ){
  43611. return;
  43612. }
  43613. if( pCx->pBt ){
  43614. sqlite3BtreeClose(pCx->pBt);
  43615. /* The pCx->pCursor will be close automatically, if it exists, by
  43616. ** the call above. */
  43617. }else if( pCx->pCursor ){
  43618. sqlite3BtreeCloseCursor(pCx->pCursor);
  43619. }
  43620. #ifndef SQLITE_OMIT_VIRTUALTABLE
  43621. if( pCx->pVtabCursor ){
  43622. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  43623. const sqlite3_module *pModule = pCx->pModule;
  43624. p->inVtabMethod = 1;
  43625. (void)sqlite3SafetyOff(p->db);
  43626. pModule->xClose(pVtabCursor);
  43627. (void)sqlite3SafetyOn(p->db);
  43628. p->inVtabMethod = 0;
  43629. }
  43630. #endif
  43631. if( !pCx->ephemPseudoTable ){
  43632. sqlite3DbFree(p->db, pCx->pData);
  43633. }
  43634. }
  43635. /*
  43636. ** Close all cursors except for VTab cursors that are currently
  43637. ** in use.
  43638. */
  43639. static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
  43640. int i;
  43641. if( p->apCsr==0 ) return;
  43642. for(i=0; i<p->nCursor; i++){
  43643. VdbeCursor *pC = p->apCsr[i];
  43644. if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
  43645. sqlite3VdbeFreeCursor(p, pC);
  43646. p->apCsr[i] = 0;
  43647. }
  43648. }
  43649. }
  43650. /*
  43651. ** Clean up the VM after execution.
  43652. **
  43653. ** This routine will automatically close any cursors, lists, and/or
  43654. ** sorters that were left open. It also deletes the values of
  43655. ** variables in the aVar[] array.
  43656. */
  43657. static void Cleanup(Vdbe *p){
  43658. int i;
  43659. sqlite3 *db = p->db;
  43660. Mem *pMem;
  43661. closeAllCursorsExceptActiveVtabs(p);
  43662. for(pMem=&p->aMem[1], i=1; i<=p->nMem; i++, pMem++){
  43663. if( pMem->flags & MEM_RowSet ){
  43664. sqlite3RowSetClear(pMem->u.pRowSet);
  43665. }
  43666. MemSetTypeFlag(pMem, MEM_Null);
  43667. }
  43668. releaseMemArray(&p->aMem[1], p->nMem);
  43669. if( p->contextStack ){
  43670. sqlite3DbFree(db, p->contextStack);
  43671. }
  43672. p->contextStack = 0;
  43673. p->contextStackDepth = 0;
  43674. p->contextStackTop = 0;
  43675. sqlite3DbFree(db, p->zErrMsg);
  43676. p->zErrMsg = 0;
  43677. p->pResultSet = 0;
  43678. }
  43679. /*
  43680. ** Set the number of result columns that will be returned by this SQL
  43681. ** statement. This is now set at compile time, rather than during
  43682. ** execution of the vdbe program so that sqlite3_column_count() can
  43683. ** be called on an SQL statement before sqlite3_step().
  43684. */
  43685. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  43686. Mem *pColName;
  43687. int n;
  43688. sqlite3 *db = p->db;
  43689. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  43690. sqlite3DbFree(db, p->aColName);
  43691. n = nResColumn*COLNAME_N;
  43692. p->nResColumn = nResColumn;
  43693. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  43694. if( p->aColName==0 ) return;
  43695. while( n-- > 0 ){
  43696. pColName->flags = MEM_Null;
  43697. pColName->db = p->db;
  43698. pColName++;
  43699. }
  43700. }
  43701. /*
  43702. ** Set the name of the idx'th column to be returned by the SQL statement.
  43703. ** zName must be a pointer to a nul terminated string.
  43704. **
  43705. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  43706. **
  43707. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  43708. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  43709. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  43710. */
  43711. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  43712. Vdbe *p, /* Vdbe being configured */
  43713. int idx, /* Index of column zName applies to */
  43714. int var, /* One of the COLNAME_* constants */
  43715. const char *zName, /* Pointer to buffer containing name */
  43716. void (*xDel)(void*) /* Memory management strategy for zName */
  43717. ){
  43718. int rc;
  43719. Mem *pColName;
  43720. assert( idx<p->nResColumn );
  43721. assert( var<COLNAME_N );
  43722. if( p->db->mallocFailed ){
  43723. assert( !zName || xDel!=SQLITE_DYNAMIC );
  43724. return SQLITE_NOMEM;
  43725. }
  43726. assert( p->aColName!=0 );
  43727. pColName = &(p->aColName[idx+var*p->nResColumn]);
  43728. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  43729. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  43730. return rc;
  43731. }
  43732. /*
  43733. ** A read or write transaction may or may not be active on database handle
  43734. ** db. If a transaction is active, commit it. If there is a
  43735. ** write-transaction spanning more than one database file, this routine
  43736. ** takes care of the master journal trickery.
  43737. */
  43738. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  43739. int i;
  43740. int nTrans = 0; /* Number of databases with an active write-transaction */
  43741. int rc = SQLITE_OK;
  43742. int needXcommit = 0;
  43743. /* Before doing anything else, call the xSync() callback for any
  43744. ** virtual module tables written in this transaction. This has to
  43745. ** be done before determining whether a master journal file is
  43746. ** required, as an xSync() callback may add an attached database
  43747. ** to the transaction.
  43748. */
  43749. rc = sqlite3VtabSync(db, &p->zErrMsg);
  43750. if( rc!=SQLITE_OK ){
  43751. return rc;
  43752. }
  43753. /* This loop determines (a) if the commit hook should be invoked and
  43754. ** (b) how many database files have open write transactions, not
  43755. ** including the temp database. (b) is important because if more than
  43756. ** one database file has an open write transaction, a master journal
  43757. ** file is required for an atomic commit.
  43758. */
  43759. for(i=0; i<db->nDb; i++){
  43760. Btree *pBt = db->aDb[i].pBt;
  43761. if( sqlite3BtreeIsInTrans(pBt) ){
  43762. needXcommit = 1;
  43763. if( i!=1 ) nTrans++;
  43764. }
  43765. }
  43766. /* If there are any write-transactions at all, invoke the commit hook */
  43767. if( needXcommit && db->xCommitCallback ){
  43768. assert( (db->flags & SQLITE_CommitBusy)==0 );
  43769. db->flags |= SQLITE_CommitBusy;
  43770. (void)sqlite3SafetyOff(db);
  43771. rc = db->xCommitCallback(db->pCommitArg);
  43772. (void)sqlite3SafetyOn(db);
  43773. db->flags &= ~SQLITE_CommitBusy;
  43774. if( rc ){
  43775. return SQLITE_CONSTRAINT;
  43776. }
  43777. }
  43778. /* The simple case - no more than one database file (not counting the
  43779. ** TEMP database) has a transaction active. There is no need for the
  43780. ** master-journal.
  43781. **
  43782. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  43783. ** string, it means the main database is :memory: or a temp file. In
  43784. ** that case we do not support atomic multi-file commits, so use the
  43785. ** simple case then too.
  43786. */
  43787. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  43788. || nTrans<=1
  43789. ){
  43790. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  43791. Btree *pBt = db->aDb[i].pBt;
  43792. if( pBt ){
  43793. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  43794. }
  43795. }
  43796. /* Do the commit only if all databases successfully complete phase 1.
  43797. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  43798. ** IO error while deleting or truncating a journal file. It is unlikely,
  43799. ** but could happen. In this case abandon processing and return the error.
  43800. */
  43801. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  43802. Btree *pBt = db->aDb[i].pBt;
  43803. if( pBt ){
  43804. rc = sqlite3BtreeCommitPhaseTwo(pBt);
  43805. }
  43806. }
  43807. if( rc==SQLITE_OK ){
  43808. sqlite3VtabCommit(db);
  43809. }
  43810. }
  43811. /* The complex case - There is a multi-file write-transaction active.
  43812. ** This requires a master journal file to ensure the transaction is
  43813. ** committed atomicly.
  43814. */
  43815. #ifndef SQLITE_OMIT_DISKIO
  43816. else{
  43817. sqlite3_vfs *pVfs = db->pVfs;
  43818. int needSync = 0;
  43819. char *zMaster = 0; /* File-name for the master journal */
  43820. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  43821. sqlite3_file *pMaster = 0;
  43822. i64 offset = 0;
  43823. int res;
  43824. /* Select a master journal file name */
  43825. do {
  43826. u32 iRandom;
  43827. sqlite3DbFree(db, zMaster);
  43828. sqlite3_randomness(sizeof(iRandom), &iRandom);
  43829. zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
  43830. if( !zMaster ){
  43831. return SQLITE_NOMEM;
  43832. }
  43833. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  43834. }while( rc==SQLITE_OK && res );
  43835. if( rc==SQLITE_OK ){
  43836. /* Open the master journal. */
  43837. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  43838. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  43839. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  43840. );
  43841. }
  43842. if( rc!=SQLITE_OK ){
  43843. sqlite3DbFree(db, zMaster);
  43844. return rc;
  43845. }
  43846. /* Write the name of each database file in the transaction into the new
  43847. ** master journal file. If an error occurs at this point close
  43848. ** and delete the master journal file. All the individual journal files
  43849. ** still have 'null' as the master journal pointer, so they will roll
  43850. ** back independently if a failure occurs.
  43851. */
  43852. for(i=0; i<db->nDb; i++){
  43853. Btree *pBt = db->aDb[i].pBt;
  43854. if( i==1 ) continue; /* Ignore the TEMP database */
  43855. if( sqlite3BtreeIsInTrans(pBt) ){
  43856. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  43857. if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
  43858. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  43859. needSync = 1;
  43860. }
  43861. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  43862. offset += sqlite3Strlen30(zFile)+1;
  43863. if( rc!=SQLITE_OK ){
  43864. sqlite3OsCloseFree(pMaster);
  43865. sqlite3OsDelete(pVfs, zMaster, 0);
  43866. sqlite3DbFree(db, zMaster);
  43867. return rc;
  43868. }
  43869. }
  43870. }
  43871. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  43872. ** flag is set this is not required.
  43873. */
  43874. if( needSync
  43875. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  43876. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  43877. ){
  43878. sqlite3OsCloseFree(pMaster);
  43879. sqlite3OsDelete(pVfs, zMaster, 0);
  43880. sqlite3DbFree(db, zMaster);
  43881. return rc;
  43882. }
  43883. /* Sync all the db files involved in the transaction. The same call
  43884. ** sets the master journal pointer in each individual journal. If
  43885. ** an error occurs here, do not delete the master journal file.
  43886. **
  43887. ** If the error occurs during the first call to
  43888. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  43889. ** master journal file will be orphaned. But we cannot delete it,
  43890. ** in case the master journal file name was written into the journal
  43891. ** file before the failure occurred.
  43892. */
  43893. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  43894. Btree *pBt = db->aDb[i].pBt;
  43895. if( pBt ){
  43896. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  43897. }
  43898. }
  43899. sqlite3OsCloseFree(pMaster);
  43900. if( rc!=SQLITE_OK ){
  43901. sqlite3DbFree(db, zMaster);
  43902. return rc;
  43903. }
  43904. /* Delete the master journal file. This commits the transaction. After
  43905. ** doing this the directory is synced again before any individual
  43906. ** transaction files are deleted.
  43907. */
  43908. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  43909. sqlite3DbFree(db, zMaster);
  43910. zMaster = 0;
  43911. if( rc ){
  43912. return rc;
  43913. }
  43914. /* All files and directories have already been synced, so the following
  43915. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  43916. ** deleting or truncating journals. If something goes wrong while
  43917. ** this is happening we don't really care. The integrity of the
  43918. ** transaction is already guaranteed, but some stray 'cold' journals
  43919. ** may be lying around. Returning an error code won't help matters.
  43920. */
  43921. disable_simulated_io_errors();
  43922. sqlite3BeginBenignMalloc();
  43923. for(i=0; i<db->nDb; i++){
  43924. Btree *pBt = db->aDb[i].pBt;
  43925. if( pBt ){
  43926. sqlite3BtreeCommitPhaseTwo(pBt);
  43927. }
  43928. }
  43929. sqlite3EndBenignMalloc();
  43930. enable_simulated_io_errors();
  43931. sqlite3VtabCommit(db);
  43932. }
  43933. #endif
  43934. return rc;
  43935. }
  43936. /*
  43937. ** This routine checks that the sqlite3.activeVdbeCnt count variable
  43938. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  43939. ** currently active. An assertion fails if the two counts do not match.
  43940. ** This is an internal self-check only - it is not an essential processing
  43941. ** step.
  43942. **
  43943. ** This is a no-op if NDEBUG is defined.
  43944. */
  43945. #ifndef NDEBUG
  43946. static void checkActiveVdbeCnt(sqlite3 *db){
  43947. Vdbe *p;
  43948. int cnt = 0;
  43949. int nWrite = 0;
  43950. p = db->pVdbe;
  43951. while( p ){
  43952. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  43953. cnt++;
  43954. if( p->readOnly==0 ) nWrite++;
  43955. }
  43956. p = p->pNext;
  43957. }
  43958. assert( cnt==db->activeVdbeCnt );
  43959. assert( nWrite==db->writeVdbeCnt );
  43960. }
  43961. #else
  43962. #define checkActiveVdbeCnt(x)
  43963. #endif
  43964. /*
  43965. ** For every Btree that in database connection db which
  43966. ** has been modified, "trip" or invalidate each cursor in
  43967. ** that Btree might have been modified so that the cursor
  43968. ** can never be used again. This happens when a rollback
  43969. *** occurs. We have to trip all the other cursors, even
  43970. ** cursor from other VMs in different database connections,
  43971. ** so that none of them try to use the data at which they
  43972. ** were pointing and which now may have been changed due
  43973. ** to the rollback.
  43974. **
  43975. ** Remember that a rollback can delete tables complete and
  43976. ** reorder rootpages. So it is not sufficient just to save
  43977. ** the state of the cursor. We have to invalidate the cursor
  43978. ** so that it is never used again.
  43979. */
  43980. static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
  43981. int i;
  43982. for(i=0; i<db->nDb; i++){
  43983. Btree *p = db->aDb[i].pBt;
  43984. if( p && sqlite3BtreeIsInTrans(p) ){
  43985. sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
  43986. }
  43987. }
  43988. }
  43989. /*
  43990. ** If the Vdbe passed as the first argument opened a statement-transaction,
  43991. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  43992. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  43993. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  43994. ** statement transaction is commtted.
  43995. **
  43996. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  43997. ** Otherwise SQLITE_OK.
  43998. */
  43999. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  44000. sqlite3 *const db = p->db;
  44001. int rc = SQLITE_OK;
  44002. if( p->iStatement && db->nStatement ){
  44003. int i;
  44004. const int iSavepoint = p->iStatement-1;
  44005. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  44006. assert( db->nStatement>0 );
  44007. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  44008. for(i=0; i<db->nDb; i++){
  44009. int rc2 = SQLITE_OK;
  44010. Btree *pBt = db->aDb[i].pBt;
  44011. if( pBt ){
  44012. if( eOp==SAVEPOINT_ROLLBACK ){
  44013. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  44014. }
  44015. if( rc2==SQLITE_OK ){
  44016. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  44017. }
  44018. if( rc==SQLITE_OK ){
  44019. rc = rc2;
  44020. }
  44021. }
  44022. }
  44023. db->nStatement--;
  44024. p->iStatement = 0;
  44025. }
  44026. return rc;
  44027. }
  44028. /*
  44029. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  44030. ** this routine obtains the mutex associated with each BtShared structure
  44031. ** that may be accessed by the VM passed as an argument. In doing so it
  44032. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  44033. ** that the correct busy-handler callback is invoked if required.
  44034. **
  44035. ** If SQLite is not threadsafe but does support shared-cache mode, then
  44036. ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
  44037. ** of all of BtShared structures accessible via the database handle
  44038. ** associated with the VM. Of course only a subset of these structures
  44039. ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
  44040. ** that subset out, but there is no advantage to doing so.
  44041. **
  44042. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  44043. ** function is a no-op.
  44044. */
  44045. #ifndef SQLITE_OMIT_SHARED_CACHE
  44046. SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
  44047. #if SQLITE_THREADSAFE
  44048. sqlite3BtreeMutexArrayEnter(&p->aMutex);
  44049. #else
  44050. sqlite3BtreeEnterAll(p->db);
  44051. #endif
  44052. }
  44053. #endif
  44054. /*
  44055. ** This routine is called the when a VDBE tries to halt. If the VDBE
  44056. ** has made changes and is in autocommit mode, then commit those
  44057. ** changes. If a rollback is needed, then do the rollback.
  44058. **
  44059. ** This routine is the only way to move the state of a VM from
  44060. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  44061. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  44062. **
  44063. ** Return an error code. If the commit could not complete because of
  44064. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  44065. ** means the close did not happen and needs to be repeated.
  44066. */
  44067. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  44068. int rc; /* Used to store transient return codes */
  44069. sqlite3 *db = p->db;
  44070. /* This function contains the logic that determines if a statement or
  44071. ** transaction will be committed or rolled back as a result of the
  44072. ** execution of this virtual machine.
  44073. **
  44074. ** If any of the following errors occur:
  44075. **
  44076. ** SQLITE_NOMEM
  44077. ** SQLITE_IOERR
  44078. ** SQLITE_FULL
  44079. ** SQLITE_INTERRUPT
  44080. **
  44081. ** Then the internal cache might have been left in an inconsistent
  44082. ** state. We need to rollback the statement transaction, if there is
  44083. ** one, or the complete transaction if there is no statement transaction.
  44084. */
  44085. if( p->db->mallocFailed ){
  44086. p->rc = SQLITE_NOMEM;
  44087. }
  44088. closeAllCursorsExceptActiveVtabs(p);
  44089. if( p->magic!=VDBE_MAGIC_RUN ){
  44090. return SQLITE_OK;
  44091. }
  44092. checkActiveVdbeCnt(db);
  44093. /* No commit or rollback needed if the program never started */
  44094. if( p->pc>=0 ){
  44095. int mrc; /* Primary error code from p->rc */
  44096. int eStatementOp = 0;
  44097. int isSpecialError; /* Set to true if a 'special' error */
  44098. /* Lock all btrees used by the statement */
  44099. sqlite3VdbeMutexArrayEnter(p);
  44100. /* Check for one of the special errors */
  44101. mrc = p->rc & 0xff;
  44102. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  44103. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  44104. if( isSpecialError ){
  44105. /* If the query was read-only, we need do no rollback at all. Otherwise,
  44106. ** proceed with the special handling.
  44107. */
  44108. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  44109. if( p->rc==SQLITE_IOERR_BLOCKED && p->usesStmtJournal ){
  44110. eStatementOp = SAVEPOINT_ROLLBACK;
  44111. p->rc = SQLITE_BUSY;
  44112. }else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL)
  44113. && p->usesStmtJournal ){
  44114. eStatementOp = SAVEPOINT_ROLLBACK;
  44115. }else{
  44116. /* We are forced to roll back the active transaction. Before doing
  44117. ** so, abort any other statements this handle currently has active.
  44118. */
  44119. invalidateCursorsOnModifiedBtrees(db);
  44120. sqlite3RollbackAll(db);
  44121. sqlite3CloseSavepoints(db);
  44122. db->autoCommit = 1;
  44123. }
  44124. }
  44125. }
  44126. /* If the auto-commit flag is set and this is the only active writer
  44127. ** VM, then we do either a commit or rollback of the current transaction.
  44128. **
  44129. ** Note: This block also runs if one of the special errors handled
  44130. ** above has occurred.
  44131. */
  44132. if( !sqlite3VtabInSync(db)
  44133. && db->autoCommit
  44134. && db->writeVdbeCnt==(p->readOnly==0)
  44135. && (db->flags & SQLITE_CommitBusy)==0
  44136. ){
  44137. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  44138. /* The auto-commit flag is true, and the vdbe program was
  44139. ** successful or hit an 'OR FAIL' constraint. This means a commit
  44140. ** is required.
  44141. */
  44142. rc = vdbeCommit(db, p);
  44143. if( rc==SQLITE_BUSY ){
  44144. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  44145. return SQLITE_BUSY;
  44146. }else if( rc!=SQLITE_OK ){
  44147. p->rc = rc;
  44148. sqlite3RollbackAll(db);
  44149. }else{
  44150. sqlite3CommitInternalChanges(db);
  44151. }
  44152. }else{
  44153. sqlite3RollbackAll(db);
  44154. }
  44155. db->nStatement = 0;
  44156. }else if( eStatementOp==0 ){
  44157. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  44158. eStatementOp = SAVEPOINT_RELEASE;
  44159. }else if( p->errorAction==OE_Abort ){
  44160. eStatementOp = SAVEPOINT_ROLLBACK;
  44161. }else{
  44162. invalidateCursorsOnModifiedBtrees(db);
  44163. sqlite3RollbackAll(db);
  44164. sqlite3CloseSavepoints(db);
  44165. db->autoCommit = 1;
  44166. }
  44167. }
  44168. /* If eStatementOp is non-zero, then a statement transaction needs to
  44169. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  44170. ** do so. If this operation returns an error, and the current statement
  44171. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
  44172. ** code to the new value.
  44173. */
  44174. if( eStatementOp ){
  44175. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  44176. if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
  44177. p->rc = rc;
  44178. sqlite3DbFree(db, p->zErrMsg);
  44179. p->zErrMsg = 0;
  44180. }
  44181. }
  44182. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  44183. ** has been rolled back, update the database connection change-counter.
  44184. */
  44185. if( p->changeCntOn && p->pc>=0 ){
  44186. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  44187. sqlite3VdbeSetChanges(db, p->nChange);
  44188. }else{
  44189. sqlite3VdbeSetChanges(db, 0);
  44190. }
  44191. p->nChange = 0;
  44192. }
  44193. /* Rollback or commit any schema changes that occurred. */
  44194. if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
  44195. sqlite3ResetInternalSchema(db, 0);
  44196. db->flags = (db->flags | SQLITE_InternChanges);
  44197. }
  44198. /* Release the locks */
  44199. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  44200. }
  44201. /* We have successfully halted and closed the VM. Record this fact. */
  44202. if( p->pc>=0 ){
  44203. db->activeVdbeCnt--;
  44204. if( !p->readOnly ){
  44205. db->writeVdbeCnt--;
  44206. }
  44207. assert( db->activeVdbeCnt>=db->writeVdbeCnt );
  44208. }
  44209. p->magic = VDBE_MAGIC_HALT;
  44210. checkActiveVdbeCnt(db);
  44211. if( p->db->mallocFailed ){
  44212. p->rc = SQLITE_NOMEM;
  44213. }
  44214. /* If the auto-commit flag is set to true, then any locks that were held
  44215. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  44216. ** to invoke any required unlock-notify callbacks.
  44217. */
  44218. if( db->autoCommit ){
  44219. sqlite3ConnectionUnlocked(db);
  44220. }
  44221. assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
  44222. return SQLITE_OK;
  44223. }
  44224. /*
  44225. ** Each VDBE holds the result of the most recent sqlite3_step() call
  44226. ** in p->rc. This routine sets that result back to SQLITE_OK.
  44227. */
  44228. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  44229. p->rc = SQLITE_OK;
  44230. }
  44231. /*
  44232. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  44233. ** Write any error messages into *pzErrMsg. Return the result code.
  44234. **
  44235. ** After this routine is run, the VDBE should be ready to be executed
  44236. ** again.
  44237. **
  44238. ** To look at it another way, this routine resets the state of the
  44239. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  44240. ** VDBE_MAGIC_INIT.
  44241. */
  44242. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  44243. sqlite3 *db;
  44244. db = p->db;
  44245. /* If the VM did not run to completion or if it encountered an
  44246. ** error, then it might not have been halted properly. So halt
  44247. ** it now.
  44248. */
  44249. (void)sqlite3SafetyOn(db);
  44250. sqlite3VdbeHalt(p);
  44251. (void)sqlite3SafetyOff(db);
  44252. /* If the VDBE has be run even partially, then transfer the error code
  44253. ** and error message from the VDBE into the main database structure. But
  44254. ** if the VDBE has just been set to run but has not actually executed any
  44255. ** instructions yet, leave the main database error information unchanged.
  44256. */
  44257. if( p->pc>=0 ){
  44258. if( p->zErrMsg ){
  44259. sqlite3BeginBenignMalloc();
  44260. sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
  44261. sqlite3EndBenignMalloc();
  44262. db->errCode = p->rc;
  44263. sqlite3DbFree(db, p->zErrMsg);
  44264. p->zErrMsg = 0;
  44265. }else if( p->rc ){
  44266. sqlite3Error(db, p->rc, 0);
  44267. }else{
  44268. sqlite3Error(db, SQLITE_OK, 0);
  44269. }
  44270. }else if( p->rc && p->expired ){
  44271. /* The expired flag was set on the VDBE before the first call
  44272. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  44273. ** called), set the database error in this case as well.
  44274. */
  44275. sqlite3Error(db, p->rc, 0);
  44276. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  44277. sqlite3DbFree(db, p->zErrMsg);
  44278. p->zErrMsg = 0;
  44279. }
  44280. /* Reclaim all memory used by the VDBE
  44281. */
  44282. Cleanup(p);
  44283. /* Save profiling information from this VDBE run.
  44284. */
  44285. #ifdef VDBE_PROFILE
  44286. {
  44287. FILE *out = fopen("vdbe_profile.out", "a");
  44288. if( out ){
  44289. int i;
  44290. fprintf(out, "---- ");
  44291. for(i=0; i<p->nOp; i++){
  44292. fprintf(out, "%02x", p->aOp[i].opcode);
  44293. }
  44294. fprintf(out, "\n");
  44295. for(i=0; i<p->nOp; i++){
  44296. fprintf(out, "%6d %10lld %8lld ",
  44297. p->aOp[i].cnt,
  44298. p->aOp[i].cycles,
  44299. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  44300. );
  44301. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  44302. }
  44303. fclose(out);
  44304. }
  44305. }
  44306. #endif
  44307. p->magic = VDBE_MAGIC_INIT;
  44308. return p->rc & db->errMask;
  44309. }
  44310. /*
  44311. ** Clean up and delete a VDBE after execution. Return an integer which is
  44312. ** the result code. Write any error message text into *pzErrMsg.
  44313. */
  44314. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  44315. int rc = SQLITE_OK;
  44316. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  44317. rc = sqlite3VdbeReset(p);
  44318. assert( (rc & p->db->errMask)==rc );
  44319. }else if( p->magic!=VDBE_MAGIC_INIT ){
  44320. return SQLITE_MISUSE;
  44321. }
  44322. sqlite3VdbeDelete(p);
  44323. return rc;
  44324. }
  44325. /*
  44326. ** Call the destructor for each auxdata entry in pVdbeFunc for which
  44327. ** the corresponding bit in mask is clear. Auxdata entries beyond 31
  44328. ** are always destroyed. To destroy all auxdata entries, call this
  44329. ** routine with mask==0.
  44330. */
  44331. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  44332. int i;
  44333. for(i=0; i<pVdbeFunc->nAux; i++){
  44334. struct AuxData *pAux = &pVdbeFunc->apAux[i];
  44335. if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
  44336. if( pAux->xDelete ){
  44337. pAux->xDelete(pAux->pAux);
  44338. }
  44339. pAux->pAux = 0;
  44340. }
  44341. }
  44342. }
  44343. /*
  44344. ** Delete an entire VDBE.
  44345. */
  44346. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  44347. int i;
  44348. sqlite3 *db;
  44349. if( p==0 ) return;
  44350. db = p->db;
  44351. if( p->pPrev ){
  44352. p->pPrev->pNext = p->pNext;
  44353. }else{
  44354. assert( db->pVdbe==p );
  44355. db->pVdbe = p->pNext;
  44356. }
  44357. if( p->pNext ){
  44358. p->pNext->pPrev = p->pPrev;
  44359. }
  44360. if( p->aOp ){
  44361. Op *pOp = p->aOp;
  44362. for(i=0; i<p->nOp; i++, pOp++){
  44363. freeP4(db, pOp->p4type, pOp->p4.p);
  44364. #ifdef SQLITE_DEBUG
  44365. sqlite3DbFree(db, pOp->zComment);
  44366. #endif
  44367. }
  44368. }
  44369. releaseMemArray(p->aVar, p->nVar);
  44370. sqlite3DbFree(db, p->aLabel);
  44371. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  44372. sqlite3DbFree(db, p->aColName);
  44373. sqlite3DbFree(db, p->zSql);
  44374. p->magic = VDBE_MAGIC_DEAD;
  44375. sqlite3DbFree(db, p->aOp);
  44376. sqlite3DbFree(db, p->pFree);
  44377. sqlite3DbFree(db, p);
  44378. }
  44379. /*
  44380. ** If a MoveTo operation is pending on the given cursor, then do that
  44381. ** MoveTo now. Return an error code. If no MoveTo is pending, this
  44382. ** routine does nothing and returns SQLITE_OK.
  44383. */
  44384. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  44385. if( p->deferredMoveto ){
  44386. int res, rc;
  44387. #ifdef SQLITE_TEST
  44388. extern int sqlite3_search_count;
  44389. #endif
  44390. assert( p->isTable );
  44391. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  44392. if( rc ) return rc;
  44393. p->lastRowid = keyToInt(p->movetoTarget);
  44394. p->rowidIsValid = res==0 ?1:0;
  44395. if( res<0 ){
  44396. rc = sqlite3BtreeNext(p->pCursor, &res);
  44397. if( rc ) return rc;
  44398. }
  44399. #ifdef SQLITE_TEST
  44400. sqlite3_search_count++;
  44401. #endif
  44402. p->deferredMoveto = 0;
  44403. p->cacheStatus = CACHE_STALE;
  44404. }else if( p->pCursor ){
  44405. int hasMoved;
  44406. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  44407. if( rc ) return rc;
  44408. if( hasMoved ){
  44409. p->cacheStatus = CACHE_STALE;
  44410. p->nullRow = 1;
  44411. }
  44412. }
  44413. return SQLITE_OK;
  44414. }
  44415. /*
  44416. ** The following functions:
  44417. **
  44418. ** sqlite3VdbeSerialType()
  44419. ** sqlite3VdbeSerialTypeLen()
  44420. ** sqlite3VdbeSerialLen()
  44421. ** sqlite3VdbeSerialPut()
  44422. ** sqlite3VdbeSerialGet()
  44423. **
  44424. ** encapsulate the code that serializes values for storage in SQLite
  44425. ** data and index records. Each serialized value consists of a
  44426. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  44427. ** integer, stored as a varint.
  44428. **
  44429. ** In an SQLite index record, the serial type is stored directly before
  44430. ** the blob of data that it corresponds to. In a table record, all serial
  44431. ** types are stored at the start of the record, and the blobs of data at
  44432. ** the end. Hence these functions allow the caller to handle the
  44433. ** serial-type and data blob seperately.
  44434. **
  44435. ** The following table describes the various storage classes for data:
  44436. **
  44437. ** serial type bytes of data type
  44438. ** -------------- --------------- ---------------
  44439. ** 0 0 NULL
  44440. ** 1 1 signed integer
  44441. ** 2 2 signed integer
  44442. ** 3 3 signed integer
  44443. ** 4 4 signed integer
  44444. ** 5 6 signed integer
  44445. ** 6 8 signed integer
  44446. ** 7 8 IEEE float
  44447. ** 8 0 Integer constant 0
  44448. ** 9 0 Integer constant 1
  44449. ** 10,11 reserved for expansion
  44450. ** N>=12 and even (N-12)/2 BLOB
  44451. ** N>=13 and odd (N-13)/2 text
  44452. **
  44453. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  44454. ** of SQLite will not understand those serial types.
  44455. */
  44456. /*
  44457. ** Return the serial-type for the value stored in pMem.
  44458. */
  44459. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  44460. int flags = pMem->flags;
  44461. int n;
  44462. if( flags&MEM_Null ){
  44463. return 0;
  44464. }
  44465. if( flags&MEM_Int ){
  44466. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  44467. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  44468. i64 i = pMem->u.i;
  44469. u64 u;
  44470. if( file_format>=4 && (i&1)==i ){
  44471. return 8+(u32)i;
  44472. }
  44473. u = i<0 ? -i : i;
  44474. if( u<=127 ) return 1;
  44475. if( u<=32767 ) return 2;
  44476. if( u<=8388607 ) return 3;
  44477. if( u<=2147483647 ) return 4;
  44478. if( u<=MAX_6BYTE ) return 5;
  44479. return 6;
  44480. }
  44481. if( flags&MEM_Real ){
  44482. return 7;
  44483. }
  44484. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  44485. n = pMem->n;
  44486. if( flags & MEM_Zero ){
  44487. n += pMem->u.nZero;
  44488. }
  44489. assert( n>=0 );
  44490. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  44491. }
  44492. /*
  44493. ** Return the length of the data corresponding to the supplied serial-type.
  44494. */
  44495. SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
  44496. if( serial_type>=12 ){
  44497. return (serial_type-12)/2;
  44498. }else{
  44499. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  44500. return aSize[serial_type];
  44501. }
  44502. }
  44503. /*
  44504. ** If we are on an architecture with mixed-endian floating
  44505. ** points (ex: ARM7) then swap the lower 4 bytes with the
  44506. ** upper 4 bytes. Return the result.
  44507. **
  44508. ** For most architectures, this is a no-op.
  44509. **
  44510. ** (later): It is reported to me that the mixed-endian problem
  44511. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  44512. ** that early versions of GCC stored the two words of a 64-bit
  44513. ** float in the wrong order. And that error has been propagated
  44514. ** ever since. The blame is not necessarily with GCC, though.
  44515. ** GCC might have just copying the problem from a prior compiler.
  44516. ** I am also told that newer versions of GCC that follow a different
  44517. ** ABI get the byte order right.
  44518. **
  44519. ** Developers using SQLite on an ARM7 should compile and run their
  44520. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  44521. ** enabled, some asserts below will ensure that the byte order of
  44522. ** floating point values is correct.
  44523. **
  44524. ** (2007-08-30) Frank van Vugt has studied this problem closely
  44525. ** and has send his findings to the SQLite developers. Frank
  44526. ** writes that some Linux kernels offer floating point hardware
  44527. ** emulation that uses only 32-bit mantissas instead of a full
  44528. ** 48-bits as required by the IEEE standard. (This is the
  44529. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  44530. ** byte swapping becomes very complicated. To avoid problems,
  44531. ** the necessary byte swapping is carried out using a 64-bit integer
  44532. ** rather than a 64-bit float. Frank assures us that the code here
  44533. ** works for him. We, the developers, have no way to independently
  44534. ** verify this, but Frank seems to know what he is talking about
  44535. ** so we trust him.
  44536. */
  44537. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  44538. static u64 floatSwap(u64 in){
  44539. union {
  44540. u64 r;
  44541. u32 i[2];
  44542. } u;
  44543. u32 t;
  44544. u.r = in;
  44545. t = u.i[0];
  44546. u.i[0] = u.i[1];
  44547. u.i[1] = t;
  44548. return u.r;
  44549. }
  44550. # define swapMixedEndianFloat(X) X = floatSwap(X)
  44551. #else
  44552. # define swapMixedEndianFloat(X)
  44553. #endif
  44554. /*
  44555. ** Write the serialized data blob for the value stored in pMem into
  44556. ** buf. It is assumed that the caller has allocated sufficient space.
  44557. ** Return the number of bytes written.
  44558. **
  44559. ** nBuf is the amount of space left in buf[]. nBuf must always be
  44560. ** large enough to hold the entire field. Except, if the field is
  44561. ** a blob with a zero-filled tail, then buf[] might be just the right
  44562. ** size to hold everything except for the zero-filled tail. If buf[]
  44563. ** is only big enough to hold the non-zero prefix, then only write that
  44564. ** prefix into buf[]. But if buf[] is large enough to hold both the
  44565. ** prefix and the tail then write the prefix and set the tail to all
  44566. ** zeros.
  44567. **
  44568. ** Return the number of bytes actually written into buf[]. The number
  44569. ** of bytes in the zero-filled tail is included in the return value only
  44570. ** if those bytes were zeroed in buf[].
  44571. */
  44572. SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  44573. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  44574. int len;
  44575. /* Integer and Real */
  44576. if( serial_type<=7 && serial_type>0 ){
  44577. u64 v;
  44578. int i;
  44579. if( serial_type==7 ){
  44580. assert( sizeof(v)==sizeof(pMem->r) );
  44581. memcpy(&v, &pMem->r, sizeof(v));
  44582. swapMixedEndianFloat(v);
  44583. }else{
  44584. v = pMem->u.i;
  44585. }
  44586. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  44587. assert( len<=nBuf );
  44588. while( i-- ){
  44589. buf[i] = (u8)(v&0xFF);
  44590. v >>= 8;
  44591. }
  44592. return len;
  44593. }
  44594. /* String or blob */
  44595. if( serial_type>=12 ){
  44596. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  44597. == sqlite3VdbeSerialTypeLen(serial_type) );
  44598. assert( pMem->n<=nBuf );
  44599. len = pMem->n;
  44600. memcpy(buf, pMem->z, len);
  44601. if( pMem->flags & MEM_Zero ){
  44602. len += pMem->u.nZero;
  44603. if( len>nBuf ){
  44604. len = nBuf;
  44605. }
  44606. memset(&buf[pMem->n], 0, len-pMem->n);
  44607. }
  44608. return len;
  44609. }
  44610. /* NULL or constants 0 or 1 */
  44611. return 0;
  44612. }
  44613. /*
  44614. ** Deserialize the data blob pointed to by buf as serial type serial_type
  44615. ** and store the result in pMem. Return the number of bytes read.
  44616. */
  44617. SQLITE_PRIVATE int sqlite3VdbeSerialGet(
  44618. const unsigned char *buf, /* Buffer to deserialize from */
  44619. u32 serial_type, /* Serial type to deserialize */
  44620. Mem *pMem /* Memory cell to write value into */
  44621. ){
  44622. switch( serial_type ){
  44623. case 10: /* Reserved for future use */
  44624. case 11: /* Reserved for future use */
  44625. case 0: { /* NULL */
  44626. pMem->flags = MEM_Null;
  44627. break;
  44628. }
  44629. case 1: { /* 1-byte signed integer */
  44630. pMem->u.i = (signed char)buf[0];
  44631. pMem->flags = MEM_Int;
  44632. return 1;
  44633. }
  44634. case 2: { /* 2-byte signed integer */
  44635. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  44636. pMem->flags = MEM_Int;
  44637. return 2;
  44638. }
  44639. case 3: { /* 3-byte signed integer */
  44640. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  44641. pMem->flags = MEM_Int;
  44642. return 3;
  44643. }
  44644. case 4: { /* 4-byte signed integer */
  44645. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  44646. pMem->flags = MEM_Int;
  44647. return 4;
  44648. }
  44649. case 5: { /* 6-byte signed integer */
  44650. u64 x = (((signed char)buf[0])<<8) | buf[1];
  44651. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  44652. x = (x<<32) | y;
  44653. pMem->u.i = *(i64*)&x;
  44654. pMem->flags = MEM_Int;
  44655. return 6;
  44656. }
  44657. case 6: /* 8-byte signed integer */
  44658. case 7: { /* IEEE floating point */
  44659. u64 x;
  44660. u32 y;
  44661. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  44662. /* Verify that integers and floating point values use the same
  44663. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  44664. ** defined that 64-bit floating point values really are mixed
  44665. ** endian.
  44666. */
  44667. static const u64 t1 = ((u64)0x3ff00000)<<32;
  44668. static const double r1 = 1.0;
  44669. u64 t2 = t1;
  44670. swapMixedEndianFloat(t2);
  44671. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  44672. #endif
  44673. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  44674. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  44675. x = (x<<32) | y;
  44676. if( serial_type==6 ){
  44677. pMem->u.i = *(i64*)&x;
  44678. pMem->flags = MEM_Int;
  44679. }else{
  44680. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  44681. swapMixedEndianFloat(x);
  44682. memcpy(&pMem->r, &x, sizeof(x));
  44683. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  44684. }
  44685. return 8;
  44686. }
  44687. case 8: /* Integer 0 */
  44688. case 9: { /* Integer 1 */
  44689. pMem->u.i = serial_type-8;
  44690. pMem->flags = MEM_Int;
  44691. return 0;
  44692. }
  44693. default: {
  44694. int len = (serial_type-12)/2;
  44695. pMem->z = (char *)buf;
  44696. pMem->n = len;
  44697. pMem->xDel = 0;
  44698. if( serial_type&0x01 ){
  44699. pMem->flags = MEM_Str | MEM_Ephem;
  44700. }else{
  44701. pMem->flags = MEM_Blob | MEM_Ephem;
  44702. }
  44703. return len;
  44704. }
  44705. }
  44706. return 0;
  44707. }
  44708. /*
  44709. ** Given the nKey-byte encoding of a record in pKey[], parse the
  44710. ** record into a UnpackedRecord structure. Return a pointer to
  44711. ** that structure.
  44712. **
  44713. ** The calling function might provide szSpace bytes of memory
  44714. ** space at pSpace. This space can be used to hold the returned
  44715. ** VDbeParsedRecord structure if it is large enough. If it is
  44716. ** not big enough, space is obtained from sqlite3_malloc().
  44717. **
  44718. ** The returned structure should be closed by a call to
  44719. ** sqlite3VdbeDeleteUnpackedRecord().
  44720. */
  44721. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
  44722. KeyInfo *pKeyInfo, /* Information about the record format */
  44723. int nKey, /* Size of the binary record */
  44724. const void *pKey, /* The binary record */
  44725. char *pSpace, /* Unaligned space available to hold the object */
  44726. int szSpace /* Size of pSpace[] in bytes */
  44727. ){
  44728. const unsigned char *aKey = (const unsigned char *)pKey;
  44729. UnpackedRecord *p; /* The unpacked record that we will return */
  44730. int nByte; /* Memory space needed to hold p, in bytes */
  44731. int d;
  44732. u32 idx;
  44733. u16 u; /* Unsigned loop counter */
  44734. u32 szHdr;
  44735. Mem *pMem;
  44736. int nOff; /* Increase pSpace by this much to 8-byte align it */
  44737. /*
  44738. ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
  44739. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  44740. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  44741. */
  44742. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  44743. pSpace += nOff;
  44744. szSpace -= nOff;
  44745. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  44746. if( nByte>szSpace ){
  44747. p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  44748. if( p==0 ) return 0;
  44749. p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
  44750. }else{
  44751. p = (UnpackedRecord*)pSpace;
  44752. p->flags = UNPACKED_NEED_DESTROY;
  44753. }
  44754. p->pKeyInfo = pKeyInfo;
  44755. p->nField = pKeyInfo->nField + 1;
  44756. p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  44757. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  44758. idx = getVarint32(aKey, szHdr);
  44759. d = szHdr;
  44760. u = 0;
  44761. while( idx<szHdr && u<p->nField ){
  44762. u32 serial_type;
  44763. idx += getVarint32(&aKey[idx], serial_type);
  44764. if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
  44765. pMem->enc = pKeyInfo->enc;
  44766. pMem->db = pKeyInfo->db;
  44767. pMem->flags = 0;
  44768. pMem->zMalloc = 0;
  44769. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  44770. pMem++;
  44771. u++;
  44772. }
  44773. assert( u<=pKeyInfo->nField + 1 );
  44774. p->nField = u;
  44775. return (void*)p;
  44776. }
  44777. /*
  44778. ** This routine destroys a UnpackedRecord object
  44779. */
  44780. SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
  44781. if( p ){
  44782. if( p->flags & UNPACKED_NEED_DESTROY ){
  44783. int i;
  44784. Mem *pMem;
  44785. for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
  44786. if( pMem->zMalloc ){
  44787. sqlite3VdbeMemRelease(pMem);
  44788. }
  44789. }
  44790. }
  44791. if( p->flags & UNPACKED_NEED_FREE ){
  44792. sqlite3DbFree(p->pKeyInfo->db, p);
  44793. }
  44794. }
  44795. }
  44796. /*
  44797. ** This function compares the two table rows or index records
  44798. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  44799. ** or positive integer if key1 is less than, equal to or
  44800. ** greater than key2. The {nKey1, pKey1} key must be a blob
  44801. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  44802. ** key must be a parsed key such as obtained from
  44803. ** sqlite3VdbeParseRecord.
  44804. **
  44805. ** Key1 and Key2 do not have to contain the same number of fields.
  44806. ** The key with fewer fields is usually compares less than the
  44807. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  44808. ** and the common prefixes are equal, then key1 is less than key2.
  44809. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  44810. ** equal, then the keys are considered to be equal and
  44811. ** the parts beyond the common prefix are ignored.
  44812. **
  44813. ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
  44814. ** the header of pKey1 is ignored. It is assumed that pKey1 is
  44815. ** an index key, and thus ends with a rowid value. The last byte
  44816. ** of the header will therefore be the serial type of the rowid:
  44817. ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
  44818. ** The serial type of the final rowid will always be a single byte.
  44819. ** By ignoring this last byte of the header, we force the comparison
  44820. ** to ignore the rowid at the end of key1.
  44821. */
  44822. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  44823. int nKey1, const void *pKey1, /* Left key */
  44824. UnpackedRecord *pPKey2 /* Right key */
  44825. ){
  44826. int d1; /* Offset into aKey[] of next data element */
  44827. u32 idx1; /* Offset into aKey[] of next header element */
  44828. u32 szHdr1; /* Number of bytes in header */
  44829. int i = 0;
  44830. int nField;
  44831. int rc = 0;
  44832. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  44833. KeyInfo *pKeyInfo;
  44834. Mem mem1;
  44835. pKeyInfo = pPKey2->pKeyInfo;
  44836. mem1.enc = pKeyInfo->enc;
  44837. mem1.db = pKeyInfo->db;
  44838. mem1.flags = 0;
  44839. mem1.zMalloc = 0;
  44840. idx1 = getVarint32(aKey1, szHdr1);
  44841. d1 = szHdr1;
  44842. if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
  44843. szHdr1--;
  44844. }
  44845. nField = pKeyInfo->nField;
  44846. while( idx1<szHdr1 && i<pPKey2->nField ){
  44847. u32 serial_type1;
  44848. /* Read the serial types for the next element in each key. */
  44849. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  44850. if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
  44851. /* Extract the values to be compared.
  44852. */
  44853. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  44854. /* Do the comparison
  44855. */
  44856. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  44857. i<nField ? pKeyInfo->aColl[i] : 0);
  44858. if( rc!=0 ){
  44859. break;
  44860. }
  44861. i++;
  44862. }
  44863. if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
  44864. if( rc==0 ){
  44865. /* rc==0 here means that one of the keys ran out of fields and
  44866. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  44867. ** flag is set, then break the tie by treating key2 as larger.
  44868. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  44869. ** are considered to be equal. Otherwise, the longer key is the
  44870. ** larger. As it happens, the pPKey2 will always be the longer
  44871. ** if there is a difference.
  44872. */
  44873. if( pPKey2->flags & UNPACKED_INCRKEY ){
  44874. rc = -1;
  44875. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  44876. /* Leave rc==0 */
  44877. }else if( idx1<szHdr1 ){
  44878. rc = 1;
  44879. }
  44880. }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
  44881. && pKeyInfo->aSortOrder[i] ){
  44882. rc = -rc;
  44883. }
  44884. return rc;
  44885. }
  44886. /*
  44887. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  44888. ** Read the rowid (the last field in the record) and store it in *rowid.
  44889. ** Return SQLITE_OK if everything works, or an error code otherwise.
  44890. **
  44891. ** pCur might be pointing to text obtained from a corrupt database file.
  44892. ** So the content cannot be trusted. Do appropriate checks on the content.
  44893. */
  44894. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
  44895. i64 nCellKey = 0;
  44896. int rc;
  44897. u32 szHdr; /* Size of the header */
  44898. u32 typeRowid; /* Serial type of the rowid */
  44899. u32 lenRowid; /* Size of the rowid */
  44900. Mem m, v;
  44901. /* Get the size of the index entry. Only indices entries of less
  44902. ** than 2GiB are support - anything large must be database corruption */
  44903. sqlite3BtreeKeySize(pCur, &nCellKey);
  44904. if( unlikely(nCellKey<=0 || nCellKey>0x7fffffff) ){
  44905. return SQLITE_CORRUPT_BKPT;
  44906. }
  44907. /* Read in the complete content of the index entry */
  44908. m.flags = 0;
  44909. m.db = 0;
  44910. m.zMalloc = 0;
  44911. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  44912. if( rc ){
  44913. return rc;
  44914. }
  44915. /* The index entry must begin with a header size */
  44916. (void)getVarint32((u8*)m.z, szHdr);
  44917. testcase( szHdr==2 );
  44918. testcase( szHdr==m.n );
  44919. if( unlikely(szHdr<2 || (int)szHdr>m.n) ){
  44920. goto idx_rowid_corruption;
  44921. }
  44922. /* The last field of the index should be an integer - the ROWID.
  44923. ** Verify that the last entry really is an integer. */
  44924. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  44925. testcase( typeRowid==1 );
  44926. testcase( typeRowid==2 );
  44927. testcase( typeRowid==3 );
  44928. testcase( typeRowid==4 );
  44929. testcase( typeRowid==5 );
  44930. testcase( typeRowid==6 );
  44931. testcase( typeRowid==8 );
  44932. testcase( typeRowid==9 );
  44933. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  44934. goto idx_rowid_corruption;
  44935. }
  44936. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  44937. testcase( m.n-lenRowid==szHdr );
  44938. if( unlikely(m.n-lenRowid<szHdr) ){
  44939. goto idx_rowid_corruption;
  44940. }
  44941. /* Fetch the integer off the end of the index record */
  44942. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  44943. *rowid = v.u.i;
  44944. sqlite3VdbeMemRelease(&m);
  44945. return SQLITE_OK;
  44946. /* Jump here if database corruption is detected after m has been
  44947. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  44948. idx_rowid_corruption:
  44949. testcase( m.zMalloc!=0 );
  44950. sqlite3VdbeMemRelease(&m);
  44951. return SQLITE_CORRUPT_BKPT;
  44952. }
  44953. /*
  44954. ** Compare the key of the index entry that cursor pC is point to against
  44955. ** the key string in pKey (of length nKey). Write into *pRes a number
  44956. ** that is negative, zero, or positive if pC is less than, equal to,
  44957. ** or greater than pKey. Return SQLITE_OK on success.
  44958. **
  44959. ** pKey is either created without a rowid or is truncated so that it
  44960. ** omits the rowid at the end. The rowid at the end of the index entry
  44961. ** is ignored as well. Hence, this routine only compares the prefixes
  44962. ** of the keys prior to the final rowid, not the entire key.
  44963. **
  44964. ** pUnpacked may be an unpacked version of pKey,nKey. If pUnpacked is
  44965. ** supplied it is used in place of pKey,nKey.
  44966. */
  44967. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  44968. VdbeCursor *pC, /* The cursor to compare against */
  44969. UnpackedRecord *pUnpacked, /* Unpacked version of pKey and nKey */
  44970. int *res /* Write the comparison result here */
  44971. ){
  44972. i64 nCellKey = 0;
  44973. int rc;
  44974. BtCursor *pCur = pC->pCursor;
  44975. Mem m;
  44976. sqlite3BtreeKeySize(pCur, &nCellKey);
  44977. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  44978. *res = 0;
  44979. return SQLITE_OK;
  44980. }
  44981. m.db = 0;
  44982. m.flags = 0;
  44983. m.zMalloc = 0;
  44984. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  44985. if( rc ){
  44986. return rc;
  44987. }
  44988. assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
  44989. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  44990. sqlite3VdbeMemRelease(&m);
  44991. return SQLITE_OK;
  44992. }
  44993. /*
  44994. ** This routine sets the value to be returned by subsequent calls to
  44995. ** sqlite3_changes() on the database handle 'db'.
  44996. */
  44997. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  44998. assert( sqlite3_mutex_held(db->mutex) );
  44999. db->nChange = nChange;
  45000. db->nTotalChange += nChange;
  45001. }
  45002. /*
  45003. ** Set a flag in the vdbe to update the change counter when it is finalised
  45004. ** or reset.
  45005. */
  45006. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  45007. v->changeCntOn = 1;
  45008. }
  45009. /*
  45010. ** Mark every prepared statement associated with a database connection
  45011. ** as expired.
  45012. **
  45013. ** An expired statement means that recompilation of the statement is
  45014. ** recommend. Statements expire when things happen that make their
  45015. ** programs obsolete. Removing user-defined functions or collating
  45016. ** sequences, or changing an authorization function are the types of
  45017. ** things that make prepared statements obsolete.
  45018. */
  45019. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  45020. Vdbe *p;
  45021. for(p = db->pVdbe; p; p=p->pNext){
  45022. p->expired = 1;
  45023. }
  45024. }
  45025. /*
  45026. ** Return the database associated with the Vdbe.
  45027. */
  45028. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  45029. return v->db;
  45030. }
  45031. /************** End of vdbeaux.c *********************************************/
  45032. /************** Begin file vdbeapi.c *****************************************/
  45033. /*
  45034. ** 2004 May 26
  45035. **
  45036. ** The author disclaims copyright to this source code. In place of
  45037. ** a legal notice, here is a blessing:
  45038. **
  45039. ** May you do good and not evil.
  45040. ** May you find forgiveness for yourself and forgive others.
  45041. ** May you share freely, never taking more than you give.
  45042. **
  45043. *************************************************************************
  45044. **
  45045. ** This file contains code use to implement APIs that are part of the
  45046. ** VDBE.
  45047. **
  45048. ** $Id: vdbeapi.c,v 1.161 2009/04/10 23:11:31 drh Exp $
  45049. */
  45050. #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  45051. /*
  45052. ** The following structure contains pointers to the end points of a
  45053. ** doubly-linked list of all compiled SQL statements that may be holding
  45054. ** buffers eligible for release when the sqlite3_release_memory() interface is
  45055. ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
  45056. ** mutex.
  45057. **
  45058. ** Statements are added to the end of this list when sqlite3_reset() is
  45059. ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
  45060. ** is called. When statements are added to this list, the associated
  45061. ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
  45062. ** can be freed using sqlite3VdbeReleaseMemory().
  45063. **
  45064. ** When statements are added or removed from this list, the mutex
  45065. ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
  45066. ** already held. The LRU2 mutex is then obtained, blocking if necessary,
  45067. ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
  45068. */
  45069. struct StatementLruList {
  45070. Vdbe *pFirst;
  45071. Vdbe *pLast;
  45072. };
  45073. static struct StatementLruList sqlite3LruStatements;
  45074. /*
  45075. ** Check that the list looks to be internally consistent. This is used
  45076. ** as part of an assert() statement as follows:
  45077. **
  45078. ** assert( stmtLruCheck() );
  45079. */
  45080. #ifndef NDEBUG
  45081. static int stmtLruCheck(){
  45082. Vdbe *p;
  45083. for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
  45084. assert(p->pLruNext || p==sqlite3LruStatements.pLast);
  45085. assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
  45086. assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
  45087. assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
  45088. }
  45089. return 1;
  45090. }
  45091. #endif
  45092. /*
  45093. ** Add vdbe p to the end of the statement lru list. It is assumed that
  45094. ** p is not already part of the list when this is called. The lru list
  45095. ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
  45096. */
  45097. static void stmtLruAdd(Vdbe *p){
  45098. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45099. if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
  45100. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45101. return;
  45102. }
  45103. assert( stmtLruCheck() );
  45104. if( !sqlite3LruStatements.pFirst ){
  45105. assert( !sqlite3LruStatements.pLast );
  45106. sqlite3LruStatements.pFirst = p;
  45107. sqlite3LruStatements.pLast = p;
  45108. }else{
  45109. assert( !sqlite3LruStatements.pLast->pLruNext );
  45110. p->pLruPrev = sqlite3LruStatements.pLast;
  45111. sqlite3LruStatements.pLast->pLruNext = p;
  45112. sqlite3LruStatements.pLast = p;
  45113. }
  45114. assert( stmtLruCheck() );
  45115. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45116. }
  45117. /*
  45118. ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
  45119. ** statement p from the least-recently-used statement list. If the
  45120. ** statement is not currently part of the list, this call is a no-op.
  45121. */
  45122. static void stmtLruRemoveNomutex(Vdbe *p){
  45123. if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
  45124. assert( stmtLruCheck() );
  45125. if( p->pLruNext ){
  45126. p->pLruNext->pLruPrev = p->pLruPrev;
  45127. }else{
  45128. sqlite3LruStatements.pLast = p->pLruPrev;
  45129. }
  45130. if( p->pLruPrev ){
  45131. p->pLruPrev->pLruNext = p->pLruNext;
  45132. }else{
  45133. sqlite3LruStatements.pFirst = p->pLruNext;
  45134. }
  45135. p->pLruNext = 0;
  45136. p->pLruPrev = 0;
  45137. assert( stmtLruCheck() );
  45138. }
  45139. }
  45140. /*
  45141. ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
  45142. ** statement p from the least-recently-used statement list. If the
  45143. ** statement is not currently part of the list, this call is a no-op.
  45144. */
  45145. static void stmtLruRemove(Vdbe *p){
  45146. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45147. stmtLruRemoveNomutex(p);
  45148. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45149. }
  45150. /*
  45151. ** Try to release n bytes of memory by freeing buffers associated
  45152. ** with the memory registers of currently unused vdbes.
  45153. */
  45154. SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
  45155. Vdbe *p;
  45156. Vdbe *pNext;
  45157. int nFree = 0;
  45158. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45159. for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
  45160. pNext = p->pLruNext;
  45161. /* For each statement handle in the lru list, attempt to obtain the
  45162. ** associated database mutex. If it cannot be obtained, continue
  45163. ** to the next statement handle. It is not possible to block on
  45164. ** the database mutex - that could cause deadlock.
  45165. */
  45166. if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
  45167. nFree += sqlite3VdbeReleaseBuffers(p);
  45168. stmtLruRemoveNomutex(p);
  45169. sqlite3_mutex_leave(p->db->mutex);
  45170. }
  45171. }
  45172. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
  45173. return nFree;
  45174. }
  45175. /*
  45176. ** Call sqlite3Reprepare() on the statement. Remove it from the
  45177. ** lru list before doing so, as Reprepare() will free all the
  45178. ** memory register buffers anyway.
  45179. */
  45180. int vdbeReprepare(Vdbe *p){
  45181. stmtLruRemove(p);
  45182. return sqlite3Reprepare(p);
  45183. }
  45184. #else /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
  45185. #define stmtLruRemove(x)
  45186. #define stmtLruAdd(x)
  45187. #define vdbeReprepare(x) sqlite3Reprepare(x)
  45188. #endif
  45189. #ifndef SQLITE_OMIT_DEPRECATED
  45190. /*
  45191. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  45192. ** to be recompiled. A statement needs to be recompiled whenever the
  45193. ** execution environment changes in a way that would alter the program
  45194. ** that sqlite3_prepare() generates. For example, if new functions or
  45195. ** collating sequences are registered or if an authorizer function is
  45196. ** added or changed.
  45197. */
  45198. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  45199. Vdbe *p = (Vdbe*)pStmt;
  45200. return p==0 || p->expired;
  45201. }
  45202. #endif
  45203. /*
  45204. ** The following routine destroys a virtual machine that is created by
  45205. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  45206. ** success/failure code that describes the result of executing the virtual
  45207. ** machine.
  45208. **
  45209. ** This routine sets the error code and string returned by
  45210. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  45211. */
  45212. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  45213. int rc;
  45214. if( pStmt==0 ){
  45215. rc = SQLITE_OK;
  45216. }else{
  45217. Vdbe *v = (Vdbe*)pStmt;
  45218. sqlite3 *db = v->db;
  45219. #if SQLITE_THREADSAFE
  45220. sqlite3_mutex *mutex = v->db->mutex;
  45221. #endif
  45222. sqlite3_mutex_enter(mutex);
  45223. stmtLruRemove(v);
  45224. rc = sqlite3VdbeFinalize(v);
  45225. rc = sqlite3ApiExit(db, rc);
  45226. sqlite3_mutex_leave(mutex);
  45227. }
  45228. return rc;
  45229. }
  45230. /*
  45231. ** Terminate the current execution of an SQL statement and reset it
  45232. ** back to its starting state so that it can be reused. A success code from
  45233. ** the prior execution is returned.
  45234. **
  45235. ** This routine sets the error code and string returned by
  45236. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  45237. */
  45238. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  45239. int rc;
  45240. if( pStmt==0 ){
  45241. rc = SQLITE_OK;
  45242. }else{
  45243. Vdbe *v = (Vdbe*)pStmt;
  45244. sqlite3_mutex_enter(v->db->mutex);
  45245. rc = sqlite3VdbeReset(v);
  45246. stmtLruAdd(v);
  45247. sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
  45248. assert( (rc & (v->db->errMask))==rc );
  45249. rc = sqlite3ApiExit(v->db, rc);
  45250. sqlite3_mutex_leave(v->db->mutex);
  45251. }
  45252. return rc;
  45253. }
  45254. /*
  45255. ** Set all the parameters in the compiled SQL statement to NULL.
  45256. */
  45257. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  45258. int i;
  45259. int rc = SQLITE_OK;
  45260. Vdbe *p = (Vdbe*)pStmt;
  45261. #if SQLITE_THREADSAFE
  45262. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  45263. #endif
  45264. sqlite3_mutex_enter(mutex);
  45265. for(i=0; i<p->nVar; i++){
  45266. sqlite3VdbeMemRelease(&p->aVar[i]);
  45267. p->aVar[i].flags = MEM_Null;
  45268. }
  45269. sqlite3_mutex_leave(mutex);
  45270. return rc;
  45271. }
  45272. /**************************** sqlite3_value_ *******************************
  45273. ** The following routines extract information from a Mem or sqlite3_value
  45274. ** structure.
  45275. */
  45276. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  45277. Mem *p = (Mem*)pVal;
  45278. if( p->flags & (MEM_Blob|MEM_Str) ){
  45279. sqlite3VdbeMemExpandBlob(p);
  45280. p->flags &= ~MEM_Str;
  45281. p->flags |= MEM_Blob;
  45282. return p->z;
  45283. }else{
  45284. return sqlite3_value_text(pVal);
  45285. }
  45286. }
  45287. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  45288. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  45289. }
  45290. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  45291. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  45292. }
  45293. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  45294. return sqlite3VdbeRealValue((Mem*)pVal);
  45295. }
  45296. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  45297. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  45298. }
  45299. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  45300. return sqlite3VdbeIntValue((Mem*)pVal);
  45301. }
  45302. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  45303. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  45304. }
  45305. #ifndef SQLITE_OMIT_UTF16
  45306. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  45307. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  45308. }
  45309. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  45310. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  45311. }
  45312. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  45313. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  45314. }
  45315. #endif /* SQLITE_OMIT_UTF16 */
  45316. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  45317. return pVal->type;
  45318. }
  45319. /**************************** sqlite3_result_ *******************************
  45320. ** The following routines are used by user-defined functions to specify
  45321. ** the function result.
  45322. */
  45323. SQLITE_API void sqlite3_result_blob(
  45324. sqlite3_context *pCtx,
  45325. const void *z,
  45326. int n,
  45327. void (*xDel)(void *)
  45328. ){
  45329. assert( n>=0 );
  45330. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45331. sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
  45332. }
  45333. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  45334. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45335. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  45336. }
  45337. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  45338. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45339. pCtx->isError = SQLITE_ERROR;
  45340. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  45341. }
  45342. #ifndef SQLITE_OMIT_UTF16
  45343. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  45344. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45345. pCtx->isError = SQLITE_ERROR;
  45346. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  45347. }
  45348. #endif
  45349. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  45350. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45351. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  45352. }
  45353. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  45354. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45355. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  45356. }
  45357. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  45358. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45359. sqlite3VdbeMemSetNull(&pCtx->s);
  45360. }
  45361. SQLITE_API void sqlite3_result_text(
  45362. sqlite3_context *pCtx,
  45363. const char *z,
  45364. int n,
  45365. void (*xDel)(void *)
  45366. ){
  45367. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45368. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
  45369. }
  45370. #ifndef SQLITE_OMIT_UTF16
  45371. SQLITE_API void sqlite3_result_text16(
  45372. sqlite3_context *pCtx,
  45373. const void *z,
  45374. int n,
  45375. void (*xDel)(void *)
  45376. ){
  45377. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45378. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
  45379. }
  45380. SQLITE_API void sqlite3_result_text16be(
  45381. sqlite3_context *pCtx,
  45382. const void *z,
  45383. int n,
  45384. void (*xDel)(void *)
  45385. ){
  45386. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45387. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
  45388. }
  45389. SQLITE_API void sqlite3_result_text16le(
  45390. sqlite3_context *pCtx,
  45391. const void *z,
  45392. int n,
  45393. void (*xDel)(void *)
  45394. ){
  45395. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45396. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
  45397. }
  45398. #endif /* SQLITE_OMIT_UTF16 */
  45399. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  45400. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45401. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  45402. }
  45403. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  45404. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45405. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  45406. }
  45407. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  45408. pCtx->isError = errCode;
  45409. }
  45410. /* Force an SQLITE_TOOBIG error. */
  45411. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  45412. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45413. pCtx->isError = SQLITE_TOOBIG;
  45414. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  45415. SQLITE_UTF8, SQLITE_STATIC);
  45416. }
  45417. /* An SQLITE_NOMEM error. */
  45418. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  45419. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45420. sqlite3VdbeMemSetNull(&pCtx->s);
  45421. pCtx->isError = SQLITE_NOMEM;
  45422. pCtx->s.db->mallocFailed = 1;
  45423. }
  45424. /*
  45425. ** Execute the statement pStmt, either until a row of data is ready, the
  45426. ** statement is completely executed or an error occurs.
  45427. **
  45428. ** This routine implements the bulk of the logic behind the sqlite_step()
  45429. ** API. The only thing omitted is the automatic recompile if a
  45430. ** schema change has occurred. That detail is handled by the
  45431. ** outer sqlite3_step() wrapper procedure.
  45432. */
  45433. static int sqlite3Step(Vdbe *p){
  45434. sqlite3 *db;
  45435. int rc;
  45436. assert(p);
  45437. if( p->magic!=VDBE_MAGIC_RUN ){
  45438. return SQLITE_MISUSE;
  45439. }
  45440. /* Assert that malloc() has not failed */
  45441. db = p->db;
  45442. if( db->mallocFailed ){
  45443. return SQLITE_NOMEM;
  45444. }
  45445. if( p->pc<=0 && p->expired ){
  45446. if( ALWAYS(p->rc==SQLITE_OK) ){
  45447. p->rc = SQLITE_SCHEMA;
  45448. }
  45449. rc = SQLITE_ERROR;
  45450. goto end_of_step;
  45451. }
  45452. if( sqlite3SafetyOn(db) ){
  45453. p->rc = SQLITE_MISUSE;
  45454. return SQLITE_MISUSE;
  45455. }
  45456. if( p->pc<0 ){
  45457. /* If there are no other statements currently running, then
  45458. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  45459. ** from interrupting a statement that has not yet started.
  45460. */
  45461. if( db->activeVdbeCnt==0 ){
  45462. db->u1.isInterrupted = 0;
  45463. }
  45464. #ifndef SQLITE_OMIT_TRACE
  45465. if( db->xProfile && !db->init.busy ){
  45466. double rNow;
  45467. sqlite3OsCurrentTime(db->pVfs, &rNow);
  45468. p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
  45469. }
  45470. #endif
  45471. db->activeVdbeCnt++;
  45472. if( p->readOnly==0 ) db->writeVdbeCnt++;
  45473. p->pc = 0;
  45474. stmtLruRemove(p);
  45475. }
  45476. #ifndef SQLITE_OMIT_EXPLAIN
  45477. if( p->explain ){
  45478. rc = sqlite3VdbeList(p);
  45479. }else
  45480. #endif /* SQLITE_OMIT_EXPLAIN */
  45481. {
  45482. rc = sqlite3VdbeExec(p);
  45483. }
  45484. if( sqlite3SafetyOff(db) ){
  45485. rc = SQLITE_MISUSE;
  45486. }
  45487. #ifndef SQLITE_OMIT_TRACE
  45488. /* Invoke the profile callback if there is one
  45489. */
  45490. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  45491. double rNow;
  45492. u64 elapseTime;
  45493. sqlite3OsCurrentTime(db->pVfs, &rNow);
  45494. elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
  45495. elapseTime -= p->startTime;
  45496. db->xProfile(db->pProfileArg, p->zSql, elapseTime);
  45497. }
  45498. #endif
  45499. db->errCode = rc;
  45500. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  45501. p->rc = SQLITE_NOMEM;
  45502. }
  45503. end_of_step:
  45504. /* At this point local variable rc holds the value that should be
  45505. ** returned if this statement was compiled using the legacy
  45506. ** sqlite3_prepare() interface. According to the docs, this can only
  45507. ** be one of the values in the first assert() below. Variable p->rc
  45508. ** contains the value that would be returned if sqlite3_finalize()
  45509. ** were called on statement p.
  45510. */
  45511. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  45512. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  45513. );
  45514. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  45515. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  45516. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  45517. ** error has occured, then return the error code in p->rc to the
  45518. ** caller. Set the error code in the database handle to the same value.
  45519. */
  45520. rc = db->errCode = p->rc;
  45521. }
  45522. return (rc&db->errMask);
  45523. }
  45524. /*
  45525. ** This is the top-level implementation of sqlite3_step(). Call
  45526. ** sqlite3Step() to do most of the work. If a schema error occurs,
  45527. ** call sqlite3Reprepare() and try again.
  45528. */
  45529. #ifdef SQLITE_OMIT_PARSER
  45530. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  45531. int rc = SQLITE_MISUSE;
  45532. if( pStmt ){
  45533. Vdbe *v;
  45534. v = (Vdbe*)pStmt;
  45535. sqlite3_mutex_enter(v->db->mutex);
  45536. rc = sqlite3Step(v);
  45537. sqlite3_mutex_leave(v->db->mutex);
  45538. }
  45539. return rc;
  45540. }
  45541. #else
  45542. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  45543. int rc = SQLITE_MISUSE;
  45544. if( pStmt ){
  45545. int cnt = 0;
  45546. Vdbe *v = (Vdbe*)pStmt;
  45547. sqlite3 *db = v->db;
  45548. sqlite3_mutex_enter(db->mutex);
  45549. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  45550. && cnt++ < 5
  45551. && (rc = vdbeReprepare(v))==SQLITE_OK ){
  45552. sqlite3_reset(pStmt);
  45553. v->expired = 0;
  45554. }
  45555. if( rc==SQLITE_SCHEMA && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  45556. /* This case occurs after failing to recompile an sql statement.
  45557. ** The error message from the SQL compiler has already been loaded
  45558. ** into the database handle. This block copies the error message
  45559. ** from the database handle into the statement and sets the statement
  45560. ** program counter to 0 to ensure that when the statement is
  45561. ** finalized or reset the parser error message is available via
  45562. ** sqlite3_errmsg() and sqlite3_errcode().
  45563. */
  45564. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  45565. sqlite3DbFree(db, v->zErrMsg);
  45566. if( !db->mallocFailed ){
  45567. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  45568. } else {
  45569. v->zErrMsg = 0;
  45570. v->rc = SQLITE_NOMEM;
  45571. }
  45572. }
  45573. rc = sqlite3ApiExit(db, rc);
  45574. sqlite3_mutex_leave(db->mutex);
  45575. }
  45576. return rc;
  45577. }
  45578. #endif
  45579. /*
  45580. ** Extract the user data from a sqlite3_context structure and return a
  45581. ** pointer to it.
  45582. */
  45583. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  45584. assert( p && p->pFunc );
  45585. return p->pFunc->pUserData;
  45586. }
  45587. /*
  45588. ** Extract the user data from a sqlite3_context structure and return a
  45589. ** pointer to it.
  45590. */
  45591. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  45592. assert( p && p->pFunc );
  45593. return p->s.db;
  45594. }
  45595. /*
  45596. ** The following is the implementation of an SQL function that always
  45597. ** fails with an error message stating that the function is used in the
  45598. ** wrong context. The sqlite3_overload_function() API might construct
  45599. ** SQL function that use this routine so that the functions will exist
  45600. ** for name resolution but are actually overloaded by the xFindFunction
  45601. ** method of virtual tables.
  45602. */
  45603. SQLITE_PRIVATE void sqlite3InvalidFunction(
  45604. sqlite3_context *context, /* The function calling context */
  45605. int NotUsed, /* Number of arguments to the function */
  45606. sqlite3_value **NotUsed2 /* Value of each argument */
  45607. ){
  45608. const char *zName = context->pFunc->zName;
  45609. char *zErr;
  45610. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  45611. zErr = sqlite3_mprintf(
  45612. "unable to use function %s in the requested context", zName);
  45613. sqlite3_result_error(context, zErr, -1);
  45614. sqlite3_free(zErr);
  45615. }
  45616. /*
  45617. ** Allocate or return the aggregate context for a user function. A new
  45618. ** context is allocated on the first call. Subsequent calls return the
  45619. ** same context that was returned on prior calls.
  45620. */
  45621. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  45622. Mem *pMem;
  45623. assert( p && p->pFunc && p->pFunc->xStep );
  45624. assert( sqlite3_mutex_held(p->s.db->mutex) );
  45625. pMem = p->pMem;
  45626. if( (pMem->flags & MEM_Agg)==0 ){
  45627. if( nByte==0 ){
  45628. sqlite3VdbeMemReleaseExternal(pMem);
  45629. pMem->flags = MEM_Null;
  45630. pMem->z = 0;
  45631. }else{
  45632. sqlite3VdbeMemGrow(pMem, nByte, 0);
  45633. pMem->flags = MEM_Agg;
  45634. pMem->u.pDef = p->pFunc;
  45635. if( pMem->z ){
  45636. memset(pMem->z, 0, nByte);
  45637. }
  45638. }
  45639. }
  45640. return (void*)pMem->z;
  45641. }
  45642. /*
  45643. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  45644. ** the user-function defined by pCtx.
  45645. */
  45646. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  45647. VdbeFunc *pVdbeFunc;
  45648. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45649. pVdbeFunc = pCtx->pVdbeFunc;
  45650. if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
  45651. return 0;
  45652. }
  45653. return pVdbeFunc->apAux[iArg].pAux;
  45654. }
  45655. /*
  45656. ** Set the auxilary data pointer and delete function, for the iArg'th
  45657. ** argument to the user-function defined by pCtx. Any previous value is
  45658. ** deleted by calling the delete function specified when it was set.
  45659. */
  45660. SQLITE_API void sqlite3_set_auxdata(
  45661. sqlite3_context *pCtx,
  45662. int iArg,
  45663. void *pAux,
  45664. void (*xDelete)(void*)
  45665. ){
  45666. struct AuxData *pAuxData;
  45667. VdbeFunc *pVdbeFunc;
  45668. if( iArg<0 ) goto failed;
  45669. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  45670. pVdbeFunc = pCtx->pVdbeFunc;
  45671. if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
  45672. int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
  45673. int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
  45674. pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
  45675. if( !pVdbeFunc ){
  45676. goto failed;
  45677. }
  45678. pCtx->pVdbeFunc = pVdbeFunc;
  45679. memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
  45680. pVdbeFunc->nAux = iArg+1;
  45681. pVdbeFunc->pFunc = pCtx->pFunc;
  45682. }
  45683. pAuxData = &pVdbeFunc->apAux[iArg];
  45684. if( pAuxData->pAux && pAuxData->xDelete ){
  45685. pAuxData->xDelete(pAuxData->pAux);
  45686. }
  45687. pAuxData->pAux = pAux;
  45688. pAuxData->xDelete = xDelete;
  45689. return;
  45690. failed:
  45691. if( xDelete ){
  45692. xDelete(pAux);
  45693. }
  45694. }
  45695. #ifndef SQLITE_OMIT_DEPRECATED
  45696. /*
  45697. ** Return the number of times the Step function of a aggregate has been
  45698. ** called.
  45699. **
  45700. ** This function is deprecated. Do not use it for new code. It is
  45701. ** provide only to avoid breaking legacy code. New aggregate function
  45702. ** implementations should keep their own counts within their aggregate
  45703. ** context.
  45704. */
  45705. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  45706. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  45707. return p->pMem->n;
  45708. }
  45709. #endif
  45710. /*
  45711. ** Return the number of columns in the result set for the statement pStmt.
  45712. */
  45713. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  45714. Vdbe *pVm = (Vdbe *)pStmt;
  45715. return pVm ? pVm->nResColumn : 0;
  45716. }
  45717. /*
  45718. ** Return the number of values available from the current row of the
  45719. ** currently executing statement pStmt.
  45720. */
  45721. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  45722. Vdbe *pVm = (Vdbe *)pStmt;
  45723. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  45724. return pVm->nResColumn;
  45725. }
  45726. /*
  45727. ** Check to see if column iCol of the given statement is valid. If
  45728. ** it is, return a pointer to the Mem for the value of that column.
  45729. ** If iCol is not valid, return a pointer to a Mem which has a value
  45730. ** of NULL.
  45731. */
  45732. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  45733. Vdbe *pVm;
  45734. int vals;
  45735. Mem *pOut;
  45736. pVm = (Vdbe *)pStmt;
  45737. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  45738. sqlite3_mutex_enter(pVm->db->mutex);
  45739. vals = sqlite3_data_count(pStmt);
  45740. pOut = &pVm->pResultSet[i];
  45741. }else{
  45742. /* ((double)0) In case of SQLITE_OMIT_FLOATING_POINT... */
  45743. static const Mem nullMem = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
  45744. if( pVm && ALWAYS(pVm->db) ){
  45745. sqlite3_mutex_enter(pVm->db->mutex);
  45746. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  45747. }
  45748. pOut = (Mem*)&nullMem;
  45749. }
  45750. return pOut;
  45751. }
  45752. /*
  45753. ** This function is called after invoking an sqlite3_value_XXX function on a
  45754. ** column value (i.e. a value returned by evaluating an SQL expression in the
  45755. ** select list of a SELECT statement) that may cause a malloc() failure. If
  45756. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  45757. ** code of statement pStmt set to SQLITE_NOMEM.
  45758. **
  45759. ** Specifically, this is called from within:
  45760. **
  45761. ** sqlite3_column_int()
  45762. ** sqlite3_column_int64()
  45763. ** sqlite3_column_text()
  45764. ** sqlite3_column_text16()
  45765. ** sqlite3_column_real()
  45766. ** sqlite3_column_bytes()
  45767. ** sqlite3_column_bytes16()
  45768. **
  45769. ** But not for sqlite3_column_blob(), which never calls malloc().
  45770. */
  45771. static void columnMallocFailure(sqlite3_stmt *pStmt)
  45772. {
  45773. /* If malloc() failed during an encoding conversion within an
  45774. ** sqlite3_column_XXX API, then set the return code of the statement to
  45775. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  45776. ** and _finalize() will return NOMEM.
  45777. */
  45778. Vdbe *p = (Vdbe *)pStmt;
  45779. if( p ){
  45780. p->rc = sqlite3ApiExit(p->db, p->rc);
  45781. sqlite3_mutex_leave(p->db->mutex);
  45782. }
  45783. }
  45784. /**************************** sqlite3_column_ *******************************
  45785. ** The following routines are used to access elements of the current row
  45786. ** in the result set.
  45787. */
  45788. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  45789. const void *val;
  45790. val = sqlite3_value_blob( columnMem(pStmt,i) );
  45791. /* Even though there is no encoding conversion, value_blob() might
  45792. ** need to call malloc() to expand the result of a zeroblob()
  45793. ** expression.
  45794. */
  45795. columnMallocFailure(pStmt);
  45796. return val;
  45797. }
  45798. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  45799. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  45800. columnMallocFailure(pStmt);
  45801. return val;
  45802. }
  45803. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  45804. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  45805. columnMallocFailure(pStmt);
  45806. return val;
  45807. }
  45808. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  45809. double val = sqlite3_value_double( columnMem(pStmt,i) );
  45810. columnMallocFailure(pStmt);
  45811. return val;
  45812. }
  45813. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  45814. int val = sqlite3_value_int( columnMem(pStmt,i) );
  45815. columnMallocFailure(pStmt);
  45816. return val;
  45817. }
  45818. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  45819. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  45820. columnMallocFailure(pStmt);
  45821. return val;
  45822. }
  45823. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  45824. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  45825. columnMallocFailure(pStmt);
  45826. return val;
  45827. }
  45828. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  45829. Mem *pOut = columnMem(pStmt, i);
  45830. if( pOut->flags&MEM_Static ){
  45831. pOut->flags &= ~MEM_Static;
  45832. pOut->flags |= MEM_Ephem;
  45833. }
  45834. columnMallocFailure(pStmt);
  45835. return (sqlite3_value *)pOut;
  45836. }
  45837. #ifndef SQLITE_OMIT_UTF16
  45838. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  45839. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  45840. columnMallocFailure(pStmt);
  45841. return val;
  45842. }
  45843. #endif /* SQLITE_OMIT_UTF16 */
  45844. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  45845. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  45846. columnMallocFailure(pStmt);
  45847. return iType;
  45848. }
  45849. /* The following function is experimental and subject to change or
  45850. ** removal */
  45851. /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
  45852. ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
  45853. **}
  45854. */
  45855. /*
  45856. ** Convert the N-th element of pStmt->pColName[] into a string using
  45857. ** xFunc() then return that string. If N is out of range, return 0.
  45858. **
  45859. ** There are up to 5 names for each column. useType determines which
  45860. ** name is returned. Here are the names:
  45861. **
  45862. ** 0 The column name as it should be displayed for output
  45863. ** 1 The datatype name for the column
  45864. ** 2 The name of the database that the column derives from
  45865. ** 3 The name of the table that the column derives from
  45866. ** 4 The name of the table column that the result column derives from
  45867. **
  45868. ** If the result is not a simple column reference (if it is an expression
  45869. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  45870. */
  45871. static const void *columnName(
  45872. sqlite3_stmt *pStmt,
  45873. int N,
  45874. const void *(*xFunc)(Mem*),
  45875. int useType
  45876. ){
  45877. const void *ret = 0;
  45878. Vdbe *p = (Vdbe *)pStmt;
  45879. int n;
  45880. sqlite3 *db = p->db;
  45881. assert( db!=0 );
  45882. n = sqlite3_column_count(pStmt);
  45883. if( N<n && N>=0 ){
  45884. N += useType*n;
  45885. sqlite3_mutex_enter(db->mutex);
  45886. assert( db->mallocFailed==0 );
  45887. ret = xFunc(&p->aColName[N]);
  45888. /* A malloc may have failed inside of the xFunc() call. If this
  45889. ** is the case, clear the mallocFailed flag and return NULL.
  45890. */
  45891. if( db->mallocFailed ){
  45892. db->mallocFailed = 0;
  45893. ret = 0;
  45894. }
  45895. sqlite3_mutex_leave(db->mutex);
  45896. }
  45897. return ret;
  45898. }
  45899. /*
  45900. ** Return the name of the Nth column of the result set returned by SQL
  45901. ** statement pStmt.
  45902. */
  45903. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  45904. return columnName(
  45905. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  45906. }
  45907. #ifndef SQLITE_OMIT_UTF16
  45908. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  45909. return columnName(
  45910. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  45911. }
  45912. #endif
  45913. /*
  45914. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  45915. ** not define OMIT_DECLTYPE.
  45916. */
  45917. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  45918. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  45919. and SQLITE_ENABLE_COLUMN_METADATA"
  45920. #endif
  45921. #ifndef SQLITE_OMIT_DECLTYPE
  45922. /*
  45923. ** Return the column declaration type (if applicable) of the 'i'th column
  45924. ** of the result set of SQL statement pStmt.
  45925. */
  45926. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  45927. return columnName(
  45928. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  45929. }
  45930. #ifndef SQLITE_OMIT_UTF16
  45931. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  45932. return columnName(
  45933. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  45934. }
  45935. #endif /* SQLITE_OMIT_UTF16 */
  45936. #endif /* SQLITE_OMIT_DECLTYPE */
  45937. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  45938. /*
  45939. ** Return the name of the database from which a result column derives.
  45940. ** NULL is returned if the result column is an expression or constant or
  45941. ** anything else which is not an unabiguous reference to a database column.
  45942. */
  45943. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  45944. return columnName(
  45945. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  45946. }
  45947. #ifndef SQLITE_OMIT_UTF16
  45948. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  45949. return columnName(
  45950. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  45951. }
  45952. #endif /* SQLITE_OMIT_UTF16 */
  45953. /*
  45954. ** Return the name of the table from which a result column derives.
  45955. ** NULL is returned if the result column is an expression or constant or
  45956. ** anything else which is not an unabiguous reference to a database column.
  45957. */
  45958. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  45959. return columnName(
  45960. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  45961. }
  45962. #ifndef SQLITE_OMIT_UTF16
  45963. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  45964. return columnName(
  45965. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  45966. }
  45967. #endif /* SQLITE_OMIT_UTF16 */
  45968. /*
  45969. ** Return the name of the table column from which a result column derives.
  45970. ** NULL is returned if the result column is an expression or constant or
  45971. ** anything else which is not an unabiguous reference to a database column.
  45972. */
  45973. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  45974. return columnName(
  45975. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  45976. }
  45977. #ifndef SQLITE_OMIT_UTF16
  45978. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  45979. return columnName(
  45980. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  45981. }
  45982. #endif /* SQLITE_OMIT_UTF16 */
  45983. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  45984. /******************************* sqlite3_bind_ ***************************
  45985. **
  45986. ** Routines used to attach values to wildcards in a compiled SQL statement.
  45987. */
  45988. /*
  45989. ** Unbind the value bound to variable i in virtual machine p. This is the
  45990. ** the same as binding a NULL value to the column. If the "i" parameter is
  45991. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  45992. **
  45993. ** A successful evaluation of this routine acquires the mutex on p.
  45994. ** the mutex is released if any kind of error occurs.
  45995. **
  45996. ** The error code stored in database p->db is overwritten with the return
  45997. ** value in any case.
  45998. */
  45999. static int vdbeUnbind(Vdbe *p, int i){
  46000. Mem *pVar;
  46001. if( p==0 ) return SQLITE_MISUSE;
  46002. sqlite3_mutex_enter(p->db->mutex);
  46003. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  46004. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  46005. sqlite3_mutex_leave(p->db->mutex);
  46006. return SQLITE_MISUSE;
  46007. }
  46008. if( i<1 || i>p->nVar ){
  46009. sqlite3Error(p->db, SQLITE_RANGE, 0);
  46010. sqlite3_mutex_leave(p->db->mutex);
  46011. return SQLITE_RANGE;
  46012. }
  46013. i--;
  46014. pVar = &p->aVar[i];
  46015. sqlite3VdbeMemRelease(pVar);
  46016. pVar->flags = MEM_Null;
  46017. sqlite3Error(p->db, SQLITE_OK, 0);
  46018. return SQLITE_OK;
  46019. }
  46020. /*
  46021. ** Bind a text or BLOB value.
  46022. */
  46023. static int bindText(
  46024. sqlite3_stmt *pStmt, /* The statement to bind against */
  46025. int i, /* Index of the parameter to bind */
  46026. const void *zData, /* Pointer to the data to be bound */
  46027. int nData, /* Number of bytes of data to be bound */
  46028. void (*xDel)(void*), /* Destructor for the data */
  46029. u8 encoding /* Encoding for the data */
  46030. ){
  46031. Vdbe *p = (Vdbe *)pStmt;
  46032. Mem *pVar;
  46033. int rc;
  46034. rc = vdbeUnbind(p, i);
  46035. if( rc==SQLITE_OK ){
  46036. if( zData!=0 ){
  46037. pVar = &p->aVar[i-1];
  46038. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  46039. if( rc==SQLITE_OK && encoding!=0 ){
  46040. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  46041. }
  46042. sqlite3Error(p->db, rc, 0);
  46043. rc = sqlite3ApiExit(p->db, rc);
  46044. }
  46045. sqlite3_mutex_leave(p->db->mutex);
  46046. }
  46047. return rc;
  46048. }
  46049. /*
  46050. ** Bind a blob value to an SQL statement variable.
  46051. */
  46052. SQLITE_API int sqlite3_bind_blob(
  46053. sqlite3_stmt *pStmt,
  46054. int i,
  46055. const void *zData,
  46056. int nData,
  46057. void (*xDel)(void*)
  46058. ){
  46059. return bindText(pStmt, i, zData, nData, xDel, 0);
  46060. }
  46061. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  46062. int rc;
  46063. Vdbe *p = (Vdbe *)pStmt;
  46064. rc = vdbeUnbind(p, i);
  46065. if( rc==SQLITE_OK ){
  46066. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  46067. sqlite3_mutex_leave(p->db->mutex);
  46068. }
  46069. return rc;
  46070. }
  46071. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  46072. return sqlite3_bind_int64(p, i, (i64)iValue);
  46073. }
  46074. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  46075. int rc;
  46076. Vdbe *p = (Vdbe *)pStmt;
  46077. rc = vdbeUnbind(p, i);
  46078. if( rc==SQLITE_OK ){
  46079. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  46080. sqlite3_mutex_leave(p->db->mutex);
  46081. }
  46082. return rc;
  46083. }
  46084. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  46085. int rc;
  46086. Vdbe *p = (Vdbe*)pStmt;
  46087. rc = vdbeUnbind(p, i);
  46088. if( rc==SQLITE_OK ){
  46089. sqlite3_mutex_leave(p->db->mutex);
  46090. }
  46091. return rc;
  46092. }
  46093. SQLITE_API int sqlite3_bind_text(
  46094. sqlite3_stmt *pStmt,
  46095. int i,
  46096. const char *zData,
  46097. int nData,
  46098. void (*xDel)(void*)
  46099. ){
  46100. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  46101. }
  46102. #ifndef SQLITE_OMIT_UTF16
  46103. SQLITE_API int sqlite3_bind_text16(
  46104. sqlite3_stmt *pStmt,
  46105. int i,
  46106. const void *zData,
  46107. int nData,
  46108. void (*xDel)(void*)
  46109. ){
  46110. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  46111. }
  46112. #endif /* SQLITE_OMIT_UTF16 */
  46113. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  46114. int rc;
  46115. Vdbe *p = (Vdbe *)pStmt;
  46116. rc = vdbeUnbind(p, i);
  46117. if( rc==SQLITE_OK ){
  46118. rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
  46119. if( rc==SQLITE_OK ){
  46120. rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
  46121. }
  46122. sqlite3_mutex_leave(p->db->mutex);
  46123. rc = sqlite3ApiExit(p->db, rc);
  46124. }
  46125. return rc;
  46126. }
  46127. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  46128. int rc;
  46129. Vdbe *p = (Vdbe *)pStmt;
  46130. rc = vdbeUnbind(p, i);
  46131. if( rc==SQLITE_OK ){
  46132. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  46133. sqlite3_mutex_leave(p->db->mutex);
  46134. }
  46135. return rc;
  46136. }
  46137. /*
  46138. ** Return the number of wildcards that can be potentially bound to.
  46139. ** This routine is added to support DBD::SQLite.
  46140. */
  46141. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  46142. Vdbe *p = (Vdbe*)pStmt;
  46143. return p ? p->nVar : 0;
  46144. }
  46145. /*
  46146. ** Create a mapping from variable numbers to variable names
  46147. ** in the Vdbe.azVar[] array, if such a mapping does not already
  46148. ** exist.
  46149. */
  46150. static void createVarMap(Vdbe *p){
  46151. if( !p->okVar ){
  46152. int j;
  46153. Op *pOp;
  46154. sqlite3_mutex_enter(p->db->mutex);
  46155. /* The race condition here is harmless. If two threads call this
  46156. ** routine on the same Vdbe at the same time, they both might end
  46157. ** up initializing the Vdbe.azVar[] array. That is a little extra
  46158. ** work but it results in the same answer.
  46159. */
  46160. for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
  46161. if( pOp->opcode==OP_Variable ){
  46162. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  46163. p->azVar[pOp->p1-1] = pOp->p4.z;
  46164. }
  46165. }
  46166. p->okVar = 1;
  46167. sqlite3_mutex_leave(p->db->mutex);
  46168. }
  46169. }
  46170. /*
  46171. ** Return the name of a wildcard parameter. Return NULL if the index
  46172. ** is out of range or if the wildcard is unnamed.
  46173. **
  46174. ** The result is always UTF-8.
  46175. */
  46176. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  46177. Vdbe *p = (Vdbe*)pStmt;
  46178. if( p==0 || i<1 || i>p->nVar ){
  46179. return 0;
  46180. }
  46181. createVarMap(p);
  46182. return p->azVar[i-1];
  46183. }
  46184. /*
  46185. ** Given a wildcard parameter name, return the index of the variable
  46186. ** with that name. If there is no variable with the given name,
  46187. ** return 0.
  46188. */
  46189. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  46190. Vdbe *p = (Vdbe*)pStmt;
  46191. int i;
  46192. if( p==0 ){
  46193. return 0;
  46194. }
  46195. createVarMap(p);
  46196. if( zName ){
  46197. for(i=0; i<p->nVar; i++){
  46198. const char *z = p->azVar[i];
  46199. if( z && strcmp(z,zName)==0 ){
  46200. return i+1;
  46201. }
  46202. }
  46203. }
  46204. return 0;
  46205. }
  46206. /*
  46207. ** Transfer all bindings from the first statement over to the second.
  46208. */
  46209. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  46210. Vdbe *pFrom = (Vdbe*)pFromStmt;
  46211. Vdbe *pTo = (Vdbe*)pToStmt;
  46212. int i;
  46213. assert( pTo->db==pFrom->db );
  46214. assert( pTo->nVar==pFrom->nVar );
  46215. sqlite3_mutex_enter(pTo->db->mutex);
  46216. for(i=0; i<pFrom->nVar; i++){
  46217. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  46218. }
  46219. sqlite3_mutex_leave(pTo->db->mutex);
  46220. return SQLITE_OK;
  46221. }
  46222. #ifndef SQLITE_OMIT_DEPRECATED
  46223. /*
  46224. ** Deprecated external interface. Internal/core SQLite code
  46225. ** should call sqlite3TransferBindings.
  46226. **
  46227. ** Is is misuse to call this routine with statements from different
  46228. ** database connections. But as this is a deprecated interface, we
  46229. ** will not bother to check for that condition.
  46230. **
  46231. ** If the two statements contain a different number of bindings, then
  46232. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  46233. ** SQLITE_OK is returned.
  46234. */
  46235. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  46236. Vdbe *pFrom = (Vdbe*)pFromStmt;
  46237. Vdbe *pTo = (Vdbe*)pToStmt;
  46238. if( pFrom->nVar!=pTo->nVar ){
  46239. return SQLITE_ERROR;
  46240. }
  46241. return sqlite3TransferBindings(pFromStmt, pToStmt);
  46242. }
  46243. #endif
  46244. /*
  46245. ** Return the sqlite3* database handle to which the prepared statement given
  46246. ** in the argument belongs. This is the same database handle that was
  46247. ** the first argument to the sqlite3_prepare() that was used to create
  46248. ** the statement in the first place.
  46249. */
  46250. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  46251. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  46252. }
  46253. /*
  46254. ** Return a pointer to the next prepared statement after pStmt associated
  46255. ** with database connection pDb. If pStmt is NULL, return the first
  46256. ** prepared statement for the database connection. Return NULL if there
  46257. ** are no more.
  46258. */
  46259. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  46260. sqlite3_stmt *pNext;
  46261. sqlite3_mutex_enter(pDb->mutex);
  46262. if( pStmt==0 ){
  46263. pNext = (sqlite3_stmt*)pDb->pVdbe;
  46264. }else{
  46265. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  46266. }
  46267. sqlite3_mutex_leave(pDb->mutex);
  46268. return pNext;
  46269. }
  46270. /*
  46271. ** Return the value of a status counter for a prepared statement
  46272. */
  46273. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  46274. Vdbe *pVdbe = (Vdbe*)pStmt;
  46275. int v = pVdbe->aCounter[op-1];
  46276. if( resetFlag ) pVdbe->aCounter[op-1] = 0;
  46277. return v;
  46278. }
  46279. /************** End of vdbeapi.c *********************************************/
  46280. /************** Begin file vdbe.c ********************************************/
  46281. /*
  46282. ** 2001 September 15
  46283. **
  46284. ** The author disclaims copyright to this source code. In place of
  46285. ** a legal notice, here is a blessing:
  46286. **
  46287. ** May you do good and not evil.
  46288. ** May you find forgiveness for yourself and forgive others.
  46289. ** May you share freely, never taking more than you give.
  46290. **
  46291. *************************************************************************
  46292. ** The code in this file implements execution method of the
  46293. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  46294. ** handles housekeeping details such as creating and deleting
  46295. ** VDBE instances. This file is solely interested in executing
  46296. ** the VDBE program.
  46297. **
  46298. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  46299. ** to a VDBE.
  46300. **
  46301. ** The SQL parser generates a program which is then executed by
  46302. ** the VDBE to do the work of the SQL statement. VDBE programs are
  46303. ** similar in form to assembly language. The program consists of
  46304. ** a linear sequence of operations. Each operation has an opcode
  46305. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  46306. ** is a null-terminated string. Operand P5 is an unsigned character.
  46307. ** Few opcodes use all 5 operands.
  46308. **
  46309. ** Computation results are stored on a set of registers numbered beginning
  46310. ** with 1 and going up to Vdbe.nMem. Each register can store
  46311. ** either an integer, a null-terminated string, a floating point
  46312. ** number, or the SQL "NULL" value. An implicit conversion from one
  46313. ** type to the other occurs as necessary.
  46314. **
  46315. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  46316. ** function which does the work of interpreting a VDBE program.
  46317. ** But other routines are also provided to help in building up
  46318. ** a program instruction by instruction.
  46319. **
  46320. ** Various scripts scan this source file in order to generate HTML
  46321. ** documentation, headers files, or other derived files. The formatting
  46322. ** of the code in this file is, therefore, important. See other comments
  46323. ** in this file for details. If in doubt, do not deviate from existing
  46324. ** commenting and indentation practices when changing or adding code.
  46325. **
  46326. ** $Id: vdbe.c,v 1.832 2009/04/10 12:55:17 danielk1977 Exp $
  46327. */
  46328. /*
  46329. ** The following global variable is incremented every time a cursor
  46330. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  46331. ** procedures use this information to make sure that indices are
  46332. ** working correctly. This variable has no function other than to
  46333. ** help verify the correct operation of the library.
  46334. */
  46335. #ifdef SQLITE_TEST
  46336. SQLITE_API int sqlite3_search_count = 0;
  46337. #endif
  46338. /*
  46339. ** When this global variable is positive, it gets decremented once before
  46340. ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
  46341. ** field of the sqlite3 structure is set in order to simulate and interrupt.
  46342. **
  46343. ** This facility is used for testing purposes only. It does not function
  46344. ** in an ordinary build.
  46345. */
  46346. #ifdef SQLITE_TEST
  46347. SQLITE_API int sqlite3_interrupt_count = 0;
  46348. #endif
  46349. /*
  46350. ** The next global variable is incremented each type the OP_Sort opcode
  46351. ** is executed. The test procedures use this information to make sure that
  46352. ** sorting is occurring or not occurring at appropriate times. This variable
  46353. ** has no function other than to help verify the correct operation of the
  46354. ** library.
  46355. */
  46356. #ifdef SQLITE_TEST
  46357. SQLITE_API int sqlite3_sort_count = 0;
  46358. #endif
  46359. /*
  46360. ** The next global variable records the size of the largest MEM_Blob
  46361. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  46362. ** use this information to make sure that the zero-blob functionality
  46363. ** is working correctly. This variable has no function other than to
  46364. ** help verify the correct operation of the library.
  46365. */
  46366. #ifdef SQLITE_TEST
  46367. SQLITE_API int sqlite3_max_blobsize = 0;
  46368. static void updateMaxBlobsize(Mem *p){
  46369. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  46370. sqlite3_max_blobsize = p->n;
  46371. }
  46372. }
  46373. #endif
  46374. /*
  46375. ** Test a register to see if it exceeds the current maximum blob size.
  46376. ** If it does, record the new maximum blob size.
  46377. */
  46378. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  46379. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  46380. #else
  46381. # define UPDATE_MAX_BLOBSIZE(P)
  46382. #endif
  46383. /*
  46384. ** Convert the given register into a string if it isn't one
  46385. ** already. Return non-zero if a malloc() fails.
  46386. */
  46387. #define Stringify(P, enc) \
  46388. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  46389. { goto no_mem; }
  46390. /*
  46391. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  46392. ** a pointer to a dynamically allocated string where some other entity
  46393. ** is responsible for deallocating that string. Because the register
  46394. ** does not control the string, it might be deleted without the register
  46395. ** knowing it.
  46396. **
  46397. ** This routine converts an ephemeral string into a dynamically allocated
  46398. ** string that the register itself controls. In other words, it
  46399. ** converts an MEM_Ephem string into an MEM_Dyn string.
  46400. */
  46401. #define Deephemeralize(P) \
  46402. if( ((P)->flags&MEM_Ephem)!=0 \
  46403. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  46404. /*
  46405. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  46406. ** P if required.
  46407. */
  46408. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  46409. /*
  46410. ** Argument pMem points at a register that will be passed to a
  46411. ** user-defined function or returned to the user as the result of a query.
  46412. ** The second argument, 'db_enc' is the text encoding used by the vdbe for
  46413. ** register variables. This routine sets the pMem->enc and pMem->type
  46414. ** variables used by the sqlite3_value_*() routines.
  46415. */
  46416. #define storeTypeInfo(A,B) _storeTypeInfo(A)
  46417. static void _storeTypeInfo(Mem *pMem){
  46418. int flags = pMem->flags;
  46419. if( flags & MEM_Null ){
  46420. pMem->type = SQLITE_NULL;
  46421. }
  46422. else if( flags & MEM_Int ){
  46423. pMem->type = SQLITE_INTEGER;
  46424. }
  46425. else if( flags & MEM_Real ){
  46426. pMem->type = SQLITE_FLOAT;
  46427. }
  46428. else if( flags & MEM_Str ){
  46429. pMem->type = SQLITE_TEXT;
  46430. }else{
  46431. pMem->type = SQLITE_BLOB;
  46432. }
  46433. }
  46434. /*
  46435. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  46436. ** created by mkopcodeh.awk during compilation. Data is obtained
  46437. ** from the comments following the "case OP_xxxx:" statements in
  46438. ** this file.
  46439. */
  46440. static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
  46441. /*
  46442. ** Return true if an opcode has any of the OPFLG_xxx properties
  46443. ** specified by mask.
  46444. */
  46445. SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
  46446. assert( opcode>0 && opcode<(int)sizeof(opcodeProperty) );
  46447. return (opcodeProperty[opcode]&mask)!=0;
  46448. }
  46449. /*
  46450. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  46451. ** if we run out of memory.
  46452. */
  46453. static VdbeCursor *allocateCursor(
  46454. Vdbe *p, /* The virtual machine */
  46455. int iCur, /* Index of the new VdbeCursor */
  46456. int nField, /* Number of fields in the table or index */
  46457. int iDb, /* When database the cursor belongs to, or -1 */
  46458. int isBtreeCursor /* */
  46459. ){
  46460. /* Find the memory cell that will be used to store the blob of memory
  46461. ** required for this VdbeCursor structure. It is convenient to use a
  46462. ** vdbe memory cell to manage the memory allocation required for a
  46463. ** VdbeCursor structure for the following reasons:
  46464. **
  46465. ** * Sometimes cursor numbers are used for a couple of different
  46466. ** purposes in a vdbe program. The different uses might require
  46467. ** different sized allocations. Memory cells provide growable
  46468. ** allocations.
  46469. **
  46470. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  46471. ** be freed lazily via the sqlite3_release_memory() API. This
  46472. ** minimizes the number of malloc calls made by the system.
  46473. **
  46474. ** Memory cells for cursors are allocated at the top of the address
  46475. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  46476. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  46477. */
  46478. Mem *pMem = &p->aMem[p->nMem-iCur];
  46479. int nByte;
  46480. VdbeCursor *pCx = 0;
  46481. nByte =
  46482. sizeof(VdbeCursor) +
  46483. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  46484. 2*nField*sizeof(u32);
  46485. assert( iCur<p->nCursor );
  46486. if( p->apCsr[iCur] ){
  46487. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  46488. p->apCsr[iCur] = 0;
  46489. }
  46490. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  46491. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  46492. memset(pMem->z, 0, nByte);
  46493. pCx->iDb = iDb;
  46494. pCx->nField = nField;
  46495. if( nField ){
  46496. pCx->aType = (u32 *)&pMem->z[sizeof(VdbeCursor)];
  46497. }
  46498. if( isBtreeCursor ){
  46499. pCx->pCursor = (BtCursor*)
  46500. &pMem->z[sizeof(VdbeCursor)+2*nField*sizeof(u32)];
  46501. }
  46502. }
  46503. return pCx;
  46504. }
  46505. /*
  46506. ** Try to convert a value into a numeric representation if we can
  46507. ** do so without loss of information. In other words, if the string
  46508. ** looks like a number, convert it into a number. If it does not
  46509. ** look like a number, leave it alone.
  46510. */
  46511. static void applyNumericAffinity(Mem *pRec){
  46512. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  46513. int realnum;
  46514. sqlite3VdbeMemNulTerminate(pRec);
  46515. if( (pRec->flags&MEM_Str)
  46516. && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
  46517. i64 value;
  46518. sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
  46519. if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
  46520. pRec->u.i = value;
  46521. MemSetTypeFlag(pRec, MEM_Int);
  46522. }else{
  46523. sqlite3VdbeMemRealify(pRec);
  46524. }
  46525. }
  46526. }
  46527. }
  46528. /*
  46529. ** Processing is determine by the affinity parameter:
  46530. **
  46531. ** SQLITE_AFF_INTEGER:
  46532. ** SQLITE_AFF_REAL:
  46533. ** SQLITE_AFF_NUMERIC:
  46534. ** Try to convert pRec to an integer representation or a
  46535. ** floating-point representation if an integer representation
  46536. ** is not possible. Note that the integer representation is
  46537. ** always preferred, even if the affinity is REAL, because
  46538. ** an integer representation is more space efficient on disk.
  46539. **
  46540. ** SQLITE_AFF_TEXT:
  46541. ** Convert pRec to a text representation.
  46542. **
  46543. ** SQLITE_AFF_NONE:
  46544. ** No-op. pRec is unchanged.
  46545. */
  46546. static void applyAffinity(
  46547. Mem *pRec, /* The value to apply affinity to */
  46548. char affinity, /* The affinity to be applied */
  46549. u8 enc /* Use this text encoding */
  46550. ){
  46551. if( affinity==SQLITE_AFF_TEXT ){
  46552. /* Only attempt the conversion to TEXT if there is an integer or real
  46553. ** representation (blob and NULL do not get converted) but no string
  46554. ** representation.
  46555. */
  46556. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  46557. sqlite3VdbeMemStringify(pRec, enc);
  46558. }
  46559. pRec->flags &= ~(MEM_Real|MEM_Int);
  46560. }else if( affinity!=SQLITE_AFF_NONE ){
  46561. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  46562. || affinity==SQLITE_AFF_NUMERIC );
  46563. applyNumericAffinity(pRec);
  46564. if( pRec->flags & MEM_Real ){
  46565. sqlite3VdbeIntegerAffinity(pRec);
  46566. }
  46567. }
  46568. }
  46569. /*
  46570. ** Try to convert the type of a function argument or a result column
  46571. ** into a numeric representation. Use either INTEGER or REAL whichever
  46572. ** is appropriate. But only do the conversion if it is possible without
  46573. ** loss of information and return the revised type of the argument.
  46574. **
  46575. ** This is an EXPERIMENTAL api and is subject to change or removal.
  46576. */
  46577. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  46578. Mem *pMem = (Mem*)pVal;
  46579. applyNumericAffinity(pMem);
  46580. storeTypeInfo(pMem, 0);
  46581. return pMem->type;
  46582. }
  46583. /*
  46584. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  46585. ** not the internal Mem* type.
  46586. */
  46587. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  46588. sqlite3_value *pVal,
  46589. u8 affinity,
  46590. u8 enc
  46591. ){
  46592. applyAffinity((Mem *)pVal, affinity, enc);
  46593. }
  46594. #ifdef SQLITE_DEBUG
  46595. /*
  46596. ** Write a nice string representation of the contents of cell pMem
  46597. ** into buffer zBuf, length nBuf.
  46598. */
  46599. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  46600. char *zCsr = zBuf;
  46601. int f = pMem->flags;
  46602. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  46603. if( f&MEM_Blob ){
  46604. int i;
  46605. char c;
  46606. if( f & MEM_Dyn ){
  46607. c = 'z';
  46608. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  46609. }else if( f & MEM_Static ){
  46610. c = 't';
  46611. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  46612. }else if( f & MEM_Ephem ){
  46613. c = 'e';
  46614. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  46615. }else{
  46616. c = 's';
  46617. }
  46618. sqlite3_snprintf(100, zCsr, "%c", c);
  46619. zCsr += sqlite3Strlen30(zCsr);
  46620. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  46621. zCsr += sqlite3Strlen30(zCsr);
  46622. for(i=0; i<16 && i<pMem->n; i++){
  46623. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  46624. zCsr += sqlite3Strlen30(zCsr);
  46625. }
  46626. for(i=0; i<16 && i<pMem->n; i++){
  46627. char z = pMem->z[i];
  46628. if( z<32 || z>126 ) *zCsr++ = '.';
  46629. else *zCsr++ = z;
  46630. }
  46631. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  46632. zCsr += sqlite3Strlen30(zCsr);
  46633. if( f & MEM_Zero ){
  46634. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  46635. zCsr += sqlite3Strlen30(zCsr);
  46636. }
  46637. *zCsr = '\0';
  46638. }else if( f & MEM_Str ){
  46639. int j, k;
  46640. zBuf[0] = ' ';
  46641. if( f & MEM_Dyn ){
  46642. zBuf[1] = 'z';
  46643. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  46644. }else if( f & MEM_Static ){
  46645. zBuf[1] = 't';
  46646. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  46647. }else if( f & MEM_Ephem ){
  46648. zBuf[1] = 'e';
  46649. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  46650. }else{
  46651. zBuf[1] = 's';
  46652. }
  46653. k = 2;
  46654. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  46655. k += sqlite3Strlen30(&zBuf[k]);
  46656. zBuf[k++] = '[';
  46657. for(j=0; j<15 && j<pMem->n; j++){
  46658. u8 c = pMem->z[j];
  46659. if( c>=0x20 && c<0x7f ){
  46660. zBuf[k++] = c;
  46661. }else{
  46662. zBuf[k++] = '.';
  46663. }
  46664. }
  46665. zBuf[k++] = ']';
  46666. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  46667. k += sqlite3Strlen30(&zBuf[k]);
  46668. zBuf[k++] = 0;
  46669. }
  46670. }
  46671. #endif
  46672. #ifdef SQLITE_DEBUG
  46673. /*
  46674. ** Print the value of a register for tracing purposes:
  46675. */
  46676. static void memTracePrint(FILE *out, Mem *p){
  46677. if( p->flags & MEM_Null ){
  46678. fprintf(out, " NULL");
  46679. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  46680. fprintf(out, " si:%lld", p->u.i);
  46681. }else if( p->flags & MEM_Int ){
  46682. fprintf(out, " i:%lld", p->u.i);
  46683. }else if( p->flags & MEM_Real ){
  46684. fprintf(out, " r:%g", p->r);
  46685. }else{
  46686. char zBuf[200];
  46687. sqlite3VdbeMemPrettyPrint(p, zBuf);
  46688. fprintf(out, " ");
  46689. fprintf(out, "%s", zBuf);
  46690. }
  46691. }
  46692. static void registerTrace(FILE *out, int iReg, Mem *p){
  46693. fprintf(out, "REG[%d] = ", iReg);
  46694. memTracePrint(out, p);
  46695. fprintf(out, "\n");
  46696. }
  46697. #endif
  46698. #ifdef SQLITE_DEBUG
  46699. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  46700. #else
  46701. # define REGISTER_TRACE(R,M)
  46702. #endif
  46703. #ifdef VDBE_PROFILE
  46704. /*
  46705. ** hwtime.h contains inline assembler code for implementing
  46706. ** high-performance timing routines.
  46707. */
  46708. /************** Include hwtime.h in the middle of vdbe.c *********************/
  46709. /************** Begin file hwtime.h ******************************************/
  46710. /*
  46711. ** 2008 May 27
  46712. **
  46713. ** The author disclaims copyright to this source code. In place of
  46714. ** a legal notice, here is a blessing:
  46715. **
  46716. ** May you do good and not evil.
  46717. ** May you find forgiveness for yourself and forgive others.
  46718. ** May you share freely, never taking more than you give.
  46719. **
  46720. ******************************************************************************
  46721. **
  46722. ** This file contains inline asm code for retrieving "high-performance"
  46723. ** counters for x86 class CPUs.
  46724. **
  46725. ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
  46726. */
  46727. #ifndef _HWTIME_H_
  46728. #define _HWTIME_H_
  46729. /*
  46730. ** The following routine only works on pentium-class (or newer) processors.
  46731. ** It uses the RDTSC opcode to read the cycle count value out of the
  46732. ** processor and returns that value. This can be used for high-res
  46733. ** profiling.
  46734. */
  46735. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  46736. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  46737. #if defined(__GNUC__)
  46738. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  46739. unsigned int lo, hi;
  46740. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  46741. return (sqlite_uint64)hi << 32 | lo;
  46742. }
  46743. #elif defined(_MSC_VER)
  46744. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  46745. __asm {
  46746. rdtsc
  46747. ret ; return value at EDX:EAX
  46748. }
  46749. }
  46750. #endif
  46751. #elif (defined(__GNUC__) && defined(__x86_64__))
  46752. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  46753. unsigned long val;
  46754. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  46755. return val;
  46756. }
  46757. #elif (defined(__GNUC__) && defined(__ppc__))
  46758. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  46759. unsigned long long retval;
  46760. unsigned long junk;
  46761. __asm__ __volatile__ ("\n\
  46762. 1: mftbu %1\n\
  46763. mftb %L0\n\
  46764. mftbu %0\n\
  46765. cmpw %0,%1\n\
  46766. bne 1b"
  46767. : "=r" (retval), "=r" (junk));
  46768. return retval;
  46769. }
  46770. #else
  46771. #error Need implementation of sqlite3Hwtime() for your platform.
  46772. /*
  46773. ** To compile without implementing sqlite3Hwtime() for your platform,
  46774. ** you can remove the above #error and use the following
  46775. ** stub function. You will lose timing support for many
  46776. ** of the debugging and testing utilities, but it should at
  46777. ** least compile and run.
  46778. */
  46779. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  46780. #endif
  46781. #endif /* !defined(_HWTIME_H_) */
  46782. /************** End of hwtime.h **********************************************/
  46783. /************** Continuing where we left off in vdbe.c ***********************/
  46784. #endif
  46785. /*
  46786. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  46787. ** sqlite3_interrupt() routine has been called. If it has been, then
  46788. ** processing of the VDBE program is interrupted.
  46789. **
  46790. ** This macro added to every instruction that does a jump in order to
  46791. ** implement a loop. This test used to be on every single instruction,
  46792. ** but that meant we more testing that we needed. By only testing the
  46793. ** flag on jump instructions, we get a (small) speed improvement.
  46794. */
  46795. #define CHECK_FOR_INTERRUPT \
  46796. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  46797. #ifdef SQLITE_DEBUG
  46798. static int fileExists(sqlite3 *db, const char *zFile){
  46799. int res = 0;
  46800. int rc = SQLITE_OK;
  46801. #ifdef SQLITE_TEST
  46802. /* If we are currently testing IO errors, then do not call OsAccess() to
  46803. ** test for the presence of zFile. This is because any IO error that
  46804. ** occurs here will not be reported, causing the test to fail.
  46805. */
  46806. extern int sqlite3_io_error_pending;
  46807. if( sqlite3_io_error_pending<=0 )
  46808. #endif
  46809. rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
  46810. return (res && rc==SQLITE_OK);
  46811. }
  46812. #endif
  46813. #ifndef NDEBUG
  46814. /*
  46815. ** This function is only called from within an assert() expression. It
  46816. ** checks that the sqlite3.nTransaction variable is correctly set to
  46817. ** the number of non-transaction savepoints currently in the
  46818. ** linked list starting at sqlite3.pSavepoint.
  46819. **
  46820. ** Usage:
  46821. **
  46822. ** assert( checkSavepointCount(db) );
  46823. */
  46824. static int checkSavepointCount(sqlite3 *db){
  46825. int n = 0;
  46826. Savepoint *p;
  46827. for(p=db->pSavepoint; p; p=p->pNext) n++;
  46828. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  46829. return 1;
  46830. }
  46831. #endif
  46832. /*
  46833. ** Execute as much of a VDBE program as we can then return.
  46834. **
  46835. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  46836. ** close the program with a final OP_Halt and to set up the callbacks
  46837. ** and the error message pointer.
  46838. **
  46839. ** Whenever a row or result data is available, this routine will either
  46840. ** invoke the result callback (if there is one) or return with
  46841. ** SQLITE_ROW.
  46842. **
  46843. ** If an attempt is made to open a locked database, then this routine
  46844. ** will either invoke the busy callback (if there is one) or it will
  46845. ** return SQLITE_BUSY.
  46846. **
  46847. ** If an error occurs, an error message is written to memory obtained
  46848. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  46849. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  46850. **
  46851. ** If the callback ever returns non-zero, then the program exits
  46852. ** immediately. There will be no error message but the p->rc field is
  46853. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  46854. **
  46855. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  46856. ** routine to return SQLITE_ERROR.
  46857. **
  46858. ** Other fatal errors return SQLITE_ERROR.
  46859. **
  46860. ** After this routine has finished, sqlite3VdbeFinalize() should be
  46861. ** used to clean up the mess that was left behind.
  46862. */
  46863. SQLITE_PRIVATE int sqlite3VdbeExec(
  46864. Vdbe *p /* The VDBE */
  46865. ){
  46866. int pc; /* The program counter */
  46867. Op *pOp; /* Current operation */
  46868. int rc = SQLITE_OK; /* Value to return */
  46869. sqlite3 *db = p->db; /* The database */
  46870. u8 encoding = ENC(db); /* The database encoding */
  46871. Mem *pIn1 = 0; /* 1st input operand */
  46872. Mem *pIn2 = 0; /* 2nd input operand */
  46873. Mem *pIn3 = 0; /* 3rd input operand */
  46874. Mem *pOut = 0; /* Output operand */
  46875. u8 opProperty;
  46876. int iCompare = 0; /* Result of last OP_Compare operation */
  46877. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  46878. #ifdef VDBE_PROFILE
  46879. u64 start; /* CPU clock count at start of opcode */
  46880. int origPc; /* Program counter at start of opcode */
  46881. #endif
  46882. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  46883. int nProgressOps = 0; /* Opcodes executed since progress callback. */
  46884. #endif
  46885. /* Temporary space into which to unpack a record. */
  46886. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  46887. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  46888. assert( db->magic==SQLITE_MAGIC_BUSY );
  46889. sqlite3VdbeMutexArrayEnter(p);
  46890. if( p->rc==SQLITE_NOMEM ){
  46891. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  46892. ** sqlite3_column_text16() failed. */
  46893. goto no_mem;
  46894. }
  46895. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  46896. p->rc = SQLITE_OK;
  46897. assert( p->explain==0 );
  46898. p->pResultSet = 0;
  46899. db->busyHandler.nBusy = 0;
  46900. CHECK_FOR_INTERRUPT;
  46901. sqlite3VdbeIOTraceSql(p);
  46902. #ifdef SQLITE_DEBUG
  46903. sqlite3BeginBenignMalloc();
  46904. if( p->pc==0
  46905. && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
  46906. ){
  46907. int i;
  46908. printf("VDBE Program Listing:\n");
  46909. sqlite3VdbePrintSql(p);
  46910. for(i=0; i<p->nOp; i++){
  46911. sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
  46912. }
  46913. }
  46914. if( fileExists(db, "vdbe_trace") ){
  46915. p->trace = stdout;
  46916. }
  46917. sqlite3EndBenignMalloc();
  46918. #endif
  46919. for(pc=p->pc; rc==SQLITE_OK; pc++){
  46920. assert( pc>=0 && pc<p->nOp );
  46921. if( db->mallocFailed ) goto no_mem;
  46922. #ifdef VDBE_PROFILE
  46923. origPc = pc;
  46924. start = sqlite3Hwtime();
  46925. #endif
  46926. pOp = &p->aOp[pc];
  46927. /* Only allow tracing if SQLITE_DEBUG is defined.
  46928. */
  46929. #ifdef SQLITE_DEBUG
  46930. if( p->trace ){
  46931. if( pc==0 ){
  46932. printf("VDBE Execution Trace:\n");
  46933. sqlite3VdbePrintSql(p);
  46934. }
  46935. sqlite3VdbePrintOp(p->trace, pc, pOp);
  46936. }
  46937. if( p->trace==0 && pc==0 ){
  46938. sqlite3BeginBenignMalloc();
  46939. if( fileExists(db, "vdbe_sqltrace") ){
  46940. sqlite3VdbePrintSql(p);
  46941. }
  46942. sqlite3EndBenignMalloc();
  46943. }
  46944. #endif
  46945. /* Check to see if we need to simulate an interrupt. This only happens
  46946. ** if we have a special test build.
  46947. */
  46948. #ifdef SQLITE_TEST
  46949. if( sqlite3_interrupt_count>0 ){
  46950. sqlite3_interrupt_count--;
  46951. if( sqlite3_interrupt_count==0 ){
  46952. sqlite3_interrupt(db);
  46953. }
  46954. }
  46955. #endif
  46956. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  46957. /* Call the progress callback if it is configured and the required number
  46958. ** of VDBE ops have been executed (either since this invocation of
  46959. ** sqlite3VdbeExec() or since last time the progress callback was called).
  46960. ** If the progress callback returns non-zero, exit the virtual machine with
  46961. ** a return code SQLITE_ABORT.
  46962. */
  46963. if( db->xProgress ){
  46964. if( db->nProgressOps==nProgressOps ){
  46965. int prc;
  46966. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  46967. prc =db->xProgress(db->pProgressArg);
  46968. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  46969. if( prc!=0 ){
  46970. rc = SQLITE_INTERRUPT;
  46971. goto vdbe_error_halt;
  46972. }
  46973. nProgressOps = 0;
  46974. }
  46975. nProgressOps++;
  46976. }
  46977. #endif
  46978. /* Do common setup processing for any opcode that is marked
  46979. ** with the "out2-prerelease" tag. Such opcodes have a single
  46980. ** output which is specified by the P2 parameter. The P2 register
  46981. ** is initialized to a NULL.
  46982. */
  46983. opProperty = opcodeProperty[pOp->opcode];
  46984. if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
  46985. assert( pOp->p2>0 );
  46986. assert( pOp->p2<=p->nMem );
  46987. pOut = &p->aMem[pOp->p2];
  46988. sqlite3VdbeMemReleaseExternal(pOut);
  46989. pOut->flags = MEM_Null;
  46990. }else
  46991. /* Do common setup for opcodes marked with one of the following
  46992. ** combinations of properties.
  46993. **
  46994. ** in1
  46995. ** in1 in2
  46996. ** in1 in2 out3
  46997. ** in1 in3
  46998. **
  46999. ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
  47000. ** registers for inputs. Variable pOut points to the output register.
  47001. */
  47002. if( (opProperty & OPFLG_IN1)!=0 ){
  47003. assert( pOp->p1>0 );
  47004. assert( pOp->p1<=p->nMem );
  47005. pIn1 = &p->aMem[pOp->p1];
  47006. REGISTER_TRACE(pOp->p1, pIn1);
  47007. if( (opProperty & OPFLG_IN2)!=0 ){
  47008. assert( pOp->p2>0 );
  47009. assert( pOp->p2<=p->nMem );
  47010. pIn2 = &p->aMem[pOp->p2];
  47011. REGISTER_TRACE(pOp->p2, pIn2);
  47012. if( (opProperty & OPFLG_OUT3)!=0 ){
  47013. assert( pOp->p3>0 );
  47014. assert( pOp->p3<=p->nMem );
  47015. pOut = &p->aMem[pOp->p3];
  47016. }
  47017. }else if( (opProperty & OPFLG_IN3)!=0 ){
  47018. assert( pOp->p3>0 );
  47019. assert( pOp->p3<=p->nMem );
  47020. pIn3 = &p->aMem[pOp->p3];
  47021. REGISTER_TRACE(pOp->p3, pIn3);
  47022. }
  47023. }else if( (opProperty & OPFLG_IN2)!=0 ){
  47024. assert( pOp->p2>0 );
  47025. assert( pOp->p2<=p->nMem );
  47026. pIn2 = &p->aMem[pOp->p2];
  47027. REGISTER_TRACE(pOp->p2, pIn2);
  47028. }else if( (opProperty & OPFLG_IN3)!=0 ){
  47029. assert( pOp->p3>0 );
  47030. assert( pOp->p3<=p->nMem );
  47031. pIn3 = &p->aMem[pOp->p3];
  47032. REGISTER_TRACE(pOp->p3, pIn3);
  47033. }
  47034. switch( pOp->opcode ){
  47035. /*****************************************************************************
  47036. ** What follows is a massive switch statement where each case implements a
  47037. ** separate instruction in the virtual machine. If we follow the usual
  47038. ** indentation conventions, each case should be indented by 6 spaces. But
  47039. ** that is a lot of wasted space on the left margin. So the code within
  47040. ** the switch statement will break with convention and be flush-left. Another
  47041. ** big comment (similar to this one) will mark the point in the code where
  47042. ** we transition back to normal indentation.
  47043. **
  47044. ** The formatting of each case is important. The makefile for SQLite
  47045. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  47046. ** file looking for lines that begin with "case OP_". The opcodes.h files
  47047. ** will be filled with #defines that give unique integer values to each
  47048. ** opcode and the opcodes.c file is filled with an array of strings where
  47049. ** each string is the symbolic name for the corresponding opcode. If the
  47050. ** case statement is followed by a comment of the form "/# same as ... #/"
  47051. ** that comment is used to determine the particular value of the opcode.
  47052. **
  47053. ** Other keywords in the comment that follows each case are used to
  47054. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  47055. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  47056. ** the mkopcodeh.awk script for additional information.
  47057. **
  47058. ** Documentation about VDBE opcodes is generated by scanning this file
  47059. ** for lines of that contain "Opcode:". That line and all subsequent
  47060. ** comment lines are used in the generation of the opcode.html documentation
  47061. ** file.
  47062. **
  47063. ** SUMMARY:
  47064. **
  47065. ** Formatting is important to scripts that scan this file.
  47066. ** Do not deviate from the formatting style currently in use.
  47067. **
  47068. *****************************************************************************/
  47069. /* Opcode: Goto * P2 * * *
  47070. **
  47071. ** An unconditional jump to address P2.
  47072. ** The next instruction executed will be
  47073. ** the one at index P2 from the beginning of
  47074. ** the program.
  47075. */
  47076. case OP_Goto: { /* jump */
  47077. CHECK_FOR_INTERRUPT;
  47078. pc = pOp->p2 - 1;
  47079. break;
  47080. }
  47081. /* Opcode: Gosub P1 P2 * * *
  47082. **
  47083. ** Write the current address onto register P1
  47084. ** and then jump to address P2.
  47085. */
  47086. case OP_Gosub: { /* jump */
  47087. assert( pOp->p1>0 );
  47088. assert( pOp->p1<=p->nMem );
  47089. pIn1 = &p->aMem[pOp->p1];
  47090. assert( (pIn1->flags & MEM_Dyn)==0 );
  47091. pIn1->flags = MEM_Int;
  47092. pIn1->u.i = pc;
  47093. REGISTER_TRACE(pOp->p1, pIn1);
  47094. pc = pOp->p2 - 1;
  47095. break;
  47096. }
  47097. /* Opcode: Return P1 * * * *
  47098. **
  47099. ** Jump to the next instruction after the address in register P1.
  47100. */
  47101. case OP_Return: { /* in1 */
  47102. assert( pIn1->flags & MEM_Int );
  47103. pc = (int)pIn1->u.i;
  47104. break;
  47105. }
  47106. /* Opcode: Yield P1 * * * *
  47107. **
  47108. ** Swap the program counter with the value in register P1.
  47109. */
  47110. case OP_Yield: { /* in1 */
  47111. int pcDest;
  47112. assert( (pIn1->flags & MEM_Dyn)==0 );
  47113. pIn1->flags = MEM_Int;
  47114. pcDest = (int)pIn1->u.i;
  47115. pIn1->u.i = pc;
  47116. REGISTER_TRACE(pOp->p1, pIn1);
  47117. pc = pcDest;
  47118. break;
  47119. }
  47120. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  47121. **
  47122. ** Check the value in register P3. If is is NULL then Halt using
  47123. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  47124. ** value in register P3 is not NULL, then this routine is a no-op.
  47125. */
  47126. case OP_HaltIfNull: { /* in3 */
  47127. if( (pIn3->flags & MEM_Null)==0 ) break;
  47128. /* Fall through into OP_Halt */
  47129. }
  47130. /* Opcode: Halt P1 P2 * P4 *
  47131. **
  47132. ** Exit immediately. All open cursors, etc are closed
  47133. ** automatically.
  47134. **
  47135. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  47136. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  47137. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  47138. ** whether or not to rollback the current transaction. Do not rollback
  47139. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  47140. ** then back out all changes that have occurred during this execution of the
  47141. ** VDBE, but do not rollback the transaction.
  47142. **
  47143. ** If P4 is not null then it is an error message string.
  47144. **
  47145. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  47146. ** every program. So a jump past the last instruction of the program
  47147. ** is the same as executing Halt.
  47148. */
  47149. case OP_Halt: {
  47150. p->rc = pOp->p1;
  47151. p->pc = pc;
  47152. p->errorAction = pOp->p2;
  47153. if( pOp->p4.z ){
  47154. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  47155. }
  47156. rc = sqlite3VdbeHalt(p);
  47157. assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
  47158. if( rc==SQLITE_BUSY ){
  47159. p->rc = rc = SQLITE_BUSY;
  47160. }else{
  47161. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  47162. }
  47163. goto vdbe_return;
  47164. }
  47165. /* Opcode: Integer P1 P2 * * *
  47166. **
  47167. ** The 32-bit integer value P1 is written into register P2.
  47168. */
  47169. case OP_Integer: { /* out2-prerelease */
  47170. pOut->flags = MEM_Int;
  47171. pOut->u.i = pOp->p1;
  47172. break;
  47173. }
  47174. /* Opcode: Int64 * P2 * P4 *
  47175. **
  47176. ** P4 is a pointer to a 64-bit integer value.
  47177. ** Write that value into register P2.
  47178. */
  47179. case OP_Int64: { /* out2-prerelease */
  47180. assert( pOp->p4.pI64!=0 );
  47181. pOut->flags = MEM_Int;
  47182. pOut->u.i = *pOp->p4.pI64;
  47183. break;
  47184. }
  47185. /* Opcode: Real * P2 * P4 *
  47186. **
  47187. ** P4 is a pointer to a 64-bit floating point value.
  47188. ** Write that value into register P2.
  47189. */
  47190. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  47191. pOut->flags = MEM_Real;
  47192. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  47193. pOut->r = *pOp->p4.pReal;
  47194. break;
  47195. }
  47196. /* Opcode: String8 * P2 * P4 *
  47197. **
  47198. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  47199. ** into an OP_String before it is executed for the first time.
  47200. */
  47201. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  47202. assert( pOp->p4.z!=0 );
  47203. pOp->opcode = OP_String;
  47204. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  47205. #ifndef SQLITE_OMIT_UTF16
  47206. if( encoding!=SQLITE_UTF8 ){
  47207. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  47208. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  47209. if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
  47210. pOut->zMalloc = 0;
  47211. pOut->flags |= MEM_Static;
  47212. pOut->flags &= ~MEM_Dyn;
  47213. if( pOp->p4type==P4_DYNAMIC ){
  47214. sqlite3DbFree(db, pOp->p4.z);
  47215. }
  47216. pOp->p4type = P4_DYNAMIC;
  47217. pOp->p4.z = pOut->z;
  47218. pOp->p1 = pOut->n;
  47219. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  47220. goto too_big;
  47221. }
  47222. UPDATE_MAX_BLOBSIZE(pOut);
  47223. break;
  47224. }
  47225. #endif
  47226. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  47227. goto too_big;
  47228. }
  47229. /* Fall through to the next case, OP_String */
  47230. }
  47231. /* Opcode: String P1 P2 * P4 *
  47232. **
  47233. ** The string value P4 of length P1 (bytes) is stored in register P2.
  47234. */
  47235. case OP_String: { /* out2-prerelease */
  47236. assert( pOp->p4.z!=0 );
  47237. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  47238. pOut->z = pOp->p4.z;
  47239. pOut->n = pOp->p1;
  47240. pOut->enc = encoding;
  47241. UPDATE_MAX_BLOBSIZE(pOut);
  47242. break;
  47243. }
  47244. /* Opcode: Null * P2 * * *
  47245. **
  47246. ** Write a NULL into register P2.
  47247. */
  47248. case OP_Null: { /* out2-prerelease */
  47249. break;
  47250. }
  47251. /* Opcode: Blob P1 P2 * P4
  47252. **
  47253. ** P4 points to a blob of data P1 bytes long. Store this
  47254. ** blob in register P2. This instruction is not coded directly
  47255. ** by the compiler. Instead, the compiler layer specifies
  47256. ** an OP_HexBlob opcode, with the hex string representation of
  47257. ** the blob as P4. This opcode is transformed to an OP_Blob
  47258. ** the first time it is executed.
  47259. */
  47260. case OP_Blob: { /* out2-prerelease */
  47261. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  47262. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  47263. pOut->enc = encoding;
  47264. UPDATE_MAX_BLOBSIZE(pOut);
  47265. break;
  47266. }
  47267. /* Opcode: Variable P1 P2 P3 P4 *
  47268. **
  47269. ** Transfer the values of bound parameters P1..P1+P3-1 into registers
  47270. ** P2..P2+P3-1.
  47271. **
  47272. ** If the parameter is named, then its name appears in P4 and P3==1.
  47273. ** The P4 value is used by sqlite3_bind_parameter_name().
  47274. */
  47275. case OP_Variable: {
  47276. int j = pOp->p1 - 1;
  47277. int k = pOp->p2;
  47278. Mem *pVar;
  47279. int n = pOp->p3;
  47280. assert( j>=0 && j+n<=p->nVar );
  47281. assert( k>=1 && k+n-1<=p->nMem );
  47282. assert( pOp->p4.z==0 || pOp->p3==1 );
  47283. while( n-- > 0 ){
  47284. pVar = &p->aVar[j++];
  47285. if( sqlite3VdbeMemTooBig(pVar) ){
  47286. goto too_big;
  47287. }
  47288. pOut = &p->aMem[k++];
  47289. sqlite3VdbeMemReleaseExternal(pOut);
  47290. pOut->flags = MEM_Null;
  47291. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  47292. UPDATE_MAX_BLOBSIZE(pOut);
  47293. }
  47294. break;
  47295. }
  47296. /* Opcode: Move P1 P2 P3 * *
  47297. **
  47298. ** Move the values in register P1..P1+P3-1 over into
  47299. ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
  47300. ** left holding a NULL. It is an error for register ranges
  47301. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
  47302. */
  47303. case OP_Move: {
  47304. char *zMalloc;
  47305. int n = pOp->p3;
  47306. int p1 = pOp->p1;
  47307. int p2 = pOp->p2;
  47308. assert( n>0 && p1>0 && p2>0 );
  47309. assert( p1+n<=p2 || p2+n<=p1 );
  47310. pIn1 = &p->aMem[p1];
  47311. pOut = &p->aMem[p2];
  47312. while( n-- ){
  47313. assert( pOut<=&p->aMem[p->nMem] );
  47314. assert( pIn1<=&p->aMem[p->nMem] );
  47315. zMalloc = pOut->zMalloc;
  47316. pOut->zMalloc = 0;
  47317. sqlite3VdbeMemMove(pOut, pIn1);
  47318. pIn1->zMalloc = zMalloc;
  47319. REGISTER_TRACE(p2++, pOut);
  47320. pIn1++;
  47321. pOut++;
  47322. }
  47323. break;
  47324. }
  47325. /* Opcode: Copy P1 P2 * * *
  47326. **
  47327. ** Make a copy of register P1 into register P2.
  47328. **
  47329. ** This instruction makes a deep copy of the value. A duplicate
  47330. ** is made of any string or blob constant. See also OP_SCopy.
  47331. */
  47332. case OP_Copy: { /* in1 */
  47333. assert( pOp->p2>0 );
  47334. assert( pOp->p2<=p->nMem );
  47335. pOut = &p->aMem[pOp->p2];
  47336. assert( pOut!=pIn1 );
  47337. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  47338. Deephemeralize(pOut);
  47339. REGISTER_TRACE(pOp->p2, pOut);
  47340. break;
  47341. }
  47342. /* Opcode: SCopy P1 P2 * * *
  47343. **
  47344. ** Make a shallow copy of register P1 into register P2.
  47345. **
  47346. ** This instruction makes a shallow copy of the value. If the value
  47347. ** is a string or blob, then the copy is only a pointer to the
  47348. ** original and hence if the original changes so will the copy.
  47349. ** Worse, if the original is deallocated, the copy becomes invalid.
  47350. ** Thus the program must guarantee that the original will not change
  47351. ** during the lifetime of the copy. Use OP_Copy to make a complete
  47352. ** copy.
  47353. */
  47354. case OP_SCopy: { /* in1 */
  47355. REGISTER_TRACE(pOp->p1, pIn1);
  47356. assert( pOp->p2>0 );
  47357. assert( pOp->p2<=p->nMem );
  47358. pOut = &p->aMem[pOp->p2];
  47359. assert( pOut!=pIn1 );
  47360. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  47361. REGISTER_TRACE(pOp->p2, pOut);
  47362. break;
  47363. }
  47364. /* Opcode: ResultRow P1 P2 * * *
  47365. **
  47366. ** The registers P1 through P1+P2-1 contain a single row of
  47367. ** results. This opcode causes the sqlite3_step() call to terminate
  47368. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  47369. ** structure to provide access to the top P1 values as the result
  47370. ** row.
  47371. */
  47372. case OP_ResultRow: {
  47373. Mem *pMem;
  47374. int i;
  47375. assert( p->nResColumn==pOp->p2 );
  47376. assert( pOp->p1>0 );
  47377. assert( pOp->p1+pOp->p2<=p->nMem+1 );
  47378. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  47379. ** DML statements invoke this opcode to return the number of rows
  47380. ** modified to the user. This is the only way that a VM that
  47381. ** opens a statement transaction may invoke this opcode.
  47382. **
  47383. ** In case this is such a statement, close any statement transaction
  47384. ** opened by this VM before returning control to the user. This is to
  47385. ** ensure that statement-transactions are always nested, not overlapping.
  47386. ** If the open statement-transaction is not closed here, then the user
  47387. ** may step another VM that opens its own statement transaction. This
  47388. ** may lead to overlapping statement transactions.
  47389. */
  47390. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  47391. if( SQLITE_OK!=(rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE)) ){
  47392. break;
  47393. }
  47394. /* Invalidate all ephemeral cursor row caches */
  47395. p->cacheCtr = (p->cacheCtr + 2)|1;
  47396. /* Make sure the results of the current row are \000 terminated
  47397. ** and have an assigned type. The results are de-ephemeralized as
  47398. ** as side effect.
  47399. */
  47400. pMem = p->pResultSet = &p->aMem[pOp->p1];
  47401. for(i=0; i<pOp->p2; i++){
  47402. sqlite3VdbeMemNulTerminate(&pMem[i]);
  47403. storeTypeInfo(&pMem[i], encoding);
  47404. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  47405. }
  47406. if( db->mallocFailed ) goto no_mem;
  47407. /* Return SQLITE_ROW
  47408. */
  47409. p->pc = pc + 1;
  47410. rc = SQLITE_ROW;
  47411. goto vdbe_return;
  47412. }
  47413. /* Opcode: Concat P1 P2 P3 * *
  47414. **
  47415. ** Add the text in register P1 onto the end of the text in
  47416. ** register P2 and store the result in register P3.
  47417. ** If either the P1 or P2 text are NULL then store NULL in P3.
  47418. **
  47419. ** P3 = P2 || P1
  47420. **
  47421. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  47422. ** if P3 is the same register as P2, the implementation is able
  47423. ** to avoid a memcpy().
  47424. */
  47425. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  47426. i64 nByte;
  47427. assert( pIn1!=pOut );
  47428. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  47429. sqlite3VdbeMemSetNull(pOut);
  47430. break;
  47431. }
  47432. ExpandBlob(pIn1);
  47433. Stringify(pIn1, encoding);
  47434. ExpandBlob(pIn2);
  47435. Stringify(pIn2, encoding);
  47436. nByte = pIn1->n + pIn2->n;
  47437. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  47438. goto too_big;
  47439. }
  47440. MemSetTypeFlag(pOut, MEM_Str);
  47441. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  47442. goto no_mem;
  47443. }
  47444. if( pOut!=pIn2 ){
  47445. memcpy(pOut->z, pIn2->z, pIn2->n);
  47446. }
  47447. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  47448. pOut->z[nByte] = 0;
  47449. pOut->z[nByte+1] = 0;
  47450. pOut->flags |= MEM_Term;
  47451. pOut->n = (int)nByte;
  47452. pOut->enc = encoding;
  47453. UPDATE_MAX_BLOBSIZE(pOut);
  47454. break;
  47455. }
  47456. /* Opcode: Add P1 P2 P3 * *
  47457. **
  47458. ** Add the value in register P1 to the value in register P2
  47459. ** and store the result in register P3.
  47460. ** If either input is NULL, the result is NULL.
  47461. */
  47462. /* Opcode: Multiply P1 P2 P3 * *
  47463. **
  47464. **
  47465. ** Multiply the value in register P1 by the value in register P2
  47466. ** and store the result in register P3.
  47467. ** If either input is NULL, the result is NULL.
  47468. */
  47469. /* Opcode: Subtract P1 P2 P3 * *
  47470. **
  47471. ** Subtract the value in register P1 from the value in register P2
  47472. ** and store the result in register P3.
  47473. ** If either input is NULL, the result is NULL.
  47474. */
  47475. /* Opcode: Divide P1 P2 P3 * *
  47476. **
  47477. ** Divide the value in register P1 by the value in register P2
  47478. ** and store the result in register P3. If the value in register P2
  47479. ** is zero, then the result is NULL.
  47480. ** If either input is NULL, the result is NULL.
  47481. */
  47482. /* Opcode: Remainder P1 P2 P3 * *
  47483. **
  47484. ** Compute the remainder after integer division of the value in
  47485. ** register P1 by the value in register P2 and store the result in P3.
  47486. ** If the value in register P2 is zero the result is NULL.
  47487. ** If either operand is NULL, the result is NULL.
  47488. */
  47489. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  47490. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  47491. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  47492. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  47493. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  47494. int flags;
  47495. applyNumericAffinity(pIn1);
  47496. applyNumericAffinity(pIn2);
  47497. flags = pIn1->flags | pIn2->flags;
  47498. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  47499. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  47500. i64 a, b;
  47501. a = pIn1->u.i;
  47502. b = pIn2->u.i;
  47503. switch( pOp->opcode ){
  47504. case OP_Add: b += a; break;
  47505. case OP_Subtract: b -= a; break;
  47506. case OP_Multiply: b *= a; break;
  47507. case OP_Divide: {
  47508. if( a==0 ) goto arithmetic_result_is_null;
  47509. /* Dividing the largest possible negative 64-bit integer (1<<63) by
  47510. ** -1 returns an integer too large to store in a 64-bit data-type. On
  47511. ** some architectures, the value overflows to (1<<63). On others,
  47512. ** a SIGFPE is issued. The following statement normalizes this
  47513. ** behavior so that all architectures behave as if integer
  47514. ** overflow occurred.
  47515. */
  47516. if( a==-1 && b==SMALLEST_INT64 ) a = 1;
  47517. b /= a;
  47518. break;
  47519. }
  47520. default: {
  47521. if( a==0 ) goto arithmetic_result_is_null;
  47522. if( a==-1 ) a = 1;
  47523. b %= a;
  47524. break;
  47525. }
  47526. }
  47527. pOut->u.i = b;
  47528. MemSetTypeFlag(pOut, MEM_Int);
  47529. }else{
  47530. double a, b;
  47531. a = sqlite3VdbeRealValue(pIn1);
  47532. b = sqlite3VdbeRealValue(pIn2);
  47533. switch( pOp->opcode ){
  47534. case OP_Add: b += a; break;
  47535. case OP_Subtract: b -= a; break;
  47536. case OP_Multiply: b *= a; break;
  47537. case OP_Divide: {
  47538. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  47539. if( a==(double)0 ) goto arithmetic_result_is_null;
  47540. b /= a;
  47541. break;
  47542. }
  47543. default: {
  47544. i64 ia = (i64)a;
  47545. i64 ib = (i64)b;
  47546. if( ia==0 ) goto arithmetic_result_is_null;
  47547. if( ia==-1 ) ia = 1;
  47548. b = (double)(ib % ia);
  47549. break;
  47550. }
  47551. }
  47552. if( sqlite3IsNaN(b) ){
  47553. goto arithmetic_result_is_null;
  47554. }
  47555. pOut->r = b;
  47556. MemSetTypeFlag(pOut, MEM_Real);
  47557. if( (flags & MEM_Real)==0 ){
  47558. sqlite3VdbeIntegerAffinity(pOut);
  47559. }
  47560. }
  47561. break;
  47562. arithmetic_result_is_null:
  47563. sqlite3VdbeMemSetNull(pOut);
  47564. break;
  47565. }
  47566. /* Opcode: CollSeq * * P4
  47567. **
  47568. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  47569. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  47570. ** be returned. This is used by the built-in min(), max() and nullif()
  47571. ** functions.
  47572. **
  47573. ** The interface used by the implementation of the aforementioned functions
  47574. ** to retrieve the collation sequence set by this opcode is not available
  47575. ** publicly, only to user functions defined in func.c.
  47576. */
  47577. case OP_CollSeq: {
  47578. assert( pOp->p4type==P4_COLLSEQ );
  47579. break;
  47580. }
  47581. /* Opcode: Function P1 P2 P3 P4 P5
  47582. **
  47583. ** Invoke a user function (P4 is a pointer to a Function structure that
  47584. ** defines the function) with P5 arguments taken from register P2 and
  47585. ** successors. The result of the function is stored in register P3.
  47586. ** Register P3 must not be one of the function inputs.
  47587. **
  47588. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  47589. ** function was determined to be constant at compile time. If the first
  47590. ** argument was constant then bit 0 of P1 is set. This is used to determine
  47591. ** whether meta data associated with a user function argument using the
  47592. ** sqlite3_set_auxdata() API may be safely retained until the next
  47593. ** invocation of this opcode.
  47594. **
  47595. ** See also: AggStep and AggFinal
  47596. */
  47597. case OP_Function: {
  47598. int i;
  47599. Mem *pArg;
  47600. sqlite3_context ctx;
  47601. sqlite3_value **apVal;
  47602. int n = pOp->p5;
  47603. apVal = p->apArg;
  47604. assert( apVal || n==0 );
  47605. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem+1) );
  47606. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  47607. pArg = &p->aMem[pOp->p2];
  47608. for(i=0; i<n; i++, pArg++){
  47609. apVal[i] = pArg;
  47610. storeTypeInfo(pArg, encoding);
  47611. REGISTER_TRACE(pOp->p2, pArg);
  47612. }
  47613. assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
  47614. if( pOp->p4type==P4_FUNCDEF ){
  47615. ctx.pFunc = pOp->p4.pFunc;
  47616. ctx.pVdbeFunc = 0;
  47617. }else{
  47618. ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
  47619. ctx.pFunc = ctx.pVdbeFunc->pFunc;
  47620. }
  47621. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  47622. pOut = &p->aMem[pOp->p3];
  47623. ctx.s.flags = MEM_Null;
  47624. ctx.s.db = db;
  47625. ctx.s.xDel = 0;
  47626. ctx.s.zMalloc = 0;
  47627. /* The output cell may already have a buffer allocated. Move
  47628. ** the pointer to ctx.s so in case the user-function can use
  47629. ** the already allocated buffer instead of allocating a new one.
  47630. */
  47631. sqlite3VdbeMemMove(&ctx.s, pOut);
  47632. MemSetTypeFlag(&ctx.s, MEM_Null);
  47633. ctx.isError = 0;
  47634. if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  47635. assert( pOp>p->aOp );
  47636. assert( pOp[-1].p4type==P4_COLLSEQ );
  47637. assert( pOp[-1].opcode==OP_CollSeq );
  47638. ctx.pColl = pOp[-1].p4.pColl;
  47639. }
  47640. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  47641. (*ctx.pFunc->xFunc)(&ctx, n, apVal);
  47642. if( sqlite3SafetyOn(db) ){
  47643. sqlite3VdbeMemRelease(&ctx.s);
  47644. goto abort_due_to_misuse;
  47645. }
  47646. if( db->mallocFailed ){
  47647. /* Even though a malloc() has failed, the implementation of the
  47648. ** user function may have called an sqlite3_result_XXX() function
  47649. ** to return a value. The following call releases any resources
  47650. ** associated with such a value.
  47651. **
  47652. ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
  47653. ** fails also (the if(...) statement above). But if people are
  47654. ** misusing sqlite, they have bigger problems than a leaked value.
  47655. */
  47656. sqlite3VdbeMemRelease(&ctx.s);
  47657. goto no_mem;
  47658. }
  47659. /* If any auxiliary data functions have been called by this user function,
  47660. ** immediately call the destructor for any non-static values.
  47661. */
  47662. if( ctx.pVdbeFunc ){
  47663. sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
  47664. pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
  47665. pOp->p4type = P4_VDBEFUNC;
  47666. }
  47667. /* If the function returned an error, throw an exception */
  47668. if( ctx.isError ){
  47669. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
  47670. rc = ctx.isError;
  47671. }
  47672. /* Copy the result of the function into register P3 */
  47673. sqlite3VdbeChangeEncoding(&ctx.s, encoding);
  47674. sqlite3VdbeMemMove(pOut, &ctx.s);
  47675. if( sqlite3VdbeMemTooBig(pOut) ){
  47676. goto too_big;
  47677. }
  47678. REGISTER_TRACE(pOp->p3, pOut);
  47679. UPDATE_MAX_BLOBSIZE(pOut);
  47680. break;
  47681. }
  47682. /* Opcode: BitAnd P1 P2 P3 * *
  47683. **
  47684. ** Take the bit-wise AND of the values in register P1 and P2 and
  47685. ** store the result in register P3.
  47686. ** If either input is NULL, the result is NULL.
  47687. */
  47688. /* Opcode: BitOr P1 P2 P3 * *
  47689. **
  47690. ** Take the bit-wise OR of the values in register P1 and P2 and
  47691. ** store the result in register P3.
  47692. ** If either input is NULL, the result is NULL.
  47693. */
  47694. /* Opcode: ShiftLeft P1 P2 P3 * *
  47695. **
  47696. ** Shift the integer value in register P2 to the left by the
  47697. ** number of bits specified by the integer in regiser P1.
  47698. ** Store the result in register P3.
  47699. ** If either input is NULL, the result is NULL.
  47700. */
  47701. /* Opcode: ShiftRight P1 P2 P3 * *
  47702. **
  47703. ** Shift the integer value in register P2 to the right by the
  47704. ** number of bits specified by the integer in register P1.
  47705. ** Store the result in register P3.
  47706. ** If either input is NULL, the result is NULL.
  47707. */
  47708. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  47709. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  47710. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  47711. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  47712. i64 a, b;
  47713. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  47714. sqlite3VdbeMemSetNull(pOut);
  47715. break;
  47716. }
  47717. a = sqlite3VdbeIntValue(pIn2);
  47718. b = sqlite3VdbeIntValue(pIn1);
  47719. switch( pOp->opcode ){
  47720. case OP_BitAnd: a &= b; break;
  47721. case OP_BitOr: a |= b; break;
  47722. case OP_ShiftLeft: a <<= b; break;
  47723. default: assert( pOp->opcode==OP_ShiftRight );
  47724. a >>= b; break;
  47725. }
  47726. pOut->u.i = a;
  47727. MemSetTypeFlag(pOut, MEM_Int);
  47728. break;
  47729. }
  47730. /* Opcode: AddImm P1 P2 * * *
  47731. **
  47732. ** Add the constant P2 to the value in register P1.
  47733. ** The result is always an integer.
  47734. **
  47735. ** To force any register to be an integer, just add 0.
  47736. */
  47737. case OP_AddImm: { /* in1 */
  47738. sqlite3VdbeMemIntegerify(pIn1);
  47739. pIn1->u.i += pOp->p2;
  47740. break;
  47741. }
  47742. /* Opcode: MustBeInt P1 P2 * * *
  47743. **
  47744. ** Force the value in register P1 to be an integer. If the value
  47745. ** in P1 is not an integer and cannot be converted into an integer
  47746. ** without data loss, then jump immediately to P2, or if P2==0
  47747. ** raise an SQLITE_MISMATCH exception.
  47748. */
  47749. case OP_MustBeInt: { /* jump, in1 */
  47750. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  47751. if( (pIn1->flags & MEM_Int)==0 ){
  47752. if( pOp->p2==0 ){
  47753. rc = SQLITE_MISMATCH;
  47754. goto abort_due_to_error;
  47755. }else{
  47756. pc = pOp->p2 - 1;
  47757. }
  47758. }else{
  47759. MemSetTypeFlag(pIn1, MEM_Int);
  47760. }
  47761. break;
  47762. }
  47763. /* Opcode: RealAffinity P1 * * * *
  47764. **
  47765. ** If register P1 holds an integer convert it to a real value.
  47766. **
  47767. ** This opcode is used when extracting information from a column that
  47768. ** has REAL affinity. Such column values may still be stored as
  47769. ** integers, for space efficiency, but after extraction we want them
  47770. ** to have only a real value.
  47771. */
  47772. case OP_RealAffinity: { /* in1 */
  47773. if( pIn1->flags & MEM_Int ){
  47774. sqlite3VdbeMemRealify(pIn1);
  47775. }
  47776. break;
  47777. }
  47778. #ifndef SQLITE_OMIT_CAST
  47779. /* Opcode: ToText P1 * * * *
  47780. **
  47781. ** Force the value in register P1 to be text.
  47782. ** If the value is numeric, convert it to a string using the
  47783. ** equivalent of printf(). Blob values are unchanged and
  47784. ** are afterwards simply interpreted as text.
  47785. **
  47786. ** A NULL value is not changed by this routine. It remains NULL.
  47787. */
  47788. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  47789. if( pIn1->flags & MEM_Null ) break;
  47790. assert( MEM_Str==(MEM_Blob>>3) );
  47791. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  47792. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  47793. rc = ExpandBlob(pIn1);
  47794. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  47795. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  47796. UPDATE_MAX_BLOBSIZE(pIn1);
  47797. break;
  47798. }
  47799. /* Opcode: ToBlob P1 * * * *
  47800. **
  47801. ** Force the value in register P1 to be a BLOB.
  47802. ** If the value is numeric, convert it to a string first.
  47803. ** Strings are simply reinterpreted as blobs with no change
  47804. ** to the underlying data.
  47805. **
  47806. ** A NULL value is not changed by this routine. It remains NULL.
  47807. */
  47808. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  47809. if( pIn1->flags & MEM_Null ) break;
  47810. if( (pIn1->flags & MEM_Blob)==0 ){
  47811. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  47812. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  47813. MemSetTypeFlag(pIn1, MEM_Blob);
  47814. }else{
  47815. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  47816. }
  47817. UPDATE_MAX_BLOBSIZE(pIn1);
  47818. break;
  47819. }
  47820. /* Opcode: ToNumeric P1 * * * *
  47821. **
  47822. ** Force the value in register P1 to be numeric (either an
  47823. ** integer or a floating-point number.)
  47824. ** If the value is text or blob, try to convert it to an using the
  47825. ** equivalent of atoi() or atof() and store 0 if no such conversion
  47826. ** is possible.
  47827. **
  47828. ** A NULL value is not changed by this routine. It remains NULL.
  47829. */
  47830. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  47831. if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
  47832. sqlite3VdbeMemNumerify(pIn1);
  47833. }
  47834. break;
  47835. }
  47836. #endif /* SQLITE_OMIT_CAST */
  47837. /* Opcode: ToInt P1 * * * *
  47838. **
  47839. ** Force the value in register P1 be an integer. If
  47840. ** The value is currently a real number, drop its fractional part.
  47841. ** If the value is text or blob, try to convert it to an integer using the
  47842. ** equivalent of atoi() and store 0 if no such conversion is possible.
  47843. **
  47844. ** A NULL value is not changed by this routine. It remains NULL.
  47845. */
  47846. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  47847. if( (pIn1->flags & MEM_Null)==0 ){
  47848. sqlite3VdbeMemIntegerify(pIn1);
  47849. }
  47850. break;
  47851. }
  47852. #ifndef SQLITE_OMIT_CAST
  47853. /* Opcode: ToReal P1 * * * *
  47854. **
  47855. ** Force the value in register P1 to be a floating point number.
  47856. ** If The value is currently an integer, convert it.
  47857. ** If the value is text or blob, try to convert it to an integer using the
  47858. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  47859. **
  47860. ** A NULL value is not changed by this routine. It remains NULL.
  47861. */
  47862. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  47863. if( (pIn1->flags & MEM_Null)==0 ){
  47864. sqlite3VdbeMemRealify(pIn1);
  47865. }
  47866. break;
  47867. }
  47868. #endif /* SQLITE_OMIT_CAST */
  47869. /* Opcode: Lt P1 P2 P3 P4 P5
  47870. **
  47871. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  47872. ** jump to address P2.
  47873. **
  47874. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  47875. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  47876. ** bit is clear then fall thru if either operand is NULL.
  47877. **
  47878. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  47879. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  47880. ** to coerce both inputs according to this affinity before the
  47881. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  47882. ** affinity is used. Note that the affinity conversions are stored
  47883. ** back into the input registers P1 and P3. So this opcode can cause
  47884. ** persistent changes to registers P1 and P3.
  47885. **
  47886. ** Once any conversions have taken place, and neither value is NULL,
  47887. ** the values are compared. If both values are blobs then memcmp() is
  47888. ** used to determine the results of the comparison. If both values
  47889. ** are text, then the appropriate collating function specified in
  47890. ** P4 is used to do the comparison. If P4 is not specified then
  47891. ** memcmp() is used to compare text string. If both values are
  47892. ** numeric, then a numeric comparison is used. If the two values
  47893. ** are of different types, then numbers are considered less than
  47894. ** strings and strings are considered less than blobs.
  47895. **
  47896. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  47897. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  47898. */
  47899. /* Opcode: Ne P1 P2 P3 P4 P5
  47900. **
  47901. ** This works just like the Lt opcode except that the jump is taken if
  47902. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  47903. ** additional information.
  47904. */
  47905. /* Opcode: Eq P1 P2 P3 P4 P5
  47906. **
  47907. ** This works just like the Lt opcode except that the jump is taken if
  47908. ** the operands in registers P1 and P3 are equal.
  47909. ** See the Lt opcode for additional information.
  47910. */
  47911. /* Opcode: Le P1 P2 P3 P4 P5
  47912. **
  47913. ** This works just like the Lt opcode except that the jump is taken if
  47914. ** the content of register P3 is less than or equal to the content of
  47915. ** register P1. See the Lt opcode for additional information.
  47916. */
  47917. /* Opcode: Gt P1 P2 P3 P4 P5
  47918. **
  47919. ** This works just like the Lt opcode except that the jump is taken if
  47920. ** the content of register P3 is greater than the content of
  47921. ** register P1. See the Lt opcode for additional information.
  47922. */
  47923. /* Opcode: Ge P1 P2 P3 P4 P5
  47924. **
  47925. ** This works just like the Lt opcode except that the jump is taken if
  47926. ** the content of register P3 is greater than or equal to the content of
  47927. ** register P1. See the Lt opcode for additional information.
  47928. */
  47929. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  47930. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  47931. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  47932. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  47933. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  47934. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  47935. int flags;
  47936. int res;
  47937. char affinity;
  47938. flags = pIn1->flags|pIn3->flags;
  47939. if( flags&MEM_Null ){
  47940. /* If either operand is NULL then the result is always NULL.
  47941. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  47942. */
  47943. if( pOp->p5 & SQLITE_STOREP2 ){
  47944. pOut = &p->aMem[pOp->p2];
  47945. MemSetTypeFlag(pOut, MEM_Null);
  47946. REGISTER_TRACE(pOp->p2, pOut);
  47947. }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
  47948. pc = pOp->p2-1;
  47949. }
  47950. break;
  47951. }
  47952. affinity = pOp->p5 & SQLITE_AFF_MASK;
  47953. if( affinity ){
  47954. applyAffinity(pIn1, affinity, encoding);
  47955. applyAffinity(pIn3, affinity, encoding);
  47956. if( db->mallocFailed ) goto no_mem;
  47957. }
  47958. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  47959. ExpandBlob(pIn1);
  47960. ExpandBlob(pIn3);
  47961. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  47962. switch( pOp->opcode ){
  47963. case OP_Eq: res = res==0; break;
  47964. case OP_Ne: res = res!=0; break;
  47965. case OP_Lt: res = res<0; break;
  47966. case OP_Le: res = res<=0; break;
  47967. case OP_Gt: res = res>0; break;
  47968. default: res = res>=0; break;
  47969. }
  47970. if( pOp->p5 & SQLITE_STOREP2 ){
  47971. pOut = &p->aMem[pOp->p2];
  47972. MemSetTypeFlag(pOut, MEM_Int);
  47973. pOut->u.i = res;
  47974. REGISTER_TRACE(pOp->p2, pOut);
  47975. }else if( res ){
  47976. pc = pOp->p2-1;
  47977. }
  47978. break;
  47979. }
  47980. /* Opcode: Permutation * * * P4 *
  47981. **
  47982. ** Set the permutation used by the OP_Compare operator to be the array
  47983. ** of integers in P4.
  47984. **
  47985. ** The permutation is only valid until the next OP_Permutation, OP_Compare,
  47986. ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
  47987. ** immediately prior to the OP_Compare.
  47988. */
  47989. case OP_Permutation: {
  47990. assert( pOp->p4type==P4_INTARRAY );
  47991. assert( pOp->p4.ai );
  47992. aPermute = pOp->p4.ai;
  47993. break;
  47994. }
  47995. /* Opcode: Compare P1 P2 P3 P4 *
  47996. **
  47997. ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
  47998. ** one "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  47999. ** the comparison for use by the next OP_Jump instruct.
  48000. **
  48001. ** P4 is a KeyInfo structure that defines collating sequences and sort
  48002. ** orders for the comparison. The permutation applies to registers
  48003. ** only. The KeyInfo elements are used sequentially.
  48004. **
  48005. ** The comparison is a sort comparison, so NULLs compare equal,
  48006. ** NULLs are less than numbers, numbers are less than strings,
  48007. ** and strings are less than blobs.
  48008. */
  48009. case OP_Compare: {
  48010. int n = pOp->p3;
  48011. int i, p1, p2;
  48012. const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  48013. assert( n>0 );
  48014. assert( pKeyInfo!=0 );
  48015. p1 = pOp->p1;
  48016. assert( p1>0 && p1+n<=p->nMem+1 );
  48017. p2 = pOp->p2;
  48018. assert( p2>0 && p2+n<=p->nMem+1 );
  48019. for(i=0; i<n; i++){
  48020. int idx = aPermute ? aPermute[i] : i;
  48021. CollSeq *pColl; /* Collating sequence to use on this term */
  48022. int bRev; /* True for DESCENDING sort order */
  48023. REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
  48024. REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
  48025. assert( i<pKeyInfo->nField );
  48026. pColl = pKeyInfo->aColl[i];
  48027. bRev = pKeyInfo->aSortOrder[i];
  48028. iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
  48029. if( iCompare ){
  48030. if( bRev ) iCompare = -iCompare;
  48031. break;
  48032. }
  48033. }
  48034. aPermute = 0;
  48035. break;
  48036. }
  48037. /* Opcode: Jump P1 P2 P3 * *
  48038. **
  48039. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  48040. ** in the most recent OP_Compare instruction the P1 vector was less than
  48041. ** equal to, or greater than the P2 vector, respectively.
  48042. */
  48043. case OP_Jump: { /* jump */
  48044. if( iCompare<0 ){
  48045. pc = pOp->p1 - 1;
  48046. }else if( iCompare==0 ){
  48047. pc = pOp->p2 - 1;
  48048. }else{
  48049. pc = pOp->p3 - 1;
  48050. }
  48051. break;
  48052. }
  48053. /* Opcode: And P1 P2 P3 * *
  48054. **
  48055. ** Take the logical AND of the values in registers P1 and P2 and
  48056. ** write the result into register P3.
  48057. **
  48058. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  48059. ** the other input is NULL. A NULL and true or two NULLs give
  48060. ** a NULL output.
  48061. */
  48062. /* Opcode: Or P1 P2 P3 * *
  48063. **
  48064. ** Take the logical OR of the values in register P1 and P2 and
  48065. ** store the answer in register P3.
  48066. **
  48067. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  48068. ** even if the other input is NULL. A NULL and false or two NULLs
  48069. ** give a NULL output.
  48070. */
  48071. case OP_And: /* same as TK_AND, in1, in2, out3 */
  48072. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  48073. int v1, v2; /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  48074. if( pIn1->flags & MEM_Null ){
  48075. v1 = 2;
  48076. }else{
  48077. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  48078. }
  48079. if( pIn2->flags & MEM_Null ){
  48080. v2 = 2;
  48081. }else{
  48082. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  48083. }
  48084. if( pOp->opcode==OP_And ){
  48085. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  48086. v1 = and_logic[v1*3+v2];
  48087. }else{
  48088. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  48089. v1 = or_logic[v1*3+v2];
  48090. }
  48091. if( v1==2 ){
  48092. MemSetTypeFlag(pOut, MEM_Null);
  48093. }else{
  48094. pOut->u.i = v1;
  48095. MemSetTypeFlag(pOut, MEM_Int);
  48096. }
  48097. break;
  48098. }
  48099. /* Opcode: Not P1 P2 * * *
  48100. **
  48101. ** Interpret the value in register P1 as a boolean value. Store the
  48102. ** boolean complement in register P2. If the value in register P1 is
  48103. ** NULL, then a NULL is stored in P2.
  48104. */
  48105. case OP_Not: { /* same as TK_NOT, in1 */
  48106. pOut = &p->aMem[pOp->p2];
  48107. if( pIn1->flags & MEM_Null ){
  48108. sqlite3VdbeMemSetNull(pOut);
  48109. }else{
  48110. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  48111. }
  48112. break;
  48113. }
  48114. /* Opcode: BitNot P1 P2 * * *
  48115. **
  48116. ** Interpret the content of register P1 as an integer. Store the
  48117. ** ones-complement of the P1 value into register P2. If P1 holds
  48118. ** a NULL then store a NULL in P2.
  48119. */
  48120. case OP_BitNot: { /* same as TK_BITNOT, in1 */
  48121. pOut = &p->aMem[pOp->p2];
  48122. if( pIn1->flags & MEM_Null ){
  48123. sqlite3VdbeMemSetNull(pOut);
  48124. }else{
  48125. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  48126. }
  48127. break;
  48128. }
  48129. /* Opcode: If P1 P2 P3 * *
  48130. **
  48131. ** Jump to P2 if the value in register P1 is true. The value is
  48132. ** is considered true if it is numeric and non-zero. If the value
  48133. ** in P1 is NULL then take the jump if P3 is true.
  48134. */
  48135. /* Opcode: IfNot P1 P2 P3 * *
  48136. **
  48137. ** Jump to P2 if the value in register P1 is False. The value is
  48138. ** is considered true if it has a numeric value of zero. If the value
  48139. ** in P1 is NULL then take the jump if P3 is true.
  48140. */
  48141. case OP_If: /* jump, in1 */
  48142. case OP_IfNot: { /* jump, in1 */
  48143. int c;
  48144. if( pIn1->flags & MEM_Null ){
  48145. c = pOp->p3;
  48146. }else{
  48147. #ifdef SQLITE_OMIT_FLOATING_POINT
  48148. c = sqlite3VdbeIntValue(pIn1)!=0;
  48149. #else
  48150. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  48151. #endif
  48152. if( pOp->opcode==OP_IfNot ) c = !c;
  48153. }
  48154. if( c ){
  48155. pc = pOp->p2-1;
  48156. }
  48157. break;
  48158. }
  48159. /* Opcode: IsNull P1 P2 P3 * *
  48160. **
  48161. ** Jump to P2 if the value in register P1 is NULL. If P3 is greater
  48162. ** than zero, then check all values reg(P1), reg(P1+1),
  48163. ** reg(P1+2), ..., reg(P1+P3-1).
  48164. */
  48165. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  48166. int n = pOp->p3;
  48167. assert( pOp->p3==0 || pOp->p1>0 );
  48168. do{
  48169. if( (pIn1->flags & MEM_Null)!=0 ){
  48170. pc = pOp->p2 - 1;
  48171. break;
  48172. }
  48173. pIn1++;
  48174. }while( --n > 0 );
  48175. break;
  48176. }
  48177. /* Opcode: NotNull P1 P2 * * *
  48178. **
  48179. ** Jump to P2 if the value in register P1 is not NULL.
  48180. */
  48181. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  48182. if( (pIn1->flags & MEM_Null)==0 ){
  48183. pc = pOp->p2 - 1;
  48184. }
  48185. break;
  48186. }
  48187. /* Opcode: SetNumColumns * P2 * * *
  48188. **
  48189. ** This opcode sets the number of columns for the cursor opened by the
  48190. ** following instruction to P2.
  48191. **
  48192. ** An OP_SetNumColumns is only useful if it occurs immediately before
  48193. ** one of the following opcodes:
  48194. **
  48195. ** OpenRead
  48196. ** OpenWrite
  48197. ** OpenPseudo
  48198. **
  48199. ** If the OP_Column opcode is to be executed on a cursor, then
  48200. ** this opcode must be present immediately before the opcode that
  48201. ** opens the cursor.
  48202. */
  48203. #if 0
  48204. case OP_SetNumColumns: {
  48205. break;
  48206. }
  48207. #endif
  48208. /* Opcode: Column P1 P2 P3 P4 *
  48209. **
  48210. ** Interpret the data that cursor P1 points to as a structure built using
  48211. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  48212. ** information about the format of the data.) Extract the P2-th column
  48213. ** from this record. If there are less that (P2+1)
  48214. ** values in the record, extract a NULL.
  48215. **
  48216. ** The value extracted is stored in register P3.
  48217. **
  48218. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  48219. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  48220. ** the result.
  48221. */
  48222. case OP_Column: {
  48223. int payloadSize; /* Number of bytes in the record */
  48224. int p1 = pOp->p1; /* P1 value of the opcode */
  48225. int p2 = pOp->p2; /* column number to retrieve */
  48226. VdbeCursor *pC = 0;/* The VDBE cursor */
  48227. char *zRec; /* Pointer to complete record-data */
  48228. BtCursor *pCrsr; /* The BTree cursor */
  48229. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  48230. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  48231. int nField; /* number of fields in the record */
  48232. int len; /* The length of the serialized data for the column */
  48233. int i; /* Loop counter */
  48234. char *zData; /* Part of the record being decoded */
  48235. Mem *pDest; /* Where to write the extracted value */
  48236. Mem sMem; /* For storing the record being decoded */
  48237. memset(&sMem, 0, sizeof(sMem));
  48238. assert( p1<p->nCursor );
  48239. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  48240. pDest = &p->aMem[pOp->p3];
  48241. MemSetTypeFlag(pDest, MEM_Null);
  48242. /* This block sets the variable payloadSize to be the total number of
  48243. ** bytes in the record.
  48244. **
  48245. ** zRec is set to be the complete text of the record if it is available.
  48246. ** The complete record text is always available for pseudo-tables
  48247. ** If the record is stored in a cursor, the complete record text
  48248. ** might be available in the pC->aRow cache. Or it might not be.
  48249. ** If the data is unavailable, zRec is set to NULL.
  48250. **
  48251. ** We also compute the number of columns in the record. For cursors,
  48252. ** the number of columns is stored in the VdbeCursor.nField element.
  48253. */
  48254. pC = p->apCsr[p1];
  48255. assert( pC!=0 );
  48256. #ifndef SQLITE_OMIT_VIRTUALTABLE
  48257. assert( pC->pVtabCursor==0 );
  48258. #endif
  48259. if( pC->pCursor!=0 ){
  48260. /* The record is stored in a B-Tree */
  48261. rc = sqlite3VdbeCursorMoveto(pC);
  48262. if( rc ) goto abort_due_to_error;
  48263. zRec = 0;
  48264. pCrsr = pC->pCursor;
  48265. if( pC->nullRow ){
  48266. payloadSize = 0;
  48267. }else if( pC->cacheStatus==p->cacheCtr ){
  48268. payloadSize = pC->payloadSize;
  48269. zRec = (char*)pC->aRow;
  48270. }else if( pC->isIndex ){
  48271. i64 payloadSize64;
  48272. sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  48273. payloadSize = (int)payloadSize64;
  48274. }else{
  48275. sqlite3BtreeDataSize(pCrsr, (u32 *)&payloadSize);
  48276. }
  48277. nField = pC->nField;
  48278. }else{
  48279. assert( pC->pseudoTable );
  48280. /* The record is the sole entry of a pseudo-table */
  48281. payloadSize = pC->nData;
  48282. zRec = pC->pData;
  48283. pC->cacheStatus = CACHE_STALE;
  48284. assert( payloadSize==0 || zRec!=0 );
  48285. nField = pC->nField;
  48286. pCrsr = 0;
  48287. }
  48288. /* If payloadSize is 0, then just store a NULL */
  48289. if( payloadSize==0 ){
  48290. assert( pDest->flags&MEM_Null );
  48291. goto op_column_out;
  48292. }
  48293. if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  48294. goto too_big;
  48295. }
  48296. assert( p2<nField );
  48297. /* Read and parse the table header. Store the results of the parse
  48298. ** into the record header cache fields of the cursor.
  48299. */
  48300. aType = pC->aType;
  48301. if( pC->cacheStatus==p->cacheCtr ){
  48302. aOffset = pC->aOffset;
  48303. }else{
  48304. u8 *zIdx; /* Index into header */
  48305. u8 *zEndHdr; /* Pointer to first byte after the header */
  48306. int offset; /* Offset into the data */
  48307. int szHdrSz; /* Size of the header size field at start of record */
  48308. int avail = 0; /* Number of bytes of available data */
  48309. assert(aType);
  48310. pC->aOffset = aOffset = &aType[nField];
  48311. pC->payloadSize = payloadSize;
  48312. pC->cacheStatus = p->cacheCtr;
  48313. /* Figure out how many bytes are in the header */
  48314. if( zRec ){
  48315. zData = zRec;
  48316. }else{
  48317. if( pC->isIndex ){
  48318. zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
  48319. }else{
  48320. zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
  48321. }
  48322. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  48323. ** save the payload in the pC->aRow cache. That will save us from
  48324. ** having to make additional calls to fetch the content portion of
  48325. ** the record.
  48326. */
  48327. if( avail>=payloadSize ){
  48328. zRec = zData;
  48329. pC->aRow = (u8*)zData;
  48330. }else{
  48331. pC->aRow = 0;
  48332. }
  48333. }
  48334. /* The following assert is true in all cases accept when
  48335. ** the database file has been corrupted externally.
  48336. ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
  48337. szHdrSz = getVarint32((u8*)zData, offset);
  48338. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  48339. ** record header in most cases. But they will fail to get the complete
  48340. ** record header if the record header does not fit on a single page
  48341. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  48342. ** acquire the complete header text.
  48343. */
  48344. if( !zRec && avail<offset ){
  48345. sMem.flags = 0;
  48346. sMem.db = 0;
  48347. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
  48348. if( rc!=SQLITE_OK ){
  48349. goto op_column_out;
  48350. }
  48351. zData = sMem.z;
  48352. }
  48353. zEndHdr = (u8 *)&zData[offset];
  48354. zIdx = (u8 *)&zData[szHdrSz];
  48355. /* Scan the header and use it to fill in the aType[] and aOffset[]
  48356. ** arrays. aType[i] will contain the type integer for the i-th
  48357. ** column and aOffset[i] will contain the offset from the beginning
  48358. ** of the record to the start of the data for the i-th column
  48359. */
  48360. for(i=0; i<nField; i++){
  48361. if( zIdx<zEndHdr ){
  48362. aOffset[i] = offset;
  48363. zIdx += getVarint32(zIdx, aType[i]);
  48364. offset += sqlite3VdbeSerialTypeLen(aType[i]);
  48365. }else{
  48366. /* If i is less that nField, then there are less fields in this
  48367. ** record than SetNumColumns indicated there are columns in the
  48368. ** table. Set the offset for any extra columns not present in
  48369. ** the record to 0. This tells code below to store a NULL
  48370. ** instead of deserializing a value from the record.
  48371. */
  48372. aOffset[i] = 0;
  48373. }
  48374. }
  48375. sqlite3VdbeMemRelease(&sMem);
  48376. sMem.flags = MEM_Null;
  48377. /* If we have read more header data than was contained in the header,
  48378. ** or if the end of the last field appears to be past the end of the
  48379. ** record, or if the end of the last field appears to be before the end
  48380. ** of the record (when all fields present), then we must be dealing
  48381. ** with a corrupt database.
  48382. */
  48383. if( zIdx>zEndHdr || offset>payloadSize
  48384. || (zIdx==zEndHdr && offset!=payloadSize) ){
  48385. rc = SQLITE_CORRUPT_BKPT;
  48386. goto op_column_out;
  48387. }
  48388. }
  48389. /* Get the column information. If aOffset[p2] is non-zero, then
  48390. ** deserialize the value from the record. If aOffset[p2] is zero,
  48391. ** then there are not enough fields in the record to satisfy the
  48392. ** request. In this case, set the value NULL or to P4 if P4 is
  48393. ** a pointer to a Mem object.
  48394. */
  48395. if( aOffset[p2] ){
  48396. assert( rc==SQLITE_OK );
  48397. if( zRec ){
  48398. sqlite3VdbeMemReleaseExternal(pDest);
  48399. sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
  48400. }else{
  48401. len = sqlite3VdbeSerialTypeLen(aType[p2]);
  48402. sqlite3VdbeMemMove(&sMem, pDest);
  48403. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
  48404. if( rc!=SQLITE_OK ){
  48405. goto op_column_out;
  48406. }
  48407. zData = sMem.z;
  48408. sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
  48409. }
  48410. pDest->enc = encoding;
  48411. }else{
  48412. if( pOp->p4type==P4_MEM ){
  48413. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  48414. }else{
  48415. assert( pDest->flags&MEM_Null );
  48416. }
  48417. }
  48418. /* If we dynamically allocated space to hold the data (in the
  48419. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  48420. ** dynamically allocated space over to the pDest structure.
  48421. ** This prevents a memory copy.
  48422. */
  48423. if( sMem.zMalloc ){
  48424. assert( sMem.z==sMem.zMalloc );
  48425. assert( !(pDest->flags & MEM_Dyn) );
  48426. assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
  48427. pDest->flags &= ~(MEM_Ephem|MEM_Static);
  48428. pDest->flags |= MEM_Term;
  48429. pDest->z = sMem.z;
  48430. pDest->zMalloc = sMem.zMalloc;
  48431. }
  48432. rc = sqlite3VdbeMemMakeWriteable(pDest);
  48433. op_column_out:
  48434. UPDATE_MAX_BLOBSIZE(pDest);
  48435. REGISTER_TRACE(pOp->p3, pDest);
  48436. break;
  48437. }
  48438. /* Opcode: Affinity P1 P2 * P4 *
  48439. **
  48440. ** Apply affinities to a range of P2 registers starting with P1.
  48441. **
  48442. ** P4 is a string that is P2 characters long. The nth character of the
  48443. ** string indicates the column affinity that should be used for the nth
  48444. ** memory cell in the range.
  48445. */
  48446. case OP_Affinity: {
  48447. char *zAffinity = pOp->p4.z;
  48448. Mem *pData0 = &p->aMem[pOp->p1];
  48449. Mem *pLast = &pData0[pOp->p2-1];
  48450. Mem *pRec;
  48451. for(pRec=pData0; pRec<=pLast; pRec++){
  48452. ExpandBlob(pRec);
  48453. applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
  48454. }
  48455. break;
  48456. }
  48457. /* Opcode: MakeRecord P1 P2 P3 P4 *
  48458. **
  48459. ** Convert P2 registers beginning with P1 into a single entry
  48460. ** suitable for use as a data record in a database table or as a key
  48461. ** in an index. The details of the format are irrelevant as long as
  48462. ** the OP_Column opcode can decode the record later.
  48463. ** Refer to source code comments for the details of the record
  48464. ** format.
  48465. **
  48466. ** P4 may be a string that is P2 characters long. The nth character of the
  48467. ** string indicates the column affinity that should be used for the nth
  48468. ** field of the index key.
  48469. **
  48470. ** The mapping from character to affinity is given by the SQLITE_AFF_
  48471. ** macros defined in sqliteInt.h.
  48472. **
  48473. ** If P4 is NULL then all index fields have the affinity NONE.
  48474. */
  48475. case OP_MakeRecord: {
  48476. /* Assuming the record contains N fields, the record format looks
  48477. ** like this:
  48478. **
  48479. ** ------------------------------------------------------------------------
  48480. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  48481. ** ------------------------------------------------------------------------
  48482. **
  48483. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  48484. ** and so froth.
  48485. **
  48486. ** Each type field is a varint representing the serial type of the
  48487. ** corresponding data element (see sqlite3VdbeSerialType()). The
  48488. ** hdr-size field is also a varint which is the offset from the beginning
  48489. ** of the record to data0.
  48490. */
  48491. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  48492. Mem *pRec; /* The new record */
  48493. u64 nData = 0; /* Number of bytes of data space */
  48494. int nHdr = 0; /* Number of bytes of header space */
  48495. i64 nByte = 0; /* Data space required for this record */
  48496. int nZero = 0; /* Number of zero bytes at the end of the record */
  48497. int nVarint; /* Number of bytes in a varint */
  48498. u32 serial_type; /* Type field */
  48499. Mem *pData0; /* First field to be combined into the record */
  48500. Mem *pLast; /* Last field of the record */
  48501. int nField; /* Number of fields in the record */
  48502. char *zAffinity; /* The affinity string for the record */
  48503. int file_format; /* File format to use for encoding */
  48504. int i; /* Space used in zNewRecord[] */
  48505. nField = pOp->p1;
  48506. zAffinity = pOp->p4.z;
  48507. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem+1 );
  48508. pData0 = &p->aMem[nField];
  48509. nField = pOp->p2;
  48510. pLast = &pData0[nField-1];
  48511. file_format = p->minWriteFileFormat;
  48512. /* Loop through the elements that will make up the record to figure
  48513. ** out how much space is required for the new record.
  48514. */
  48515. for(pRec=pData0; pRec<=pLast; pRec++){
  48516. int len;
  48517. if( zAffinity ){
  48518. applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
  48519. }
  48520. if( pRec->flags&MEM_Zero && pRec->n>0 ){
  48521. sqlite3VdbeMemExpandBlob(pRec);
  48522. }
  48523. serial_type = sqlite3VdbeSerialType(pRec, file_format);
  48524. len = sqlite3VdbeSerialTypeLen(serial_type);
  48525. nData += len;
  48526. nHdr += sqlite3VarintLen(serial_type);
  48527. if( pRec->flags & MEM_Zero ){
  48528. /* Only pure zero-filled BLOBs can be input to this Opcode.
  48529. ** We do not allow blobs with a prefix and a zero-filled tail. */
  48530. nZero += pRec->u.nZero;
  48531. }else if( len ){
  48532. nZero = 0;
  48533. }
  48534. }
  48535. /* Add the initial header varint and total the size */
  48536. nHdr += nVarint = sqlite3VarintLen(nHdr);
  48537. if( nVarint<sqlite3VarintLen(nHdr) ){
  48538. nHdr++;
  48539. }
  48540. nByte = nHdr+nData-nZero;
  48541. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  48542. goto too_big;
  48543. }
  48544. /* Make sure the output register has a buffer large enough to store
  48545. ** the new record. The output register (pOp->p3) is not allowed to
  48546. ** be one of the input registers (because the following call to
  48547. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  48548. */
  48549. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  48550. pOut = &p->aMem[pOp->p3];
  48551. if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
  48552. goto no_mem;
  48553. }
  48554. zNewRecord = (u8 *)pOut->z;
  48555. /* Write the record */
  48556. i = putVarint32(zNewRecord, nHdr);
  48557. for(pRec=pData0; pRec<=pLast; pRec++){
  48558. serial_type = sqlite3VdbeSerialType(pRec, file_format);
  48559. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  48560. }
  48561. for(pRec=pData0; pRec<=pLast; pRec++){ /* serial data */
  48562. i += sqlite3VdbeSerialPut(&zNewRecord[i], (int)(nByte-i), pRec,file_format);
  48563. }
  48564. assert( i==nByte );
  48565. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  48566. pOut->n = (int)nByte;
  48567. pOut->flags = MEM_Blob | MEM_Dyn;
  48568. pOut->xDel = 0;
  48569. if( nZero ){
  48570. pOut->u.nZero = nZero;
  48571. pOut->flags |= MEM_Zero;
  48572. }
  48573. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  48574. REGISTER_TRACE(pOp->p3, pOut);
  48575. UPDATE_MAX_BLOBSIZE(pOut);
  48576. break;
  48577. }
  48578. /* Opcode: Count P1 P2 * * *
  48579. **
  48580. ** Store the number of entries (an integer value) in the table or index
  48581. ** opened by cursor P1 in register P2
  48582. */
  48583. #ifndef SQLITE_OMIT_BTREECOUNT
  48584. case OP_Count: { /* out2-prerelease */
  48585. i64 nEntry;
  48586. BtCursor *pCrsr = p->apCsr[pOp->p1]->pCursor;
  48587. if( pCrsr ){
  48588. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  48589. }else{
  48590. nEntry = 0;
  48591. }
  48592. pOut->flags = MEM_Int;
  48593. pOut->u.i = nEntry;
  48594. break;
  48595. }
  48596. #endif
  48597. /* Opcode: Statement P1 * * * *
  48598. **
  48599. ** Begin an individual statement transaction which is part of a larger
  48600. ** transaction. This is needed so that the statement
  48601. ** can be rolled back after an error without having to roll back the
  48602. ** entire transaction. The statement transaction will automatically
  48603. ** commit when the VDBE halts.
  48604. **
  48605. ** If the database connection is currently in autocommit mode (that
  48606. ** is to say, if it is in between BEGIN and COMMIT)
  48607. ** and if there are no other active statements on the same database
  48608. ** connection, then this operation is a no-op. No statement transaction
  48609. ** is needed since any error can use the normal ROLLBACK process to
  48610. ** undo changes.
  48611. **
  48612. ** If a statement transaction is started, then a statement journal file
  48613. ** will be allocated and initialized.
  48614. **
  48615. ** The statement is begun on the database file with index P1. The main
  48616. ** database file has an index of 0 and the file used for temporary tables
  48617. ** has an index of 1.
  48618. */
  48619. case OP_Statement: {
  48620. if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
  48621. int i = pOp->p1;
  48622. Btree *pBt;
  48623. assert( i>=0 && i<db->nDb );
  48624. assert( db->aDb[i].pBt!=0 );
  48625. pBt = db->aDb[i].pBt;
  48626. assert( sqlite3BtreeIsInTrans(pBt) );
  48627. assert( (p->btreeMask & (1<<i))!=0 );
  48628. if( p->iStatement==0 ){
  48629. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  48630. db->nStatement++;
  48631. p->iStatement = db->nSavepoint + db->nStatement;
  48632. }
  48633. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  48634. }
  48635. break;
  48636. }
  48637. /* Opcode: Savepoint P1 * * P4 *
  48638. **
  48639. ** Open, release or rollback the savepoint named by parameter P4, depending
  48640. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  48641. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  48642. */
  48643. case OP_Savepoint: {
  48644. int p1 = pOp->p1;
  48645. char *zName = pOp->p4.z; /* Name of savepoint */
  48646. /* Assert that the p1 parameter is valid. Also that if there is no open
  48647. ** transaction, then there cannot be any savepoints.
  48648. */
  48649. assert( db->pSavepoint==0 || db->autoCommit==0 );
  48650. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  48651. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  48652. assert( checkSavepointCount(db) );
  48653. if( p1==SAVEPOINT_BEGIN ){
  48654. if( db->writeVdbeCnt>0 ){
  48655. /* A new savepoint cannot be created if there are active write
  48656. ** statements (i.e. open read/write incremental blob handles).
  48657. */
  48658. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  48659. "SQL statements in progress");
  48660. rc = SQLITE_BUSY;
  48661. }else{
  48662. int nName = sqlite3Strlen30(zName);
  48663. Savepoint *pNew;
  48664. /* Create a new savepoint structure. */
  48665. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  48666. if( pNew ){
  48667. pNew->zName = (char *)&pNew[1];
  48668. memcpy(pNew->zName, zName, nName+1);
  48669. /* If there is no open transaction, then mark this as a special
  48670. ** "transaction savepoint". */
  48671. if( db->autoCommit ){
  48672. db->autoCommit = 0;
  48673. db->isTransactionSavepoint = 1;
  48674. }else{
  48675. db->nSavepoint++;
  48676. }
  48677. /* Link the new savepoint into the database handle's list. */
  48678. pNew->pNext = db->pSavepoint;
  48679. db->pSavepoint = pNew;
  48680. }
  48681. }
  48682. }else{
  48683. Savepoint *pSavepoint;
  48684. int iSavepoint = 0;
  48685. /* Find the named savepoint. If there is no such savepoint, then an
  48686. ** an error is returned to the user. */
  48687. for(
  48688. pSavepoint=db->pSavepoint;
  48689. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  48690. pSavepoint=pSavepoint->pNext
  48691. ){
  48692. iSavepoint++;
  48693. }
  48694. if( !pSavepoint ){
  48695. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
  48696. rc = SQLITE_ERROR;
  48697. }else if(
  48698. db->writeVdbeCnt>0 || (p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
  48699. ){
  48700. /* It is not possible to release (commit) a savepoint if there are
  48701. ** active write statements. It is not possible to rollback a savepoint
  48702. ** if there are any active statements at all.
  48703. */
  48704. sqlite3SetString(&p->zErrMsg, db,
  48705. "cannot %s savepoint - SQL statements in progress",
  48706. (p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
  48707. );
  48708. rc = SQLITE_BUSY;
  48709. }else{
  48710. /* Determine whether or not this is a transaction savepoint. If so,
  48711. ** and this is a RELEASE command, then the current transaction
  48712. ** is committed.
  48713. */
  48714. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  48715. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  48716. db->autoCommit = 1;
  48717. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  48718. p->pc = pc;
  48719. db->autoCommit = 0;
  48720. p->rc = rc = SQLITE_BUSY;
  48721. goto vdbe_return;
  48722. }
  48723. db->isTransactionSavepoint = 0;
  48724. rc = p->rc;
  48725. }else{
  48726. int ii;
  48727. iSavepoint = db->nSavepoint - iSavepoint - 1;
  48728. for(ii=0; ii<db->nDb; ii++){
  48729. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  48730. if( rc!=SQLITE_OK ){
  48731. goto abort_due_to_error;
  48732. }
  48733. }
  48734. if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  48735. sqlite3ExpirePreparedStatements(db);
  48736. sqlite3ResetInternalSchema(db, 0);
  48737. }
  48738. }
  48739. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  48740. ** savepoints nested inside of the savepoint being operated on. */
  48741. while( db->pSavepoint!=pSavepoint ){
  48742. Savepoint *pTmp = db->pSavepoint;
  48743. db->pSavepoint = pTmp->pNext;
  48744. sqlite3DbFree(db, pTmp);
  48745. db->nSavepoint--;
  48746. }
  48747. /* If it is a RELEASE, then destroy the savepoint being operated on too */
  48748. if( p1==SAVEPOINT_RELEASE ){
  48749. assert( pSavepoint==db->pSavepoint );
  48750. db->pSavepoint = pSavepoint->pNext;
  48751. sqlite3DbFree(db, pSavepoint);
  48752. if( !isTransaction ){
  48753. db->nSavepoint--;
  48754. }
  48755. }
  48756. }
  48757. }
  48758. break;
  48759. }
  48760. /* Opcode: AutoCommit P1 P2 * * *
  48761. **
  48762. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  48763. ** back any currently active btree transactions. If there are any active
  48764. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  48765. ** there are active writing VMs or active VMs that use shared cache.
  48766. **
  48767. ** This instruction causes the VM to halt.
  48768. */
  48769. case OP_AutoCommit: {
  48770. int desiredAutoCommit = pOp->p1;
  48771. int rollback = pOp->p2;
  48772. int turnOnAC = desiredAutoCommit && !db->autoCommit;
  48773. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  48774. assert( desiredAutoCommit==1 || rollback==0 );
  48775. assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
  48776. if( turnOnAC && rollback && db->activeVdbeCnt>1 ){
  48777. /* If this instruction implements a ROLLBACK and other VMs are
  48778. ** still running, and a transaction is active, return an error indicating
  48779. ** that the other VMs must complete first.
  48780. */
  48781. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  48782. "SQL statements in progress");
  48783. rc = SQLITE_BUSY;
  48784. }else if( turnOnAC && !rollback && db->writeVdbeCnt>1 ){
  48785. /* If this instruction implements a COMMIT and other VMs are writing
  48786. ** return an error indicating that the other VMs must complete first.
  48787. */
  48788. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  48789. "SQL statements in progress");
  48790. rc = SQLITE_BUSY;
  48791. }else if( desiredAutoCommit!=db->autoCommit ){
  48792. if( rollback ){
  48793. assert( desiredAutoCommit==1 );
  48794. sqlite3RollbackAll(db);
  48795. db->autoCommit = 1;
  48796. }else{
  48797. db->autoCommit = (u8)desiredAutoCommit;
  48798. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  48799. p->pc = pc;
  48800. db->autoCommit = (u8)(1-desiredAutoCommit);
  48801. p->rc = rc = SQLITE_BUSY;
  48802. goto vdbe_return;
  48803. }
  48804. }
  48805. assert( db->nStatement==0 );
  48806. sqlite3CloseSavepoints(db);
  48807. if( p->rc==SQLITE_OK ){
  48808. rc = SQLITE_DONE;
  48809. }else{
  48810. rc = SQLITE_ERROR;
  48811. }
  48812. goto vdbe_return;
  48813. }else{
  48814. sqlite3SetString(&p->zErrMsg, db,
  48815. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  48816. (rollback)?"cannot rollback - no transaction is active":
  48817. "cannot commit - no transaction is active"));
  48818. rc = SQLITE_ERROR;
  48819. }
  48820. break;
  48821. }
  48822. /* Opcode: Transaction P1 P2 * * *
  48823. **
  48824. ** Begin a transaction. The transaction ends when a Commit or Rollback
  48825. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  48826. ** transaction might also be rolled back if an error is encountered.
  48827. **
  48828. ** P1 is the index of the database file on which the transaction is
  48829. ** started. Index 0 is the main database file and index 1 is the
  48830. ** file used for temporary tables. Indices of 2 or more are used for
  48831. ** attached databases.
  48832. **
  48833. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  48834. ** obtained on the database file when a write-transaction is started. No
  48835. ** other process can start another write transaction while this transaction is
  48836. ** underway. Starting a write transaction also creates a rollback journal. A
  48837. ** write transaction must be started before any changes can be made to the
  48838. ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
  48839. ** on the file.
  48840. **
  48841. ** If P2 is zero, then a read-lock is obtained on the database file.
  48842. */
  48843. case OP_Transaction: {
  48844. int i = pOp->p1;
  48845. Btree *pBt;
  48846. assert( i>=0 && i<db->nDb );
  48847. assert( (p->btreeMask & (1<<i))!=0 );
  48848. pBt = db->aDb[i].pBt;
  48849. if( pBt ){
  48850. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  48851. if( rc==SQLITE_BUSY ){
  48852. p->pc = pc;
  48853. p->rc = rc = SQLITE_BUSY;
  48854. goto vdbe_return;
  48855. }
  48856. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
  48857. goto abort_due_to_error;
  48858. }
  48859. }
  48860. break;
  48861. }
  48862. /* Opcode: ReadCookie P1 P2 P3 * *
  48863. **
  48864. ** Read cookie number P3 from database P1 and write it into register P2.
  48865. ** P3==0 is the schema version. P3==1 is the database format.
  48866. ** P3==2 is the recommended pager cache size, and so forth. P1==0 is
  48867. ** the main database file and P1==1 is the database file used to store
  48868. ** temporary tables.
  48869. **
  48870. ** If P1 is negative, then this is a request to read the size of a
  48871. ** databases free-list. P3 must be set to 1 in this case. The actual
  48872. ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
  48873. ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
  48874. **
  48875. ** There must be a read-lock on the database (either a transaction
  48876. ** must be started or there must be an open cursor) before
  48877. ** executing this instruction.
  48878. */
  48879. case OP_ReadCookie: { /* out2-prerelease */
  48880. int iMeta;
  48881. int iDb = pOp->p1;
  48882. int iCookie = pOp->p3;
  48883. assert( pOp->p3<SQLITE_N_BTREE_META );
  48884. if( iDb<0 ){
  48885. iDb = (-1*(iDb+1));
  48886. iCookie *= -1;
  48887. }
  48888. assert( iDb>=0 && iDb<db->nDb );
  48889. assert( db->aDb[iDb].pBt!=0 );
  48890. assert( (p->btreeMask & (1<<iDb))!=0 );
  48891. /* The indexing of meta values at the schema layer is off by one from
  48892. ** the indexing in the btree layer. The btree considers meta[0] to
  48893. ** be the number of free pages in the database (a read-only value)
  48894. ** and meta[1] to be the schema cookie. The schema layer considers
  48895. ** meta[1] to be the schema cookie. So we have to shift the index
  48896. ** by one in the following statement.
  48897. */
  48898. rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
  48899. pOut->u.i = iMeta;
  48900. MemSetTypeFlag(pOut, MEM_Int);
  48901. break;
  48902. }
  48903. /* Opcode: SetCookie P1 P2 P3 * *
  48904. **
  48905. ** Write the content of register P3 (interpreted as an integer)
  48906. ** into cookie number P2 of database P1.
  48907. ** P2==0 is the schema version. P2==1 is the database format.
  48908. ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
  48909. ** the main database file and P1==1 is the database file used to store
  48910. ** temporary tables.
  48911. **
  48912. ** A transaction must be started before executing this opcode.
  48913. */
  48914. case OP_SetCookie: { /* in3 */
  48915. Db *pDb;
  48916. assert( pOp->p2<SQLITE_N_BTREE_META );
  48917. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  48918. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  48919. pDb = &db->aDb[pOp->p1];
  48920. assert( pDb->pBt!=0 );
  48921. sqlite3VdbeMemIntegerify(pIn3);
  48922. /* See note about index shifting on OP_ReadCookie */
  48923. rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
  48924. if( pOp->p2==0 ){
  48925. /* When the schema cookie changes, record the new cookie internally */
  48926. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  48927. db->flags |= SQLITE_InternChanges;
  48928. }else if( pOp->p2==1 ){
  48929. /* Record changes in the file format */
  48930. pDb->pSchema->file_format = (u8)pIn3->u.i;
  48931. }
  48932. if( pOp->p1==1 ){
  48933. /* Invalidate all prepared statements whenever the TEMP database
  48934. ** schema is changed. Ticket #1644 */
  48935. sqlite3ExpirePreparedStatements(db);
  48936. }
  48937. break;
  48938. }
  48939. /* Opcode: VerifyCookie P1 P2 *
  48940. **
  48941. ** Check the value of global database parameter number 0 (the
  48942. ** schema version) and make sure it is equal to P2.
  48943. ** P1 is the database number which is 0 for the main database file
  48944. ** and 1 for the file holding temporary tables and some higher number
  48945. ** for auxiliary databases.
  48946. **
  48947. ** The cookie changes its value whenever the database schema changes.
  48948. ** This operation is used to detect when that the cookie has changed
  48949. ** and that the current process needs to reread the schema.
  48950. **
  48951. ** Either a transaction needs to have been started or an OP_Open needs
  48952. ** to be executed (to establish a read lock) before this opcode is
  48953. ** invoked.
  48954. */
  48955. case OP_VerifyCookie: {
  48956. int iMeta;
  48957. Btree *pBt;
  48958. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  48959. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  48960. pBt = db->aDb[pOp->p1].pBt;
  48961. if( pBt ){
  48962. rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
  48963. }else{
  48964. rc = SQLITE_OK;
  48965. iMeta = 0;
  48966. }
  48967. if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
  48968. sqlite3DbFree(db, p->zErrMsg);
  48969. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  48970. /* If the schema-cookie from the database file matches the cookie
  48971. ** stored with the in-memory representation of the schema, do
  48972. ** not reload the schema from the database file.
  48973. **
  48974. ** If virtual-tables are in use, this is not just an optimization.
  48975. ** Often, v-tables store their data in other SQLite tables, which
  48976. ** are queried from within xNext() and other v-table methods using
  48977. ** prepared queries. If such a query is out-of-date, we do not want to
  48978. ** discard the database schema, as the user code implementing the
  48979. ** v-table would have to be ready for the sqlite3_vtab structure itself
  48980. ** to be invalidated whenever sqlite3_step() is called from within
  48981. ** a v-table method.
  48982. */
  48983. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  48984. sqlite3ResetInternalSchema(db, pOp->p1);
  48985. }
  48986. sqlite3ExpirePreparedStatements(db);
  48987. rc = SQLITE_SCHEMA;
  48988. }
  48989. break;
  48990. }
  48991. /* Opcode: OpenRead P1 P2 P3 P4 P5
  48992. **
  48993. ** Open a read-only cursor for the database table whose root page is
  48994. ** P2 in a database file. The database file is determined by P3.
  48995. ** P3==0 means the main database, P3==1 means the database used for
  48996. ** temporary tables, and P3>1 means used the corresponding attached
  48997. ** database. Give the new cursor an identifier of P1. The P1
  48998. ** values need not be contiguous but all P1 values should be small integers.
  48999. ** It is an error for P1 to be negative.
  49000. **
  49001. ** If P5!=0 then use the content of register P2 as the root page, not
  49002. ** the value of P2 itself.
  49003. **
  49004. ** There will be a read lock on the database whenever there is an
  49005. ** open cursor. If the database was unlocked prior to this instruction
  49006. ** then a read lock is acquired as part of this instruction. A read
  49007. ** lock allows other processes to read the database but prohibits
  49008. ** any other process from modifying the database. The read lock is
  49009. ** released when all cursors are closed. If this instruction attempts
  49010. ** to get a read lock but fails, the script terminates with an
  49011. ** SQLITE_BUSY error code.
  49012. **
  49013. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  49014. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  49015. ** structure, then said structure defines the content and collating
  49016. ** sequence of the index being opened. Otherwise, if P4 is an integer
  49017. ** value, it is set to the number of columns in the table.
  49018. **
  49019. ** See also OpenWrite.
  49020. */
  49021. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  49022. **
  49023. ** Open a read/write cursor named P1 on the table or index whose root
  49024. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  49025. ** root page.
  49026. **
  49027. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  49028. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  49029. ** structure, then said structure defines the content and collating
  49030. ** sequence of the index being opened. Otherwise, if P4 is an integer
  49031. ** value, it is set to the number of columns in the table.
  49032. **
  49033. ** This instruction works just like OpenRead except that it opens the cursor
  49034. ** in read/write mode. For a given table, there can be one or more read-only
  49035. ** cursors or a single read/write cursor but not both.
  49036. **
  49037. ** See also OpenRead.
  49038. */
  49039. case OP_OpenRead:
  49040. case OP_OpenWrite: {
  49041. int nField = 0;
  49042. KeyInfo *pKeyInfo = 0;
  49043. int i = pOp->p1;
  49044. int p2 = pOp->p2;
  49045. int iDb = pOp->p3;
  49046. int wrFlag;
  49047. Btree *pX;
  49048. VdbeCursor *pCur;
  49049. Db *pDb;
  49050. assert( iDb>=0 && iDb<db->nDb );
  49051. assert( (p->btreeMask & (1<<iDb))!=0 );
  49052. pDb = &db->aDb[iDb];
  49053. pX = pDb->pBt;
  49054. assert( pX!=0 );
  49055. if( pOp->opcode==OP_OpenWrite ){
  49056. wrFlag = 1;
  49057. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  49058. p->minWriteFileFormat = pDb->pSchema->file_format;
  49059. }
  49060. }else{
  49061. wrFlag = 0;
  49062. }
  49063. if( pOp->p5 ){
  49064. assert( p2>0 );
  49065. assert( p2<=p->nMem );
  49066. pIn2 = &p->aMem[p2];
  49067. sqlite3VdbeMemIntegerify(pIn2);
  49068. p2 = (int)pIn2->u.i;
  49069. if( p2<2 ) {
  49070. rc = SQLITE_CORRUPT_BKPT;
  49071. goto abort_due_to_error;
  49072. }
  49073. }
  49074. assert( i>=0 );
  49075. if( pOp->p4type==P4_KEYINFO ){
  49076. pKeyInfo = pOp->p4.pKeyInfo;
  49077. pKeyInfo->enc = ENC(p->db);
  49078. nField = pKeyInfo->nField+1;
  49079. }else if( pOp->p4type==P4_INT32 ){
  49080. nField = pOp->p4.i;
  49081. }
  49082. pCur = allocateCursor(p, i, nField, iDb, 1);
  49083. if( pCur==0 ) goto no_mem;
  49084. pCur->nullRow = 1;
  49085. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  49086. pCur->pKeyInfo = pKeyInfo;
  49087. switch( rc ){
  49088. case SQLITE_BUSY: {
  49089. p->pc = pc;
  49090. p->rc = rc = SQLITE_BUSY;
  49091. goto vdbe_return;
  49092. }
  49093. case SQLITE_OK: {
  49094. int flags = sqlite3BtreeFlags(pCur->pCursor);
  49095. /* Sanity checking. Only the lower four bits of the flags byte should
  49096. ** be used. Bit 3 (mask 0x08) is unpredictable. The lower 3 bits
  49097. ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
  49098. ** 2 (zerodata for indices). If these conditions are not met it can
  49099. ** only mean that we are dealing with a corrupt database file
  49100. */
  49101. if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
  49102. rc = SQLITE_CORRUPT_BKPT;
  49103. goto abort_due_to_error;
  49104. }
  49105. pCur->isTable = (flags & BTREE_INTKEY)!=0 ?1:0;
  49106. pCur->isIndex = (flags & BTREE_ZERODATA)!=0 ?1:0;
  49107. /* If P4==0 it means we are expected to open a table. If P4!=0 then
  49108. ** we expect to be opening an index. If this is not what happened,
  49109. ** then the database is corrupt
  49110. */
  49111. if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
  49112. || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
  49113. rc = SQLITE_CORRUPT_BKPT;
  49114. goto abort_due_to_error;
  49115. }
  49116. break;
  49117. }
  49118. case SQLITE_EMPTY: {
  49119. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  49120. pCur->isIndex = !pCur->isTable;
  49121. pCur->pCursor = 0;
  49122. rc = SQLITE_OK;
  49123. break;
  49124. }
  49125. default: {
  49126. goto abort_due_to_error;
  49127. }
  49128. }
  49129. break;
  49130. }
  49131. /* Opcode: OpenEphemeral P1 P2 * P4 *
  49132. **
  49133. ** Open a new cursor P1 to a transient table.
  49134. ** The cursor is always opened read/write even if
  49135. ** the main database is read-only. The transient or virtual
  49136. ** table is deleted automatically when the cursor is closed.
  49137. **
  49138. ** P2 is the number of columns in the virtual table.
  49139. ** The cursor points to a BTree table if P4==0 and to a BTree index
  49140. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  49141. ** that defines the format of keys in the index.
  49142. **
  49143. ** This opcode was once called OpenTemp. But that created
  49144. ** confusion because the term "temp table", might refer either
  49145. ** to a TEMP table at the SQL level, or to a table opened by
  49146. ** this opcode. Then this opcode was call OpenVirtual. But
  49147. ** that created confusion with the whole virtual-table idea.
  49148. */
  49149. case OP_OpenEphemeral: {
  49150. int i = pOp->p1;
  49151. VdbeCursor *pCx;
  49152. static const int openFlags =
  49153. SQLITE_OPEN_READWRITE |
  49154. SQLITE_OPEN_CREATE |
  49155. SQLITE_OPEN_EXCLUSIVE |
  49156. SQLITE_OPEN_DELETEONCLOSE |
  49157. SQLITE_OPEN_TRANSIENT_DB;
  49158. assert( i>=0 );
  49159. pCx = allocateCursor(p, i, pOp->p2, -1, 1);
  49160. if( pCx==0 ) goto no_mem;
  49161. pCx->nullRow = 1;
  49162. rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
  49163. &pCx->pBt);
  49164. if( rc==SQLITE_OK ){
  49165. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  49166. }
  49167. if( rc==SQLITE_OK ){
  49168. /* If a transient index is required, create it by calling
  49169. ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
  49170. ** opening it. If a transient table is required, just use the
  49171. ** automatically created table with root-page 1 (an INTKEY table).
  49172. */
  49173. if( pOp->p4.pKeyInfo ){
  49174. int pgno;
  49175. assert( pOp->p4type==P4_KEYINFO );
  49176. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
  49177. if( rc==SQLITE_OK ){
  49178. assert( pgno==MASTER_ROOT+1 );
  49179. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1,
  49180. (KeyInfo*)pOp->p4.z, pCx->pCursor);
  49181. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  49182. pCx->pKeyInfo->enc = ENC(p->db);
  49183. }
  49184. pCx->isTable = 0;
  49185. }else{
  49186. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  49187. pCx->isTable = 1;
  49188. }
  49189. }
  49190. pCx->isIndex = !pCx->isTable;
  49191. break;
  49192. }
  49193. /* Opcode: OpenPseudo P1 P2 P3 * *
  49194. **
  49195. ** Open a new cursor that points to a fake table that contains a single
  49196. ** row of data. Any attempt to write a second row of data causes the
  49197. ** first row to be deleted. All data is deleted when the cursor is
  49198. ** closed.
  49199. **
  49200. ** A pseudo-table created by this opcode is useful for holding the
  49201. ** NEW or OLD tables in a trigger. Also used to hold the a single
  49202. ** row output from the sorter so that the row can be decomposed into
  49203. ** individual columns using the OP_Column opcode.
  49204. **
  49205. ** When OP_Insert is executed to insert a row in to the pseudo table,
  49206. ** the pseudo-table cursor may or may not make it's own copy of the
  49207. ** original row data. If P2 is 0, then the pseudo-table will copy the
  49208. ** original row data. Otherwise, a pointer to the original memory cell
  49209. ** is stored. In this case, the vdbe program must ensure that the
  49210. ** memory cell containing the row data is not overwritten until the
  49211. ** pseudo table is closed (or a new row is inserted into it).
  49212. **
  49213. ** P3 is the number of fields in the records that will be stored by
  49214. ** the pseudo-table.
  49215. */
  49216. case OP_OpenPseudo: {
  49217. int i = pOp->p1;
  49218. VdbeCursor *pCx;
  49219. assert( i>=0 );
  49220. pCx = allocateCursor(p, i, pOp->p3, -1, 0);
  49221. if( pCx==0 ) goto no_mem;
  49222. pCx->nullRow = 1;
  49223. pCx->pseudoTable = 1;
  49224. pCx->ephemPseudoTable = (u8)pOp->p2;
  49225. pCx->isTable = 1;
  49226. pCx->isIndex = 0;
  49227. break;
  49228. }
  49229. /* Opcode: Close P1 * * * *
  49230. **
  49231. ** Close a cursor previously opened as P1. If P1 is not
  49232. ** currently open, this instruction is a no-op.
  49233. */
  49234. case OP_Close: {
  49235. int i = pOp->p1;
  49236. assert( i>=0 && i<p->nCursor );
  49237. sqlite3VdbeFreeCursor(p, p->apCsr[i]);
  49238. p->apCsr[i] = 0;
  49239. break;
  49240. }
  49241. /* Opcode: SeekGe P1 P2 P3 P4 *
  49242. **
  49243. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  49244. ** use the value in register P3 as the key. If cursor P1 refers
  49245. ** to an SQL index, then P3 is the first in an array of P4 registers
  49246. ** that are used as an unpacked index key.
  49247. **
  49248. ** Reposition cursor P1 so that it points to the smallest entry that
  49249. ** is greater than or equal to the key value. If there are no records
  49250. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  49251. **
  49252. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  49253. */
  49254. /* Opcode: SeekGt P1 P2 P3 P4 *
  49255. **
  49256. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  49257. ** use the value in register P3 as a key. If cursor P1 refers
  49258. ** to an SQL index, then P3 is the first in an array of P4 registers
  49259. ** that are used as an unpacked index key.
  49260. **
  49261. ** Reposition cursor P1 so that it points to the smallest entry that
  49262. ** is greater than the key value. If there are no records greater than
  49263. ** the key and P2 is not zero, then jump to P2.
  49264. **
  49265. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  49266. */
  49267. /* Opcode: SeekLt P1 P2 P3 P4 *
  49268. **
  49269. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  49270. ** use the value in register P3 as a key. If cursor P1 refers
  49271. ** to an SQL index, then P3 is the first in an array of P4 registers
  49272. ** that are used as an unpacked index key.
  49273. **
  49274. ** Reposition cursor P1 so that it points to the largest entry that
  49275. ** is less than the key value. If there are no records less than
  49276. ** the key and P2 is not zero, then jump to P2.
  49277. **
  49278. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  49279. */
  49280. /* Opcode: SeekLe P1 P2 P3 P4 *
  49281. **
  49282. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  49283. ** use the value in register P3 as a key. If cursor P1 refers
  49284. ** to an SQL index, then P3 is the first in an array of P4 registers
  49285. ** that are used as an unpacked index key.
  49286. **
  49287. ** Reposition cursor P1 so that it points to the largest entry that
  49288. ** is less than or equal to the key value. If there are no records
  49289. ** less than or equal to the key and P2 is not zero, then jump to P2.
  49290. **
  49291. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  49292. */
  49293. case OP_SeekLt: /* jump, in3 */
  49294. case OP_SeekLe: /* jump, in3 */
  49295. case OP_SeekGe: /* jump, in3 */
  49296. case OP_SeekGt: { /* jump, in3 */
  49297. int i = pOp->p1;
  49298. VdbeCursor *pC;
  49299. assert( i>=0 && i<p->nCursor );
  49300. assert( pOp->p2!=0 );
  49301. pC = p->apCsr[i];
  49302. assert( pC!=0 );
  49303. if( pC->pCursor!=0 ){
  49304. int res, oc;
  49305. oc = pOp->opcode;
  49306. pC->nullRow = 0;
  49307. if( pC->isTable ){
  49308. i64 iKey; /* The rowid we are to seek to */
  49309. /* The input value in P3 might be of any type: integer, real, string,
  49310. ** blob, or NULL. But it needs to be an integer before we can do
  49311. ** the seek, so covert it. */
  49312. applyNumericAffinity(pIn3);
  49313. iKey = sqlite3VdbeIntValue(pIn3);
  49314. pC->rowidIsValid = 0;
  49315. /* If the P3 value could not be converted into an integer without
  49316. ** loss of information, then special processing is required... */
  49317. if( (pIn3->flags & MEM_Int)==0 ){
  49318. if( (pIn3->flags & MEM_Real)==0 ){
  49319. /* If the P3 value cannot be converted into any kind of a number,
  49320. ** then the seek is not possible, so jump to P2 */
  49321. pc = pOp->p2 - 1;
  49322. break;
  49323. }
  49324. /* If we reach this point, then the P3 value must be a floating
  49325. ** point number. */
  49326. assert( (pIn3->flags & MEM_Real)!=0 );
  49327. if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){
  49328. /* The P3 value is to large in magnitude to be expressed as an
  49329. ** integer. */
  49330. res = 1;
  49331. if( pIn3->r<0 ){
  49332. if( oc==OP_SeekGt || oc==OP_SeekGe ){
  49333. rc = sqlite3BtreeFirst(pC->pCursor, &res);
  49334. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  49335. }
  49336. }else{
  49337. if( oc==OP_SeekLt || oc==OP_SeekLe ){
  49338. rc = sqlite3BtreeLast(pC->pCursor, &res);
  49339. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  49340. }
  49341. }
  49342. if( res ){
  49343. pc = pOp->p2 - 1;
  49344. }
  49345. break;
  49346. }else if( oc==OP_SeekLt || oc==OP_SeekGe ){
  49347. /* Use the ceiling() function to convert real->int */
  49348. if( pIn3->r > (double)iKey ) iKey++;
  49349. }else{
  49350. /* Use the floor() function to convert real->int */
  49351. assert( oc==OP_SeekLe || oc==OP_SeekGt );
  49352. if( pIn3->r < (double)iKey ) iKey--;
  49353. }
  49354. }
  49355. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  49356. if( rc!=SQLITE_OK ){
  49357. goto abort_due_to_error;
  49358. }
  49359. if( res==0 ){
  49360. pC->rowidIsValid = 1;
  49361. pC->lastRowid = iKey;
  49362. }
  49363. }else{
  49364. UnpackedRecord r;
  49365. int nField = pOp->p4.i;
  49366. assert( pOp->p4type==P4_INT32 );
  49367. assert( nField>0 );
  49368. r.pKeyInfo = pC->pKeyInfo;
  49369. r.nField = (u16)nField;
  49370. if( oc==OP_SeekGt || oc==OP_SeekLe ){
  49371. r.flags = UNPACKED_INCRKEY;
  49372. }else{
  49373. r.flags = 0;
  49374. }
  49375. r.aMem = &p->aMem[pOp->p3];
  49376. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  49377. if( rc!=SQLITE_OK ){
  49378. goto abort_due_to_error;
  49379. }
  49380. pC->rowidIsValid = 0;
  49381. }
  49382. pC->deferredMoveto = 0;
  49383. pC->cacheStatus = CACHE_STALE;
  49384. #ifdef SQLITE_TEST
  49385. sqlite3_search_count++;
  49386. #endif
  49387. if( oc==OP_SeekGe || oc==OP_SeekGt ){
  49388. if( res<0 || (res==0 && oc==OP_SeekGt) ){
  49389. rc = sqlite3BtreeNext(pC->pCursor, &res);
  49390. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  49391. pC->rowidIsValid = 0;
  49392. }else{
  49393. res = 0;
  49394. }
  49395. }else{
  49396. assert( oc==OP_SeekLt || oc==OP_SeekLe );
  49397. if( res>0 || (res==0 && oc==OP_SeekLt) ){
  49398. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  49399. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  49400. pC->rowidIsValid = 0;
  49401. }else{
  49402. /* res might be negative because the table is empty. Check to
  49403. ** see if this is the case.
  49404. */
  49405. res = sqlite3BtreeEof(pC->pCursor);
  49406. }
  49407. }
  49408. assert( pOp->p2>0 );
  49409. if( res ){
  49410. pc = pOp->p2 - 1;
  49411. }
  49412. }else if( !pC->pseudoTable ){
  49413. /* This happens when attempting to open the sqlite3_master table
  49414. ** for read access returns SQLITE_EMPTY. In this case always
  49415. ** take the jump (since there are no records in the table).
  49416. */
  49417. pc = pOp->p2 - 1;
  49418. }
  49419. break;
  49420. }
  49421. /* Opcode: Seek P1 P2 * * *
  49422. **
  49423. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  49424. ** for P1 to move so that it points to the rowid given by P2.
  49425. **
  49426. ** This is actually a deferred seek. Nothing actually happens until
  49427. ** the cursor is used to read a record. That way, if no reads
  49428. ** occur, no unnecessary I/O happens.
  49429. */
  49430. case OP_Seek: { /* in2 */
  49431. int i = pOp->p1;
  49432. VdbeCursor *pC;
  49433. assert( i>=0 && i<p->nCursor );
  49434. pC = p->apCsr[i];
  49435. assert( pC!=0 );
  49436. if( pC->pCursor!=0 ){
  49437. assert( pC->isTable );
  49438. pC->nullRow = 0;
  49439. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  49440. pC->rowidIsValid = 0;
  49441. pC->deferredMoveto = 1;
  49442. }
  49443. break;
  49444. }
  49445. /* Opcode: Found P1 P2 P3 * *
  49446. **
  49447. ** Register P3 holds a blob constructed by MakeRecord. P1 is an index.
  49448. ** If an entry that matches the value in register p3 exists in P1 then
  49449. ** jump to P2. If the P3 value does not match any entry in P1
  49450. ** then fall thru. The P1 cursor is left pointing at the matching entry
  49451. ** if it exists.
  49452. **
  49453. ** This instruction is used to implement the IN operator where the
  49454. ** left-hand side is a SELECT statement. P1 may be a true index, or it
  49455. ** may be a temporary index that holds the results of the SELECT
  49456. ** statement. This instruction is also used to implement the
  49457. ** DISTINCT keyword in SELECT statements.
  49458. **
  49459. ** This instruction checks if index P1 contains a record for which
  49460. ** the first N serialized values exactly match the N serialized values
  49461. ** in the record in register P3, where N is the total number of values in
  49462. ** the P3 record (the P3 record is a prefix of the P1 record).
  49463. **
  49464. ** See also: NotFound, IsUnique, NotExists
  49465. */
  49466. /* Opcode: NotFound P1 P2 P3 * *
  49467. **
  49468. ** Register P3 holds a blob constructed by MakeRecord. P1 is
  49469. ** an index. If no entry exists in P1 that matches the blob then jump
  49470. ** to P2. If an entry does existing, fall through. The cursor is left
  49471. ** pointing to the entry that matches.
  49472. **
  49473. ** See also: Found, NotExists, IsUnique
  49474. */
  49475. case OP_NotFound: /* jump, in3 */
  49476. case OP_Found: { /* jump, in3 */
  49477. int i = pOp->p1;
  49478. int alreadyExists = 0;
  49479. VdbeCursor *pC;
  49480. assert( i>=0 && i<p->nCursor );
  49481. assert( p->apCsr[i]!=0 );
  49482. if( (pC = p->apCsr[i])->pCursor!=0 ){
  49483. int res;
  49484. UnpackedRecord *pIdxKey;
  49485. assert( pC->isTable==0 );
  49486. assert( pIn3->flags & MEM_Blob );
  49487. pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
  49488. aTempRec, sizeof(aTempRec));
  49489. if( pIdxKey==0 ){
  49490. goto no_mem;
  49491. }
  49492. if( pOp->opcode==OP_Found ){
  49493. pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  49494. }
  49495. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  49496. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  49497. if( rc!=SQLITE_OK ){
  49498. break;
  49499. }
  49500. alreadyExists = (res==0);
  49501. pC->deferredMoveto = 0;
  49502. pC->cacheStatus = CACHE_STALE;
  49503. }
  49504. if( pOp->opcode==OP_Found ){
  49505. if( alreadyExists ) pc = pOp->p2 - 1;
  49506. }else{
  49507. if( !alreadyExists ) pc = pOp->p2 - 1;
  49508. }
  49509. break;
  49510. }
  49511. /* Opcode: IsUnique P1 P2 P3 P4 *
  49512. **
  49513. ** The P3 register contains an integer record number. Call this
  49514. ** record number R. The P4 register contains an index key created
  49515. ** using MakeRecord. Call it K.
  49516. **
  49517. ** P1 is an index. So it has no data and its key consists of a
  49518. ** record generated by OP_MakeRecord where the last field is the
  49519. ** rowid of the entry that the index refers to.
  49520. **
  49521. ** This instruction asks if there is an entry in P1 where the
  49522. ** fields matches K but the rowid is different from R.
  49523. ** If there is no such entry, then there is an immediate
  49524. ** jump to P2. If any entry does exist where the index string
  49525. ** matches K but the record number is not R, then the record
  49526. ** number for that entry is written into P3 and control
  49527. ** falls through to the next instruction.
  49528. **
  49529. ** See also: NotFound, NotExists, Found
  49530. */
  49531. case OP_IsUnique: { /* jump, in3 */
  49532. int i = pOp->p1;
  49533. VdbeCursor *pCx;
  49534. BtCursor *pCrsr;
  49535. Mem *pK;
  49536. i64 R;
  49537. /* Pop the value R off the top of the stack
  49538. */
  49539. assert( pOp->p4type==P4_INT32 );
  49540. assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
  49541. pK = &p->aMem[pOp->p4.i];
  49542. sqlite3VdbeMemIntegerify(pIn3);
  49543. R = pIn3->u.i;
  49544. assert( i>=0 && i<p->nCursor );
  49545. pCx = p->apCsr[i];
  49546. assert( pCx!=0 );
  49547. pCrsr = pCx->pCursor;
  49548. if( pCrsr!=0 ){
  49549. int res;
  49550. i64 v; /* The record number that matches K */
  49551. UnpackedRecord *pIdxKey; /* Unpacked version of P4 */
  49552. /* Make sure K is a string and make zKey point to K
  49553. */
  49554. assert( pK->flags & MEM_Blob );
  49555. pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
  49556. aTempRec, sizeof(aTempRec));
  49557. if( pIdxKey==0 ){
  49558. goto no_mem;
  49559. }
  49560. pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
  49561. /* Search for an entry in P1 where all but the last rowid match K
  49562. ** If there is no such entry, jump immediately to P2.
  49563. */
  49564. assert( pCx->deferredMoveto==0 );
  49565. pCx->cacheStatus = CACHE_STALE;
  49566. rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
  49567. if( rc!=SQLITE_OK ){
  49568. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  49569. goto abort_due_to_error;
  49570. }
  49571. if( res<0 ){
  49572. rc = sqlite3BtreeNext(pCrsr, &res);
  49573. if( res ){
  49574. pc = pOp->p2 - 1;
  49575. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  49576. break;
  49577. }
  49578. }
  49579. rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res);
  49580. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  49581. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  49582. if( res>0 ){
  49583. pc = pOp->p2 - 1;
  49584. break;
  49585. }
  49586. /* At this point, pCrsr is pointing to an entry in P1 where all but
  49587. ** the final entry (the rowid) matches K. Check to see if the
  49588. ** final rowid column is different from R. If it equals R then jump
  49589. ** immediately to P2.
  49590. */
  49591. rc = sqlite3VdbeIdxRowid(pCrsr, &v);
  49592. if( rc!=SQLITE_OK ){
  49593. goto abort_due_to_error;
  49594. }
  49595. if( v==R ){
  49596. pc = pOp->p2 - 1;
  49597. break;
  49598. }
  49599. /* The final varint of the key is different from R. Store it back
  49600. ** into register R3. (The record number of an entry that violates
  49601. ** a UNIQUE constraint.)
  49602. */
  49603. pIn3->u.i = v;
  49604. assert( pIn3->flags&MEM_Int );
  49605. }
  49606. break;
  49607. }
  49608. /* Opcode: NotExists P1 P2 P3 * *
  49609. **
  49610. ** Use the content of register P3 as a integer key. If a record
  49611. ** with that key does not exist in table of P1, then jump to P2.
  49612. ** If the record does exist, then fall thru. The cursor is left
  49613. ** pointing to the record if it exists.
  49614. **
  49615. ** The difference between this operation and NotFound is that this
  49616. ** operation assumes the key is an integer and that P1 is a table whereas
  49617. ** NotFound assumes key is a blob constructed from MakeRecord and
  49618. ** P1 is an index.
  49619. **
  49620. ** See also: Found, NotFound, IsUnique
  49621. */
  49622. case OP_NotExists: { /* jump, in3 */
  49623. int i = pOp->p1;
  49624. VdbeCursor *pC;
  49625. BtCursor *pCrsr;
  49626. assert( i>=0 && i<p->nCursor );
  49627. assert( p->apCsr[i]!=0 );
  49628. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  49629. int res = 0;
  49630. u64 iKey;
  49631. assert( pIn3->flags & MEM_Int );
  49632. assert( p->apCsr[i]->isTable );
  49633. iKey = intToKey(pIn3->u.i);
  49634. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
  49635. pC->lastRowid = pIn3->u.i;
  49636. pC->rowidIsValid = res==0 ?1:0;
  49637. pC->nullRow = 0;
  49638. pC->cacheStatus = CACHE_STALE;
  49639. if( res!=0 ){
  49640. pc = pOp->p2 - 1;
  49641. assert( pC->rowidIsValid==0 );
  49642. }
  49643. }else if( !pC->pseudoTable ){
  49644. /* This happens when an attempt to open a read cursor on the
  49645. ** sqlite_master table returns SQLITE_EMPTY.
  49646. */
  49647. assert( pC->isTable );
  49648. pc = pOp->p2 - 1;
  49649. assert( pC->rowidIsValid==0 );
  49650. }
  49651. break;
  49652. }
  49653. /* Opcode: Sequence P1 P2 * * *
  49654. **
  49655. ** Find the next available sequence number for cursor P1.
  49656. ** Write the sequence number into register P2.
  49657. ** The sequence number on the cursor is incremented after this
  49658. ** instruction.
  49659. */
  49660. case OP_Sequence: { /* out2-prerelease */
  49661. int i = pOp->p1;
  49662. assert( i>=0 && i<p->nCursor );
  49663. assert( p->apCsr[i]!=0 );
  49664. pOut->u.i = p->apCsr[i]->seqCount++;
  49665. MemSetTypeFlag(pOut, MEM_Int);
  49666. break;
  49667. }
  49668. /* Opcode: NewRowid P1 P2 P3 * *
  49669. **
  49670. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  49671. ** The record number is not previously used as a key in the database
  49672. ** table that cursor P1 points to. The new record number is written
  49673. ** written to register P2.
  49674. **
  49675. ** If P3>0 then P3 is a register that holds the largest previously
  49676. ** generated record number. No new record numbers are allowed to be less
  49677. ** than this value. When this value reaches its maximum, a SQLITE_FULL
  49678. ** error is generated. The P3 register is updated with the generated
  49679. ** record number. This P3 mechanism is used to help implement the
  49680. ** AUTOINCREMENT feature.
  49681. */
  49682. case OP_NewRowid: { /* out2-prerelease */
  49683. int i = pOp->p1;
  49684. i64 v = 0;
  49685. VdbeCursor *pC;
  49686. assert( i>=0 && i<p->nCursor );
  49687. assert( p->apCsr[i]!=0 );
  49688. if( (pC = p->apCsr[i])->pCursor==0 ){
  49689. /* The zero initialization above is all that is needed */
  49690. }else{
  49691. /* The next rowid or record number (different terms for the same
  49692. ** thing) is obtained in a two-step algorithm.
  49693. **
  49694. ** First we attempt to find the largest existing rowid and add one
  49695. ** to that. But if the largest existing rowid is already the maximum
  49696. ** positive integer, we have to fall through to the second
  49697. ** probabilistic algorithm
  49698. **
  49699. ** The second algorithm is to select a rowid at random and see if
  49700. ** it already exists in the table. If it does not exist, we have
  49701. ** succeeded. If the random rowid does exist, we select a new one
  49702. ** and try again, up to 1000 times.
  49703. **
  49704. ** For a table with less than 2 billion entries, the probability
  49705. ** of not finding a unused rowid is about 1.0e-300. This is a
  49706. ** non-zero probability, but it is still vanishingly small and should
  49707. ** never cause a problem. You are much, much more likely to have a
  49708. ** hardware failure than for this algorithm to fail.
  49709. **
  49710. ** The analysis in the previous paragraph assumes that you have a good
  49711. ** source of random numbers. Is a library function like lrand48()
  49712. ** good enough? Maybe. Maybe not. It's hard to know whether there
  49713. ** might be subtle bugs is some implementations of lrand48() that
  49714. ** could cause problems. To avoid uncertainty, SQLite uses its own
  49715. ** random number generator based on the RC4 algorithm.
  49716. **
  49717. ** To promote locality of reference for repetitive inserts, the
  49718. ** first few attempts at choosing a random rowid pick values just a little
  49719. ** larger than the previous rowid. This has been shown experimentally
  49720. ** to double the speed of the COPY operation.
  49721. */
  49722. int res=0, rx=SQLITE_OK, cnt;
  49723. i64 x;
  49724. cnt = 0;
  49725. if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
  49726. BTREE_INTKEY ){
  49727. rc = SQLITE_CORRUPT_BKPT;
  49728. goto abort_due_to_error;
  49729. }
  49730. assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
  49731. assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
  49732. #ifdef SQLITE_32BIT_ROWID
  49733. # define MAX_ROWID 0x7fffffff
  49734. #else
  49735. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  49736. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  49737. ** to provide the constant while making all compilers happy.
  49738. */
  49739. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  49740. #endif
  49741. if( !pC->useRandomRowid ){
  49742. v = sqlite3BtreeGetCachedRowid(pC->pCursor);
  49743. if( v==0 ){
  49744. rc = sqlite3BtreeLast(pC->pCursor, &res);
  49745. if( rc!=SQLITE_OK ){
  49746. goto abort_due_to_error;
  49747. }
  49748. if( res ){
  49749. v = 1;
  49750. }else{
  49751. sqlite3BtreeKeySize(pC->pCursor, &v);
  49752. v = keyToInt(v);
  49753. if( v==MAX_ROWID ){
  49754. pC->useRandomRowid = 1;
  49755. }else{
  49756. v++;
  49757. }
  49758. }
  49759. }
  49760. #ifndef SQLITE_OMIT_AUTOINCREMENT
  49761. if( pOp->p3 ){
  49762. Mem *pMem;
  49763. assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
  49764. pMem = &p->aMem[pOp->p3];
  49765. REGISTER_TRACE(pOp->p3, pMem);
  49766. sqlite3VdbeMemIntegerify(pMem);
  49767. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  49768. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  49769. rc = SQLITE_FULL;
  49770. goto abort_due_to_error;
  49771. }
  49772. if( v<pMem->u.i+1 ){
  49773. v = pMem->u.i + 1;
  49774. }
  49775. pMem->u.i = v;
  49776. }
  49777. #endif
  49778. sqlite3BtreeSetCachedRowid(pC->pCursor, v<MAX_ROWID ? v+1 : 0);
  49779. }
  49780. if( pC->useRandomRowid ){
  49781. assert( pOp->p3==0 ); /* SQLITE_FULL must have occurred prior to this */
  49782. v = db->priorNewRowid;
  49783. cnt = 0;
  49784. do{
  49785. if( cnt==0 && (v&0xffffff)==v ){
  49786. v++;
  49787. }else{
  49788. sqlite3_randomness(sizeof(v), &v);
  49789. if( cnt<5 ) v &= 0xffffff;
  49790. }
  49791. if( v==0 ) continue;
  49792. x = intToKey(v);
  49793. rx = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)x, 0, &res);
  49794. cnt++;
  49795. }while( cnt<100 && rx==SQLITE_OK && res==0 );
  49796. db->priorNewRowid = v;
  49797. if( rx==SQLITE_OK && res==0 ){
  49798. rc = SQLITE_FULL;
  49799. goto abort_due_to_error;
  49800. }
  49801. }
  49802. pC->rowidIsValid = 0;
  49803. pC->deferredMoveto = 0;
  49804. pC->cacheStatus = CACHE_STALE;
  49805. }
  49806. MemSetTypeFlag(pOut, MEM_Int);
  49807. pOut->u.i = v;
  49808. break;
  49809. }
  49810. /* Opcode: Insert P1 P2 P3 P4 P5
  49811. **
  49812. ** Write an entry into the table of cursor P1. A new entry is
  49813. ** created if it doesn't already exist or the data for an existing
  49814. ** entry is overwritten. The data is the value stored register
  49815. ** number P2. The key is stored in register P3. The key must
  49816. ** be an integer.
  49817. **
  49818. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  49819. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  49820. ** then rowid is stored for subsequent return by the
  49821. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  49822. **
  49823. ** Parameter P4 may point to a string containing the table-name, or
  49824. ** may be NULL. If it is not NULL, then the update-hook
  49825. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  49826. **
  49827. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  49828. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  49829. ** and register P2 becomes ephemeral. If the cursor is changed, the
  49830. ** value of register P2 will then change. Make sure this does not
  49831. ** cause any problems.)
  49832. **
  49833. ** This instruction only works on tables. The equivalent instruction
  49834. ** for indices is OP_IdxInsert.
  49835. */
  49836. case OP_Insert: {
  49837. Mem *pData = &p->aMem[pOp->p2];
  49838. Mem *pKey = &p->aMem[pOp->p3];
  49839. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  49840. int i = pOp->p1;
  49841. VdbeCursor *pC;
  49842. assert( i>=0 && i<p->nCursor );
  49843. pC = p->apCsr[i];
  49844. assert( pC!=0 );
  49845. assert( pC->pCursor!=0 || pC->pseudoTable );
  49846. assert( pKey->flags & MEM_Int );
  49847. assert( pC->isTable );
  49848. REGISTER_TRACE(pOp->p2, pData);
  49849. REGISTER_TRACE(pOp->p3, pKey);
  49850. iKey = intToKey(pKey->u.i);
  49851. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  49852. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
  49853. if( pData->flags & MEM_Null ){
  49854. pData->z = 0;
  49855. pData->n = 0;
  49856. }else{
  49857. assert( pData->flags & (MEM_Blob|MEM_Str) );
  49858. }
  49859. if( pC->pseudoTable ){
  49860. if( !pC->ephemPseudoTable ){
  49861. sqlite3DbFree(db, pC->pData);
  49862. }
  49863. pC->iKey = iKey;
  49864. pC->nData = pData->n;
  49865. if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
  49866. pC->pData = pData->z;
  49867. if( !pC->ephemPseudoTable ){
  49868. pData->flags &= ~MEM_Dyn;
  49869. pData->flags |= MEM_Ephem;
  49870. pData->zMalloc = 0;
  49871. }
  49872. }else{
  49873. pC->pData = sqlite3Malloc( pC->nData+2 );
  49874. if( !pC->pData ) goto no_mem;
  49875. memcpy(pC->pData, pData->z, pC->nData);
  49876. pC->pData[pC->nData] = 0;
  49877. pC->pData[pC->nData+1] = 0;
  49878. }
  49879. pC->nullRow = 0;
  49880. }else{
  49881. int nZero;
  49882. if( pData->flags & MEM_Zero ){
  49883. nZero = pData->u.nZero;
  49884. }else{
  49885. nZero = 0;
  49886. }
  49887. sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
  49888. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  49889. pData->z, pData->n, nZero,
  49890. pOp->p5 & OPFLAG_APPEND);
  49891. }
  49892. pC->rowidIsValid = 0;
  49893. pC->deferredMoveto = 0;
  49894. pC->cacheStatus = CACHE_STALE;
  49895. /* Invoke the update-hook if required. */
  49896. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  49897. const char *zDb = db->aDb[pC->iDb].zName;
  49898. const char *zTbl = pOp->p4.z;
  49899. int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  49900. assert( pC->isTable );
  49901. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  49902. assert( pC->iDb>=0 );
  49903. }
  49904. break;
  49905. }
  49906. /* Opcode: Delete P1 P2 * P4 *
  49907. **
  49908. ** Delete the record at which the P1 cursor is currently pointing.
  49909. **
  49910. ** The cursor will be left pointing at either the next or the previous
  49911. ** record in the table. If it is left pointing at the next record, then
  49912. ** the next Next instruction will be a no-op. Hence it is OK to delete
  49913. ** a record from within an Next loop.
  49914. **
  49915. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  49916. ** incremented (otherwise not).
  49917. **
  49918. ** P1 must not be pseudo-table. It has to be a real table with
  49919. ** multiple rows.
  49920. **
  49921. ** If P4 is not NULL, then it is the name of the table that P1 is
  49922. ** pointing to. The update hook will be invoked, if it exists.
  49923. ** If P4 is not NULL then the P1 cursor must have been positioned
  49924. ** using OP_NotFound prior to invoking this opcode.
  49925. */
  49926. case OP_Delete: {
  49927. int i = pOp->p1;
  49928. i64 iKey = 0;
  49929. VdbeCursor *pC;
  49930. assert( i>=0 && i<p->nCursor );
  49931. pC = p->apCsr[i];
  49932. assert( pC!=0 );
  49933. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  49934. /* If the update-hook will be invoked, set iKey to the rowid of the
  49935. ** row being deleted.
  49936. */
  49937. if( db->xUpdateCallback && pOp->p4.z ){
  49938. assert( pC->isTable );
  49939. assert( pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  49940. iKey = pC->lastRowid;
  49941. }
  49942. rc = sqlite3VdbeCursorMoveto(pC);
  49943. if( rc ) goto abort_due_to_error;
  49944. sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
  49945. rc = sqlite3BtreeDelete(pC->pCursor);
  49946. pC->cacheStatus = CACHE_STALE;
  49947. /* Invoke the update-hook if required. */
  49948. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  49949. const char *zDb = db->aDb[pC->iDb].zName;
  49950. const char *zTbl = pOp->p4.z;
  49951. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
  49952. assert( pC->iDb>=0 );
  49953. }
  49954. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  49955. break;
  49956. }
  49957. /* Opcode: ResetCount P1 * *
  49958. **
  49959. ** This opcode resets the VMs internal change counter to 0. If P1 is true,
  49960. ** then the value of the change counter is copied to the database handle
  49961. ** change counter (returned by subsequent calls to sqlite3_changes())
  49962. ** before it is reset. This is used by trigger programs.
  49963. */
  49964. case OP_ResetCount: {
  49965. if( pOp->p1 ){
  49966. sqlite3VdbeSetChanges(db, p->nChange);
  49967. }
  49968. p->nChange = 0;
  49969. break;
  49970. }
  49971. /* Opcode: RowData P1 P2 * * *
  49972. **
  49973. ** Write into register P2 the complete row data for cursor P1.
  49974. ** There is no interpretation of the data.
  49975. ** It is just copied onto the P2 register exactly as
  49976. ** it is found in the database file.
  49977. **
  49978. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  49979. ** of a real table, not a pseudo-table.
  49980. */
  49981. /* Opcode: RowKey P1 P2 * * *
  49982. **
  49983. ** Write into register P2 the complete row key for cursor P1.
  49984. ** There is no interpretation of the data.
  49985. ** The key is copied onto the P3 register exactly as
  49986. ** it is found in the database file.
  49987. **
  49988. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  49989. ** of a real table, not a pseudo-table.
  49990. */
  49991. case OP_RowKey:
  49992. case OP_RowData: {
  49993. int i = pOp->p1;
  49994. VdbeCursor *pC;
  49995. BtCursor *pCrsr;
  49996. u32 n;
  49997. pOut = &p->aMem[pOp->p2];
  49998. /* Note that RowKey and RowData are really exactly the same instruction */
  49999. assert( i>=0 && i<p->nCursor );
  50000. pC = p->apCsr[i];
  50001. assert( pC->isTable || pOp->opcode==OP_RowKey );
  50002. assert( pC->isIndex || pOp->opcode==OP_RowData );
  50003. assert( pC!=0 );
  50004. assert( pC->nullRow==0 );
  50005. assert( pC->pseudoTable==0 );
  50006. assert( pC->pCursor!=0 );
  50007. pCrsr = pC->pCursor;
  50008. rc = sqlite3VdbeCursorMoveto(pC);
  50009. if( rc ) goto abort_due_to_error;
  50010. if( pC->isIndex ){
  50011. i64 n64;
  50012. assert( !pC->isTable );
  50013. sqlite3BtreeKeySize(pCrsr, &n64);
  50014. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  50015. goto too_big;
  50016. }
  50017. n = (int)n64;
  50018. }else{
  50019. sqlite3BtreeDataSize(pCrsr, &n);
  50020. if( (int)n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  50021. goto too_big;
  50022. }
  50023. }
  50024. if( sqlite3VdbeMemGrow(pOut, n, 0) ){
  50025. goto no_mem;
  50026. }
  50027. pOut->n = n;
  50028. MemSetTypeFlag(pOut, MEM_Blob);
  50029. if( pC->isIndex ){
  50030. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  50031. }else{
  50032. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  50033. }
  50034. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  50035. UPDATE_MAX_BLOBSIZE(pOut);
  50036. break;
  50037. }
  50038. /* Opcode: Rowid P1 P2 * * *
  50039. **
  50040. ** Store in register P2 an integer which is the key of the table entry that
  50041. ** P1 is currently point to.
  50042. */
  50043. case OP_Rowid: { /* out2-prerelease */
  50044. int i = pOp->p1;
  50045. VdbeCursor *pC;
  50046. i64 v;
  50047. assert( i>=0 && i<p->nCursor );
  50048. pC = p->apCsr[i];
  50049. assert( pC!=0 );
  50050. rc = sqlite3VdbeCursorMoveto(pC);
  50051. if( rc ) goto abort_due_to_error;
  50052. if( pC->rowidIsValid ){
  50053. v = pC->lastRowid;
  50054. }else if( pC->pseudoTable ){
  50055. v = keyToInt(pC->iKey);
  50056. }else if( pC->nullRow ){
  50057. /* Leave the rowid set to a NULL */
  50058. break;
  50059. }else{
  50060. assert( pC->pCursor!=0 );
  50061. sqlite3BtreeKeySize(pC->pCursor, &v);
  50062. v = keyToInt(v);
  50063. }
  50064. pOut->u.i = v;
  50065. MemSetTypeFlag(pOut, MEM_Int);
  50066. break;
  50067. }
  50068. /* Opcode: NullRow P1 * * * *
  50069. **
  50070. ** Move the cursor P1 to a null row. Any OP_Column operations
  50071. ** that occur while the cursor is on the null row will always
  50072. ** write a NULL.
  50073. */
  50074. case OP_NullRow: {
  50075. int i = pOp->p1;
  50076. VdbeCursor *pC;
  50077. assert( i>=0 && i<p->nCursor );
  50078. pC = p->apCsr[i];
  50079. assert( pC!=0 );
  50080. pC->nullRow = 1;
  50081. pC->rowidIsValid = 0;
  50082. if( pC->pCursor ){
  50083. sqlite3BtreeClearCursor(pC->pCursor);
  50084. }
  50085. break;
  50086. }
  50087. /* Opcode: Last P1 P2 * * *
  50088. **
  50089. ** The next use of the Rowid or Column or Next instruction for P1
  50090. ** will refer to the last entry in the database table or index.
  50091. ** If the table or index is empty and P2>0, then jump immediately to P2.
  50092. ** If P2 is 0 or if the table or index is not empty, fall through
  50093. ** to the following instruction.
  50094. */
  50095. case OP_Last: { /* jump */
  50096. int i = pOp->p1;
  50097. VdbeCursor *pC;
  50098. BtCursor *pCrsr;
  50099. int res;
  50100. assert( i>=0 && i<p->nCursor );
  50101. pC = p->apCsr[i];
  50102. assert( pC!=0 );
  50103. pCrsr = pC->pCursor;
  50104. assert( pCrsr!=0 );
  50105. rc = sqlite3BtreeLast(pCrsr, &res);
  50106. pC->nullRow = (u8)res;
  50107. pC->deferredMoveto = 0;
  50108. pC->rowidIsValid = 0;
  50109. pC->cacheStatus = CACHE_STALE;
  50110. if( res && pOp->p2>0 ){
  50111. pc = pOp->p2 - 1;
  50112. }
  50113. break;
  50114. }
  50115. /* Opcode: Sort P1 P2 * * *
  50116. **
  50117. ** This opcode does exactly the same thing as OP_Rewind except that
  50118. ** it increments an undocumented global variable used for testing.
  50119. **
  50120. ** Sorting is accomplished by writing records into a sorting index,
  50121. ** then rewinding that index and playing it back from beginning to
  50122. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  50123. ** rewinding so that the global variable will be incremented and
  50124. ** regression tests can determine whether or not the optimizer is
  50125. ** correctly optimizing out sorts.
  50126. */
  50127. case OP_Sort: { /* jump */
  50128. #ifdef SQLITE_TEST
  50129. sqlite3_sort_count++;
  50130. sqlite3_search_count--;
  50131. #endif
  50132. p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
  50133. /* Fall through into OP_Rewind */
  50134. }
  50135. /* Opcode: Rewind P1 P2 * * *
  50136. **
  50137. ** The next use of the Rowid or Column or Next instruction for P1
  50138. ** will refer to the first entry in the database table or index.
  50139. ** If the table or index is empty and P2>0, then jump immediately to P2.
  50140. ** If P2 is 0 or if the table or index is not empty, fall through
  50141. ** to the following instruction.
  50142. */
  50143. case OP_Rewind: { /* jump */
  50144. int i = pOp->p1;
  50145. VdbeCursor *pC;
  50146. BtCursor *pCrsr;
  50147. int res;
  50148. assert( i>=0 && i<p->nCursor );
  50149. pC = p->apCsr[i];
  50150. assert( pC!=0 );
  50151. if( (pCrsr = pC->pCursor)!=0 ){
  50152. rc = sqlite3BtreeFirst(pCrsr, &res);
  50153. pC->atFirst = res==0 ?1:0;
  50154. pC->deferredMoveto = 0;
  50155. pC->cacheStatus = CACHE_STALE;
  50156. pC->rowidIsValid = 0;
  50157. }else{
  50158. res = 1;
  50159. }
  50160. pC->nullRow = (u8)res;
  50161. assert( pOp->p2>0 && pOp->p2<p->nOp );
  50162. if( res ){
  50163. pc = pOp->p2 - 1;
  50164. }
  50165. break;
  50166. }
  50167. /* Opcode: Next P1 P2 * * *
  50168. **
  50169. ** Advance cursor P1 so that it points to the next key/data pair in its
  50170. ** table or index. If there are no more key/value pairs then fall through
  50171. ** to the following instruction. But if the cursor advance was successful,
  50172. ** jump immediately to P2.
  50173. **
  50174. ** The P1 cursor must be for a real table, not a pseudo-table.
  50175. **
  50176. ** See also: Prev
  50177. */
  50178. /* Opcode: Prev P1 P2 * * *
  50179. **
  50180. ** Back up cursor P1 so that it points to the previous key/data pair in its
  50181. ** table or index. If there is no previous key/value pairs then fall through
  50182. ** to the following instruction. But if the cursor backup was successful,
  50183. ** jump immediately to P2.
  50184. **
  50185. ** The P1 cursor must be for a real table, not a pseudo-table.
  50186. */
  50187. case OP_Prev: /* jump */
  50188. case OP_Next: { /* jump */
  50189. VdbeCursor *pC;
  50190. BtCursor *pCrsr;
  50191. int res;
  50192. CHECK_FOR_INTERRUPT;
  50193. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  50194. pC = p->apCsr[pOp->p1];
  50195. if( pC==0 ){
  50196. break; /* See ticket #2273 */
  50197. }
  50198. pCrsr = pC->pCursor;
  50199. assert( pCrsr );
  50200. res = 1;
  50201. assert( pC->deferredMoveto==0 );
  50202. rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
  50203. sqlite3BtreePrevious(pCrsr, &res);
  50204. pC->nullRow = (u8)res;
  50205. pC->cacheStatus = CACHE_STALE;
  50206. if( res==0 ){
  50207. pc = pOp->p2 - 1;
  50208. if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
  50209. #ifdef SQLITE_TEST
  50210. sqlite3_search_count++;
  50211. #endif
  50212. }
  50213. pC->rowidIsValid = 0;
  50214. break;
  50215. }
  50216. /* Opcode: IdxInsert P1 P2 P3 * *
  50217. **
  50218. ** Register P2 holds a SQL index key made using the
  50219. ** MakeRecord instructions. This opcode writes that key
  50220. ** into the index P1. Data for the entry is nil.
  50221. **
  50222. ** P3 is a flag that provides a hint to the b-tree layer that this
  50223. ** insert is likely to be an append.
  50224. **
  50225. ** This instruction only works for indices. The equivalent instruction
  50226. ** for tables is OP_Insert.
  50227. */
  50228. case OP_IdxInsert: { /* in2 */
  50229. int i = pOp->p1;
  50230. VdbeCursor *pC;
  50231. BtCursor *pCrsr;
  50232. assert( i>=0 && i<p->nCursor );
  50233. assert( p->apCsr[i]!=0 );
  50234. assert( pIn2->flags & MEM_Blob );
  50235. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  50236. assert( pC->isTable==0 );
  50237. rc = ExpandBlob(pIn2);
  50238. if( rc==SQLITE_OK ){
  50239. int nKey = pIn2->n;
  50240. const char *zKey = pIn2->z;
  50241. rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
  50242. assert( pC->deferredMoveto==0 );
  50243. pC->cacheStatus = CACHE_STALE;
  50244. }
  50245. }
  50246. break;
  50247. }
  50248. /* Opcode: IdxDelete P1 P2 P3 * *
  50249. **
  50250. ** The content of P3 registers starting at register P2 form
  50251. ** an unpacked index key. This opcode removes that entry from the
  50252. ** index opened by cursor P1.
  50253. */
  50254. case OP_IdxDelete: {
  50255. int i = pOp->p1;
  50256. VdbeCursor *pC;
  50257. BtCursor *pCrsr;
  50258. assert( pOp->p3>0 );
  50259. assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
  50260. assert( i>=0 && i<p->nCursor );
  50261. assert( p->apCsr[i]!=0 );
  50262. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  50263. int res;
  50264. UnpackedRecord r;
  50265. r.pKeyInfo = pC->pKeyInfo;
  50266. r.nField = (u16)pOp->p3;
  50267. r.flags = 0;
  50268. r.aMem = &p->aMem[pOp->p2];
  50269. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  50270. if( rc==SQLITE_OK && res==0 ){
  50271. rc = sqlite3BtreeDelete(pCrsr);
  50272. }
  50273. assert( pC->deferredMoveto==0 );
  50274. pC->cacheStatus = CACHE_STALE;
  50275. }
  50276. break;
  50277. }
  50278. /* Opcode: IdxRowid P1 P2 * * *
  50279. **
  50280. ** Write into register P2 an integer which is the last entry in the record at
  50281. ** the end of the index key pointed to by cursor P1. This integer should be
  50282. ** the rowid of the table entry to which this index entry points.
  50283. **
  50284. ** See also: Rowid, MakeRecord.
  50285. */
  50286. case OP_IdxRowid: { /* out2-prerelease */
  50287. int i = pOp->p1;
  50288. BtCursor *pCrsr;
  50289. VdbeCursor *pC;
  50290. assert( i>=0 && i<p->nCursor );
  50291. assert( p->apCsr[i]!=0 );
  50292. if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
  50293. i64 rowid;
  50294. rc = sqlite3VdbeCursorMoveto(pC);
  50295. if( rc ) goto abort_due_to_error;
  50296. assert( pC->deferredMoveto==0 );
  50297. assert( pC->isTable==0 );
  50298. if( !pC->nullRow ){
  50299. rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
  50300. if( rc!=SQLITE_OK ){
  50301. goto abort_due_to_error;
  50302. }
  50303. MemSetTypeFlag(pOut, MEM_Int);
  50304. pOut->u.i = rowid;
  50305. }
  50306. }
  50307. break;
  50308. }
  50309. /* Opcode: IdxGE P1 P2 P3 P4 P5
  50310. **
  50311. ** The P4 register values beginning with P3 form an unpacked index
  50312. ** key that omits the ROWID. Compare this key value against the index
  50313. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  50314. **
  50315. ** If the P1 index entry is greater than or equal to the key value
  50316. ** then jump to P2. Otherwise fall through to the next instruction.
  50317. **
  50318. ** If P5 is non-zero then the key value is increased by an epsilon
  50319. ** prior to the comparison. This make the opcode work like IdxGT except
  50320. ** that if the key from register P3 is a prefix of the key in the cursor,
  50321. ** the result is false whereas it would be true with IdxGT.
  50322. */
  50323. /* Opcode: IdxLT P1 P2 P3 * P5
  50324. **
  50325. ** The P4 register values beginning with P3 form an unpacked index
  50326. ** key that omits the ROWID. Compare this key value against the index
  50327. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  50328. **
  50329. ** If the P1 index entry is less than the key value then jump to P2.
  50330. ** Otherwise fall through to the next instruction.
  50331. **
  50332. ** If P5 is non-zero then the key value is increased by an epsilon prior
  50333. ** to the comparison. This makes the opcode work like IdxLE.
  50334. */
  50335. case OP_IdxLT: /* jump, in3 */
  50336. case OP_IdxGE: { /* jump, in3 */
  50337. int i= pOp->p1;
  50338. VdbeCursor *pC;
  50339. assert( i>=0 && i<p->nCursor );
  50340. assert( p->apCsr[i]!=0 );
  50341. if( (pC = p->apCsr[i])->pCursor!=0 ){
  50342. int res;
  50343. UnpackedRecord r;
  50344. assert( pC->deferredMoveto==0 );
  50345. assert( pOp->p5==0 || pOp->p5==1 );
  50346. assert( pOp->p4type==P4_INT32 );
  50347. r.pKeyInfo = pC->pKeyInfo;
  50348. r.nField = (u16)pOp->p4.i;
  50349. if( pOp->p5 ){
  50350. r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
  50351. }else{
  50352. r.flags = UNPACKED_IGNORE_ROWID;
  50353. }
  50354. r.aMem = &p->aMem[pOp->p3];
  50355. rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
  50356. if( pOp->opcode==OP_IdxLT ){
  50357. res = -res;
  50358. }else{
  50359. assert( pOp->opcode==OP_IdxGE );
  50360. res++;
  50361. }
  50362. if( res>0 ){
  50363. pc = pOp->p2 - 1 ;
  50364. }
  50365. }
  50366. break;
  50367. }
  50368. /* Opcode: Destroy P1 P2 P3 * *
  50369. **
  50370. ** Delete an entire database table or index whose root page in the database
  50371. ** file is given by P1.
  50372. **
  50373. ** The table being destroyed is in the main database file if P3==0. If
  50374. ** P3==1 then the table to be clear is in the auxiliary database file
  50375. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  50376. **
  50377. ** If AUTOVACUUM is enabled then it is possible that another root page
  50378. ** might be moved into the newly deleted root page in order to keep all
  50379. ** root pages contiguous at the beginning of the database. The former
  50380. ** value of the root page that moved - its value before the move occurred -
  50381. ** is stored in register P2. If no page
  50382. ** movement was required (because the table being dropped was already
  50383. ** the last one in the database) then a zero is stored in register P2.
  50384. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  50385. **
  50386. ** See also: Clear
  50387. */
  50388. case OP_Destroy: { /* out2-prerelease */
  50389. int iMoved;
  50390. int iCnt;
  50391. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50392. Vdbe *pVdbe;
  50393. iCnt = 0;
  50394. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  50395. if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
  50396. iCnt++;
  50397. }
  50398. }
  50399. #else
  50400. iCnt = db->activeVdbeCnt;
  50401. #endif
  50402. if( iCnt>1 ){
  50403. rc = SQLITE_LOCKED;
  50404. p->errorAction = OE_Abort;
  50405. }else{
  50406. int iDb = pOp->p3;
  50407. assert( iCnt==1 );
  50408. assert( (p->btreeMask & (1<<iDb))!=0 );
  50409. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  50410. MemSetTypeFlag(pOut, MEM_Int);
  50411. pOut->u.i = iMoved;
  50412. #ifndef SQLITE_OMIT_AUTOVACUUM
  50413. if( rc==SQLITE_OK && iMoved!=0 ){
  50414. sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
  50415. }
  50416. #endif
  50417. }
  50418. break;
  50419. }
  50420. /* Opcode: Clear P1 P2 P3
  50421. **
  50422. ** Delete all contents of the database table or index whose root page
  50423. ** in the database file is given by P1. But, unlike Destroy, do not
  50424. ** remove the table or index from the database file.
  50425. **
  50426. ** The table being clear is in the main database file if P2==0. If
  50427. ** P2==1 then the table to be clear is in the auxiliary database file
  50428. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  50429. **
  50430. ** If the P3 value is non-zero, then the table referred to must be an
  50431. ** intkey table (an SQL table, not an index). In this case the row change
  50432. ** count is incremented by the number of rows in the table being cleared.
  50433. ** If P3 is greater than zero, then the value stored in register P3 is
  50434. ** also incremented by the number of rows in the table being cleared.
  50435. **
  50436. ** See also: Destroy
  50437. */
  50438. case OP_Clear: {
  50439. int nChange = 0;
  50440. assert( (p->btreeMask & (1<<pOp->p2))!=0 );
  50441. rc = sqlite3BtreeClearTable(
  50442. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  50443. );
  50444. if( pOp->p3 ){
  50445. p->nChange += nChange;
  50446. if( pOp->p3>0 ){
  50447. p->aMem[pOp->p3].u.i += nChange;
  50448. }
  50449. }
  50450. break;
  50451. }
  50452. /* Opcode: CreateTable P1 P2 * * *
  50453. **
  50454. ** Allocate a new table in the main database file if P1==0 or in the
  50455. ** auxiliary database file if P1==1 or in an attached database if
  50456. ** P1>1. Write the root page number of the new table into
  50457. ** register P2
  50458. **
  50459. ** The difference between a table and an index is this: A table must
  50460. ** have a 4-byte integer key and can have arbitrary data. An index
  50461. ** has an arbitrary key but no data.
  50462. **
  50463. ** See also: CreateIndex
  50464. */
  50465. /* Opcode: CreateIndex P1 P2 * * *
  50466. **
  50467. ** Allocate a new index in the main database file if P1==0 or in the
  50468. ** auxiliary database file if P1==1 or in an attached database if
  50469. ** P1>1. Write the root page number of the new table into
  50470. ** register P2.
  50471. **
  50472. ** See documentation on OP_CreateTable for additional information.
  50473. */
  50474. case OP_CreateIndex: /* out2-prerelease */
  50475. case OP_CreateTable: { /* out2-prerelease */
  50476. int pgno = 0;
  50477. int flags;
  50478. Db *pDb;
  50479. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  50480. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  50481. pDb = &db->aDb[pOp->p1];
  50482. assert( pDb->pBt!=0 );
  50483. if( pOp->opcode==OP_CreateTable ){
  50484. /* flags = BTREE_INTKEY; */
  50485. flags = BTREE_LEAFDATA|BTREE_INTKEY;
  50486. }else{
  50487. flags = BTREE_ZERODATA;
  50488. }
  50489. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  50490. pOut->u.i = pgno;
  50491. MemSetTypeFlag(pOut, MEM_Int);
  50492. break;
  50493. }
  50494. /* Opcode: ParseSchema P1 P2 * P4 *
  50495. **
  50496. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  50497. ** that match the WHERE clause P4. P2 is the "force" flag. Always do
  50498. ** the parsing if P2 is true. If P2 is false, then this routine is a
  50499. ** no-op if the schema is not currently loaded. In other words, if P2
  50500. ** is false, the SQLITE_MASTER table is only parsed if the rest of the
  50501. ** schema is already loaded into the symbol table.
  50502. **
  50503. ** This opcode invokes the parser to create a new virtual machine,
  50504. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  50505. */
  50506. case OP_ParseSchema: {
  50507. int iDb = pOp->p1;
  50508. assert( iDb>=0 && iDb<db->nDb );
  50509. /* If pOp->p2 is 0, then this opcode is being executed to read a
  50510. ** single row, for example the row corresponding to a new index
  50511. ** created by this VDBE, from the sqlite_master table. It only
  50512. ** does this if the corresponding in-memory schema is currently
  50513. ** loaded. Otherwise, the new index definition can be loaded along
  50514. ** with the rest of the schema when it is required.
  50515. **
  50516. ** Although the mutex on the BtShared object that corresponds to
  50517. ** database iDb (the database containing the sqlite_master table
  50518. ** read by this instruction) is currently held, it is necessary to
  50519. ** obtain the mutexes on all attached databases before checking if
  50520. ** the schema of iDb is loaded. This is because, at the start of
  50521. ** the sqlite3_exec() call below, SQLite will invoke
  50522. ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
  50523. ** iDb mutex may be temporarily released to avoid deadlock. If
  50524. ** this happens, then some other thread may delete the in-memory
  50525. ** schema of database iDb before the SQL statement runs. The schema
  50526. ** will not be reloaded becuase the db->init.busy flag is set. This
  50527. ** can result in a "no such table: sqlite_master" or "malformed
  50528. ** database schema" error being returned to the user.
  50529. */
  50530. assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  50531. sqlite3BtreeEnterAll(db);
  50532. if( pOp->p2 || DbHasProperty(db, iDb, DB_SchemaLoaded) ){
  50533. const char *zMaster = SCHEMA_TABLE(iDb);
  50534. char *zSql;
  50535. InitData initData;
  50536. initData.db = db;
  50537. initData.iDb = pOp->p1;
  50538. initData.pzErrMsg = &p->zErrMsg;
  50539. zSql = sqlite3MPrintf(db,
  50540. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
  50541. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  50542. if( zSql==0 ){
  50543. rc = SQLITE_NOMEM;
  50544. }else{
  50545. (void)sqlite3SafetyOff(db);
  50546. assert( db->init.busy==0 );
  50547. db->init.busy = 1;
  50548. initData.rc = SQLITE_OK;
  50549. assert( !db->mallocFailed );
  50550. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  50551. if( rc==SQLITE_OK ) rc = initData.rc;
  50552. sqlite3DbFree(db, zSql);
  50553. db->init.busy = 0;
  50554. (void)sqlite3SafetyOn(db);
  50555. }
  50556. }
  50557. sqlite3BtreeLeaveAll(db);
  50558. if( rc==SQLITE_NOMEM ){
  50559. goto no_mem;
  50560. }
  50561. break;
  50562. }
  50563. #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
  50564. /* Opcode: LoadAnalysis P1 * * * *
  50565. **
  50566. ** Read the sqlite_stat1 table for database P1 and load the content
  50567. ** of that table into the internal index hash table. This will cause
  50568. ** the analysis to be used when preparing all subsequent queries.
  50569. */
  50570. case OP_LoadAnalysis: {
  50571. int iDb = pOp->p1;
  50572. assert( iDb>=0 && iDb<db->nDb );
  50573. rc = sqlite3AnalysisLoad(db, iDb);
  50574. break;
  50575. }
  50576. #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
  50577. /* Opcode: DropTable P1 * * P4 *
  50578. **
  50579. ** Remove the internal (in-memory) data structures that describe
  50580. ** the table named P4 in database P1. This is called after a table
  50581. ** is dropped in order to keep the internal representation of the
  50582. ** schema consistent with what is on disk.
  50583. */
  50584. case OP_DropTable: {
  50585. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  50586. break;
  50587. }
  50588. /* Opcode: DropIndex P1 * * P4 *
  50589. **
  50590. ** Remove the internal (in-memory) data structures that describe
  50591. ** the index named P4 in database P1. This is called after an index
  50592. ** is dropped in order to keep the internal representation of the
  50593. ** schema consistent with what is on disk.
  50594. */
  50595. case OP_DropIndex: {
  50596. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  50597. break;
  50598. }
  50599. /* Opcode: DropTrigger P1 * * P4 *
  50600. **
  50601. ** Remove the internal (in-memory) data structures that describe
  50602. ** the trigger named P4 in database P1. This is called after a trigger
  50603. ** is dropped in order to keep the internal representation of the
  50604. ** schema consistent with what is on disk.
  50605. */
  50606. case OP_DropTrigger: {
  50607. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  50608. break;
  50609. }
  50610. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  50611. /* Opcode: IntegrityCk P1 P2 P3 * P5
  50612. **
  50613. ** Do an analysis of the currently open database. Store in
  50614. ** register P1 the text of an error message describing any problems.
  50615. ** If no problems are found, store a NULL in register P1.
  50616. **
  50617. ** The register P3 contains the maximum number of allowed errors.
  50618. ** At most reg(P3) errors will be reported.
  50619. ** In other words, the analysis stops as soon as reg(P1) errors are
  50620. ** seen. Reg(P1) is updated with the number of errors remaining.
  50621. **
  50622. ** The root page numbers of all tables in the database are integer
  50623. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  50624. ** total.
  50625. **
  50626. ** If P5 is not zero, the check is done on the auxiliary database
  50627. ** file, not the main database file.
  50628. **
  50629. ** This opcode is used to implement the integrity_check pragma.
  50630. */
  50631. case OP_IntegrityCk: {
  50632. int nRoot; /* Number of tables to check. (Number of root pages.) */
  50633. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  50634. int j; /* Loop counter */
  50635. int nErr; /* Number of errors reported */
  50636. char *z; /* Text of the error report */
  50637. Mem *pnErr; /* Register keeping track of errors remaining */
  50638. nRoot = pOp->p2;
  50639. assert( nRoot>0 );
  50640. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  50641. if( aRoot==0 ) goto no_mem;
  50642. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  50643. pnErr = &p->aMem[pOp->p3];
  50644. assert( (pnErr->flags & MEM_Int)!=0 );
  50645. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  50646. pIn1 = &p->aMem[pOp->p1];
  50647. for(j=0; j<nRoot; j++){
  50648. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  50649. }
  50650. aRoot[j] = 0;
  50651. assert( pOp->p5<db->nDb );
  50652. assert( (p->btreeMask & (1<<pOp->p5))!=0 );
  50653. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  50654. (int)pnErr->u.i, &nErr);
  50655. sqlite3DbFree(db, aRoot);
  50656. pnErr->u.i -= nErr;
  50657. sqlite3VdbeMemSetNull(pIn1);
  50658. if( nErr==0 ){
  50659. assert( z==0 );
  50660. }else if( z==0 ){
  50661. goto no_mem;
  50662. }else{
  50663. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  50664. }
  50665. UPDATE_MAX_BLOBSIZE(pIn1);
  50666. sqlite3VdbeChangeEncoding(pIn1, encoding);
  50667. break;
  50668. }
  50669. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  50670. /* Opcode: RowSetAdd P1 P2 * * *
  50671. **
  50672. ** Insert the integer value held by register P2 into a boolean index
  50673. ** held in register P1.
  50674. **
  50675. ** An assertion fails if P2 is not an integer.
  50676. */
  50677. case OP_RowSetAdd: { /* in2 */
  50678. Mem *pIdx;
  50679. Mem *pVal;
  50680. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  50681. pIdx = &p->aMem[pOp->p1];
  50682. assert( pOp->p2>0 && pOp->p2<=p->nMem );
  50683. pVal = &p->aMem[pOp->p2];
  50684. assert( (pVal->flags & MEM_Int)!=0 );
  50685. if( (pIdx->flags & MEM_RowSet)==0 ){
  50686. sqlite3VdbeMemSetRowSet(pIdx);
  50687. if( (pIdx->flags & MEM_RowSet)==0 ) goto no_mem;
  50688. }
  50689. sqlite3RowSetInsert(pIdx->u.pRowSet, pVal->u.i);
  50690. break;
  50691. }
  50692. /* Opcode: RowSetRead P1 P2 P3 * *
  50693. **
  50694. ** Extract the smallest value from boolean index P1 and put that value into
  50695. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  50696. ** unchanged and jump to instruction P2.
  50697. */
  50698. case OP_RowSetRead: { /* jump, out3 */
  50699. Mem *pIdx;
  50700. i64 val;
  50701. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  50702. CHECK_FOR_INTERRUPT;
  50703. pIdx = &p->aMem[pOp->p1];
  50704. pOut = &p->aMem[pOp->p3];
  50705. if( (pIdx->flags & MEM_RowSet)==0
  50706. || sqlite3RowSetNext(pIdx->u.pRowSet, &val)==0
  50707. ){
  50708. /* The boolean index is empty */
  50709. sqlite3VdbeMemSetNull(pIdx);
  50710. pc = pOp->p2 - 1;
  50711. }else{
  50712. /* A value was pulled from the index */
  50713. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  50714. sqlite3VdbeMemSetInt64(pOut, val);
  50715. }
  50716. break;
  50717. }
  50718. #ifndef SQLITE_OMIT_TRIGGER
  50719. /* Opcode: ContextPush * * *
  50720. **
  50721. ** Save the current Vdbe context such that it can be restored by a ContextPop
  50722. ** opcode. The context stores the last insert row id, the last statement change
  50723. ** count, and the current statement change count.
  50724. */
  50725. case OP_ContextPush: {
  50726. int i = p->contextStackTop++;
  50727. Context *pContext;
  50728. assert( i>=0 );
  50729. /* FIX ME: This should be allocated as part of the vdbe at compile-time */
  50730. if( i>=p->contextStackDepth ){
  50731. p->contextStackDepth = i+1;
  50732. p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
  50733. sizeof(Context)*(i+1));
  50734. if( p->contextStack==0 ) goto no_mem;
  50735. }
  50736. pContext = &p->contextStack[i];
  50737. pContext->lastRowid = db->lastRowid;
  50738. pContext->nChange = p->nChange;
  50739. break;
  50740. }
  50741. /* Opcode: ContextPop * * *
  50742. **
  50743. ** Restore the Vdbe context to the state it was in when contextPush was last
  50744. ** executed. The context stores the last insert row id, the last statement
  50745. ** change count, and the current statement change count.
  50746. */
  50747. case OP_ContextPop: {
  50748. Context *pContext = &p->contextStack[--p->contextStackTop];
  50749. assert( p->contextStackTop>=0 );
  50750. db->lastRowid = pContext->lastRowid;
  50751. p->nChange = pContext->nChange;
  50752. break;
  50753. }
  50754. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  50755. #ifndef SQLITE_OMIT_AUTOINCREMENT
  50756. /* Opcode: MemMax P1 P2 * * *
  50757. **
  50758. ** Set the value of register P1 to the maximum of its current value
  50759. ** and the value in register P2.
  50760. **
  50761. ** This instruction throws an error if the memory cell is not initially
  50762. ** an integer.
  50763. */
  50764. case OP_MemMax: { /* in1, in2 */
  50765. sqlite3VdbeMemIntegerify(pIn1);
  50766. sqlite3VdbeMemIntegerify(pIn2);
  50767. if( pIn1->u.i<pIn2->u.i){
  50768. pIn1->u.i = pIn2->u.i;
  50769. }
  50770. break;
  50771. }
  50772. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  50773. /* Opcode: IfPos P1 P2 * * *
  50774. **
  50775. ** If the value of register P1 is 1 or greater, jump to P2.
  50776. **
  50777. ** It is illegal to use this instruction on a register that does
  50778. ** not contain an integer. An assertion fault will result if you try.
  50779. */
  50780. case OP_IfPos: { /* jump, in1 */
  50781. assert( pIn1->flags&MEM_Int );
  50782. if( pIn1->u.i>0 ){
  50783. pc = pOp->p2 - 1;
  50784. }
  50785. break;
  50786. }
  50787. /* Opcode: IfNeg P1 P2 * * *
  50788. **
  50789. ** If the value of register P1 is less than zero, jump to P2.
  50790. **
  50791. ** It is illegal to use this instruction on a register that does
  50792. ** not contain an integer. An assertion fault will result if you try.
  50793. */
  50794. case OP_IfNeg: { /* jump, in1 */
  50795. assert( pIn1->flags&MEM_Int );
  50796. if( pIn1->u.i<0 ){
  50797. pc = pOp->p2 - 1;
  50798. }
  50799. break;
  50800. }
  50801. /* Opcode: IfZero P1 P2 * * *
  50802. **
  50803. ** If the value of register P1 is exactly 0, jump to P2.
  50804. **
  50805. ** It is illegal to use this instruction on a register that does
  50806. ** not contain an integer. An assertion fault will result if you try.
  50807. */
  50808. case OP_IfZero: { /* jump, in1 */
  50809. assert( pIn1->flags&MEM_Int );
  50810. if( pIn1->u.i==0 ){
  50811. pc = pOp->p2 - 1;
  50812. }
  50813. break;
  50814. }
  50815. /* Opcode: AggStep * P2 P3 P4 P5
  50816. **
  50817. ** Execute the step function for an aggregate. The
  50818. ** function has P5 arguments. P4 is a pointer to the FuncDef
  50819. ** structure that specifies the function. Use register
  50820. ** P3 as the accumulator.
  50821. **
  50822. ** The P5 arguments are taken from register P2 and its
  50823. ** successors.
  50824. */
  50825. case OP_AggStep: {
  50826. int n = pOp->p5;
  50827. int i;
  50828. Mem *pMem, *pRec;
  50829. sqlite3_context ctx;
  50830. sqlite3_value **apVal;
  50831. assert( n>=0 );
  50832. pRec = &p->aMem[pOp->p2];
  50833. apVal = p->apArg;
  50834. assert( apVal || n==0 );
  50835. for(i=0; i<n; i++, pRec++){
  50836. apVal[i] = pRec;
  50837. storeTypeInfo(pRec, encoding);
  50838. }
  50839. ctx.pFunc = pOp->p4.pFunc;
  50840. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  50841. ctx.pMem = pMem = &p->aMem[pOp->p3];
  50842. pMem->n++;
  50843. ctx.s.flags = MEM_Null;
  50844. ctx.s.z = 0;
  50845. ctx.s.zMalloc = 0;
  50846. ctx.s.xDel = 0;
  50847. ctx.s.db = db;
  50848. ctx.isError = 0;
  50849. ctx.pColl = 0;
  50850. if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  50851. assert( pOp>p->aOp );
  50852. assert( pOp[-1].p4type==P4_COLLSEQ );
  50853. assert( pOp[-1].opcode==OP_CollSeq );
  50854. ctx.pColl = pOp[-1].p4.pColl;
  50855. }
  50856. (ctx.pFunc->xStep)(&ctx, n, apVal);
  50857. if( ctx.isError ){
  50858. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
  50859. rc = ctx.isError;
  50860. }
  50861. sqlite3VdbeMemRelease(&ctx.s);
  50862. break;
  50863. }
  50864. /* Opcode: AggFinal P1 P2 * P4 *
  50865. **
  50866. ** Execute the finalizer function for an aggregate. P1 is
  50867. ** the memory location that is the accumulator for the aggregate.
  50868. **
  50869. ** P2 is the number of arguments that the step function takes and
  50870. ** P4 is a pointer to the FuncDef for this function. The P2
  50871. ** argument is not used by this opcode. It is only there to disambiguate
  50872. ** functions that can take varying numbers of arguments. The
  50873. ** P4 argument is only needed for the degenerate case where
  50874. ** the step function was not previously called.
  50875. */
  50876. case OP_AggFinal: {
  50877. Mem *pMem;
  50878. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  50879. pMem = &p->aMem[pOp->p1];
  50880. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  50881. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  50882. if( rc==SQLITE_ERROR ){
  50883. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
  50884. }
  50885. sqlite3VdbeChangeEncoding(pMem, encoding);
  50886. UPDATE_MAX_BLOBSIZE(pMem);
  50887. if( sqlite3VdbeMemTooBig(pMem) ){
  50888. goto too_big;
  50889. }
  50890. break;
  50891. }
  50892. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  50893. /* Opcode: Vacuum * * * * *
  50894. **
  50895. ** Vacuum the entire database. This opcode will cause other virtual
  50896. ** machines to be created and run. It may not be called from within
  50897. ** a transaction.
  50898. */
  50899. case OP_Vacuum: {
  50900. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  50901. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  50902. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  50903. break;
  50904. }
  50905. #endif
  50906. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  50907. /* Opcode: IncrVacuum P1 P2 * * *
  50908. **
  50909. ** Perform a single step of the incremental vacuum procedure on
  50910. ** the P1 database. If the vacuum has finished, jump to instruction
  50911. ** P2. Otherwise, fall through to the next instruction.
  50912. */
  50913. case OP_IncrVacuum: { /* jump */
  50914. Btree *pBt;
  50915. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  50916. assert( (p->btreeMask & (1<<pOp->p1))!=0 );
  50917. pBt = db->aDb[pOp->p1].pBt;
  50918. rc = sqlite3BtreeIncrVacuum(pBt);
  50919. if( rc==SQLITE_DONE ){
  50920. pc = pOp->p2 - 1;
  50921. rc = SQLITE_OK;
  50922. }
  50923. break;
  50924. }
  50925. #endif
  50926. /* Opcode: Expire P1 * * * *
  50927. **
  50928. ** Cause precompiled statements to become expired. An expired statement
  50929. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  50930. ** (via sqlite3_step()).
  50931. **
  50932. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  50933. ** then only the currently executing statement is affected.
  50934. */
  50935. case OP_Expire: {
  50936. if( !pOp->p1 ){
  50937. sqlite3ExpirePreparedStatements(db);
  50938. }else{
  50939. p->expired = 1;
  50940. }
  50941. break;
  50942. }
  50943. #ifndef SQLITE_OMIT_SHARED_CACHE
  50944. /* Opcode: TableLock P1 P2 P3 P4 *
  50945. **
  50946. ** Obtain a lock on a particular table. This instruction is only used when
  50947. ** the shared-cache feature is enabled.
  50948. **
  50949. ** If P1 is the index of the database in sqlite3.aDb[] of the database
  50950. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  50951. ** a write lock if P3==1.
  50952. **
  50953. ** P2 contains the root-page of the table to lock.
  50954. **
  50955. ** P4 contains a pointer to the name of the table being locked. This is only
  50956. ** used to generate an error message if the lock cannot be obtained.
  50957. */
  50958. case OP_TableLock: {
  50959. int p1 = pOp->p1;
  50960. u8 isWriteLock = (u8)pOp->p3;
  50961. assert( p1>=0 && p1<db->nDb );
  50962. assert( (p->btreeMask & (1<<p1))!=0 );
  50963. assert( isWriteLock==0 || isWriteLock==1 );
  50964. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  50965. if( (rc&0xFF)==SQLITE_LOCKED ){
  50966. const char *z = pOp->p4.z;
  50967. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  50968. }
  50969. break;
  50970. }
  50971. #endif /* SQLITE_OMIT_SHARED_CACHE */
  50972. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50973. /* Opcode: VBegin * * * P4 *
  50974. **
  50975. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  50976. ** xBegin method for that table.
  50977. **
  50978. ** Also, whether or not P4 is set, check that this is not being called from
  50979. ** within a callback to a virtual table xSync() method. If it is, the error
  50980. ** code will be set to SQLITE_LOCKED.
  50981. */
  50982. case OP_VBegin: {
  50983. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  50984. rc = sqlite3VtabBegin(db, pVtab);
  50985. if( pVtab ){
  50986. sqlite3DbFree(db, p->zErrMsg);
  50987. p->zErrMsg = pVtab->zErrMsg;
  50988. pVtab->zErrMsg = 0;
  50989. }
  50990. break;
  50991. }
  50992. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50993. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50994. /* Opcode: VCreate P1 * * P4 *
  50995. **
  50996. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  50997. ** for that table.
  50998. */
  50999. case OP_VCreate: {
  51000. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  51001. break;
  51002. }
  51003. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51004. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51005. /* Opcode: VDestroy P1 * * P4 *
  51006. **
  51007. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  51008. ** of that table.
  51009. */
  51010. case OP_VDestroy: {
  51011. p->inVtabMethod = 2;
  51012. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  51013. p->inVtabMethod = 0;
  51014. break;
  51015. }
  51016. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51017. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51018. /* Opcode: VOpen P1 * * P4 *
  51019. **
  51020. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  51021. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  51022. ** table and stores that cursor in P1.
  51023. */
  51024. case OP_VOpen: {
  51025. VdbeCursor *pCur = 0;
  51026. sqlite3_vtab_cursor *pVtabCursor = 0;
  51027. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  51028. sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
  51029. assert(pVtab && pModule);
  51030. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51031. rc = pModule->xOpen(pVtab, &pVtabCursor);
  51032. sqlite3DbFree(db, p->zErrMsg);
  51033. p->zErrMsg = pVtab->zErrMsg;
  51034. pVtab->zErrMsg = 0;
  51035. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  51036. if( SQLITE_OK==rc ){
  51037. /* Initialize sqlite3_vtab_cursor base class */
  51038. pVtabCursor->pVtab = pVtab;
  51039. /* Initialise vdbe cursor object */
  51040. pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  51041. if( pCur ){
  51042. pCur->pVtabCursor = pVtabCursor;
  51043. pCur->pModule = pVtabCursor->pVtab->pModule;
  51044. }else{
  51045. db->mallocFailed = 1;
  51046. pModule->xClose(pVtabCursor);
  51047. }
  51048. }
  51049. break;
  51050. }
  51051. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51052. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51053. /* Opcode: VFilter P1 P2 P3 P4 *
  51054. **
  51055. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  51056. ** the filtered result set is empty.
  51057. **
  51058. ** P4 is either NULL or a string that was generated by the xBestIndex
  51059. ** method of the module. The interpretation of the P4 string is left
  51060. ** to the module implementation.
  51061. **
  51062. ** This opcode invokes the xFilter method on the virtual table specified
  51063. ** by P1. The integer query plan parameter to xFilter is stored in register
  51064. ** P3. Register P3+1 stores the argc parameter to be passed to the
  51065. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  51066. ** additional parameters which are passed to
  51067. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  51068. **
  51069. ** A jump is made to P2 if the result set after filtering would be empty.
  51070. */
  51071. case OP_VFilter: { /* jump */
  51072. int nArg;
  51073. int iQuery;
  51074. const sqlite3_module *pModule;
  51075. Mem *pQuery = &p->aMem[pOp->p3];
  51076. Mem *pArgc = &pQuery[1];
  51077. sqlite3_vtab_cursor *pVtabCursor;
  51078. sqlite3_vtab *pVtab;
  51079. VdbeCursor *pCur = p->apCsr[pOp->p1];
  51080. REGISTER_TRACE(pOp->p3, pQuery);
  51081. assert( pCur->pVtabCursor );
  51082. pVtabCursor = pCur->pVtabCursor;
  51083. pVtab = pVtabCursor->pVtab;
  51084. pModule = pVtab->pModule;
  51085. /* Grab the index number and argc parameters */
  51086. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  51087. nArg = (int)pArgc->u.i;
  51088. iQuery = (int)pQuery->u.i;
  51089. /* Invoke the xFilter method */
  51090. {
  51091. int res = 0;
  51092. int i;
  51093. Mem **apArg = p->apArg;
  51094. for(i = 0; i<nArg; i++){
  51095. apArg[i] = &pArgc[i+1];
  51096. storeTypeInfo(apArg[i], 0);
  51097. }
  51098. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51099. sqlite3VtabLock(pVtab);
  51100. p->inVtabMethod = 1;
  51101. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  51102. p->inVtabMethod = 0;
  51103. sqlite3DbFree(db, p->zErrMsg);
  51104. p->zErrMsg = pVtab->zErrMsg;
  51105. pVtab->zErrMsg = 0;
  51106. sqlite3VtabUnlock(db, pVtab);
  51107. if( rc==SQLITE_OK ){
  51108. res = pModule->xEof(pVtabCursor);
  51109. }
  51110. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  51111. if( res ){
  51112. pc = pOp->p2 - 1;
  51113. }
  51114. }
  51115. pCur->nullRow = 0;
  51116. break;
  51117. }
  51118. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51119. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51120. /* Opcode: VRowid P1 P2 * * *
  51121. **
  51122. ** Store into register P2 the rowid of
  51123. ** the virtual-table that the P1 cursor is pointing to.
  51124. */
  51125. case OP_VRowid: { /* out2-prerelease */
  51126. sqlite3_vtab *pVtab;
  51127. const sqlite3_module *pModule;
  51128. sqlite_int64 iRow;
  51129. VdbeCursor *pCur = p->apCsr[pOp->p1];
  51130. assert( pCur->pVtabCursor );
  51131. if( pCur->nullRow ){
  51132. break;
  51133. }
  51134. pVtab = pCur->pVtabCursor->pVtab;
  51135. pModule = pVtab->pModule;
  51136. assert( pModule->xRowid );
  51137. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51138. rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
  51139. sqlite3DbFree(db, p->zErrMsg);
  51140. p->zErrMsg = pVtab->zErrMsg;
  51141. pVtab->zErrMsg = 0;
  51142. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  51143. MemSetTypeFlag(pOut, MEM_Int);
  51144. pOut->u.i = iRow;
  51145. break;
  51146. }
  51147. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51148. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51149. /* Opcode: VColumn P1 P2 P3 * *
  51150. **
  51151. ** Store the value of the P2-th column of
  51152. ** the row of the virtual-table that the
  51153. ** P1 cursor is pointing to into register P3.
  51154. */
  51155. case OP_VColumn: {
  51156. sqlite3_vtab *pVtab;
  51157. const sqlite3_module *pModule;
  51158. Mem *pDest;
  51159. sqlite3_context sContext;
  51160. VdbeCursor *pCur = p->apCsr[pOp->p1];
  51161. assert( pCur->pVtabCursor );
  51162. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  51163. pDest = &p->aMem[pOp->p3];
  51164. if( pCur->nullRow ){
  51165. sqlite3VdbeMemSetNull(pDest);
  51166. break;
  51167. }
  51168. pVtab = pCur->pVtabCursor->pVtab;
  51169. pModule = pVtab->pModule;
  51170. assert( pModule->xColumn );
  51171. memset(&sContext, 0, sizeof(sContext));
  51172. /* The output cell may already have a buffer allocated. Move
  51173. ** the current contents to sContext.s so in case the user-function
  51174. ** can use the already allocated buffer instead of allocating a
  51175. ** new one.
  51176. */
  51177. sqlite3VdbeMemMove(&sContext.s, pDest);
  51178. MemSetTypeFlag(&sContext.s, MEM_Null);
  51179. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51180. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  51181. sqlite3DbFree(db, p->zErrMsg);
  51182. p->zErrMsg = pVtab->zErrMsg;
  51183. pVtab->zErrMsg = 0;
  51184. /* Copy the result of the function to the P3 register. We
  51185. ** do this regardless of whether or not an error occurred to ensure any
  51186. ** dynamic allocation in sContext.s (a Mem struct) is released.
  51187. */
  51188. sqlite3VdbeChangeEncoding(&sContext.s, encoding);
  51189. REGISTER_TRACE(pOp->p3, pDest);
  51190. sqlite3VdbeMemMove(pDest, &sContext.s);
  51191. UPDATE_MAX_BLOBSIZE(pDest);
  51192. if( sqlite3SafetyOn(db) ){
  51193. goto abort_due_to_misuse;
  51194. }
  51195. if( sqlite3VdbeMemTooBig(pDest) ){
  51196. goto too_big;
  51197. }
  51198. break;
  51199. }
  51200. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51201. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51202. /* Opcode: VNext P1 P2 * * *
  51203. **
  51204. ** Advance virtual table P1 to the next row in its result set and
  51205. ** jump to instruction P2. Or, if the virtual table has reached
  51206. ** the end of its result set, then fall through to the next instruction.
  51207. */
  51208. case OP_VNext: { /* jump */
  51209. sqlite3_vtab *pVtab;
  51210. const sqlite3_module *pModule;
  51211. int res = 0;
  51212. VdbeCursor *pCur = p->apCsr[pOp->p1];
  51213. assert( pCur->pVtabCursor );
  51214. if( pCur->nullRow ){
  51215. break;
  51216. }
  51217. pVtab = pCur->pVtabCursor->pVtab;
  51218. pModule = pVtab->pModule;
  51219. assert( pModule->xNext );
  51220. /* Invoke the xNext() method of the module. There is no way for the
  51221. ** underlying implementation to return an error if one occurs during
  51222. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  51223. ** data is available) and the error code returned when xColumn or
  51224. ** some other method is next invoked on the save virtual table cursor.
  51225. */
  51226. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51227. sqlite3VtabLock(pVtab);
  51228. p->inVtabMethod = 1;
  51229. rc = pModule->xNext(pCur->pVtabCursor);
  51230. p->inVtabMethod = 0;
  51231. sqlite3DbFree(db, p->zErrMsg);
  51232. p->zErrMsg = pVtab->zErrMsg;
  51233. pVtab->zErrMsg = 0;
  51234. sqlite3VtabUnlock(db, pVtab);
  51235. if( rc==SQLITE_OK ){
  51236. res = pModule->xEof(pCur->pVtabCursor);
  51237. }
  51238. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  51239. if( !res ){
  51240. /* If there is data, jump to P2 */
  51241. pc = pOp->p2 - 1;
  51242. }
  51243. break;
  51244. }
  51245. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51246. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51247. /* Opcode: VRename P1 * * P4 *
  51248. **
  51249. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  51250. ** This opcode invokes the corresponding xRename method. The value
  51251. ** in register P1 is passed as the zName argument to the xRename method.
  51252. */
  51253. case OP_VRename: {
  51254. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  51255. Mem *pName = &p->aMem[pOp->p1];
  51256. assert( pVtab->pModule->xRename );
  51257. REGISTER_TRACE(pOp->p1, pName);
  51258. Stringify(pName, encoding);
  51259. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51260. sqlite3VtabLock(pVtab);
  51261. rc = pVtab->pModule->xRename(pVtab, pName->z);
  51262. sqlite3DbFree(db, p->zErrMsg);
  51263. p->zErrMsg = pVtab->zErrMsg;
  51264. pVtab->zErrMsg = 0;
  51265. sqlite3VtabUnlock(db, pVtab);
  51266. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  51267. break;
  51268. }
  51269. #endif
  51270. #ifndef SQLITE_OMIT_VIRTUALTABLE
  51271. /* Opcode: VUpdate P1 P2 P3 P4 *
  51272. **
  51273. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  51274. ** This opcode invokes the corresponding xUpdate method. P2 values
  51275. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  51276. ** invocation. The value in register (P3+P2-1) corresponds to the
  51277. ** p2th element of the argv array passed to xUpdate.
  51278. **
  51279. ** The xUpdate method will do a DELETE or an INSERT or both.
  51280. ** The argv[0] element (which corresponds to memory cell P3)
  51281. ** is the rowid of a row to delete. If argv[0] is NULL then no
  51282. ** deletion occurs. The argv[1] element is the rowid of the new
  51283. ** row. This can be NULL to have the virtual table select the new
  51284. ** rowid for itself. The subsequent elements in the array are
  51285. ** the values of columns in the new row.
  51286. **
  51287. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  51288. ** a row to delete.
  51289. **
  51290. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  51291. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  51292. ** is set to the value of the rowid for the row just inserted.
  51293. */
  51294. case OP_VUpdate: {
  51295. sqlite3_vtab *pVtab = pOp->p4.pVtab;
  51296. sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
  51297. int nArg = pOp->p2;
  51298. assert( pOp->p4type==P4_VTAB );
  51299. if( pModule->xUpdate==0 ){
  51300. sqlite3SetString(&p->zErrMsg, db, "read-only table");
  51301. rc = SQLITE_ERROR;
  51302. }else{
  51303. int i;
  51304. sqlite_int64 rowid;
  51305. Mem **apArg = p->apArg;
  51306. Mem *pX = &p->aMem[pOp->p3];
  51307. for(i=0; i<nArg; i++){
  51308. storeTypeInfo(pX, 0);
  51309. apArg[i] = pX;
  51310. pX++;
  51311. }
  51312. if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  51313. sqlite3VtabLock(pVtab);
  51314. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  51315. sqlite3DbFree(db, p->zErrMsg);
  51316. p->zErrMsg = pVtab->zErrMsg;
  51317. pVtab->zErrMsg = 0;
  51318. sqlite3VtabUnlock(db, pVtab);
  51319. if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
  51320. if( pOp->p1 && rc==SQLITE_OK ){
  51321. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  51322. db->lastRowid = rowid;
  51323. }
  51324. p->nChange++;
  51325. }
  51326. break;
  51327. }
  51328. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  51329. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  51330. /* Opcode: Pagecount P1 P2 * * *
  51331. **
  51332. ** Write the current number of pages in database P1 to memory cell P2.
  51333. */
  51334. case OP_Pagecount: { /* out2-prerelease */
  51335. int p1 = pOp->p1;
  51336. int nPage;
  51337. Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
  51338. rc = sqlite3PagerPagecount(pPager, &nPage);
  51339. if( rc==SQLITE_OK ){
  51340. pOut->flags = MEM_Int;
  51341. pOut->u.i = nPage;
  51342. }
  51343. break;
  51344. }
  51345. #endif
  51346. #ifndef SQLITE_OMIT_TRACE
  51347. /* Opcode: Trace * * * P4 *
  51348. **
  51349. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  51350. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  51351. */
  51352. case OP_Trace: {
  51353. char *zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  51354. if( zTrace ){
  51355. if( db->xTrace ){
  51356. db->xTrace(db->pTraceArg, zTrace);
  51357. }
  51358. #ifdef SQLITE_DEBUG
  51359. if( (db->flags & SQLITE_SqlTrace)!=0 ){
  51360. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  51361. }
  51362. #endif /* SQLITE_DEBUG */
  51363. }
  51364. break;
  51365. }
  51366. #endif
  51367. /* Opcode: Noop * * * * *
  51368. **
  51369. ** Do nothing. This instruction is often useful as a jump
  51370. ** destination.
  51371. */
  51372. /*
  51373. ** The magic Explain opcode are only inserted when explain==2 (which
  51374. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  51375. ** This opcode records information from the optimizer. It is the
  51376. ** the same as a no-op. This opcodesnever appears in a real VM program.
  51377. */
  51378. default: { /* This is really OP_Noop and OP_Explain */
  51379. break;
  51380. }
  51381. /*****************************************************************************
  51382. ** The cases of the switch statement above this line should all be indented
  51383. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  51384. ** readability. From this point on down, the normal indentation rules are
  51385. ** restored.
  51386. *****************************************************************************/
  51387. }
  51388. #ifdef VDBE_PROFILE
  51389. {
  51390. u64 elapsed = sqlite3Hwtime() - start;
  51391. pOp->cycles += elapsed;
  51392. pOp->cnt++;
  51393. #if 0
  51394. fprintf(stdout, "%10llu ", elapsed);
  51395. sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
  51396. #endif
  51397. }
  51398. #endif
  51399. /* The following code adds nothing to the actual functionality
  51400. ** of the program. It is only here for testing and debugging.
  51401. ** On the other hand, it does burn CPU cycles every time through
  51402. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  51403. */
  51404. #ifndef NDEBUG
  51405. assert( pc>=-1 && pc<p->nOp );
  51406. #ifdef SQLITE_DEBUG
  51407. if( p->trace ){
  51408. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  51409. if( opProperty & OPFLG_OUT2_PRERELEASE ){
  51410. registerTrace(p->trace, pOp->p2, pOut);
  51411. }
  51412. if( opProperty & OPFLG_OUT3 ){
  51413. registerTrace(p->trace, pOp->p3, pOut);
  51414. }
  51415. }
  51416. #endif /* SQLITE_DEBUG */
  51417. #endif /* NDEBUG */
  51418. } /* The end of the for(;;) loop the loops through opcodes */
  51419. /* If we reach this point, it means that execution is finished with
  51420. ** an error of some kind.
  51421. */
  51422. vdbe_error_halt:
  51423. assert( rc );
  51424. p->rc = rc;
  51425. sqlite3VdbeHalt(p);
  51426. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  51427. rc = SQLITE_ERROR;
  51428. /* This is the only way out of this procedure. We have to
  51429. ** release the mutexes on btrees that were acquired at the
  51430. ** top. */
  51431. vdbe_return:
  51432. sqlite3BtreeMutexArrayLeave(&p->aMutex);
  51433. return rc;
  51434. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  51435. ** is encountered.
  51436. */
  51437. too_big:
  51438. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  51439. rc = SQLITE_TOOBIG;
  51440. goto vdbe_error_halt;
  51441. /* Jump to here if a malloc() fails.
  51442. */
  51443. no_mem:
  51444. db->mallocFailed = 1;
  51445. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  51446. rc = SQLITE_NOMEM;
  51447. goto vdbe_error_halt;
  51448. /* Jump to here for an SQLITE_MISUSE error.
  51449. */
  51450. abort_due_to_misuse:
  51451. rc = SQLITE_MISUSE;
  51452. /* Fall thru into abort_due_to_error */
  51453. /* Jump to here for any other kind of fatal error. The "rc" variable
  51454. ** should hold the error number.
  51455. */
  51456. abort_due_to_error:
  51457. assert( p->zErrMsg==0 );
  51458. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  51459. if( rc!=SQLITE_IOERR_NOMEM ){
  51460. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  51461. }
  51462. goto vdbe_error_halt;
  51463. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  51464. ** flag.
  51465. */
  51466. abort_due_to_interrupt:
  51467. assert( db->u1.isInterrupted );
  51468. rc = SQLITE_INTERRUPT;
  51469. p->rc = rc;
  51470. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  51471. goto vdbe_error_halt;
  51472. }
  51473. /************** End of vdbe.c ************************************************/
  51474. /************** Begin file vdbeblob.c ****************************************/
  51475. /*
  51476. ** 2007 May 1
  51477. **
  51478. ** The author disclaims copyright to this source code. In place of
  51479. ** a legal notice, here is a blessing:
  51480. **
  51481. ** May you do good and not evil.
  51482. ** May you find forgiveness for yourself and forgive others.
  51483. ** May you share freely, never taking more than you give.
  51484. **
  51485. *************************************************************************
  51486. **
  51487. ** This file contains code used to implement incremental BLOB I/O.
  51488. **
  51489. ** $Id: vdbeblob.c,v 1.31 2009/03/24 15:08:10 drh Exp $
  51490. */
  51491. #ifndef SQLITE_OMIT_INCRBLOB
  51492. /*
  51493. ** Valid sqlite3_blob* handles point to Incrblob structures.
  51494. */
  51495. typedef struct Incrblob Incrblob;
  51496. struct Incrblob {
  51497. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  51498. int nByte; /* Size of open blob, in bytes */
  51499. int iOffset; /* Byte offset of blob in cursor data */
  51500. BtCursor *pCsr; /* Cursor pointing at blob row */
  51501. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  51502. sqlite3 *db; /* The associated database */
  51503. };
  51504. /*
  51505. ** Open a blob handle.
  51506. */
  51507. SQLITE_API int sqlite3_blob_open(
  51508. sqlite3* db, /* The database connection */
  51509. const char *zDb, /* The attached database containing the blob */
  51510. const char *zTable, /* The table containing the blob */
  51511. const char *zColumn, /* The column containing the blob */
  51512. sqlite_int64 iRow, /* The row containing the glob */
  51513. int flags, /* True -> read/write access, false -> read-only */
  51514. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  51515. ){
  51516. int nAttempt = 0;
  51517. int iCol; /* Index of zColumn in row-record */
  51518. /* This VDBE program seeks a btree cursor to the identified
  51519. ** db/table/row entry. The reason for using a vdbe program instead
  51520. ** of writing code to use the b-tree layer directly is that the
  51521. ** vdbe program will take advantage of the various transaction,
  51522. ** locking and error handling infrastructure built into the vdbe.
  51523. **
  51524. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  51525. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  51526. ** uses it to implement the blob_read(), blob_write() and
  51527. ** blob_bytes() functions.
  51528. **
  51529. ** The sqlite3_blob_close() function finalizes the vdbe program,
  51530. ** which closes the b-tree cursor and (possibly) commits the
  51531. ** transaction.
  51532. */
  51533. static const VdbeOpList openBlob[] = {
  51534. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  51535. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  51536. /* One of the following two instructions is replaced by an
  51537. ** OP_Noop before exection.
  51538. */
  51539. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  51540. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  51541. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  51542. {OP_NotExists, 0, 8, 1}, /* 5: Seek the cursor */
  51543. {OP_Column, 0, 0, 1}, /* 6 */
  51544. {OP_ResultRow, 1, 0, 0}, /* 7 */
  51545. {OP_Close, 0, 0, 0}, /* 8 */
  51546. {OP_Halt, 0, 0, 0}, /* 9 */
  51547. };
  51548. Vdbe *v = 0;
  51549. int rc = SQLITE_OK;
  51550. char zErr[128];
  51551. zErr[0] = 0;
  51552. sqlite3_mutex_enter(db->mutex);
  51553. do {
  51554. Parse sParse;
  51555. Table *pTab;
  51556. memset(&sParse, 0, sizeof(Parse));
  51557. sParse.db = db;
  51558. if( sqlite3SafetyOn(db) ){
  51559. sqlite3_mutex_leave(db->mutex);
  51560. return SQLITE_MISUSE;
  51561. }
  51562. sqlite3BtreeEnterAll(db);
  51563. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  51564. if( pTab && IsVirtual(pTab) ){
  51565. pTab = 0;
  51566. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  51567. }
  51568. #ifndef SQLITE_OMIT_VIEW
  51569. if( pTab && pTab->pSelect ){
  51570. pTab = 0;
  51571. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  51572. }
  51573. #endif
  51574. if( !pTab ){
  51575. if( sParse.zErrMsg ){
  51576. sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
  51577. }
  51578. sqlite3DbFree(db, sParse.zErrMsg);
  51579. rc = SQLITE_ERROR;
  51580. (void)sqlite3SafetyOff(db);
  51581. sqlite3BtreeLeaveAll(db);
  51582. goto blob_open_out;
  51583. }
  51584. /* Now search pTab for the exact column. */
  51585. for(iCol=0; iCol < pTab->nCol; iCol++) {
  51586. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  51587. break;
  51588. }
  51589. }
  51590. if( iCol==pTab->nCol ){
  51591. sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
  51592. rc = SQLITE_ERROR;
  51593. (void)sqlite3SafetyOff(db);
  51594. sqlite3BtreeLeaveAll(db);
  51595. goto blob_open_out;
  51596. }
  51597. /* If the value is being opened for writing, check that the
  51598. ** column is not indexed. It is against the rules to open an
  51599. ** indexed column for writing.
  51600. */
  51601. if( flags ){
  51602. Index *pIdx;
  51603. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  51604. int j;
  51605. for(j=0; j<pIdx->nColumn; j++){
  51606. if( pIdx->aiColumn[j]==iCol ){
  51607. sqlite3_snprintf(sizeof(zErr), zErr,
  51608. "cannot open indexed column for writing");
  51609. rc = SQLITE_ERROR;
  51610. (void)sqlite3SafetyOff(db);
  51611. sqlite3BtreeLeaveAll(db);
  51612. goto blob_open_out;
  51613. }
  51614. }
  51615. }
  51616. }
  51617. v = sqlite3VdbeCreate(db);
  51618. if( v ){
  51619. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  51620. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  51621. /* Configure the OP_Transaction */
  51622. sqlite3VdbeChangeP1(v, 0, iDb);
  51623. sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
  51624. /* Configure the OP_VerifyCookie */
  51625. sqlite3VdbeChangeP1(v, 1, iDb);
  51626. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  51627. /* Make sure a mutex is held on the table to be accessed */
  51628. sqlite3VdbeUsesBtree(v, iDb);
  51629. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  51630. ** parameter of the other to pTab->tnum.
  51631. */
  51632. sqlite3VdbeChangeToNoop(v, (flags ? 2 : 3), 1);
  51633. sqlite3VdbeChangeP2(v, (flags ? 3 : 2), pTab->tnum);
  51634. sqlite3VdbeChangeP3(v, (flags ? 3 : 2), iDb);
  51635. /* Configure the number of columns. Configure the cursor to
  51636. ** think that the table has one more column than it really
  51637. ** does. An OP_Column to retrieve this imaginary column will
  51638. ** always return an SQL NULL. This is useful because it means
  51639. ** we can invoke OP_Column to fill in the vdbe cursors type
  51640. ** and offset cache without causing any IO.
  51641. */
  51642. sqlite3VdbeChangeP4(v, flags ? 3 : 2, SQLITE_INT_TO_PTR(pTab->nCol+1), P4_INT32);
  51643. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  51644. if( !db->mallocFailed ){
  51645. sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
  51646. }
  51647. }
  51648. sqlite3BtreeLeaveAll(db);
  51649. rc = sqlite3SafetyOff(db);
  51650. if( rc!=SQLITE_OK || db->mallocFailed ){
  51651. goto blob_open_out;
  51652. }
  51653. sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
  51654. rc = sqlite3_step((sqlite3_stmt *)v);
  51655. if( rc!=SQLITE_ROW ){
  51656. nAttempt++;
  51657. rc = sqlite3_finalize((sqlite3_stmt *)v);
  51658. sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
  51659. v = 0;
  51660. }
  51661. } while( nAttempt<5 && rc==SQLITE_SCHEMA );
  51662. if( rc==SQLITE_ROW ){
  51663. /* The row-record has been opened successfully. Check that the
  51664. ** column in question contains text or a blob. If it contains
  51665. ** text, it is up to the caller to get the encoding right.
  51666. */
  51667. Incrblob *pBlob;
  51668. u32 type = v->apCsr[0]->aType[iCol];
  51669. if( type<12 ){
  51670. sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
  51671. type==0?"null": type==7?"real": "integer"
  51672. );
  51673. rc = SQLITE_ERROR;
  51674. goto blob_open_out;
  51675. }
  51676. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  51677. if( db->mallocFailed ){
  51678. sqlite3DbFree(db, pBlob);
  51679. goto blob_open_out;
  51680. }
  51681. pBlob->flags = flags;
  51682. pBlob->pCsr = v->apCsr[0]->pCursor;
  51683. sqlite3BtreeEnterCursor(pBlob->pCsr);
  51684. sqlite3BtreeCacheOverflow(pBlob->pCsr);
  51685. sqlite3BtreeLeaveCursor(pBlob->pCsr);
  51686. pBlob->pStmt = (sqlite3_stmt *)v;
  51687. pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
  51688. pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
  51689. pBlob->db = db;
  51690. *ppBlob = (sqlite3_blob *)pBlob;
  51691. rc = SQLITE_OK;
  51692. }else if( rc==SQLITE_OK ){
  51693. sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
  51694. rc = SQLITE_ERROR;
  51695. }
  51696. blob_open_out:
  51697. zErr[sizeof(zErr)-1] = '\0';
  51698. if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
  51699. sqlite3VdbeFinalize(v);
  51700. }
  51701. sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
  51702. rc = sqlite3ApiExit(db, rc);
  51703. sqlite3_mutex_leave(db->mutex);
  51704. return rc;
  51705. }
  51706. /*
  51707. ** Close a blob handle that was previously created using
  51708. ** sqlite3_blob_open().
  51709. */
  51710. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  51711. Incrblob *p = (Incrblob *)pBlob;
  51712. int rc;
  51713. sqlite3 *db;
  51714. db = p->db;
  51715. sqlite3_mutex_enter(db->mutex);
  51716. rc = sqlite3_finalize(p->pStmt);
  51717. sqlite3DbFree(db, p);
  51718. sqlite3_mutex_leave(db->mutex);
  51719. return rc;
  51720. }
  51721. /*
  51722. ** Perform a read or write operation on a blob
  51723. */
  51724. static int blobReadWrite(
  51725. sqlite3_blob *pBlob,
  51726. void *z,
  51727. int n,
  51728. int iOffset,
  51729. int (*xCall)(BtCursor*, u32, u32, void*)
  51730. ){
  51731. int rc;
  51732. Incrblob *p = (Incrblob *)pBlob;
  51733. Vdbe *v;
  51734. sqlite3 *db = p->db;
  51735. sqlite3_mutex_enter(db->mutex);
  51736. v = (Vdbe*)p->pStmt;
  51737. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  51738. /* Request is out of range. Return a transient error. */
  51739. rc = SQLITE_ERROR;
  51740. sqlite3Error(db, SQLITE_ERROR, 0);
  51741. } else if( v==0 ){
  51742. /* If there is no statement handle, then the blob-handle has
  51743. ** already been invalidated. Return SQLITE_ABORT in this case.
  51744. */
  51745. rc = SQLITE_ABORT;
  51746. }else{
  51747. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  51748. ** returned, clean-up the statement handle.
  51749. */
  51750. assert( db == v->db );
  51751. sqlite3BtreeEnterCursor(p->pCsr);
  51752. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  51753. sqlite3BtreeLeaveCursor(p->pCsr);
  51754. if( rc==SQLITE_ABORT ){
  51755. sqlite3VdbeFinalize(v);
  51756. p->pStmt = 0;
  51757. }else{
  51758. db->errCode = rc;
  51759. v->rc = rc;
  51760. }
  51761. }
  51762. rc = sqlite3ApiExit(db, rc);
  51763. sqlite3_mutex_leave(db->mutex);
  51764. return rc;
  51765. }
  51766. /*
  51767. ** Read data from a blob handle.
  51768. */
  51769. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  51770. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  51771. }
  51772. /*
  51773. ** Write data to a blob handle.
  51774. */
  51775. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  51776. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  51777. }
  51778. /*
  51779. ** Query a blob handle for the size of the data.
  51780. **
  51781. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  51782. ** so no mutex is required for access.
  51783. */
  51784. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  51785. Incrblob *p = (Incrblob *)pBlob;
  51786. return p->nByte;
  51787. }
  51788. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  51789. /************** End of vdbeblob.c ********************************************/
  51790. /************** Begin file journal.c *****************************************/
  51791. /*
  51792. ** 2007 August 22
  51793. **
  51794. ** The author disclaims copyright to this source code. In place of
  51795. ** a legal notice, here is a blessing:
  51796. **
  51797. ** May you do good and not evil.
  51798. ** May you find forgiveness for yourself and forgive others.
  51799. ** May you share freely, never taking more than you give.
  51800. **
  51801. *************************************************************************
  51802. **
  51803. ** @(#) $Id: journal.c,v 1.9 2009/01/20 17:06:27 danielk1977 Exp $
  51804. */
  51805. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  51806. /*
  51807. ** This file implements a special kind of sqlite3_file object used
  51808. ** by SQLite to create journal files if the atomic-write optimization
  51809. ** is enabled.
  51810. **
  51811. ** The distinctive characteristic of this sqlite3_file is that the
  51812. ** actual on disk file is created lazily. When the file is created,
  51813. ** the caller specifies a buffer size for an in-memory buffer to
  51814. ** be used to service read() and write() requests. The actual file
  51815. ** on disk is not created or populated until either:
  51816. **
  51817. ** 1) The in-memory representation grows too large for the allocated
  51818. ** buffer, or
  51819. ** 2) The sqlite3JournalCreate() function is called.
  51820. */
  51821. /*
  51822. ** A JournalFile object is a subclass of sqlite3_file used by
  51823. ** as an open file handle for journal files.
  51824. */
  51825. struct JournalFile {
  51826. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  51827. int nBuf; /* Size of zBuf[] in bytes */
  51828. char *zBuf; /* Space to buffer journal writes */
  51829. int iSize; /* Amount of zBuf[] currently used */
  51830. int flags; /* xOpen flags */
  51831. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  51832. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  51833. const char *zJournal; /* Name of the journal file */
  51834. };
  51835. typedef struct JournalFile JournalFile;
  51836. /*
  51837. ** If it does not already exists, create and populate the on-disk file
  51838. ** for JournalFile p.
  51839. */
  51840. static int createFile(JournalFile *p){
  51841. int rc = SQLITE_OK;
  51842. if( !p->pReal ){
  51843. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  51844. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  51845. if( rc==SQLITE_OK ){
  51846. p->pReal = pReal;
  51847. if( p->iSize>0 ){
  51848. assert(p->iSize<=p->nBuf);
  51849. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  51850. }
  51851. }
  51852. }
  51853. return rc;
  51854. }
  51855. /*
  51856. ** Close the file.
  51857. */
  51858. static int jrnlClose(sqlite3_file *pJfd){
  51859. JournalFile *p = (JournalFile *)pJfd;
  51860. if( p->pReal ){
  51861. sqlite3OsClose(p->pReal);
  51862. }
  51863. sqlite3_free(p->zBuf);
  51864. return SQLITE_OK;
  51865. }
  51866. /*
  51867. ** Read data from the file.
  51868. */
  51869. static int jrnlRead(
  51870. sqlite3_file *pJfd, /* The journal file from which to read */
  51871. void *zBuf, /* Put the results here */
  51872. int iAmt, /* Number of bytes to read */
  51873. sqlite_int64 iOfst /* Begin reading at this offset */
  51874. ){
  51875. int rc = SQLITE_OK;
  51876. JournalFile *p = (JournalFile *)pJfd;
  51877. if( p->pReal ){
  51878. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  51879. }else if( (iAmt+iOfst)>p->iSize ){
  51880. rc = SQLITE_IOERR_SHORT_READ;
  51881. }else{
  51882. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  51883. }
  51884. return rc;
  51885. }
  51886. /*
  51887. ** Write data to the file.
  51888. */
  51889. static int jrnlWrite(
  51890. sqlite3_file *pJfd, /* The journal file into which to write */
  51891. const void *zBuf, /* Take data to be written from here */
  51892. int iAmt, /* Number of bytes to write */
  51893. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  51894. ){
  51895. int rc = SQLITE_OK;
  51896. JournalFile *p = (JournalFile *)pJfd;
  51897. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  51898. rc = createFile(p);
  51899. }
  51900. if( rc==SQLITE_OK ){
  51901. if( p->pReal ){
  51902. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  51903. }else{
  51904. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  51905. if( p->iSize<(iOfst+iAmt) ){
  51906. p->iSize = (iOfst+iAmt);
  51907. }
  51908. }
  51909. }
  51910. return rc;
  51911. }
  51912. /*
  51913. ** Truncate the file.
  51914. */
  51915. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  51916. int rc = SQLITE_OK;
  51917. JournalFile *p = (JournalFile *)pJfd;
  51918. if( p->pReal ){
  51919. rc = sqlite3OsTruncate(p->pReal, size);
  51920. }else if( size<p->iSize ){
  51921. p->iSize = size;
  51922. }
  51923. return rc;
  51924. }
  51925. /*
  51926. ** Sync the file.
  51927. */
  51928. static int jrnlSync(sqlite3_file *pJfd, int flags){
  51929. int rc;
  51930. JournalFile *p = (JournalFile *)pJfd;
  51931. if( p->pReal ){
  51932. rc = sqlite3OsSync(p->pReal, flags);
  51933. }else{
  51934. rc = SQLITE_OK;
  51935. }
  51936. return rc;
  51937. }
  51938. /*
  51939. ** Query the size of the file in bytes.
  51940. */
  51941. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  51942. int rc = SQLITE_OK;
  51943. JournalFile *p = (JournalFile *)pJfd;
  51944. if( p->pReal ){
  51945. rc = sqlite3OsFileSize(p->pReal, pSize);
  51946. }else{
  51947. *pSize = (sqlite_int64) p->iSize;
  51948. }
  51949. return rc;
  51950. }
  51951. /*
  51952. ** Table of methods for JournalFile sqlite3_file object.
  51953. */
  51954. static struct sqlite3_io_methods JournalFileMethods = {
  51955. 1, /* iVersion */
  51956. jrnlClose, /* xClose */
  51957. jrnlRead, /* xRead */
  51958. jrnlWrite, /* xWrite */
  51959. jrnlTruncate, /* xTruncate */
  51960. jrnlSync, /* xSync */
  51961. jrnlFileSize, /* xFileSize */
  51962. 0, /* xLock */
  51963. 0, /* xUnlock */
  51964. 0, /* xCheckReservedLock */
  51965. 0, /* xFileControl */
  51966. 0, /* xSectorSize */
  51967. 0 /* xDeviceCharacteristics */
  51968. };
  51969. /*
  51970. ** Open a journal file.
  51971. */
  51972. SQLITE_PRIVATE int sqlite3JournalOpen(
  51973. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  51974. const char *zName, /* Name of the journal file */
  51975. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  51976. int flags, /* Opening flags */
  51977. int nBuf /* Bytes buffered before opening the file */
  51978. ){
  51979. JournalFile *p = (JournalFile *)pJfd;
  51980. memset(p, 0, sqlite3JournalSize(pVfs));
  51981. if( nBuf>0 ){
  51982. p->zBuf = sqlite3MallocZero(nBuf);
  51983. if( !p->zBuf ){
  51984. return SQLITE_NOMEM;
  51985. }
  51986. }else{
  51987. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  51988. }
  51989. p->pMethod = &JournalFileMethods;
  51990. p->nBuf = nBuf;
  51991. p->flags = flags;
  51992. p->zJournal = zName;
  51993. p->pVfs = pVfs;
  51994. return SQLITE_OK;
  51995. }
  51996. /*
  51997. ** If the argument p points to a JournalFile structure, and the underlying
  51998. ** file has not yet been created, create it now.
  51999. */
  52000. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  52001. if( p->pMethods!=&JournalFileMethods ){
  52002. return SQLITE_OK;
  52003. }
  52004. return createFile((JournalFile *)p);
  52005. }
  52006. /*
  52007. ** Return the number of bytes required to store a JournalFile that uses vfs
  52008. ** pVfs to create the underlying on-disk files.
  52009. */
  52010. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  52011. return (pVfs->szOsFile+sizeof(JournalFile));
  52012. }
  52013. #endif
  52014. /************** End of journal.c *********************************************/
  52015. /************** Begin file memjournal.c **************************************/
  52016. /*
  52017. ** 2008 October 7
  52018. **
  52019. ** The author disclaims copyright to this source code. In place of
  52020. ** a legal notice, here is a blessing:
  52021. **
  52022. ** May you do good and not evil.
  52023. ** May you find forgiveness for yourself and forgive others.
  52024. ** May you share freely, never taking more than you give.
  52025. **
  52026. *************************************************************************
  52027. **
  52028. ** This file contains code use to implement an in-memory rollback journal.
  52029. ** The in-memory rollback journal is used to journal transactions for
  52030. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  52031. **
  52032. ** @(#) $Id: memjournal.c,v 1.11 2009/04/05 12:22:09 drh Exp $
  52033. */
  52034. /* Forward references to internal structures */
  52035. typedef struct MemJournal MemJournal;
  52036. typedef struct FilePoint FilePoint;
  52037. typedef struct FileChunk FileChunk;
  52038. /* Space to hold the rollback journal is allocated in increments of
  52039. ** this many bytes.
  52040. **
  52041. ** The size chosen is a little less than a power of two. That way,
  52042. ** the FileChunk object will have a size that almost exactly fills
  52043. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  52044. ** memory allocators.
  52045. */
  52046. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  52047. /* Macro to find the minimum of two numeric values.
  52048. */
  52049. #ifndef MIN
  52050. # define MIN(x,y) ((x)<(y)?(x):(y))
  52051. #endif
  52052. /*
  52053. ** The rollback journal is composed of a linked list of these structures.
  52054. */
  52055. struct FileChunk {
  52056. FileChunk *pNext; /* Next chunk in the journal */
  52057. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  52058. };
  52059. /*
  52060. ** An instance of this object serves as a cursor into the rollback journal.
  52061. ** The cursor can be either for reading or writing.
  52062. */
  52063. struct FilePoint {
  52064. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  52065. FileChunk *pChunk; /* Specific chunk into which cursor points */
  52066. };
  52067. /*
  52068. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  52069. ** is an instance of this class.
  52070. */
  52071. struct MemJournal {
  52072. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  52073. FileChunk *pFirst; /* Head of in-memory chunk-list */
  52074. FilePoint endpoint; /* Pointer to the end of the file */
  52075. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  52076. };
  52077. /*
  52078. ** Read data from the in-memory journal file. This is the implementation
  52079. ** of the sqlite3_vfs.xRead method.
  52080. */
  52081. static int memjrnlRead(
  52082. sqlite3_file *pJfd, /* The journal file from which to read */
  52083. void *zBuf, /* Put the results here */
  52084. int iAmt, /* Number of bytes to read */
  52085. sqlite_int64 iOfst /* Begin reading at this offset */
  52086. ){
  52087. MemJournal *p = (MemJournal *)pJfd;
  52088. u8 *zOut = zBuf;
  52089. int nRead = iAmt;
  52090. int iChunkOffset;
  52091. FileChunk *pChunk;
  52092. /* SQLite never tries to read past the end of a rollback journal file */
  52093. assert( iOfst+iAmt<=p->endpoint.iOffset );
  52094. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  52095. sqlite3_int64 iOff = 0;
  52096. for(pChunk=p->pFirst;
  52097. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  52098. pChunk=pChunk->pNext
  52099. ){
  52100. iOff += JOURNAL_CHUNKSIZE;
  52101. }
  52102. }else{
  52103. pChunk = p->readpoint.pChunk;
  52104. }
  52105. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  52106. do {
  52107. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  52108. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  52109. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  52110. zOut += nCopy;
  52111. nRead -= iSpace;
  52112. iChunkOffset = 0;
  52113. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  52114. p->readpoint.iOffset = iOfst+iAmt;
  52115. p->readpoint.pChunk = pChunk;
  52116. return SQLITE_OK;
  52117. }
  52118. /*
  52119. ** Write data to the file.
  52120. */
  52121. static int memjrnlWrite(
  52122. sqlite3_file *pJfd, /* The journal file into which to write */
  52123. const void *zBuf, /* Take data to be written from here */
  52124. int iAmt, /* Number of bytes to write */
  52125. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  52126. ){
  52127. MemJournal *p = (MemJournal *)pJfd;
  52128. int nWrite = iAmt;
  52129. u8 *zWrite = (u8 *)zBuf;
  52130. /* An in-memory journal file should only ever be appended to. Random
  52131. ** access writes are not required by sqlite.
  52132. */
  52133. assert(iOfst==p->endpoint.iOffset);
  52134. UNUSED_PARAMETER(iOfst);
  52135. while( nWrite>0 ){
  52136. FileChunk *pChunk = p->endpoint.pChunk;
  52137. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  52138. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  52139. if( iChunkOffset==0 ){
  52140. /* New chunk is required to extend the file. */
  52141. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  52142. if( !pNew ){
  52143. return SQLITE_IOERR_NOMEM;
  52144. }
  52145. pNew->pNext = 0;
  52146. if( pChunk ){
  52147. assert( p->pFirst );
  52148. pChunk->pNext = pNew;
  52149. }else{
  52150. assert( !p->pFirst );
  52151. p->pFirst = pNew;
  52152. }
  52153. p->endpoint.pChunk = pNew;
  52154. }
  52155. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  52156. zWrite += iSpace;
  52157. nWrite -= iSpace;
  52158. p->endpoint.iOffset += iSpace;
  52159. }
  52160. return SQLITE_OK;
  52161. }
  52162. /*
  52163. ** Truncate the file.
  52164. */
  52165. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  52166. MemJournal *p = (MemJournal *)pJfd;
  52167. FileChunk *pChunk;
  52168. assert(size==0);
  52169. UNUSED_PARAMETER(size);
  52170. pChunk = p->pFirst;
  52171. while( pChunk ){
  52172. FileChunk *pTmp = pChunk;
  52173. pChunk = pChunk->pNext;
  52174. sqlite3_free(pTmp);
  52175. }
  52176. sqlite3MemJournalOpen(pJfd);
  52177. return SQLITE_OK;
  52178. }
  52179. /*
  52180. ** Close the file.
  52181. */
  52182. static int memjrnlClose(sqlite3_file *pJfd){
  52183. memjrnlTruncate(pJfd, 0);
  52184. return SQLITE_OK;
  52185. }
  52186. /*
  52187. ** Sync the file.
  52188. **
  52189. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  52190. ** is never called in a working implementation. This implementation
  52191. ** exists purely as a contingency, in case some malfunction in some other
  52192. ** part of SQLite causes Sync to be called by mistake.
  52193. */
  52194. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){ /*NO_TEST*/
  52195. UNUSED_PARAMETER2(NotUsed, NotUsed2); /*NO_TEST*/
  52196. assert( 0 ); /*NO_TEST*/
  52197. return SQLITE_OK; /*NO_TEST*/
  52198. } /*NO_TEST*/
  52199. /*
  52200. ** Query the size of the file in bytes.
  52201. */
  52202. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  52203. MemJournal *p = (MemJournal *)pJfd;
  52204. *pSize = (sqlite_int64) p->endpoint.iOffset;
  52205. return SQLITE_OK;
  52206. }
  52207. /*
  52208. ** Table of methods for MemJournal sqlite3_file object.
  52209. */
  52210. static struct sqlite3_io_methods MemJournalMethods = {
  52211. 1, /* iVersion */
  52212. memjrnlClose, /* xClose */
  52213. memjrnlRead, /* xRead */
  52214. memjrnlWrite, /* xWrite */
  52215. memjrnlTruncate, /* xTruncate */
  52216. memjrnlSync, /* xSync */
  52217. memjrnlFileSize, /* xFileSize */
  52218. 0, /* xLock */
  52219. 0, /* xUnlock */
  52220. 0, /* xCheckReservedLock */
  52221. 0, /* xFileControl */
  52222. 0, /* xSectorSize */
  52223. 0 /* xDeviceCharacteristics */
  52224. };
  52225. /*
  52226. ** Open a journal file.
  52227. */
  52228. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  52229. MemJournal *p = (MemJournal *)pJfd;
  52230. assert( EIGHT_BYTE_ALIGNMENT(p) );
  52231. memset(p, 0, sqlite3MemJournalSize());
  52232. p->pMethod = &MemJournalMethods;
  52233. }
  52234. /*
  52235. ** Return true if the file-handle passed as an argument is
  52236. ** an in-memory journal
  52237. */
  52238. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  52239. return pJfd->pMethods==&MemJournalMethods;
  52240. }
  52241. /*
  52242. ** Return the number of bytes required to store a MemJournal that uses vfs
  52243. ** pVfs to create the underlying on-disk files.
  52244. */
  52245. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  52246. return sizeof(MemJournal);
  52247. }
  52248. /************** End of memjournal.c ******************************************/
  52249. /************** Begin file walker.c ******************************************/
  52250. /*
  52251. ** 2008 August 16
  52252. **
  52253. ** The author disclaims copyright to this source code. In place of
  52254. ** a legal notice, here is a blessing:
  52255. **
  52256. ** May you do good and not evil.
  52257. ** May you find forgiveness for yourself and forgive others.
  52258. ** May you share freely, never taking more than you give.
  52259. **
  52260. *************************************************************************
  52261. ** This file contains routines used for walking the parser tree for
  52262. ** an SQL statement.
  52263. **
  52264. ** $Id: walker.c,v 1.4 2009/04/08 13:51:52 drh Exp $
  52265. */
  52266. /*
  52267. ** Walk an expression tree. Invoke the callback once for each node
  52268. ** of the expression, while decending. (In other words, the callback
  52269. ** is invoked before visiting children.)
  52270. **
  52271. ** The return value from the callback should be one of the WRC_*
  52272. ** constants to specify how to proceed with the walk.
  52273. **
  52274. ** WRC_Continue Continue descending down the tree.
  52275. **
  52276. ** WRC_Prune Do not descend into child nodes. But allow
  52277. ** the walk to continue with sibling nodes.
  52278. **
  52279. ** WRC_Abort Do no more callbacks. Unwind the stack and
  52280. ** return the top-level walk call.
  52281. **
  52282. ** The return value from this routine is WRC_Abort to abandon the tree walk
  52283. ** and WRC_Continue to continue.
  52284. */
  52285. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  52286. int rc;
  52287. if( pExpr==0 ) return WRC_Continue;
  52288. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  52289. testcase( ExprHasProperty(pExpr, EP_SpanToken) );
  52290. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  52291. rc = pWalker->xExprCallback(pWalker, pExpr);
  52292. if( rc==WRC_Continue
  52293. && !ExprHasAnyProperty(pExpr,EP_TokenOnly|EP_SpanToken) ){
  52294. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  52295. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  52296. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  52297. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  52298. }else{
  52299. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  52300. }
  52301. }
  52302. return rc & WRC_Abort;
  52303. }
  52304. /*
  52305. ** Call sqlite3WalkExpr() for every expression in list p or until
  52306. ** an abort request is seen.
  52307. */
  52308. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  52309. int i, rc = WRC_Continue;
  52310. struct ExprList_item *pItem;
  52311. if( p ){
  52312. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  52313. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  52314. }
  52315. }
  52316. return rc & WRC_Continue;
  52317. }
  52318. /*
  52319. ** Walk all expressions associated with SELECT statement p. Do
  52320. ** not invoke the SELECT callback on p, but do (of course) invoke
  52321. ** any expr callbacks and SELECT callbacks that come from subqueries.
  52322. ** Return WRC_Abort or WRC_Continue.
  52323. */
  52324. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  52325. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  52326. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  52327. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  52328. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  52329. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  52330. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  52331. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  52332. return WRC_Continue;
  52333. }
  52334. /*
  52335. ** Walk the parse trees associated with all subqueries in the
  52336. ** FROM clause of SELECT statement p. Do not invoke the select
  52337. ** callback on p, but do invoke it on each FROM clause subquery
  52338. ** and on any subqueries further down in the tree. Return
  52339. ** WRC_Abort or WRC_Continue;
  52340. */
  52341. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  52342. SrcList *pSrc;
  52343. int i;
  52344. struct SrcList_item *pItem;
  52345. pSrc = p->pSrc;
  52346. if( pSrc ){
  52347. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  52348. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  52349. return WRC_Abort;
  52350. }
  52351. }
  52352. }
  52353. return WRC_Continue;
  52354. }
  52355. /*
  52356. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  52357. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  52358. ** on the compound select chain, p->pPrior.
  52359. **
  52360. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  52361. ** there is an abort request.
  52362. **
  52363. ** If the Walker does not have an xSelectCallback() then this routine
  52364. ** is a no-op returning WRC_Continue.
  52365. */
  52366. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  52367. int rc;
  52368. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  52369. rc = WRC_Continue;
  52370. while( p ){
  52371. rc = pWalker->xSelectCallback(pWalker, p);
  52372. if( rc ) break;
  52373. if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
  52374. if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
  52375. p = p->pPrior;
  52376. }
  52377. return rc & WRC_Abort;
  52378. }
  52379. /************** End of walker.c **********************************************/
  52380. /************** Begin file resolve.c *****************************************/
  52381. /*
  52382. ** 2008 August 18
  52383. **
  52384. ** The author disclaims copyright to this source code. In place of
  52385. ** a legal notice, here is a blessing:
  52386. **
  52387. ** May you do good and not evil.
  52388. ** May you find forgiveness for yourself and forgive others.
  52389. ** May you share freely, never taking more than you give.
  52390. **
  52391. *************************************************************************
  52392. **
  52393. ** This file contains routines used for walking the parser tree and
  52394. ** resolve all identifiers by associating them with a particular
  52395. ** table and column.
  52396. **
  52397. ** $Id: resolve.c,v 1.20 2009/03/05 04:23:47 shane Exp $
  52398. */
  52399. /*
  52400. ** Turn the pExpr expression into an alias for the iCol-th column of the
  52401. ** result set in pEList.
  52402. **
  52403. ** If the result set column is a simple column reference, then this routine
  52404. ** makes an exact copy. But for any other kind of expression, this
  52405. ** routine make a copy of the result set column as the argument to the
  52406. ** TK_AS operator. The TK_AS operator causes the expression to be
  52407. ** evaluated just once and then reused for each alias.
  52408. **
  52409. ** The reason for suppressing the TK_AS term when the expression is a simple
  52410. ** column reference is so that the column reference will be recognized as
  52411. ** usable by indices within the WHERE clause processing logic.
  52412. **
  52413. ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
  52414. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  52415. **
  52416. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  52417. **
  52418. ** Is equivalent to:
  52419. **
  52420. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  52421. **
  52422. ** The result of random()%5 in the GROUP BY clause is probably different
  52423. ** from the result in the result-set. We might fix this someday. Or
  52424. ** then again, we might not...
  52425. */
  52426. static void resolveAlias(
  52427. Parse *pParse, /* Parsing context */
  52428. ExprList *pEList, /* A result set */
  52429. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  52430. Expr *pExpr, /* Transform this into an alias to the result set */
  52431. const char *zType /* "GROUP" or "ORDER" or "" */
  52432. ){
  52433. Expr *pOrig; /* The iCol-th column of the result set */
  52434. Expr *pDup; /* Copy of pOrig */
  52435. sqlite3 *db; /* The database connection */
  52436. assert( iCol>=0 && iCol<pEList->nExpr );
  52437. pOrig = pEList->a[iCol].pExpr;
  52438. assert( pOrig!=0 );
  52439. assert( pOrig->flags & EP_Resolved );
  52440. db = pParse->db;
  52441. pDup = sqlite3ExprDup(db, pOrig, 0);
  52442. if( pDup==0 ) return;
  52443. sqlite3TokenCopy(db, &pDup->token, &pOrig->token);
  52444. if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
  52445. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  52446. if( pDup==0 ) return;
  52447. if( pEList->a[iCol].iAlias==0 ){
  52448. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  52449. }
  52450. pDup->iTable = pEList->a[iCol].iAlias;
  52451. }
  52452. if( pExpr->flags & EP_ExpCollate ){
  52453. pDup->pColl = pExpr->pColl;
  52454. pDup->flags |= EP_ExpCollate;
  52455. }
  52456. sqlite3ExprClear(db, pExpr);
  52457. memcpy(pExpr, pDup, sizeof(*pExpr));
  52458. sqlite3DbFree(db, pDup);
  52459. }
  52460. /*
  52461. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  52462. ** that name in the set of source tables in pSrcList and make the pExpr
  52463. ** expression node refer back to that source column. The following changes
  52464. ** are made to pExpr:
  52465. **
  52466. ** pExpr->iDb Set the index in db->aDb[] of the database X
  52467. ** (even if X is implied).
  52468. ** pExpr->iTable Set to the cursor number for the table obtained
  52469. ** from pSrcList.
  52470. ** pExpr->pTab Points to the Table structure of X.Y (even if
  52471. ** X and/or Y are implied.)
  52472. ** pExpr->iColumn Set to the column number within the table.
  52473. ** pExpr->op Set to TK_COLUMN.
  52474. ** pExpr->pLeft Any expression this points to is deleted
  52475. ** pExpr->pRight Any expression this points to is deleted.
  52476. **
  52477. ** The pDbToken is the name of the database (the "X"). This value may be
  52478. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  52479. ** can be used. The pTableToken is the name of the table (the "Y"). This
  52480. ** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
  52481. ** means that the form of the name is Z and that columns from any table
  52482. ** can be used.
  52483. **
  52484. ** If the name cannot be resolved unambiguously, leave an error message
  52485. ** in pParse and return non-zero. Return zero on success.
  52486. */
  52487. static int lookupName(
  52488. Parse *pParse, /* The parsing context */
  52489. Token *pDbToken, /* Name of the database containing table, or NULL */
  52490. Token *pTableToken, /* Name of table containing column, or NULL */
  52491. Token *pColumnToken, /* Name of the column. */
  52492. NameContext *pNC, /* The name context used to resolve the name */
  52493. Expr *pExpr /* Make this EXPR node point to the selected column */
  52494. ){
  52495. char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
  52496. char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
  52497. char *zCol = 0; /* Name of the column. The "Z" */
  52498. int i, j; /* Loop counters */
  52499. int cnt = 0; /* Number of matching column names */
  52500. int cntTab = 0; /* Number of matching table names */
  52501. sqlite3 *db = pParse->db; /* The database connection */
  52502. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  52503. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  52504. NameContext *pTopNC = pNC; /* First namecontext in the list */
  52505. Schema *pSchema = 0; /* Schema of the expression */
  52506. assert( pNC ); /* the name context cannot be NULL. */
  52507. assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
  52508. /* Dequote and zero-terminate the names */
  52509. zDb = sqlite3NameFromToken(db, pDbToken);
  52510. zTab = sqlite3NameFromToken(db, pTableToken);
  52511. zCol = sqlite3NameFromToken(db, pColumnToken);
  52512. if( db->mallocFailed ){
  52513. goto lookupname_end;
  52514. }
  52515. /* Initialize the node to no-match */
  52516. pExpr->iTable = -1;
  52517. pExpr->pTab = 0;
  52518. /* Start at the inner-most context and move outward until a match is found */
  52519. while( pNC && cnt==0 ){
  52520. ExprList *pEList;
  52521. SrcList *pSrcList = pNC->pSrcList;
  52522. if( pSrcList ){
  52523. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  52524. Table *pTab;
  52525. int iDb;
  52526. Column *pCol;
  52527. pTab = pItem->pTab;
  52528. assert( pTab!=0 && pTab->zName!=0 );
  52529. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  52530. assert( pTab->nCol>0 );
  52531. if( zTab ){
  52532. if( pItem->zAlias ){
  52533. char *zTabName = pItem->zAlias;
  52534. if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
  52535. }else{
  52536. char *zTabName = pTab->zName;
  52537. if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
  52538. if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
  52539. continue;
  52540. }
  52541. }
  52542. }
  52543. if( 0==(cntTab++) ){
  52544. pExpr->iTable = pItem->iCursor;
  52545. pExpr->pTab = pTab;
  52546. pSchema = pTab->pSchema;
  52547. pMatch = pItem;
  52548. }
  52549. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  52550. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  52551. IdList *pUsing;
  52552. cnt++;
  52553. pExpr->iTable = pItem->iCursor;
  52554. pExpr->pTab = pTab;
  52555. pMatch = pItem;
  52556. pSchema = pTab->pSchema;
  52557. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  52558. pExpr->iColumn = j==pTab->iPKey ? -1 : j;
  52559. if( i<pSrcList->nSrc-1 ){
  52560. if( pItem[1].jointype & JT_NATURAL ){
  52561. /* If this match occurred in the left table of a natural join,
  52562. ** then skip the right table to avoid a duplicate match */
  52563. pItem++;
  52564. i++;
  52565. }else if( (pUsing = pItem[1].pUsing)!=0 ){
  52566. /* If this match occurs on a column that is in the USING clause
  52567. ** of a join, skip the search of the right table of the join
  52568. ** to avoid a duplicate match there. */
  52569. int k;
  52570. for(k=0; k<pUsing->nId; k++){
  52571. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
  52572. pItem++;
  52573. i++;
  52574. break;
  52575. }
  52576. }
  52577. }
  52578. }
  52579. break;
  52580. }
  52581. }
  52582. }
  52583. }
  52584. #ifndef SQLITE_OMIT_TRIGGER
  52585. /* If we have not already resolved the name, then maybe
  52586. ** it is a new.* or old.* trigger argument reference
  52587. */
  52588. if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
  52589. TriggerStack *pTriggerStack = pParse->trigStack;
  52590. Table *pTab = 0;
  52591. u32 *piColMask = 0;
  52592. if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
  52593. pExpr->iTable = pTriggerStack->newIdx;
  52594. assert( pTriggerStack->pTab );
  52595. pTab = pTriggerStack->pTab;
  52596. piColMask = &(pTriggerStack->newColMask);
  52597. }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
  52598. pExpr->iTable = pTriggerStack->oldIdx;
  52599. assert( pTriggerStack->pTab );
  52600. pTab = pTriggerStack->pTab;
  52601. piColMask = &(pTriggerStack->oldColMask);
  52602. }
  52603. if( pTab ){
  52604. int iCol;
  52605. Column *pCol = pTab->aCol;
  52606. pSchema = pTab->pSchema;
  52607. cntTab++;
  52608. for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
  52609. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  52610. cnt++;
  52611. pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
  52612. pExpr->pTab = pTab;
  52613. if( iCol>=0 ){
  52614. testcase( iCol==31 );
  52615. testcase( iCol==32 );
  52616. *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
  52617. }
  52618. break;
  52619. }
  52620. }
  52621. }
  52622. }
  52623. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  52624. /*
  52625. ** Perhaps the name is a reference to the ROWID
  52626. */
  52627. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  52628. cnt = 1;
  52629. pExpr->iColumn = -1;
  52630. pExpr->affinity = SQLITE_AFF_INTEGER;
  52631. }
  52632. /*
  52633. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  52634. ** might refer to an result-set alias. This happens, for example, when
  52635. ** we are resolving names in the WHERE clause of the following command:
  52636. **
  52637. ** SELECT a+b AS x FROM table WHERE x<10;
  52638. **
  52639. ** In cases like this, replace pExpr with a copy of the expression that
  52640. ** forms the result set entry ("a+b" in the example) and return immediately.
  52641. ** Note that the expression in the result set should have already been
  52642. ** resolved by the time the WHERE clause is resolved.
  52643. */
  52644. if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
  52645. for(j=0; j<pEList->nExpr; j++){
  52646. char *zAs = pEList->a[j].zName;
  52647. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  52648. Expr *pOrig;
  52649. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  52650. assert( pExpr->x.pList==0 );
  52651. assert( pExpr->x.pSelect==0 );
  52652. pOrig = pEList->a[j].pExpr;
  52653. if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
  52654. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  52655. sqlite3DbFree(db, zCol);
  52656. return 2;
  52657. }
  52658. resolveAlias(pParse, pEList, j, pExpr, "");
  52659. cnt = 1;
  52660. pMatch = 0;
  52661. assert( zTab==0 && zDb==0 );
  52662. goto lookupname_end_2;
  52663. }
  52664. }
  52665. }
  52666. /* Advance to the next name context. The loop will exit when either
  52667. ** we have a match (cnt>0) or when we run out of name contexts.
  52668. */
  52669. if( cnt==0 ){
  52670. pNC = pNC->pNext;
  52671. }
  52672. }
  52673. /*
  52674. ** If X and Y are NULL (in other words if only the column name Z is
  52675. ** supplied) and the value of Z is enclosed in double-quotes, then
  52676. ** Z is a string literal if it doesn't match any column names. In that
  52677. ** case, we need to return right away and not make any changes to
  52678. ** pExpr.
  52679. **
  52680. ** Because no reference was made to outer contexts, the pNC->nRef
  52681. ** fields are not changed in any context.
  52682. */
  52683. if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
  52684. sqlite3DbFree(db, zCol);
  52685. pExpr->op = TK_STRING;
  52686. pExpr->pTab = 0;
  52687. return 0;
  52688. }
  52689. /*
  52690. ** cnt==0 means there was not match. cnt>1 means there were two or
  52691. ** more matches. Either way, we have an error.
  52692. */
  52693. if( cnt!=1 ){
  52694. const char *zErr;
  52695. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  52696. if( zDb ){
  52697. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  52698. }else if( zTab ){
  52699. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  52700. }else{
  52701. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  52702. }
  52703. pTopNC->nErr++;
  52704. }
  52705. /* If a column from a table in pSrcList is referenced, then record
  52706. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  52707. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  52708. ** column number is greater than the number of bits in the bitmask
  52709. ** then set the high-order bit of the bitmask.
  52710. */
  52711. if( pExpr->iColumn>=0 && pMatch!=0 ){
  52712. int n = pExpr->iColumn;
  52713. testcase( n==BMS-1 );
  52714. if( n>=BMS ){
  52715. n = BMS-1;
  52716. }
  52717. assert( pMatch->iCursor==pExpr->iTable );
  52718. pMatch->colUsed |= ((Bitmask)1)<<n;
  52719. }
  52720. lookupname_end:
  52721. /* Clean up and return
  52722. */
  52723. sqlite3DbFree(db, zDb);
  52724. sqlite3DbFree(db, zTab);
  52725. sqlite3ExprDelete(db, pExpr->pLeft);
  52726. pExpr->pLeft = 0;
  52727. sqlite3ExprDelete(db, pExpr->pRight);
  52728. pExpr->pRight = 0;
  52729. pExpr->op = TK_COLUMN;
  52730. lookupname_end_2:
  52731. sqlite3DbFree(db, zCol);
  52732. if( cnt==1 ){
  52733. assert( pNC!=0 );
  52734. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  52735. /* Increment the nRef value on all name contexts from TopNC up to
  52736. ** the point where the name matched. */
  52737. for(;;){
  52738. assert( pTopNC!=0 );
  52739. pTopNC->nRef++;
  52740. if( pTopNC==pNC ) break;
  52741. pTopNC = pTopNC->pNext;
  52742. }
  52743. return 0;
  52744. } else {
  52745. return 1;
  52746. }
  52747. }
  52748. /*
  52749. ** This routine is callback for sqlite3WalkExpr().
  52750. **
  52751. ** Resolve symbolic names into TK_COLUMN operators for the current
  52752. ** node in the expression tree. Return 0 to continue the search down
  52753. ** the tree or 2 to abort the tree walk.
  52754. **
  52755. ** This routine also does error checking and name resolution for
  52756. ** function names. The operator for aggregate functions is changed
  52757. ** to TK_AGG_FUNCTION.
  52758. */
  52759. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  52760. NameContext *pNC;
  52761. Parse *pParse;
  52762. pNC = pWalker->u.pNC;
  52763. assert( pNC!=0 );
  52764. pParse = pNC->pParse;
  52765. assert( pParse==pWalker->pParse );
  52766. if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  52767. ExprSetProperty(pExpr, EP_Resolved);
  52768. #ifndef NDEBUG
  52769. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  52770. SrcList *pSrcList = pNC->pSrcList;
  52771. int i;
  52772. for(i=0; i<pNC->pSrcList->nSrc; i++){
  52773. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  52774. }
  52775. }
  52776. #endif
  52777. switch( pExpr->op ){
  52778. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  52779. /* The special operator TK_ROW means use the rowid for the first
  52780. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  52781. ** clause processing on UPDATE and DELETE statements.
  52782. */
  52783. case TK_ROW: {
  52784. SrcList *pSrcList = pNC->pSrcList;
  52785. struct SrcList_item *pItem;
  52786. assert( pSrcList && pSrcList->nSrc==1 );
  52787. pItem = pSrcList->a;
  52788. pExpr->op = TK_COLUMN;
  52789. pExpr->pTab = pItem->pTab;
  52790. pExpr->iTable = pItem->iCursor;
  52791. pExpr->iColumn = -1;
  52792. pExpr->affinity = SQLITE_AFF_INTEGER;
  52793. break;
  52794. }
  52795. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  52796. /* A lone identifier is the name of a column.
  52797. */
  52798. case TK_ID: {
  52799. lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
  52800. return WRC_Prune;
  52801. }
  52802. /* A table name and column name: ID.ID
  52803. ** Or a database, table and column: ID.ID.ID
  52804. */
  52805. case TK_DOT: {
  52806. Token *pColumn;
  52807. Token *pTable;
  52808. Token *pDb;
  52809. Expr *pRight;
  52810. /* if( pSrcList==0 ) break; */
  52811. pRight = pExpr->pRight;
  52812. if( pRight->op==TK_ID ){
  52813. pDb = 0;
  52814. pTable = &pExpr->pLeft->token;
  52815. pColumn = &pRight->token;
  52816. }else{
  52817. assert( pRight->op==TK_DOT );
  52818. pDb = &pExpr->pLeft->token;
  52819. pTable = &pRight->pLeft->token;
  52820. pColumn = &pRight->pRight->token;
  52821. }
  52822. lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
  52823. return WRC_Prune;
  52824. }
  52825. /* Resolve function names
  52826. */
  52827. case TK_CONST_FUNC:
  52828. case TK_FUNCTION: {
  52829. ExprList *pList = pExpr->x.pList; /* The argument list */
  52830. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  52831. int no_such_func = 0; /* True if no such function exists */
  52832. int wrong_num_args = 0; /* True if wrong number of arguments */
  52833. int is_agg = 0; /* True if is an aggregate function */
  52834. int auth; /* Authorization to use the function */
  52835. int nId; /* Number of characters in function name */
  52836. const char *zId; /* The function name. */
  52837. FuncDef *pDef; /* Information about the function */
  52838. u8 enc = ENC(pParse->db); /* The database encoding */
  52839. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  52840. zId = (char*)pExpr->token.z;
  52841. nId = pExpr->token.n;
  52842. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  52843. if( pDef==0 ){
  52844. pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
  52845. if( pDef==0 ){
  52846. no_such_func = 1;
  52847. }else{
  52848. wrong_num_args = 1;
  52849. }
  52850. }else{
  52851. is_agg = pDef->xFunc==0;
  52852. }
  52853. #ifndef SQLITE_OMIT_AUTHORIZATION
  52854. if( pDef ){
  52855. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  52856. if( auth!=SQLITE_OK ){
  52857. if( auth==SQLITE_DENY ){
  52858. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  52859. pDef->zName);
  52860. pNC->nErr++;
  52861. }
  52862. pExpr->op = TK_NULL;
  52863. return WRC_Prune;
  52864. }
  52865. }
  52866. #endif
  52867. if( is_agg && !pNC->allowAgg ){
  52868. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  52869. pNC->nErr++;
  52870. is_agg = 0;
  52871. }else if( no_such_func ){
  52872. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  52873. pNC->nErr++;
  52874. }else if( wrong_num_args ){
  52875. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  52876. nId, zId);
  52877. pNC->nErr++;
  52878. }
  52879. if( is_agg ){
  52880. pExpr->op = TK_AGG_FUNCTION;
  52881. pNC->hasAgg = 1;
  52882. }
  52883. if( is_agg ) pNC->allowAgg = 0;
  52884. sqlite3WalkExprList(pWalker, pList);
  52885. if( is_agg ) pNC->allowAgg = 1;
  52886. /* FIX ME: Compute pExpr->affinity based on the expected return
  52887. ** type of the function
  52888. */
  52889. return WRC_Prune;
  52890. }
  52891. #ifndef SQLITE_OMIT_SUBQUERY
  52892. case TK_SELECT:
  52893. case TK_EXISTS:
  52894. #endif
  52895. case TK_IN: {
  52896. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  52897. int nRef = pNC->nRef;
  52898. #ifndef SQLITE_OMIT_CHECK
  52899. if( pNC->isCheck ){
  52900. sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
  52901. }
  52902. #endif
  52903. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  52904. assert( pNC->nRef>=nRef );
  52905. if( nRef!=pNC->nRef ){
  52906. ExprSetProperty(pExpr, EP_VarSelect);
  52907. }
  52908. }
  52909. break;
  52910. }
  52911. #ifndef SQLITE_OMIT_CHECK
  52912. case TK_VARIABLE: {
  52913. if( pNC->isCheck ){
  52914. sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
  52915. }
  52916. break;
  52917. }
  52918. #endif
  52919. }
  52920. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  52921. }
  52922. /*
  52923. ** pEList is a list of expressions which are really the result set of the
  52924. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  52925. ** This routine checks to see if pE is a simple identifier which corresponds
  52926. ** to the AS-name of one of the terms of the expression list. If it is,
  52927. ** this routine return an integer between 1 and N where N is the number of
  52928. ** elements in pEList, corresponding to the matching entry. If there is
  52929. ** no match, or if pE is not a simple identifier, then this routine
  52930. ** return 0.
  52931. **
  52932. ** pEList has been resolved. pE has not.
  52933. */
  52934. static int resolveAsName(
  52935. Parse *pParse, /* Parsing context for error messages */
  52936. ExprList *pEList, /* List of expressions to scan */
  52937. Expr *pE /* Expression we are trying to match */
  52938. ){
  52939. int i; /* Loop counter */
  52940. if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
  52941. sqlite3 *db = pParse->db;
  52942. char *zCol = sqlite3NameFromToken(db, &pE->token);
  52943. if( zCol==0 ){
  52944. return -1;
  52945. }
  52946. for(i=0; i<pEList->nExpr; i++){
  52947. char *zAs = pEList->a[i].zName;
  52948. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  52949. sqlite3DbFree(db, zCol);
  52950. return i+1;
  52951. }
  52952. }
  52953. sqlite3DbFree(db, zCol);
  52954. }
  52955. return 0;
  52956. }
  52957. /*
  52958. ** pE is a pointer to an expression which is a single term in the
  52959. ** ORDER BY of a compound SELECT. The expression has not been
  52960. ** name resolved.
  52961. **
  52962. ** At the point this routine is called, we already know that the
  52963. ** ORDER BY term is not an integer index into the result set. That
  52964. ** case is handled by the calling routine.
  52965. **
  52966. ** Attempt to match pE against result set columns in the left-most
  52967. ** SELECT statement. Return the index i of the matching column,
  52968. ** as an indication to the caller that it should sort by the i-th column.
  52969. ** The left-most column is 1. In other words, the value returned is the
  52970. ** same integer value that would be used in the SQL statement to indicate
  52971. ** the column.
  52972. **
  52973. ** If there is no match, return 0. Return -1 if an error occurs.
  52974. */
  52975. static int resolveOrderByTermToExprList(
  52976. Parse *pParse, /* Parsing context for error messages */
  52977. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  52978. Expr *pE /* The specific ORDER BY term */
  52979. ){
  52980. int i; /* Loop counter */
  52981. ExprList *pEList; /* The columns of the result set */
  52982. NameContext nc; /* Name context for resolving pE */
  52983. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  52984. pEList = pSelect->pEList;
  52985. /* Resolve all names in the ORDER BY term expression
  52986. */
  52987. memset(&nc, 0, sizeof(nc));
  52988. nc.pParse = pParse;
  52989. nc.pSrcList = pSelect->pSrc;
  52990. nc.pEList = pEList;
  52991. nc.allowAgg = 1;
  52992. nc.nErr = 0;
  52993. if( sqlite3ResolveExprNames(&nc, pE) ){
  52994. sqlite3ErrorClear(pParse);
  52995. return 0;
  52996. }
  52997. /* Try to match the ORDER BY expression against an expression
  52998. ** in the result set. Return an 1-based index of the matching
  52999. ** result-set entry.
  53000. */
  53001. for(i=0; i<pEList->nExpr; i++){
  53002. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
  53003. return i+1;
  53004. }
  53005. }
  53006. /* If no match, return 0. */
  53007. return 0;
  53008. }
  53009. /*
  53010. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  53011. */
  53012. static void resolveOutOfRangeError(
  53013. Parse *pParse, /* The error context into which to write the error */
  53014. const char *zType, /* "ORDER" or "GROUP" */
  53015. int i, /* The index (1-based) of the term out of range */
  53016. int mx /* Largest permissible value of i */
  53017. ){
  53018. sqlite3ErrorMsg(pParse,
  53019. "%r %s BY term out of range - should be "
  53020. "between 1 and %d", i, zType, mx);
  53021. }
  53022. /*
  53023. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  53024. ** each term of the ORDER BY clause is a constant integer between 1
  53025. ** and N where N is the number of columns in the compound SELECT.
  53026. **
  53027. ** ORDER BY terms that are already an integer between 1 and N are
  53028. ** unmodified. ORDER BY terms that are integers outside the range of
  53029. ** 1 through N generate an error. ORDER BY terms that are expressions
  53030. ** are matched against result set expressions of compound SELECT
  53031. ** beginning with the left-most SELECT and working toward the right.
  53032. ** At the first match, the ORDER BY expression is transformed into
  53033. ** the integer column number.
  53034. **
  53035. ** Return the number of errors seen.
  53036. */
  53037. static int resolveCompoundOrderBy(
  53038. Parse *pParse, /* Parsing context. Leave error messages here */
  53039. Select *pSelect /* The SELECT statement containing the ORDER BY */
  53040. ){
  53041. int i;
  53042. ExprList *pOrderBy;
  53043. ExprList *pEList;
  53044. sqlite3 *db;
  53045. int moreToDo = 1;
  53046. pOrderBy = pSelect->pOrderBy;
  53047. if( pOrderBy==0 ) return 0;
  53048. db = pParse->db;
  53049. #if SQLITE_MAX_COLUMN
  53050. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  53051. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  53052. return 1;
  53053. }
  53054. #endif
  53055. for(i=0; i<pOrderBy->nExpr; i++){
  53056. pOrderBy->a[i].done = 0;
  53057. }
  53058. pSelect->pNext = 0;
  53059. while( pSelect->pPrior ){
  53060. pSelect->pPrior->pNext = pSelect;
  53061. pSelect = pSelect->pPrior;
  53062. }
  53063. while( pSelect && moreToDo ){
  53064. struct ExprList_item *pItem;
  53065. moreToDo = 0;
  53066. pEList = pSelect->pEList;
  53067. assert( pEList!=0 );
  53068. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  53069. int iCol = -1;
  53070. Expr *pE, *pDup;
  53071. if( pItem->done ) continue;
  53072. pE = pItem->pExpr;
  53073. if( sqlite3ExprIsInteger(pE, &iCol) ){
  53074. if( iCol<0 || iCol>pEList->nExpr ){
  53075. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  53076. return 1;
  53077. }
  53078. }else{
  53079. iCol = resolveAsName(pParse, pEList, pE);
  53080. if( iCol==0 ){
  53081. pDup = sqlite3ExprDup(db, pE, 0);
  53082. if( !db->mallocFailed ){
  53083. assert(pDup);
  53084. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  53085. }
  53086. sqlite3ExprDelete(db, pDup);
  53087. }
  53088. if( iCol<0 ){
  53089. return 1;
  53090. }
  53091. }
  53092. if( iCol>0 ){
  53093. CollSeq *pColl = pE->pColl;
  53094. int flags = pE->flags & EP_ExpCollate;
  53095. sqlite3ExprDelete(db, pE);
  53096. pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
  53097. if( pE==0 ) return 1;
  53098. pE->pColl = pColl;
  53099. pE->flags |= EP_IntValue | flags;
  53100. pE->iTable = iCol;
  53101. pItem->iCol = (u16)iCol;
  53102. pItem->done = 1;
  53103. }else{
  53104. moreToDo = 1;
  53105. }
  53106. }
  53107. pSelect = pSelect->pNext;
  53108. }
  53109. for(i=0; i<pOrderBy->nExpr; i++){
  53110. if( pOrderBy->a[i].done==0 ){
  53111. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  53112. "column in the result set", i+1);
  53113. return 1;
  53114. }
  53115. }
  53116. return 0;
  53117. }
  53118. /*
  53119. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  53120. ** the SELECT statement pSelect. If any term is reference to a
  53121. ** result set expression (as determined by the ExprList.a.iCol field)
  53122. ** then convert that term into a copy of the corresponding result set
  53123. ** column.
  53124. **
  53125. ** If any errors are detected, add an error message to pParse and
  53126. ** return non-zero. Return zero if no errors are seen.
  53127. */
  53128. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  53129. Parse *pParse, /* Parsing context. Leave error messages here */
  53130. Select *pSelect, /* The SELECT statement containing the clause */
  53131. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  53132. const char *zType /* "ORDER" or "GROUP" */
  53133. ){
  53134. int i;
  53135. sqlite3 *db = pParse->db;
  53136. ExprList *pEList;
  53137. struct ExprList_item *pItem;
  53138. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  53139. #if SQLITE_MAX_COLUMN
  53140. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  53141. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  53142. return 1;
  53143. }
  53144. #endif
  53145. pEList = pSelect->pEList;
  53146. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  53147. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  53148. if( pItem->iCol ){
  53149. if( pItem->iCol>pEList->nExpr ){
  53150. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  53151. return 1;
  53152. }
  53153. resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
  53154. }
  53155. }
  53156. return 0;
  53157. }
  53158. /*
  53159. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  53160. ** The Name context of the SELECT statement is pNC. zType is either
  53161. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  53162. **
  53163. ** This routine resolves each term of the clause into an expression.
  53164. ** If the order-by term is an integer I between 1 and N (where N is the
  53165. ** number of columns in the result set of the SELECT) then the expression
  53166. ** in the resolution is a copy of the I-th result-set expression. If
  53167. ** the order-by term is an identify that corresponds to the AS-name of
  53168. ** a result-set expression, then the term resolves to a copy of the
  53169. ** result-set expression. Otherwise, the expression is resolved in
  53170. ** the usual way - using sqlite3ResolveExprNames().
  53171. **
  53172. ** This routine returns the number of errors. If errors occur, then
  53173. ** an appropriate error message might be left in pParse. (OOM errors
  53174. ** excepted.)
  53175. */
  53176. static int resolveOrderGroupBy(
  53177. NameContext *pNC, /* The name context of the SELECT statement */
  53178. Select *pSelect, /* The SELECT statement holding pOrderBy */
  53179. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  53180. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  53181. ){
  53182. int i; /* Loop counter */
  53183. int iCol; /* Column number */
  53184. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  53185. Parse *pParse; /* Parsing context */
  53186. int nResult; /* Number of terms in the result set */
  53187. if( pOrderBy==0 ) return 0;
  53188. nResult = pSelect->pEList->nExpr;
  53189. pParse = pNC->pParse;
  53190. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  53191. Expr *pE = pItem->pExpr;
  53192. iCol = resolveAsName(pParse, pSelect->pEList, pE);
  53193. if( iCol<0 ){
  53194. return 1; /* OOM error */
  53195. }
  53196. if( iCol>0 ){
  53197. /* If an AS-name match is found, mark this ORDER BY column as being
  53198. ** a copy of the iCol-th result-set column. The subsequent call to
  53199. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  53200. ** copy of the iCol-th result-set expression. */
  53201. pItem->iCol = (u16)iCol;
  53202. continue;
  53203. }
  53204. if( sqlite3ExprIsInteger(pE, &iCol) ){
  53205. /* The ORDER BY term is an integer constant. Again, set the column
  53206. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  53207. ** order-by term to a copy of the result-set expression */
  53208. if( iCol<1 ){
  53209. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  53210. return 1;
  53211. }
  53212. pItem->iCol = (u16)iCol;
  53213. continue;
  53214. }
  53215. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  53216. pItem->iCol = 0;
  53217. if( sqlite3ResolveExprNames(pNC, pE) ){
  53218. return 1;
  53219. }
  53220. }
  53221. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  53222. }
  53223. /*
  53224. ** Resolve names in the SELECT statement p and all of its descendents.
  53225. */
  53226. static int resolveSelectStep(Walker *pWalker, Select *p){
  53227. NameContext *pOuterNC; /* Context that contains this SELECT */
  53228. NameContext sNC; /* Name context of this SELECT */
  53229. int isCompound; /* True if p is a compound select */
  53230. int nCompound; /* Number of compound terms processed so far */
  53231. Parse *pParse; /* Parsing context */
  53232. ExprList *pEList; /* Result set expression list */
  53233. int i; /* Loop counter */
  53234. ExprList *pGroupBy; /* The GROUP BY clause */
  53235. Select *pLeftmost; /* Left-most of SELECT of a compound */
  53236. sqlite3 *db; /* Database connection */
  53237. assert( p!=0 );
  53238. if( p->selFlags & SF_Resolved ){
  53239. return WRC_Prune;
  53240. }
  53241. pOuterNC = pWalker->u.pNC;
  53242. pParse = pWalker->pParse;
  53243. db = pParse->db;
  53244. /* Normally sqlite3SelectExpand() will be called first and will have
  53245. ** already expanded this SELECT. However, if this is a subquery within
  53246. ** an expression, sqlite3ResolveExprNames() will be called without a
  53247. ** prior call to sqlite3SelectExpand(). When that happens, let
  53248. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  53249. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  53250. ** this routine in the correct order.
  53251. */
  53252. if( (p->selFlags & SF_Expanded)==0 ){
  53253. sqlite3SelectPrep(pParse, p, pOuterNC);
  53254. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  53255. }
  53256. isCompound = p->pPrior!=0;
  53257. nCompound = 0;
  53258. pLeftmost = p;
  53259. while( p ){
  53260. assert( (p->selFlags & SF_Expanded)!=0 );
  53261. assert( (p->selFlags & SF_Resolved)==0 );
  53262. p->selFlags |= SF_Resolved;
  53263. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  53264. ** are not allowed to refer to any names, so pass an empty NameContext.
  53265. */
  53266. memset(&sNC, 0, sizeof(sNC));
  53267. sNC.pParse = pParse;
  53268. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  53269. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  53270. return WRC_Abort;
  53271. }
  53272. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  53273. ** resolve the result-set expression list.
  53274. */
  53275. sNC.allowAgg = 1;
  53276. sNC.pSrcList = p->pSrc;
  53277. sNC.pNext = pOuterNC;
  53278. /* Resolve names in the result set. */
  53279. pEList = p->pEList;
  53280. assert( pEList!=0 );
  53281. for(i=0; i<pEList->nExpr; i++){
  53282. Expr *pX = pEList->a[i].pExpr;
  53283. if( sqlite3ResolveExprNames(&sNC, pX) ){
  53284. return WRC_Abort;
  53285. }
  53286. }
  53287. /* Recursively resolve names in all subqueries
  53288. */
  53289. for(i=0; i<p->pSrc->nSrc; i++){
  53290. struct SrcList_item *pItem = &p->pSrc->a[i];
  53291. if( pItem->pSelect ){
  53292. const char *zSavedContext = pParse->zAuthContext;
  53293. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  53294. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  53295. pParse->zAuthContext = zSavedContext;
  53296. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  53297. }
  53298. }
  53299. /* If there are no aggregate functions in the result-set, and no GROUP BY
  53300. ** expression, do not allow aggregates in any of the other expressions.
  53301. */
  53302. assert( (p->selFlags & SF_Aggregate)==0 );
  53303. pGroupBy = p->pGroupBy;
  53304. if( pGroupBy || sNC.hasAgg ){
  53305. p->selFlags |= SF_Aggregate;
  53306. }else{
  53307. sNC.allowAgg = 0;
  53308. }
  53309. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  53310. */
  53311. if( p->pHaving && !pGroupBy ){
  53312. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  53313. return WRC_Abort;
  53314. }
  53315. /* Add the expression list to the name-context before parsing the
  53316. ** other expressions in the SELECT statement. This is so that
  53317. ** expressions in the WHERE clause (etc.) can refer to expressions by
  53318. ** aliases in the result set.
  53319. **
  53320. ** Minor point: If this is the case, then the expression will be
  53321. ** re-evaluated for each reference to it.
  53322. */
  53323. sNC.pEList = p->pEList;
  53324. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
  53325. sqlite3ResolveExprNames(&sNC, p->pHaving)
  53326. ){
  53327. return WRC_Abort;
  53328. }
  53329. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  53330. ** outer queries
  53331. */
  53332. sNC.pNext = 0;
  53333. sNC.allowAgg = 1;
  53334. /* Process the ORDER BY clause for singleton SELECT statements.
  53335. ** The ORDER BY clause for compounds SELECT statements is handled
  53336. ** below, after all of the result-sets for all of the elements of
  53337. ** the compound have been resolved.
  53338. */
  53339. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  53340. return WRC_Abort;
  53341. }
  53342. if( db->mallocFailed ){
  53343. return WRC_Abort;
  53344. }
  53345. /* Resolve the GROUP BY clause. At the same time, make sure
  53346. ** the GROUP BY clause does not contain aggregate functions.
  53347. */
  53348. if( pGroupBy ){
  53349. struct ExprList_item *pItem;
  53350. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  53351. return WRC_Abort;
  53352. }
  53353. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  53354. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  53355. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  53356. "the GROUP BY clause");
  53357. return WRC_Abort;
  53358. }
  53359. }
  53360. }
  53361. /* Advance to the next term of the compound
  53362. */
  53363. p = p->pPrior;
  53364. nCompound++;
  53365. }
  53366. /* Resolve the ORDER BY on a compound SELECT after all terms of
  53367. ** the compound have been resolved.
  53368. */
  53369. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  53370. return WRC_Abort;
  53371. }
  53372. return WRC_Prune;
  53373. }
  53374. /*
  53375. ** This routine walks an expression tree and resolves references to
  53376. ** table columns and result-set columns. At the same time, do error
  53377. ** checking on function usage and set a flag if any aggregate functions
  53378. ** are seen.
  53379. **
  53380. ** To resolve table columns references we look for nodes (or subtrees) of the
  53381. ** form X.Y.Z or Y.Z or just Z where
  53382. **
  53383. ** X: The name of a database. Ex: "main" or "temp" or
  53384. ** the symbolic name assigned to an ATTACH-ed database.
  53385. **
  53386. ** Y: The name of a table in a FROM clause. Or in a trigger
  53387. ** one of the special names "old" or "new".
  53388. **
  53389. ** Z: The name of a column in table Y.
  53390. **
  53391. ** The node at the root of the subtree is modified as follows:
  53392. **
  53393. ** Expr.op Changed to TK_COLUMN
  53394. ** Expr.pTab Points to the Table object for X.Y
  53395. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  53396. ** Expr.iTable The VDBE cursor number for X.Y
  53397. **
  53398. **
  53399. ** To resolve result-set references, look for expression nodes of the
  53400. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  53401. ** size of an AS clause in the result-set of a SELECT. The Z expression
  53402. ** is replaced by a copy of the left-hand side of the result-set expression.
  53403. ** Table-name and function resolution occurs on the substituted expression
  53404. ** tree. For example, in:
  53405. **
  53406. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  53407. **
  53408. ** The "x" term of the order by is replaced by "a+b" to render:
  53409. **
  53410. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  53411. **
  53412. ** Function calls are checked to make sure that the function is
  53413. ** defined and that the correct number of arguments are specified.
  53414. ** If the function is an aggregate function, then the pNC->hasAgg is
  53415. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  53416. ** If an expression contains aggregate functions then the EP_Agg
  53417. ** property on the expression is set.
  53418. **
  53419. ** An error message is left in pParse if anything is amiss. The number
  53420. ** if errors is returned.
  53421. */
  53422. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  53423. NameContext *pNC, /* Namespace to resolve expressions in. */
  53424. Expr *pExpr /* The expression to be analyzed. */
  53425. ){
  53426. int savedHasAgg;
  53427. Walker w;
  53428. if( pExpr==0 ) return 0;
  53429. #if SQLITE_MAX_EXPR_DEPTH>0
  53430. {
  53431. Parse *pParse = pNC->pParse;
  53432. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  53433. return 1;
  53434. }
  53435. pParse->nHeight += pExpr->nHeight;
  53436. }
  53437. #endif
  53438. savedHasAgg = pNC->hasAgg;
  53439. pNC->hasAgg = 0;
  53440. w.xExprCallback = resolveExprStep;
  53441. w.xSelectCallback = resolveSelectStep;
  53442. w.pParse = pNC->pParse;
  53443. w.u.pNC = pNC;
  53444. sqlite3WalkExpr(&w, pExpr);
  53445. #if SQLITE_MAX_EXPR_DEPTH>0
  53446. pNC->pParse->nHeight -= pExpr->nHeight;
  53447. #endif
  53448. if( pNC->nErr>0 ){
  53449. ExprSetProperty(pExpr, EP_Error);
  53450. }
  53451. if( pNC->hasAgg ){
  53452. ExprSetProperty(pExpr, EP_Agg);
  53453. }else if( savedHasAgg ){
  53454. pNC->hasAgg = 1;
  53455. }
  53456. return ExprHasProperty(pExpr, EP_Error);
  53457. }
  53458. /*
  53459. ** Resolve all names in all expressions of a SELECT and in all
  53460. ** decendents of the SELECT, including compounds off of p->pPrior,
  53461. ** subqueries in expressions, and subqueries used as FROM clause
  53462. ** terms.
  53463. **
  53464. ** See sqlite3ResolveExprNames() for a description of the kinds of
  53465. ** transformations that occur.
  53466. **
  53467. ** All SELECT statements should have been expanded using
  53468. ** sqlite3SelectExpand() prior to invoking this routine.
  53469. */
  53470. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  53471. Parse *pParse, /* The parser context */
  53472. Select *p, /* The SELECT statement being coded. */
  53473. NameContext *pOuterNC /* Name context for parent SELECT statement */
  53474. ){
  53475. Walker w;
  53476. assert( p!=0 );
  53477. w.xExprCallback = resolveExprStep;
  53478. w.xSelectCallback = resolveSelectStep;
  53479. w.pParse = pParse;
  53480. w.u.pNC = pOuterNC;
  53481. sqlite3WalkSelect(&w, p);
  53482. }
  53483. /************** End of resolve.c *********************************************/
  53484. /************** Begin file expr.c ********************************************/
  53485. /*
  53486. ** 2001 September 15
  53487. **
  53488. ** The author disclaims copyright to this source code. In place of
  53489. ** a legal notice, here is a blessing:
  53490. **
  53491. ** May you do good and not evil.
  53492. ** May you find forgiveness for yourself and forgive others.
  53493. ** May you share freely, never taking more than you give.
  53494. **
  53495. *************************************************************************
  53496. ** This file contains routines used for analyzing expressions and
  53497. ** for generating VDBE code that evaluates expressions in SQLite.
  53498. **
  53499. ** $Id: expr.c,v 1.426 2009/04/08 13:51:51 drh Exp $
  53500. */
  53501. /*
  53502. ** Return the 'affinity' of the expression pExpr if any.
  53503. **
  53504. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  53505. ** or a sub-select with a column as the return value, then the
  53506. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  53507. ** indicating no affinity for the expression.
  53508. **
  53509. ** i.e. the WHERE clause expresssions in the following statements all
  53510. ** have an affinity:
  53511. **
  53512. ** CREATE TABLE t1(a);
  53513. ** SELECT * FROM t1 WHERE a;
  53514. ** SELECT a AS b FROM t1 WHERE b;
  53515. ** SELECT * FROM t1 WHERE (select a from t1);
  53516. */
  53517. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  53518. int op = pExpr->op;
  53519. if( op==TK_SELECT ){
  53520. assert( pExpr->flags&EP_xIsSelect );
  53521. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  53522. }
  53523. #ifndef SQLITE_OMIT_CAST
  53524. if( op==TK_CAST ){
  53525. return sqlite3AffinityType(&pExpr->token);
  53526. }
  53527. #endif
  53528. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  53529. && pExpr->pTab!=0
  53530. ){
  53531. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  53532. ** a TK_COLUMN but was previously evaluated and cached in a register */
  53533. int j = pExpr->iColumn;
  53534. if( j<0 ) return SQLITE_AFF_INTEGER;
  53535. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  53536. return pExpr->pTab->aCol[j].affinity;
  53537. }
  53538. return pExpr->affinity;
  53539. }
  53540. /*
  53541. ** Set the collating sequence for expression pExpr to be the collating
  53542. ** sequence named by pToken. Return a pointer to the revised expression.
  53543. ** The collating sequence is marked as "explicit" using the EP_ExpCollate
  53544. ** flag. An explicit collating sequence will override implicit
  53545. ** collating sequences.
  53546. */
  53547. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
  53548. char *zColl = 0; /* Dequoted name of collation sequence */
  53549. CollSeq *pColl;
  53550. sqlite3 *db = pParse->db;
  53551. zColl = sqlite3NameFromToken(db, pCollName);
  53552. if( pExpr && zColl ){
  53553. pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
  53554. if( pColl ){
  53555. pExpr->pColl = pColl;
  53556. pExpr->flags |= EP_ExpCollate;
  53557. }
  53558. }
  53559. sqlite3DbFree(db, zColl);
  53560. return pExpr;
  53561. }
  53562. /*
  53563. ** Return the default collation sequence for the expression pExpr. If
  53564. ** there is no default collation type, return 0.
  53565. */
  53566. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  53567. CollSeq *pColl = 0;
  53568. Expr *p = pExpr;
  53569. while( p ){
  53570. int op;
  53571. pColl = p->pColl;
  53572. if( pColl ) break;
  53573. op = p->op;
  53574. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
  53575. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  53576. ** a TK_COLUMN but was previously evaluated and cached in a register */
  53577. const char *zColl;
  53578. int j = p->iColumn;
  53579. if( j>=0 ){
  53580. sqlite3 *db = pParse->db;
  53581. zColl = p->pTab->aCol[j].zColl;
  53582. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
  53583. pExpr->pColl = pColl;
  53584. }
  53585. break;
  53586. }
  53587. if( op!=TK_CAST && op!=TK_UPLUS ){
  53588. break;
  53589. }
  53590. p = p->pLeft;
  53591. }
  53592. if( sqlite3CheckCollSeq(pParse, pColl) ){
  53593. pColl = 0;
  53594. }
  53595. return pColl;
  53596. }
  53597. /*
  53598. ** pExpr is an operand of a comparison operator. aff2 is the
  53599. ** type affinity of the other operand. This routine returns the
  53600. ** type affinity that should be used for the comparison operator.
  53601. */
  53602. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  53603. char aff1 = sqlite3ExprAffinity(pExpr);
  53604. if( aff1 && aff2 ){
  53605. /* Both sides of the comparison are columns. If one has numeric
  53606. ** affinity, use that. Otherwise use no affinity.
  53607. */
  53608. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  53609. return SQLITE_AFF_NUMERIC;
  53610. }else{
  53611. return SQLITE_AFF_NONE;
  53612. }
  53613. }else if( !aff1 && !aff2 ){
  53614. /* Neither side of the comparison is a column. Compare the
  53615. ** results directly.
  53616. */
  53617. return SQLITE_AFF_NONE;
  53618. }else{
  53619. /* One side is a column, the other is not. Use the columns affinity. */
  53620. assert( aff1==0 || aff2==0 );
  53621. return (aff1 + aff2);
  53622. }
  53623. }
  53624. /*
  53625. ** pExpr is a comparison operator. Return the type affinity that should
  53626. ** be applied to both operands prior to doing the comparison.
  53627. */
  53628. static char comparisonAffinity(Expr *pExpr){
  53629. char aff;
  53630. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  53631. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  53632. pExpr->op==TK_NE );
  53633. assert( pExpr->pLeft );
  53634. aff = sqlite3ExprAffinity(pExpr->pLeft);
  53635. if( pExpr->pRight ){
  53636. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  53637. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  53638. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  53639. }else if( !aff ){
  53640. aff = SQLITE_AFF_NONE;
  53641. }
  53642. return aff;
  53643. }
  53644. /*
  53645. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  53646. ** idx_affinity is the affinity of an indexed column. Return true
  53647. ** if the index with affinity idx_affinity may be used to implement
  53648. ** the comparison in pExpr.
  53649. */
  53650. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  53651. char aff = comparisonAffinity(pExpr);
  53652. switch( aff ){
  53653. case SQLITE_AFF_NONE:
  53654. return 1;
  53655. case SQLITE_AFF_TEXT:
  53656. return idx_affinity==SQLITE_AFF_TEXT;
  53657. default:
  53658. return sqlite3IsNumericAffinity(idx_affinity);
  53659. }
  53660. }
  53661. /*
  53662. ** Return the P5 value that should be used for a binary comparison
  53663. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  53664. */
  53665. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  53666. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  53667. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  53668. return aff;
  53669. }
  53670. /*
  53671. ** Return a pointer to the collation sequence that should be used by
  53672. ** a binary comparison operator comparing pLeft and pRight.
  53673. **
  53674. ** If the left hand expression has a collating sequence type, then it is
  53675. ** used. Otherwise the collation sequence for the right hand expression
  53676. ** is used, or the default (BINARY) if neither expression has a collating
  53677. ** type.
  53678. **
  53679. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  53680. ** it is not considered.
  53681. */
  53682. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  53683. Parse *pParse,
  53684. Expr *pLeft,
  53685. Expr *pRight
  53686. ){
  53687. CollSeq *pColl;
  53688. assert( pLeft );
  53689. if( pLeft->flags & EP_ExpCollate ){
  53690. assert( pLeft->pColl );
  53691. pColl = pLeft->pColl;
  53692. }else if( pRight && pRight->flags & EP_ExpCollate ){
  53693. assert( pRight->pColl );
  53694. pColl = pRight->pColl;
  53695. }else{
  53696. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  53697. if( !pColl ){
  53698. pColl = sqlite3ExprCollSeq(pParse, pRight);
  53699. }
  53700. }
  53701. return pColl;
  53702. }
  53703. /*
  53704. ** Generate the operands for a comparison operation. Before
  53705. ** generating the code for each operand, set the EP_AnyAff
  53706. ** flag on the expression so that it will be able to used a
  53707. ** cached column value that has previously undergone an
  53708. ** affinity change.
  53709. */
  53710. static void codeCompareOperands(
  53711. Parse *pParse, /* Parsing and code generating context */
  53712. Expr *pLeft, /* The left operand */
  53713. int *pRegLeft, /* Register where left operand is stored */
  53714. int *pFreeLeft, /* Free this register when done */
  53715. Expr *pRight, /* The right operand */
  53716. int *pRegRight, /* Register where right operand is stored */
  53717. int *pFreeRight /* Write temp register for right operand there */
  53718. ){
  53719. while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
  53720. pLeft->flags |= EP_AnyAff;
  53721. *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
  53722. while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
  53723. pRight->flags |= EP_AnyAff;
  53724. *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
  53725. }
  53726. /*
  53727. ** Generate code for a comparison operator.
  53728. */
  53729. static int codeCompare(
  53730. Parse *pParse, /* The parsing (and code generating) context */
  53731. Expr *pLeft, /* The left operand */
  53732. Expr *pRight, /* The right operand */
  53733. int opcode, /* The comparison opcode */
  53734. int in1, int in2, /* Register holding operands */
  53735. int dest, /* Jump here if true. */
  53736. int jumpIfNull /* If true, jump if either operand is NULL */
  53737. ){
  53738. int p5;
  53739. int addr;
  53740. CollSeq *p4;
  53741. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  53742. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  53743. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  53744. (void*)p4, P4_COLLSEQ);
  53745. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  53746. if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
  53747. sqlite3ExprCacheAffinityChange(pParse, in1, 1);
  53748. sqlite3ExprCacheAffinityChange(pParse, in2, 1);
  53749. }
  53750. return addr;
  53751. }
  53752. #if SQLITE_MAX_EXPR_DEPTH>0
  53753. /*
  53754. ** Check that argument nHeight is less than or equal to the maximum
  53755. ** expression depth allowed. If it is not, leave an error message in
  53756. ** pParse.
  53757. */
  53758. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  53759. int rc = SQLITE_OK;
  53760. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  53761. if( nHeight>mxHeight ){
  53762. sqlite3ErrorMsg(pParse,
  53763. "Expression tree is too large (maximum depth %d)", mxHeight
  53764. );
  53765. rc = SQLITE_ERROR;
  53766. }
  53767. return rc;
  53768. }
  53769. /* The following three functions, heightOfExpr(), heightOfExprList()
  53770. ** and heightOfSelect(), are used to determine the maximum height
  53771. ** of any expression tree referenced by the structure passed as the
  53772. ** first argument.
  53773. **
  53774. ** If this maximum height is greater than the current value pointed
  53775. ** to by pnHeight, the second parameter, then set *pnHeight to that
  53776. ** value.
  53777. */
  53778. static void heightOfExpr(Expr *p, int *pnHeight){
  53779. if( p ){
  53780. if( p->nHeight>*pnHeight ){
  53781. *pnHeight = p->nHeight;
  53782. }
  53783. }
  53784. }
  53785. static void heightOfExprList(ExprList *p, int *pnHeight){
  53786. if( p ){
  53787. int i;
  53788. for(i=0; i<p->nExpr; i++){
  53789. heightOfExpr(p->a[i].pExpr, pnHeight);
  53790. }
  53791. }
  53792. }
  53793. static void heightOfSelect(Select *p, int *pnHeight){
  53794. if( p ){
  53795. heightOfExpr(p->pWhere, pnHeight);
  53796. heightOfExpr(p->pHaving, pnHeight);
  53797. heightOfExpr(p->pLimit, pnHeight);
  53798. heightOfExpr(p->pOffset, pnHeight);
  53799. heightOfExprList(p->pEList, pnHeight);
  53800. heightOfExprList(p->pGroupBy, pnHeight);
  53801. heightOfExprList(p->pOrderBy, pnHeight);
  53802. heightOfSelect(p->pPrior, pnHeight);
  53803. }
  53804. }
  53805. /*
  53806. ** Set the Expr.nHeight variable in the structure passed as an
  53807. ** argument. An expression with no children, Expr.pList or
  53808. ** Expr.pSelect member has a height of 1. Any other expression
  53809. ** has a height equal to the maximum height of any other
  53810. ** referenced Expr plus one.
  53811. */
  53812. static void exprSetHeight(Expr *p){
  53813. int nHeight = 0;
  53814. heightOfExpr(p->pLeft, &nHeight);
  53815. heightOfExpr(p->pRight, &nHeight);
  53816. if( ExprHasProperty(p, EP_xIsSelect) ){
  53817. heightOfSelect(p->x.pSelect, &nHeight);
  53818. }else{
  53819. heightOfExprList(p->x.pList, &nHeight);
  53820. }
  53821. p->nHeight = nHeight + 1;
  53822. }
  53823. /*
  53824. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  53825. ** the height is greater than the maximum allowed expression depth,
  53826. ** leave an error in pParse.
  53827. */
  53828. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  53829. exprSetHeight(p);
  53830. sqlite3ExprCheckHeight(pParse, p->nHeight);
  53831. }
  53832. /*
  53833. ** Return the maximum height of any expression tree referenced
  53834. ** by the select statement passed as an argument.
  53835. */
  53836. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  53837. int nHeight = 0;
  53838. heightOfSelect(p, &nHeight);
  53839. return nHeight;
  53840. }
  53841. #else
  53842. #define exprSetHeight(y)
  53843. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  53844. /*
  53845. ** Construct a new expression node and return a pointer to it. Memory
  53846. ** for this node is obtained from sqlite3_malloc(). The calling function
  53847. ** is responsible for making sure the node eventually gets freed.
  53848. */
  53849. SQLITE_PRIVATE Expr *sqlite3Expr(
  53850. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  53851. int op, /* Expression opcode */
  53852. Expr *pLeft, /* Left operand */
  53853. Expr *pRight, /* Right operand */
  53854. const Token *pToken /* Argument token */
  53855. ){
  53856. Expr *pNew;
  53857. pNew = sqlite3DbMallocZero(db, sizeof(Expr));
  53858. if( pNew==0 ){
  53859. /* When malloc fails, delete pLeft and pRight. Expressions passed to
  53860. ** this function must always be allocated with sqlite3Expr() for this
  53861. ** reason.
  53862. */
  53863. sqlite3ExprDelete(db, pLeft);
  53864. sqlite3ExprDelete(db, pRight);
  53865. return 0;
  53866. }
  53867. pNew->op = (u8)op;
  53868. pNew->pLeft = pLeft;
  53869. pNew->pRight = pRight;
  53870. pNew->iAgg = -1;
  53871. pNew->span.z = (u8*)"";
  53872. if( pToken ){
  53873. int c;
  53874. assert( pToken->dyn==0 );
  53875. pNew->span = *pToken;
  53876. /* The pToken->z value is read-only. But the new expression
  53877. ** node created here might be passed to sqlite3DequoteExpr() which
  53878. ** will attempt to modify pNew->token.z. Hence, if the token
  53879. ** is quoted, make a copy now so that DequoteExpr() will change
  53880. ** the copy rather than the original text.
  53881. */
  53882. if( pToken->n>=2
  53883. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  53884. sqlite3TokenCopy(db, &pNew->token, pToken);
  53885. }else{
  53886. pNew->token = *pToken;
  53887. pNew->flags |= EP_Dequoted;
  53888. VVA_ONLY( pNew->vvaFlags |= EVVA_ReadOnlyToken; )
  53889. }
  53890. }else if( pLeft ){
  53891. if( pRight ){
  53892. if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
  53893. sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
  53894. }
  53895. if( pRight->flags & EP_ExpCollate ){
  53896. pNew->flags |= EP_ExpCollate;
  53897. pNew->pColl = pRight->pColl;
  53898. }
  53899. }
  53900. if( pLeft->flags & EP_ExpCollate ){
  53901. pNew->flags |= EP_ExpCollate;
  53902. pNew->pColl = pLeft->pColl;
  53903. }
  53904. }
  53905. exprSetHeight(pNew);
  53906. return pNew;
  53907. }
  53908. /*
  53909. ** Works like sqlite3Expr() except that it takes an extra Parse*
  53910. ** argument and notifies the associated connection object if malloc fails.
  53911. */
  53912. SQLITE_PRIVATE Expr *sqlite3PExpr(
  53913. Parse *pParse, /* Parsing context */
  53914. int op, /* Expression opcode */
  53915. Expr *pLeft, /* Left operand */
  53916. Expr *pRight, /* Right operand */
  53917. const Token *pToken /* Argument token */
  53918. ){
  53919. Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
  53920. if( p ){
  53921. sqlite3ExprCheckHeight(pParse, p->nHeight);
  53922. }
  53923. return p;
  53924. }
  53925. /*
  53926. ** When doing a nested parse, you can include terms in an expression
  53927. ** that look like this: #1 #2 ... These terms refer to registers
  53928. ** in the virtual machine. #N is the N-th register.
  53929. **
  53930. ** This routine is called by the parser to deal with on of those terms.
  53931. ** It immediately generates code to store the value in a memory location.
  53932. ** The returns an expression that will code to extract the value from
  53933. ** that memory location as needed.
  53934. */
  53935. SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
  53936. Vdbe *v = pParse->pVdbe;
  53937. Expr *p;
  53938. if( pParse->nested==0 ){
  53939. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
  53940. return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  53941. }
  53942. if( v==0 ) return 0;
  53943. p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
  53944. if( p==0 ){
  53945. return 0; /* Malloc failed */
  53946. }
  53947. p->iTable = atoi((char*)&pToken->z[1]);
  53948. return p;
  53949. }
  53950. /*
  53951. ** Join two expressions using an AND operator. If either expression is
  53952. ** NULL, then just return the other expression.
  53953. */
  53954. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  53955. if( pLeft==0 ){
  53956. return pRight;
  53957. }else if( pRight==0 ){
  53958. return pLeft;
  53959. }else{
  53960. return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
  53961. }
  53962. }
  53963. /*
  53964. ** Set the Expr.span field of the given expression to span all
  53965. ** text between the two given tokens. Both tokens must be pointing
  53966. ** at the same string.
  53967. */
  53968. SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
  53969. assert( pRight!=0 );
  53970. assert( pLeft!=0 );
  53971. if( pExpr ){
  53972. pExpr->span.z = pLeft->z;
  53973. /* The following assert() may fail when this is called
  53974. ** via sqlite3PExpr()/sqlite3Expr() from addWhereTerm(). */
  53975. /* assert(pRight->z >= pLeft->z); */
  53976. pExpr->span.n = pRight->n + (unsigned)(pRight->z - pLeft->z);
  53977. }
  53978. }
  53979. /*
  53980. ** Construct a new expression node for a function with multiple
  53981. ** arguments.
  53982. */
  53983. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  53984. Expr *pNew;
  53985. sqlite3 *db = pParse->db;
  53986. assert( pToken );
  53987. pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
  53988. if( pNew==0 ){
  53989. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  53990. return 0;
  53991. }
  53992. pNew->op = TK_FUNCTION;
  53993. pNew->x.pList = pList;
  53994. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  53995. assert( pToken->dyn==0 );
  53996. pNew->span = *pToken;
  53997. sqlite3TokenCopy(db, &pNew->token, pToken);
  53998. sqlite3ExprSetHeight(pParse, pNew);
  53999. return pNew;
  54000. }
  54001. /*
  54002. ** Assign a variable number to an expression that encodes a wildcard
  54003. ** in the original SQL statement.
  54004. **
  54005. ** Wildcards consisting of a single "?" are assigned the next sequential
  54006. ** variable number.
  54007. **
  54008. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  54009. ** sure "nnn" is not too be to avoid a denial of service attack when
  54010. ** the SQL statement comes from an external source.
  54011. **
  54012. ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
  54013. ** as the previous instance of the same wildcard. Or if this is the first
  54014. ** instance of the wildcard, the next sequenial variable number is
  54015. ** assigned.
  54016. */
  54017. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  54018. Token *pToken;
  54019. sqlite3 *db = pParse->db;
  54020. if( pExpr==0 ) return;
  54021. pToken = &pExpr->token;
  54022. assert( pToken->n>=1 );
  54023. assert( pToken->z!=0 );
  54024. assert( pToken->z[0]!=0 );
  54025. if( pToken->n==1 ){
  54026. /* Wildcard of the form "?". Assign the next variable number */
  54027. pExpr->iTable = ++pParse->nVar;
  54028. }else if( pToken->z[0]=='?' ){
  54029. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  54030. ** use it as the variable number */
  54031. int i;
  54032. pExpr->iTable = i = atoi((char*)&pToken->z[1]);
  54033. testcase( i==0 );
  54034. testcase( i==1 );
  54035. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  54036. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  54037. if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  54038. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  54039. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  54040. }
  54041. if( i>pParse->nVar ){
  54042. pParse->nVar = i;
  54043. }
  54044. }else{
  54045. /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
  54046. ** number as the prior appearance of the same name, or if the name
  54047. ** has never appeared before, reuse the same variable number
  54048. */
  54049. int i;
  54050. u32 n;
  54051. n = pToken->n;
  54052. for(i=0; i<pParse->nVarExpr; i++){
  54053. Expr *pE;
  54054. if( (pE = pParse->apVarExpr[i])!=0
  54055. && pE->token.n==n
  54056. && memcmp(pE->token.z, pToken->z, n)==0 ){
  54057. pExpr->iTable = pE->iTable;
  54058. break;
  54059. }
  54060. }
  54061. if( i>=pParse->nVarExpr ){
  54062. pExpr->iTable = ++pParse->nVar;
  54063. if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
  54064. pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
  54065. pParse->apVarExpr =
  54066. sqlite3DbReallocOrFree(
  54067. db,
  54068. pParse->apVarExpr,
  54069. pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
  54070. );
  54071. }
  54072. if( !db->mallocFailed ){
  54073. assert( pParse->apVarExpr!=0 );
  54074. pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
  54075. }
  54076. }
  54077. }
  54078. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  54079. sqlite3ErrorMsg(pParse, "too many SQL variables");
  54080. }
  54081. }
  54082. /*
  54083. ** Clear an expression structure without deleting the structure itself.
  54084. ** Substructure is deleted.
  54085. */
  54086. SQLITE_PRIVATE void sqlite3ExprClear(sqlite3 *db, Expr *p){
  54087. if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
  54088. if( !ExprHasAnyProperty(p, EP_TokenOnly|EP_SpanToken) ){
  54089. if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
  54090. if( ExprHasProperty(p, EP_Reduced) ){
  54091. /* Subtrees are part of the same memory allocation when EP_Reduced set */
  54092. if( p->pLeft ) sqlite3ExprClear(db, p->pLeft);
  54093. if( p->pRight ) sqlite3ExprClear(db, p->pRight);
  54094. }else{
  54095. /* Subtrees are separate allocations when EP_Reduced is clear */
  54096. sqlite3ExprDelete(db, p->pLeft);
  54097. sqlite3ExprDelete(db, p->pRight);
  54098. }
  54099. /* x.pSelect and x.pList are always separately allocated */
  54100. if( ExprHasProperty(p, EP_xIsSelect) ){
  54101. sqlite3SelectDelete(db, p->x.pSelect);
  54102. }else{
  54103. sqlite3ExprListDelete(db, p->x.pList);
  54104. }
  54105. }
  54106. }
  54107. /*
  54108. ** Recursively delete an expression tree.
  54109. */
  54110. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  54111. if( p==0 ) return;
  54112. sqlite3ExprClear(db, p);
  54113. sqlite3DbFree(db, p);
  54114. }
  54115. /*
  54116. ** The Expr.token field might be a string literal that is quoted.
  54117. ** If so, remove the quotation marks.
  54118. */
  54119. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
  54120. if( !ExprHasAnyProperty(p, EP_Dequoted) ){
  54121. ExprSetProperty(p, EP_Dequoted);
  54122. assert( (p->vvaFlags & EVVA_ReadOnlyToken)==0 );
  54123. sqlite3Dequote((char*)p->token.z);
  54124. }
  54125. }
  54126. /*
  54127. ** Return the number of bytes allocated for the expression structure
  54128. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  54129. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  54130. */
  54131. static int exprStructSize(Expr *p){
  54132. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  54133. if( ExprHasProperty(p, EP_SpanToken) ) return EXPR_SPANTOKENSIZE;
  54134. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  54135. return EXPR_FULLSIZE;
  54136. }
  54137. /*
  54138. ** sqlite3ExprDup() has been called to create a copy of expression p with
  54139. ** the EXPRDUP_XXX flags passed as the second argument. This function
  54140. ** returns the space required for the copy of the Expr structure only.
  54141. ** This is always one of EXPR_FULLSIZE, EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  54142. */
  54143. static int dupedExprStructSize(Expr *p, int flags){
  54144. int nSize;
  54145. if( 0==(flags&EXPRDUP_REDUCE) ){
  54146. nSize = EXPR_FULLSIZE;
  54147. }else if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
  54148. nSize = EXPR_REDUCEDSIZE;
  54149. }else if( flags&EXPRDUP_SPAN ){
  54150. nSize = EXPR_SPANTOKENSIZE;
  54151. }else{
  54152. nSize = EXPR_TOKENONLYSIZE;
  54153. }
  54154. return nSize;
  54155. }
  54156. /*
  54157. ** sqlite3ExprDup() has been called to create a copy of expression p with
  54158. ** the EXPRDUP_XXX passed as the second argument. This function returns
  54159. ** the space in bytes required to store the copy of the Expr structure
  54160. ** and the copies of the Expr.token.z and Expr.span.z (if applicable)
  54161. ** string buffers.
  54162. */
  54163. static int dupedExprNodeSize(Expr *p, int flags){
  54164. int nByte = dupedExprStructSize(p, flags) + (p->token.z ? p->token.n + 1 : 0);
  54165. if( (flags&EXPRDUP_SPAN)!=0
  54166. && (p->token.z!=p->span.z || p->token.n!=p->span.n)
  54167. ){
  54168. nByte += p->span.n;
  54169. }
  54170. return ROUND8(nByte);
  54171. }
  54172. /*
  54173. ** Return the number of bytes required to create a duplicate of the
  54174. ** expression passed as the first argument. The second argument is a
  54175. ** mask containing EXPRDUP_XXX flags.
  54176. **
  54177. ** The value returned includes space to create a copy of the Expr struct
  54178. ** itself and the buffer referred to by Expr.token, if any. If the
  54179. ** EXPRDUP_SPAN flag is set, then space to create a copy of the buffer
  54180. ** refered to by Expr.span is also included.
  54181. **
  54182. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  54183. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  54184. ** and Expr.pRight variables (but not for any structures pointed to or
  54185. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  54186. */
  54187. static int dupedExprSize(Expr *p, int flags){
  54188. int nByte = 0;
  54189. if( p ){
  54190. nByte = dupedExprNodeSize(p, flags);
  54191. if( flags&EXPRDUP_REDUCE ){
  54192. int f = flags&(~EXPRDUP_SPAN);
  54193. nByte += dupedExprSize(p->pLeft, f) + dupedExprSize(p->pRight, f);
  54194. }
  54195. }
  54196. return nByte;
  54197. }
  54198. /*
  54199. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  54200. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  54201. ** to store the copy of expression p, the copies of p->token and p->span
  54202. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  54203. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  54204. ** portion of the buffer copied into by this function.
  54205. */
  54206. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  54207. Expr *pNew = 0; /* Value to return */
  54208. if( p ){
  54209. const int isRequireSpan = (flags&EXPRDUP_SPAN);
  54210. const int isReduced = (flags&EXPRDUP_REDUCE);
  54211. u8 *zAlloc;
  54212. assert( pzBuffer==0 || isReduced );
  54213. /* Figure out where to write the new Expr structure. */
  54214. if( pzBuffer ){
  54215. zAlloc = *pzBuffer;
  54216. }else{
  54217. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  54218. }
  54219. pNew = (Expr *)zAlloc;
  54220. if( pNew ){
  54221. /* Set nNewSize to the size allocated for the structure pointed to
  54222. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  54223. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  54224. ** by the copy of the p->token.z string (if any).
  54225. */
  54226. const int nNewSize = dupedExprStructSize(p, flags);
  54227. const int nToken = (p->token.z ? p->token.n + 1 : 0);
  54228. if( isReduced ){
  54229. assert( ExprHasProperty(p, EP_Reduced)==0 );
  54230. memcpy(zAlloc, p, nNewSize);
  54231. }else{
  54232. int nSize = exprStructSize(p);
  54233. memcpy(zAlloc, p, nSize);
  54234. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  54235. }
  54236. /* Set the EP_Reduced and EP_TokenOnly flags appropriately. */
  54237. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_SpanToken);
  54238. switch( nNewSize ){
  54239. case EXPR_REDUCEDSIZE: pNew->flags |= EP_Reduced; break;
  54240. case EXPR_TOKENONLYSIZE: pNew->flags |= EP_TokenOnly; break;
  54241. case EXPR_SPANTOKENSIZE: pNew->flags |= EP_SpanToken; break;
  54242. }
  54243. /* Copy the p->token string, if any. */
  54244. if( nToken ){
  54245. unsigned char *zToken = &zAlloc[nNewSize];
  54246. memcpy(zToken, p->token.z, nToken-1);
  54247. zToken[nToken-1] = '\0';
  54248. pNew->token.dyn = 0;
  54249. pNew->token.z = zToken;
  54250. }
  54251. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  54252. /* Fill in the pNew->span token, if required. */
  54253. if( isRequireSpan ){
  54254. if( p->token.z!=p->span.z || p->token.n!=p->span.n ){
  54255. pNew->span.z = &zAlloc[nNewSize+nToken];
  54256. memcpy((char *)pNew->span.z, p->span.z, p->span.n);
  54257. pNew->span.dyn = 0;
  54258. }else{
  54259. pNew->span.z = pNew->token.z;
  54260. pNew->span.n = pNew->token.n;
  54261. }
  54262. }else{
  54263. pNew->span.z = 0;
  54264. pNew->span.n = 0;
  54265. }
  54266. }
  54267. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_SpanToken)) ){
  54268. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  54269. if( ExprHasProperty(p, EP_xIsSelect) ){
  54270. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  54271. }else{
  54272. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  54273. }
  54274. }
  54275. /* Fill in pNew->pLeft and pNew->pRight. */
  54276. if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly|EP_SpanToken) ){
  54277. zAlloc += dupedExprNodeSize(p, flags);
  54278. if( ExprHasProperty(pNew, EP_Reduced) ){
  54279. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  54280. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  54281. }
  54282. if( pzBuffer ){
  54283. *pzBuffer = zAlloc;
  54284. }
  54285. }else if( !ExprHasAnyProperty(p, EP_TokenOnly|EP_SpanToken) ){
  54286. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  54287. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  54288. }
  54289. }
  54290. }
  54291. return pNew;
  54292. }
  54293. /*
  54294. ** The following group of routines make deep copies of expressions,
  54295. ** expression lists, ID lists, and select statements. The copies can
  54296. ** be deleted (by being passed to their respective ...Delete() routines)
  54297. ** without effecting the originals.
  54298. **
  54299. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  54300. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  54301. ** by subsequent calls to sqlite*ListAppend() routines.
  54302. **
  54303. ** Any tables that the SrcList might point to are not duplicated.
  54304. **
  54305. ** The flags parameter contains a combination of the EXPRDUP_XXX flags. If
  54306. ** the EXPRDUP_SPAN flag is set in the argument parameter, then the
  54307. ** Expr.span field of the input expression is copied. If EXPRDUP_SPAN is
  54308. ** clear, then the Expr.span field of the returned expression structure
  54309. ** is zeroed.
  54310. **
  54311. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  54312. ** truncated version of the usual Expr structure that will be stored as
  54313. ** part of the in-memory representation of the database schema.
  54314. */
  54315. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  54316. return exprDup(db, p, flags, 0);
  54317. }
  54318. SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, const Token *pFrom){
  54319. if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
  54320. if( pFrom->z ){
  54321. pTo->n = pFrom->n;
  54322. pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
  54323. pTo->dyn = 1;
  54324. }else{
  54325. pTo->z = 0;
  54326. }
  54327. }
  54328. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  54329. ExprList *pNew;
  54330. struct ExprList_item *pItem, *pOldItem;
  54331. int i;
  54332. if( p==0 ) return 0;
  54333. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  54334. if( pNew==0 ) return 0;
  54335. pNew->iECursor = 0;
  54336. pNew->nExpr = pNew->nAlloc = p->nExpr;
  54337. pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
  54338. if( pItem==0 ){
  54339. sqlite3DbFree(db, pNew);
  54340. return 0;
  54341. }
  54342. pOldItem = p->a;
  54343. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  54344. Expr *pNewExpr;
  54345. Expr *pOldExpr = pOldItem->pExpr;
  54346. pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr, flags);
  54347. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  54348. pItem->sortOrder = pOldItem->sortOrder;
  54349. pItem->done = 0;
  54350. pItem->iCol = pOldItem->iCol;
  54351. pItem->iAlias = pOldItem->iAlias;
  54352. }
  54353. return pNew;
  54354. }
  54355. /*
  54356. ** If cursors, triggers, views and subqueries are all omitted from
  54357. ** the build, then none of the following routines, except for
  54358. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  54359. ** called with a NULL argument.
  54360. */
  54361. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  54362. || !defined(SQLITE_OMIT_SUBQUERY)
  54363. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  54364. SrcList *pNew;
  54365. int i;
  54366. int nByte;
  54367. if( p==0 ) return 0;
  54368. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  54369. pNew = sqlite3DbMallocRaw(db, nByte );
  54370. if( pNew==0 ) return 0;
  54371. pNew->nSrc = pNew->nAlloc = p->nSrc;
  54372. for(i=0; i<p->nSrc; i++){
  54373. struct SrcList_item *pNewItem = &pNew->a[i];
  54374. struct SrcList_item *pOldItem = &p->a[i];
  54375. Table *pTab;
  54376. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  54377. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  54378. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  54379. pNewItem->jointype = pOldItem->jointype;
  54380. pNewItem->iCursor = pOldItem->iCursor;
  54381. pNewItem->isPopulated = pOldItem->isPopulated;
  54382. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  54383. pNewItem->notIndexed = pOldItem->notIndexed;
  54384. pNewItem->pIndex = pOldItem->pIndex;
  54385. pTab = pNewItem->pTab = pOldItem->pTab;
  54386. if( pTab ){
  54387. pTab->nRef++;
  54388. }
  54389. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  54390. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  54391. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  54392. pNewItem->colUsed = pOldItem->colUsed;
  54393. }
  54394. return pNew;
  54395. }
  54396. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  54397. IdList *pNew;
  54398. int i;
  54399. if( p==0 ) return 0;
  54400. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  54401. if( pNew==0 ) return 0;
  54402. pNew->nId = pNew->nAlloc = p->nId;
  54403. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  54404. if( pNew->a==0 ){
  54405. sqlite3DbFree(db, pNew);
  54406. return 0;
  54407. }
  54408. for(i=0; i<p->nId; i++){
  54409. struct IdList_item *pNewItem = &pNew->a[i];
  54410. struct IdList_item *pOldItem = &p->a[i];
  54411. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  54412. pNewItem->idx = pOldItem->idx;
  54413. }
  54414. return pNew;
  54415. }
  54416. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  54417. Select *pNew;
  54418. if( p==0 ) return 0;
  54419. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  54420. if( pNew==0 ) return 0;
  54421. /* Always make a copy of the span for top-level expressions in the
  54422. ** expression list. The logic in SELECT processing that determines
  54423. ** the names of columns in the result set needs this information */
  54424. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags|EXPRDUP_SPAN);
  54425. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  54426. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  54427. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  54428. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  54429. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  54430. pNew->op = p->op;
  54431. pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  54432. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  54433. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  54434. pNew->iLimit = 0;
  54435. pNew->iOffset = 0;
  54436. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  54437. pNew->pRightmost = 0;
  54438. pNew->addrOpenEphm[0] = -1;
  54439. pNew->addrOpenEphm[1] = -1;
  54440. pNew->addrOpenEphm[2] = -1;
  54441. return pNew;
  54442. }
  54443. #else
  54444. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  54445. assert( p==0 );
  54446. return 0;
  54447. }
  54448. #endif
  54449. /*
  54450. ** Add a new element to the end of an expression list. If pList is
  54451. ** initially NULL, then create a new expression list.
  54452. */
  54453. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  54454. Parse *pParse, /* Parsing context */
  54455. ExprList *pList, /* List to which to append. Might be NULL */
  54456. Expr *pExpr, /* Expression to be appended */
  54457. Token *pName /* AS keyword for the expression */
  54458. ){
  54459. sqlite3 *db = pParse->db;
  54460. if( pList==0 ){
  54461. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  54462. if( pList==0 ){
  54463. goto no_mem;
  54464. }
  54465. assert( pList->nAlloc==0 );
  54466. }
  54467. if( pList->nAlloc<=pList->nExpr ){
  54468. struct ExprList_item *a;
  54469. int n = pList->nAlloc*2 + 4;
  54470. a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
  54471. if( a==0 ){
  54472. goto no_mem;
  54473. }
  54474. pList->a = a;
  54475. pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
  54476. }
  54477. assert( pList->a!=0 );
  54478. if( pExpr || pName ){
  54479. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  54480. memset(pItem, 0, sizeof(*pItem));
  54481. pItem->zName = sqlite3NameFromToken(db, pName);
  54482. pItem->pExpr = pExpr;
  54483. pItem->iAlias = 0;
  54484. }
  54485. return pList;
  54486. no_mem:
  54487. /* Avoid leaking memory if malloc has failed. */
  54488. sqlite3ExprDelete(db, pExpr);
  54489. sqlite3ExprListDelete(db, pList);
  54490. return 0;
  54491. }
  54492. /*
  54493. ** If the expression list pEList contains more than iLimit elements,
  54494. ** leave an error message in pParse.
  54495. */
  54496. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  54497. Parse *pParse,
  54498. ExprList *pEList,
  54499. const char *zObject
  54500. ){
  54501. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  54502. testcase( pEList && pEList->nExpr==mx );
  54503. testcase( pEList && pEList->nExpr==mx+1 );
  54504. if( pEList && pEList->nExpr>mx ){
  54505. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  54506. }
  54507. }
  54508. /*
  54509. ** Delete an entire expression list.
  54510. */
  54511. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  54512. int i;
  54513. struct ExprList_item *pItem;
  54514. if( pList==0 ) return;
  54515. assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
  54516. assert( pList->nExpr<=pList->nAlloc );
  54517. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  54518. sqlite3ExprDelete(db, pItem->pExpr);
  54519. sqlite3DbFree(db, pItem->zName);
  54520. }
  54521. sqlite3DbFree(db, pList->a);
  54522. sqlite3DbFree(db, pList);
  54523. }
  54524. /*
  54525. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  54526. ** to an integer. These routines are checking an expression to see
  54527. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  54528. ** not constant.
  54529. **
  54530. ** These callback routines are used to implement the following:
  54531. **
  54532. ** sqlite3ExprIsConstant()
  54533. ** sqlite3ExprIsConstantNotJoin()
  54534. ** sqlite3ExprIsConstantOrFunction()
  54535. **
  54536. */
  54537. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  54538. /* If pWalker->u.i is 3 then any term of the expression that comes from
  54539. ** the ON or USING clauses of a join disqualifies the expression
  54540. ** from being considered constant. */
  54541. if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
  54542. pWalker->u.i = 0;
  54543. return WRC_Abort;
  54544. }
  54545. switch( pExpr->op ){
  54546. /* Consider functions to be constant if all their arguments are constant
  54547. ** and pWalker->u.i==2 */
  54548. case TK_FUNCTION:
  54549. if( pWalker->u.i==2 ) return 0;
  54550. /* Fall through */
  54551. case TK_ID:
  54552. case TK_COLUMN:
  54553. case TK_AGG_FUNCTION:
  54554. case TK_AGG_COLUMN:
  54555. #ifndef SQLITE_OMIT_SUBQUERY
  54556. case TK_SELECT:
  54557. case TK_EXISTS:
  54558. testcase( pExpr->op==TK_SELECT );
  54559. testcase( pExpr->op==TK_EXISTS );
  54560. #endif
  54561. testcase( pExpr->op==TK_ID );
  54562. testcase( pExpr->op==TK_COLUMN );
  54563. testcase( pExpr->op==TK_AGG_FUNCTION );
  54564. testcase( pExpr->op==TK_AGG_COLUMN );
  54565. pWalker->u.i = 0;
  54566. return WRC_Abort;
  54567. default:
  54568. return WRC_Continue;
  54569. }
  54570. }
  54571. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  54572. UNUSED_PARAMETER(NotUsed);
  54573. pWalker->u.i = 0;
  54574. return WRC_Abort;
  54575. }
  54576. static int exprIsConst(Expr *p, int initFlag){
  54577. Walker w;
  54578. w.u.i = initFlag;
  54579. w.xExprCallback = exprNodeIsConstant;
  54580. w.xSelectCallback = selectNodeIsConstant;
  54581. sqlite3WalkExpr(&w, p);
  54582. return w.u.i;
  54583. }
  54584. /*
  54585. ** Walk an expression tree. Return 1 if the expression is constant
  54586. ** and 0 if it involves variables or function calls.
  54587. **
  54588. ** For the purposes of this function, a double-quoted string (ex: "abc")
  54589. ** is considered a variable but a single-quoted string (ex: 'abc') is
  54590. ** a constant.
  54591. */
  54592. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  54593. return exprIsConst(p, 1);
  54594. }
  54595. /*
  54596. ** Walk an expression tree. Return 1 if the expression is constant
  54597. ** that does no originate from the ON or USING clauses of a join.
  54598. ** Return 0 if it involves variables or function calls or terms from
  54599. ** an ON or USING clause.
  54600. */
  54601. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  54602. return exprIsConst(p, 3);
  54603. }
  54604. /*
  54605. ** Walk an expression tree. Return 1 if the expression is constant
  54606. ** or a function call with constant arguments. Return and 0 if there
  54607. ** are any variables.
  54608. **
  54609. ** For the purposes of this function, a double-quoted string (ex: "abc")
  54610. ** is considered a variable but a single-quoted string (ex: 'abc') is
  54611. ** a constant.
  54612. */
  54613. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  54614. return exprIsConst(p, 2);
  54615. }
  54616. /*
  54617. ** If the expression p codes a constant integer that is small enough
  54618. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  54619. ** in *pValue. If the expression is not an integer or if it is too big
  54620. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  54621. */
  54622. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  54623. int rc = 0;
  54624. if( p->flags & EP_IntValue ){
  54625. *pValue = p->iTable;
  54626. return 1;
  54627. }
  54628. switch( p->op ){
  54629. case TK_INTEGER: {
  54630. rc = sqlite3GetInt32((char*)p->token.z, pValue);
  54631. break;
  54632. }
  54633. case TK_UPLUS: {
  54634. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  54635. break;
  54636. }
  54637. case TK_UMINUS: {
  54638. int v;
  54639. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  54640. *pValue = -v;
  54641. rc = 1;
  54642. }
  54643. break;
  54644. }
  54645. default: break;
  54646. }
  54647. if( rc ){
  54648. p->op = TK_INTEGER;
  54649. p->flags |= EP_IntValue;
  54650. p->iTable = *pValue;
  54651. }
  54652. return rc;
  54653. }
  54654. /*
  54655. ** Return TRUE if the given string is a row-id column name.
  54656. */
  54657. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  54658. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  54659. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  54660. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  54661. return 0;
  54662. }
  54663. /*
  54664. ** Return true if the IN operator optimization is enabled and
  54665. ** the SELECT statement p exists and is of the
  54666. ** simple form:
  54667. **
  54668. ** SELECT <column> FROM <table>
  54669. **
  54670. ** If this is the case, it may be possible to use an existing table
  54671. ** or index instead of generating an epheremal table.
  54672. */
  54673. #ifndef SQLITE_OMIT_SUBQUERY
  54674. static int isCandidateForInOpt(Select *p){
  54675. SrcList *pSrc;
  54676. ExprList *pEList;
  54677. Table *pTab;
  54678. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  54679. if( p->pPrior ) return 0; /* Not a compound SELECT */
  54680. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  54681. return 0; /* No DISTINCT keyword and no aggregate functions */
  54682. }
  54683. if( p->pGroupBy ) return 0; /* Has no GROUP BY clause */
  54684. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  54685. if( p->pOffset ) return 0;
  54686. if( p->pWhere ) return 0; /* Has no WHERE clause */
  54687. pSrc = p->pSrc;
  54688. assert( pSrc!=0 );
  54689. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  54690. if( pSrc->a[0].pSelect ) return 0; /* FROM clause is not a subquery */
  54691. pTab = pSrc->a[0].pTab;
  54692. if( pTab==0 ) return 0;
  54693. if( pTab->pSelect ) return 0; /* FROM clause is not a view */
  54694. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  54695. pEList = p->pEList;
  54696. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  54697. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  54698. return 1;
  54699. }
  54700. #endif /* SQLITE_OMIT_SUBQUERY */
  54701. /*
  54702. ** This function is used by the implementation of the IN (...) operator.
  54703. ** It's job is to find or create a b-tree structure that may be used
  54704. ** either to test for membership of the (...) set or to iterate through
  54705. ** its members, skipping duplicates.
  54706. **
  54707. ** The cursor opened on the structure (database table, database index
  54708. ** or ephermal table) is stored in pX->iTable before this function returns.
  54709. ** The returned value indicates the structure type, as follows:
  54710. **
  54711. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  54712. ** IN_INDEX_INDEX - The cursor was opened on a database index.
  54713. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  54714. ** populated epheremal table.
  54715. **
  54716. ** An existing structure may only be used if the SELECT is of the simple
  54717. ** form:
  54718. **
  54719. ** SELECT <column> FROM <table>
  54720. **
  54721. ** If prNotFound parameter is 0, then the structure will be used to iterate
  54722. ** through the set members, skipping any duplicates. In this case an
  54723. ** epheremal table must be used unless the selected <column> is guaranteed
  54724. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  54725. ** is unique by virtue of a constraint or implicit index.
  54726. **
  54727. ** If the prNotFound parameter is not 0, then the structure will be used
  54728. ** for fast set membership tests. In this case an epheremal table must
  54729. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  54730. ** be found with <column> as its left-most column.
  54731. **
  54732. ** When the structure is being used for set membership tests, the user
  54733. ** needs to know whether or not the structure contains an SQL NULL
  54734. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  54735. ** If there is a chance that the structure may contain a NULL value at
  54736. ** runtime, then a register is allocated and the register number written
  54737. ** to *prNotFound. If there is no chance that the structure contains a
  54738. ** NULL value, then *prNotFound is left unchanged.
  54739. **
  54740. ** If a register is allocated and its location stored in *prNotFound, then
  54741. ** its initial value is NULL. If the structure does not remain constant
  54742. ** for the duration of the query (i.e. the set is a correlated sub-select),
  54743. ** the value of the allocated register is reset to NULL each time the
  54744. ** structure is repopulated. This allows the caller to use vdbe code
  54745. ** equivalent to the following:
  54746. **
  54747. ** if( register==NULL ){
  54748. ** has_null = <test if data structure contains null>
  54749. ** register = 1
  54750. ** }
  54751. **
  54752. ** in order to avoid running the <test if data structure contains null>
  54753. ** test more often than is necessary.
  54754. */
  54755. #ifndef SQLITE_OMIT_SUBQUERY
  54756. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  54757. Select *p;
  54758. int eType = 0;
  54759. int iTab = pParse->nTab++;
  54760. int mustBeUnique = !prNotFound;
  54761. /* The follwing if(...) expression is true if the SELECT is of the
  54762. ** simple form:
  54763. **
  54764. ** SELECT <column> FROM <table>
  54765. **
  54766. ** If this is the case, it may be possible to use an existing table
  54767. ** or index instead of generating an epheremal table.
  54768. */
  54769. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  54770. if( isCandidateForInOpt(p) ){
  54771. sqlite3 *db = pParse->db; /* Database connection */
  54772. Expr *pExpr = p->pEList->a[0].pExpr; /* Expression <column> */
  54773. int iCol = pExpr->iColumn; /* Index of column <column> */
  54774. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  54775. Table *pTab = p->pSrc->a[0].pTab; /* Table <table>. */
  54776. int iDb; /* Database idx for pTab */
  54777. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  54778. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  54779. sqlite3CodeVerifySchema(pParse, iDb);
  54780. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  54781. /* This function is only called from two places. In both cases the vdbe
  54782. ** has already been allocated. So assume sqlite3GetVdbe() is always
  54783. ** successful here.
  54784. */
  54785. assert(v);
  54786. if( iCol<0 ){
  54787. int iMem = ++pParse->nMem;
  54788. int iAddr;
  54789. sqlite3VdbeUsesBtree(v, iDb);
  54790. iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  54791. sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  54792. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  54793. eType = IN_INDEX_ROWID;
  54794. sqlite3VdbeJumpHere(v, iAddr);
  54795. }else{
  54796. Index *pIdx; /* Iterator variable */
  54797. /* The collation sequence used by the comparison. If an index is to
  54798. ** be used in place of a temp-table, it must be ordered according
  54799. ** to this collation sequence. */
  54800. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  54801. /* Check that the affinity that will be used to perform the
  54802. ** comparison is the same as the affinity of the column. If
  54803. ** it is not, it is not possible to use any index.
  54804. */
  54805. char aff = comparisonAffinity(pX);
  54806. int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
  54807. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  54808. if( (pIdx->aiColumn[0]==iCol)
  54809. && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
  54810. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  54811. ){
  54812. int iMem = ++pParse->nMem;
  54813. int iAddr;
  54814. char *pKey;
  54815. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  54816. iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  54817. sqlite3VdbeUsesBtree(v, iDb);
  54818. iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  54819. sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  54820. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  54821. pKey,P4_KEYINFO_HANDOFF);
  54822. VdbeComment((v, "%s", pIdx->zName));
  54823. eType = IN_INDEX_INDEX;
  54824. sqlite3VdbeJumpHere(v, iAddr);
  54825. if( prNotFound && !pTab->aCol[iCol].notNull ){
  54826. *prNotFound = ++pParse->nMem;
  54827. }
  54828. }
  54829. }
  54830. }
  54831. }
  54832. if( eType==0 ){
  54833. int rMayHaveNull = 0;
  54834. eType = IN_INDEX_EPH;
  54835. if( prNotFound ){
  54836. *prNotFound = rMayHaveNull = ++pParse->nMem;
  54837. }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
  54838. eType = IN_INDEX_ROWID;
  54839. }
  54840. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  54841. }else{
  54842. pX->iTable = iTab;
  54843. }
  54844. return eType;
  54845. }
  54846. #endif
  54847. /*
  54848. ** Generate code for scalar subqueries used as an expression
  54849. ** and IN operators. Examples:
  54850. **
  54851. ** (SELECT a FROM b) -- subquery
  54852. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  54853. ** x IN (4,5,11) -- IN operator with list on right-hand side
  54854. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  54855. **
  54856. ** The pExpr parameter describes the expression that contains the IN
  54857. ** operator or subquery.
  54858. **
  54859. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  54860. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  54861. ** to some integer key column of a table B-Tree. In this case, use an
  54862. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  54863. ** (slower) variable length keys B-Tree.
  54864. */
  54865. #ifndef SQLITE_OMIT_SUBQUERY
  54866. SQLITE_PRIVATE void sqlite3CodeSubselect(
  54867. Parse *pParse,
  54868. Expr *pExpr,
  54869. int rMayHaveNull,
  54870. int isRowid
  54871. ){
  54872. int testAddr = 0; /* One-time test address */
  54873. Vdbe *v = sqlite3GetVdbe(pParse);
  54874. if( v==0 ) return;
  54875. /* This code must be run in its entirety every time it is encountered
  54876. ** if any of the following is true:
  54877. **
  54878. ** * The right-hand side is a correlated subquery
  54879. ** * The right-hand side is an expression list containing variables
  54880. ** * We are inside a trigger
  54881. **
  54882. ** If all of the above are false, then we can run this code just once
  54883. ** save the results, and reuse the same result on subsequent invocations.
  54884. */
  54885. if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
  54886. int mem = ++pParse->nMem;
  54887. sqlite3VdbeAddOp1(v, OP_If, mem);
  54888. testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
  54889. assert( testAddr>0 || pParse->db->mallocFailed );
  54890. }
  54891. switch( pExpr->op ){
  54892. case TK_IN: {
  54893. char affinity;
  54894. KeyInfo keyInfo;
  54895. int addr; /* Address of OP_OpenEphemeral instruction */
  54896. Expr *pLeft = pExpr->pLeft;
  54897. if( rMayHaveNull ){
  54898. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  54899. }
  54900. affinity = sqlite3ExprAffinity(pLeft);
  54901. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  54902. ** expression it is handled the same way. A virtual table is
  54903. ** filled with single-field index keys representing the results
  54904. ** from the SELECT or the <exprlist>.
  54905. **
  54906. ** If the 'x' expression is a column value, or the SELECT...
  54907. ** statement returns a column value, then the affinity of that
  54908. ** column is used to build the index keys. If both 'x' and the
  54909. ** SELECT... statement are columns, then numeric affinity is used
  54910. ** if either column has NUMERIC or INTEGER affinity. If neither
  54911. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  54912. ** is used.
  54913. */
  54914. pExpr->iTable = pParse->nTab++;
  54915. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  54916. memset(&keyInfo, 0, sizeof(keyInfo));
  54917. keyInfo.nField = 1;
  54918. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  54919. /* Case 1: expr IN (SELECT ...)
  54920. **
  54921. ** Generate code to write the results of the select into the temporary
  54922. ** table allocated and opened above.
  54923. */
  54924. SelectDest dest;
  54925. ExprList *pEList;
  54926. assert( !isRowid );
  54927. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  54928. dest.affinity = (u8)affinity;
  54929. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  54930. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  54931. return;
  54932. }
  54933. pEList = pExpr->x.pSelect->pEList;
  54934. if( pEList && pEList->nExpr>0 ){
  54935. keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  54936. pEList->a[0].pExpr);
  54937. }
  54938. }else if( pExpr->x.pList ){
  54939. /* Case 2: expr IN (exprlist)
  54940. **
  54941. ** For each expression, build an index key from the evaluation and
  54942. ** store it in the temporary table. If <expr> is a column, then use
  54943. ** that columns affinity when building index keys. If <expr> is not
  54944. ** a column, use numeric affinity.
  54945. */
  54946. int i;
  54947. ExprList *pList = pExpr->x.pList;
  54948. struct ExprList_item *pItem;
  54949. int r1, r2, r3;
  54950. if( !affinity ){
  54951. affinity = SQLITE_AFF_NONE;
  54952. }
  54953. keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  54954. /* Loop through each expression in <exprlist>. */
  54955. r1 = sqlite3GetTempReg(pParse);
  54956. r2 = sqlite3GetTempReg(pParse);
  54957. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  54958. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  54959. Expr *pE2 = pItem->pExpr;
  54960. /* If the expression is not constant then we will need to
  54961. ** disable the test that was generated above that makes sure
  54962. ** this code only executes once. Because for a non-constant
  54963. ** expression we need to rerun this code each time.
  54964. */
  54965. if( testAddr && !sqlite3ExprIsConstant(pE2) ){
  54966. sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
  54967. testAddr = 0;
  54968. }
  54969. /* Evaluate the expression and insert it into the temp table */
  54970. pParse->disableColCache++;
  54971. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  54972. assert( pParse->disableColCache>0 );
  54973. pParse->disableColCache--;
  54974. if( isRowid ){
  54975. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
  54976. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  54977. }else{
  54978. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  54979. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  54980. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  54981. }
  54982. }
  54983. sqlite3ReleaseTempReg(pParse, r1);
  54984. sqlite3ReleaseTempReg(pParse, r2);
  54985. }
  54986. if( !isRowid ){
  54987. sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
  54988. }
  54989. break;
  54990. }
  54991. case TK_EXISTS:
  54992. case TK_SELECT: {
  54993. /* This has to be a scalar SELECT. Generate code to put the
  54994. ** value of this select in a memory cell and record the number
  54995. ** of the memory cell in iColumn.
  54996. */
  54997. static const Token one = { (u8*)"1", 0, 1 };
  54998. Select *pSel;
  54999. SelectDest dest;
  55000. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  55001. pSel = pExpr->x.pSelect;
  55002. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  55003. if( pExpr->op==TK_SELECT ){
  55004. dest.eDest = SRT_Mem;
  55005. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
  55006. VdbeComment((v, "Init subquery result"));
  55007. }else{
  55008. dest.eDest = SRT_Exists;
  55009. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
  55010. VdbeComment((v, "Init EXISTS result"));
  55011. }
  55012. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  55013. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
  55014. if( sqlite3Select(pParse, pSel, &dest) ){
  55015. return;
  55016. }
  55017. pExpr->iColumn = dest.iParm;
  55018. break;
  55019. }
  55020. }
  55021. if( testAddr ){
  55022. sqlite3VdbeJumpHere(v, testAddr-1);
  55023. }
  55024. return;
  55025. }
  55026. #endif /* SQLITE_OMIT_SUBQUERY */
  55027. /*
  55028. ** Duplicate an 8-byte value
  55029. */
  55030. static char *dup8bytes(Vdbe *v, const char *in){
  55031. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  55032. if( out ){
  55033. memcpy(out, in, 8);
  55034. }
  55035. return out;
  55036. }
  55037. /*
  55038. ** Generate an instruction that will put the floating point
  55039. ** value described by z[0..n-1] into register iMem.
  55040. **
  55041. ** The z[] string will probably not be zero-terminated. But the
  55042. ** z[n] character is guaranteed to be something that does not look
  55043. ** like the continuation of the number.
  55044. */
  55045. static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
  55046. assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
  55047. assert( !z || !sqlite3Isdigit(z[n]) );
  55048. UNUSED_PARAMETER(n);
  55049. if( z ){
  55050. double value;
  55051. char *zV;
  55052. sqlite3AtoF(z, &value);
  55053. if( sqlite3IsNaN(value) ){
  55054. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
  55055. }else{
  55056. if( negateFlag ) value = -value;
  55057. zV = dup8bytes(v, (char*)&value);
  55058. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  55059. }
  55060. }
  55061. }
  55062. /*
  55063. ** Generate an instruction that will put the integer describe by
  55064. ** text z[0..n-1] into register iMem.
  55065. **
  55066. ** The z[] string will probably not be zero-terminated. But the
  55067. ** z[n] character is guaranteed to be something that does not look
  55068. ** like the continuation of the number.
  55069. */
  55070. static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
  55071. const char *z;
  55072. if( pExpr->flags & EP_IntValue ){
  55073. int i = pExpr->iTable;
  55074. if( negFlag ) i = -i;
  55075. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  55076. }else if( (z = (char*)pExpr->token.z)!=0 ){
  55077. int i;
  55078. int n = pExpr->token.n;
  55079. assert( !sqlite3Isdigit(z[n]) );
  55080. if( sqlite3GetInt32(z, &i) ){
  55081. if( negFlag ) i = -i;
  55082. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  55083. }else if( sqlite3FitsIn64Bits(z, negFlag) ){
  55084. i64 value;
  55085. char *zV;
  55086. sqlite3Atoi64(z, &value);
  55087. if( negFlag ) value = -value;
  55088. zV = dup8bytes(v, (char*)&value);
  55089. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  55090. }else{
  55091. codeReal(v, z, n, negFlag, iMem);
  55092. }
  55093. }
  55094. }
  55095. /*
  55096. ** Generate code that will extract the iColumn-th column from
  55097. ** table pTab and store the column value in a register. An effort
  55098. ** is made to store the column value in register iReg, but this is
  55099. ** not guaranteed. The location of the column value is returned.
  55100. **
  55101. ** There must be an open cursor to pTab in iTable when this routine
  55102. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  55103. **
  55104. ** This routine might attempt to reuse the value of the column that
  55105. ** has already been loaded into a register. The value will always
  55106. ** be used if it has not undergone any affinity changes. But if
  55107. ** an affinity change has occurred, then the cached value will only be
  55108. ** used if allowAffChng is true.
  55109. */
  55110. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  55111. Parse *pParse, /* Parsing and code generating context */
  55112. Table *pTab, /* Description of the table we are reading from */
  55113. int iColumn, /* Index of the table column */
  55114. int iTable, /* The cursor pointing to the table */
  55115. int iReg, /* Store results here */
  55116. int allowAffChng /* True if prior affinity changes are OK */
  55117. ){
  55118. Vdbe *v = pParse->pVdbe;
  55119. int i;
  55120. struct yColCache *p;
  55121. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  55122. if( p->iTable==iTable && p->iColumn==iColumn
  55123. && (!p->affChange || allowAffChng) ){
  55124. #if 0
  55125. sqlite3VdbeAddOp0(v, OP_Noop);
  55126. VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
  55127. #endif
  55128. return p->iReg;
  55129. }
  55130. }
  55131. assert( v!=0 );
  55132. if( iColumn<0 ){
  55133. int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
  55134. sqlite3VdbeAddOp2(v, op, iTable, iReg);
  55135. }else if( pTab==0 ){
  55136. sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
  55137. }else{
  55138. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  55139. sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
  55140. sqlite3ColumnDefault(v, pTab, iColumn);
  55141. #ifndef SQLITE_OMIT_FLOATING_POINT
  55142. if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
  55143. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  55144. }
  55145. #endif
  55146. }
  55147. if( pParse->disableColCache==0 ){
  55148. i = pParse->iColCache;
  55149. p = &pParse->aColCache[i];
  55150. p->iTable = iTable;
  55151. p->iColumn = iColumn;
  55152. p->iReg = iReg;
  55153. p->affChange = 0;
  55154. i++;
  55155. if( i>=ArraySize(pParse->aColCache) ) i = 0;
  55156. if( i>pParse->nColCache ) pParse->nColCache = i;
  55157. pParse->iColCache = i;
  55158. }
  55159. return iReg;
  55160. }
  55161. /*
  55162. ** Clear all column cache entries associated with the vdbe
  55163. ** cursor with cursor number iTable.
  55164. */
  55165. SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
  55166. if( iTable<0 ){
  55167. pParse->nColCache = 0;
  55168. pParse->iColCache = 0;
  55169. }else{
  55170. int i;
  55171. for(i=0; i<pParse->nColCache; i++){
  55172. if( pParse->aColCache[i].iTable==iTable ){
  55173. testcase( i==pParse->nColCache-1 );
  55174. pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
  55175. pParse->iColCache = pParse->nColCache;
  55176. }
  55177. }
  55178. }
  55179. }
  55180. /*
  55181. ** Record the fact that an affinity change has occurred on iCount
  55182. ** registers starting with iStart.
  55183. */
  55184. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  55185. int iEnd = iStart + iCount - 1;
  55186. int i;
  55187. for(i=0; i<pParse->nColCache; i++){
  55188. int r = pParse->aColCache[i].iReg;
  55189. if( r>=iStart && r<=iEnd ){
  55190. pParse->aColCache[i].affChange = 1;
  55191. }
  55192. }
  55193. }
  55194. /*
  55195. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  55196. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  55197. */
  55198. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  55199. int i;
  55200. if( iFrom==iTo ) return;
  55201. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  55202. for(i=0; i<pParse->nColCache; i++){
  55203. int x = pParse->aColCache[i].iReg;
  55204. if( x>=iFrom && x<iFrom+nReg ){
  55205. pParse->aColCache[i].iReg += iTo-iFrom;
  55206. }
  55207. }
  55208. }
  55209. /*
  55210. ** Generate code to copy content from registers iFrom...iFrom+nReg-1
  55211. ** over to iTo..iTo+nReg-1.
  55212. */
  55213. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
  55214. int i;
  55215. if( iFrom==iTo ) return;
  55216. for(i=0; i<nReg; i++){
  55217. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
  55218. }
  55219. }
  55220. /*
  55221. ** Return true if any register in the range iFrom..iTo (inclusive)
  55222. ** is used as part of the column cache.
  55223. */
  55224. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  55225. int i;
  55226. for(i=0; i<pParse->nColCache; i++){
  55227. int r = pParse->aColCache[i].iReg;
  55228. if( r>=iFrom && r<=iTo ) return 1;
  55229. }
  55230. return 0;
  55231. }
  55232. /*
  55233. ** There is a value in register iReg.
  55234. **
  55235. ** We are going to modify the value, so we need to make sure it
  55236. ** is not a cached register. If iReg is a cached register,
  55237. ** then clear the corresponding cache line.
  55238. */
  55239. SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse *pParse, int iReg){
  55240. int i;
  55241. if( usedAsColumnCache(pParse, iReg, iReg) ){
  55242. for(i=0; i<pParse->nColCache; i++){
  55243. if( pParse->aColCache[i].iReg==iReg ){
  55244. pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
  55245. pParse->iColCache = pParse->nColCache;
  55246. }
  55247. }
  55248. }
  55249. }
  55250. /*
  55251. ** If the last instruction coded is an ephemeral copy of any of
  55252. ** the registers in the nReg registers beginning with iReg, then
  55253. ** convert the last instruction from OP_SCopy to OP_Copy.
  55254. */
  55255. SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
  55256. int addr;
  55257. VdbeOp *pOp;
  55258. Vdbe *v;
  55259. v = pParse->pVdbe;
  55260. addr = sqlite3VdbeCurrentAddr(v);
  55261. pOp = sqlite3VdbeGetOp(v, addr-1);
  55262. assert( pOp || pParse->db->mallocFailed );
  55263. if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
  55264. pOp->opcode = OP_Copy;
  55265. }
  55266. }
  55267. /*
  55268. ** Generate code to store the value of the iAlias-th alias in register
  55269. ** target. The first time this is called, pExpr is evaluated to compute
  55270. ** the value of the alias. The value is stored in an auxiliary register
  55271. ** and the number of that register is returned. On subsequent calls,
  55272. ** the register number is returned without generating any code.
  55273. **
  55274. ** Note that in order for this to work, code must be generated in the
  55275. ** same order that it is executed.
  55276. **
  55277. ** Aliases are numbered starting with 1. So iAlias is in the range
  55278. ** of 1 to pParse->nAlias inclusive.
  55279. **
  55280. ** pParse->aAlias[iAlias-1] records the register number where the value
  55281. ** of the iAlias-th alias is stored. If zero, that means that the
  55282. ** alias has not yet been computed.
  55283. */
  55284. static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
  55285. sqlite3 *db = pParse->db;
  55286. int iReg;
  55287. if( pParse->nAliasAlloc<pParse->nAlias ){
  55288. pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
  55289. sizeof(pParse->aAlias[0])*pParse->nAlias );
  55290. testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
  55291. if( db->mallocFailed ) return 0;
  55292. memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
  55293. (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
  55294. pParse->nAliasAlloc = pParse->nAlias;
  55295. }
  55296. assert( iAlias>0 && iAlias<=pParse->nAlias );
  55297. iReg = pParse->aAlias[iAlias-1];
  55298. if( iReg==0 ){
  55299. if( pParse->disableColCache ){
  55300. iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  55301. }else{
  55302. iReg = ++pParse->nMem;
  55303. sqlite3ExprCode(pParse, pExpr, iReg);
  55304. pParse->aAlias[iAlias-1] = iReg;
  55305. }
  55306. }
  55307. return iReg;
  55308. }
  55309. /*
  55310. ** Generate code into the current Vdbe to evaluate the given
  55311. ** expression. Attempt to store the results in register "target".
  55312. ** Return the register where results are stored.
  55313. **
  55314. ** With this routine, there is no guarantee that results will
  55315. ** be stored in target. The result might be stored in some other
  55316. ** register if it is convenient to do so. The calling function
  55317. ** must check the return code and move the results to the desired
  55318. ** register.
  55319. */
  55320. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  55321. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  55322. int op; /* The opcode being coded */
  55323. int inReg = target; /* Results stored in register inReg */
  55324. int regFree1 = 0; /* If non-zero free this temporary register */
  55325. int regFree2 = 0; /* If non-zero free this temporary register */
  55326. int r1, r2, r3, r4; /* Various register numbers */
  55327. sqlite3 *db;
  55328. db = pParse->db;
  55329. assert( v!=0 || db->mallocFailed );
  55330. assert( target>0 && target<=pParse->nMem );
  55331. if( v==0 ) return 0;
  55332. if( pExpr==0 ){
  55333. op = TK_NULL;
  55334. }else{
  55335. op = pExpr->op;
  55336. }
  55337. switch( op ){
  55338. case TK_AGG_COLUMN: {
  55339. AggInfo *pAggInfo = pExpr->pAggInfo;
  55340. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  55341. if( !pAggInfo->directMode ){
  55342. assert( pCol->iMem>0 );
  55343. inReg = pCol->iMem;
  55344. break;
  55345. }else if( pAggInfo->useSortingIdx ){
  55346. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
  55347. pCol->iSorterColumn, target);
  55348. break;
  55349. }
  55350. /* Otherwise, fall thru into the TK_COLUMN case */
  55351. }
  55352. case TK_COLUMN: {
  55353. if( pExpr->iTable<0 ){
  55354. /* This only happens when coding check constraints */
  55355. assert( pParse->ckBase>0 );
  55356. inReg = pExpr->iColumn + pParse->ckBase;
  55357. }else{
  55358. testcase( (pExpr->flags & EP_AnyAff)!=0 );
  55359. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  55360. pExpr->iColumn, pExpr->iTable, target,
  55361. pExpr->flags & EP_AnyAff);
  55362. }
  55363. break;
  55364. }
  55365. case TK_INTEGER: {
  55366. codeInteger(v, pExpr, 0, target);
  55367. break;
  55368. }
  55369. case TK_FLOAT: {
  55370. codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
  55371. break;
  55372. }
  55373. case TK_STRING: {
  55374. sqlite3DequoteExpr(pExpr);
  55375. sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
  55376. (char*)pExpr->token.z, pExpr->token.n);
  55377. break;
  55378. }
  55379. case TK_NULL: {
  55380. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  55381. break;
  55382. }
  55383. #ifndef SQLITE_OMIT_BLOB_LITERAL
  55384. case TK_BLOB: {
  55385. int n;
  55386. const char *z;
  55387. char *zBlob;
  55388. assert( pExpr->token.n>=3 );
  55389. assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
  55390. assert( pExpr->token.z[1]=='\'' );
  55391. assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
  55392. n = pExpr->token.n - 3;
  55393. z = (char*)pExpr->token.z + 2;
  55394. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  55395. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  55396. break;
  55397. }
  55398. #endif
  55399. case TK_VARIABLE: {
  55400. int iPrior;
  55401. VdbeOp *pOp;
  55402. if( pExpr->token.n<=1
  55403. && (iPrior = sqlite3VdbeCurrentAddr(v)-1)>=0
  55404. && (pOp = sqlite3VdbeGetOp(v, iPrior))->opcode==OP_Variable
  55405. && pOp->p1+pOp->p3==pExpr->iTable
  55406. && pOp->p2+pOp->p3==target
  55407. && pOp->p4.z==0
  55408. ){
  55409. /* If the previous instruction was a copy of the previous unnamed
  55410. ** parameter into the previous register, then simply increment the
  55411. ** repeat count on the prior instruction rather than making a new
  55412. ** instruction.
  55413. */
  55414. pOp->p3++;
  55415. }else{
  55416. sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iTable, target, 1);
  55417. if( pExpr->token.n>1 ){
  55418. sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
  55419. }
  55420. }
  55421. break;
  55422. }
  55423. case TK_REGISTER: {
  55424. inReg = pExpr->iTable;
  55425. break;
  55426. }
  55427. case TK_AS: {
  55428. inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
  55429. break;
  55430. }
  55431. #ifndef SQLITE_OMIT_CAST
  55432. case TK_CAST: {
  55433. /* Expressions of the form: CAST(pLeft AS token) */
  55434. int aff, to_op;
  55435. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  55436. aff = sqlite3AffinityType(&pExpr->token);
  55437. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  55438. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  55439. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  55440. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  55441. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  55442. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  55443. testcase( to_op==OP_ToText );
  55444. testcase( to_op==OP_ToBlob );
  55445. testcase( to_op==OP_ToNumeric );
  55446. testcase( to_op==OP_ToInt );
  55447. testcase( to_op==OP_ToReal );
  55448. if( inReg!=target ){
  55449. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  55450. inReg = target;
  55451. }
  55452. sqlite3VdbeAddOp1(v, to_op, inReg);
  55453. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  55454. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  55455. break;
  55456. }
  55457. #endif /* SQLITE_OMIT_CAST */
  55458. case TK_LT:
  55459. case TK_LE:
  55460. case TK_GT:
  55461. case TK_GE:
  55462. case TK_NE:
  55463. case TK_EQ: {
  55464. assert( TK_LT==OP_Lt );
  55465. assert( TK_LE==OP_Le );
  55466. assert( TK_GT==OP_Gt );
  55467. assert( TK_GE==OP_Ge );
  55468. assert( TK_EQ==OP_Eq );
  55469. assert( TK_NE==OP_Ne );
  55470. testcase( op==TK_LT );
  55471. testcase( op==TK_LE );
  55472. testcase( op==TK_GT );
  55473. testcase( op==TK_GE );
  55474. testcase( op==TK_EQ );
  55475. testcase( op==TK_NE );
  55476. codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
  55477. pExpr->pRight, &r2, &regFree2);
  55478. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  55479. r1, r2, inReg, SQLITE_STOREP2);
  55480. testcase( regFree1==0 );
  55481. testcase( regFree2==0 );
  55482. break;
  55483. }
  55484. case TK_AND:
  55485. case TK_OR:
  55486. case TK_PLUS:
  55487. case TK_STAR:
  55488. case TK_MINUS:
  55489. case TK_REM:
  55490. case TK_BITAND:
  55491. case TK_BITOR:
  55492. case TK_SLASH:
  55493. case TK_LSHIFT:
  55494. case TK_RSHIFT:
  55495. case TK_CONCAT: {
  55496. assert( TK_AND==OP_And );
  55497. assert( TK_OR==OP_Or );
  55498. assert( TK_PLUS==OP_Add );
  55499. assert( TK_MINUS==OP_Subtract );
  55500. assert( TK_REM==OP_Remainder );
  55501. assert( TK_BITAND==OP_BitAnd );
  55502. assert( TK_BITOR==OP_BitOr );
  55503. assert( TK_SLASH==OP_Divide );
  55504. assert( TK_LSHIFT==OP_ShiftLeft );
  55505. assert( TK_RSHIFT==OP_ShiftRight );
  55506. assert( TK_CONCAT==OP_Concat );
  55507. testcase( op==TK_AND );
  55508. testcase( op==TK_OR );
  55509. testcase( op==TK_PLUS );
  55510. testcase( op==TK_MINUS );
  55511. testcase( op==TK_REM );
  55512. testcase( op==TK_BITAND );
  55513. testcase( op==TK_BITOR );
  55514. testcase( op==TK_SLASH );
  55515. testcase( op==TK_LSHIFT );
  55516. testcase( op==TK_RSHIFT );
  55517. testcase( op==TK_CONCAT );
  55518. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  55519. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  55520. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  55521. testcase( regFree1==0 );
  55522. testcase( regFree2==0 );
  55523. break;
  55524. }
  55525. case TK_UMINUS: {
  55526. Expr *pLeft = pExpr->pLeft;
  55527. assert( pLeft );
  55528. if( pLeft->op==TK_FLOAT ){
  55529. codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
  55530. }else if( pLeft->op==TK_INTEGER ){
  55531. codeInteger(v, pLeft, 1, target);
  55532. }else{
  55533. regFree1 = r1 = sqlite3GetTempReg(pParse);
  55534. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  55535. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  55536. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  55537. testcase( regFree2==0 );
  55538. }
  55539. inReg = target;
  55540. break;
  55541. }
  55542. case TK_BITNOT:
  55543. case TK_NOT: {
  55544. assert( TK_BITNOT==OP_BitNot );
  55545. assert( TK_NOT==OP_Not );
  55546. testcase( op==TK_BITNOT );
  55547. testcase( op==TK_NOT );
  55548. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  55549. testcase( regFree1==0 );
  55550. inReg = target;
  55551. sqlite3VdbeAddOp2(v, op, r1, inReg);
  55552. break;
  55553. }
  55554. case TK_ISNULL:
  55555. case TK_NOTNULL: {
  55556. int addr;
  55557. assert( TK_ISNULL==OP_IsNull );
  55558. assert( TK_NOTNULL==OP_NotNull );
  55559. testcase( op==TK_ISNULL );
  55560. testcase( op==TK_NOTNULL );
  55561. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  55562. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  55563. testcase( regFree1==0 );
  55564. addr = sqlite3VdbeAddOp1(v, op, r1);
  55565. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  55566. sqlite3VdbeJumpHere(v, addr);
  55567. break;
  55568. }
  55569. case TK_AGG_FUNCTION: {
  55570. AggInfo *pInfo = pExpr->pAggInfo;
  55571. if( pInfo==0 ){
  55572. sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
  55573. &pExpr->span);
  55574. }else{
  55575. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  55576. }
  55577. break;
  55578. }
  55579. case TK_CONST_FUNC:
  55580. case TK_FUNCTION: {
  55581. ExprList *pFarg; /* List of function arguments */
  55582. int nFarg; /* Number of function arguments */
  55583. FuncDef *pDef; /* The function definition object */
  55584. int nId; /* Length of the function name in bytes */
  55585. const char *zId; /* The function name */
  55586. int constMask = 0; /* Mask of function arguments that are constant */
  55587. int i; /* Loop counter */
  55588. u8 enc = ENC(db); /* The text encoding used by this database */
  55589. CollSeq *pColl = 0; /* A collating sequence */
  55590. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  55591. testcase( op==TK_CONST_FUNC );
  55592. testcase( op==TK_FUNCTION );
  55593. if( ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_SpanToken) ){
  55594. pFarg = 0;
  55595. }else{
  55596. pFarg = pExpr->x.pList;
  55597. }
  55598. nFarg = pFarg ? pFarg->nExpr : 0;
  55599. zId = (char*)pExpr->token.z;
  55600. nId = pExpr->token.n;
  55601. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  55602. assert( pDef!=0 );
  55603. if( pFarg ){
  55604. r1 = sqlite3GetTempRange(pParse, nFarg);
  55605. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  55606. }else{
  55607. r1 = 0;
  55608. }
  55609. #ifndef SQLITE_OMIT_VIRTUALTABLE
  55610. /* Possibly overload the function if the first argument is
  55611. ** a virtual table column.
  55612. **
  55613. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  55614. ** second argument, not the first, as the argument to test to
  55615. ** see if it is a column in a virtual table. This is done because
  55616. ** the left operand of infix functions (the operand we want to
  55617. ** control overloading) ends up as the second argument to the
  55618. ** function. The expression "A glob B" is equivalent to
  55619. ** "glob(B,A). We want to use the A in "A glob B" to test
  55620. ** for function overloading. But we use the B term in "glob(B,A)".
  55621. */
  55622. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  55623. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  55624. }else if( nFarg>0 ){
  55625. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  55626. }
  55627. #endif
  55628. for(i=0; i<nFarg && i<32; i++){
  55629. if( sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  55630. constMask |= (1<<i);
  55631. }
  55632. if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  55633. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  55634. }
  55635. }
  55636. if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
  55637. if( !pColl ) pColl = db->pDfltColl;
  55638. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  55639. }
  55640. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  55641. (char*)pDef, P4_FUNCDEF);
  55642. sqlite3VdbeChangeP5(v, (u8)nFarg);
  55643. if( nFarg ){
  55644. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  55645. }
  55646. sqlite3ExprCacheAffinityChange(pParse, r1, nFarg);
  55647. break;
  55648. }
  55649. #ifndef SQLITE_OMIT_SUBQUERY
  55650. case TK_EXISTS:
  55651. case TK_SELECT: {
  55652. testcase( op==TK_EXISTS );
  55653. testcase( op==TK_SELECT );
  55654. if( pExpr->iColumn==0 ){
  55655. sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  55656. }
  55657. inReg = pExpr->iColumn;
  55658. break;
  55659. }
  55660. case TK_IN: {
  55661. int rNotFound = 0;
  55662. int rMayHaveNull = 0;
  55663. int j2, j3, j4, j5;
  55664. char affinity;
  55665. int eType;
  55666. VdbeNoopComment((v, "begin IN expr r%d", target));
  55667. eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
  55668. if( rMayHaveNull ){
  55669. rNotFound = ++pParse->nMem;
  55670. }
  55671. /* Figure out the affinity to use to create a key from the results
  55672. ** of the expression. affinityStr stores a static string suitable for
  55673. ** P4 of OP_MakeRecord.
  55674. */
  55675. affinity = comparisonAffinity(pExpr);
  55676. /* Code the <expr> from "<expr> IN (...)". The temporary table
  55677. ** pExpr->iTable contains the values that make up the (...) set.
  55678. */
  55679. pParse->disableColCache++;
  55680. sqlite3ExprCode(pParse, pExpr->pLeft, target);
  55681. pParse->disableColCache--;
  55682. j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
  55683. if( eType==IN_INDEX_ROWID ){
  55684. j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
  55685. j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
  55686. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  55687. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  55688. sqlite3VdbeJumpHere(v, j3);
  55689. sqlite3VdbeJumpHere(v, j4);
  55690. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  55691. }else{
  55692. r2 = regFree2 = sqlite3GetTempReg(pParse);
  55693. /* Create a record and test for set membership. If the set contains
  55694. ** the value, then jump to the end of the test code. The target
  55695. ** register still contains the true (1) value written to it earlier.
  55696. */
  55697. sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
  55698. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  55699. j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
  55700. /* If the set membership test fails, then the result of the
  55701. ** "x IN (...)" expression must be either 0 or NULL. If the set
  55702. ** contains no NULL values, then the result is 0. If the set
  55703. ** contains one or more NULL values, then the result of the
  55704. ** expression is also NULL.
  55705. */
  55706. if( rNotFound==0 ){
  55707. /* This branch runs if it is known at compile time (now) that
  55708. ** the set contains no NULL values. This happens as the result
  55709. ** of a "NOT NULL" constraint in the database schema. No need
  55710. ** to test the data structure at runtime in this case.
  55711. */
  55712. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  55713. }else{
  55714. /* This block populates the rNotFound register with either NULL
  55715. ** or 0 (an integer value). If the data structure contains one
  55716. ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
  55717. ** to 0. If register rMayHaveNull is already set to some value
  55718. ** other than NULL, then the test has already been run and
  55719. ** rNotFound is already populated.
  55720. */
  55721. static const char nullRecord[] = { 0x02, 0x00 };
  55722. j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
  55723. sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
  55724. sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0,
  55725. nullRecord, P4_STATIC);
  55726. j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
  55727. sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
  55728. sqlite3VdbeJumpHere(v, j4);
  55729. sqlite3VdbeJumpHere(v, j3);
  55730. /* Copy the value of register rNotFound (which is either NULL or 0)
  55731. ** into the target register. This will be the result of the
  55732. ** expression.
  55733. */
  55734. sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
  55735. }
  55736. }
  55737. sqlite3VdbeJumpHere(v, j2);
  55738. sqlite3VdbeJumpHere(v, j5);
  55739. VdbeComment((v, "end IN expr r%d", target));
  55740. break;
  55741. }
  55742. #endif
  55743. /*
  55744. ** x BETWEEN y AND z
  55745. **
  55746. ** This is equivalent to
  55747. **
  55748. ** x>=y AND x<=z
  55749. **
  55750. ** X is stored in pExpr->pLeft.
  55751. ** Y is stored in pExpr->pList->a[0].pExpr.
  55752. ** Z is stored in pExpr->pList->a[1].pExpr.
  55753. */
  55754. case TK_BETWEEN: {
  55755. Expr *pLeft = pExpr->pLeft;
  55756. struct ExprList_item *pLItem = pExpr->x.pList->a;
  55757. Expr *pRight = pLItem->pExpr;
  55758. codeCompareOperands(pParse, pLeft, &r1, &regFree1,
  55759. pRight, &r2, &regFree2);
  55760. testcase( regFree1==0 );
  55761. testcase( regFree2==0 );
  55762. r3 = sqlite3GetTempReg(pParse);
  55763. r4 = sqlite3GetTempReg(pParse);
  55764. codeCompare(pParse, pLeft, pRight, OP_Ge,
  55765. r1, r2, r3, SQLITE_STOREP2);
  55766. pLItem++;
  55767. pRight = pLItem->pExpr;
  55768. sqlite3ReleaseTempReg(pParse, regFree2);
  55769. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  55770. testcase( regFree2==0 );
  55771. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  55772. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  55773. sqlite3ReleaseTempReg(pParse, r3);
  55774. sqlite3ReleaseTempReg(pParse, r4);
  55775. break;
  55776. }
  55777. case TK_UPLUS: {
  55778. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  55779. break;
  55780. }
  55781. /*
  55782. ** Form A:
  55783. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  55784. **
  55785. ** Form B:
  55786. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  55787. **
  55788. ** Form A is can be transformed into the equivalent form B as follows:
  55789. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  55790. ** WHEN x=eN THEN rN ELSE y END
  55791. **
  55792. ** X (if it exists) is in pExpr->pLeft.
  55793. ** Y is in pExpr->pRight. The Y is also optional. If there is no
  55794. ** ELSE clause and no other term matches, then the result of the
  55795. ** exprssion is NULL.
  55796. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  55797. **
  55798. ** The result of the expression is the Ri for the first matching Ei,
  55799. ** or if there is no matching Ei, the ELSE term Y, or if there is
  55800. ** no ELSE term, NULL.
  55801. */
  55802. case TK_CASE: {
  55803. int endLabel; /* GOTO label for end of CASE stmt */
  55804. int nextCase; /* GOTO label for next WHEN clause */
  55805. int nExpr; /* 2x number of WHEN terms */
  55806. int i; /* Loop counter */
  55807. ExprList *pEList; /* List of WHEN terms */
  55808. struct ExprList_item *aListelem; /* Array of WHEN terms */
  55809. Expr opCompare; /* The X==Ei expression */
  55810. Expr cacheX; /* Cached expression X */
  55811. Expr *pX; /* The X expression */
  55812. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  55813. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  55814. assert((pExpr->x.pList->nExpr % 2) == 0);
  55815. assert(pExpr->x.pList->nExpr > 0);
  55816. pEList = pExpr->x.pList;
  55817. aListelem = pEList->a;
  55818. nExpr = pEList->nExpr;
  55819. endLabel = sqlite3VdbeMakeLabel(v);
  55820. if( (pX = pExpr->pLeft)!=0 ){
  55821. cacheX = *pX;
  55822. testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
  55823. cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
  55824. testcase( regFree1==0 );
  55825. cacheX.op = TK_REGISTER;
  55826. opCompare.op = TK_EQ;
  55827. opCompare.pLeft = &cacheX;
  55828. pTest = &opCompare;
  55829. }
  55830. pParse->disableColCache++;
  55831. for(i=0; i<nExpr; i=i+2){
  55832. if( pX ){
  55833. assert( pTest!=0 );
  55834. opCompare.pRight = aListelem[i].pExpr;
  55835. }else{
  55836. pTest = aListelem[i].pExpr;
  55837. }
  55838. nextCase = sqlite3VdbeMakeLabel(v);
  55839. testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
  55840. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  55841. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  55842. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  55843. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  55844. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  55845. sqlite3VdbeResolveLabel(v, nextCase);
  55846. }
  55847. if( pExpr->pRight ){
  55848. sqlite3ExprCode(pParse, pExpr->pRight, target);
  55849. }else{
  55850. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  55851. }
  55852. sqlite3VdbeResolveLabel(v, endLabel);
  55853. assert( pParse->disableColCache>0 );
  55854. pParse->disableColCache--;
  55855. break;
  55856. }
  55857. #ifndef SQLITE_OMIT_TRIGGER
  55858. case TK_RAISE: {
  55859. if( !pParse->trigStack ){
  55860. sqlite3ErrorMsg(pParse,
  55861. "RAISE() may only be used within a trigger-program");
  55862. return 0;
  55863. }
  55864. if( pExpr->affinity!=OE_Ignore ){
  55865. assert( pExpr->affinity==OE_Rollback ||
  55866. pExpr->affinity == OE_Abort ||
  55867. pExpr->affinity == OE_Fail );
  55868. sqlite3DequoteExpr(pExpr);
  55869. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->affinity, 0,
  55870. (char*)pExpr->token.z, pExpr->token.n);
  55871. } else {
  55872. assert( pExpr->affinity == OE_Ignore );
  55873. sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
  55874. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
  55875. VdbeComment((v, "raise(IGNORE)"));
  55876. }
  55877. break;
  55878. }
  55879. #endif
  55880. }
  55881. sqlite3ReleaseTempReg(pParse, regFree1);
  55882. sqlite3ReleaseTempReg(pParse, regFree2);
  55883. return inReg;
  55884. }
  55885. /*
  55886. ** Generate code to evaluate an expression and store the results
  55887. ** into a register. Return the register number where the results
  55888. ** are stored.
  55889. **
  55890. ** If the register is a temporary register that can be deallocated,
  55891. ** then write its number into *pReg. If the result register is not
  55892. ** a temporary, then set *pReg to zero.
  55893. */
  55894. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  55895. int r1 = sqlite3GetTempReg(pParse);
  55896. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  55897. if( r2==r1 ){
  55898. *pReg = r1;
  55899. }else{
  55900. sqlite3ReleaseTempReg(pParse, r1);
  55901. *pReg = 0;
  55902. }
  55903. return r2;
  55904. }
  55905. /*
  55906. ** Generate code that will evaluate expression pExpr and store the
  55907. ** results in register target. The results are guaranteed to appear
  55908. ** in register target.
  55909. */
  55910. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  55911. int inReg;
  55912. assert( target>0 && target<=pParse->nMem );
  55913. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  55914. assert( pParse->pVdbe || pParse->db->mallocFailed );
  55915. if( inReg!=target && pParse->pVdbe ){
  55916. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  55917. }
  55918. return target;
  55919. }
  55920. /*
  55921. ** Generate code that evalutes the given expression and puts the result
  55922. ** in register target.
  55923. **
  55924. ** Also make a copy of the expression results into another "cache" register
  55925. ** and modify the expression so that the next time it is evaluated,
  55926. ** the result is a copy of the cache register.
  55927. **
  55928. ** This routine is used for expressions that are used multiple
  55929. ** times. They are evaluated once and the results of the expression
  55930. ** are reused.
  55931. */
  55932. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  55933. Vdbe *v = pParse->pVdbe;
  55934. int inReg;
  55935. inReg = sqlite3ExprCode(pParse, pExpr, target);
  55936. assert( target>0 );
  55937. if( pExpr->op!=TK_REGISTER ){
  55938. int iMem;
  55939. iMem = ++pParse->nMem;
  55940. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  55941. pExpr->iTable = iMem;
  55942. pExpr->op = TK_REGISTER;
  55943. }
  55944. return inReg;
  55945. }
  55946. /*
  55947. ** Return TRUE if pExpr is an constant expression that is appropriate
  55948. ** for factoring out of a loop. Appropriate expressions are:
  55949. **
  55950. ** * Any expression that evaluates to two or more opcodes.
  55951. **
  55952. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  55953. ** or OP_Variable that does not need to be placed in a
  55954. ** specific register.
  55955. **
  55956. ** There is no point in factoring out single-instruction constant
  55957. ** expressions that need to be placed in a particular register.
  55958. ** We could factor them out, but then we would end up adding an
  55959. ** OP_SCopy instruction to move the value into the correct register
  55960. ** later. We might as well just use the original instruction and
  55961. ** avoid the OP_SCopy.
  55962. */
  55963. static int isAppropriateForFactoring(Expr *p){
  55964. if( !sqlite3ExprIsConstantNotJoin(p) ){
  55965. return 0; /* Only constant expressions are appropriate for factoring */
  55966. }
  55967. if( (p->flags & EP_FixedDest)==0 ){
  55968. return 1; /* Any constant without a fixed destination is appropriate */
  55969. }
  55970. while( p->op==TK_UPLUS ) p = p->pLeft;
  55971. switch( p->op ){
  55972. #ifndef SQLITE_OMIT_BLOB_LITERAL
  55973. case TK_BLOB:
  55974. #endif
  55975. case TK_VARIABLE:
  55976. case TK_INTEGER:
  55977. case TK_FLOAT:
  55978. case TK_NULL:
  55979. case TK_STRING: {
  55980. testcase( p->op==TK_BLOB );
  55981. testcase( p->op==TK_VARIABLE );
  55982. testcase( p->op==TK_INTEGER );
  55983. testcase( p->op==TK_FLOAT );
  55984. testcase( p->op==TK_NULL );
  55985. testcase( p->op==TK_STRING );
  55986. /* Single-instruction constants with a fixed destination are
  55987. ** better done in-line. If we factor them, they will just end
  55988. ** up generating an OP_SCopy to move the value to the destination
  55989. ** register. */
  55990. return 0;
  55991. }
  55992. case TK_UMINUS: {
  55993. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  55994. return 0;
  55995. }
  55996. break;
  55997. }
  55998. default: {
  55999. break;
  56000. }
  56001. }
  56002. return 1;
  56003. }
  56004. /*
  56005. ** If pExpr is a constant expression that is appropriate for
  56006. ** factoring out of a loop, then evaluate the expression
  56007. ** into a register and convert the expression into a TK_REGISTER
  56008. ** expression.
  56009. */
  56010. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  56011. Parse *pParse = pWalker->pParse;
  56012. switch( pExpr->op ){
  56013. case TK_REGISTER: {
  56014. return 1;
  56015. }
  56016. case TK_FUNCTION:
  56017. case TK_AGG_FUNCTION:
  56018. case TK_CONST_FUNC: {
  56019. /* The arguments to a function have a fixed destination.
  56020. ** Mark them this way to avoid generated unneeded OP_SCopy
  56021. ** instructions.
  56022. */
  56023. ExprList *pList = pExpr->x.pList;
  56024. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  56025. if( pList ){
  56026. int i = pList->nExpr;
  56027. struct ExprList_item *pItem = pList->a;
  56028. for(; i>0; i--, pItem++){
  56029. if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
  56030. }
  56031. }
  56032. break;
  56033. }
  56034. }
  56035. if( isAppropriateForFactoring(pExpr) ){
  56036. int r1 = ++pParse->nMem;
  56037. int r2;
  56038. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  56039. if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
  56040. pExpr->op = TK_REGISTER;
  56041. pExpr->iTable = r2;
  56042. return WRC_Prune;
  56043. }
  56044. return WRC_Continue;
  56045. }
  56046. /*
  56047. ** Preevaluate constant subexpressions within pExpr and store the
  56048. ** results in registers. Modify pExpr so that the constant subexpresions
  56049. ** are TK_REGISTER opcodes that refer to the precomputed values.
  56050. */
  56051. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  56052. Walker w;
  56053. w.xExprCallback = evalConstExpr;
  56054. w.xSelectCallback = 0;
  56055. w.pParse = pParse;
  56056. sqlite3WalkExpr(&w, pExpr);
  56057. }
  56058. /*
  56059. ** Generate code that pushes the value of every element of the given
  56060. ** expression list into a sequence of registers beginning at target.
  56061. **
  56062. ** Return the number of elements evaluated.
  56063. */
  56064. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  56065. Parse *pParse, /* Parsing context */
  56066. ExprList *pList, /* The expression list to be coded */
  56067. int target, /* Where to write results */
  56068. int doHardCopy /* Make a hard copy of every element */
  56069. ){
  56070. struct ExprList_item *pItem;
  56071. int i, n;
  56072. assert( pList!=0 );
  56073. assert( target>0 );
  56074. n = pList->nExpr;
  56075. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  56076. if( pItem->iAlias ){
  56077. int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
  56078. Vdbe *v = sqlite3GetVdbe(pParse);
  56079. if( iReg!=target+i ){
  56080. sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
  56081. }
  56082. }else{
  56083. sqlite3ExprCode(pParse, pItem->pExpr, target+i);
  56084. }
  56085. if( doHardCopy ){
  56086. sqlite3ExprHardCopy(pParse, target, n);
  56087. }
  56088. }
  56089. return n;
  56090. }
  56091. /*
  56092. ** Generate code for a boolean expression such that a jump is made
  56093. ** to the label "dest" if the expression is true but execution
  56094. ** continues straight thru if the expression is false.
  56095. **
  56096. ** If the expression evaluates to NULL (neither true nor false), then
  56097. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  56098. **
  56099. ** This code depends on the fact that certain token values (ex: TK_EQ)
  56100. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  56101. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  56102. ** the make process cause these values to align. Assert()s in the code
  56103. ** below verify that the numbers are aligned correctly.
  56104. */
  56105. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  56106. Vdbe *v = pParse->pVdbe;
  56107. int op = 0;
  56108. int regFree1 = 0;
  56109. int regFree2 = 0;
  56110. int r1, r2;
  56111. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  56112. if( v==0 || pExpr==0 ) return;
  56113. op = pExpr->op;
  56114. switch( op ){
  56115. case TK_AND: {
  56116. int d2 = sqlite3VdbeMakeLabel(v);
  56117. testcase( jumpIfNull==0 );
  56118. testcase( pParse->disableColCache==0 );
  56119. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  56120. pParse->disableColCache++;
  56121. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  56122. assert( pParse->disableColCache>0 );
  56123. pParse->disableColCache--;
  56124. sqlite3VdbeResolveLabel(v, d2);
  56125. break;
  56126. }
  56127. case TK_OR: {
  56128. testcase( jumpIfNull==0 );
  56129. testcase( pParse->disableColCache==0 );
  56130. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  56131. pParse->disableColCache++;
  56132. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  56133. assert( pParse->disableColCache>0 );
  56134. pParse->disableColCache--;
  56135. break;
  56136. }
  56137. case TK_NOT: {
  56138. testcase( jumpIfNull==0 );
  56139. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  56140. break;
  56141. }
  56142. case TK_LT:
  56143. case TK_LE:
  56144. case TK_GT:
  56145. case TK_GE:
  56146. case TK_NE:
  56147. case TK_EQ: {
  56148. assert( TK_LT==OP_Lt );
  56149. assert( TK_LE==OP_Le );
  56150. assert( TK_GT==OP_Gt );
  56151. assert( TK_GE==OP_Ge );
  56152. assert( TK_EQ==OP_Eq );
  56153. assert( TK_NE==OP_Ne );
  56154. testcase( op==TK_LT );
  56155. testcase( op==TK_LE );
  56156. testcase( op==TK_GT );
  56157. testcase( op==TK_GE );
  56158. testcase( op==TK_EQ );
  56159. testcase( op==TK_NE );
  56160. testcase( jumpIfNull==0 );
  56161. codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
  56162. pExpr->pRight, &r2, &regFree2);
  56163. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  56164. r1, r2, dest, jumpIfNull);
  56165. testcase( regFree1==0 );
  56166. testcase( regFree2==0 );
  56167. break;
  56168. }
  56169. case TK_ISNULL:
  56170. case TK_NOTNULL: {
  56171. assert( TK_ISNULL==OP_IsNull );
  56172. assert( TK_NOTNULL==OP_NotNull );
  56173. testcase( op==TK_ISNULL );
  56174. testcase( op==TK_NOTNULL );
  56175. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  56176. sqlite3VdbeAddOp2(v, op, r1, dest);
  56177. testcase( regFree1==0 );
  56178. break;
  56179. }
  56180. case TK_BETWEEN: {
  56181. /* x BETWEEN y AND z
  56182. **
  56183. ** Is equivalent to
  56184. **
  56185. ** x>=y AND x<=z
  56186. **
  56187. ** Code it as such, taking care to do the common subexpression
  56188. ** elementation of x.
  56189. */
  56190. Expr exprAnd;
  56191. Expr compLeft;
  56192. Expr compRight;
  56193. Expr exprX;
  56194. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  56195. exprX = *pExpr->pLeft;
  56196. exprAnd.op = TK_AND;
  56197. exprAnd.pLeft = &compLeft;
  56198. exprAnd.pRight = &compRight;
  56199. compLeft.op = TK_GE;
  56200. compLeft.pLeft = &exprX;
  56201. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  56202. compRight.op = TK_LE;
  56203. compRight.pLeft = &exprX;
  56204. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  56205. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  56206. testcase( regFree1==0 );
  56207. exprX.op = TK_REGISTER;
  56208. testcase( jumpIfNull==0 );
  56209. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  56210. break;
  56211. }
  56212. default: {
  56213. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  56214. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  56215. testcase( regFree1==0 );
  56216. testcase( jumpIfNull==0 );
  56217. break;
  56218. }
  56219. }
  56220. sqlite3ReleaseTempReg(pParse, regFree1);
  56221. sqlite3ReleaseTempReg(pParse, regFree2);
  56222. }
  56223. /*
  56224. ** Generate code for a boolean expression such that a jump is made
  56225. ** to the label "dest" if the expression is false but execution
  56226. ** continues straight thru if the expression is true.
  56227. **
  56228. ** If the expression evaluates to NULL (neither true nor false) then
  56229. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  56230. ** is 0.
  56231. */
  56232. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  56233. Vdbe *v = pParse->pVdbe;
  56234. int op = 0;
  56235. int regFree1 = 0;
  56236. int regFree2 = 0;
  56237. int r1, r2;
  56238. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  56239. if( v==0 || pExpr==0 ) return;
  56240. /* The value of pExpr->op and op are related as follows:
  56241. **
  56242. ** pExpr->op op
  56243. ** --------- ----------
  56244. ** TK_ISNULL OP_NotNull
  56245. ** TK_NOTNULL OP_IsNull
  56246. ** TK_NE OP_Eq
  56247. ** TK_EQ OP_Ne
  56248. ** TK_GT OP_Le
  56249. ** TK_LE OP_Gt
  56250. ** TK_GE OP_Lt
  56251. ** TK_LT OP_Ge
  56252. **
  56253. ** For other values of pExpr->op, op is undefined and unused.
  56254. ** The value of TK_ and OP_ constants are arranged such that we
  56255. ** can compute the mapping above using the following expression.
  56256. ** Assert()s verify that the computation is correct.
  56257. */
  56258. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  56259. /* Verify correct alignment of TK_ and OP_ constants
  56260. */
  56261. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  56262. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  56263. assert( pExpr->op!=TK_NE || op==OP_Eq );
  56264. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  56265. assert( pExpr->op!=TK_LT || op==OP_Ge );
  56266. assert( pExpr->op!=TK_LE || op==OP_Gt );
  56267. assert( pExpr->op!=TK_GT || op==OP_Le );
  56268. assert( pExpr->op!=TK_GE || op==OP_Lt );
  56269. switch( pExpr->op ){
  56270. case TK_AND: {
  56271. testcase( jumpIfNull==0 );
  56272. testcase( pParse->disableColCache==0 );
  56273. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  56274. pParse->disableColCache++;
  56275. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  56276. assert( pParse->disableColCache>0 );
  56277. pParse->disableColCache--;
  56278. break;
  56279. }
  56280. case TK_OR: {
  56281. int d2 = sqlite3VdbeMakeLabel(v);
  56282. testcase( jumpIfNull==0 );
  56283. testcase( pParse->disableColCache==0 );
  56284. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  56285. pParse->disableColCache++;
  56286. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  56287. assert( pParse->disableColCache>0 );
  56288. pParse->disableColCache--;
  56289. sqlite3VdbeResolveLabel(v, d2);
  56290. break;
  56291. }
  56292. case TK_NOT: {
  56293. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  56294. break;
  56295. }
  56296. case TK_LT:
  56297. case TK_LE:
  56298. case TK_GT:
  56299. case TK_GE:
  56300. case TK_NE:
  56301. case TK_EQ: {
  56302. testcase( op==TK_LT );
  56303. testcase( op==TK_LE );
  56304. testcase( op==TK_GT );
  56305. testcase( op==TK_GE );
  56306. testcase( op==TK_EQ );
  56307. testcase( op==TK_NE );
  56308. testcase( jumpIfNull==0 );
  56309. codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
  56310. pExpr->pRight, &r2, &regFree2);
  56311. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  56312. r1, r2, dest, jumpIfNull);
  56313. testcase( regFree1==0 );
  56314. testcase( regFree2==0 );
  56315. break;
  56316. }
  56317. case TK_ISNULL:
  56318. case TK_NOTNULL: {
  56319. testcase( op==TK_ISNULL );
  56320. testcase( op==TK_NOTNULL );
  56321. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  56322. sqlite3VdbeAddOp2(v, op, r1, dest);
  56323. testcase( regFree1==0 );
  56324. break;
  56325. }
  56326. case TK_BETWEEN: {
  56327. /* x BETWEEN y AND z
  56328. **
  56329. ** Is equivalent to
  56330. **
  56331. ** x>=y AND x<=z
  56332. **
  56333. ** Code it as such, taking care to do the common subexpression
  56334. ** elementation of x.
  56335. */
  56336. Expr exprAnd;
  56337. Expr compLeft;
  56338. Expr compRight;
  56339. Expr exprX;
  56340. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  56341. exprX = *pExpr->pLeft;
  56342. exprAnd.op = TK_AND;
  56343. exprAnd.pLeft = &compLeft;
  56344. exprAnd.pRight = &compRight;
  56345. compLeft.op = TK_GE;
  56346. compLeft.pLeft = &exprX;
  56347. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  56348. compRight.op = TK_LE;
  56349. compRight.pLeft = &exprX;
  56350. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  56351. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  56352. testcase( regFree1==0 );
  56353. exprX.op = TK_REGISTER;
  56354. testcase( jumpIfNull==0 );
  56355. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  56356. break;
  56357. }
  56358. default: {
  56359. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  56360. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  56361. testcase( regFree1==0 );
  56362. testcase( jumpIfNull==0 );
  56363. break;
  56364. }
  56365. }
  56366. sqlite3ReleaseTempReg(pParse, regFree1);
  56367. sqlite3ReleaseTempReg(pParse, regFree2);
  56368. }
  56369. /*
  56370. ** Do a deep comparison of two expression trees. Return TRUE (non-zero)
  56371. ** if they are identical and return FALSE if they differ in any way.
  56372. **
  56373. ** Sometimes this routine will return FALSE even if the two expressions
  56374. ** really are equivalent. If we cannot prove that the expressions are
  56375. ** identical, we return FALSE just to be safe. So if this routine
  56376. ** returns false, then you do not really know for certain if the two
  56377. ** expressions are the same. But if you get a TRUE return, then you
  56378. ** can be sure the expressions are the same. In the places where
  56379. ** this routine is used, it does not hurt to get an extra FALSE - that
  56380. ** just might result in some slightly slower code. But returning
  56381. ** an incorrect TRUE could lead to a malfunction.
  56382. */
  56383. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
  56384. int i;
  56385. if( pA==0||pB==0 ){
  56386. return pB==pA;
  56387. }
  56388. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  56389. return 0;
  56390. }
  56391. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
  56392. if( pA->op!=pB->op ) return 0;
  56393. if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
  56394. if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
  56395. if( pA->x.pList && pB->x.pList ){
  56396. if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
  56397. for(i=0; i<pA->x.pList->nExpr; i++){
  56398. Expr *pExprA = pA->x.pList->a[i].pExpr;
  56399. Expr *pExprB = pB->x.pList->a[i].pExpr;
  56400. if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
  56401. }
  56402. }else if( pA->x.pList || pB->x.pList ){
  56403. return 0;
  56404. }
  56405. if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
  56406. if( pA->op!=TK_COLUMN && pA->token.z ){
  56407. if( pB->token.z==0 ) return 0;
  56408. if( pB->token.n!=pA->token.n ) return 0;
  56409. if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
  56410. return 0;
  56411. }
  56412. }
  56413. return 1;
  56414. }
  56415. /*
  56416. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  56417. ** the new element. Return a negative number if malloc fails.
  56418. */
  56419. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  56420. int i;
  56421. pInfo->aCol = sqlite3ArrayAllocate(
  56422. db,
  56423. pInfo->aCol,
  56424. sizeof(pInfo->aCol[0]),
  56425. 3,
  56426. &pInfo->nColumn,
  56427. &pInfo->nColumnAlloc,
  56428. &i
  56429. );
  56430. return i;
  56431. }
  56432. /*
  56433. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  56434. ** the new element. Return a negative number if malloc fails.
  56435. */
  56436. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  56437. int i;
  56438. pInfo->aFunc = sqlite3ArrayAllocate(
  56439. db,
  56440. pInfo->aFunc,
  56441. sizeof(pInfo->aFunc[0]),
  56442. 3,
  56443. &pInfo->nFunc,
  56444. &pInfo->nFuncAlloc,
  56445. &i
  56446. );
  56447. return i;
  56448. }
  56449. /*
  56450. ** This is the xExprCallback for a tree walker. It is used to
  56451. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  56452. ** for additional information.
  56453. */
  56454. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  56455. int i;
  56456. NameContext *pNC = pWalker->u.pNC;
  56457. Parse *pParse = pNC->pParse;
  56458. SrcList *pSrcList = pNC->pSrcList;
  56459. AggInfo *pAggInfo = pNC->pAggInfo;
  56460. switch( pExpr->op ){
  56461. case TK_AGG_COLUMN:
  56462. case TK_COLUMN: {
  56463. testcase( pExpr->op==TK_AGG_COLUMN );
  56464. testcase( pExpr->op==TK_COLUMN );
  56465. /* Check to see if the column is in one of the tables in the FROM
  56466. ** clause of the aggregate query */
  56467. if( pSrcList ){
  56468. struct SrcList_item *pItem = pSrcList->a;
  56469. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  56470. struct AggInfo_col *pCol;
  56471. if( pExpr->iTable==pItem->iCursor ){
  56472. /* If we reach this point, it means that pExpr refers to a table
  56473. ** that is in the FROM clause of the aggregate query.
  56474. **
  56475. ** Make an entry for the column in pAggInfo->aCol[] if there
  56476. ** is not an entry there already.
  56477. */
  56478. int k;
  56479. pCol = pAggInfo->aCol;
  56480. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  56481. if( pCol->iTable==pExpr->iTable &&
  56482. pCol->iColumn==pExpr->iColumn ){
  56483. break;
  56484. }
  56485. }
  56486. if( (k>=pAggInfo->nColumn)
  56487. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  56488. ){
  56489. pCol = &pAggInfo->aCol[k];
  56490. pCol->pTab = pExpr->pTab;
  56491. pCol->iTable = pExpr->iTable;
  56492. pCol->iColumn = pExpr->iColumn;
  56493. pCol->iMem = ++pParse->nMem;
  56494. pCol->iSorterColumn = -1;
  56495. pCol->pExpr = pExpr;
  56496. if( pAggInfo->pGroupBy ){
  56497. int j, n;
  56498. ExprList *pGB = pAggInfo->pGroupBy;
  56499. struct ExprList_item *pTerm = pGB->a;
  56500. n = pGB->nExpr;
  56501. for(j=0; j<n; j++, pTerm++){
  56502. Expr *pE = pTerm->pExpr;
  56503. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  56504. pE->iColumn==pExpr->iColumn ){
  56505. pCol->iSorterColumn = j;
  56506. break;
  56507. }
  56508. }
  56509. }
  56510. if( pCol->iSorterColumn<0 ){
  56511. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  56512. }
  56513. }
  56514. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  56515. ** because it was there before or because we just created it).
  56516. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  56517. ** pAggInfo->aCol[] entry.
  56518. */
  56519. pExpr->pAggInfo = pAggInfo;
  56520. pExpr->op = TK_AGG_COLUMN;
  56521. pExpr->iAgg = k;
  56522. break;
  56523. } /* endif pExpr->iTable==pItem->iCursor */
  56524. } /* end loop over pSrcList */
  56525. }
  56526. return WRC_Prune;
  56527. }
  56528. case TK_AGG_FUNCTION: {
  56529. /* The pNC->nDepth==0 test causes aggregate functions in subqueries
  56530. ** to be ignored */
  56531. if( pNC->nDepth==0 ){
  56532. /* Check to see if pExpr is a duplicate of another aggregate
  56533. ** function that is already in the pAggInfo structure
  56534. */
  56535. struct AggInfo_func *pItem = pAggInfo->aFunc;
  56536. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  56537. if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
  56538. break;
  56539. }
  56540. }
  56541. if( i>=pAggInfo->nFunc ){
  56542. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  56543. */
  56544. u8 enc = ENC(pParse->db);
  56545. i = addAggInfoFunc(pParse->db, pAggInfo);
  56546. if( i>=0 ){
  56547. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  56548. pItem = &pAggInfo->aFunc[i];
  56549. pItem->pExpr = pExpr;
  56550. pItem->iMem = ++pParse->nMem;
  56551. pItem->pFunc = sqlite3FindFunction(pParse->db,
  56552. (char*)pExpr->token.z, pExpr->token.n,
  56553. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  56554. if( pExpr->flags & EP_Distinct ){
  56555. pItem->iDistinct = pParse->nTab++;
  56556. }else{
  56557. pItem->iDistinct = -1;
  56558. }
  56559. }
  56560. }
  56561. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  56562. */
  56563. pExpr->iAgg = i;
  56564. pExpr->pAggInfo = pAggInfo;
  56565. return WRC_Prune;
  56566. }
  56567. }
  56568. }
  56569. return WRC_Continue;
  56570. }
  56571. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  56572. NameContext *pNC = pWalker->u.pNC;
  56573. if( pNC->nDepth==0 ){
  56574. pNC->nDepth++;
  56575. sqlite3WalkSelect(pWalker, pSelect);
  56576. pNC->nDepth--;
  56577. return WRC_Prune;
  56578. }else{
  56579. return WRC_Continue;
  56580. }
  56581. }
  56582. /*
  56583. ** Analyze the given expression looking for aggregate functions and
  56584. ** for variables that need to be added to the pParse->aAgg[] array.
  56585. ** Make additional entries to the pParse->aAgg[] array as necessary.
  56586. **
  56587. ** This routine should only be called after the expression has been
  56588. ** analyzed by sqlite3ResolveExprNames().
  56589. */
  56590. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  56591. Walker w;
  56592. w.xExprCallback = analyzeAggregate;
  56593. w.xSelectCallback = analyzeAggregatesInSelect;
  56594. w.u.pNC = pNC;
  56595. sqlite3WalkExpr(&w, pExpr);
  56596. }
  56597. /*
  56598. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  56599. ** expression list. Return the number of errors.
  56600. **
  56601. ** If an error is found, the analysis is cut short.
  56602. */
  56603. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  56604. struct ExprList_item *pItem;
  56605. int i;
  56606. if( pList ){
  56607. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  56608. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  56609. }
  56610. }
  56611. }
  56612. /*
  56613. ** Allocate or deallocate temporary use registers during code generation.
  56614. */
  56615. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  56616. if( pParse->nTempReg==0 ){
  56617. return ++pParse->nMem;
  56618. }
  56619. return pParse->aTempReg[--pParse->nTempReg];
  56620. }
  56621. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  56622. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  56623. sqlite3ExprWritableRegister(pParse, iReg);
  56624. pParse->aTempReg[pParse->nTempReg++] = iReg;
  56625. }
  56626. }
  56627. /*
  56628. ** Allocate or deallocate a block of nReg consecutive registers
  56629. */
  56630. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  56631. int i, n;
  56632. i = pParse->iRangeReg;
  56633. n = pParse->nRangeReg;
  56634. if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
  56635. pParse->iRangeReg += nReg;
  56636. pParse->nRangeReg -= nReg;
  56637. }else{
  56638. i = pParse->nMem+1;
  56639. pParse->nMem += nReg;
  56640. }
  56641. return i;
  56642. }
  56643. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  56644. if( nReg>pParse->nRangeReg ){
  56645. pParse->nRangeReg = nReg;
  56646. pParse->iRangeReg = iReg;
  56647. }
  56648. }
  56649. /************** End of expr.c ************************************************/
  56650. /************** Begin file alter.c *******************************************/
  56651. /*
  56652. ** 2005 February 15
  56653. **
  56654. ** The author disclaims copyright to this source code. In place of
  56655. ** a legal notice, here is a blessing:
  56656. **
  56657. ** May you do good and not evil.
  56658. ** May you find forgiveness for yourself and forgive others.
  56659. ** May you share freely, never taking more than you give.
  56660. **
  56661. *************************************************************************
  56662. ** This file contains C code routines that used to generate VDBE code
  56663. ** that implements the ALTER TABLE command.
  56664. **
  56665. ** $Id: alter.c,v 1.55 2009/03/24 15:08:10 drh Exp $
  56666. */
  56667. /*
  56668. ** The code in this file only exists if we are not omitting the
  56669. ** ALTER TABLE logic from the build.
  56670. */
  56671. #ifndef SQLITE_OMIT_ALTERTABLE
  56672. /*
  56673. ** This function is used by SQL generated to implement the
  56674. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  56675. ** CREATE INDEX command. The second is a table name. The table name in
  56676. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  56677. ** argument and the result returned. Examples:
  56678. **
  56679. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  56680. ** -> 'CREATE TABLE def(a, b, c)'
  56681. **
  56682. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  56683. ** -> 'CREATE INDEX i ON def(a, b, c)'
  56684. */
  56685. static void renameTableFunc(
  56686. sqlite3_context *context,
  56687. int NotUsed,
  56688. sqlite3_value **argv
  56689. ){
  56690. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  56691. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  56692. int token;
  56693. Token tname;
  56694. unsigned char const *zCsr = zSql;
  56695. int len = 0;
  56696. char *zRet;
  56697. sqlite3 *db = sqlite3_context_db_handle(context);
  56698. UNUSED_PARAMETER(NotUsed);
  56699. /* The principle used to locate the table name in the CREATE TABLE
  56700. ** statement is that the table name is the first non-space token that
  56701. ** is immediately followed by a TK_LP or TK_USING token.
  56702. */
  56703. if( zSql ){
  56704. do {
  56705. if( !*zCsr ){
  56706. /* Ran out of input before finding an opening bracket. Return NULL. */
  56707. return;
  56708. }
  56709. /* Store the token that zCsr points to in tname. */
  56710. tname.z = zCsr;
  56711. tname.n = len;
  56712. /* Advance zCsr to the next token. Store that token type in 'token',
  56713. ** and its length in 'len' (to be used next iteration of this loop).
  56714. */
  56715. do {
  56716. zCsr += len;
  56717. len = sqlite3GetToken(zCsr, &token);
  56718. } while( token==TK_SPACE );
  56719. assert( len>0 );
  56720. } while( token!=TK_LP && token!=TK_USING );
  56721. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql,
  56722. zTableName, tname.z+tname.n);
  56723. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  56724. }
  56725. }
  56726. #ifndef SQLITE_OMIT_TRIGGER
  56727. /* This function is used by SQL generated to implement the
  56728. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  56729. ** statement. The second is a table name. The table name in the CREATE
  56730. ** TRIGGER statement is replaced with the third argument and the result
  56731. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  56732. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  56733. */
  56734. static void renameTriggerFunc(
  56735. sqlite3_context *context,
  56736. int NotUsed,
  56737. sqlite3_value **argv
  56738. ){
  56739. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  56740. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  56741. int token;
  56742. Token tname;
  56743. int dist = 3;
  56744. unsigned char const *zCsr = zSql;
  56745. int len = 0;
  56746. char *zRet;
  56747. sqlite3 *db = sqlite3_context_db_handle(context);
  56748. UNUSED_PARAMETER(NotUsed);
  56749. /* The principle used to locate the table name in the CREATE TRIGGER
  56750. ** statement is that the table name is the first token that is immediatedly
  56751. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  56752. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  56753. */
  56754. if( zSql ){
  56755. do {
  56756. if( !*zCsr ){
  56757. /* Ran out of input before finding the table name. Return NULL. */
  56758. return;
  56759. }
  56760. /* Store the token that zCsr points to in tname. */
  56761. tname.z = zCsr;
  56762. tname.n = len;
  56763. /* Advance zCsr to the next token. Store that token type in 'token',
  56764. ** and its length in 'len' (to be used next iteration of this loop).
  56765. */
  56766. do {
  56767. zCsr += len;
  56768. len = sqlite3GetToken(zCsr, &token);
  56769. }while( token==TK_SPACE );
  56770. assert( len>0 );
  56771. /* Variable 'dist' stores the number of tokens read since the most
  56772. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  56773. ** token is read and 'dist' equals 2, the condition stated above
  56774. ** to be met.
  56775. **
  56776. ** Note that ON cannot be a database, table or column name, so
  56777. ** there is no need to worry about syntax like
  56778. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  56779. */
  56780. dist++;
  56781. if( token==TK_DOT || token==TK_ON ){
  56782. dist = 0;
  56783. }
  56784. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  56785. /* Variable tname now contains the token that is the old table-name
  56786. ** in the CREATE TRIGGER statement.
  56787. */
  56788. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql,
  56789. zTableName, tname.z+tname.n);
  56790. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  56791. }
  56792. }
  56793. #endif /* !SQLITE_OMIT_TRIGGER */
  56794. /*
  56795. ** Register built-in functions used to help implement ALTER TABLE
  56796. */
  56797. SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
  56798. sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
  56799. renameTableFunc, 0, 0);
  56800. #ifndef SQLITE_OMIT_TRIGGER
  56801. sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
  56802. renameTriggerFunc, 0, 0);
  56803. #endif
  56804. }
  56805. /*
  56806. ** Generate the text of a WHERE expression which can be used to select all
  56807. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  56808. ** table pTab has no temporary triggers, or is itself stored in the
  56809. ** temporary database, NULL is returned.
  56810. */
  56811. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  56812. Trigger *pTrig;
  56813. char *zWhere = 0;
  56814. char *tmp = 0;
  56815. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  56816. /* If the table is not located in the temp-db (in which case NULL is
  56817. ** returned, loop through the tables list of triggers. For each trigger
  56818. ** that is not part of the temp-db schema, add a clause to the WHERE
  56819. ** expression being built up in zWhere.
  56820. */
  56821. if( pTab->pSchema!=pTempSchema ){
  56822. sqlite3 *db = pParse->db;
  56823. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  56824. if( pTrig->pSchema==pTempSchema ){
  56825. if( !zWhere ){
  56826. zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
  56827. }else{
  56828. tmp = zWhere;
  56829. zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
  56830. sqlite3DbFree(db, tmp);
  56831. }
  56832. }
  56833. }
  56834. }
  56835. return zWhere;
  56836. }
  56837. /*
  56838. ** Generate code to drop and reload the internal representation of table
  56839. ** pTab from the database, including triggers and temporary triggers.
  56840. ** Argument zName is the name of the table in the database schema at
  56841. ** the time the generated code is executed. This can be different from
  56842. ** pTab->zName if this function is being called to code part of an
  56843. ** "ALTER TABLE RENAME TO" statement.
  56844. */
  56845. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  56846. Vdbe *v;
  56847. char *zWhere;
  56848. int iDb; /* Index of database containing pTab */
  56849. #ifndef SQLITE_OMIT_TRIGGER
  56850. Trigger *pTrig;
  56851. #endif
  56852. v = sqlite3GetVdbe(pParse);
  56853. if( !v ) return;
  56854. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  56855. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  56856. assert( iDb>=0 );
  56857. #ifndef SQLITE_OMIT_TRIGGER
  56858. /* Drop any table triggers from the internal schema. */
  56859. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  56860. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  56861. assert( iTrigDb==iDb || iTrigDb==1 );
  56862. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
  56863. }
  56864. #endif
  56865. /* Drop the table and index from the internal schema */
  56866. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  56867. /* Reload the table, index and permanent trigger schemas. */
  56868. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  56869. if( !zWhere ) return;
  56870. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  56871. #ifndef SQLITE_OMIT_TRIGGER
  56872. /* Now, if the table is not stored in the temp database, reload any temp
  56873. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  56874. */
  56875. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  56876. sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
  56877. }
  56878. #endif
  56879. }
  56880. /*
  56881. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  56882. ** command.
  56883. */
  56884. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  56885. Parse *pParse, /* Parser context. */
  56886. SrcList *pSrc, /* The table to rename. */
  56887. Token *pName /* The new table name. */
  56888. ){
  56889. int iDb; /* Database that contains the table */
  56890. char *zDb; /* Name of database iDb */
  56891. Table *pTab; /* Table being renamed */
  56892. char *zName = 0; /* NULL-terminated version of pName */
  56893. sqlite3 *db = pParse->db; /* Database connection */
  56894. int nTabName; /* Number of UTF-8 characters in zTabName */
  56895. const char *zTabName; /* Original name of the table */
  56896. Vdbe *v;
  56897. #ifndef SQLITE_OMIT_TRIGGER
  56898. char *zWhere = 0; /* Where clause to locate temp triggers */
  56899. #endif
  56900. int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
  56901. if( db->mallocFailed ) goto exit_rename_table;
  56902. assert( pSrc->nSrc==1 );
  56903. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  56904. pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  56905. if( !pTab ) goto exit_rename_table;
  56906. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  56907. zDb = db->aDb[iDb].zName;
  56908. /* Get a NULL terminated version of the new table name. */
  56909. zName = sqlite3NameFromToken(db, pName);
  56910. if( !zName ) goto exit_rename_table;
  56911. /* Check that a table or index named 'zName' does not already exist
  56912. ** in database iDb. If so, this is an error.
  56913. */
  56914. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  56915. sqlite3ErrorMsg(pParse,
  56916. "there is already another table or index with this name: %s", zName);
  56917. goto exit_rename_table;
  56918. }
  56919. /* Make sure it is not a system table being altered, or a reserved name
  56920. ** that the table is being renamed to.
  56921. */
  56922. if( sqlite3Strlen30(pTab->zName)>6
  56923. && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
  56924. ){
  56925. sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
  56926. goto exit_rename_table;
  56927. }
  56928. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  56929. goto exit_rename_table;
  56930. }
  56931. #ifndef SQLITE_OMIT_VIEW
  56932. if( pTab->pSelect ){
  56933. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  56934. goto exit_rename_table;
  56935. }
  56936. #endif
  56937. #ifndef SQLITE_OMIT_AUTHORIZATION
  56938. /* Invoke the authorization callback. */
  56939. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  56940. goto exit_rename_table;
  56941. }
  56942. #endif
  56943. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56944. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  56945. goto exit_rename_table;
  56946. }
  56947. if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
  56948. isVirtualRename = 1;
  56949. }
  56950. #endif
  56951. /* Begin a transaction and code the VerifyCookie for database iDb.
  56952. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  56953. ** schema). Open a statement transaction if the table is a virtual
  56954. ** table.
  56955. */
  56956. v = sqlite3GetVdbe(pParse);
  56957. if( v==0 ){
  56958. goto exit_rename_table;
  56959. }
  56960. sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
  56961. sqlite3ChangeCookie(pParse, iDb);
  56962. /* If this is a virtual table, invoke the xRename() function if
  56963. ** one is defined. The xRename() callback will modify the names
  56964. ** of any resources used by the v-table implementation (including other
  56965. ** SQLite tables) that are identified by the name of the virtual table.
  56966. */
  56967. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56968. if( isVirtualRename ){
  56969. int i = ++pParse->nMem;
  56970. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  56971. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
  56972. }
  56973. #endif
  56974. /* figure out how many UTF-8 characters are in zName */
  56975. zTabName = pTab->zName;
  56976. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  56977. /* Modify the sqlite_master table to use the new table name. */
  56978. sqlite3NestedParse(pParse,
  56979. "UPDATE %Q.%s SET "
  56980. #ifdef SQLITE_OMIT_TRIGGER
  56981. "sql = sqlite_rename_table(sql, %Q), "
  56982. #else
  56983. "sql = CASE "
  56984. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  56985. "ELSE sqlite_rename_table(sql, %Q) END, "
  56986. #endif
  56987. "tbl_name = %Q, "
  56988. "name = CASE "
  56989. "WHEN type='table' THEN %Q "
  56990. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  56991. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  56992. "ELSE name END "
  56993. "WHERE tbl_name=%Q AND "
  56994. "(type='table' OR type='index' OR type='trigger');",
  56995. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  56996. #ifndef SQLITE_OMIT_TRIGGER
  56997. zName,
  56998. #endif
  56999. zName, nTabName, zTabName
  57000. );
  57001. #ifndef SQLITE_OMIT_AUTOINCREMENT
  57002. /* If the sqlite_sequence table exists in this database, then update
  57003. ** it with the new table name.
  57004. */
  57005. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  57006. sqlite3NestedParse(pParse,
  57007. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  57008. zDb, zName, pTab->zName);
  57009. }
  57010. #endif
  57011. #ifndef SQLITE_OMIT_TRIGGER
  57012. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  57013. ** table. Don't do this if the table being ALTERed is itself located in
  57014. ** the temp database.
  57015. */
  57016. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  57017. sqlite3NestedParse(pParse,
  57018. "UPDATE sqlite_temp_master SET "
  57019. "sql = sqlite_rename_trigger(sql, %Q), "
  57020. "tbl_name = %Q "
  57021. "WHERE %s;", zName, zName, zWhere);
  57022. sqlite3DbFree(db, zWhere);
  57023. }
  57024. #endif
  57025. /* Drop and reload the internal table schema. */
  57026. reloadTableSchema(pParse, pTab, zName);
  57027. exit_rename_table:
  57028. sqlite3SrcListDelete(db, pSrc);
  57029. sqlite3DbFree(db, zName);
  57030. }
  57031. /*
  57032. ** This function is called after an "ALTER TABLE ... ADD" statement
  57033. ** has been parsed. Argument pColDef contains the text of the new
  57034. ** column definition.
  57035. **
  57036. ** The Table structure pParse->pNewTable was extended to include
  57037. ** the new column during parsing.
  57038. */
  57039. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  57040. Table *pNew; /* Copy of pParse->pNewTable */
  57041. Table *pTab; /* Table being altered */
  57042. int iDb; /* Database number */
  57043. const char *zDb; /* Database name */
  57044. const char *zTab; /* Table name */
  57045. char *zCol; /* Null-terminated column definition */
  57046. Column *pCol; /* The new column */
  57047. Expr *pDflt; /* Default value for the new column */
  57048. sqlite3 *db; /* The database connection; */
  57049. db = pParse->db;
  57050. if( pParse->nErr || db->mallocFailed ) return;
  57051. pNew = pParse->pNewTable;
  57052. assert( pNew );
  57053. assert( sqlite3BtreeHoldsAllMutexes(db) );
  57054. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  57055. zDb = db->aDb[iDb].zName;
  57056. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  57057. pCol = &pNew->aCol[pNew->nCol-1];
  57058. pDflt = pCol->pDflt;
  57059. pTab = sqlite3FindTable(db, zTab, zDb);
  57060. assert( pTab );
  57061. #ifndef SQLITE_OMIT_AUTHORIZATION
  57062. /* Invoke the authorization callback. */
  57063. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  57064. return;
  57065. }
  57066. #endif
  57067. /* If the default value for the new column was specified with a
  57068. ** literal NULL, then set pDflt to 0. This simplifies checking
  57069. ** for an SQL NULL default below.
  57070. */
  57071. if( pDflt && pDflt->op==TK_NULL ){
  57072. pDflt = 0;
  57073. }
  57074. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  57075. ** If there is a NOT NULL constraint, then the default value for the
  57076. ** column must not be NULL.
  57077. */
  57078. if( pCol->isPrimKey ){
  57079. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  57080. return;
  57081. }
  57082. if( pNew->pIndex ){
  57083. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  57084. return;
  57085. }
  57086. if( pCol->notNull && !pDflt ){
  57087. sqlite3ErrorMsg(pParse,
  57088. "Cannot add a NOT NULL column with default value NULL");
  57089. return;
  57090. }
  57091. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  57092. ** can handle (i.e. not CURRENT_TIME etc.)
  57093. */
  57094. if( pDflt ){
  57095. sqlite3_value *pVal;
  57096. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  57097. db->mallocFailed = 1;
  57098. return;
  57099. }
  57100. if( !pVal ){
  57101. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  57102. return;
  57103. }
  57104. sqlite3ValueFree(pVal);
  57105. }
  57106. /* Modify the CREATE TABLE statement. */
  57107. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  57108. if( zCol ){
  57109. char *zEnd = &zCol[pColDef->n-1];
  57110. while( (zEnd>zCol && *zEnd==';') || sqlite3Isspace(*zEnd) ){
  57111. *zEnd-- = '\0';
  57112. }
  57113. sqlite3NestedParse(pParse,
  57114. "UPDATE \"%w\".%s SET "
  57115. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  57116. "WHERE type = 'table' AND name = %Q",
  57117. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  57118. zTab
  57119. );
  57120. sqlite3DbFree(db, zCol);
  57121. }
  57122. /* If the default value of the new column is NULL, then set the file
  57123. ** format to 2. If the default value of the new column is not NULL,
  57124. ** the file format becomes 3.
  57125. */
  57126. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  57127. /* Reload the schema of the modified table. */
  57128. reloadTableSchema(pParse, pTab, pTab->zName);
  57129. }
  57130. /*
  57131. ** This function is called by the parser after the table-name in
  57132. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  57133. ** pSrc is the full-name of the table being altered.
  57134. **
  57135. ** This routine makes a (partial) copy of the Table structure
  57136. ** for the table being altered and sets Parse.pNewTable to point
  57137. ** to it. Routines called by the parser as the column definition
  57138. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  57139. ** the copy. The copy of the Table structure is deleted by tokenize.c
  57140. ** after parsing is finished.
  57141. **
  57142. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  57143. ** coding the "ALTER TABLE ... ADD" statement.
  57144. */
  57145. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  57146. Table *pNew;
  57147. Table *pTab;
  57148. Vdbe *v;
  57149. int iDb;
  57150. int i;
  57151. int nAlloc;
  57152. sqlite3 *db = pParse->db;
  57153. /* Look up the table being altered. */
  57154. assert( pParse->pNewTable==0 );
  57155. assert( sqlite3BtreeHoldsAllMutexes(db) );
  57156. if( db->mallocFailed ) goto exit_begin_add_column;
  57157. pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  57158. if( !pTab ) goto exit_begin_add_column;
  57159. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57160. if( IsVirtual(pTab) ){
  57161. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  57162. goto exit_begin_add_column;
  57163. }
  57164. #endif
  57165. /* Make sure this is not an attempt to ALTER a view. */
  57166. if( pTab->pSelect ){
  57167. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  57168. goto exit_begin_add_column;
  57169. }
  57170. assert( pTab->addColOffset>0 );
  57171. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  57172. /* Put a copy of the Table struct in Parse.pNewTable for the
  57173. ** sqlite3AddColumn() function and friends to modify. But modify
  57174. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  57175. ** prefix, we insure that the name will not collide with an existing
  57176. ** table because user table are not allowed to have the "sqlite_"
  57177. ** prefix on their name.
  57178. */
  57179. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  57180. if( !pNew ) goto exit_begin_add_column;
  57181. pParse->pNewTable = pNew;
  57182. pNew->nRef = 1;
  57183. pNew->dbMem = pTab->dbMem;
  57184. pNew->nCol = pTab->nCol;
  57185. assert( pNew->nCol>0 );
  57186. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  57187. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  57188. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  57189. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  57190. if( !pNew->aCol || !pNew->zName ){
  57191. db->mallocFailed = 1;
  57192. goto exit_begin_add_column;
  57193. }
  57194. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  57195. for(i=0; i<pNew->nCol; i++){
  57196. Column *pCol = &pNew->aCol[i];
  57197. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  57198. pCol->zColl = 0;
  57199. pCol->zType = 0;
  57200. pCol->pDflt = 0;
  57201. }
  57202. pNew->pSchema = db->aDb[iDb].pSchema;
  57203. pNew->addColOffset = pTab->addColOffset;
  57204. pNew->nRef = 1;
  57205. /* Begin a transaction and increment the schema cookie. */
  57206. sqlite3BeginWriteOperation(pParse, 0, iDb);
  57207. v = sqlite3GetVdbe(pParse);
  57208. if( !v ) goto exit_begin_add_column;
  57209. sqlite3ChangeCookie(pParse, iDb);
  57210. exit_begin_add_column:
  57211. sqlite3SrcListDelete(db, pSrc);
  57212. return;
  57213. }
  57214. #endif /* SQLITE_ALTER_TABLE */
  57215. /************** End of alter.c ***********************************************/
  57216. /************** Begin file analyze.c *****************************************/
  57217. /*
  57218. ** 2005 July 8
  57219. **
  57220. ** The author disclaims copyright to this source code. In place of
  57221. ** a legal notice, here is a blessing:
  57222. **
  57223. ** May you do good and not evil.
  57224. ** May you find forgiveness for yourself and forgive others.
  57225. ** May you share freely, never taking more than you give.
  57226. **
  57227. *************************************************************************
  57228. ** This file contains code associated with the ANALYZE command.
  57229. **
  57230. ** @(#) $Id: analyze.c,v 1.51 2009/02/28 10:47:42 danielk1977 Exp $
  57231. */
  57232. #ifndef SQLITE_OMIT_ANALYZE
  57233. /*
  57234. ** This routine generates code that opens the sqlite_stat1 table on cursor
  57235. ** iStatCur.
  57236. **
  57237. ** If the sqlite_stat1 tables does not previously exist, it is created.
  57238. ** If it does previously exist, all entires associated with table zWhere
  57239. ** are removed. If zWhere==0 then all entries are removed.
  57240. */
  57241. static void openStatTable(
  57242. Parse *pParse, /* Parsing context */
  57243. int iDb, /* The database we are looking in */
  57244. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  57245. const char *zWhere /* Delete entries associated with this table */
  57246. ){
  57247. sqlite3 *db = pParse->db;
  57248. Db *pDb;
  57249. int iRootPage;
  57250. u8 createStat1 = 0;
  57251. Table *pStat;
  57252. Vdbe *v = sqlite3GetVdbe(pParse);
  57253. if( v==0 ) return;
  57254. assert( sqlite3BtreeHoldsAllMutexes(db) );
  57255. assert( sqlite3VdbeDb(v)==db );
  57256. pDb = &db->aDb[iDb];
  57257. if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
  57258. /* The sqlite_stat1 tables does not exist. Create it.
  57259. ** Note that a side-effect of the CREATE TABLE statement is to leave
  57260. ** the rootpage of the new table in register pParse->regRoot. This is
  57261. ** important because the OpenWrite opcode below will be needing it. */
  57262. sqlite3NestedParse(pParse,
  57263. "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
  57264. pDb->zName
  57265. );
  57266. iRootPage = pParse->regRoot;
  57267. createStat1 = 1; /* Cause rootpage to be taken from top of stack */
  57268. }else if( zWhere ){
  57269. /* The sqlite_stat1 table exists. Delete all entries associated with
  57270. ** the table zWhere. */
  57271. sqlite3NestedParse(pParse,
  57272. "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
  57273. pDb->zName, zWhere
  57274. );
  57275. iRootPage = pStat->tnum;
  57276. }else{
  57277. /* The sqlite_stat1 table already exists. Delete all rows. */
  57278. iRootPage = pStat->tnum;
  57279. sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
  57280. }
  57281. /* Open the sqlite_stat1 table for writing. Unless it was created
  57282. ** by this vdbe program, lock it for writing at the shared-cache level.
  57283. ** If this vdbe did create the sqlite_stat1 table, then it must have
  57284. ** already obtained a schema-lock, making the write-lock redundant.
  57285. */
  57286. if( !createStat1 ){
  57287. sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
  57288. }
  57289. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
  57290. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  57291. sqlite3VdbeChangeP5(v, createStat1);
  57292. }
  57293. /*
  57294. ** Generate code to do an analysis of all indices associated with
  57295. ** a single table.
  57296. */
  57297. static void analyzeOneTable(
  57298. Parse *pParse, /* Parser context */
  57299. Table *pTab, /* Table whose indices are to be analyzed */
  57300. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  57301. int iMem /* Available memory locations begin here */
  57302. ){
  57303. Index *pIdx; /* An index to being analyzed */
  57304. int iIdxCur; /* Index of VdbeCursor for index being analyzed */
  57305. int nCol; /* Number of columns in the index */
  57306. Vdbe *v; /* The virtual machine being built up */
  57307. int i; /* Loop counter */
  57308. int topOfLoop; /* The top of the loop */
  57309. int endOfLoop; /* The end of the loop */
  57310. int addr; /* The address of an instruction */
  57311. int iDb; /* Index of database containing pTab */
  57312. v = sqlite3GetVdbe(pParse);
  57313. if( v==0 || pTab==0 || pTab->pIndex==0 ){
  57314. /* Do no analysis for tables that have no indices */
  57315. return;
  57316. }
  57317. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  57318. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  57319. assert( iDb>=0 );
  57320. #ifndef SQLITE_OMIT_AUTHORIZATION
  57321. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  57322. pParse->db->aDb[iDb].zName ) ){
  57323. return;
  57324. }
  57325. #endif
  57326. /* Establish a read-lock on the table at the shared-cache level. */
  57327. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  57328. iIdxCur = pParse->nTab++;
  57329. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  57330. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  57331. int regFields; /* Register block for building records */
  57332. int regRec; /* Register holding completed record */
  57333. int regTemp; /* Temporary use register */
  57334. int regCol; /* Content of a column from the table being analyzed */
  57335. int regRowid; /* Rowid for the inserted record */
  57336. int regF2;
  57337. /* Open a cursor to the index to be analyzed
  57338. */
  57339. assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
  57340. nCol = pIdx->nColumn;
  57341. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
  57342. (char *)pKey, P4_KEYINFO_HANDOFF);
  57343. VdbeComment((v, "%s", pIdx->zName));
  57344. regFields = iMem+nCol*2;
  57345. regTemp = regRowid = regCol = regFields+3;
  57346. regRec = regCol+1;
  57347. if( regRec>pParse->nMem ){
  57348. pParse->nMem = regRec;
  57349. }
  57350. /* Memory cells are used as follows:
  57351. **
  57352. ** mem[iMem]: The total number of rows in the table.
  57353. ** mem[iMem+1]: Number of distinct values in column 1
  57354. ** ...
  57355. ** mem[iMem+nCol]: Number of distinct values in column N
  57356. ** mem[iMem+nCol+1] Last observed value of column 1
  57357. ** ...
  57358. ** mem[iMem+nCol+nCol]: Last observed value of column N
  57359. **
  57360. ** Cells iMem through iMem+nCol are initialized to 0. The others
  57361. ** are initialized to NULL.
  57362. */
  57363. for(i=0; i<=nCol; i++){
  57364. sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
  57365. }
  57366. for(i=0; i<nCol; i++){
  57367. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
  57368. }
  57369. /* Do the analysis.
  57370. */
  57371. endOfLoop = sqlite3VdbeMakeLabel(v);
  57372. sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
  57373. topOfLoop = sqlite3VdbeCurrentAddr(v);
  57374. sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
  57375. for(i=0; i<nCol; i++){
  57376. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
  57377. sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
  57378. /**** TODO: add collating sequence *****/
  57379. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  57380. }
  57381. sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
  57382. for(i=0; i<nCol; i++){
  57383. sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
  57384. sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
  57385. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
  57386. }
  57387. sqlite3VdbeResolveLabel(v, endOfLoop);
  57388. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
  57389. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  57390. /* Store the results.
  57391. **
  57392. ** The result is a single row of the sqlite_stat1 table. The first
  57393. ** two columns are the names of the table and index. The third column
  57394. ** is a string composed of a list of integer statistics about the
  57395. ** index. The first integer in the list is the total number of entries
  57396. ** in the index. There is one additional integer in the list for each
  57397. ** column of the table. This additional integer is a guess of how many
  57398. ** rows of the table the index will select. If D is the count of distinct
  57399. ** values and K is the total number of rows, then the integer is computed
  57400. ** as:
  57401. **
  57402. ** I = (K+D-1)/D
  57403. **
  57404. ** If K==0 then no entry is made into the sqlite_stat1 table.
  57405. ** If K>0 then it is always the case the D>0 so division by zero
  57406. ** is never possible.
  57407. */
  57408. addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
  57409. sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
  57410. sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
  57411. regF2 = regFields+2;
  57412. sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
  57413. for(i=0; i<nCol; i++){
  57414. sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
  57415. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
  57416. sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
  57417. sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
  57418. sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
  57419. sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
  57420. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
  57421. }
  57422. sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
  57423. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
  57424. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
  57425. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  57426. sqlite3VdbeJumpHere(v, addr);
  57427. }
  57428. }
  57429. /*
  57430. ** Generate code that will cause the most recent index analysis to
  57431. ** be laoded into internal hash tables where is can be used.
  57432. */
  57433. static void loadAnalysis(Parse *pParse, int iDb){
  57434. Vdbe *v = sqlite3GetVdbe(pParse);
  57435. if( v ){
  57436. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  57437. }
  57438. }
  57439. /*
  57440. ** Generate code that will do an analysis of an entire database
  57441. */
  57442. static void analyzeDatabase(Parse *pParse, int iDb){
  57443. sqlite3 *db = pParse->db;
  57444. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  57445. HashElem *k;
  57446. int iStatCur;
  57447. int iMem;
  57448. sqlite3BeginWriteOperation(pParse, 0, iDb);
  57449. iStatCur = pParse->nTab++;
  57450. openStatTable(pParse, iDb, iStatCur, 0);
  57451. iMem = pParse->nMem+1;
  57452. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  57453. Table *pTab = (Table*)sqliteHashData(k);
  57454. analyzeOneTable(pParse, pTab, iStatCur, iMem);
  57455. }
  57456. loadAnalysis(pParse, iDb);
  57457. }
  57458. /*
  57459. ** Generate code that will do an analysis of a single table in
  57460. ** a database.
  57461. */
  57462. static void analyzeTable(Parse *pParse, Table *pTab){
  57463. int iDb;
  57464. int iStatCur;
  57465. assert( pTab!=0 );
  57466. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  57467. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  57468. sqlite3BeginWriteOperation(pParse, 0, iDb);
  57469. iStatCur = pParse->nTab++;
  57470. openStatTable(pParse, iDb, iStatCur, pTab->zName);
  57471. analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
  57472. loadAnalysis(pParse, iDb);
  57473. }
  57474. /*
  57475. ** Generate code for the ANALYZE command. The parser calls this routine
  57476. ** when it recognizes an ANALYZE command.
  57477. **
  57478. ** ANALYZE -- 1
  57479. ** ANALYZE <database> -- 2
  57480. ** ANALYZE ?<database>.?<tablename> -- 3
  57481. **
  57482. ** Form 1 causes all indices in all attached databases to be analyzed.
  57483. ** Form 2 analyzes all indices the single database named.
  57484. ** Form 3 analyzes all indices associated with the named table.
  57485. */
  57486. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  57487. sqlite3 *db = pParse->db;
  57488. int iDb;
  57489. int i;
  57490. char *z, *zDb;
  57491. Table *pTab;
  57492. Token *pTableName;
  57493. /* Read the database schema. If an error occurs, leave an error message
  57494. ** and code in pParse and return NULL. */
  57495. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  57496. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  57497. return;
  57498. }
  57499. if( pName1==0 ){
  57500. /* Form 1: Analyze everything */
  57501. for(i=0; i<db->nDb; i++){
  57502. if( i==1 ) continue; /* Do not analyze the TEMP database */
  57503. analyzeDatabase(pParse, i);
  57504. }
  57505. }else if( pName2==0 || pName2->n==0 ){
  57506. /* Form 2: Analyze the database or table named */
  57507. iDb = sqlite3FindDb(db, pName1);
  57508. if( iDb>=0 ){
  57509. analyzeDatabase(pParse, iDb);
  57510. }else{
  57511. z = sqlite3NameFromToken(db, pName1);
  57512. if( z ){
  57513. pTab = sqlite3LocateTable(pParse, 0, z, 0);
  57514. sqlite3DbFree(db, z);
  57515. if( pTab ){
  57516. analyzeTable(pParse, pTab);
  57517. }
  57518. }
  57519. }
  57520. }else{
  57521. /* Form 3: Analyze the fully qualified table name */
  57522. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  57523. if( iDb>=0 ){
  57524. zDb = db->aDb[iDb].zName;
  57525. z = sqlite3NameFromToken(db, pTableName);
  57526. if( z ){
  57527. pTab = sqlite3LocateTable(pParse, 0, z, zDb);
  57528. sqlite3DbFree(db, z);
  57529. if( pTab ){
  57530. analyzeTable(pParse, pTab);
  57531. }
  57532. }
  57533. }
  57534. }
  57535. }
  57536. /*
  57537. ** Used to pass information from the analyzer reader through to the
  57538. ** callback routine.
  57539. */
  57540. typedef struct analysisInfo analysisInfo;
  57541. struct analysisInfo {
  57542. sqlite3 *db;
  57543. const char *zDatabase;
  57544. };
  57545. /*
  57546. ** This callback is invoked once for each index when reading the
  57547. ** sqlite_stat1 table.
  57548. **
  57549. ** argv[0] = name of the index
  57550. ** argv[1] = results of analysis - on integer for each column
  57551. */
  57552. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  57553. analysisInfo *pInfo = (analysisInfo*)pData;
  57554. Index *pIndex;
  57555. int i, c;
  57556. unsigned int v;
  57557. const char *z;
  57558. assert( argc==2 );
  57559. UNUSED_PARAMETER2(NotUsed, argc);
  57560. if( argv==0 || argv[0]==0 || argv[1]==0 ){
  57561. return 0;
  57562. }
  57563. pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
  57564. if( pIndex==0 ){
  57565. return 0;
  57566. }
  57567. z = argv[1];
  57568. for(i=0; *z && i<=pIndex->nColumn; i++){
  57569. v = 0;
  57570. while( (c=z[0])>='0' && c<='9' ){
  57571. v = v*10 + c - '0';
  57572. z++;
  57573. }
  57574. pIndex->aiRowEst[i] = v;
  57575. if( *z==' ' ) z++;
  57576. }
  57577. return 0;
  57578. }
  57579. /*
  57580. ** Load the content of the sqlite_stat1 table into the index hash tables.
  57581. */
  57582. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  57583. analysisInfo sInfo;
  57584. HashElem *i;
  57585. char *zSql;
  57586. int rc;
  57587. assert( iDb>=0 && iDb<db->nDb );
  57588. assert( db->aDb[iDb].pBt!=0 );
  57589. assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  57590. /* Clear any prior statistics */
  57591. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  57592. Index *pIdx = sqliteHashData(i);
  57593. sqlite3DefaultRowEst(pIdx);
  57594. }
  57595. /* Check to make sure the sqlite_stat1 table existss */
  57596. sInfo.db = db;
  57597. sInfo.zDatabase = db->aDb[iDb].zName;
  57598. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  57599. return SQLITE_ERROR;
  57600. }
  57601. /* Load new statistics out of the sqlite_stat1 table */
  57602. zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
  57603. sInfo.zDatabase);
  57604. if( zSql==0 ){
  57605. rc = SQLITE_NOMEM;
  57606. }else{
  57607. (void)sqlite3SafetyOff(db);
  57608. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  57609. (void)sqlite3SafetyOn(db);
  57610. sqlite3DbFree(db, zSql);
  57611. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  57612. }
  57613. return rc;
  57614. }
  57615. #endif /* SQLITE_OMIT_ANALYZE */
  57616. /************** End of analyze.c *********************************************/
  57617. /************** Begin file attach.c ******************************************/
  57618. /*
  57619. ** 2003 April 6
  57620. **
  57621. ** The author disclaims copyright to this source code. In place of
  57622. ** a legal notice, here is a blessing:
  57623. **
  57624. ** May you do good and not evil.
  57625. ** May you find forgiveness for yourself and forgive others.
  57626. ** May you share freely, never taking more than you give.
  57627. **
  57628. *************************************************************************
  57629. ** This file contains code used to implement the ATTACH and DETACH commands.
  57630. **
  57631. ** $Id: attach.c,v 1.84 2009/04/08 13:51:51 drh Exp $
  57632. */
  57633. #ifndef SQLITE_OMIT_ATTACH
  57634. /*
  57635. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  57636. ** is slightly different from resolving a normal SQL expression, because simple
  57637. ** identifiers are treated as strings, not possible column names or aliases.
  57638. **
  57639. ** i.e. if the parser sees:
  57640. **
  57641. ** ATTACH DATABASE abc AS def
  57642. **
  57643. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  57644. ** looking for columns of the same name.
  57645. **
  57646. ** This only applies to the root node of pExpr, so the statement:
  57647. **
  57648. ** ATTACH DATABASE abc||def AS 'db2'
  57649. **
  57650. ** will fail because neither abc or def can be resolved.
  57651. */
  57652. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  57653. {
  57654. int rc = SQLITE_OK;
  57655. if( pExpr ){
  57656. if( pExpr->op!=TK_ID ){
  57657. rc = sqlite3ResolveExprNames(pName, pExpr);
  57658. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  57659. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
  57660. return SQLITE_ERROR;
  57661. }
  57662. }else{
  57663. pExpr->op = TK_STRING;
  57664. }
  57665. }
  57666. return rc;
  57667. }
  57668. /*
  57669. ** An SQL user-function registered to do the work of an ATTACH statement. The
  57670. ** three arguments to the function come directly from an attach statement:
  57671. **
  57672. ** ATTACH DATABASE x AS y KEY z
  57673. **
  57674. ** SELECT sqlite_attach(x, y, z)
  57675. **
  57676. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  57677. ** third argument.
  57678. */
  57679. static void attachFunc(
  57680. sqlite3_context *context,
  57681. int NotUsed,
  57682. sqlite3_value **argv
  57683. ){
  57684. int i;
  57685. int rc = 0;
  57686. sqlite3 *db = sqlite3_context_db_handle(context);
  57687. const char *zName;
  57688. const char *zFile;
  57689. Db *aNew;
  57690. char *zErrDyn = 0;
  57691. char zErr[128];
  57692. UNUSED_PARAMETER(NotUsed);
  57693. zFile = (const char *)sqlite3_value_text(argv[0]);
  57694. zName = (const char *)sqlite3_value_text(argv[1]);
  57695. if( zFile==0 ) zFile = "";
  57696. if( zName==0 ) zName = "";
  57697. /* Check for the following errors:
  57698. **
  57699. ** * Too many attached databases,
  57700. ** * Transaction currently open
  57701. ** * Specified database name already being used.
  57702. */
  57703. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  57704. sqlite3_snprintf(
  57705. sizeof(zErr), zErr, "too many attached databases - max %d",
  57706. db->aLimit[SQLITE_LIMIT_ATTACHED]
  57707. );
  57708. goto attach_error;
  57709. }
  57710. if( !db->autoCommit ){
  57711. sqlite3_snprintf(sizeof(zErr), zErr,
  57712. "cannot ATTACH database within transaction");
  57713. goto attach_error;
  57714. }
  57715. for(i=0; i<db->nDb; i++){
  57716. char *z = db->aDb[i].zName;
  57717. if( z && zName && sqlite3StrICmp(z, zName)==0 ){
  57718. sqlite3_snprintf(sizeof(zErr), zErr,
  57719. "database %s is already in use", zName);
  57720. goto attach_error;
  57721. }
  57722. }
  57723. /* Allocate the new entry in the db->aDb[] array and initialise the schema
  57724. ** hash tables.
  57725. */
  57726. if( db->aDb==db->aDbStatic ){
  57727. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  57728. if( aNew==0 ) return;
  57729. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  57730. }else{
  57731. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  57732. if( aNew==0 ) return;
  57733. }
  57734. db->aDb = aNew;
  57735. aNew = &db->aDb[db->nDb++];
  57736. memset(aNew, 0, sizeof(*aNew));
  57737. /* Open the database file. If the btree is successfully opened, use
  57738. ** it to obtain the database schema. At this point the schema may
  57739. ** or may not be initialised.
  57740. */
  57741. rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
  57742. db->openFlags | SQLITE_OPEN_MAIN_DB,
  57743. &aNew->pBt);
  57744. if( rc==SQLITE_OK ){
  57745. Pager *pPager;
  57746. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  57747. if( !aNew->pSchema ){
  57748. rc = SQLITE_NOMEM;
  57749. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  57750. sqlite3_snprintf(sizeof(zErr), zErr,
  57751. "attached databases must use the same text encoding as main database");
  57752. goto attach_error;
  57753. }
  57754. pPager = sqlite3BtreePager(aNew->pBt);
  57755. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  57756. sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
  57757. }
  57758. aNew->zName = sqlite3DbStrDup(db, zName);
  57759. aNew->safety_level = 3;
  57760. #if SQLITE_HAS_CODEC
  57761. {
  57762. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  57763. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  57764. int nKey;
  57765. char *zKey;
  57766. int t = sqlite3_value_type(argv[2]);
  57767. switch( t ){
  57768. case SQLITE_INTEGER:
  57769. case SQLITE_FLOAT:
  57770. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  57771. rc = SQLITE_ERROR;
  57772. break;
  57773. case SQLITE_TEXT:
  57774. case SQLITE_BLOB:
  57775. nKey = sqlite3_value_bytes(argv[2]);
  57776. zKey = (char *)sqlite3_value_blob(argv[2]);
  57777. sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  57778. break;
  57779. case SQLITE_NULL:
  57780. /* No key specified. Use the key from the main database */
  57781. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  57782. sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  57783. break;
  57784. }
  57785. }
  57786. #endif
  57787. /* If the file was opened successfully, read the schema for the new database.
  57788. ** If this fails, or if opening the file failed, then close the file and
  57789. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  57790. ** we found it.
  57791. */
  57792. if( rc==SQLITE_OK ){
  57793. (void)sqlite3SafetyOn(db);
  57794. sqlite3BtreeEnterAll(db);
  57795. rc = sqlite3Init(db, &zErrDyn);
  57796. sqlite3BtreeLeaveAll(db);
  57797. (void)sqlite3SafetyOff(db);
  57798. }
  57799. if( rc ){
  57800. int iDb = db->nDb - 1;
  57801. assert( iDb>=2 );
  57802. if( db->aDb[iDb].pBt ){
  57803. sqlite3BtreeClose(db->aDb[iDb].pBt);
  57804. db->aDb[iDb].pBt = 0;
  57805. db->aDb[iDb].pSchema = 0;
  57806. }
  57807. sqlite3ResetInternalSchema(db, 0);
  57808. db->nDb = iDb;
  57809. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  57810. db->mallocFailed = 1;
  57811. sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
  57812. }else{
  57813. sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
  57814. }
  57815. goto attach_error;
  57816. }
  57817. return;
  57818. attach_error:
  57819. /* Return an error if we get here */
  57820. if( zErrDyn ){
  57821. sqlite3_result_error(context, zErrDyn, -1);
  57822. sqlite3DbFree(db, zErrDyn);
  57823. }else{
  57824. zErr[sizeof(zErr)-1] = 0;
  57825. sqlite3_result_error(context, zErr, -1);
  57826. }
  57827. if( rc ) sqlite3_result_error_code(context, rc);
  57828. }
  57829. /*
  57830. ** An SQL user-function registered to do the work of an DETACH statement. The
  57831. ** three arguments to the function come directly from a detach statement:
  57832. **
  57833. ** DETACH DATABASE x
  57834. **
  57835. ** SELECT sqlite_detach(x)
  57836. */
  57837. static void detachFunc(
  57838. sqlite3_context *context,
  57839. int NotUsed,
  57840. sqlite3_value **argv
  57841. ){
  57842. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  57843. sqlite3 *db = sqlite3_context_db_handle(context);
  57844. int i;
  57845. Db *pDb = 0;
  57846. char zErr[128];
  57847. UNUSED_PARAMETER(NotUsed);
  57848. if( zName==0 ) zName = "";
  57849. for(i=0; i<db->nDb; i++){
  57850. pDb = &db->aDb[i];
  57851. if( pDb->pBt==0 ) continue;
  57852. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  57853. }
  57854. if( i>=db->nDb ){
  57855. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  57856. goto detach_error;
  57857. }
  57858. if( i<2 ){
  57859. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  57860. goto detach_error;
  57861. }
  57862. if( !db->autoCommit ){
  57863. sqlite3_snprintf(sizeof(zErr), zErr,
  57864. "cannot DETACH database within transaction");
  57865. goto detach_error;
  57866. }
  57867. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  57868. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  57869. goto detach_error;
  57870. }
  57871. sqlite3BtreeClose(pDb->pBt);
  57872. pDb->pBt = 0;
  57873. pDb->pSchema = 0;
  57874. sqlite3ResetInternalSchema(db, 0);
  57875. return;
  57876. detach_error:
  57877. sqlite3_result_error(context, zErr, -1);
  57878. }
  57879. /*
  57880. ** This procedure generates VDBE code for a single invocation of either the
  57881. ** sqlite_detach() or sqlite_attach() SQL user functions.
  57882. */
  57883. static void codeAttach(
  57884. Parse *pParse, /* The parser context */
  57885. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  57886. FuncDef *pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
  57887. Expr *pAuthArg, /* Expression to pass to authorization callback */
  57888. Expr *pFilename, /* Name of database file */
  57889. Expr *pDbname, /* Name of the database to use internally */
  57890. Expr *pKey /* Database key for encryption extension */
  57891. ){
  57892. int rc;
  57893. NameContext sName;
  57894. Vdbe *v;
  57895. sqlite3* db = pParse->db;
  57896. int regArgs;
  57897. #ifndef SQLITE_OMIT_AUTHORIZATION
  57898. assert( db->mallocFailed || pAuthArg );
  57899. if( pAuthArg ){
  57900. char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
  57901. if( !zAuthArg ){
  57902. goto attach_end;
  57903. }
  57904. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  57905. sqlite3DbFree(db, zAuthArg);
  57906. if(rc!=SQLITE_OK ){
  57907. goto attach_end;
  57908. }
  57909. }
  57910. #endif /* SQLITE_OMIT_AUTHORIZATION */
  57911. memset(&sName, 0, sizeof(NameContext));
  57912. sName.pParse = pParse;
  57913. if(
  57914. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  57915. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  57916. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  57917. ){
  57918. pParse->nErr++;
  57919. goto attach_end;
  57920. }
  57921. v = sqlite3GetVdbe(pParse);
  57922. regArgs = sqlite3GetTempRange(pParse, 4);
  57923. sqlite3ExprCode(pParse, pFilename, regArgs);
  57924. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  57925. sqlite3ExprCode(pParse, pKey, regArgs+2);
  57926. assert( v || db->mallocFailed );
  57927. if( v ){
  57928. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  57929. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  57930. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  57931. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  57932. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  57933. ** statement only). For DETACH, set it to false (expire all existing
  57934. ** statements).
  57935. */
  57936. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  57937. }
  57938. attach_end:
  57939. sqlite3ExprDelete(db, pFilename);
  57940. sqlite3ExprDelete(db, pDbname);
  57941. sqlite3ExprDelete(db, pKey);
  57942. }
  57943. /*
  57944. ** Called by the parser to compile a DETACH statement.
  57945. **
  57946. ** DETACH pDbname
  57947. */
  57948. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  57949. static FuncDef detach_func = {
  57950. 1, /* nArg */
  57951. SQLITE_UTF8, /* iPrefEnc */
  57952. 0, /* flags */
  57953. 0, /* pUserData */
  57954. 0, /* pNext */
  57955. detachFunc, /* xFunc */
  57956. 0, /* xStep */
  57957. 0, /* xFinalize */
  57958. "sqlite_detach", /* zName */
  57959. 0 /* pHash */
  57960. };
  57961. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  57962. }
  57963. /*
  57964. ** Called by the parser to compile an ATTACH statement.
  57965. **
  57966. ** ATTACH p AS pDbname KEY pKey
  57967. */
  57968. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  57969. static FuncDef attach_func = {
  57970. 3, /* nArg */
  57971. SQLITE_UTF8, /* iPrefEnc */
  57972. 0, /* flags */
  57973. 0, /* pUserData */
  57974. 0, /* pNext */
  57975. attachFunc, /* xFunc */
  57976. 0, /* xStep */
  57977. 0, /* xFinalize */
  57978. "sqlite_attach", /* zName */
  57979. 0 /* pHash */
  57980. };
  57981. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  57982. }
  57983. #endif /* SQLITE_OMIT_ATTACH */
  57984. /*
  57985. ** Initialize a DbFixer structure. This routine must be called prior
  57986. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  57987. **
  57988. ** The return value indicates whether or not fixation is required. TRUE
  57989. ** means we do need to fix the database references, FALSE means we do not.
  57990. */
  57991. SQLITE_PRIVATE int sqlite3FixInit(
  57992. DbFixer *pFix, /* The fixer to be initialized */
  57993. Parse *pParse, /* Error messages will be written here */
  57994. int iDb, /* This is the database that must be used */
  57995. const char *zType, /* "view", "trigger", or "index" */
  57996. const Token *pName /* Name of the view, trigger, or index */
  57997. ){
  57998. sqlite3 *db;
  57999. if( iDb<0 || iDb==1 ) return 0;
  58000. db = pParse->db;
  58001. assert( db->nDb>iDb );
  58002. pFix->pParse = pParse;
  58003. pFix->zDb = db->aDb[iDb].zName;
  58004. pFix->zType = zType;
  58005. pFix->pName = pName;
  58006. return 1;
  58007. }
  58008. /*
  58009. ** The following set of routines walk through the parse tree and assign
  58010. ** a specific database to all table references where the database name
  58011. ** was left unspecified in the original SQL statement. The pFix structure
  58012. ** must have been initialized by a prior call to sqlite3FixInit().
  58013. **
  58014. ** These routines are used to make sure that an index, trigger, or
  58015. ** view in one database does not refer to objects in a different database.
  58016. ** (Exception: indices, triggers, and views in the TEMP database are
  58017. ** allowed to refer to anything.) If a reference is explicitly made
  58018. ** to an object in a different database, an error message is added to
  58019. ** pParse->zErrMsg and these routines return non-zero. If everything
  58020. ** checks out, these routines return 0.
  58021. */
  58022. SQLITE_PRIVATE int sqlite3FixSrcList(
  58023. DbFixer *pFix, /* Context of the fixation */
  58024. SrcList *pList /* The Source list to check and modify */
  58025. ){
  58026. int i;
  58027. const char *zDb;
  58028. struct SrcList_item *pItem;
  58029. if( pList==0 ) return 0;
  58030. zDb = pFix->zDb;
  58031. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  58032. if( pItem->zDatabase==0 ){
  58033. pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
  58034. }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
  58035. sqlite3ErrorMsg(pFix->pParse,
  58036. "%s %T cannot reference objects in database %s",
  58037. pFix->zType, pFix->pName, pItem->zDatabase);
  58038. return 1;
  58039. }
  58040. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  58041. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  58042. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  58043. #endif
  58044. }
  58045. return 0;
  58046. }
  58047. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  58048. SQLITE_PRIVATE int sqlite3FixSelect(
  58049. DbFixer *pFix, /* Context of the fixation */
  58050. Select *pSelect /* The SELECT statement to be fixed to one database */
  58051. ){
  58052. while( pSelect ){
  58053. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  58054. return 1;
  58055. }
  58056. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  58057. return 1;
  58058. }
  58059. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  58060. return 1;
  58061. }
  58062. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  58063. return 1;
  58064. }
  58065. pSelect = pSelect->pPrior;
  58066. }
  58067. return 0;
  58068. }
  58069. SQLITE_PRIVATE int sqlite3FixExpr(
  58070. DbFixer *pFix, /* Context of the fixation */
  58071. Expr *pExpr /* The expression to be fixed to one database */
  58072. ){
  58073. while( pExpr ){
  58074. if( ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_SpanToken) ) break;
  58075. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  58076. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  58077. }else{
  58078. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  58079. }
  58080. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  58081. return 1;
  58082. }
  58083. pExpr = pExpr->pLeft;
  58084. }
  58085. return 0;
  58086. }
  58087. SQLITE_PRIVATE int sqlite3FixExprList(
  58088. DbFixer *pFix, /* Context of the fixation */
  58089. ExprList *pList /* The expression to be fixed to one database */
  58090. ){
  58091. int i;
  58092. struct ExprList_item *pItem;
  58093. if( pList==0 ) return 0;
  58094. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  58095. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  58096. return 1;
  58097. }
  58098. }
  58099. return 0;
  58100. }
  58101. #endif
  58102. #ifndef SQLITE_OMIT_TRIGGER
  58103. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  58104. DbFixer *pFix, /* Context of the fixation */
  58105. TriggerStep *pStep /* The trigger step be fixed to one database */
  58106. ){
  58107. while( pStep ){
  58108. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  58109. return 1;
  58110. }
  58111. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  58112. return 1;
  58113. }
  58114. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  58115. return 1;
  58116. }
  58117. pStep = pStep->pNext;
  58118. }
  58119. return 0;
  58120. }
  58121. #endif
  58122. /************** End of attach.c **********************************************/
  58123. /************** Begin file auth.c ********************************************/
  58124. /*
  58125. ** 2003 January 11
  58126. **
  58127. ** The author disclaims copyright to this source code. In place of
  58128. ** a legal notice, here is a blessing:
  58129. **
  58130. ** May you do good and not evil.
  58131. ** May you find forgiveness for yourself and forgive others.
  58132. ** May you share freely, never taking more than you give.
  58133. **
  58134. *************************************************************************
  58135. ** This file contains code used to implement the sqlite3_set_authorizer()
  58136. ** API. This facility is an optional feature of the library. Embedded
  58137. ** systems that do not need this facility may omit it by recompiling
  58138. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  58139. **
  58140. ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
  58141. */
  58142. /*
  58143. ** All of the code in this file may be omitted by defining a single
  58144. ** macro.
  58145. */
  58146. #ifndef SQLITE_OMIT_AUTHORIZATION
  58147. /*
  58148. ** Set or clear the access authorization function.
  58149. **
  58150. ** The access authorization function is be called during the compilation
  58151. ** phase to verify that the user has read and/or write access permission on
  58152. ** various fields of the database. The first argument to the auth function
  58153. ** is a copy of the 3rd argument to this routine. The second argument
  58154. ** to the auth function is one of these constants:
  58155. **
  58156. ** SQLITE_CREATE_INDEX
  58157. ** SQLITE_CREATE_TABLE
  58158. ** SQLITE_CREATE_TEMP_INDEX
  58159. ** SQLITE_CREATE_TEMP_TABLE
  58160. ** SQLITE_CREATE_TEMP_TRIGGER
  58161. ** SQLITE_CREATE_TEMP_VIEW
  58162. ** SQLITE_CREATE_TRIGGER
  58163. ** SQLITE_CREATE_VIEW
  58164. ** SQLITE_DELETE
  58165. ** SQLITE_DROP_INDEX
  58166. ** SQLITE_DROP_TABLE
  58167. ** SQLITE_DROP_TEMP_INDEX
  58168. ** SQLITE_DROP_TEMP_TABLE
  58169. ** SQLITE_DROP_TEMP_TRIGGER
  58170. ** SQLITE_DROP_TEMP_VIEW
  58171. ** SQLITE_DROP_TRIGGER
  58172. ** SQLITE_DROP_VIEW
  58173. ** SQLITE_INSERT
  58174. ** SQLITE_PRAGMA
  58175. ** SQLITE_READ
  58176. ** SQLITE_SELECT
  58177. ** SQLITE_TRANSACTION
  58178. ** SQLITE_UPDATE
  58179. **
  58180. ** The third and fourth arguments to the auth function are the name of
  58181. ** the table and the column that are being accessed. The auth function
  58182. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  58183. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  58184. ** means that the SQL statement will never-run - the sqlite3_exec() call
  58185. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  58186. ** should run but attempts to read the specified column will return NULL
  58187. ** and attempts to write the column will be ignored.
  58188. **
  58189. ** Setting the auth function to NULL disables this hook. The default
  58190. ** setting of the auth function is NULL.
  58191. */
  58192. SQLITE_API int sqlite3_set_authorizer(
  58193. sqlite3 *db,
  58194. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  58195. void *pArg
  58196. ){
  58197. sqlite3_mutex_enter(db->mutex);
  58198. db->xAuth = xAuth;
  58199. db->pAuthArg = pArg;
  58200. sqlite3ExpirePreparedStatements(db);
  58201. sqlite3_mutex_leave(db->mutex);
  58202. return SQLITE_OK;
  58203. }
  58204. /*
  58205. ** Write an error message into pParse->zErrMsg that explains that the
  58206. ** user-supplied authorization function returned an illegal value.
  58207. */
  58208. static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
  58209. sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
  58210. "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
  58211. "or SQLITE_DENY", rc);
  58212. pParse->rc = SQLITE_ERROR;
  58213. }
  58214. /*
  58215. ** The pExpr should be a TK_COLUMN expression. The table referred to
  58216. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  58217. ** Check to see if it is OK to read this particular column.
  58218. **
  58219. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  58220. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  58221. ** then generate an error.
  58222. */
  58223. SQLITE_PRIVATE void sqlite3AuthRead(
  58224. Parse *pParse, /* The parser context */
  58225. Expr *pExpr, /* The expression to check authorization on */
  58226. Schema *pSchema, /* The schema of the expression */
  58227. SrcList *pTabList /* All table that pExpr might refer to */
  58228. ){
  58229. sqlite3 *db = pParse->db;
  58230. int rc;
  58231. Table *pTab = 0; /* The table being read */
  58232. const char *zCol; /* Name of the column of the table */
  58233. int iSrc; /* Index in pTabList->a[] of table being read */
  58234. const char *zDBase; /* Name of database being accessed */
  58235. TriggerStack *pStack; /* The stack of current triggers */
  58236. int iDb; /* The index of the database the expression refers to */
  58237. if( db->xAuth==0 ) return;
  58238. if( pExpr->op!=TK_COLUMN ) return;
  58239. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  58240. if( iDb<0 ){
  58241. /* An attempt to read a column out of a subquery or other
  58242. ** temporary table. */
  58243. return;
  58244. }
  58245. for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
  58246. if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
  58247. }
  58248. if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
  58249. pTab = pTabList->a[iSrc].pTab;
  58250. }else if( (pStack = pParse->trigStack)!=0 ){
  58251. /* This must be an attempt to read the NEW or OLD pseudo-tables
  58252. ** of a trigger.
  58253. */
  58254. assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
  58255. pTab = pStack->pTab;
  58256. }
  58257. if( pTab==0 ) return;
  58258. if( pExpr->iColumn>=0 ){
  58259. assert( pExpr->iColumn<pTab->nCol );
  58260. zCol = pTab->aCol[pExpr->iColumn].zName;
  58261. }else if( pTab->iPKey>=0 ){
  58262. assert( pTab->iPKey<pTab->nCol );
  58263. zCol = pTab->aCol[pTab->iPKey].zName;
  58264. }else{
  58265. zCol = "ROWID";
  58266. }
  58267. assert( iDb>=0 && iDb<db->nDb );
  58268. zDBase = db->aDb[iDb].zName;
  58269. rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
  58270. pParse->zAuthContext);
  58271. if( rc==SQLITE_IGNORE ){
  58272. pExpr->op = TK_NULL;
  58273. }else if( rc==SQLITE_DENY ){
  58274. if( db->nDb>2 || iDb!=0 ){
  58275. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",
  58276. zDBase, pTab->zName, zCol);
  58277. }else{
  58278. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
  58279. }
  58280. pParse->rc = SQLITE_AUTH;
  58281. }else if( rc!=SQLITE_OK ){
  58282. sqliteAuthBadReturnCode(pParse, rc);
  58283. }
  58284. }
  58285. /*
  58286. ** Do an authorization check using the code and arguments given. Return
  58287. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  58288. ** is returned, then the error count and error message in pParse are
  58289. ** modified appropriately.
  58290. */
  58291. SQLITE_PRIVATE int sqlite3AuthCheck(
  58292. Parse *pParse,
  58293. int code,
  58294. const char *zArg1,
  58295. const char *zArg2,
  58296. const char *zArg3
  58297. ){
  58298. sqlite3 *db = pParse->db;
  58299. int rc;
  58300. /* Don't do any authorization checks if the database is initialising
  58301. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  58302. */
  58303. if( db->init.busy || IN_DECLARE_VTAB ){
  58304. return SQLITE_OK;
  58305. }
  58306. if( db->xAuth==0 ){
  58307. return SQLITE_OK;
  58308. }
  58309. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  58310. if( rc==SQLITE_DENY ){
  58311. sqlite3ErrorMsg(pParse, "not authorized");
  58312. pParse->rc = SQLITE_AUTH;
  58313. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  58314. rc = SQLITE_DENY;
  58315. sqliteAuthBadReturnCode(pParse, rc);
  58316. }
  58317. return rc;
  58318. }
  58319. /*
  58320. ** Push an authorization context. After this routine is called, the
  58321. ** zArg3 argument to authorization callbacks will be zContext until
  58322. ** popped. Or if pParse==0, this routine is a no-op.
  58323. */
  58324. SQLITE_PRIVATE void sqlite3AuthContextPush(
  58325. Parse *pParse,
  58326. AuthContext *pContext,
  58327. const char *zContext
  58328. ){
  58329. pContext->pParse = pParse;
  58330. if( pParse ){
  58331. pContext->zAuthContext = pParse->zAuthContext;
  58332. pParse->zAuthContext = zContext;
  58333. }
  58334. }
  58335. /*
  58336. ** Pop an authorization context that was previously pushed
  58337. ** by sqlite3AuthContextPush
  58338. */
  58339. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  58340. if( pContext->pParse ){
  58341. pContext->pParse->zAuthContext = pContext->zAuthContext;
  58342. pContext->pParse = 0;
  58343. }
  58344. }
  58345. #endif /* SQLITE_OMIT_AUTHORIZATION */
  58346. /************** End of auth.c ************************************************/
  58347. /************** Begin file build.c *******************************************/
  58348. /*
  58349. ** 2001 September 15
  58350. **
  58351. ** The author disclaims copyright to this source code. In place of
  58352. ** a legal notice, here is a blessing:
  58353. **
  58354. ** May you do good and not evil.
  58355. ** May you find forgiveness for yourself and forgive others.
  58356. ** May you share freely, never taking more than you give.
  58357. **
  58358. *************************************************************************
  58359. ** This file contains C code routines that are called by the SQLite parser
  58360. ** when syntax rules are reduced. The routines in this file handle the
  58361. ** following kinds of SQL syntax:
  58362. **
  58363. ** CREATE TABLE
  58364. ** DROP TABLE
  58365. ** CREATE INDEX
  58366. ** DROP INDEX
  58367. ** creating ID lists
  58368. ** BEGIN TRANSACTION
  58369. ** COMMIT
  58370. ** ROLLBACK
  58371. **
  58372. ** $Id: build.c,v 1.528 2009/04/08 13:51:51 drh Exp $
  58373. */
  58374. /*
  58375. ** This routine is called when a new SQL statement is beginning to
  58376. ** be parsed. Initialize the pParse structure as needed.
  58377. */
  58378. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  58379. pParse->explain = (u8)explainFlag;
  58380. pParse->nVar = 0;
  58381. }
  58382. #ifndef SQLITE_OMIT_SHARED_CACHE
  58383. /*
  58384. ** The TableLock structure is only used by the sqlite3TableLock() and
  58385. ** codeTableLocks() functions.
  58386. */
  58387. struct TableLock {
  58388. int iDb; /* The database containing the table to be locked */
  58389. int iTab; /* The root page of the table to be locked */
  58390. u8 isWriteLock; /* True for write lock. False for a read lock */
  58391. const char *zName; /* Name of the table */
  58392. };
  58393. /*
  58394. ** Record the fact that we want to lock a table at run-time.
  58395. **
  58396. ** The table to be locked has root page iTab and is found in database iDb.
  58397. ** A read or a write lock can be taken depending on isWritelock.
  58398. **
  58399. ** This routine just records the fact that the lock is desired. The
  58400. ** code to make the lock occur is generated by a later call to
  58401. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  58402. */
  58403. SQLITE_PRIVATE void sqlite3TableLock(
  58404. Parse *pParse, /* Parsing context */
  58405. int iDb, /* Index of the database containing the table to lock */
  58406. int iTab, /* Root page number of the table to be locked */
  58407. u8 isWriteLock, /* True for a write lock */
  58408. const char *zName /* Name of the table to be locked */
  58409. ){
  58410. int i;
  58411. int nBytes;
  58412. TableLock *p;
  58413. if( iDb<0 ){
  58414. return;
  58415. }
  58416. for(i=0; i<pParse->nTableLock; i++){
  58417. p = &pParse->aTableLock[i];
  58418. if( p->iDb==iDb && p->iTab==iTab ){
  58419. p->isWriteLock = (p->isWriteLock || isWriteLock);
  58420. return;
  58421. }
  58422. }
  58423. nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
  58424. pParse->aTableLock =
  58425. sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
  58426. if( pParse->aTableLock ){
  58427. p = &pParse->aTableLock[pParse->nTableLock++];
  58428. p->iDb = iDb;
  58429. p->iTab = iTab;
  58430. p->isWriteLock = isWriteLock;
  58431. p->zName = zName;
  58432. }else{
  58433. pParse->nTableLock = 0;
  58434. pParse->db->mallocFailed = 1;
  58435. }
  58436. }
  58437. /*
  58438. ** Code an OP_TableLock instruction for each table locked by the
  58439. ** statement (configured by calls to sqlite3TableLock()).
  58440. */
  58441. static void codeTableLocks(Parse *pParse){
  58442. int i;
  58443. Vdbe *pVdbe;
  58444. if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
  58445. return;
  58446. }
  58447. for(i=0; i<pParse->nTableLock; i++){
  58448. TableLock *p = &pParse->aTableLock[i];
  58449. int p1 = p->iDb;
  58450. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  58451. p->zName, P4_STATIC);
  58452. }
  58453. }
  58454. #else
  58455. #define codeTableLocks(x)
  58456. #endif
  58457. /*
  58458. ** This routine is called after a single SQL statement has been
  58459. ** parsed and a VDBE program to execute that statement has been
  58460. ** prepared. This routine puts the finishing touches on the
  58461. ** VDBE program and resets the pParse structure for the next
  58462. ** parse.
  58463. **
  58464. ** Note that if an error occurred, it might be the case that
  58465. ** no VDBE code was generated.
  58466. */
  58467. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  58468. sqlite3 *db;
  58469. Vdbe *v;
  58470. db = pParse->db;
  58471. if( db->mallocFailed ) return;
  58472. if( pParse->nested ) return;
  58473. if( pParse->nErr ) return;
  58474. /* Begin by generating some termination code at the end of the
  58475. ** vdbe program
  58476. */
  58477. v = sqlite3GetVdbe(pParse);
  58478. if( v ){
  58479. sqlite3VdbeAddOp0(v, OP_Halt);
  58480. /* The cookie mask contains one bit for each database file open.
  58481. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  58482. ** set for each database that is used. Generate code to start a
  58483. ** transaction on each used database and to verify the schema cookie
  58484. ** on each used database.
  58485. */
  58486. if( pParse->cookieGoto>0 ){
  58487. u32 mask;
  58488. int iDb;
  58489. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  58490. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  58491. if( (mask & pParse->cookieMask)==0 ) continue;
  58492. sqlite3VdbeUsesBtree(v, iDb);
  58493. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  58494. sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
  58495. }
  58496. #ifndef SQLITE_OMIT_VIRTUALTABLE
  58497. {
  58498. int i;
  58499. for(i=0; i<pParse->nVtabLock; i++){
  58500. char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
  58501. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  58502. }
  58503. pParse->nVtabLock = 0;
  58504. }
  58505. #endif
  58506. /* Once all the cookies have been verified and transactions opened,
  58507. ** obtain the required table-locks. This is a no-op unless the
  58508. ** shared-cache feature is enabled.
  58509. */
  58510. codeTableLocks(pParse);
  58511. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  58512. }
  58513. }
  58514. /* Get the VDBE program ready for execution
  58515. */
  58516. if( v && pParse->nErr==0 && !db->mallocFailed ){
  58517. #ifdef SQLITE_DEBUG
  58518. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  58519. sqlite3VdbeTrace(v, trace);
  58520. #endif
  58521. assert( pParse->disableColCache==0 ); /* Disables and re-enables match */
  58522. sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
  58523. pParse->nTab, pParse->explain);
  58524. pParse->rc = SQLITE_DONE;
  58525. pParse->colNamesSet = 0;
  58526. }else if( pParse->rc==SQLITE_OK ){
  58527. pParse->rc = SQLITE_ERROR;
  58528. }
  58529. pParse->nTab = 0;
  58530. pParse->nMem = 0;
  58531. pParse->nSet = 0;
  58532. pParse->nVar = 0;
  58533. pParse->cookieMask = 0;
  58534. pParse->cookieGoto = 0;
  58535. }
  58536. /*
  58537. ** Run the parser and code generator recursively in order to generate
  58538. ** code for the SQL statement given onto the end of the pParse context
  58539. ** currently under construction. When the parser is run recursively
  58540. ** this way, the final OP_Halt is not appended and other initialization
  58541. ** and finalization steps are omitted because those are handling by the
  58542. ** outermost parser.
  58543. **
  58544. ** Not everything is nestable. This facility is designed to permit
  58545. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  58546. ** care if you decide to try to use this routine for some other purposes.
  58547. */
  58548. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  58549. va_list ap;
  58550. char *zSql;
  58551. char *zErrMsg = 0;
  58552. sqlite3 *db = pParse->db;
  58553. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  58554. char saveBuf[SAVE_SZ];
  58555. if( pParse->nErr ) return;
  58556. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  58557. va_start(ap, zFormat);
  58558. zSql = sqlite3VMPrintf(db, zFormat, ap);
  58559. va_end(ap);
  58560. if( zSql==0 ){
  58561. return; /* A malloc must have failed */
  58562. }
  58563. pParse->nested++;
  58564. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  58565. memset(&pParse->nVar, 0, SAVE_SZ);
  58566. sqlite3RunParser(pParse, zSql, &zErrMsg);
  58567. sqlite3DbFree(db, zErrMsg);
  58568. sqlite3DbFree(db, zSql);
  58569. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  58570. pParse->nested--;
  58571. }
  58572. /*
  58573. ** Locate the in-memory structure that describes a particular database
  58574. ** table given the name of that table and (optionally) the name of the
  58575. ** database containing the table. Return NULL if not found.
  58576. **
  58577. ** If zDatabase is 0, all databases are searched for the table and the
  58578. ** first matching table is returned. (No checking for duplicate table
  58579. ** names is done.) The search order is TEMP first, then MAIN, then any
  58580. ** auxiliary databases added using the ATTACH command.
  58581. **
  58582. ** See also sqlite3LocateTable().
  58583. */
  58584. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  58585. Table *p = 0;
  58586. int i;
  58587. int nName;
  58588. assert( zName!=0 );
  58589. nName = sqlite3Strlen(db, zName) + 1;
  58590. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  58591. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  58592. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  58593. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  58594. if( p ) break;
  58595. }
  58596. return p;
  58597. }
  58598. /*
  58599. ** Locate the in-memory structure that describes a particular database
  58600. ** table given the name of that table and (optionally) the name of the
  58601. ** database containing the table. Return NULL if not found. Also leave an
  58602. ** error message in pParse->zErrMsg.
  58603. **
  58604. ** The difference between this routine and sqlite3FindTable() is that this
  58605. ** routine leaves an error message in pParse->zErrMsg where
  58606. ** sqlite3FindTable() does not.
  58607. */
  58608. SQLITE_PRIVATE Table *sqlite3LocateTable(
  58609. Parse *pParse, /* context in which to report errors */
  58610. int isView, /* True if looking for a VIEW rather than a TABLE */
  58611. const char *zName, /* Name of the table we are looking for */
  58612. const char *zDbase /* Name of the database. Might be NULL */
  58613. ){
  58614. Table *p;
  58615. /* Read the database schema. If an error occurs, leave an error message
  58616. ** and code in pParse and return NULL. */
  58617. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  58618. return 0;
  58619. }
  58620. p = sqlite3FindTable(pParse->db, zName, zDbase);
  58621. if( p==0 ){
  58622. const char *zMsg = isView ? "no such view" : "no such table";
  58623. if( zDbase ){
  58624. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  58625. }else{
  58626. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  58627. }
  58628. pParse->checkSchema = 1;
  58629. }
  58630. return p;
  58631. }
  58632. /*
  58633. ** Locate the in-memory structure that describes
  58634. ** a particular index given the name of that index
  58635. ** and the name of the database that contains the index.
  58636. ** Return NULL if not found.
  58637. **
  58638. ** If zDatabase is 0, all databases are searched for the
  58639. ** table and the first matching index is returned. (No checking
  58640. ** for duplicate index names is done.) The search order is
  58641. ** TEMP first, then MAIN, then any auxiliary databases added
  58642. ** using the ATTACH command.
  58643. */
  58644. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  58645. Index *p = 0;
  58646. int i;
  58647. int nName = sqlite3Strlen(db, zName)+1;
  58648. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  58649. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  58650. Schema *pSchema = db->aDb[j].pSchema;
  58651. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  58652. assert( pSchema || (j==1 && !db->aDb[1].pBt) );
  58653. if( pSchema ){
  58654. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  58655. }
  58656. if( p ) break;
  58657. }
  58658. return p;
  58659. }
  58660. /*
  58661. ** Reclaim the memory used by an index
  58662. */
  58663. static void freeIndex(Index *p){
  58664. sqlite3 *db = p->pTable->dbMem;
  58665. sqlite3DbFree(db, p->zColAff);
  58666. sqlite3DbFree(db, p);
  58667. }
  58668. /*
  58669. ** Remove the given index from the index hash table, and free
  58670. ** its memory structures.
  58671. **
  58672. ** The index is removed from the database hash tables but
  58673. ** it is not unlinked from the Table that it indexes.
  58674. ** Unlinking from the Table must be done by the calling function.
  58675. */
  58676. static void sqlite3DeleteIndex(Index *p){
  58677. Index *pOld;
  58678. const char *zName = p->zName;
  58679. pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
  58680. sqlite3Strlen30(zName)+1, 0);
  58681. assert( pOld==0 || pOld==p );
  58682. freeIndex(p);
  58683. }
  58684. /*
  58685. ** For the index called zIdxName which is found in the database iDb,
  58686. ** unlike that index from its Table then remove the index from
  58687. ** the index hash table and free all memory structures associated
  58688. ** with the index.
  58689. */
  58690. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  58691. Index *pIndex;
  58692. int len;
  58693. Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
  58694. len = sqlite3Strlen(db, zIdxName);
  58695. pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
  58696. if( pIndex ){
  58697. if( pIndex->pTable->pIndex==pIndex ){
  58698. pIndex->pTable->pIndex = pIndex->pNext;
  58699. }else{
  58700. Index *p;
  58701. for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
  58702. if( p && p->pNext==pIndex ){
  58703. p->pNext = pIndex->pNext;
  58704. }
  58705. }
  58706. freeIndex(pIndex);
  58707. }
  58708. db->flags |= SQLITE_InternChanges;
  58709. }
  58710. /*
  58711. ** Erase all schema information from the in-memory hash tables of
  58712. ** a single database. This routine is called to reclaim memory
  58713. ** before the database closes. It is also called during a rollback
  58714. ** if there were schema changes during the transaction or if a
  58715. ** schema-cookie mismatch occurs.
  58716. **
  58717. ** If iDb==0 then reset the internal schema tables for all database
  58718. ** files. If iDb>=1 then reset the internal schema for only the
  58719. ** single file indicated.
  58720. */
  58721. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
  58722. int i, j;
  58723. assert( iDb>=0 && iDb<db->nDb );
  58724. if( iDb==0 ){
  58725. sqlite3BtreeEnterAll(db);
  58726. }
  58727. for(i=iDb; i<db->nDb; i++){
  58728. Db *pDb = &db->aDb[i];
  58729. if( pDb->pSchema ){
  58730. assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
  58731. sqlite3SchemaFree(pDb->pSchema);
  58732. }
  58733. if( iDb>0 ) return;
  58734. }
  58735. assert( iDb==0 );
  58736. db->flags &= ~SQLITE_InternChanges;
  58737. sqlite3BtreeLeaveAll(db);
  58738. /* If one or more of the auxiliary database files has been closed,
  58739. ** then remove them from the auxiliary database list. We take the
  58740. ** opportunity to do this here since we have just deleted all of the
  58741. ** schema hash tables and therefore do not have to make any changes
  58742. ** to any of those tables.
  58743. */
  58744. for(i=0; i<db->nDb; i++){
  58745. struct Db *pDb = &db->aDb[i];
  58746. if( pDb->pBt==0 ){
  58747. if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
  58748. pDb->pAux = 0;
  58749. }
  58750. }
  58751. for(i=j=2; i<db->nDb; i++){
  58752. struct Db *pDb = &db->aDb[i];
  58753. if( pDb->pBt==0 ){
  58754. sqlite3DbFree(db, pDb->zName);
  58755. pDb->zName = 0;
  58756. continue;
  58757. }
  58758. if( j<i ){
  58759. db->aDb[j] = db->aDb[i];
  58760. }
  58761. j++;
  58762. }
  58763. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  58764. db->nDb = j;
  58765. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  58766. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  58767. sqlite3DbFree(db, db->aDb);
  58768. db->aDb = db->aDbStatic;
  58769. }
  58770. }
  58771. /*
  58772. ** This routine is called when a commit occurs.
  58773. */
  58774. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  58775. db->flags &= ~SQLITE_InternChanges;
  58776. }
  58777. /*
  58778. ** Clear the column names from a table or view.
  58779. */
  58780. static void sqliteResetColumnNames(Table *pTable){
  58781. int i;
  58782. Column *pCol;
  58783. sqlite3 *db = pTable->dbMem;
  58784. assert( pTable!=0 );
  58785. if( (pCol = pTable->aCol)!=0 ){
  58786. for(i=0; i<pTable->nCol; i++, pCol++){
  58787. sqlite3DbFree(db, pCol->zName);
  58788. sqlite3ExprDelete(db, pCol->pDflt);
  58789. sqlite3DbFree(db, pCol->zType);
  58790. sqlite3DbFree(db, pCol->zColl);
  58791. }
  58792. sqlite3DbFree(db, pTable->aCol);
  58793. }
  58794. pTable->aCol = 0;
  58795. pTable->nCol = 0;
  58796. }
  58797. /*
  58798. ** Remove the memory data structures associated with the given
  58799. ** Table. No changes are made to disk by this routine.
  58800. **
  58801. ** This routine just deletes the data structure. It does not unlink
  58802. ** the table data structure from the hash table. Nor does it remove
  58803. ** foreign keys from the sqlite.aFKey hash table. But it does destroy
  58804. ** memory structures of the indices and foreign keys associated with
  58805. ** the table.
  58806. */
  58807. SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
  58808. Index *pIndex, *pNext;
  58809. FKey *pFKey, *pNextFKey;
  58810. sqlite3 *db;
  58811. if( pTable==0 ) return;
  58812. db = pTable->dbMem;
  58813. /* Do not delete the table until the reference count reaches zero. */
  58814. pTable->nRef--;
  58815. if( pTable->nRef>0 ){
  58816. return;
  58817. }
  58818. assert( pTable->nRef==0 );
  58819. /* Delete all indices associated with this table
  58820. */
  58821. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  58822. pNext = pIndex->pNext;
  58823. assert( pIndex->pSchema==pTable->pSchema );
  58824. sqlite3DeleteIndex(pIndex);
  58825. }
  58826. #ifndef SQLITE_OMIT_FOREIGN_KEY
  58827. /* Delete all foreign keys associated with this table. The keys
  58828. ** should have already been unlinked from the pSchema->aFKey hash table
  58829. */
  58830. for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
  58831. pNextFKey = pFKey->pNextFrom;
  58832. assert( sqlite3HashFind(&pTable->pSchema->aFKey,
  58833. pFKey->zTo, sqlite3Strlen30(pFKey->zTo)+1)!=pFKey );
  58834. sqlite3DbFree(db, pFKey);
  58835. }
  58836. #endif
  58837. /* Delete the Table structure itself.
  58838. */
  58839. sqliteResetColumnNames(pTable);
  58840. sqlite3DbFree(db, pTable->zName);
  58841. sqlite3DbFree(db, pTable->zColAff);
  58842. sqlite3SelectDelete(db, pTable->pSelect);
  58843. #ifndef SQLITE_OMIT_CHECK
  58844. sqlite3ExprDelete(db, pTable->pCheck);
  58845. #endif
  58846. sqlite3VtabClear(pTable);
  58847. sqlite3DbFree(db, pTable);
  58848. }
  58849. /*
  58850. ** Unlink the given table from the hash tables and the delete the
  58851. ** table structure with all its indices and foreign keys.
  58852. */
  58853. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  58854. Table *p;
  58855. FKey *pF1, *pF2;
  58856. Db *pDb;
  58857. assert( db!=0 );
  58858. assert( iDb>=0 && iDb<db->nDb );
  58859. assert( zTabName && zTabName[0] );
  58860. pDb = &db->aDb[iDb];
  58861. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  58862. sqlite3Strlen30(zTabName)+1,0);
  58863. if( p ){
  58864. #ifndef SQLITE_OMIT_FOREIGN_KEY
  58865. for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
  58866. int nTo = sqlite3Strlen30(pF1->zTo) + 1;
  58867. pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
  58868. if( pF2==pF1 ){
  58869. sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
  58870. }else{
  58871. while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
  58872. if( pF2 ){
  58873. pF2->pNextTo = pF1->pNextTo;
  58874. }
  58875. }
  58876. }
  58877. #endif
  58878. sqlite3DeleteTable(p);
  58879. }
  58880. db->flags |= SQLITE_InternChanges;
  58881. }
  58882. /*
  58883. ** Given a token, return a string that consists of the text of that
  58884. ** token with any quotations removed. Space to hold the returned string
  58885. ** is obtained from sqliteMalloc() and must be freed by the calling
  58886. ** function.
  58887. **
  58888. ** Tokens are often just pointers into the original SQL text and so
  58889. ** are not \000 terminated and are not persistent. The returned string
  58890. ** is \000 terminated and is persistent.
  58891. */
  58892. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  58893. char *zName;
  58894. if( pName ){
  58895. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  58896. sqlite3Dequote(zName);
  58897. }else{
  58898. zName = 0;
  58899. }
  58900. return zName;
  58901. }
  58902. /*
  58903. ** Open the sqlite_master table stored in database number iDb for
  58904. ** writing. The table is opened using cursor 0.
  58905. */
  58906. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  58907. Vdbe *v = sqlite3GetVdbe(p);
  58908. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  58909. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  58910. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  58911. if( p->nTab==0 ){
  58912. p->nTab = 1;
  58913. }
  58914. }
  58915. /*
  58916. ** Parameter zName points to a nul-terminated buffer containing the name
  58917. ** of a database ("main", "temp" or the name of an attached db). This
  58918. ** function returns the index of the named database in db->aDb[], or
  58919. ** -1 if the named db cannot be found.
  58920. */
  58921. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  58922. int i = -1; /* Database number */
  58923. if( zName ){
  58924. Db *pDb;
  58925. int n = sqlite3Strlen30(zName);
  58926. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  58927. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  58928. 0==sqlite3StrICmp(pDb->zName, zName) ){
  58929. break;
  58930. }
  58931. }
  58932. }
  58933. return i;
  58934. }
  58935. /*
  58936. ** The token *pName contains the name of a database (either "main" or
  58937. ** "temp" or the name of an attached db). This routine returns the
  58938. ** index of the named database in db->aDb[], or -1 if the named db
  58939. ** does not exist.
  58940. */
  58941. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  58942. int i; /* Database number */
  58943. char *zName; /* Name we are searching for */
  58944. zName = sqlite3NameFromToken(db, pName);
  58945. i = sqlite3FindDbName(db, zName);
  58946. sqlite3DbFree(db, zName);
  58947. return i;
  58948. }
  58949. /* The table or view or trigger name is passed to this routine via tokens
  58950. ** pName1 and pName2. If the table name was fully qualified, for example:
  58951. **
  58952. ** CREATE TABLE xxx.yyy (...);
  58953. **
  58954. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  58955. ** the table name is not fully qualified, i.e.:
  58956. **
  58957. ** CREATE TABLE yyy(...);
  58958. **
  58959. ** Then pName1 is set to "yyy" and pName2 is "".
  58960. **
  58961. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  58962. ** pName2) that stores the unqualified table name. The index of the
  58963. ** database "xxx" is returned.
  58964. */
  58965. SQLITE_PRIVATE int sqlite3TwoPartName(
  58966. Parse *pParse, /* Parsing and code generating context */
  58967. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  58968. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  58969. Token **pUnqual /* Write the unqualified object name here */
  58970. ){
  58971. int iDb; /* Database holding the object */
  58972. sqlite3 *db = pParse->db;
  58973. if( pName2 && pName2->n>0 ){
  58974. if( db->init.busy ) {
  58975. sqlite3ErrorMsg(pParse, "corrupt database");
  58976. pParse->nErr++;
  58977. return -1;
  58978. }
  58979. *pUnqual = pName2;
  58980. iDb = sqlite3FindDb(db, pName1);
  58981. if( iDb<0 ){
  58982. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  58983. pParse->nErr++;
  58984. return -1;
  58985. }
  58986. }else{
  58987. assert( db->init.iDb==0 || db->init.busy );
  58988. iDb = db->init.iDb;
  58989. *pUnqual = pName1;
  58990. }
  58991. return iDb;
  58992. }
  58993. /*
  58994. ** This routine is used to check if the UTF-8 string zName is a legal
  58995. ** unqualified name for a new schema object (table, index, view or
  58996. ** trigger). All names are legal except those that begin with the string
  58997. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  58998. ** is reserved for internal use.
  58999. */
  59000. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  59001. if( !pParse->db->init.busy && pParse->nested==0
  59002. && (pParse->db->flags & SQLITE_WriteSchema)==0
  59003. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  59004. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  59005. return SQLITE_ERROR;
  59006. }
  59007. return SQLITE_OK;
  59008. }
  59009. /*
  59010. ** Begin constructing a new table representation in memory. This is
  59011. ** the first of several action routines that get called in response
  59012. ** to a CREATE TABLE statement. In particular, this routine is called
  59013. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  59014. ** flag is true if the table should be stored in the auxiliary database
  59015. ** file instead of in the main database file. This is normally the case
  59016. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  59017. ** CREATE and TABLE.
  59018. **
  59019. ** The new table record is initialized and put in pParse->pNewTable.
  59020. ** As more of the CREATE TABLE statement is parsed, additional action
  59021. ** routines will be called to add more information to this record.
  59022. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  59023. ** is called to complete the construction of the new table record.
  59024. */
  59025. SQLITE_PRIVATE void sqlite3StartTable(
  59026. Parse *pParse, /* Parser context */
  59027. Token *pName1, /* First part of the name of the table or view */
  59028. Token *pName2, /* Second part of the name of the table or view */
  59029. int isTemp, /* True if this is a TEMP table */
  59030. int isView, /* True if this is a VIEW */
  59031. int isVirtual, /* True if this is a VIRTUAL table */
  59032. int noErr /* Do nothing if table already exists */
  59033. ){
  59034. Table *pTable;
  59035. char *zName = 0; /* The name of the new table */
  59036. sqlite3 *db = pParse->db;
  59037. Vdbe *v;
  59038. int iDb; /* Database number to create the table in */
  59039. Token *pName; /* Unqualified name of the table to create */
  59040. /* The table or view name to create is passed to this routine via tokens
  59041. ** pName1 and pName2. If the table name was fully qualified, for example:
  59042. **
  59043. ** CREATE TABLE xxx.yyy (...);
  59044. **
  59045. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  59046. ** the table name is not fully qualified, i.e.:
  59047. **
  59048. ** CREATE TABLE yyy(...);
  59049. **
  59050. ** Then pName1 is set to "yyy" and pName2 is "".
  59051. **
  59052. ** The call below sets the pName pointer to point at the token (pName1 or
  59053. ** pName2) that stores the unqualified table name. The variable iDb is
  59054. ** set to the index of the database that the table or view is to be
  59055. ** created in.
  59056. */
  59057. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  59058. if( iDb<0 ) return;
  59059. if( !OMIT_TEMPDB && isTemp && iDb>1 ){
  59060. /* If creating a temp table, the name may not be qualified */
  59061. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  59062. return;
  59063. }
  59064. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  59065. pParse->sNameToken = *pName;
  59066. zName = sqlite3NameFromToken(db, pName);
  59067. if( zName==0 ) return;
  59068. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  59069. goto begin_table_error;
  59070. }
  59071. if( db->init.iDb==1 ) isTemp = 1;
  59072. #ifndef SQLITE_OMIT_AUTHORIZATION
  59073. assert( (isTemp & 1)==isTemp );
  59074. {
  59075. int code;
  59076. char *zDb = db->aDb[iDb].zName;
  59077. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  59078. goto begin_table_error;
  59079. }
  59080. if( isView ){
  59081. if( !OMIT_TEMPDB && isTemp ){
  59082. code = SQLITE_CREATE_TEMP_VIEW;
  59083. }else{
  59084. code = SQLITE_CREATE_VIEW;
  59085. }
  59086. }else{
  59087. if( !OMIT_TEMPDB && isTemp ){
  59088. code = SQLITE_CREATE_TEMP_TABLE;
  59089. }else{
  59090. code = SQLITE_CREATE_TABLE;
  59091. }
  59092. }
  59093. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  59094. goto begin_table_error;
  59095. }
  59096. }
  59097. #endif
  59098. /* Make sure the new table name does not collide with an existing
  59099. ** index or table name in the same database. Issue an error message if
  59100. ** it does. The exception is if the statement being parsed was passed
  59101. ** to an sqlite3_declare_vtab() call. In that case only the column names
  59102. ** and types will be used, so there is no need to test for namespace
  59103. ** collisions.
  59104. */
  59105. if( !IN_DECLARE_VTAB ){
  59106. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  59107. goto begin_table_error;
  59108. }
  59109. pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
  59110. if( pTable ){
  59111. if( !noErr ){
  59112. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  59113. }
  59114. goto begin_table_error;
  59115. }
  59116. if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
  59117. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  59118. goto begin_table_error;
  59119. }
  59120. }
  59121. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  59122. if( pTable==0 ){
  59123. db->mallocFailed = 1;
  59124. pParse->rc = SQLITE_NOMEM;
  59125. pParse->nErr++;
  59126. goto begin_table_error;
  59127. }
  59128. pTable->zName = zName;
  59129. pTable->iPKey = -1;
  59130. pTable->pSchema = db->aDb[iDb].pSchema;
  59131. pTable->nRef = 1;
  59132. pTable->dbMem = db->lookaside.bEnabled ? db : 0;
  59133. if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
  59134. pParse->pNewTable = pTable;
  59135. /* If this is the magic sqlite_sequence table used by autoincrement,
  59136. ** then record a pointer to this table in the main database structure
  59137. ** so that INSERT can find the table easily.
  59138. */
  59139. #ifndef SQLITE_OMIT_AUTOINCREMENT
  59140. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  59141. pTable->pSchema->pSeqTab = pTable;
  59142. }
  59143. #endif
  59144. /* Begin generating the code that will insert the table record into
  59145. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  59146. ** and allocate the record number for the table entry now. Before any
  59147. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  59148. ** indices to be created and the table record must come before the
  59149. ** indices. Hence, the record number for the table must be allocated
  59150. ** now.
  59151. */
  59152. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  59153. int j1;
  59154. int fileFormat;
  59155. int reg1, reg2, reg3;
  59156. sqlite3BeginWriteOperation(pParse, 0, iDb);
  59157. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59158. if( isVirtual ){
  59159. sqlite3VdbeAddOp0(v, OP_VBegin);
  59160. }
  59161. #endif
  59162. /* If the file format and encoding in the database have not been set,
  59163. ** set them now.
  59164. */
  59165. reg1 = pParse->regRowid = ++pParse->nMem;
  59166. reg2 = pParse->regRoot = ++pParse->nMem;
  59167. reg3 = ++pParse->nMem;
  59168. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */
  59169. sqlite3VdbeUsesBtree(v, iDb);
  59170. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  59171. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  59172. 1 : SQLITE_MAX_FILE_FORMAT;
  59173. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  59174. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
  59175. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  59176. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
  59177. sqlite3VdbeJumpHere(v, j1);
  59178. /* This just creates a place-holder record in the sqlite_master table.
  59179. ** The record created does not contain anything yet. It will be replaced
  59180. ** by the real entry in code generated at sqlite3EndTable().
  59181. **
  59182. ** The rowid for the new entry is left in register pParse->regRowid.
  59183. ** The root page number of the new table is left in reg pParse->regRoot.
  59184. ** The rowid and root page number values are needed by the code that
  59185. ** sqlite3EndTable will generate.
  59186. */
  59187. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  59188. if( isView || isVirtual ){
  59189. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  59190. }else
  59191. #endif
  59192. {
  59193. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  59194. }
  59195. sqlite3OpenMasterTable(pParse, iDb);
  59196. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  59197. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  59198. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  59199. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  59200. sqlite3VdbeAddOp0(v, OP_Close);
  59201. }
  59202. /* Normal (non-error) return. */
  59203. return;
  59204. /* If an error occurs, we jump here */
  59205. begin_table_error:
  59206. sqlite3DbFree(db, zName);
  59207. return;
  59208. }
  59209. /*
  59210. ** This macro is used to compare two strings in a case-insensitive manner.
  59211. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  59212. ** produces larger code.
  59213. **
  59214. ** WARNING: This macro is not compatible with the strcmp() family. It
  59215. ** returns true if the two strings are equal, otherwise false.
  59216. */
  59217. #define STRICMP(x, y) (\
  59218. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  59219. sqlite3UpperToLower[*(unsigned char *)(y)] \
  59220. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  59221. /*
  59222. ** Add a new column to the table currently being constructed.
  59223. **
  59224. ** The parser calls this routine once for each column declaration
  59225. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  59226. ** first to get things going. Then this routine is called for each
  59227. ** column.
  59228. */
  59229. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  59230. Table *p;
  59231. int i;
  59232. char *z;
  59233. Column *pCol;
  59234. sqlite3 *db = pParse->db;
  59235. if( (p = pParse->pNewTable)==0 ) return;
  59236. #if SQLITE_MAX_COLUMN
  59237. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  59238. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  59239. return;
  59240. }
  59241. #endif
  59242. z = sqlite3NameFromToken(db, pName);
  59243. if( z==0 ) return;
  59244. for(i=0; i<p->nCol; i++){
  59245. if( STRICMP(z, p->aCol[i].zName) ){
  59246. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  59247. sqlite3DbFree(db, z);
  59248. return;
  59249. }
  59250. }
  59251. if( (p->nCol & 0x7)==0 ){
  59252. Column *aNew;
  59253. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  59254. if( aNew==0 ){
  59255. sqlite3DbFree(db, z);
  59256. return;
  59257. }
  59258. p->aCol = aNew;
  59259. }
  59260. pCol = &p->aCol[p->nCol];
  59261. memset(pCol, 0, sizeof(p->aCol[0]));
  59262. pCol->zName = z;
  59263. /* If there is no type specified, columns have the default affinity
  59264. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  59265. ** be called next to set pCol->affinity correctly.
  59266. */
  59267. pCol->affinity = SQLITE_AFF_NONE;
  59268. p->nCol++;
  59269. }
  59270. /*
  59271. ** This routine is called by the parser while in the middle of
  59272. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  59273. ** been seen on a column. This routine sets the notNull flag on
  59274. ** the column currently under construction.
  59275. */
  59276. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  59277. Table *p;
  59278. int i;
  59279. if( (p = pParse->pNewTable)==0 ) return;
  59280. i = p->nCol-1;
  59281. if( i>=0 ) p->aCol[i].notNull = (u8)onError;
  59282. }
  59283. /*
  59284. ** Scan the column type name zType (length nType) and return the
  59285. ** associated affinity type.
  59286. **
  59287. ** This routine does a case-independent search of zType for the
  59288. ** substrings in the following table. If one of the substrings is
  59289. ** found, the corresponding affinity is returned. If zType contains
  59290. ** more than one of the substrings, entries toward the top of
  59291. ** the table take priority. For example, if zType is 'BLOBINT',
  59292. ** SQLITE_AFF_INTEGER is returned.
  59293. **
  59294. ** Substring | Affinity
  59295. ** --------------------------------
  59296. ** 'INT' | SQLITE_AFF_INTEGER
  59297. ** 'CHAR' | SQLITE_AFF_TEXT
  59298. ** 'CLOB' | SQLITE_AFF_TEXT
  59299. ** 'TEXT' | SQLITE_AFF_TEXT
  59300. ** 'BLOB' | SQLITE_AFF_NONE
  59301. ** 'REAL' | SQLITE_AFF_REAL
  59302. ** 'FLOA' | SQLITE_AFF_REAL
  59303. ** 'DOUB' | SQLITE_AFF_REAL
  59304. **
  59305. ** If none of the substrings in the above table are found,
  59306. ** SQLITE_AFF_NUMERIC is returned.
  59307. */
  59308. SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
  59309. u32 h = 0;
  59310. char aff = SQLITE_AFF_NUMERIC;
  59311. const unsigned char *zIn = pType->z;
  59312. const unsigned char *zEnd = &pType->z[pType->n];
  59313. while( zIn!=zEnd ){
  59314. h = (h<<8) + sqlite3UpperToLower[*zIn];
  59315. zIn++;
  59316. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  59317. aff = SQLITE_AFF_TEXT;
  59318. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  59319. aff = SQLITE_AFF_TEXT;
  59320. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  59321. aff = SQLITE_AFF_TEXT;
  59322. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  59323. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  59324. aff = SQLITE_AFF_NONE;
  59325. #ifndef SQLITE_OMIT_FLOATING_POINT
  59326. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  59327. && aff==SQLITE_AFF_NUMERIC ){
  59328. aff = SQLITE_AFF_REAL;
  59329. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  59330. && aff==SQLITE_AFF_NUMERIC ){
  59331. aff = SQLITE_AFF_REAL;
  59332. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  59333. && aff==SQLITE_AFF_NUMERIC ){
  59334. aff = SQLITE_AFF_REAL;
  59335. #endif
  59336. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  59337. aff = SQLITE_AFF_INTEGER;
  59338. break;
  59339. }
  59340. }
  59341. return aff;
  59342. }
  59343. /*
  59344. ** This routine is called by the parser while in the middle of
  59345. ** parsing a CREATE TABLE statement. The pFirst token is the first
  59346. ** token in the sequence of tokens that describe the type of the
  59347. ** column currently under construction. pLast is the last token
  59348. ** in the sequence. Use this information to construct a string
  59349. ** that contains the typename of the column and store that string
  59350. ** in zType.
  59351. */
  59352. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  59353. Table *p;
  59354. int i;
  59355. Column *pCol;
  59356. sqlite3 *db;
  59357. if( (p = pParse->pNewTable)==0 ) return;
  59358. i = p->nCol-1;
  59359. if( i<0 ) return;
  59360. pCol = &p->aCol[i];
  59361. db = pParse->db;
  59362. sqlite3DbFree(db, pCol->zType);
  59363. pCol->zType = sqlite3NameFromToken(db, pType);
  59364. pCol->affinity = sqlite3AffinityType(pType);
  59365. }
  59366. /*
  59367. ** The expression is the default value for the most recently added column
  59368. ** of the table currently under construction.
  59369. **
  59370. ** Default value expressions must be constant. Raise an exception if this
  59371. ** is not the case.
  59372. **
  59373. ** This routine is called by the parser while in the middle of
  59374. ** parsing a CREATE TABLE statement.
  59375. */
  59376. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
  59377. Table *p;
  59378. Column *pCol;
  59379. sqlite3 *db = pParse->db;
  59380. if( (p = pParse->pNewTable)!=0 ){
  59381. pCol = &(p->aCol[p->nCol-1]);
  59382. if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
  59383. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  59384. pCol->zName);
  59385. }else{
  59386. /* A copy of pExpr is used instead of the original, as pExpr contains
  59387. ** tokens that point to volatile memory. The 'span' of the expression
  59388. ** is required by pragma table_info.
  59389. */
  59390. sqlite3ExprDelete(db, pCol->pDflt);
  59391. pCol->pDflt = sqlite3ExprDup(db, pExpr, EXPRDUP_REDUCE|EXPRDUP_SPAN);
  59392. }
  59393. }
  59394. sqlite3ExprDelete(db, pExpr);
  59395. }
  59396. /*
  59397. ** Designate the PRIMARY KEY for the table. pList is a list of names
  59398. ** of columns that form the primary key. If pList is NULL, then the
  59399. ** most recently added column of the table is the primary key.
  59400. **
  59401. ** A table can have at most one primary key. If the table already has
  59402. ** a primary key (and this is the second primary key) then create an
  59403. ** error.
  59404. **
  59405. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  59406. ** then we will try to use that column as the rowid. Set the Table.iPKey
  59407. ** field of the table under construction to be the index of the
  59408. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  59409. ** no INTEGER PRIMARY KEY.
  59410. **
  59411. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  59412. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  59413. */
  59414. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  59415. Parse *pParse, /* Parsing context */
  59416. ExprList *pList, /* List of field names to be indexed */
  59417. int onError, /* What to do with a uniqueness conflict */
  59418. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  59419. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  59420. ){
  59421. Table *pTab = pParse->pNewTable;
  59422. char *zType = 0;
  59423. int iCol = -1, i;
  59424. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  59425. if( pTab->tabFlags & TF_HasPrimaryKey ){
  59426. sqlite3ErrorMsg(pParse,
  59427. "table \"%s\" has more than one primary key", pTab->zName);
  59428. goto primary_key_exit;
  59429. }
  59430. pTab->tabFlags |= TF_HasPrimaryKey;
  59431. if( pList==0 ){
  59432. iCol = pTab->nCol - 1;
  59433. pTab->aCol[iCol].isPrimKey = 1;
  59434. }else{
  59435. for(i=0; i<pList->nExpr; i++){
  59436. for(iCol=0; iCol<pTab->nCol; iCol++){
  59437. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  59438. break;
  59439. }
  59440. }
  59441. if( iCol<pTab->nCol ){
  59442. pTab->aCol[iCol].isPrimKey = 1;
  59443. }
  59444. }
  59445. if( pList->nExpr>1 ) iCol = -1;
  59446. }
  59447. if( iCol>=0 && iCol<pTab->nCol ){
  59448. zType = pTab->aCol[iCol].zType;
  59449. }
  59450. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  59451. && sortOrder==SQLITE_SO_ASC ){
  59452. pTab->iPKey = iCol;
  59453. pTab->keyConf = (u8)onError;
  59454. assert( autoInc==0 || autoInc==1 );
  59455. pTab->tabFlags |= autoInc*TF_Autoincrement;
  59456. }else if( autoInc ){
  59457. #ifndef SQLITE_OMIT_AUTOINCREMENT
  59458. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  59459. "INTEGER PRIMARY KEY");
  59460. #endif
  59461. }else{
  59462. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  59463. pList = 0;
  59464. }
  59465. primary_key_exit:
  59466. sqlite3ExprListDelete(pParse->db, pList);
  59467. return;
  59468. }
  59469. /*
  59470. ** Add a new CHECK constraint to the table currently under construction.
  59471. */
  59472. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  59473. Parse *pParse, /* Parsing context */
  59474. Expr *pCheckExpr /* The check expression */
  59475. ){
  59476. sqlite3 *db = pParse->db;
  59477. #ifndef SQLITE_OMIT_CHECK
  59478. Table *pTab = pParse->pNewTable;
  59479. if( pTab && !IN_DECLARE_VTAB ){
  59480. /* The CHECK expression must be duplicated so that tokens refer
  59481. ** to malloced space and not the (ephemeral) text of the CREATE TABLE
  59482. ** statement */
  59483. pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
  59484. sqlite3ExprDup(db, pCheckExpr, 0));
  59485. }
  59486. #endif
  59487. sqlite3ExprDelete(db, pCheckExpr);
  59488. }
  59489. /*
  59490. ** Set the collation function of the most recently parsed table column
  59491. ** to the CollSeq given.
  59492. */
  59493. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  59494. Table *p;
  59495. int i;
  59496. char *zColl; /* Dequoted name of collation sequence */
  59497. sqlite3 *db;
  59498. if( (p = pParse->pNewTable)==0 ) return;
  59499. i = p->nCol-1;
  59500. db = pParse->db;
  59501. zColl = sqlite3NameFromToken(db, pToken);
  59502. if( !zColl ) return;
  59503. if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
  59504. Index *pIdx;
  59505. p->aCol[i].zColl = zColl;
  59506. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  59507. ** then an index may have been created on this column before the
  59508. ** collation type was added. Correct this if it is the case.
  59509. */
  59510. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  59511. assert( pIdx->nColumn==1 );
  59512. if( pIdx->aiColumn[0]==i ){
  59513. pIdx->azColl[0] = p->aCol[i].zColl;
  59514. }
  59515. }
  59516. }else{
  59517. sqlite3DbFree(db, zColl);
  59518. }
  59519. }
  59520. /*
  59521. ** This function returns the collation sequence for database native text
  59522. ** encoding identified by the string zName, length nName.
  59523. **
  59524. ** If the requested collation sequence is not available, or not available
  59525. ** in the database native encoding, the collation factory is invoked to
  59526. ** request it. If the collation factory does not supply such a sequence,
  59527. ** and the sequence is available in another text encoding, then that is
  59528. ** returned instead.
  59529. **
  59530. ** If no versions of the requested collations sequence are available, or
  59531. ** another error occurs, NULL is returned and an error message written into
  59532. ** pParse.
  59533. **
  59534. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  59535. ** invokes the collation factory if the named collation cannot be found
  59536. ** and generates an error message.
  59537. */
  59538. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
  59539. sqlite3 *db = pParse->db;
  59540. u8 enc = ENC(db);
  59541. u8 initbusy = db->init.busy;
  59542. CollSeq *pColl;
  59543. pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
  59544. if( !initbusy && (!pColl || !pColl->xCmp) ){
  59545. pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
  59546. if( !pColl ){
  59547. if( nName<0 ){
  59548. nName = sqlite3Strlen(db, zName);
  59549. }
  59550. sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
  59551. pColl = 0;
  59552. }
  59553. }
  59554. return pColl;
  59555. }
  59556. /*
  59557. ** Generate code that will increment the schema cookie.
  59558. **
  59559. ** The schema cookie is used to determine when the schema for the
  59560. ** database changes. After each schema change, the cookie value
  59561. ** changes. When a process first reads the schema it records the
  59562. ** cookie. Thereafter, whenever it goes to access the database,
  59563. ** it checks the cookie to make sure the schema has not changed
  59564. ** since it was last read.
  59565. **
  59566. ** This plan is not completely bullet-proof. It is possible for
  59567. ** the schema to change multiple times and for the cookie to be
  59568. ** set back to prior value. But schema changes are infrequent
  59569. ** and the probability of hitting the same cookie value is only
  59570. ** 1 chance in 2^32. So we're safe enough.
  59571. */
  59572. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  59573. int r1 = sqlite3GetTempReg(pParse);
  59574. sqlite3 *db = pParse->db;
  59575. Vdbe *v = pParse->pVdbe;
  59576. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  59577. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
  59578. sqlite3ReleaseTempReg(pParse, r1);
  59579. }
  59580. /*
  59581. ** Measure the number of characters needed to output the given
  59582. ** identifier. The number returned includes any quotes used
  59583. ** but does not include the null terminator.
  59584. **
  59585. ** The estimate is conservative. It might be larger that what is
  59586. ** really needed.
  59587. */
  59588. static int identLength(const char *z){
  59589. int n;
  59590. for(n=0; *z; n++, z++){
  59591. if( *z=='"' ){ n++; }
  59592. }
  59593. return n + 2;
  59594. }
  59595. /*
  59596. ** This function is a wrapper around sqlite3GetToken() used by
  59597. ** isValidDimension(). This function differs from sqlite3GetToken() in
  59598. ** that:
  59599. **
  59600. ** * Whitespace is ignored, and
  59601. ** * The output variable *peToken is set to 0 if the end of the
  59602. ** nul-terminated input string is reached.
  59603. */
  59604. static int getTokenNoSpace(unsigned char *z, int *peToken){
  59605. int n = 0;
  59606. while( sqlite3Isspace(z[n]) ) n++;
  59607. if( !z[n] ){
  59608. *peToken = 0;
  59609. return 0;
  59610. }
  59611. return n + sqlite3GetToken(&z[n], peToken);
  59612. }
  59613. /*
  59614. ** Parameter z points to a nul-terminated string. Return true if, when
  59615. ** whitespace is ignored, the contents of this string matches one of
  59616. ** the following patterns:
  59617. **
  59618. ** ""
  59619. ** "(number)"
  59620. ** "(number,number)"
  59621. */
  59622. static int isValidDimension(unsigned char *z){
  59623. int eToken;
  59624. int n = 0;
  59625. n += getTokenNoSpace(&z[n], &eToken);
  59626. if( eToken ){
  59627. if( eToken!=TK_LP ) return 0;
  59628. n += getTokenNoSpace(&z[n], &eToken);
  59629. if( eToken==TK_PLUS || eToken==TK_MINUS ){
  59630. n += getTokenNoSpace(&z[n], &eToken);
  59631. }
  59632. if( eToken!=TK_INTEGER && eToken!=TK_FLOAT ) return 0;
  59633. n += getTokenNoSpace(&z[n], &eToken);
  59634. if( eToken==TK_COMMA ){
  59635. n += getTokenNoSpace(&z[n], &eToken);
  59636. if( eToken==TK_PLUS || eToken==TK_MINUS ){
  59637. n += getTokenNoSpace(&z[n], &eToken);
  59638. }
  59639. if( eToken!=TK_INTEGER && eToken!=TK_FLOAT ) return 0;
  59640. n += getTokenNoSpace(&z[n], &eToken);
  59641. }
  59642. if( eToken!=TK_RP ) return 0;
  59643. getTokenNoSpace(&z[n], &eToken);
  59644. }
  59645. if( eToken ) return 0;
  59646. return 1;
  59647. }
  59648. /*
  59649. ** The first parameter is a pointer to an output buffer. The second
  59650. ** parameter is a pointer to an integer that contains the offset at
  59651. ** which to write into the output buffer. This function copies the
  59652. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  59653. ** to the specified offset in the buffer and updates *pIdx to refer
  59654. ** to the first byte after the last byte written before returning.
  59655. **
  59656. ** If the string zSignedIdent consists entirely of alpha-numeric
  59657. ** characters, does not begin with a digit and is not an SQL keyword,
  59658. ** then it is copied to the output buffer exactly as it is. Otherwise,
  59659. ** it is quoted using double-quotes.
  59660. */
  59661. static void identPut(char *z, int *pIdx, char *zSignedIdent, int isTypename){
  59662. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  59663. int i, j, needQuote;
  59664. i = *pIdx;
  59665. for(j=0; zIdent[j]; j++){
  59666. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  59667. }
  59668. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  59669. if( !needQuote ){
  59670. if( isTypename ){
  59671. /* If this is a type-name, allow a little more flexibility. In SQLite,
  59672. ** a type-name is specified as:
  59673. **
  59674. ** ids [ids] [(number [, number])]
  59675. **
  59676. ** where "ids" is either a quoted string or a simple identifier (in the
  59677. ** above notation, [] means optional). It is a bit tricky to check
  59678. ** for all cases, but it is good to avoid unnecessarily quoting common
  59679. ** typenames like VARCHAR(10).
  59680. */
  59681. needQuote = !isValidDimension(&zIdent[j]);
  59682. }else{
  59683. needQuote = zIdent[j];
  59684. }
  59685. }
  59686. if( needQuote ) z[i++] = '"';
  59687. for(j=0; zIdent[j]; j++){
  59688. z[i++] = zIdent[j];
  59689. if( zIdent[j]=='"' ) z[i++] = '"';
  59690. }
  59691. if( needQuote ) z[i++] = '"';
  59692. z[i] = 0;
  59693. *pIdx = i;
  59694. }
  59695. /*
  59696. ** Generate a CREATE TABLE statement appropriate for the given
  59697. ** table. Memory to hold the text of the statement is obtained
  59698. ** from sqliteMalloc() and must be freed by the calling function.
  59699. */
  59700. static char *createTableStmt(sqlite3 *db, Table *p){
  59701. int i, k, n;
  59702. char *zStmt;
  59703. char *zSep, *zSep2, *zEnd, *z;
  59704. Column *pCol;
  59705. n = 0;
  59706. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  59707. n += identLength(pCol->zName);
  59708. z = pCol->zType;
  59709. if( z ){
  59710. n += identLength(z);
  59711. }
  59712. }
  59713. n += identLength(p->zName);
  59714. if( n<50 ){
  59715. zSep = "";
  59716. zSep2 = ",";
  59717. zEnd = ")";
  59718. }else{
  59719. zSep = "\n ";
  59720. zSep2 = ",\n ";
  59721. zEnd = "\n)";
  59722. }
  59723. n += 35 + 6*p->nCol;
  59724. zStmt = sqlite3Malloc( n );
  59725. if( zStmt==0 ){
  59726. db->mallocFailed = 1;
  59727. return 0;
  59728. }
  59729. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  59730. k = sqlite3Strlen30(zStmt);
  59731. identPut(zStmt, &k, p->zName, 0);
  59732. zStmt[k++] = '(';
  59733. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  59734. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  59735. k += sqlite3Strlen30(&zStmt[k]);
  59736. zSep = zSep2;
  59737. identPut(zStmt, &k, pCol->zName, 0);
  59738. if( (z = pCol->zType)!=0 ){
  59739. zStmt[k++] = ' ';
  59740. assert( (int)(sqlite3Strlen30(z)+k+1)<=n );
  59741. identPut(zStmt, &k, z, 1);
  59742. }
  59743. }
  59744. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  59745. return zStmt;
  59746. }
  59747. /*
  59748. ** This routine is called to report the final ")" that terminates
  59749. ** a CREATE TABLE statement.
  59750. **
  59751. ** The table structure that other action routines have been building
  59752. ** is added to the internal hash tables, assuming no errors have
  59753. ** occurred.
  59754. **
  59755. ** An entry for the table is made in the master table on disk, unless
  59756. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  59757. ** it means we are reading the sqlite_master table because we just
  59758. ** connected to the database or because the sqlite_master table has
  59759. ** recently changed, so the entry for this table already exists in
  59760. ** the sqlite_master table. We do not want to create it again.
  59761. **
  59762. ** If the pSelect argument is not NULL, it means that this routine
  59763. ** was called to create a table generated from a
  59764. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  59765. ** the new table will match the result set of the SELECT.
  59766. */
  59767. SQLITE_PRIVATE void sqlite3EndTable(
  59768. Parse *pParse, /* Parse context */
  59769. Token *pCons, /* The ',' token after the last column defn. */
  59770. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  59771. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  59772. ){
  59773. Table *p;
  59774. sqlite3 *db = pParse->db;
  59775. int iDb;
  59776. if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
  59777. return;
  59778. }
  59779. p = pParse->pNewTable;
  59780. if( p==0 ) return;
  59781. assert( !db->init.busy || !pSelect );
  59782. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  59783. #ifndef SQLITE_OMIT_CHECK
  59784. /* Resolve names in all CHECK constraint expressions.
  59785. */
  59786. if( p->pCheck ){
  59787. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  59788. NameContext sNC; /* Name context for pParse->pNewTable */
  59789. memset(&sNC, 0, sizeof(sNC));
  59790. memset(&sSrc, 0, sizeof(sSrc));
  59791. sSrc.nSrc = 1;
  59792. sSrc.a[0].zName = p->zName;
  59793. sSrc.a[0].pTab = p;
  59794. sSrc.a[0].iCursor = -1;
  59795. sNC.pParse = pParse;
  59796. sNC.pSrcList = &sSrc;
  59797. sNC.isCheck = 1;
  59798. if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
  59799. return;
  59800. }
  59801. }
  59802. #endif /* !defined(SQLITE_OMIT_CHECK) */
  59803. /* If the db->init.busy is 1 it means we are reading the SQL off the
  59804. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  59805. ** So do not write to the disk again. Extract the root page number
  59806. ** for the table from the db->init.newTnum field. (The page number
  59807. ** should have been put there by the sqliteOpenCb routine.)
  59808. */
  59809. if( db->init.busy ){
  59810. p->tnum = db->init.newTnum;
  59811. }
  59812. /* If not initializing, then create a record for the new table
  59813. ** in the SQLITE_MASTER table of the database.
  59814. **
  59815. ** If this is a TEMPORARY table, write the entry into the auxiliary
  59816. ** file instead of into the main database file.
  59817. */
  59818. if( !db->init.busy ){
  59819. int n;
  59820. Vdbe *v;
  59821. char *zType; /* "view" or "table" */
  59822. char *zType2; /* "VIEW" or "TABLE" */
  59823. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  59824. v = sqlite3GetVdbe(pParse);
  59825. if( v==0 ) return;
  59826. sqlite3VdbeAddOp1(v, OP_Close, 0);
  59827. /*
  59828. ** Initialize zType for the new view or table.
  59829. */
  59830. if( p->pSelect==0 ){
  59831. /* A regular table */
  59832. zType = "table";
  59833. zType2 = "TABLE";
  59834. #ifndef SQLITE_OMIT_VIEW
  59835. }else{
  59836. /* A view */
  59837. zType = "view";
  59838. zType2 = "VIEW";
  59839. #endif
  59840. }
  59841. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  59842. ** statement to populate the new table. The root-page number for the
  59843. ** new table is in register pParse->regRoot.
  59844. **
  59845. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  59846. ** suitable state to query for the column names and types to be used
  59847. ** by the new table.
  59848. **
  59849. ** A shared-cache write-lock is not required to write to the new table,
  59850. ** as a schema-lock must have already been obtained to create it. Since
  59851. ** a schema-lock excludes all other database users, the write-lock would
  59852. ** be redundant.
  59853. */
  59854. if( pSelect ){
  59855. SelectDest dest;
  59856. Table *pSelTab;
  59857. assert(pParse->nTab==1);
  59858. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  59859. sqlite3VdbeChangeP5(v, 1);
  59860. pParse->nTab = 2;
  59861. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  59862. sqlite3Select(pParse, pSelect, &dest);
  59863. sqlite3VdbeAddOp1(v, OP_Close, 1);
  59864. if( pParse->nErr==0 ){
  59865. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  59866. if( pSelTab==0 ) return;
  59867. assert( p->aCol==0 );
  59868. p->nCol = pSelTab->nCol;
  59869. p->aCol = pSelTab->aCol;
  59870. pSelTab->nCol = 0;
  59871. pSelTab->aCol = 0;
  59872. sqlite3DeleteTable(pSelTab);
  59873. }
  59874. }
  59875. /* Compute the complete text of the CREATE statement */
  59876. if( pSelect ){
  59877. zStmt = createTableStmt(db, p);
  59878. }else{
  59879. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  59880. zStmt = sqlite3MPrintf(db,
  59881. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  59882. );
  59883. }
  59884. /* A slot for the record has already been allocated in the
  59885. ** SQLITE_MASTER table. We just need to update that slot with all
  59886. ** the information we've collected.
  59887. */
  59888. sqlite3NestedParse(pParse,
  59889. "UPDATE %Q.%s "
  59890. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  59891. "WHERE rowid=#%d",
  59892. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  59893. zType,
  59894. p->zName,
  59895. p->zName,
  59896. pParse->regRoot,
  59897. zStmt,
  59898. pParse->regRowid
  59899. );
  59900. sqlite3DbFree(db, zStmt);
  59901. sqlite3ChangeCookie(pParse, iDb);
  59902. #ifndef SQLITE_OMIT_AUTOINCREMENT
  59903. /* Check to see if we need to create an sqlite_sequence table for
  59904. ** keeping track of autoincrement keys.
  59905. */
  59906. if( p->tabFlags & TF_Autoincrement ){
  59907. Db *pDb = &db->aDb[iDb];
  59908. if( pDb->pSchema->pSeqTab==0 ){
  59909. sqlite3NestedParse(pParse,
  59910. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  59911. pDb->zName
  59912. );
  59913. }
  59914. }
  59915. #endif
  59916. /* Reparse everything to update our internal data structures */
  59917. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  59918. sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
  59919. }
  59920. /* Add the table to the in-memory representation of the database.
  59921. */
  59922. if( db->init.busy && pParse->nErr==0 ){
  59923. Table *pOld;
  59924. FKey *pFKey;
  59925. Schema *pSchema = p->pSchema;
  59926. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  59927. sqlite3Strlen30(p->zName)+1,p);
  59928. if( pOld ){
  59929. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  59930. db->mallocFailed = 1;
  59931. return;
  59932. }
  59933. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59934. for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  59935. void *data;
  59936. int nTo = sqlite3Strlen30(pFKey->zTo) + 1;
  59937. pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
  59938. data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
  59939. if( data==(void *)pFKey ){
  59940. db->mallocFailed = 1;
  59941. }
  59942. }
  59943. #endif
  59944. pParse->pNewTable = 0;
  59945. db->nTable++;
  59946. db->flags |= SQLITE_InternChanges;
  59947. #ifndef SQLITE_OMIT_ALTERTABLE
  59948. if( !p->pSelect ){
  59949. const char *zName = (const char *)pParse->sNameToken.z;
  59950. int nName;
  59951. assert( !pSelect && pCons && pEnd );
  59952. if( pCons->z==0 ){
  59953. pCons = pEnd;
  59954. }
  59955. nName = (int)((const char *)pCons->z - zName);
  59956. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  59957. }
  59958. #endif
  59959. }
  59960. }
  59961. #ifndef SQLITE_OMIT_VIEW
  59962. /*
  59963. ** The parser calls this routine in order to create a new VIEW
  59964. */
  59965. SQLITE_PRIVATE void sqlite3CreateView(
  59966. Parse *pParse, /* The parsing context */
  59967. Token *pBegin, /* The CREATE token that begins the statement */
  59968. Token *pName1, /* The token that holds the name of the view */
  59969. Token *pName2, /* The token that holds the name of the view */
  59970. Select *pSelect, /* A SELECT statement that will become the new view */
  59971. int isTemp, /* TRUE for a TEMPORARY view */
  59972. int noErr /* Suppress error messages if VIEW already exists */
  59973. ){
  59974. Table *p;
  59975. int n;
  59976. const unsigned char *z;
  59977. Token sEnd;
  59978. DbFixer sFix;
  59979. Token *pName;
  59980. int iDb;
  59981. sqlite3 *db = pParse->db;
  59982. if( pParse->nVar>0 ){
  59983. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  59984. sqlite3SelectDelete(db, pSelect);
  59985. return;
  59986. }
  59987. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  59988. p = pParse->pNewTable;
  59989. if( p==0 || pParse->nErr ){
  59990. sqlite3SelectDelete(db, pSelect);
  59991. return;
  59992. }
  59993. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  59994. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  59995. if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  59996. && sqlite3FixSelect(&sFix, pSelect)
  59997. ){
  59998. sqlite3SelectDelete(db, pSelect);
  59999. return;
  60000. }
  60001. /* Make a copy of the entire SELECT statement that defines the view.
  60002. ** This will force all the Expr.token.z values to be dynamically
  60003. ** allocated rather than point to the input string - which means that
  60004. ** they will persist after the current sqlite3_exec() call returns.
  60005. */
  60006. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  60007. sqlite3SelectDelete(db, pSelect);
  60008. if( db->mallocFailed ){
  60009. return;
  60010. }
  60011. if( !db->init.busy ){
  60012. sqlite3ViewGetColumnNames(pParse, p);
  60013. }
  60014. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  60015. ** the end.
  60016. */
  60017. sEnd = pParse->sLastToken;
  60018. if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
  60019. sEnd.z += sEnd.n;
  60020. }
  60021. sEnd.n = 0;
  60022. n = (int)(sEnd.z - pBegin->z);
  60023. z = (const unsigned char*)pBegin->z;
  60024. while( n>0 && (z[n-1]==';' || sqlite3Isspace(z[n-1])) ){ n--; }
  60025. sEnd.z = &z[n-1];
  60026. sEnd.n = 1;
  60027. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  60028. sqlite3EndTable(pParse, 0, &sEnd, 0);
  60029. return;
  60030. }
  60031. #endif /* SQLITE_OMIT_VIEW */
  60032. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  60033. /*
  60034. ** The Table structure pTable is really a VIEW. Fill in the names of
  60035. ** the columns of the view in the pTable structure. Return the number
  60036. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  60037. */
  60038. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  60039. Table *pSelTab; /* A fake table from which we get the result set */
  60040. Select *pSel; /* Copy of the SELECT that implements the view */
  60041. int nErr = 0; /* Number of errors encountered */
  60042. int n; /* Temporarily holds the number of cursors assigned */
  60043. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  60044. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  60045. assert( pTable );
  60046. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60047. if( sqlite3VtabCallConnect(pParse, pTable) ){
  60048. return SQLITE_ERROR;
  60049. }
  60050. if( IsVirtual(pTable) ) return 0;
  60051. #endif
  60052. #ifndef SQLITE_OMIT_VIEW
  60053. /* A positive nCol means the columns names for this view are
  60054. ** already known.
  60055. */
  60056. if( pTable->nCol>0 ) return 0;
  60057. /* A negative nCol is a special marker meaning that we are currently
  60058. ** trying to compute the column names. If we enter this routine with
  60059. ** a negative nCol, it means two or more views form a loop, like this:
  60060. **
  60061. ** CREATE VIEW one AS SELECT * FROM two;
  60062. ** CREATE VIEW two AS SELECT * FROM one;
  60063. **
  60064. ** Actually, this error is caught previously and so the following test
  60065. ** should always fail. But we will leave it in place just to be safe.
  60066. */
  60067. if( pTable->nCol<0 ){
  60068. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  60069. return 1;
  60070. }
  60071. assert( pTable->nCol>=0 );
  60072. /* If we get this far, it means we need to compute the table names.
  60073. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  60074. ** "*" elements in the results set of the view and will assign cursors
  60075. ** to the elements of the FROM clause. But we do not want these changes
  60076. ** to be permanent. So the computation is done on a copy of the SELECT
  60077. ** statement that defines the view.
  60078. */
  60079. assert( pTable->pSelect );
  60080. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  60081. if( pSel ){
  60082. u8 enableLookaside = db->lookaside.bEnabled;
  60083. n = pParse->nTab;
  60084. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  60085. pTable->nCol = -1;
  60086. db->lookaside.bEnabled = 0;
  60087. #ifndef SQLITE_OMIT_AUTHORIZATION
  60088. xAuth = db->xAuth;
  60089. db->xAuth = 0;
  60090. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  60091. db->xAuth = xAuth;
  60092. #else
  60093. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  60094. #endif
  60095. db->lookaside.bEnabled = enableLookaside;
  60096. pParse->nTab = n;
  60097. if( pSelTab ){
  60098. assert( pTable->aCol==0 );
  60099. pTable->nCol = pSelTab->nCol;
  60100. pTable->aCol = pSelTab->aCol;
  60101. pSelTab->nCol = 0;
  60102. pSelTab->aCol = 0;
  60103. sqlite3DeleteTable(pSelTab);
  60104. pTable->pSchema->flags |= DB_UnresetViews;
  60105. }else{
  60106. pTable->nCol = 0;
  60107. nErr++;
  60108. }
  60109. sqlite3SelectDelete(db, pSel);
  60110. } else {
  60111. nErr++;
  60112. }
  60113. #endif /* SQLITE_OMIT_VIEW */
  60114. return nErr;
  60115. }
  60116. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  60117. #ifndef SQLITE_OMIT_VIEW
  60118. /*
  60119. ** Clear the column names from every VIEW in database idx.
  60120. */
  60121. static void sqliteViewResetAll(sqlite3 *db, int idx){
  60122. HashElem *i;
  60123. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  60124. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  60125. Table *pTab = sqliteHashData(i);
  60126. if( pTab->pSelect ){
  60127. sqliteResetColumnNames(pTab);
  60128. }
  60129. }
  60130. DbClearProperty(db, idx, DB_UnresetViews);
  60131. }
  60132. #else
  60133. # define sqliteViewResetAll(A,B)
  60134. #endif /* SQLITE_OMIT_VIEW */
  60135. /*
  60136. ** This function is called by the VDBE to adjust the internal schema
  60137. ** used by SQLite when the btree layer moves a table root page. The
  60138. ** root-page of a table or index in database iDb has changed from iFrom
  60139. ** to iTo.
  60140. **
  60141. ** Ticket #1728: The symbol table might still contain information
  60142. ** on tables and/or indices that are the process of being deleted.
  60143. ** If you are unlucky, one of those deleted indices or tables might
  60144. ** have the same rootpage number as the real table or index that is
  60145. ** being moved. So we cannot stop searching after the first match
  60146. ** because the first match might be for one of the deleted indices
  60147. ** or tables and not the table/index that is actually being moved.
  60148. ** We must continue looping until all tables and indices with
  60149. ** rootpage==iFrom have been converted to have a rootpage of iTo
  60150. ** in order to be certain that we got the right one.
  60151. */
  60152. #ifndef SQLITE_OMIT_AUTOVACUUM
  60153. SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
  60154. HashElem *pElem;
  60155. Hash *pHash;
  60156. pHash = &pDb->pSchema->tblHash;
  60157. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  60158. Table *pTab = sqliteHashData(pElem);
  60159. if( pTab->tnum==iFrom ){
  60160. pTab->tnum = iTo;
  60161. }
  60162. }
  60163. pHash = &pDb->pSchema->idxHash;
  60164. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  60165. Index *pIdx = sqliteHashData(pElem);
  60166. if( pIdx->tnum==iFrom ){
  60167. pIdx->tnum = iTo;
  60168. }
  60169. }
  60170. }
  60171. #endif
  60172. /*
  60173. ** Write code to erase the table with root-page iTable from database iDb.
  60174. ** Also write code to modify the sqlite_master table and internal schema
  60175. ** if a root-page of another table is moved by the btree-layer whilst
  60176. ** erasing iTable (this can happen with an auto-vacuum database).
  60177. */
  60178. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  60179. Vdbe *v = sqlite3GetVdbe(pParse);
  60180. int r1 = sqlite3GetTempReg(pParse);
  60181. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  60182. #ifndef SQLITE_OMIT_AUTOVACUUM
  60183. /* OP_Destroy stores an in integer r1. If this integer
  60184. ** is non-zero, then it is the root page number of a table moved to
  60185. ** location iTable. The following code modifies the sqlite_master table to
  60186. ** reflect this.
  60187. **
  60188. ** The "#NNN" in the SQL is a special constant that means whatever value
  60189. ** is in register NNN. See sqlite3RegisterExpr().
  60190. */
  60191. sqlite3NestedParse(pParse,
  60192. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  60193. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  60194. #endif
  60195. sqlite3ReleaseTempReg(pParse, r1);
  60196. }
  60197. /*
  60198. ** Write VDBE code to erase table pTab and all associated indices on disk.
  60199. ** Code to update the sqlite_master tables and internal schema definitions
  60200. ** in case a root-page belonging to another table is moved by the btree layer
  60201. ** is also added (this can happen with an auto-vacuum database).
  60202. */
  60203. static void destroyTable(Parse *pParse, Table *pTab){
  60204. #ifdef SQLITE_OMIT_AUTOVACUUM
  60205. Index *pIdx;
  60206. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  60207. destroyRootPage(pParse, pTab->tnum, iDb);
  60208. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  60209. destroyRootPage(pParse, pIdx->tnum, iDb);
  60210. }
  60211. #else
  60212. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  60213. ** is not defined), then it is important to call OP_Destroy on the
  60214. ** table and index root-pages in order, starting with the numerically
  60215. ** largest root-page number. This guarantees that none of the root-pages
  60216. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  60217. ** following were coded:
  60218. **
  60219. ** OP_Destroy 4 0
  60220. ** ...
  60221. ** OP_Destroy 5 0
  60222. **
  60223. ** and root page 5 happened to be the largest root-page number in the
  60224. ** database, then root page 5 would be moved to page 4 by the
  60225. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  60226. ** a free-list page.
  60227. */
  60228. int iTab = pTab->tnum;
  60229. int iDestroyed = 0;
  60230. while( 1 ){
  60231. Index *pIdx;
  60232. int iLargest = 0;
  60233. if( iDestroyed==0 || iTab<iDestroyed ){
  60234. iLargest = iTab;
  60235. }
  60236. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  60237. int iIdx = pIdx->tnum;
  60238. assert( pIdx->pSchema==pTab->pSchema );
  60239. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  60240. iLargest = iIdx;
  60241. }
  60242. }
  60243. if( iLargest==0 ){
  60244. return;
  60245. }else{
  60246. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  60247. destroyRootPage(pParse, iLargest, iDb);
  60248. iDestroyed = iLargest;
  60249. }
  60250. }
  60251. #endif
  60252. }
  60253. /*
  60254. ** This routine is called to do the work of a DROP TABLE statement.
  60255. ** pName is the name of the table to be dropped.
  60256. */
  60257. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  60258. Table *pTab;
  60259. Vdbe *v;
  60260. sqlite3 *db = pParse->db;
  60261. int iDb;
  60262. if( pParse->nErr || db->mallocFailed ){
  60263. goto exit_drop_table;
  60264. }
  60265. assert( pName->nSrc==1 );
  60266. pTab = sqlite3LocateTable(pParse, isView,
  60267. pName->a[0].zName, pName->a[0].zDatabase);
  60268. if( pTab==0 ){
  60269. if( noErr ){
  60270. sqlite3ErrorClear(pParse);
  60271. }
  60272. goto exit_drop_table;
  60273. }
  60274. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  60275. assert( iDb>=0 && iDb<db->nDb );
  60276. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  60277. ** it is initialized.
  60278. */
  60279. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  60280. goto exit_drop_table;
  60281. }
  60282. #ifndef SQLITE_OMIT_AUTHORIZATION
  60283. {
  60284. int code;
  60285. const char *zTab = SCHEMA_TABLE(iDb);
  60286. const char *zDb = db->aDb[iDb].zName;
  60287. const char *zArg2 = 0;
  60288. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  60289. goto exit_drop_table;
  60290. }
  60291. if( isView ){
  60292. if( !OMIT_TEMPDB && iDb==1 ){
  60293. code = SQLITE_DROP_TEMP_VIEW;
  60294. }else{
  60295. code = SQLITE_DROP_VIEW;
  60296. }
  60297. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60298. }else if( IsVirtual(pTab) ){
  60299. code = SQLITE_DROP_VTABLE;
  60300. zArg2 = pTab->pMod->zName;
  60301. #endif
  60302. }else{
  60303. if( !OMIT_TEMPDB && iDb==1 ){
  60304. code = SQLITE_DROP_TEMP_TABLE;
  60305. }else{
  60306. code = SQLITE_DROP_TABLE;
  60307. }
  60308. }
  60309. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  60310. goto exit_drop_table;
  60311. }
  60312. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  60313. goto exit_drop_table;
  60314. }
  60315. }
  60316. #endif
  60317. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  60318. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  60319. goto exit_drop_table;
  60320. }
  60321. #ifndef SQLITE_OMIT_VIEW
  60322. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  60323. ** on a table.
  60324. */
  60325. if( isView && pTab->pSelect==0 ){
  60326. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  60327. goto exit_drop_table;
  60328. }
  60329. if( !isView && pTab->pSelect ){
  60330. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  60331. goto exit_drop_table;
  60332. }
  60333. #endif
  60334. /* Generate code to remove the table from the master table
  60335. ** on disk.
  60336. */
  60337. v = sqlite3GetVdbe(pParse);
  60338. if( v ){
  60339. Trigger *pTrigger;
  60340. Db *pDb = &db->aDb[iDb];
  60341. sqlite3BeginWriteOperation(pParse, 1, iDb);
  60342. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60343. if( IsVirtual(pTab) ){
  60344. if( v ){
  60345. sqlite3VdbeAddOp0(v, OP_VBegin);
  60346. }
  60347. }
  60348. #endif
  60349. /* Drop all triggers associated with the table being dropped. Code
  60350. ** is generated to remove entries from sqlite_master and/or
  60351. ** sqlite_temp_master if required.
  60352. */
  60353. pTrigger = sqlite3TriggerList(pParse, pTab);
  60354. while( pTrigger ){
  60355. assert( pTrigger->pSchema==pTab->pSchema ||
  60356. pTrigger->pSchema==db->aDb[1].pSchema );
  60357. sqlite3DropTriggerPtr(pParse, pTrigger);
  60358. pTrigger = pTrigger->pNext;
  60359. }
  60360. #ifndef SQLITE_OMIT_AUTOINCREMENT
  60361. /* Remove any entries of the sqlite_sequence table associated with
  60362. ** the table being dropped. This is done before the table is dropped
  60363. ** at the btree level, in case the sqlite_sequence table needs to
  60364. ** move as a result of the drop (can happen in auto-vacuum mode).
  60365. */
  60366. if( pTab->tabFlags & TF_Autoincrement ){
  60367. sqlite3NestedParse(pParse,
  60368. "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
  60369. pDb->zName, pTab->zName
  60370. );
  60371. }
  60372. #endif
  60373. /* Drop all SQLITE_MASTER table and index entries that refer to the
  60374. ** table. The program name loops through the master table and deletes
  60375. ** every row that refers to a table of the same name as the one being
  60376. ** dropped. Triggers are handled seperately because a trigger can be
  60377. ** created in the temp database that refers to a table in another
  60378. ** database.
  60379. */
  60380. sqlite3NestedParse(pParse,
  60381. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  60382. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  60383. /* Drop any statistics from the sqlite_stat1 table, if it exists */
  60384. if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  60385. sqlite3NestedParse(pParse,
  60386. "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
  60387. );
  60388. }
  60389. if( !isView && !IsVirtual(pTab) ){
  60390. destroyTable(pParse, pTab);
  60391. }
  60392. /* Remove the table entry from SQLite's internal schema and modify
  60393. ** the schema cookie.
  60394. */
  60395. if( IsVirtual(pTab) ){
  60396. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  60397. }
  60398. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  60399. sqlite3ChangeCookie(pParse, iDb);
  60400. }
  60401. sqliteViewResetAll(db, iDb);
  60402. exit_drop_table:
  60403. sqlite3SrcListDelete(db, pName);
  60404. }
  60405. /*
  60406. ** This routine is called to create a new foreign key on the table
  60407. ** currently under construction. pFromCol determines which columns
  60408. ** in the current table point to the foreign key. If pFromCol==0 then
  60409. ** connect the key to the last column inserted. pTo is the name of
  60410. ** the table referred to. pToCol is a list of tables in the other
  60411. ** pTo table that the foreign key points to. flags contains all
  60412. ** information about the conflict resolution algorithms specified
  60413. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  60414. **
  60415. ** An FKey structure is created and added to the table currently
  60416. ** under construction in the pParse->pNewTable field. The new FKey
  60417. ** is not linked into db->aFKey at this point - that does not happen
  60418. ** until sqlite3EndTable().
  60419. **
  60420. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  60421. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  60422. */
  60423. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  60424. Parse *pParse, /* Parsing context */
  60425. ExprList *pFromCol, /* Columns in this table that point to other table */
  60426. Token *pTo, /* Name of the other table */
  60427. ExprList *pToCol, /* Columns in the other table */
  60428. int flags /* Conflict resolution algorithms. */
  60429. ){
  60430. sqlite3 *db = pParse->db;
  60431. #ifndef SQLITE_OMIT_FOREIGN_KEY
  60432. FKey *pFKey = 0;
  60433. Table *p = pParse->pNewTable;
  60434. int nByte;
  60435. int i;
  60436. int nCol;
  60437. char *z;
  60438. assert( pTo!=0 );
  60439. if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
  60440. if( pFromCol==0 ){
  60441. int iCol = p->nCol-1;
  60442. if( iCol<0 ) goto fk_end;
  60443. if( pToCol && pToCol->nExpr!=1 ){
  60444. sqlite3ErrorMsg(pParse, "foreign key on %s"
  60445. " should reference only one column of table %T",
  60446. p->aCol[iCol].zName, pTo);
  60447. goto fk_end;
  60448. }
  60449. nCol = 1;
  60450. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  60451. sqlite3ErrorMsg(pParse,
  60452. "number of columns in foreign key does not match the number of "
  60453. "columns in the referenced table");
  60454. goto fk_end;
  60455. }else{
  60456. nCol = pFromCol->nExpr;
  60457. }
  60458. nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  60459. if( pToCol ){
  60460. for(i=0; i<pToCol->nExpr; i++){
  60461. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  60462. }
  60463. }
  60464. pFKey = sqlite3DbMallocZero(db, nByte );
  60465. if( pFKey==0 ){
  60466. goto fk_end;
  60467. }
  60468. pFKey->pFrom = p;
  60469. pFKey->pNextFrom = p->pFKey;
  60470. z = (char*)&pFKey[1];
  60471. pFKey->aCol = (struct sColMap*)z;
  60472. z += sizeof(struct sColMap)*nCol;
  60473. pFKey->zTo = z;
  60474. memcpy(z, pTo->z, pTo->n);
  60475. z[pTo->n] = 0;
  60476. z += pTo->n+1;
  60477. pFKey->pNextTo = 0;
  60478. pFKey->nCol = nCol;
  60479. if( pFromCol==0 ){
  60480. pFKey->aCol[0].iFrom = p->nCol-1;
  60481. }else{
  60482. for(i=0; i<nCol; i++){
  60483. int j;
  60484. for(j=0; j<p->nCol; j++){
  60485. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  60486. pFKey->aCol[i].iFrom = j;
  60487. break;
  60488. }
  60489. }
  60490. if( j>=p->nCol ){
  60491. sqlite3ErrorMsg(pParse,
  60492. "unknown column \"%s\" in foreign key definition",
  60493. pFromCol->a[i].zName);
  60494. goto fk_end;
  60495. }
  60496. }
  60497. }
  60498. if( pToCol ){
  60499. for(i=0; i<nCol; i++){
  60500. int n = sqlite3Strlen30(pToCol->a[i].zName);
  60501. pFKey->aCol[i].zCol = z;
  60502. memcpy(z, pToCol->a[i].zName, n);
  60503. z[n] = 0;
  60504. z += n+1;
  60505. }
  60506. }
  60507. pFKey->isDeferred = 0;
  60508. pFKey->deleteConf = (u8)(flags & 0xff);
  60509. pFKey->updateConf = (u8)((flags >> 8 ) & 0xff);
  60510. pFKey->insertConf = (u8)((flags >> 16 ) & 0xff);
  60511. /* Link the foreign key to the table as the last step.
  60512. */
  60513. p->pFKey = pFKey;
  60514. pFKey = 0;
  60515. fk_end:
  60516. sqlite3DbFree(db, pFKey);
  60517. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  60518. sqlite3ExprListDelete(db, pFromCol);
  60519. sqlite3ExprListDelete(db, pToCol);
  60520. }
  60521. /*
  60522. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  60523. ** clause is seen as part of a foreign key definition. The isDeferred
  60524. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  60525. ** The behavior of the most recently created foreign key is adjusted
  60526. ** accordingly.
  60527. */
  60528. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  60529. #ifndef SQLITE_OMIT_FOREIGN_KEY
  60530. Table *pTab;
  60531. FKey *pFKey;
  60532. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  60533. assert( isDeferred==0 || isDeferred==1 );
  60534. pFKey->isDeferred = (u8)isDeferred;
  60535. #endif
  60536. }
  60537. /*
  60538. ** Generate code that will erase and refill index *pIdx. This is
  60539. ** used to initialize a newly created index or to recompute the
  60540. ** content of an index in response to a REINDEX command.
  60541. **
  60542. ** if memRootPage is not negative, it means that the index is newly
  60543. ** created. The register specified by memRootPage contains the
  60544. ** root page number of the index. If memRootPage is negative, then
  60545. ** the index already exists and must be cleared before being refilled and
  60546. ** the root page number of the index is taken from pIndex->tnum.
  60547. */
  60548. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  60549. Table *pTab = pIndex->pTable; /* The table that is indexed */
  60550. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  60551. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  60552. int addr1; /* Address of top of loop */
  60553. int tnum; /* Root page of index */
  60554. Vdbe *v; /* Generate code into this virtual machine */
  60555. KeyInfo *pKey; /* KeyInfo for index */
  60556. int regIdxKey; /* Registers containing the index key */
  60557. int regRecord; /* Register holding assemblied index record */
  60558. sqlite3 *db = pParse->db; /* The database connection */
  60559. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  60560. #ifndef SQLITE_OMIT_AUTHORIZATION
  60561. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  60562. db->aDb[iDb].zName ) ){
  60563. return;
  60564. }
  60565. #endif
  60566. /* Require a write-lock on the table to perform this operation */
  60567. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  60568. v = sqlite3GetVdbe(pParse);
  60569. if( v==0 ) return;
  60570. if( memRootPage>=0 ){
  60571. tnum = memRootPage;
  60572. }else{
  60573. tnum = pIndex->tnum;
  60574. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  60575. }
  60576. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  60577. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  60578. (char *)pKey, P4_KEYINFO_HANDOFF);
  60579. if( memRootPage>=0 ){
  60580. sqlite3VdbeChangeP5(v, 1);
  60581. }
  60582. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  60583. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  60584. regRecord = sqlite3GetTempReg(pParse);
  60585. regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  60586. if( pIndex->onError!=OE_None ){
  60587. int j1, j2;
  60588. int regRowid;
  60589. regRowid = regIdxKey + pIndex->nColumn;
  60590. j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
  60591. j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
  60592. 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
  60593. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
  60594. "indexed columns are not unique", P4_STATIC);
  60595. sqlite3VdbeJumpHere(v, j1);
  60596. sqlite3VdbeJumpHere(v, j2);
  60597. }
  60598. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  60599. sqlite3ReleaseTempReg(pParse, regRecord);
  60600. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  60601. sqlite3VdbeJumpHere(v, addr1);
  60602. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  60603. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  60604. }
  60605. /*
  60606. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  60607. ** and pTblList is the name of the table that is to be indexed. Both will
  60608. ** be NULL for a primary key or an index that is created to satisfy a
  60609. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  60610. ** as the table to be indexed. pParse->pNewTable is a table that is
  60611. ** currently being constructed by a CREATE TABLE statement.
  60612. **
  60613. ** pList is a list of columns to be indexed. pList will be NULL if this
  60614. ** is a primary key or unique-constraint on the most recent column added
  60615. ** to the table currently under construction.
  60616. */
  60617. SQLITE_PRIVATE void sqlite3CreateIndex(
  60618. Parse *pParse, /* All information about this parse */
  60619. Token *pName1, /* First part of index name. May be NULL */
  60620. Token *pName2, /* Second part of index name. May be NULL */
  60621. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  60622. ExprList *pList, /* A list of columns to be indexed */
  60623. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  60624. Token *pStart, /* The CREATE token that begins this statement */
  60625. Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
  60626. int sortOrder, /* Sort order of primary key when pList==NULL */
  60627. int ifNotExist /* Omit error if index already exists */
  60628. ){
  60629. Table *pTab = 0; /* Table to be indexed */
  60630. Index *pIndex = 0; /* The index to be created */
  60631. char *zName = 0; /* Name of the index */
  60632. int nName; /* Number of characters in zName */
  60633. int i, j;
  60634. Token nullId; /* Fake token for an empty ID list */
  60635. DbFixer sFix; /* For assigning database names to pTable */
  60636. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  60637. sqlite3 *db = pParse->db;
  60638. Db *pDb; /* The specific table containing the indexed database */
  60639. int iDb; /* Index of the database that is being written */
  60640. Token *pName = 0; /* Unqualified name of the index to create */
  60641. struct ExprList_item *pListItem; /* For looping over pList */
  60642. int nCol;
  60643. int nExtra = 0;
  60644. char *zExtra;
  60645. if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
  60646. goto exit_create_index;
  60647. }
  60648. /*
  60649. ** Find the table that is to be indexed. Return early if not found.
  60650. */
  60651. if( pTblName!=0 ){
  60652. /* Use the two-part index name to determine the database
  60653. ** to search for the table. 'Fix' the table name to this db
  60654. ** before looking up the table.
  60655. */
  60656. assert( pName1 && pName2 );
  60657. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  60658. if( iDb<0 ) goto exit_create_index;
  60659. #ifndef SQLITE_OMIT_TEMPDB
  60660. /* If the index name was unqualified, check if the the table
  60661. ** is a temp table. If so, set the database to 1. Do not do this
  60662. ** if initialising a database schema.
  60663. */
  60664. if( !db->init.busy ){
  60665. pTab = sqlite3SrcListLookup(pParse, pTblName);
  60666. if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  60667. iDb = 1;
  60668. }
  60669. }
  60670. #endif
  60671. if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  60672. sqlite3FixSrcList(&sFix, pTblName)
  60673. ){
  60674. /* Because the parser constructs pTblName from a single identifier,
  60675. ** sqlite3FixSrcList can never fail. */
  60676. assert(0);
  60677. }
  60678. pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
  60679. pTblName->a[0].zDatabase);
  60680. if( !pTab || db->mallocFailed ) goto exit_create_index;
  60681. assert( db->aDb[iDb].pSchema==pTab->pSchema );
  60682. }else{
  60683. assert( pName==0 );
  60684. pTab = pParse->pNewTable;
  60685. if( !pTab ) goto exit_create_index;
  60686. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  60687. }
  60688. pDb = &db->aDb[iDb];
  60689. if( pTab==0 || pParse->nErr ) goto exit_create_index;
  60690. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  60691. && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
  60692. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  60693. goto exit_create_index;
  60694. }
  60695. #ifndef SQLITE_OMIT_VIEW
  60696. if( pTab->pSelect ){
  60697. sqlite3ErrorMsg(pParse, "views may not be indexed");
  60698. goto exit_create_index;
  60699. }
  60700. #endif
  60701. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60702. if( IsVirtual(pTab) ){
  60703. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  60704. goto exit_create_index;
  60705. }
  60706. #endif
  60707. /*
  60708. ** Find the name of the index. Make sure there is not already another
  60709. ** index or table with the same name.
  60710. **
  60711. ** Exception: If we are reading the names of permanent indices from the
  60712. ** sqlite_master table (because some other process changed the schema) and
  60713. ** one of the index names collides with the name of a temporary table or
  60714. ** index, then we will continue to process this index.
  60715. **
  60716. ** If pName==0 it means that we are
  60717. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  60718. ** own name.
  60719. */
  60720. if( pName ){
  60721. zName = sqlite3NameFromToken(db, pName);
  60722. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  60723. if( zName==0 ) goto exit_create_index;
  60724. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  60725. goto exit_create_index;
  60726. }
  60727. if( !db->init.busy ){
  60728. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
  60729. if( sqlite3FindTable(db, zName, 0)!=0 ){
  60730. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  60731. goto exit_create_index;
  60732. }
  60733. }
  60734. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  60735. if( !ifNotExist ){
  60736. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  60737. }
  60738. goto exit_create_index;
  60739. }
  60740. }else{
  60741. int n;
  60742. Index *pLoop;
  60743. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  60744. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  60745. if( zName==0 ){
  60746. goto exit_create_index;
  60747. }
  60748. }
  60749. /* Check for authorization to create an index.
  60750. */
  60751. #ifndef SQLITE_OMIT_AUTHORIZATION
  60752. {
  60753. const char *zDb = pDb->zName;
  60754. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  60755. goto exit_create_index;
  60756. }
  60757. i = SQLITE_CREATE_INDEX;
  60758. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  60759. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  60760. goto exit_create_index;
  60761. }
  60762. }
  60763. #endif
  60764. /* If pList==0, it means this routine was called to make a primary
  60765. ** key out of the last column added to the table under construction.
  60766. ** So create a fake list to simulate this.
  60767. */
  60768. if( pList==0 ){
  60769. nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
  60770. nullId.n = sqlite3Strlen30((char*)nullId.z);
  60771. pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
  60772. if( pList==0 ) goto exit_create_index;
  60773. pList->a[0].sortOrder = (u8)sortOrder;
  60774. }
  60775. /* Figure out how many bytes of space are required to store explicitly
  60776. ** specified collation sequence names.
  60777. */
  60778. for(i=0; i<pList->nExpr; i++){
  60779. Expr *pExpr;
  60780. CollSeq *pColl;
  60781. if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
  60782. nExtra += (1 + sqlite3Strlen30(pColl->zName));
  60783. }
  60784. }
  60785. /*
  60786. ** Allocate the index structure.
  60787. */
  60788. nName = sqlite3Strlen30(zName);
  60789. nCol = pList->nExpr;
  60790. pIndex = sqlite3DbMallocZero(db,
  60791. sizeof(Index) + /* Index structure */
  60792. sizeof(int)*nCol + /* Index.aiColumn */
  60793. sizeof(int)*(nCol+1) + /* Index.aiRowEst */
  60794. sizeof(char *)*nCol + /* Index.azColl */
  60795. sizeof(u8)*nCol + /* Index.aSortOrder */
  60796. nName + 1 + /* Index.zName */
  60797. nExtra /* Collation sequence names */
  60798. );
  60799. if( db->mallocFailed ){
  60800. goto exit_create_index;
  60801. }
  60802. pIndex->azColl = (char**)(&pIndex[1]);
  60803. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  60804. pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
  60805. pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
  60806. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  60807. zExtra = (char *)(&pIndex->zName[nName+1]);
  60808. memcpy(pIndex->zName, zName, nName+1);
  60809. pIndex->pTable = pTab;
  60810. pIndex->nColumn = pList->nExpr;
  60811. pIndex->onError = (u8)onError;
  60812. pIndex->autoIndex = (u8)(pName==0);
  60813. pIndex->pSchema = db->aDb[iDb].pSchema;
  60814. /* Check to see if we should honor DESC requests on index columns
  60815. */
  60816. if( pDb->pSchema->file_format>=4 ){
  60817. sortOrderMask = -1; /* Honor DESC */
  60818. }else{
  60819. sortOrderMask = 0; /* Ignore DESC */
  60820. }
  60821. /* Scan the names of the columns of the table to be indexed and
  60822. ** load the column indices into the Index structure. Report an error
  60823. ** if any column is not found.
  60824. */
  60825. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  60826. const char *zColName = pListItem->zName;
  60827. Column *pTabCol;
  60828. int requestedSortOrder;
  60829. char *zColl; /* Collation sequence name */
  60830. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  60831. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  60832. }
  60833. if( j>=pTab->nCol ){
  60834. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  60835. pTab->zName, zColName);
  60836. goto exit_create_index;
  60837. }
  60838. /* TODO: Add a test to make sure that the same column is not named
  60839. ** more than once within the same index. Only the first instance of
  60840. ** the column will ever be used by the optimizer. Note that using the
  60841. ** same column more than once cannot be an error because that would
  60842. ** break backwards compatibility - it needs to be a warning.
  60843. */
  60844. pIndex->aiColumn[i] = j;
  60845. if( pListItem->pExpr && pListItem->pExpr->pColl ){
  60846. assert( pListItem->pExpr->pColl );
  60847. zColl = zExtra;
  60848. sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
  60849. zExtra += (sqlite3Strlen30(zColl) + 1);
  60850. }else{
  60851. zColl = pTab->aCol[j].zColl;
  60852. if( !zColl ){
  60853. zColl = db->pDfltColl->zName;
  60854. }
  60855. }
  60856. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
  60857. goto exit_create_index;
  60858. }
  60859. pIndex->azColl[i] = zColl;
  60860. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  60861. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  60862. }
  60863. sqlite3DefaultRowEst(pIndex);
  60864. if( pTab==pParse->pNewTable ){
  60865. /* This routine has been called to create an automatic index as a
  60866. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  60867. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  60868. ** i.e. one of:
  60869. **
  60870. ** CREATE TABLE t(x PRIMARY KEY, y);
  60871. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  60872. **
  60873. ** Either way, check to see if the table already has such an index. If
  60874. ** so, don't bother creating this one. This only applies to
  60875. ** automatically created indices. Users can do as they wish with
  60876. ** explicit indices.
  60877. */
  60878. Index *pIdx;
  60879. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  60880. int k;
  60881. assert( pIdx->onError!=OE_None );
  60882. assert( pIdx->autoIndex );
  60883. assert( pIndex->onError!=OE_None );
  60884. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  60885. for(k=0; k<pIdx->nColumn; k++){
  60886. const char *z1 = pIdx->azColl[k];
  60887. const char *z2 = pIndex->azColl[k];
  60888. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  60889. if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
  60890. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  60891. }
  60892. if( k==pIdx->nColumn ){
  60893. if( pIdx->onError!=pIndex->onError ){
  60894. /* This constraint creates the same index as a previous
  60895. ** constraint specified somewhere in the CREATE TABLE statement.
  60896. ** However the ON CONFLICT clauses are different. If both this
  60897. ** constraint and the previous equivalent constraint have explicit
  60898. ** ON CONFLICT clauses this is an error. Otherwise, use the
  60899. ** explicitly specified behaviour for the index.
  60900. */
  60901. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  60902. sqlite3ErrorMsg(pParse,
  60903. "conflicting ON CONFLICT clauses specified", 0);
  60904. }
  60905. if( pIdx->onError==OE_Default ){
  60906. pIdx->onError = pIndex->onError;
  60907. }
  60908. }
  60909. goto exit_create_index;
  60910. }
  60911. }
  60912. }
  60913. /* Link the new Index structure to its table and to the other
  60914. ** in-memory database structures.
  60915. */
  60916. if( db->init.busy ){
  60917. Index *p;
  60918. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  60919. pIndex->zName, sqlite3Strlen30(pIndex->zName)+1,
  60920. pIndex);
  60921. if( p ){
  60922. assert( p==pIndex ); /* Malloc must have failed */
  60923. db->mallocFailed = 1;
  60924. goto exit_create_index;
  60925. }
  60926. db->flags |= SQLITE_InternChanges;
  60927. if( pTblName!=0 ){
  60928. pIndex->tnum = db->init.newTnum;
  60929. }
  60930. }
  60931. /* If the db->init.busy is 0 then create the index on disk. This
  60932. ** involves writing the index into the master table and filling in the
  60933. ** index with the current table contents.
  60934. **
  60935. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  60936. ** command. db->init.busy is 1 when a database is opened and
  60937. ** CREATE INDEX statements are read out of the master table. In
  60938. ** the latter case the index already exists on disk, which is why
  60939. ** we don't want to recreate it.
  60940. **
  60941. ** If pTblName==0 it means this index is generated as a primary key
  60942. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  60943. ** has just been created, it contains no data and the index initialization
  60944. ** step can be skipped.
  60945. */
  60946. else if( db->init.busy==0 ){
  60947. Vdbe *v;
  60948. char *zStmt;
  60949. int iMem = ++pParse->nMem;
  60950. v = sqlite3GetVdbe(pParse);
  60951. if( v==0 ) goto exit_create_index;
  60952. /* Create the rootpage for the index
  60953. */
  60954. sqlite3BeginWriteOperation(pParse, 1, iDb);
  60955. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  60956. /* Gather the complete text of the CREATE INDEX statement into
  60957. ** the zStmt variable
  60958. */
  60959. if( pStart && pEnd ){
  60960. /* A named index with an explicit CREATE INDEX statement */
  60961. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  60962. onError==OE_None ? "" : " UNIQUE",
  60963. pEnd->z - pName->z + 1,
  60964. pName->z);
  60965. }else{
  60966. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  60967. /* zStmt = sqlite3MPrintf(""); */
  60968. zStmt = 0;
  60969. }
  60970. /* Add an entry in sqlite_master for this index
  60971. */
  60972. sqlite3NestedParse(pParse,
  60973. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  60974. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  60975. pIndex->zName,
  60976. pTab->zName,
  60977. iMem,
  60978. zStmt
  60979. );
  60980. sqlite3DbFree(db, zStmt);
  60981. /* Fill the index with data and reparse the schema. Code an OP_Expire
  60982. ** to invalidate all pre-compiled statements.
  60983. */
  60984. if( pTblName ){
  60985. sqlite3RefillIndex(pParse, pIndex, iMem);
  60986. sqlite3ChangeCookie(pParse, iDb);
  60987. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  60988. sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
  60989. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  60990. }
  60991. }
  60992. /* When adding an index to the list of indices for a table, make
  60993. ** sure all indices labeled OE_Replace come after all those labeled
  60994. ** OE_Ignore. This is necessary for the correct operation of UPDATE
  60995. ** and INSERT.
  60996. */
  60997. if( db->init.busy || pTblName==0 ){
  60998. if( onError!=OE_Replace || pTab->pIndex==0
  60999. || pTab->pIndex->onError==OE_Replace){
  61000. pIndex->pNext = pTab->pIndex;
  61001. pTab->pIndex = pIndex;
  61002. }else{
  61003. Index *pOther = pTab->pIndex;
  61004. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  61005. pOther = pOther->pNext;
  61006. }
  61007. pIndex->pNext = pOther->pNext;
  61008. pOther->pNext = pIndex;
  61009. }
  61010. pIndex = 0;
  61011. }
  61012. /* Clean up before exiting */
  61013. exit_create_index:
  61014. if( pIndex ){
  61015. sqlite3_free(pIndex->zColAff);
  61016. sqlite3DbFree(db, pIndex);
  61017. }
  61018. sqlite3ExprListDelete(db, pList);
  61019. sqlite3SrcListDelete(db, pTblName);
  61020. sqlite3DbFree(db, zName);
  61021. return;
  61022. }
  61023. /*
  61024. ** Generate code to make sure the file format number is at least minFormat.
  61025. ** The generated code will increase the file format number if necessary.
  61026. */
  61027. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  61028. Vdbe *v;
  61029. v = sqlite3GetVdbe(pParse);
  61030. if( v ){
  61031. int r1 = sqlite3GetTempReg(pParse);
  61032. int r2 = sqlite3GetTempReg(pParse);
  61033. int j1;
  61034. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
  61035. sqlite3VdbeUsesBtree(v, iDb);
  61036. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  61037. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  61038. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
  61039. sqlite3VdbeJumpHere(v, j1);
  61040. sqlite3ReleaseTempReg(pParse, r1);
  61041. sqlite3ReleaseTempReg(pParse, r2);
  61042. }
  61043. }
  61044. /*
  61045. ** Fill the Index.aiRowEst[] array with default information - information
  61046. ** to be used when we have not run the ANALYZE command.
  61047. **
  61048. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  61049. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  61050. ** number of rows in the table that match any particular value of the
  61051. ** first column of the index. aiRowEst[2] is an estimate of the number
  61052. ** of rows that match any particular combiniation of the first 2 columns
  61053. ** of the index. And so forth. It must always be the case that
  61054. *
  61055. ** aiRowEst[N]<=aiRowEst[N-1]
  61056. ** aiRowEst[N]>=1
  61057. **
  61058. ** Apart from that, we have little to go on besides intuition as to
  61059. ** how aiRowEst[] should be initialized. The numbers generated here
  61060. ** are based on typical values found in actual indices.
  61061. */
  61062. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  61063. unsigned *a = pIdx->aiRowEst;
  61064. int i;
  61065. assert( a!=0 );
  61066. a[0] = 1000000;
  61067. for(i=pIdx->nColumn; i>=5; i--){
  61068. a[i] = 5;
  61069. }
  61070. while( i>=1 ){
  61071. a[i] = 11 - i;
  61072. i--;
  61073. }
  61074. if( pIdx->onError!=OE_None ){
  61075. a[pIdx->nColumn] = 1;
  61076. }
  61077. }
  61078. /*
  61079. ** This routine will drop an existing named index. This routine
  61080. ** implements the DROP INDEX statement.
  61081. */
  61082. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  61083. Index *pIndex;
  61084. Vdbe *v;
  61085. sqlite3 *db = pParse->db;
  61086. int iDb;
  61087. if( pParse->nErr || db->mallocFailed ){
  61088. goto exit_drop_index;
  61089. }
  61090. assert( pName->nSrc==1 );
  61091. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  61092. goto exit_drop_index;
  61093. }
  61094. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  61095. if( pIndex==0 ){
  61096. if( !ifExists ){
  61097. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  61098. }
  61099. pParse->checkSchema = 1;
  61100. goto exit_drop_index;
  61101. }
  61102. if( pIndex->autoIndex ){
  61103. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  61104. "or PRIMARY KEY constraint cannot be dropped", 0);
  61105. goto exit_drop_index;
  61106. }
  61107. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  61108. #ifndef SQLITE_OMIT_AUTHORIZATION
  61109. {
  61110. int code = SQLITE_DROP_INDEX;
  61111. Table *pTab = pIndex->pTable;
  61112. const char *zDb = db->aDb[iDb].zName;
  61113. const char *zTab = SCHEMA_TABLE(iDb);
  61114. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  61115. goto exit_drop_index;
  61116. }
  61117. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  61118. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  61119. goto exit_drop_index;
  61120. }
  61121. }
  61122. #endif
  61123. /* Generate code to remove the index and from the master table */
  61124. v = sqlite3GetVdbe(pParse);
  61125. if( v ){
  61126. sqlite3BeginWriteOperation(pParse, 1, iDb);
  61127. sqlite3NestedParse(pParse,
  61128. "DELETE FROM %Q.%s WHERE name=%Q",
  61129. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  61130. pIndex->zName
  61131. );
  61132. if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  61133. sqlite3NestedParse(pParse,
  61134. "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
  61135. db->aDb[iDb].zName, pIndex->zName
  61136. );
  61137. }
  61138. sqlite3ChangeCookie(pParse, iDb);
  61139. destroyRootPage(pParse, pIndex->tnum, iDb);
  61140. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  61141. }
  61142. exit_drop_index:
  61143. sqlite3SrcListDelete(db, pName);
  61144. }
  61145. /*
  61146. ** pArray is a pointer to an array of objects. Each object in the
  61147. ** array is szEntry bytes in size. This routine allocates a new
  61148. ** object on the end of the array.
  61149. **
  61150. ** *pnEntry is the number of entries already in use. *pnAlloc is
  61151. ** the previously allocated size of the array. initSize is the
  61152. ** suggested initial array size allocation.
  61153. **
  61154. ** The index of the new entry is returned in *pIdx.
  61155. **
  61156. ** This routine returns a pointer to the array of objects. This
  61157. ** might be the same as the pArray parameter or it might be a different
  61158. ** pointer if the array was resized.
  61159. */
  61160. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  61161. sqlite3 *db, /* Connection to notify of malloc failures */
  61162. void *pArray, /* Array of objects. Might be reallocated */
  61163. int szEntry, /* Size of each object in the array */
  61164. int initSize, /* Suggested initial allocation, in elements */
  61165. int *pnEntry, /* Number of objects currently in use */
  61166. int *pnAlloc, /* Current size of the allocation, in elements */
  61167. int *pIdx /* Write the index of a new slot here */
  61168. ){
  61169. char *z;
  61170. if( *pnEntry >= *pnAlloc ){
  61171. void *pNew;
  61172. int newSize;
  61173. newSize = (*pnAlloc)*2 + initSize;
  61174. pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
  61175. if( pNew==0 ){
  61176. *pIdx = -1;
  61177. return pArray;
  61178. }
  61179. *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
  61180. pArray = pNew;
  61181. }
  61182. z = (char*)pArray;
  61183. memset(&z[*pnEntry * szEntry], 0, szEntry);
  61184. *pIdx = *pnEntry;
  61185. ++*pnEntry;
  61186. return pArray;
  61187. }
  61188. /*
  61189. ** Append a new element to the given IdList. Create a new IdList if
  61190. ** need be.
  61191. **
  61192. ** A new IdList is returned, or NULL if malloc() fails.
  61193. */
  61194. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  61195. int i;
  61196. if( pList==0 ){
  61197. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  61198. if( pList==0 ) return 0;
  61199. pList->nAlloc = 0;
  61200. }
  61201. pList->a = sqlite3ArrayAllocate(
  61202. db,
  61203. pList->a,
  61204. sizeof(pList->a[0]),
  61205. 5,
  61206. &pList->nId,
  61207. &pList->nAlloc,
  61208. &i
  61209. );
  61210. if( i<0 ){
  61211. sqlite3IdListDelete(db, pList);
  61212. return 0;
  61213. }
  61214. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  61215. return pList;
  61216. }
  61217. /*
  61218. ** Delete an IdList.
  61219. */
  61220. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  61221. int i;
  61222. if( pList==0 ) return;
  61223. for(i=0; i<pList->nId; i++){
  61224. sqlite3DbFree(db, pList->a[i].zName);
  61225. }
  61226. sqlite3DbFree(db, pList->a);
  61227. sqlite3DbFree(db, pList);
  61228. }
  61229. /*
  61230. ** Return the index in pList of the identifier named zId. Return -1
  61231. ** if not found.
  61232. */
  61233. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  61234. int i;
  61235. if( pList==0 ) return -1;
  61236. for(i=0; i<pList->nId; i++){
  61237. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  61238. }
  61239. return -1;
  61240. }
  61241. /*
  61242. ** Expand the space allocated for the given SrcList object by
  61243. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  61244. ** New slots are zeroed.
  61245. **
  61246. ** For example, suppose a SrcList initially contains two entries: A,B.
  61247. ** To append 3 new entries onto the end, do this:
  61248. **
  61249. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  61250. **
  61251. ** After the call above it would contain: A, B, nil, nil, nil.
  61252. ** If the iStart argument had been 1 instead of 2, then the result
  61253. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  61254. ** the iStart value would be 0. The result then would
  61255. ** be: nil, nil, nil, A, B.
  61256. **
  61257. ** If a memory allocation fails the SrcList is unchanged. The
  61258. ** db->mallocFailed flag will be set to true.
  61259. */
  61260. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  61261. sqlite3 *db, /* Database connection to notify of OOM errors */
  61262. SrcList *pSrc, /* The SrcList to be enlarged */
  61263. int nExtra, /* Number of new slots to add to pSrc->a[] */
  61264. int iStart /* Index in pSrc->a[] of first new slot */
  61265. ){
  61266. int i;
  61267. /* Sanity checking on calling parameters */
  61268. assert( iStart>=0 );
  61269. assert( nExtra>=1 );
  61270. if( pSrc==0 || iStart>pSrc->nSrc ){
  61271. assert( db->mallocFailed );
  61272. return pSrc;
  61273. }
  61274. /* Allocate additional space if needed */
  61275. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  61276. SrcList *pNew;
  61277. int nAlloc = pSrc->nSrc+nExtra;
  61278. int nGot;
  61279. pNew = sqlite3DbRealloc(db, pSrc,
  61280. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  61281. if( pNew==0 ){
  61282. assert( db->mallocFailed );
  61283. return pSrc;
  61284. }
  61285. pSrc = pNew;
  61286. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  61287. pSrc->nAlloc = (u16)nGot;
  61288. }
  61289. /* Move existing slots that come after the newly inserted slots
  61290. ** out of the way */
  61291. for(i=pSrc->nSrc-1; i>=iStart; i--){
  61292. pSrc->a[i+nExtra] = pSrc->a[i];
  61293. }
  61294. pSrc->nSrc += (i16)nExtra;
  61295. /* Zero the newly allocated slots */
  61296. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  61297. for(i=iStart; i<iStart+nExtra; i++){
  61298. pSrc->a[i].iCursor = -1;
  61299. }
  61300. /* Return a pointer to the enlarged SrcList */
  61301. return pSrc;
  61302. }
  61303. /*
  61304. ** Append a new table name to the given SrcList. Create a new SrcList if
  61305. ** need be. A new entry is created in the SrcList even if pToken is NULL.
  61306. **
  61307. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  61308. ** SrcList might be the same as the SrcList that was input or it might be
  61309. ** a new one. If an OOM error does occurs, then the prior value of pList
  61310. ** that is input to this routine is automatically freed.
  61311. **
  61312. ** If pDatabase is not null, it means that the table has an optional
  61313. ** database name prefix. Like this: "database.table". The pDatabase
  61314. ** points to the table name and the pTable points to the database name.
  61315. ** The SrcList.a[].zName field is filled with the table name which might
  61316. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  61317. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  61318. ** or with NULL if no database is specified.
  61319. **
  61320. ** In other words, if call like this:
  61321. **
  61322. ** sqlite3SrcListAppend(D,A,B,0);
  61323. **
  61324. ** Then B is a table name and the database name is unspecified. If called
  61325. ** like this:
  61326. **
  61327. ** sqlite3SrcListAppend(D,A,B,C);
  61328. **
  61329. ** Then C is the table name and B is the database name.
  61330. */
  61331. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  61332. sqlite3 *db, /* Connection to notify of malloc failures */
  61333. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  61334. Token *pTable, /* Table to append */
  61335. Token *pDatabase /* Database of the table */
  61336. ){
  61337. struct SrcList_item *pItem;
  61338. if( pList==0 ){
  61339. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  61340. if( pList==0 ) return 0;
  61341. pList->nAlloc = 1;
  61342. }
  61343. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  61344. if( db->mallocFailed ){
  61345. sqlite3SrcListDelete(db, pList);
  61346. return 0;
  61347. }
  61348. pItem = &pList->a[pList->nSrc-1];
  61349. if( pDatabase && pDatabase->z==0 ){
  61350. pDatabase = 0;
  61351. }
  61352. if( pDatabase && pTable ){
  61353. Token *pTemp = pDatabase;
  61354. pDatabase = pTable;
  61355. pTable = pTemp;
  61356. }
  61357. pItem->zName = sqlite3NameFromToken(db, pTable);
  61358. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  61359. return pList;
  61360. }
  61361. /*
  61362. ** Assign VdbeCursor index numbers to all tables in a SrcList
  61363. */
  61364. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  61365. int i;
  61366. struct SrcList_item *pItem;
  61367. assert(pList || pParse->db->mallocFailed );
  61368. if( pList ){
  61369. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  61370. if( pItem->iCursor>=0 ) break;
  61371. pItem->iCursor = pParse->nTab++;
  61372. if( pItem->pSelect ){
  61373. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  61374. }
  61375. }
  61376. }
  61377. }
  61378. /*
  61379. ** Delete an entire SrcList including all its substructure.
  61380. */
  61381. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  61382. int i;
  61383. struct SrcList_item *pItem;
  61384. if( pList==0 ) return;
  61385. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  61386. sqlite3DbFree(db, pItem->zDatabase);
  61387. sqlite3DbFree(db, pItem->zName);
  61388. sqlite3DbFree(db, pItem->zAlias);
  61389. sqlite3DbFree(db, pItem->zIndex);
  61390. sqlite3DeleteTable(pItem->pTab);
  61391. sqlite3SelectDelete(db, pItem->pSelect);
  61392. sqlite3ExprDelete(db, pItem->pOn);
  61393. sqlite3IdListDelete(db, pItem->pUsing);
  61394. }
  61395. sqlite3DbFree(db, pList);
  61396. }
  61397. /*
  61398. ** This routine is called by the parser to add a new term to the
  61399. ** end of a growing FROM clause. The "p" parameter is the part of
  61400. ** the FROM clause that has already been constructed. "p" is NULL
  61401. ** if this is the first term of the FROM clause. pTable and pDatabase
  61402. ** are the name of the table and database named in the FROM clause term.
  61403. ** pDatabase is NULL if the database name qualifier is missing - the
  61404. ** usual case. If the term has a alias, then pAlias points to the
  61405. ** alias token. If the term is a subquery, then pSubquery is the
  61406. ** SELECT statement that the subquery encodes. The pTable and
  61407. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  61408. ** parameters are the content of the ON and USING clauses.
  61409. **
  61410. ** Return a new SrcList which encodes is the FROM with the new
  61411. ** term added.
  61412. */
  61413. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  61414. Parse *pParse, /* Parsing context */
  61415. SrcList *p, /* The left part of the FROM clause already seen */
  61416. Token *pTable, /* Name of the table to add to the FROM clause */
  61417. Token *pDatabase, /* Name of the database containing pTable */
  61418. Token *pAlias, /* The right-hand side of the AS subexpression */
  61419. Select *pSubquery, /* A subquery used in place of a table name */
  61420. Expr *pOn, /* The ON clause of a join */
  61421. IdList *pUsing /* The USING clause of a join */
  61422. ){
  61423. struct SrcList_item *pItem;
  61424. sqlite3 *db = pParse->db;
  61425. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  61426. if( p==0 || p->nSrc==0 ){
  61427. sqlite3ExprDelete(db, pOn);
  61428. sqlite3IdListDelete(db, pUsing);
  61429. sqlite3SelectDelete(db, pSubquery);
  61430. return p;
  61431. }
  61432. pItem = &p->a[p->nSrc-1];
  61433. if( pAlias && pAlias->n ){
  61434. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  61435. }
  61436. pItem->pSelect = pSubquery;
  61437. pItem->pOn = pOn;
  61438. pItem->pUsing = pUsing;
  61439. return p;
  61440. }
  61441. /*
  61442. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  61443. ** element of the source-list passed as the second argument.
  61444. */
  61445. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  61446. if( pIndexedBy && p && p->nSrc>0 ){
  61447. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  61448. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  61449. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  61450. /* A "NOT INDEXED" clause was supplied. See parse.y
  61451. ** construct "indexed_opt" for details. */
  61452. pItem->notIndexed = 1;
  61453. }else{
  61454. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  61455. }
  61456. }
  61457. }
  61458. /*
  61459. ** When building up a FROM clause in the parser, the join operator
  61460. ** is initially attached to the left operand. But the code generator
  61461. ** expects the join operator to be on the right operand. This routine
  61462. ** Shifts all join operators from left to right for an entire FROM
  61463. ** clause.
  61464. **
  61465. ** Example: Suppose the join is like this:
  61466. **
  61467. ** A natural cross join B
  61468. **
  61469. ** The operator is "natural cross join". The A and B operands are stored
  61470. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  61471. ** operator with A. This routine shifts that operator over to B.
  61472. */
  61473. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  61474. if( p && p->a ){
  61475. int i;
  61476. for(i=p->nSrc-1; i>0; i--){
  61477. p->a[i].jointype = p->a[i-1].jointype;
  61478. }
  61479. p->a[0].jointype = 0;
  61480. }
  61481. }
  61482. /*
  61483. ** Begin a transaction
  61484. */
  61485. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  61486. sqlite3 *db;
  61487. Vdbe *v;
  61488. int i;
  61489. if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  61490. if( pParse->nErr || db->mallocFailed ) return;
  61491. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
  61492. v = sqlite3GetVdbe(pParse);
  61493. if( !v ) return;
  61494. if( type!=TK_DEFERRED ){
  61495. for(i=0; i<db->nDb; i++){
  61496. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  61497. sqlite3VdbeUsesBtree(v, i);
  61498. }
  61499. }
  61500. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  61501. }
  61502. /*
  61503. ** Commit a transaction
  61504. */
  61505. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  61506. sqlite3 *db;
  61507. Vdbe *v;
  61508. if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  61509. if( pParse->nErr || db->mallocFailed ) return;
  61510. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
  61511. v = sqlite3GetVdbe(pParse);
  61512. if( v ){
  61513. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  61514. }
  61515. }
  61516. /*
  61517. ** Rollback a transaction
  61518. */
  61519. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  61520. sqlite3 *db;
  61521. Vdbe *v;
  61522. if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  61523. if( pParse->nErr || db->mallocFailed ) return;
  61524. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
  61525. v = sqlite3GetVdbe(pParse);
  61526. if( v ){
  61527. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  61528. }
  61529. }
  61530. /*
  61531. ** This function is called by the parser when it parses a command to create,
  61532. ** release or rollback an SQL savepoint.
  61533. */
  61534. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  61535. char *zName = sqlite3NameFromToken(pParse->db, pName);
  61536. if( zName ){
  61537. Vdbe *v = sqlite3GetVdbe(pParse);
  61538. #ifndef SQLITE_OMIT_AUTHORIZATION
  61539. static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  61540. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  61541. #endif
  61542. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  61543. sqlite3DbFree(pParse->db, zName);
  61544. return;
  61545. }
  61546. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  61547. }
  61548. }
  61549. /*
  61550. ** Make sure the TEMP database is open and available for use. Return
  61551. ** the number of errors. Leave any error messages in the pParse structure.
  61552. */
  61553. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  61554. sqlite3 *db = pParse->db;
  61555. if( db->aDb[1].pBt==0 && !pParse->explain ){
  61556. int rc;
  61557. static const int flags =
  61558. SQLITE_OPEN_READWRITE |
  61559. SQLITE_OPEN_CREATE |
  61560. SQLITE_OPEN_EXCLUSIVE |
  61561. SQLITE_OPEN_DELETEONCLOSE |
  61562. SQLITE_OPEN_TEMP_DB;
  61563. rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
  61564. &db->aDb[1].pBt);
  61565. if( rc!=SQLITE_OK ){
  61566. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  61567. "file for storing temporary tables");
  61568. pParse->rc = rc;
  61569. return 1;
  61570. }
  61571. assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
  61572. assert( db->aDb[1].pSchema );
  61573. sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
  61574. db->dfltJournalMode);
  61575. }
  61576. return 0;
  61577. }
  61578. /*
  61579. ** Generate VDBE code that will verify the schema cookie and start
  61580. ** a read-transaction for all named database files.
  61581. **
  61582. ** It is important that all schema cookies be verified and all
  61583. ** read transactions be started before anything else happens in
  61584. ** the VDBE program. But this routine can be called after much other
  61585. ** code has been generated. So here is what we do:
  61586. **
  61587. ** The first time this routine is called, we code an OP_Goto that
  61588. ** will jump to a subroutine at the end of the program. Then we
  61589. ** record every database that needs its schema verified in the
  61590. ** pParse->cookieMask field. Later, after all other code has been
  61591. ** generated, the subroutine that does the cookie verifications and
  61592. ** starts the transactions will be coded and the OP_Goto P2 value
  61593. ** will be made to point to that subroutine. The generation of the
  61594. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  61595. **
  61596. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  61597. ** schema on any databases. This can be used to position the OP_Goto
  61598. ** early in the code, before we know if any database tables will be used.
  61599. */
  61600. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  61601. sqlite3 *db;
  61602. Vdbe *v;
  61603. int mask;
  61604. v = sqlite3GetVdbe(pParse);
  61605. if( v==0 ) return; /* This only happens if there was a prior error */
  61606. db = pParse->db;
  61607. if( pParse->cookieGoto==0 ){
  61608. pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  61609. }
  61610. if( iDb>=0 ){
  61611. assert( iDb<db->nDb );
  61612. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  61613. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  61614. mask = 1<<iDb;
  61615. if( (pParse->cookieMask & mask)==0 ){
  61616. pParse->cookieMask |= mask;
  61617. pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  61618. if( !OMIT_TEMPDB && iDb==1 ){
  61619. sqlite3OpenTempDatabase(pParse);
  61620. }
  61621. }
  61622. }
  61623. }
  61624. /*
  61625. ** Generate VDBE code that prepares for doing an operation that
  61626. ** might change the database.
  61627. **
  61628. ** This routine starts a new transaction if we are not already within
  61629. ** a transaction. If we are already within a transaction, then a checkpoint
  61630. ** is set if the setStatement parameter is true. A checkpoint should
  61631. ** be set for operations that might fail (due to a constraint) part of
  61632. ** the way through and which will need to undo some writes without having to
  61633. ** rollback the whole transaction. For operations where all constraints
  61634. ** can be checked before any changes are made to the database, it is never
  61635. ** necessary to undo a write and the checkpoint should not be set.
  61636. */
  61637. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  61638. Vdbe *v = sqlite3GetVdbe(pParse);
  61639. if( v==0 ) return;
  61640. sqlite3CodeVerifySchema(pParse, iDb);
  61641. pParse->writeMask |= 1<<iDb;
  61642. if( setStatement && pParse->nested==0 ){
  61643. sqlite3VdbeAddOp1(v, OP_Statement, iDb);
  61644. }
  61645. }
  61646. /*
  61647. ** Check to see if pIndex uses the collating sequence pColl. Return
  61648. ** true if it does and false if it does not.
  61649. */
  61650. #ifndef SQLITE_OMIT_REINDEX
  61651. static int collationMatch(const char *zColl, Index *pIndex){
  61652. int i;
  61653. for(i=0; i<pIndex->nColumn; i++){
  61654. const char *z = pIndex->azColl[i];
  61655. if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
  61656. return 1;
  61657. }
  61658. }
  61659. return 0;
  61660. }
  61661. #endif
  61662. /*
  61663. ** Recompute all indices of pTab that use the collating sequence pColl.
  61664. ** If pColl==0 then recompute all indices of pTab.
  61665. */
  61666. #ifndef SQLITE_OMIT_REINDEX
  61667. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  61668. Index *pIndex; /* An index associated with pTab */
  61669. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  61670. if( zColl==0 || collationMatch(zColl, pIndex) ){
  61671. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  61672. sqlite3BeginWriteOperation(pParse, 0, iDb);
  61673. sqlite3RefillIndex(pParse, pIndex, -1);
  61674. }
  61675. }
  61676. }
  61677. #endif
  61678. /*
  61679. ** Recompute all indices of all tables in all databases where the
  61680. ** indices use the collating sequence pColl. If pColl==0 then recompute
  61681. ** all indices everywhere.
  61682. */
  61683. #ifndef SQLITE_OMIT_REINDEX
  61684. static void reindexDatabases(Parse *pParse, char const *zColl){
  61685. Db *pDb; /* A single database */
  61686. int iDb; /* The database index number */
  61687. sqlite3 *db = pParse->db; /* The database connection */
  61688. HashElem *k; /* For looping over tables in pDb */
  61689. Table *pTab; /* A table in the database */
  61690. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  61691. assert( pDb!=0 );
  61692. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  61693. pTab = (Table*)sqliteHashData(k);
  61694. reindexTable(pParse, pTab, zColl);
  61695. }
  61696. }
  61697. }
  61698. #endif
  61699. /*
  61700. ** Generate code for the REINDEX command.
  61701. **
  61702. ** REINDEX -- 1
  61703. ** REINDEX <collation> -- 2
  61704. ** REINDEX ?<database>.?<tablename> -- 3
  61705. ** REINDEX ?<database>.?<indexname> -- 4
  61706. **
  61707. ** Form 1 causes all indices in all attached databases to be rebuilt.
  61708. ** Form 2 rebuilds all indices in all databases that use the named
  61709. ** collating function. Forms 3 and 4 rebuild the named index or all
  61710. ** indices associated with the named table.
  61711. */
  61712. #ifndef SQLITE_OMIT_REINDEX
  61713. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  61714. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  61715. char *z; /* Name of a table or index */
  61716. const char *zDb; /* Name of the database */
  61717. Table *pTab; /* A table in the database */
  61718. Index *pIndex; /* An index associated with pTab */
  61719. int iDb; /* The database index number */
  61720. sqlite3 *db = pParse->db; /* The database connection */
  61721. Token *pObjName; /* Name of the table or index to be reindexed */
  61722. /* Read the database schema. If an error occurs, leave an error message
  61723. ** and code in pParse and return NULL. */
  61724. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  61725. return;
  61726. }
  61727. if( pName1==0 || pName1->z==0 ){
  61728. reindexDatabases(pParse, 0);
  61729. return;
  61730. }else if( pName2==0 || pName2->z==0 ){
  61731. char *zColl;
  61732. assert( pName1->z );
  61733. zColl = sqlite3NameFromToken(pParse->db, pName1);
  61734. if( !zColl ) return;
  61735. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
  61736. if( pColl ){
  61737. if( zColl ){
  61738. reindexDatabases(pParse, zColl);
  61739. sqlite3DbFree(db, zColl);
  61740. }
  61741. return;
  61742. }
  61743. sqlite3DbFree(db, zColl);
  61744. }
  61745. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  61746. if( iDb<0 ) return;
  61747. z = sqlite3NameFromToken(db, pObjName);
  61748. if( z==0 ) return;
  61749. zDb = db->aDb[iDb].zName;
  61750. pTab = sqlite3FindTable(db, z, zDb);
  61751. if( pTab ){
  61752. reindexTable(pParse, pTab, 0);
  61753. sqlite3DbFree(db, z);
  61754. return;
  61755. }
  61756. pIndex = sqlite3FindIndex(db, z, zDb);
  61757. sqlite3DbFree(db, z);
  61758. if( pIndex ){
  61759. sqlite3BeginWriteOperation(pParse, 0, iDb);
  61760. sqlite3RefillIndex(pParse, pIndex, -1);
  61761. return;
  61762. }
  61763. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  61764. }
  61765. #endif
  61766. /*
  61767. ** Return a dynamicly allocated KeyInfo structure that can be used
  61768. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  61769. **
  61770. ** If successful, a pointer to the new structure is returned. In this case
  61771. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  61772. ** pointer. If an error occurs (out of memory or missing collation
  61773. ** sequence), NULL is returned and the state of pParse updated to reflect
  61774. ** the error.
  61775. */
  61776. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  61777. int i;
  61778. int nCol = pIdx->nColumn;
  61779. int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  61780. sqlite3 *db = pParse->db;
  61781. KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
  61782. if( pKey ){
  61783. pKey->db = pParse->db;
  61784. pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  61785. assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  61786. for(i=0; i<nCol; i++){
  61787. char *zColl = pIdx->azColl[i];
  61788. assert( zColl );
  61789. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
  61790. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  61791. }
  61792. pKey->nField = (u16)nCol;
  61793. }
  61794. if( pParse->nErr ){
  61795. sqlite3DbFree(db, pKey);
  61796. pKey = 0;
  61797. }
  61798. return pKey;
  61799. }
  61800. /************** End of build.c ***********************************************/
  61801. /************** Begin file callback.c ****************************************/
  61802. /*
  61803. ** 2005 May 23
  61804. **
  61805. ** The author disclaims copyright to this source code. In place of
  61806. ** a legal notice, here is a blessing:
  61807. **
  61808. ** May you do good and not evil.
  61809. ** May you find forgiveness for yourself and forgive others.
  61810. ** May you share freely, never taking more than you give.
  61811. **
  61812. *************************************************************************
  61813. **
  61814. ** This file contains functions used to access the internal hash tables
  61815. ** of user defined functions and collation sequences.
  61816. **
  61817. ** $Id: callback.c,v 1.37 2009/03/24 15:08:10 drh Exp $
  61818. */
  61819. /*
  61820. ** Invoke the 'collation needed' callback to request a collation sequence
  61821. ** in the database text encoding of name zName, length nName.
  61822. ** If the collation sequence
  61823. */
  61824. static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
  61825. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  61826. if( nName<0 ) nName = sqlite3Strlen(db, zName);
  61827. if( db->xCollNeeded ){
  61828. char *zExternal = sqlite3DbStrNDup(db, zName, nName);
  61829. if( !zExternal ) return;
  61830. db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  61831. sqlite3DbFree(db, zExternal);
  61832. }
  61833. #ifndef SQLITE_OMIT_UTF16
  61834. if( db->xCollNeeded16 ){
  61835. char const *zExternal;
  61836. sqlite3_value *pTmp = sqlite3ValueNew(db);
  61837. sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
  61838. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  61839. if( zExternal ){
  61840. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  61841. }
  61842. sqlite3ValueFree(pTmp);
  61843. }
  61844. #endif
  61845. }
  61846. /*
  61847. ** This routine is called if the collation factory fails to deliver a
  61848. ** collation function in the best encoding but there may be other versions
  61849. ** of this collation function (for other text encodings) available. Use one
  61850. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  61851. ** possible.
  61852. */
  61853. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  61854. CollSeq *pColl2;
  61855. char *z = pColl->zName;
  61856. int n = sqlite3Strlen30(z);
  61857. int i;
  61858. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  61859. for(i=0; i<3; i++){
  61860. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
  61861. if( pColl2->xCmp!=0 ){
  61862. memcpy(pColl, pColl2, sizeof(CollSeq));
  61863. pColl->xDel = 0; /* Do not copy the destructor */
  61864. return SQLITE_OK;
  61865. }
  61866. }
  61867. return SQLITE_ERROR;
  61868. }
  61869. /*
  61870. ** This function is responsible for invoking the collation factory callback
  61871. ** or substituting a collation sequence of a different encoding when the
  61872. ** requested collation sequence is not available in the database native
  61873. ** encoding.
  61874. **
  61875. ** If it is not NULL, then pColl must point to the database native encoding
  61876. ** collation sequence with name zName, length nName.
  61877. **
  61878. ** The return value is either the collation sequence to be used in database
  61879. ** db for collation type name zName, length nName, or NULL, if no collation
  61880. ** sequence can be found.
  61881. */
  61882. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  61883. sqlite3* db,
  61884. CollSeq *pColl,
  61885. const char *zName,
  61886. int nName
  61887. ){
  61888. CollSeq *p;
  61889. p = pColl;
  61890. if( !p ){
  61891. p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
  61892. }
  61893. if( !p || !p->xCmp ){
  61894. /* No collation sequence of this type for this encoding is registered.
  61895. ** Call the collation factory to see if it can supply us with one.
  61896. */
  61897. callCollNeeded(db, zName, nName);
  61898. p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
  61899. }
  61900. if( p && !p->xCmp && synthCollSeq(db, p) ){
  61901. p = 0;
  61902. }
  61903. assert( !p || p->xCmp );
  61904. return p;
  61905. }
  61906. /*
  61907. ** This routine is called on a collation sequence before it is used to
  61908. ** check that it is defined. An undefined collation sequence exists when
  61909. ** a database is loaded that contains references to collation sequences
  61910. ** that have not been defined by sqlite3_create_collation() etc.
  61911. **
  61912. ** If required, this routine calls the 'collation needed' callback to
  61913. ** request a definition of the collating sequence. If this doesn't work,
  61914. ** an equivalent collating sequence that uses a text encoding different
  61915. ** from the main database is substituted, if one is available.
  61916. */
  61917. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  61918. if( pColl ){
  61919. const char *zName = pColl->zName;
  61920. CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
  61921. if( !p ){
  61922. if( pParse->nErr==0 ){
  61923. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  61924. }
  61925. pParse->nErr++;
  61926. return SQLITE_ERROR;
  61927. }
  61928. assert( p==pColl );
  61929. }
  61930. return SQLITE_OK;
  61931. }
  61932. /*
  61933. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  61934. ** specified by zName and nName is not found and parameter 'create' is
  61935. ** true, then create a new entry. Otherwise return NULL.
  61936. **
  61937. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  61938. ** array of three CollSeq structures. The first is the collation sequence
  61939. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  61940. **
  61941. ** Stored immediately after the three collation sequences is a copy of
  61942. ** the collation sequence name. A pointer to this string is stored in
  61943. ** each collation sequence structure.
  61944. */
  61945. static CollSeq *findCollSeqEntry(
  61946. sqlite3 *db,
  61947. const char *zName,
  61948. int nName,
  61949. int create
  61950. ){
  61951. CollSeq *pColl;
  61952. if( nName<0 ) nName = sqlite3Strlen(db, zName);
  61953. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  61954. if( 0==pColl && create ){
  61955. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  61956. if( pColl ){
  61957. CollSeq *pDel = 0;
  61958. pColl[0].zName = (char*)&pColl[3];
  61959. pColl[0].enc = SQLITE_UTF8;
  61960. pColl[1].zName = (char*)&pColl[3];
  61961. pColl[1].enc = SQLITE_UTF16LE;
  61962. pColl[2].zName = (char*)&pColl[3];
  61963. pColl[2].enc = SQLITE_UTF16BE;
  61964. memcpy(pColl[0].zName, zName, nName);
  61965. pColl[0].zName[nName] = 0;
  61966. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  61967. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  61968. ** return the pColl pointer to be deleted (because it wasn't added
  61969. ** to the hash table).
  61970. */
  61971. assert( pDel==0 || pDel==pColl );
  61972. if( pDel!=0 ){
  61973. db->mallocFailed = 1;
  61974. sqlite3DbFree(db, pDel);
  61975. pColl = 0;
  61976. }
  61977. }
  61978. }
  61979. return pColl;
  61980. }
  61981. /*
  61982. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  61983. ** Return the CollSeq* pointer for the collation sequence named zName
  61984. ** for the encoding 'enc' from the database 'db'.
  61985. **
  61986. ** If the entry specified is not found and 'create' is true, then create a
  61987. ** new entry. Otherwise return NULL.
  61988. **
  61989. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  61990. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  61991. ** if necessary and generates an error message if the collating sequence
  61992. ** cannot be found.
  61993. */
  61994. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  61995. sqlite3 *db,
  61996. u8 enc,
  61997. const char *zName,
  61998. int nName,
  61999. int create
  62000. ){
  62001. CollSeq *pColl;
  62002. if( zName ){
  62003. pColl = findCollSeqEntry(db, zName, nName, create);
  62004. }else{
  62005. pColl = db->pDfltColl;
  62006. }
  62007. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  62008. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  62009. if( pColl ) pColl += enc-1;
  62010. return pColl;
  62011. }
  62012. /* During the search for the best function definition, this procedure
  62013. ** is called to test how well the function passed as the first argument
  62014. ** matches the request for a function with nArg arguments in a system
  62015. ** that uses encoding enc. The value returned indicates how well the
  62016. ** request is matched. A higher value indicates a better match.
  62017. **
  62018. ** The returned value is always between 0 and 6, as follows:
  62019. **
  62020. ** 0: Not a match, or if nArg<0 and the function is has no implementation.
  62021. ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
  62022. ** encoding is requested, or vice versa.
  62023. ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
  62024. ** requested, or vice versa.
  62025. ** 3: A variable arguments function using the same text encoding.
  62026. ** 4: A function with the exact number of arguments requested that
  62027. ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
  62028. ** 5: A function with the exact number of arguments requested that
  62029. ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
  62030. ** 6: An exact match.
  62031. **
  62032. */
  62033. static int matchQuality(FuncDef *p, int nArg, u8 enc){
  62034. int match = 0;
  62035. if( p->nArg==-1 || p->nArg==nArg
  62036. || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
  62037. ){
  62038. match = 1;
  62039. if( p->nArg==nArg || nArg==-1 ){
  62040. match = 4;
  62041. }
  62042. if( enc==p->iPrefEnc ){
  62043. match += 2;
  62044. }
  62045. else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
  62046. (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
  62047. match += 1;
  62048. }
  62049. }
  62050. return match;
  62051. }
  62052. /*
  62053. ** Search a FuncDefHash for a function with the given name. Return
  62054. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  62055. */
  62056. static FuncDef *functionSearch(
  62057. FuncDefHash *pHash, /* Hash table to search */
  62058. int h, /* Hash of the name */
  62059. const char *zFunc, /* Name of function */
  62060. int nFunc /* Number of bytes in zFunc */
  62061. ){
  62062. FuncDef *p;
  62063. for(p=pHash->a[h]; p; p=p->pHash){
  62064. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  62065. return p;
  62066. }
  62067. }
  62068. return 0;
  62069. }
  62070. /*
  62071. ** Insert a new FuncDef into a FuncDefHash hash table.
  62072. */
  62073. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  62074. FuncDefHash *pHash, /* The hash table into which to insert */
  62075. FuncDef *pDef /* The function definition to insert */
  62076. ){
  62077. FuncDef *pOther;
  62078. int nName = sqlite3Strlen30(pDef->zName);
  62079. u8 c1 = (u8)pDef->zName[0];
  62080. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  62081. pOther = functionSearch(pHash, h, pDef->zName, nName);
  62082. if( pOther ){
  62083. pDef->pNext = pOther->pNext;
  62084. pOther->pNext = pDef;
  62085. }else{
  62086. pDef->pNext = 0;
  62087. pDef->pHash = pHash->a[h];
  62088. pHash->a[h] = pDef;
  62089. }
  62090. }
  62091. /*
  62092. ** Locate a user function given a name, a number of arguments and a flag
  62093. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  62094. ** pointer to the FuncDef structure that defines that function, or return
  62095. ** NULL if the function does not exist.
  62096. **
  62097. ** If the createFlag argument is true, then a new (blank) FuncDef
  62098. ** structure is created and liked into the "db" structure if a
  62099. ** no matching function previously existed. When createFlag is true
  62100. ** and the nArg parameter is -1, then only a function that accepts
  62101. ** any number of arguments will be returned.
  62102. **
  62103. ** If createFlag is false and nArg is -1, then the first valid
  62104. ** function found is returned. A function is valid if either xFunc
  62105. ** or xStep is non-zero.
  62106. **
  62107. ** If createFlag is false, then a function with the required name and
  62108. ** number of arguments may be returned even if the eTextRep flag does not
  62109. ** match that requested.
  62110. */
  62111. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  62112. sqlite3 *db, /* An open database */
  62113. const char *zName, /* Name of the function. Not null-terminated */
  62114. int nName, /* Number of characters in the name */
  62115. int nArg, /* Number of arguments. -1 means any number */
  62116. u8 enc, /* Preferred text encoding */
  62117. int createFlag /* Create new entry if true and does not otherwise exist */
  62118. ){
  62119. FuncDef *p; /* Iterator variable */
  62120. FuncDef *pBest = 0; /* Best match found so far */
  62121. int bestScore = 0; /* Score of best match */
  62122. int h; /* Hash value */
  62123. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  62124. if( nArg<-1 ) nArg = -1;
  62125. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  62126. /* First search for a match amongst the application-defined functions.
  62127. */
  62128. p = functionSearch(&db->aFunc, h, zName, nName);
  62129. while( p ){
  62130. int score = matchQuality(p, nArg, enc);
  62131. if( score>bestScore ){
  62132. pBest = p;
  62133. bestScore = score;
  62134. }
  62135. p = p->pNext;
  62136. }
  62137. /* If no match is found, search the built-in functions.
  62138. **
  62139. ** Except, if createFlag is true, that means that we are trying to
  62140. ** install a new function. Whatever FuncDef structure is returned will
  62141. ** have fields overwritten with new information appropriate for the
  62142. ** new function. But the FuncDefs for built-in functions are read-only.
  62143. ** So we must not search for built-ins when creating a new function.
  62144. */
  62145. if( !createFlag && !pBest ){
  62146. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  62147. p = functionSearch(pHash, h, zName, nName);
  62148. while( p ){
  62149. int score = matchQuality(p, nArg, enc);
  62150. if( score>bestScore ){
  62151. pBest = p;
  62152. bestScore = score;
  62153. }
  62154. p = p->pNext;
  62155. }
  62156. }
  62157. /* If the createFlag parameter is true and the search did not reveal an
  62158. ** exact match for the name, number of arguments and encoding, then add a
  62159. ** new entry to the hash table and return it.
  62160. */
  62161. if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
  62162. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  62163. pBest->zName = (char *)&pBest[1];
  62164. pBest->nArg = (u16)nArg;
  62165. pBest->iPrefEnc = enc;
  62166. memcpy(pBest->zName, zName, nName);
  62167. pBest->zName[nName] = 0;
  62168. sqlite3FuncDefInsert(&db->aFunc, pBest);
  62169. }
  62170. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  62171. return pBest;
  62172. }
  62173. return 0;
  62174. }
  62175. /*
  62176. ** Free all resources held by the schema structure. The void* argument points
  62177. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  62178. ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
  62179. ** of the schema hash tables).
  62180. **
  62181. ** The Schema.cache_size variable is not cleared.
  62182. */
  62183. SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
  62184. Hash temp1;
  62185. Hash temp2;
  62186. HashElem *pElem;
  62187. Schema *pSchema = (Schema *)p;
  62188. temp1 = pSchema->tblHash;
  62189. temp2 = pSchema->trigHash;
  62190. sqlite3HashInit(&pSchema->trigHash, 0);
  62191. sqlite3HashClear(&pSchema->aFKey);
  62192. sqlite3HashClear(&pSchema->idxHash);
  62193. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  62194. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  62195. }
  62196. sqlite3HashClear(&temp2);
  62197. sqlite3HashInit(&pSchema->tblHash, 0);
  62198. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  62199. Table *pTab = sqliteHashData(pElem);
  62200. assert( pTab->dbMem==0 );
  62201. sqlite3DeleteTable(pTab);
  62202. }
  62203. sqlite3HashClear(&temp1);
  62204. pSchema->pSeqTab = 0;
  62205. pSchema->flags &= ~DB_SchemaLoaded;
  62206. }
  62207. /*
  62208. ** Find and return the schema associated with a BTree. Create
  62209. ** a new one if necessary.
  62210. */
  62211. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  62212. Schema * p;
  62213. if( pBt ){
  62214. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
  62215. }else{
  62216. p = (Schema *)sqlite3MallocZero(sizeof(Schema));
  62217. }
  62218. if( !p ){
  62219. db->mallocFailed = 1;
  62220. }else if ( 0==p->file_format ){
  62221. sqlite3HashInit(&p->tblHash, 0);
  62222. sqlite3HashInit(&p->idxHash, 0);
  62223. sqlite3HashInit(&p->trigHash, 0);
  62224. sqlite3HashInit(&p->aFKey, 1);
  62225. p->enc = SQLITE_UTF8;
  62226. }
  62227. return p;
  62228. }
  62229. /************** End of callback.c ********************************************/
  62230. /************** Begin file delete.c ******************************************/
  62231. /*
  62232. ** 2001 September 15
  62233. **
  62234. ** The author disclaims copyright to this source code. In place of
  62235. ** a legal notice, here is a blessing:
  62236. **
  62237. ** May you do good and not evil.
  62238. ** May you find forgiveness for yourself and forgive others.
  62239. ** May you share freely, never taking more than you give.
  62240. **
  62241. *************************************************************************
  62242. ** This file contains C code routines that are called by the parser
  62243. ** in order to generate code for DELETE FROM statements.
  62244. **
  62245. ** $Id: delete.c,v 1.198 2009/03/05 03:48:07 shane Exp $
  62246. */
  62247. /*
  62248. ** Look up every table that is named in pSrc. If any table is not found,
  62249. ** add an error message to pParse->zErrMsg and return NULL. If all tables
  62250. ** are found, return a pointer to the last table.
  62251. */
  62252. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  62253. struct SrcList_item *pItem = pSrc->a;
  62254. Table *pTab;
  62255. assert( pItem && pSrc->nSrc==1 );
  62256. pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  62257. sqlite3DeleteTable(pItem->pTab);
  62258. pItem->pTab = pTab;
  62259. if( pTab ){
  62260. pTab->nRef++;
  62261. }
  62262. if( sqlite3IndexedByLookup(pParse, pItem) ){
  62263. pTab = 0;
  62264. }
  62265. return pTab;
  62266. }
  62267. /*
  62268. ** Check to make sure the given table is writable. If it is not
  62269. ** writable, generate an error message and return 1. If it is
  62270. ** writable return 0;
  62271. */
  62272. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  62273. if( ((pTab->tabFlags & TF_Readonly)!=0
  62274. && (pParse->db->flags & SQLITE_WriteSchema)==0
  62275. && pParse->nested==0)
  62276. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62277. || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
  62278. #endif
  62279. ){
  62280. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  62281. return 1;
  62282. }
  62283. #ifndef SQLITE_OMIT_VIEW
  62284. if( !viewOk && pTab->pSelect ){
  62285. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  62286. return 1;
  62287. }
  62288. #endif
  62289. return 0;
  62290. }
  62291. /*
  62292. ** Generate code that will open a table for reading.
  62293. */
  62294. SQLITE_PRIVATE void sqlite3OpenTable(
  62295. Parse *p, /* Generate code into this VDBE */
  62296. int iCur, /* The cursor number of the table */
  62297. int iDb, /* The database index in sqlite3.aDb[] */
  62298. Table *pTab, /* The table to be opened */
  62299. int opcode /* OP_OpenRead or OP_OpenWrite */
  62300. ){
  62301. Vdbe *v;
  62302. if( IsVirtual(pTab) ) return;
  62303. v = sqlite3GetVdbe(p);
  62304. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  62305. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  62306. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  62307. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  62308. VdbeComment((v, "%s", pTab->zName));
  62309. }
  62310. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  62311. /*
  62312. ** Evaluate a view and store its result in an ephemeral table. The
  62313. ** pWhere argument is an optional WHERE clause that restricts the
  62314. ** set of rows in the view that are to be added to the ephemeral table.
  62315. */
  62316. SQLITE_PRIVATE void sqlite3MaterializeView(
  62317. Parse *pParse, /* Parsing context */
  62318. Table *pView, /* View definition */
  62319. Expr *pWhere, /* Optional WHERE clause to be added */
  62320. int iCur /* Cursor number for ephemerial table */
  62321. ){
  62322. SelectDest dest;
  62323. Select *pDup;
  62324. sqlite3 *db = pParse->db;
  62325. pDup = sqlite3SelectDup(db, pView->pSelect, 0);
  62326. if( pWhere ){
  62327. SrcList *pFrom;
  62328. Token viewName;
  62329. pWhere = sqlite3ExprDup(db, pWhere, 0);
  62330. viewName.z = (u8*)pView->zName;
  62331. viewName.n = (unsigned int)sqlite3Strlen30((const char*)viewName.z);
  62332. pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
  62333. pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  62334. }
  62335. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  62336. sqlite3Select(pParse, pDup, &dest);
  62337. sqlite3SelectDelete(db, pDup);
  62338. }
  62339. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  62340. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  62341. /*
  62342. ** Generate an expression tree to implement the WHERE, ORDER BY,
  62343. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  62344. **
  62345. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  62346. ** \__________________________/
  62347. ** pLimitWhere (pInClause)
  62348. */
  62349. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  62350. Parse *pParse, /* The parser context */
  62351. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  62352. Expr *pWhere, /* The WHERE clause. May be null */
  62353. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  62354. Expr *pLimit, /* The LIMIT clause. May be null */
  62355. Expr *pOffset, /* The OFFSET clause. May be null */
  62356. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  62357. ){
  62358. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  62359. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  62360. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  62361. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  62362. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  62363. Select *pSelect = NULL; /* Complete SELECT tree */
  62364. /* Check that there isn't an ORDER BY without a LIMIT clause.
  62365. */
  62366. if( pOrderBy && (pLimit == 0) ) {
  62367. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  62368. pParse->parseError = 1;
  62369. goto limit_where_cleanup_2;
  62370. }
  62371. /* We only need to generate a select expression if there
  62372. ** is a limit/offset term to enforce.
  62373. */
  62374. if( pLimit == 0 ) {
  62375. /* if pLimit is null, pOffset will always be null as well. */
  62376. assert( pOffset == 0 );
  62377. return pWhere;
  62378. }
  62379. /* Generate a select expression tree to enforce the limit/offset
  62380. ** term for the DELETE or UPDATE statement. For example:
  62381. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  62382. ** becomes:
  62383. ** DELETE FROM table_a WHERE rowid IN (
  62384. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  62385. ** );
  62386. */
  62387. pSelectRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
  62388. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  62389. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid, 0);
  62390. if( pEList == 0 ) goto limit_where_cleanup_2;
  62391. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  62392. ** and the SELECT subtree. */
  62393. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  62394. if( pSelectSrc == 0 ) {
  62395. sqlite3ExprListDelete(pParse->db, pEList);
  62396. goto limit_where_cleanup_2;
  62397. }
  62398. /* generate the SELECT expression tree. */
  62399. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  62400. pOrderBy,0,pLimit,pOffset);
  62401. if( pSelect == 0 ) return 0;
  62402. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  62403. pWhereRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
  62404. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  62405. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  62406. if( pInClause == 0 ) goto limit_where_cleanup_1;
  62407. pInClause->x.pSelect = pSelect;
  62408. pInClause->flags |= EP_xIsSelect;
  62409. sqlite3ExprSetHeight(pParse, pInClause);
  62410. return pInClause;
  62411. /* something went wrong. clean up anything allocated. */
  62412. limit_where_cleanup_1:
  62413. sqlite3SelectDelete(pParse->db, pSelect);
  62414. return 0;
  62415. limit_where_cleanup_2:
  62416. sqlite3ExprDelete(pParse->db, pWhere);
  62417. sqlite3ExprListDelete(pParse->db, pOrderBy);
  62418. sqlite3ExprDelete(pParse->db, pLimit);
  62419. sqlite3ExprDelete(pParse->db, pOffset);
  62420. return 0;
  62421. }
  62422. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  62423. /*
  62424. ** Generate code for a DELETE FROM statement.
  62425. **
  62426. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  62427. ** \________/ \________________/
  62428. ** pTabList pWhere
  62429. */
  62430. SQLITE_PRIVATE void sqlite3DeleteFrom(
  62431. Parse *pParse, /* The parser context */
  62432. SrcList *pTabList, /* The table from which we should delete things */
  62433. Expr *pWhere /* The WHERE clause. May be null */
  62434. ){
  62435. Vdbe *v; /* The virtual database engine */
  62436. Table *pTab; /* The table from which records will be deleted */
  62437. const char *zDb; /* Name of database holding pTab */
  62438. int end, addr = 0; /* A couple addresses of generated code */
  62439. int i; /* Loop counter */
  62440. WhereInfo *pWInfo; /* Information about the WHERE clause */
  62441. Index *pIdx; /* For looping over indices of the table */
  62442. int iCur; /* VDBE Cursor number for pTab */
  62443. sqlite3 *db; /* Main database structure */
  62444. AuthContext sContext; /* Authorization context */
  62445. int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
  62446. NameContext sNC; /* Name context to resolve expressions in */
  62447. int iDb; /* Database number */
  62448. int memCnt = -1; /* Memory cell used for change counting */
  62449. int rcauth; /* Value returned by authorization callback */
  62450. #ifndef SQLITE_OMIT_TRIGGER
  62451. int isView; /* True if attempting to delete from a view */
  62452. Trigger *pTrigger; /* List of table triggers, if required */
  62453. #endif
  62454. int iBeginAfterTrigger = 0; /* Address of after trigger program */
  62455. int iEndAfterTrigger = 0; /* Exit of after trigger program */
  62456. int iBeginBeforeTrigger = 0; /* Address of before trigger program */
  62457. int iEndBeforeTrigger = 0; /* Exit of before trigger program */
  62458. u32 old_col_mask = 0; /* Mask of OLD.* columns in use */
  62459. sContext.pParse = 0;
  62460. db = pParse->db;
  62461. if( pParse->nErr || db->mallocFailed ){
  62462. goto delete_from_cleanup;
  62463. }
  62464. assert( pTabList->nSrc==1 );
  62465. /* Locate the table which we want to delete. This table has to be
  62466. ** put in an SrcList structure because some of the subroutines we
  62467. ** will be calling are designed to work with multiple tables and expect
  62468. ** an SrcList* parameter instead of just a Table* parameter.
  62469. */
  62470. pTab = sqlite3SrcListLookup(pParse, pTabList);
  62471. if( pTab==0 ) goto delete_from_cleanup;
  62472. /* Figure out if we have any triggers and if the table being
  62473. ** deleted from is a view
  62474. */
  62475. #ifndef SQLITE_OMIT_TRIGGER
  62476. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  62477. isView = pTab->pSelect!=0;
  62478. #else
  62479. # define pTrigger 0
  62480. # define isView 0
  62481. #endif
  62482. #ifdef SQLITE_OMIT_VIEW
  62483. # undef isView
  62484. # define isView 0
  62485. #endif
  62486. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  62487. goto delete_from_cleanup;
  62488. }
  62489. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  62490. assert( iDb<db->nDb );
  62491. zDb = db->aDb[iDb].zName;
  62492. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  62493. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  62494. if( rcauth==SQLITE_DENY ){
  62495. goto delete_from_cleanup;
  62496. }
  62497. assert(!isView || pTrigger);
  62498. /* If pTab is really a view, make sure it has been initialized.
  62499. */
  62500. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  62501. goto delete_from_cleanup;
  62502. }
  62503. /* Allocate a cursor used to store the old.* data for a trigger.
  62504. */
  62505. if( pTrigger ){
  62506. oldIdx = pParse->nTab++;
  62507. }
  62508. /* Assign cursor number to the table and all its indices.
  62509. */
  62510. assert( pTabList->nSrc==1 );
  62511. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  62512. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  62513. pParse->nTab++;
  62514. }
  62515. /* Start the view context
  62516. */
  62517. if( isView ){
  62518. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  62519. }
  62520. /* Begin generating code.
  62521. */
  62522. v = sqlite3GetVdbe(pParse);
  62523. if( v==0 ){
  62524. goto delete_from_cleanup;
  62525. }
  62526. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  62527. sqlite3BeginWriteOperation(pParse, (pTrigger?1:0), iDb);
  62528. if( pTrigger ){
  62529. int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
  62530. int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  62531. addr = sqlite3VdbeMakeLabel(v);
  62532. iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
  62533. (void)sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0,
  62534. TRIGGER_BEFORE, pTab, -1, oldIdx, orconf, addr, &old_col_mask, 0);
  62535. iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
  62536. iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
  62537. (void)sqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0,
  62538. TRIGGER_AFTER, pTab, -1, oldIdx, orconf, addr, &old_col_mask, 0);
  62539. iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
  62540. sqlite3VdbeJumpHere(v, iGoto);
  62541. }
  62542. /* If we are trying to delete from a view, realize that view into
  62543. ** a ephemeral table.
  62544. */
  62545. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  62546. if( isView ){
  62547. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  62548. }
  62549. #endif
  62550. /* Resolve the column names in the WHERE clause.
  62551. */
  62552. memset(&sNC, 0, sizeof(sNC));
  62553. sNC.pParse = pParse;
  62554. sNC.pSrcList = pTabList;
  62555. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  62556. goto delete_from_cleanup;
  62557. }
  62558. /* Initialize the counter of the number of rows deleted, if
  62559. ** we are counting rows.
  62560. */
  62561. if( db->flags & SQLITE_CountRows ){
  62562. memCnt = ++pParse->nMem;
  62563. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  62564. }
  62565. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  62566. /* Special case: A DELETE without a WHERE clause deletes everything.
  62567. ** It is easier just to erase the whole table. Note, however, that
  62568. ** this means that the row change count will be incorrect.
  62569. */
  62570. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) ){
  62571. assert( !isView );
  62572. sqlite3VdbeAddOp3(v, OP_Clear, pTab->tnum, iDb, memCnt);
  62573. if( !pParse->nested ){
  62574. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  62575. }
  62576. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  62577. assert( pIdx->pSchema==pTab->pSchema );
  62578. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  62579. }
  62580. }else
  62581. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  62582. /* The usual case: There is a WHERE clause so we have to scan through
  62583. ** the table and pick which records to delete.
  62584. */
  62585. {
  62586. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  62587. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  62588. /* Collect rowids of every row to be deleted.
  62589. */
  62590. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  62591. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
  62592. WHERE_FILL_ROWSET, iRowSet);
  62593. if( pWInfo==0 ) goto delete_from_cleanup;
  62594. if( db->flags & SQLITE_CountRows ){
  62595. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  62596. }
  62597. sqlite3WhereEnd(pWInfo);
  62598. /* Open the pseudo-table used to store OLD if there are triggers.
  62599. */
  62600. if( pTrigger ){
  62601. sqlite3VdbeAddOp3(v, OP_OpenPseudo, oldIdx, 0, pTab->nCol);
  62602. }
  62603. /* Delete every item whose key was written to the list during the
  62604. ** database scan. We have to delete items after the scan is complete
  62605. ** because deleting an item can change the scan order.
  62606. */
  62607. end = sqlite3VdbeMakeLabel(v);
  62608. if( !isView ){
  62609. /* Open cursors for the table we are deleting from and
  62610. ** all its indices.
  62611. */
  62612. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  62613. }
  62614. /* This is the beginning of the delete loop. If a trigger encounters
  62615. ** an IGNORE constraint, it jumps back to here.
  62616. */
  62617. if( pTrigger ){
  62618. sqlite3VdbeResolveLabel(v, addr);
  62619. }
  62620. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  62621. if( pTrigger ){
  62622. int iData = ++pParse->nMem; /* For storing row data of OLD table */
  62623. /* If the record is no longer present in the table, jump to the
  62624. ** next iteration of the loop through the contents of the fifo.
  62625. */
  62626. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
  62627. /* Populate the OLD.* pseudo-table */
  62628. if( old_col_mask ){
  62629. sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
  62630. }else{
  62631. sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
  62632. }
  62633. sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
  62634. /* Jump back and run the BEFORE triggers */
  62635. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
  62636. sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
  62637. }
  62638. if( !isView ){
  62639. /* Delete the row */
  62640. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62641. if( IsVirtual(pTab) ){
  62642. const char *pVtab = (const char *)pTab->pVtab;
  62643. sqlite3VtabMakeWritable(pParse, pTab);
  62644. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
  62645. }else
  62646. #endif
  62647. {
  62648. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
  62649. }
  62650. }
  62651. /* If there are row triggers, close all cursors then invoke
  62652. ** the AFTER triggers
  62653. */
  62654. if( pTrigger ){
  62655. /* Jump back and run the AFTER triggers */
  62656. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
  62657. sqlite3VdbeJumpHere(v, iEndAfterTrigger);
  62658. }
  62659. /* End of the delete loop */
  62660. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  62661. sqlite3VdbeResolveLabel(v, end);
  62662. /* Close the cursors after the loop if there are no row triggers */
  62663. if( !isView && !IsVirtual(pTab) ){
  62664. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  62665. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  62666. }
  62667. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  62668. }
  62669. }
  62670. /*
  62671. ** Return the number of rows that were deleted. If this routine is
  62672. ** generating code because of a call to sqlite3NestedParse(), do not
  62673. ** invoke the callback function.
  62674. */
  62675. if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
  62676. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  62677. sqlite3VdbeSetNumCols(v, 1);
  62678. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  62679. }
  62680. delete_from_cleanup:
  62681. sqlite3AuthContextPop(&sContext);
  62682. sqlite3SrcListDelete(db, pTabList);
  62683. sqlite3ExprDelete(db, pWhere);
  62684. return;
  62685. }
  62686. /*
  62687. ** This routine generates VDBE code that causes a single row of a
  62688. ** single table to be deleted.
  62689. **
  62690. ** The VDBE must be in a particular state when this routine is called.
  62691. ** These are the requirements:
  62692. **
  62693. ** 1. A read/write cursor pointing to pTab, the table containing the row
  62694. ** to be deleted, must be opened as cursor number "base".
  62695. **
  62696. ** 2. Read/write cursors for all indices of pTab must be open as
  62697. ** cursor number base+i for the i-th index.
  62698. **
  62699. ** 3. The record number of the row to be deleted must be stored in
  62700. ** memory cell iRowid.
  62701. **
  62702. ** This routine pops the top of the stack to remove the record number
  62703. ** and then generates code to remove both the table record and all index
  62704. ** entries that point to that record.
  62705. */
  62706. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  62707. Parse *pParse, /* Parsing context */
  62708. Table *pTab, /* Table containing the row to be deleted */
  62709. int iCur, /* Cursor number for the table */
  62710. int iRowid, /* Memory cell that contains the rowid to delete */
  62711. int count /* Increment the row change counter */
  62712. ){
  62713. int addr;
  62714. Vdbe *v;
  62715. v = pParse->pVdbe;
  62716. addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
  62717. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  62718. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  62719. if( count ){
  62720. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  62721. }
  62722. sqlite3VdbeJumpHere(v, addr);
  62723. }
  62724. /*
  62725. ** This routine generates VDBE code that causes the deletion of all
  62726. ** index entries associated with a single row of a single table.
  62727. **
  62728. ** The VDBE must be in a particular state when this routine is called.
  62729. ** These are the requirements:
  62730. **
  62731. ** 1. A read/write cursor pointing to pTab, the table containing the row
  62732. ** to be deleted, must be opened as cursor number "iCur".
  62733. **
  62734. ** 2. Read/write cursors for all indices of pTab must be open as
  62735. ** cursor number iCur+i for the i-th index.
  62736. **
  62737. ** 3. The "iCur" cursor must be pointing to the row that is to be
  62738. ** deleted.
  62739. */
  62740. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  62741. Parse *pParse, /* Parsing and code generating context */
  62742. Table *pTab, /* Table containing the row to be deleted */
  62743. int iCur, /* Cursor number for the table */
  62744. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  62745. ){
  62746. int i;
  62747. Index *pIdx;
  62748. int r1;
  62749. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  62750. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  62751. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
  62752. sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
  62753. }
  62754. }
  62755. /*
  62756. ** Generate code that will assemble an index key and put it in register
  62757. ** regOut. The key with be for index pIdx which is an index on pTab.
  62758. ** iCur is the index of a cursor open on the pTab table and pointing to
  62759. ** the entry that needs indexing.
  62760. **
  62761. ** Return a register number which is the first in a block of
  62762. ** registers that holds the elements of the index key. The
  62763. ** block of registers has already been deallocated by the time
  62764. ** this routine returns.
  62765. */
  62766. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  62767. Parse *pParse, /* Parsing context */
  62768. Index *pIdx, /* The index for which to generate a key */
  62769. int iCur, /* Cursor number for the pIdx->pTable table */
  62770. int regOut, /* Write the new index key to this register */
  62771. int doMakeRec /* Run the OP_MakeRecord instruction if true */
  62772. ){
  62773. Vdbe *v = pParse->pVdbe;
  62774. int j;
  62775. Table *pTab = pIdx->pTable;
  62776. int regBase;
  62777. int nCol;
  62778. nCol = pIdx->nColumn;
  62779. regBase = sqlite3GetTempRange(pParse, nCol+1);
  62780. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  62781. for(j=0; j<nCol; j++){
  62782. int idx = pIdx->aiColumn[j];
  62783. if( idx==pTab->iPKey ){
  62784. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  62785. }else{
  62786. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  62787. sqlite3ColumnDefault(v, pTab, idx);
  62788. }
  62789. }
  62790. if( doMakeRec ){
  62791. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  62792. sqlite3IndexAffinityStr(v, pIdx);
  62793. sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
  62794. }
  62795. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  62796. return regBase;
  62797. }
  62798. /* Make sure "isView" gets undefined in case this file becomes part of
  62799. ** the amalgamation - so that subsequent files do not see isView as a
  62800. ** macro. */
  62801. #undef isView
  62802. /************** End of delete.c **********************************************/
  62803. /************** Begin file func.c ********************************************/
  62804. /*
  62805. ** 2002 February 23
  62806. **
  62807. ** The author disclaims copyright to this source code. In place of
  62808. ** a legal notice, here is a blessing:
  62809. **
  62810. ** May you do good and not evil.
  62811. ** May you find forgiveness for yourself and forgive others.
  62812. ** May you share freely, never taking more than you give.
  62813. **
  62814. *************************************************************************
  62815. ** This file contains the C functions that implement various SQL
  62816. ** functions of SQLite.
  62817. **
  62818. ** There is only one exported symbol in this file - the function
  62819. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  62820. ** All other code has file scope.
  62821. **
  62822. ** $Id: func.c,v 1.231 2009/04/08 23:04:14 drh Exp $
  62823. */
  62824. /*
  62825. ** Return the collating function associated with a function.
  62826. */
  62827. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  62828. return context->pColl;
  62829. }
  62830. /*
  62831. ** Implementation of the non-aggregate min() and max() functions
  62832. */
  62833. static void minmaxFunc(
  62834. sqlite3_context *context,
  62835. int argc,
  62836. sqlite3_value **argv
  62837. ){
  62838. int i;
  62839. int mask; /* 0 for min() or 0xffffffff for max() */
  62840. int iBest;
  62841. CollSeq *pColl;
  62842. assert( argc>1 );
  62843. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  62844. pColl = sqlite3GetFuncCollSeq(context);
  62845. assert( pColl );
  62846. assert( mask==-1 || mask==0 );
  62847. iBest = 0;
  62848. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  62849. for(i=1; i<argc; i++){
  62850. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  62851. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  62852. testcase( mask==0 );
  62853. iBest = i;
  62854. }
  62855. }
  62856. sqlite3_result_value(context, argv[iBest]);
  62857. }
  62858. /*
  62859. ** Return the type of the argument.
  62860. */
  62861. static void typeofFunc(
  62862. sqlite3_context *context,
  62863. int NotUsed,
  62864. sqlite3_value **argv
  62865. ){
  62866. const char *z = 0;
  62867. UNUSED_PARAMETER(NotUsed);
  62868. switch( sqlite3_value_type(argv[0]) ){
  62869. case SQLITE_INTEGER: z = "integer"; break;
  62870. case SQLITE_TEXT: z = "text"; break;
  62871. case SQLITE_FLOAT: z = "numeric"; break;
  62872. case SQLITE_BLOB: z = "blob"; break;
  62873. default: z = "null"; break;
  62874. }
  62875. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  62876. }
  62877. /*
  62878. ** Implementation of the length() function
  62879. */
  62880. static void lengthFunc(
  62881. sqlite3_context *context,
  62882. int argc,
  62883. sqlite3_value **argv
  62884. ){
  62885. int len;
  62886. assert( argc==1 );
  62887. UNUSED_PARAMETER(argc);
  62888. switch( sqlite3_value_type(argv[0]) ){
  62889. case SQLITE_BLOB:
  62890. case SQLITE_INTEGER:
  62891. case SQLITE_FLOAT: {
  62892. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  62893. break;
  62894. }
  62895. case SQLITE_TEXT: {
  62896. const unsigned char *z = sqlite3_value_text(argv[0]);
  62897. if( z==0 ) return;
  62898. len = 0;
  62899. while( *z ){
  62900. len++;
  62901. SQLITE_SKIP_UTF8(z);
  62902. }
  62903. sqlite3_result_int(context, len);
  62904. break;
  62905. }
  62906. default: {
  62907. sqlite3_result_null(context);
  62908. break;
  62909. }
  62910. }
  62911. }
  62912. /*
  62913. ** Implementation of the abs() function
  62914. */
  62915. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  62916. assert( argc==1 );
  62917. UNUSED_PARAMETER(argc);
  62918. switch( sqlite3_value_type(argv[0]) ){
  62919. case SQLITE_INTEGER: {
  62920. i64 iVal = sqlite3_value_int64(argv[0]);
  62921. if( iVal<0 ){
  62922. if( (iVal<<1)==0 ){
  62923. sqlite3_result_error(context, "integer overflow", -1);
  62924. return;
  62925. }
  62926. iVal = -iVal;
  62927. }
  62928. sqlite3_result_int64(context, iVal);
  62929. break;
  62930. }
  62931. case SQLITE_NULL: {
  62932. sqlite3_result_null(context);
  62933. break;
  62934. }
  62935. default: {
  62936. double rVal = sqlite3_value_double(argv[0]);
  62937. if( rVal<0 ) rVal = -rVal;
  62938. sqlite3_result_double(context, rVal);
  62939. break;
  62940. }
  62941. }
  62942. }
  62943. /*
  62944. ** Implementation of the substr() function.
  62945. **
  62946. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  62947. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  62948. ** of x. If x is text, then we actually count UTF-8 characters.
  62949. ** If x is a blob, then we count bytes.
  62950. **
  62951. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  62952. */
  62953. static void substrFunc(
  62954. sqlite3_context *context,
  62955. int argc,
  62956. sqlite3_value **argv
  62957. ){
  62958. const unsigned char *z;
  62959. const unsigned char *z2;
  62960. int len;
  62961. int p0type;
  62962. i64 p1, p2;
  62963. int negP2 = 0;
  62964. assert( argc==3 || argc==2 );
  62965. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  62966. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  62967. ){
  62968. return;
  62969. }
  62970. p0type = sqlite3_value_type(argv[0]);
  62971. if( p0type==SQLITE_BLOB ){
  62972. len = sqlite3_value_bytes(argv[0]);
  62973. z = sqlite3_value_blob(argv[0]);
  62974. if( z==0 ) return;
  62975. assert( len==sqlite3_value_bytes(argv[0]) );
  62976. }else{
  62977. z = sqlite3_value_text(argv[0]);
  62978. if( z==0 ) return;
  62979. len = 0;
  62980. for(z2=z; *z2; len++){
  62981. SQLITE_SKIP_UTF8(z2);
  62982. }
  62983. }
  62984. p1 = sqlite3_value_int(argv[1]);
  62985. if( argc==3 ){
  62986. p2 = sqlite3_value_int(argv[2]);
  62987. if( p2<0 ){
  62988. p2 = -p2;
  62989. negP2 = 1;
  62990. }
  62991. }else{
  62992. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  62993. }
  62994. if( p1<0 ){
  62995. p1 += len;
  62996. if( p1<0 ){
  62997. p2 += p1;
  62998. if( p2<0 ) p2 = 0;
  62999. p1 = 0;
  63000. }
  63001. }else if( p1>0 ){
  63002. p1--;
  63003. }else if( p2>0 ){
  63004. p2--;
  63005. }
  63006. if( negP2 ){
  63007. p1 -= p2;
  63008. if( p1<0 ){
  63009. p2 += p1;
  63010. p1 = 0;
  63011. }
  63012. }
  63013. assert( p1>=0 && p2>=0 );
  63014. if( p1+p2>len ){
  63015. p2 = len-p1;
  63016. if( p2<0 ) p2 = 0;
  63017. }
  63018. if( p0type!=SQLITE_BLOB ){
  63019. while( *z && p1 ){
  63020. SQLITE_SKIP_UTF8(z);
  63021. p1--;
  63022. }
  63023. for(z2=z; *z2 && p2; p2--){
  63024. SQLITE_SKIP_UTF8(z2);
  63025. }
  63026. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  63027. }else{
  63028. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  63029. }
  63030. }
  63031. /*
  63032. ** Implementation of the round() function
  63033. */
  63034. #ifndef SQLITE_OMIT_FLOATING_POINT
  63035. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  63036. int n = 0;
  63037. double r;
  63038. char zBuf[500]; /* larger than the %f representation of the largest double */
  63039. assert( argc==1 || argc==2 );
  63040. if( argc==2 ){
  63041. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  63042. n = sqlite3_value_int(argv[1]);
  63043. if( n>30 ) n = 30;
  63044. if( n<0 ) n = 0;
  63045. }
  63046. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  63047. r = sqlite3_value_double(argv[0]);
  63048. sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
  63049. sqlite3AtoF(zBuf, &r);
  63050. sqlite3_result_double(context, r);
  63051. }
  63052. #endif
  63053. /*
  63054. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  63055. ** allocation fails, call sqlite3_result_error_nomem() to notify
  63056. ** the database handle that malloc() has failed and return NULL.
  63057. ** If nByte is larger than the maximum string or blob length, then
  63058. ** raise an SQLITE_TOOBIG exception and return NULL.
  63059. */
  63060. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  63061. char *z;
  63062. sqlite3 *db = sqlite3_context_db_handle(context);
  63063. assert( nByte>0 );
  63064. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  63065. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  63066. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63067. sqlite3_result_error_toobig(context);
  63068. z = 0;
  63069. }else{
  63070. z = sqlite3Malloc((int)nByte);
  63071. if( !z ){
  63072. sqlite3_result_error_nomem(context);
  63073. }
  63074. }
  63075. return z;
  63076. }
  63077. /*
  63078. ** Implementation of the upper() and lower() SQL functions.
  63079. */
  63080. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  63081. char *z1;
  63082. const char *z2;
  63083. int i, n;
  63084. UNUSED_PARAMETER(argc);
  63085. z2 = (char*)sqlite3_value_text(argv[0]);
  63086. n = sqlite3_value_bytes(argv[0]);
  63087. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  63088. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  63089. if( z2 ){
  63090. z1 = contextMalloc(context, ((i64)n)+1);
  63091. if( z1 ){
  63092. memcpy(z1, z2, n+1);
  63093. for(i=0; z1[i]; i++){
  63094. z1[i] = (char)sqlite3Toupper(z1[i]);
  63095. }
  63096. sqlite3_result_text(context, z1, -1, sqlite3_free);
  63097. }
  63098. }
  63099. }
  63100. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  63101. u8 *z1;
  63102. const char *z2;
  63103. int i, n;
  63104. UNUSED_PARAMETER(argc);
  63105. z2 = (char*)sqlite3_value_text(argv[0]);
  63106. n = sqlite3_value_bytes(argv[0]);
  63107. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  63108. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  63109. if( z2 ){
  63110. z1 = contextMalloc(context, ((i64)n)+1);
  63111. if( z1 ){
  63112. memcpy(z1, z2, n+1);
  63113. for(i=0; z1[i]; i++){
  63114. z1[i] = sqlite3Tolower(z1[i]);
  63115. }
  63116. sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
  63117. }
  63118. }
  63119. }
  63120. /*
  63121. ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
  63122. ** All three do the same thing. They return the first non-NULL
  63123. ** argument.
  63124. */
  63125. static void ifnullFunc(
  63126. sqlite3_context *context,
  63127. int argc,
  63128. sqlite3_value **argv
  63129. ){
  63130. int i;
  63131. for(i=0; i<argc; i++){
  63132. if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
  63133. sqlite3_result_value(context, argv[i]);
  63134. break;
  63135. }
  63136. }
  63137. }
  63138. /*
  63139. ** Implementation of random(). Return a random integer.
  63140. */
  63141. static void randomFunc(
  63142. sqlite3_context *context,
  63143. int NotUsed,
  63144. sqlite3_value **NotUsed2
  63145. ){
  63146. sqlite_int64 r;
  63147. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63148. sqlite3_randomness(sizeof(r), &r);
  63149. if( r<0 ){
  63150. /* We need to prevent a random number of 0x8000000000000000
  63151. ** (or -9223372036854775808) since when you do abs() of that
  63152. ** number of you get the same value back again. To do this
  63153. ** in a way that is testable, mask the sign bit off of negative
  63154. ** values, resulting in a positive value. Then take the
  63155. ** 2s complement of that positive value. The end result can
  63156. ** therefore be no less than -9223372036854775807.
  63157. */
  63158. r = -(r ^ (((sqlite3_int64)1)<<63));
  63159. }
  63160. sqlite3_result_int64(context, r);
  63161. }
  63162. /*
  63163. ** Implementation of randomblob(N). Return a random blob
  63164. ** that is N bytes long.
  63165. */
  63166. static void randomBlob(
  63167. sqlite3_context *context,
  63168. int argc,
  63169. sqlite3_value **argv
  63170. ){
  63171. int n;
  63172. unsigned char *p;
  63173. assert( argc==1 );
  63174. UNUSED_PARAMETER(argc);
  63175. n = sqlite3_value_int(argv[0]);
  63176. if( n<1 ){
  63177. n = 1;
  63178. }
  63179. p = contextMalloc(context, n);
  63180. if( p ){
  63181. sqlite3_randomness(n, p);
  63182. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  63183. }
  63184. }
  63185. /*
  63186. ** Implementation of the last_insert_rowid() SQL function. The return
  63187. ** value is the same as the sqlite3_last_insert_rowid() API function.
  63188. */
  63189. static void last_insert_rowid(
  63190. sqlite3_context *context,
  63191. int NotUsed,
  63192. sqlite3_value **NotUsed2
  63193. ){
  63194. sqlite3 *db = sqlite3_context_db_handle(context);
  63195. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63196. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  63197. }
  63198. /*
  63199. ** Implementation of the changes() SQL function. The return value is the
  63200. ** same as the sqlite3_changes() API function.
  63201. */
  63202. static void changes(
  63203. sqlite3_context *context,
  63204. int NotUsed,
  63205. sqlite3_value **NotUsed2
  63206. ){
  63207. sqlite3 *db = sqlite3_context_db_handle(context);
  63208. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63209. sqlite3_result_int(context, sqlite3_changes(db));
  63210. }
  63211. /*
  63212. ** Implementation of the total_changes() SQL function. The return value is
  63213. ** the same as the sqlite3_total_changes() API function.
  63214. */
  63215. static void total_changes(
  63216. sqlite3_context *context,
  63217. int NotUsed,
  63218. sqlite3_value **NotUsed2
  63219. ){
  63220. sqlite3 *db = sqlite3_context_db_handle(context);
  63221. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63222. sqlite3_result_int(context, sqlite3_total_changes(db));
  63223. }
  63224. /*
  63225. ** A structure defining how to do GLOB-style comparisons.
  63226. */
  63227. struct compareInfo {
  63228. u8 matchAll;
  63229. u8 matchOne;
  63230. u8 matchSet;
  63231. u8 noCase;
  63232. };
  63233. /*
  63234. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  63235. ** character is exactly one byte in size. Also, all characters are
  63236. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  63237. ** whereas only characters less than 0x80 do in ASCII.
  63238. */
  63239. #if defined(SQLITE_EBCDIC)
  63240. # define sqlite3Utf8Read(A,C) (*(A++))
  63241. # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
  63242. #else
  63243. # define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
  63244. #endif
  63245. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  63246. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  63247. ** case. Thus 'a' LIKE 'A' would be true. */
  63248. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  63249. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  63250. ** is case sensitive causing 'a' LIKE 'A' to be false */
  63251. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  63252. /*
  63253. ** Compare two UTF-8 strings for equality where the first string can
  63254. ** potentially be a "glob" expression. Return true (1) if they
  63255. ** are the same and false (0) if they are different.
  63256. **
  63257. ** Globbing rules:
  63258. **
  63259. ** '*' Matches any sequence of zero or more characters.
  63260. **
  63261. ** '?' Matches exactly one character.
  63262. **
  63263. ** [...] Matches one character from the enclosed list of
  63264. ** characters.
  63265. **
  63266. ** [^...] Matches one character not in the enclosed list.
  63267. **
  63268. ** With the [...] and [^...] matching, a ']' character can be included
  63269. ** in the list by making it the first character after '[' or '^'. A
  63270. ** range of characters can be specified using '-'. Example:
  63271. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  63272. ** it the last character in the list.
  63273. **
  63274. ** This routine is usually quick, but can be N**2 in the worst case.
  63275. **
  63276. ** Hints: to match '*' or '?', put them in "[]". Like this:
  63277. **
  63278. ** abc[*]xyz Matches "abc*xyz" only
  63279. */
  63280. static int patternCompare(
  63281. const u8 *zPattern, /* The glob pattern */
  63282. const u8 *zString, /* The string to compare against the glob */
  63283. const struct compareInfo *pInfo, /* Information about how to do the compare */
  63284. const int esc /* The escape character */
  63285. ){
  63286. int c, c2;
  63287. int invert;
  63288. int seen;
  63289. u8 matchOne = pInfo->matchOne;
  63290. u8 matchAll = pInfo->matchAll;
  63291. u8 matchSet = pInfo->matchSet;
  63292. u8 noCase = pInfo->noCase;
  63293. int prevEscape = 0; /* True if the previous character was 'escape' */
  63294. while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
  63295. if( !prevEscape && c==matchAll ){
  63296. while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
  63297. || c == matchOne ){
  63298. if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
  63299. return 0;
  63300. }
  63301. }
  63302. if( c==0 ){
  63303. return 1;
  63304. }else if( c==esc ){
  63305. c = sqlite3Utf8Read(zPattern, &zPattern);
  63306. if( c==0 ){
  63307. return 0;
  63308. }
  63309. }else if( c==matchSet ){
  63310. assert( esc==0 ); /* This is GLOB, not LIKE */
  63311. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  63312. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  63313. SQLITE_SKIP_UTF8(zString);
  63314. }
  63315. return *zString!=0;
  63316. }
  63317. while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
  63318. if( noCase ){
  63319. GlogUpperToLower(c2);
  63320. GlogUpperToLower(c);
  63321. while( c2 != 0 && c2 != c ){
  63322. c2 = sqlite3Utf8Read(zString, &zString);
  63323. GlogUpperToLower(c2);
  63324. }
  63325. }else{
  63326. while( c2 != 0 && c2 != c ){
  63327. c2 = sqlite3Utf8Read(zString, &zString);
  63328. }
  63329. }
  63330. if( c2==0 ) return 0;
  63331. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  63332. }
  63333. return 0;
  63334. }else if( !prevEscape && c==matchOne ){
  63335. if( sqlite3Utf8Read(zString, &zString)==0 ){
  63336. return 0;
  63337. }
  63338. }else if( c==matchSet ){
  63339. int prior_c = 0;
  63340. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  63341. seen = 0;
  63342. invert = 0;
  63343. c = sqlite3Utf8Read(zString, &zString);
  63344. if( c==0 ) return 0;
  63345. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  63346. if( c2=='^' ){
  63347. invert = 1;
  63348. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  63349. }
  63350. if( c2==']' ){
  63351. if( c==']' ) seen = 1;
  63352. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  63353. }
  63354. while( c2 && c2!=']' ){
  63355. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  63356. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  63357. if( c>=prior_c && c<=c2 ) seen = 1;
  63358. prior_c = 0;
  63359. }else{
  63360. if( c==c2 ){
  63361. seen = 1;
  63362. }
  63363. prior_c = c2;
  63364. }
  63365. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  63366. }
  63367. if( c2==0 || (seen ^ invert)==0 ){
  63368. return 0;
  63369. }
  63370. }else if( esc==c && !prevEscape ){
  63371. prevEscape = 1;
  63372. }else{
  63373. c2 = sqlite3Utf8Read(zString, &zString);
  63374. if( noCase ){
  63375. GlogUpperToLower(c);
  63376. GlogUpperToLower(c2);
  63377. }
  63378. if( c!=c2 ){
  63379. return 0;
  63380. }
  63381. prevEscape = 0;
  63382. }
  63383. }
  63384. return *zString==0;
  63385. }
  63386. /*
  63387. ** Count the number of times that the LIKE operator (or GLOB which is
  63388. ** just a variation of LIKE) gets called. This is used for testing
  63389. ** only.
  63390. */
  63391. #ifdef SQLITE_TEST
  63392. SQLITE_API int sqlite3_like_count = 0;
  63393. #endif
  63394. /*
  63395. ** Implementation of the like() SQL function. This function implements
  63396. ** the build-in LIKE operator. The first argument to the function is the
  63397. ** pattern and the second argument is the string. So, the SQL statements:
  63398. **
  63399. ** A LIKE B
  63400. **
  63401. ** is implemented as like(B,A).
  63402. **
  63403. ** This same function (with a different compareInfo structure) computes
  63404. ** the GLOB operator.
  63405. */
  63406. static void likeFunc(
  63407. sqlite3_context *context,
  63408. int argc,
  63409. sqlite3_value **argv
  63410. ){
  63411. const unsigned char *zA, *zB;
  63412. int escape = 0;
  63413. int nPat;
  63414. sqlite3 *db = sqlite3_context_db_handle(context);
  63415. zB = sqlite3_value_text(argv[0]);
  63416. zA = sqlite3_value_text(argv[1]);
  63417. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  63418. ** of deep recursion and N*N behavior in patternCompare().
  63419. */
  63420. nPat = sqlite3_value_bytes(argv[0]);
  63421. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  63422. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  63423. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  63424. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  63425. return;
  63426. }
  63427. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  63428. if( argc==3 ){
  63429. /* The escape character string must consist of a single UTF-8 character.
  63430. ** Otherwise, return an error.
  63431. */
  63432. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  63433. if( zEsc==0 ) return;
  63434. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  63435. sqlite3_result_error(context,
  63436. "ESCAPE expression must be a single character", -1);
  63437. return;
  63438. }
  63439. escape = sqlite3Utf8Read(zEsc, &zEsc);
  63440. }
  63441. if( zA && zB ){
  63442. struct compareInfo *pInfo = sqlite3_user_data(context);
  63443. #ifdef SQLITE_TEST
  63444. sqlite3_like_count++;
  63445. #endif
  63446. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  63447. }
  63448. }
  63449. /*
  63450. ** Implementation of the NULLIF(x,y) function. The result is the first
  63451. ** argument if the arguments are different. The result is NULL if the
  63452. ** arguments are equal to each other.
  63453. */
  63454. static void nullifFunc(
  63455. sqlite3_context *context,
  63456. int NotUsed,
  63457. sqlite3_value **argv
  63458. ){
  63459. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  63460. UNUSED_PARAMETER(NotUsed);
  63461. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  63462. sqlite3_result_value(context, argv[0]);
  63463. }
  63464. }
  63465. /*
  63466. ** Implementation of the VERSION(*) function. The result is the version
  63467. ** of the SQLite library that is running.
  63468. */
  63469. static void versionFunc(
  63470. sqlite3_context *context,
  63471. int NotUsed,
  63472. sqlite3_value **NotUsed2
  63473. ){
  63474. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63475. sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
  63476. }
  63477. /* Array for converting from half-bytes (nybbles) into ASCII hex
  63478. ** digits. */
  63479. static const char hexdigits[] = {
  63480. '0', '1', '2', '3', '4', '5', '6', '7',
  63481. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  63482. };
  63483. /*
  63484. ** EXPERIMENTAL - This is not an official function. The interface may
  63485. ** change. This function may disappear. Do not write code that depends
  63486. ** on this function.
  63487. **
  63488. ** Implementation of the QUOTE() function. This function takes a single
  63489. ** argument. If the argument is numeric, the return value is the same as
  63490. ** the argument. If the argument is NULL, the return value is the string
  63491. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  63492. ** single-quote escapes.
  63493. */
  63494. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  63495. assert( argc==1 );
  63496. UNUSED_PARAMETER(argc);
  63497. switch( sqlite3_value_type(argv[0]) ){
  63498. case SQLITE_INTEGER:
  63499. case SQLITE_FLOAT: {
  63500. sqlite3_result_value(context, argv[0]);
  63501. break;
  63502. }
  63503. case SQLITE_BLOB: {
  63504. char *zText = 0;
  63505. char const *zBlob = sqlite3_value_blob(argv[0]);
  63506. int nBlob = sqlite3_value_bytes(argv[0]);
  63507. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  63508. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  63509. if( zText ){
  63510. int i;
  63511. for(i=0; i<nBlob; i++){
  63512. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  63513. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  63514. }
  63515. zText[(nBlob*2)+2] = '\'';
  63516. zText[(nBlob*2)+3] = '\0';
  63517. zText[0] = 'X';
  63518. zText[1] = '\'';
  63519. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  63520. sqlite3_free(zText);
  63521. }
  63522. break;
  63523. }
  63524. case SQLITE_TEXT: {
  63525. int i,j;
  63526. u64 n;
  63527. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  63528. char *z;
  63529. if( zArg==0 ) return;
  63530. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  63531. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  63532. if( z ){
  63533. z[0] = '\'';
  63534. for(i=0, j=1; zArg[i]; i++){
  63535. z[j++] = zArg[i];
  63536. if( zArg[i]=='\'' ){
  63537. z[j++] = '\'';
  63538. }
  63539. }
  63540. z[j++] = '\'';
  63541. z[j] = 0;
  63542. sqlite3_result_text(context, z, j, sqlite3_free);
  63543. }
  63544. break;
  63545. }
  63546. default: {
  63547. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  63548. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  63549. break;
  63550. }
  63551. }
  63552. }
  63553. /*
  63554. ** The hex() function. Interpret the argument as a blob. Return
  63555. ** a hexadecimal rendering as text.
  63556. */
  63557. static void hexFunc(
  63558. sqlite3_context *context,
  63559. int argc,
  63560. sqlite3_value **argv
  63561. ){
  63562. int i, n;
  63563. const unsigned char *pBlob;
  63564. char *zHex, *z;
  63565. assert( argc==1 );
  63566. UNUSED_PARAMETER(argc);
  63567. pBlob = sqlite3_value_blob(argv[0]);
  63568. n = sqlite3_value_bytes(argv[0]);
  63569. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  63570. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  63571. if( zHex ){
  63572. for(i=0; i<n; i++, pBlob++){
  63573. unsigned char c = *pBlob;
  63574. *(z++) = hexdigits[(c>>4)&0xf];
  63575. *(z++) = hexdigits[c&0xf];
  63576. }
  63577. *z = 0;
  63578. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  63579. }
  63580. }
  63581. /*
  63582. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  63583. */
  63584. static void zeroblobFunc(
  63585. sqlite3_context *context,
  63586. int argc,
  63587. sqlite3_value **argv
  63588. ){
  63589. i64 n;
  63590. sqlite3 *db = sqlite3_context_db_handle(context);
  63591. assert( argc==1 );
  63592. UNUSED_PARAMETER(argc);
  63593. n = sqlite3_value_int64(argv[0]);
  63594. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  63595. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  63596. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63597. sqlite3_result_error_toobig(context);
  63598. }else{
  63599. sqlite3_result_zeroblob(context, (int)n);
  63600. }
  63601. }
  63602. /*
  63603. ** The replace() function. Three arguments are all strings: call
  63604. ** them A, B, and C. The result is also a string which is derived
  63605. ** from A by replacing every occurance of B with C. The match
  63606. ** must be exact. Collating sequences are not used.
  63607. */
  63608. static void replaceFunc(
  63609. sqlite3_context *context,
  63610. int argc,
  63611. sqlite3_value **argv
  63612. ){
  63613. const unsigned char *zStr; /* The input string A */
  63614. const unsigned char *zPattern; /* The pattern string B */
  63615. const unsigned char *zRep; /* The replacement string C */
  63616. unsigned char *zOut; /* The output */
  63617. int nStr; /* Size of zStr */
  63618. int nPattern; /* Size of zPattern */
  63619. int nRep; /* Size of zRep */
  63620. i64 nOut; /* Maximum size of zOut */
  63621. int loopLimit; /* Last zStr[] that might match zPattern[] */
  63622. int i, j; /* Loop counters */
  63623. assert( argc==3 );
  63624. UNUSED_PARAMETER(argc);
  63625. zStr = sqlite3_value_text(argv[0]);
  63626. if( zStr==0 ) return;
  63627. nStr = sqlite3_value_bytes(argv[0]);
  63628. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  63629. zPattern = sqlite3_value_text(argv[1]);
  63630. if( zPattern==0 ){
  63631. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  63632. || sqlite3_context_db_handle(context)->mallocFailed );
  63633. return;
  63634. }
  63635. if( zPattern[0]==0 ){
  63636. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  63637. sqlite3_result_value(context, argv[0]);
  63638. return;
  63639. }
  63640. nPattern = sqlite3_value_bytes(argv[1]);
  63641. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  63642. zRep = sqlite3_value_text(argv[2]);
  63643. if( zRep==0 ) return;
  63644. nRep = sqlite3_value_bytes(argv[2]);
  63645. assert( zRep==sqlite3_value_text(argv[2]) );
  63646. nOut = nStr + 1;
  63647. assert( nOut<SQLITE_MAX_LENGTH );
  63648. zOut = contextMalloc(context, (i64)nOut);
  63649. if( zOut==0 ){
  63650. return;
  63651. }
  63652. loopLimit = nStr - nPattern;
  63653. for(i=j=0; i<=loopLimit; i++){
  63654. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  63655. zOut[j++] = zStr[i];
  63656. }else{
  63657. u8 *zOld;
  63658. sqlite3 *db = sqlite3_context_db_handle(context);
  63659. nOut += nRep - nPattern;
  63660. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  63661. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  63662. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63663. sqlite3_result_error_toobig(context);
  63664. sqlite3DbFree(db, zOut);
  63665. return;
  63666. }
  63667. zOld = zOut;
  63668. zOut = sqlite3_realloc(zOut, (int)nOut);
  63669. if( zOut==0 ){
  63670. sqlite3_result_error_nomem(context);
  63671. sqlite3DbFree(db, zOld);
  63672. return;
  63673. }
  63674. memcpy(&zOut[j], zRep, nRep);
  63675. j += nRep;
  63676. i += nPattern-1;
  63677. }
  63678. }
  63679. assert( j+nStr-i+1==nOut );
  63680. memcpy(&zOut[j], &zStr[i], nStr-i);
  63681. j += nStr - i;
  63682. assert( j<=nOut );
  63683. zOut[j] = 0;
  63684. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  63685. }
  63686. /*
  63687. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  63688. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  63689. */
  63690. static void trimFunc(
  63691. sqlite3_context *context,
  63692. int argc,
  63693. sqlite3_value **argv
  63694. ){
  63695. const unsigned char *zIn; /* Input string */
  63696. const unsigned char *zCharSet; /* Set of characters to trim */
  63697. int nIn; /* Number of bytes in input */
  63698. int flags; /* 1: trimleft 2: trimright 3: trim */
  63699. int i; /* Loop counter */
  63700. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  63701. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  63702. int nChar; /* Number of characters in zCharSet */
  63703. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  63704. return;
  63705. }
  63706. zIn = sqlite3_value_text(argv[0]);
  63707. if( zIn==0 ) return;
  63708. nIn = sqlite3_value_bytes(argv[0]);
  63709. assert( zIn==sqlite3_value_text(argv[0]) );
  63710. if( argc==1 ){
  63711. static const unsigned char lenOne[] = { 1 };
  63712. static unsigned char * const azOne[] = { (u8*)" " };
  63713. nChar = 1;
  63714. aLen = (u8*)lenOne;
  63715. azChar = (unsigned char **)azOne;
  63716. zCharSet = 0;
  63717. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  63718. return;
  63719. }else{
  63720. const unsigned char *z;
  63721. for(z=zCharSet, nChar=0; *z; nChar++){
  63722. SQLITE_SKIP_UTF8(z);
  63723. }
  63724. if( nChar>0 ){
  63725. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  63726. if( azChar==0 ){
  63727. return;
  63728. }
  63729. aLen = (unsigned char*)&azChar[nChar];
  63730. for(z=zCharSet, nChar=0; *z; nChar++){
  63731. azChar[nChar] = (unsigned char *)z;
  63732. SQLITE_SKIP_UTF8(z);
  63733. aLen[nChar] = (u8)(z - azChar[nChar]);
  63734. }
  63735. }
  63736. }
  63737. if( nChar>0 ){
  63738. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  63739. if( flags & 1 ){
  63740. while( nIn>0 ){
  63741. int len = 0;
  63742. for(i=0; i<nChar; i++){
  63743. len = aLen[i];
  63744. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  63745. }
  63746. if( i>=nChar ) break;
  63747. zIn += len;
  63748. nIn -= len;
  63749. }
  63750. }
  63751. if( flags & 2 ){
  63752. while( nIn>0 ){
  63753. int len = 0;
  63754. for(i=0; i<nChar; i++){
  63755. len = aLen[i];
  63756. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  63757. }
  63758. if( i>=nChar ) break;
  63759. nIn -= len;
  63760. }
  63761. }
  63762. if( zCharSet ){
  63763. sqlite3_free(azChar);
  63764. }
  63765. }
  63766. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  63767. }
  63768. #ifdef SQLITE_SOUNDEX
  63769. /*
  63770. ** Compute the soundex encoding of a word.
  63771. */
  63772. static void soundexFunc(
  63773. sqlite3_context *context,
  63774. int argc,
  63775. sqlite3_value **argv
  63776. ){
  63777. char zResult[8];
  63778. const u8 *zIn;
  63779. int i, j;
  63780. static const unsigned char iCode[] = {
  63781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  63782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  63783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  63784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  63785. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  63786. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  63787. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  63788. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  63789. };
  63790. assert( argc==1 );
  63791. zIn = (u8*)sqlite3_value_text(argv[0]);
  63792. if( zIn==0 ) zIn = (u8*)"";
  63793. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  63794. if( zIn[i] ){
  63795. u8 prevcode = iCode[zIn[i]&0x7f];
  63796. zResult[0] = sqlite3Toupper(zIn[i]);
  63797. for(j=1; j<4 && zIn[i]; i++){
  63798. int code = iCode[zIn[i]&0x7f];
  63799. if( code>0 ){
  63800. if( code!=prevcode ){
  63801. prevcode = code;
  63802. zResult[j++] = code + '0';
  63803. }
  63804. }else{
  63805. prevcode = 0;
  63806. }
  63807. }
  63808. while( j<4 ){
  63809. zResult[j++] = '0';
  63810. }
  63811. zResult[j] = 0;
  63812. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  63813. }else{
  63814. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  63815. }
  63816. }
  63817. #endif
  63818. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  63819. /*
  63820. ** A function that loads a shared-library extension then returns NULL.
  63821. */
  63822. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  63823. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  63824. const char *zProc;
  63825. sqlite3 *db = sqlite3_context_db_handle(context);
  63826. char *zErrMsg = 0;
  63827. if( argc==2 ){
  63828. zProc = (const char *)sqlite3_value_text(argv[1]);
  63829. }else{
  63830. zProc = 0;
  63831. }
  63832. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  63833. sqlite3_result_error(context, zErrMsg, -1);
  63834. sqlite3_free(zErrMsg);
  63835. }
  63836. }
  63837. #endif
  63838. /*
  63839. ** An instance of the following structure holds the context of a
  63840. ** sum() or avg() aggregate computation.
  63841. */
  63842. typedef struct SumCtx SumCtx;
  63843. struct SumCtx {
  63844. double rSum; /* Floating point sum */
  63845. i64 iSum; /* Integer sum */
  63846. i64 cnt; /* Number of elements summed */
  63847. u8 overflow; /* True if integer overflow seen */
  63848. u8 approx; /* True if non-integer value was input to the sum */
  63849. };
  63850. /*
  63851. ** Routines used to compute the sum, average, and total.
  63852. **
  63853. ** The SUM() function follows the (broken) SQL standard which means
  63854. ** that it returns NULL if it sums over no inputs. TOTAL returns
  63855. ** 0.0 in that case. In addition, TOTAL always returns a float where
  63856. ** SUM might return an integer if it never encounters a floating point
  63857. ** value. TOTAL never fails, but SUM might through an exception if
  63858. ** it overflows an integer.
  63859. */
  63860. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  63861. SumCtx *p;
  63862. int type;
  63863. assert( argc==1 );
  63864. UNUSED_PARAMETER(argc);
  63865. p = sqlite3_aggregate_context(context, sizeof(*p));
  63866. type = sqlite3_value_numeric_type(argv[0]);
  63867. if( p && type!=SQLITE_NULL ){
  63868. p->cnt++;
  63869. if( type==SQLITE_INTEGER ){
  63870. i64 v = sqlite3_value_int64(argv[0]);
  63871. p->rSum += v;
  63872. if( (p->approx|p->overflow)==0 ){
  63873. i64 iNewSum = p->iSum + v;
  63874. int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
  63875. int s2 = (int)(v >> (sizeof(i64)*8-1));
  63876. int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
  63877. p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
  63878. p->iSum = iNewSum;
  63879. }
  63880. }else{
  63881. p->rSum += sqlite3_value_double(argv[0]);
  63882. p->approx = 1;
  63883. }
  63884. }
  63885. }
  63886. static void sumFinalize(sqlite3_context *context){
  63887. SumCtx *p;
  63888. p = sqlite3_aggregate_context(context, 0);
  63889. if( p && p->cnt>0 ){
  63890. if( p->overflow ){
  63891. sqlite3_result_error(context,"integer overflow",-1);
  63892. }else if( p->approx ){
  63893. sqlite3_result_double(context, p->rSum);
  63894. }else{
  63895. sqlite3_result_int64(context, p->iSum);
  63896. }
  63897. }
  63898. }
  63899. static void avgFinalize(sqlite3_context *context){
  63900. SumCtx *p;
  63901. p = sqlite3_aggregate_context(context, 0);
  63902. if( p && p->cnt>0 ){
  63903. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  63904. }
  63905. }
  63906. static void totalFinalize(sqlite3_context *context){
  63907. SumCtx *p;
  63908. p = sqlite3_aggregate_context(context, 0);
  63909. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  63910. sqlite3_result_double(context, p ? p->rSum : (double)0);
  63911. }
  63912. /*
  63913. ** The following structure keeps track of state information for the
  63914. ** count() aggregate function.
  63915. */
  63916. typedef struct CountCtx CountCtx;
  63917. struct CountCtx {
  63918. i64 n;
  63919. };
  63920. /*
  63921. ** Routines to implement the count() aggregate function.
  63922. */
  63923. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  63924. CountCtx *p;
  63925. p = sqlite3_aggregate_context(context, sizeof(*p));
  63926. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  63927. p->n++;
  63928. }
  63929. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  63930. ** sure it still operates correctly, verify that its count agrees with our
  63931. ** internal count when using count(*) and when the total count can be
  63932. ** expressed as a 32-bit integer. */
  63933. assert( argc==1 || p==0 || p->n>0x7fffffff
  63934. || p->n==sqlite3_aggregate_count(context) );
  63935. }
  63936. static void countFinalize(sqlite3_context *context){
  63937. CountCtx *p;
  63938. p = sqlite3_aggregate_context(context, 0);
  63939. sqlite3_result_int64(context, p ? p->n : 0);
  63940. }
  63941. /*
  63942. ** Routines to implement min() and max() aggregate functions.
  63943. */
  63944. static void minmaxStep(
  63945. sqlite3_context *context,
  63946. int NotUsed,
  63947. sqlite3_value **argv
  63948. ){
  63949. Mem *pArg = (Mem *)argv[0];
  63950. Mem *pBest;
  63951. UNUSED_PARAMETER(NotUsed);
  63952. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  63953. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  63954. if( !pBest ) return;
  63955. if( pBest->flags ){
  63956. int max;
  63957. int cmp;
  63958. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  63959. /* This step function is used for both the min() and max() aggregates,
  63960. ** the only difference between the two being that the sense of the
  63961. ** comparison is inverted. For the max() aggregate, the
  63962. ** sqlite3_user_data() function returns (void *)-1. For min() it
  63963. ** returns (void *)db, where db is the sqlite3* database pointer.
  63964. ** Therefore the next statement sets variable 'max' to 1 for the max()
  63965. ** aggregate, or 0 for min().
  63966. */
  63967. max = sqlite3_user_data(context)!=0;
  63968. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  63969. if( (max && cmp<0) || (!max && cmp>0) ){
  63970. sqlite3VdbeMemCopy(pBest, pArg);
  63971. }
  63972. }else{
  63973. sqlite3VdbeMemCopy(pBest, pArg);
  63974. }
  63975. }
  63976. static void minMaxFinalize(sqlite3_context *context){
  63977. sqlite3_value *pRes;
  63978. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  63979. if( pRes ){
  63980. if( ALWAYS(pRes->flags) ){
  63981. sqlite3_result_value(context, pRes);
  63982. }
  63983. sqlite3VdbeMemRelease(pRes);
  63984. }
  63985. }
  63986. /*
  63987. ** group_concat(EXPR, ?SEPARATOR?)
  63988. */
  63989. static void groupConcatStep(
  63990. sqlite3_context *context,
  63991. int argc,
  63992. sqlite3_value **argv
  63993. ){
  63994. const char *zVal;
  63995. StrAccum *pAccum;
  63996. const char *zSep;
  63997. int nVal, nSep;
  63998. assert( argc==1 || argc==2 );
  63999. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  64000. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  64001. if( pAccum ){
  64002. sqlite3 *db = sqlite3_context_db_handle(context);
  64003. pAccum->useMalloc = 1;
  64004. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  64005. if( pAccum->nChar ){
  64006. if( argc==2 ){
  64007. zSep = (char*)sqlite3_value_text(argv[1]);
  64008. nSep = sqlite3_value_bytes(argv[1]);
  64009. }else{
  64010. zSep = ",";
  64011. nSep = 1;
  64012. }
  64013. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  64014. }
  64015. zVal = (char*)sqlite3_value_text(argv[0]);
  64016. nVal = sqlite3_value_bytes(argv[0]);
  64017. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  64018. }
  64019. }
  64020. static void groupConcatFinalize(sqlite3_context *context){
  64021. StrAccum *pAccum;
  64022. pAccum = sqlite3_aggregate_context(context, 0);
  64023. if( pAccum ){
  64024. if( pAccum->tooBig ){
  64025. sqlite3_result_error_toobig(context);
  64026. }else if( pAccum->mallocFailed ){
  64027. sqlite3_result_error_nomem(context);
  64028. }else{
  64029. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  64030. sqlite3_free);
  64031. }
  64032. }
  64033. }
  64034. /*
  64035. ** This function registered all of the above C functions as SQL
  64036. ** functions. This should be the only routine in this file with
  64037. ** external linkage.
  64038. */
  64039. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  64040. #ifndef SQLITE_OMIT_ALTERTABLE
  64041. sqlite3AlterFunctions(db);
  64042. #endif
  64043. if( !db->mallocFailed ){
  64044. int rc = sqlite3_overload_function(db, "MATCH", 2);
  64045. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  64046. if( rc==SQLITE_NOMEM ){
  64047. db->mallocFailed = 1;
  64048. }
  64049. }
  64050. #ifdef SQLITE_SSE
  64051. (void)sqlite3SseFunctions(db);
  64052. #endif
  64053. }
  64054. /*
  64055. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  64056. */
  64057. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  64058. FuncDef *pDef;
  64059. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  64060. 2, SQLITE_UTF8, 0);
  64061. if( ALWAYS(pDef) ){
  64062. pDef->flags = flagVal;
  64063. }
  64064. }
  64065. /*
  64066. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  64067. ** parameter determines whether or not the LIKE operator is case
  64068. ** sensitive. GLOB is always case sensitive.
  64069. */
  64070. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  64071. struct compareInfo *pInfo;
  64072. if( caseSensitive ){
  64073. pInfo = (struct compareInfo*)&likeInfoAlt;
  64074. }else{
  64075. pInfo = (struct compareInfo*)&likeInfoNorm;
  64076. }
  64077. sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
  64078. sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
  64079. sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
  64080. (struct compareInfo*)&globInfo, likeFunc, 0,0);
  64081. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  64082. setLikeOptFlag(db, "like",
  64083. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  64084. }
  64085. /*
  64086. ** pExpr points to an expression which implements a function. If
  64087. ** it is appropriate to apply the LIKE optimization to that function
  64088. ** then set aWc[0] through aWc[2] to the wildcard characters and
  64089. ** return TRUE. If the function is not a LIKE-style function then
  64090. ** return FALSE.
  64091. */
  64092. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  64093. FuncDef *pDef;
  64094. if( pExpr->op!=TK_FUNCTION
  64095. || !pExpr->x.pList
  64096. || pExpr->x.pList->nExpr!=2
  64097. ){
  64098. return 0;
  64099. }
  64100. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64101. pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
  64102. SQLITE_UTF8, 0);
  64103. if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  64104. return 0;
  64105. }
  64106. /* The memcpy() statement assumes that the wildcard characters are
  64107. ** the first three statements in the compareInfo structure. The
  64108. ** asserts() that follow verify that assumption
  64109. */
  64110. memcpy(aWc, pDef->pUserData, 3);
  64111. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  64112. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  64113. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  64114. *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  64115. return 1;
  64116. }
  64117. /*
  64118. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  64119. ** to the global function hash table. This occurs at start-time (as
  64120. ** a consequence of calling sqlite3_initialize()).
  64121. **
  64122. ** After this routine runs
  64123. */
  64124. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  64125. /*
  64126. ** The following array holds FuncDef structures for all of the functions
  64127. ** defined in this file.
  64128. **
  64129. ** The array cannot be constant since changes are made to the
  64130. ** FuncDef.pHash elements at start-time. The elements of this array
  64131. ** are read-only after initialization is complete.
  64132. */
  64133. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  64134. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  64135. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  64136. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  64137. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  64138. FUNCTION(trim, 1, 3, 0, trimFunc ),
  64139. FUNCTION(trim, 2, 3, 0, trimFunc ),
  64140. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  64141. FUNCTION(min, 0, 0, 1, 0 ),
  64142. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  64143. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  64144. FUNCTION(max, 0, 1, 1, 0 ),
  64145. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  64146. FUNCTION(typeof, 1, 0, 0, typeofFunc ),
  64147. FUNCTION(length, 1, 0, 0, lengthFunc ),
  64148. FUNCTION(substr, 2, 0, 0, substrFunc ),
  64149. FUNCTION(substr, 3, 0, 0, substrFunc ),
  64150. FUNCTION(abs, 1, 0, 0, absFunc ),
  64151. #ifndef SQLITE_OMIT_FLOATING_POINT
  64152. FUNCTION(round, 1, 0, 0, roundFunc ),
  64153. FUNCTION(round, 2, 0, 0, roundFunc ),
  64154. #endif
  64155. FUNCTION(upper, 1, 0, 0, upperFunc ),
  64156. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  64157. FUNCTION(coalesce, 1, 0, 0, 0 ),
  64158. FUNCTION(coalesce, -1, 0, 0, ifnullFunc ),
  64159. FUNCTION(coalesce, 0, 0, 0, 0 ),
  64160. FUNCTION(hex, 1, 0, 0, hexFunc ),
  64161. FUNCTION(ifnull, 2, 0, 1, ifnullFunc ),
  64162. FUNCTION(random, 0, 0, 0, randomFunc ),
  64163. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  64164. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  64165. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  64166. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  64167. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  64168. FUNCTION(changes, 0, 0, 0, changes ),
  64169. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  64170. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  64171. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  64172. #ifdef SQLITE_SOUNDEX
  64173. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  64174. #endif
  64175. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  64176. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  64177. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  64178. #endif
  64179. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  64180. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  64181. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  64182. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  64183. {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
  64184. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  64185. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  64186. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  64187. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  64188. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  64189. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  64190. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  64191. #else
  64192. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  64193. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  64194. #endif
  64195. };
  64196. int i;
  64197. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  64198. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  64199. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  64200. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  64201. }
  64202. sqlite3RegisterDateTimeFunctions();
  64203. }
  64204. /************** End of func.c ************************************************/
  64205. /************** Begin file insert.c ******************************************/
  64206. /*
  64207. ** 2001 September 15
  64208. **
  64209. ** The author disclaims copyright to this source code. In place of
  64210. ** a legal notice, here is a blessing:
  64211. **
  64212. ** May you do good and not evil.
  64213. ** May you find forgiveness for yourself and forgive others.
  64214. ** May you share freely, never taking more than you give.
  64215. **
  64216. *************************************************************************
  64217. ** This file contains C code routines that are called by the parser
  64218. ** to handle INSERT statements in SQLite.
  64219. **
  64220. ** $Id: insert.c,v 1.260 2009/02/28 10:47:42 danielk1977 Exp $
  64221. */
  64222. /*
  64223. ** Set P4 of the most recently inserted opcode to a column affinity
  64224. ** string for index pIdx. A column affinity string has one character
  64225. ** for each column in the table, according to the affinity of the column:
  64226. **
  64227. ** Character Column affinity
  64228. ** ------------------------------
  64229. ** 'a' TEXT
  64230. ** 'b' NONE
  64231. ** 'c' NUMERIC
  64232. ** 'd' INTEGER
  64233. ** 'e' REAL
  64234. **
  64235. ** An extra 'b' is appended to the end of the string to cover the
  64236. ** rowid that appears as the last column in every index.
  64237. */
  64238. SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  64239. if( !pIdx->zColAff ){
  64240. /* The first time a column affinity string for a particular index is
  64241. ** required, it is allocated and populated here. It is then stored as
  64242. ** a member of the Index structure for subsequent use.
  64243. **
  64244. ** The column affinity string will eventually be deleted by
  64245. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  64246. ** up.
  64247. */
  64248. int n;
  64249. Table *pTab = pIdx->pTable;
  64250. sqlite3 *db = sqlite3VdbeDb(v);
  64251. pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
  64252. if( !pIdx->zColAff ){
  64253. db->mallocFailed = 1;
  64254. return;
  64255. }
  64256. for(n=0; n<pIdx->nColumn; n++){
  64257. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  64258. }
  64259. pIdx->zColAff[n++] = SQLITE_AFF_NONE;
  64260. pIdx->zColAff[n] = 0;
  64261. }
  64262. sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
  64263. }
  64264. /*
  64265. ** Set P4 of the most recently inserted opcode to a column affinity
  64266. ** string for table pTab. A column affinity string has one character
  64267. ** for each column indexed by the index, according to the affinity of the
  64268. ** column:
  64269. **
  64270. ** Character Column affinity
  64271. ** ------------------------------
  64272. ** 'a' TEXT
  64273. ** 'b' NONE
  64274. ** 'c' NUMERIC
  64275. ** 'd' INTEGER
  64276. ** 'e' REAL
  64277. */
  64278. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  64279. /* The first time a column affinity string for a particular table
  64280. ** is required, it is allocated and populated here. It is then
  64281. ** stored as a member of the Table structure for subsequent use.
  64282. **
  64283. ** The column affinity string will eventually be deleted by
  64284. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  64285. */
  64286. if( !pTab->zColAff ){
  64287. char *zColAff;
  64288. int i;
  64289. sqlite3 *db = sqlite3VdbeDb(v);
  64290. zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
  64291. if( !zColAff ){
  64292. db->mallocFailed = 1;
  64293. return;
  64294. }
  64295. for(i=0; i<pTab->nCol; i++){
  64296. zColAff[i] = pTab->aCol[i].affinity;
  64297. }
  64298. zColAff[pTab->nCol] = '\0';
  64299. pTab->zColAff = zColAff;
  64300. }
  64301. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
  64302. }
  64303. /*
  64304. ** Return non-zero if the table pTab in database iDb or any of its indices
  64305. ** have been opened at any point in the VDBE program beginning at location
  64306. ** iStartAddr throught the end of the program. This is used to see if
  64307. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  64308. ** run without using temporary table for the results of the SELECT.
  64309. */
  64310. static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
  64311. int i;
  64312. int iEnd = sqlite3VdbeCurrentAddr(v);
  64313. for(i=iStartAddr; i<iEnd; i++){
  64314. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  64315. assert( pOp!=0 );
  64316. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  64317. Index *pIndex;
  64318. int tnum = pOp->p2;
  64319. if( tnum==pTab->tnum ){
  64320. return 1;
  64321. }
  64322. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  64323. if( tnum==pIndex->tnum ){
  64324. return 1;
  64325. }
  64326. }
  64327. }
  64328. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64329. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
  64330. assert( pOp->p4.pVtab!=0 );
  64331. assert( pOp->p4type==P4_VTAB );
  64332. return 1;
  64333. }
  64334. #endif
  64335. }
  64336. return 0;
  64337. }
  64338. #ifndef SQLITE_OMIT_AUTOINCREMENT
  64339. /*
  64340. ** Write out code to initialize the autoincrement logic. This code
  64341. ** looks up the current autoincrement value in the sqlite_sequence
  64342. ** table and stores that value in a register. Code generated by
  64343. ** autoIncStep() will keep that register holding the largest
  64344. ** rowid value. Code generated by autoIncEnd() will write the new
  64345. ** largest value of the counter back into the sqlite_sequence table.
  64346. **
  64347. ** This routine returns the index of the mem[] cell that contains
  64348. ** the maximum rowid counter.
  64349. **
  64350. ** Three consecutive registers are allocated by this routine. The
  64351. ** first two hold the name of the target table and the maximum rowid
  64352. ** inserted into the target table, respectively.
  64353. ** The third holds the rowid in sqlite_sequence where we will
  64354. ** write back the revised maximum rowid. This routine returns the
  64355. ** index of the second of these three registers.
  64356. */
  64357. static int autoIncBegin(
  64358. Parse *pParse, /* Parsing context */
  64359. int iDb, /* Index of the database holding pTab */
  64360. Table *pTab /* The table we are writing to */
  64361. ){
  64362. int memId = 0; /* Register holding maximum rowid */
  64363. if( pTab->tabFlags & TF_Autoincrement ){
  64364. Vdbe *v = pParse->pVdbe;
  64365. Db *pDb = &pParse->db->aDb[iDb];
  64366. int iCur = pParse->nTab++;
  64367. int addr; /* Address of the top of the loop */
  64368. assert( v );
  64369. pParse->nMem++; /* Holds name of table */
  64370. memId = ++pParse->nMem;
  64371. pParse->nMem++;
  64372. sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  64373. addr = sqlite3VdbeCurrentAddr(v);
  64374. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
  64375. sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
  64376. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
  64377. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  64378. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  64379. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
  64380. sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
  64381. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  64382. sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
  64383. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  64384. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  64385. }
  64386. return memId;
  64387. }
  64388. /*
  64389. ** Update the maximum rowid for an autoincrement calculation.
  64390. **
  64391. ** This routine should be called when the top of the stack holds a
  64392. ** new rowid that is about to be inserted. If that new rowid is
  64393. ** larger than the maximum rowid in the memId memory cell, then the
  64394. ** memory cell is updated. The stack is unchanged.
  64395. */
  64396. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  64397. if( memId>0 ){
  64398. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  64399. }
  64400. }
  64401. /*
  64402. ** After doing one or more inserts, the maximum rowid is stored
  64403. ** in reg[memId]. Generate code to write this value back into the
  64404. ** the sqlite_sequence table.
  64405. */
  64406. static void autoIncEnd(
  64407. Parse *pParse, /* The parsing context */
  64408. int iDb, /* Index of the database holding pTab */
  64409. Table *pTab, /* Table we are inserting into */
  64410. int memId /* Memory cell holding the maximum rowid */
  64411. ){
  64412. if( pTab->tabFlags & TF_Autoincrement ){
  64413. int iCur = pParse->nTab++;
  64414. Vdbe *v = pParse->pVdbe;
  64415. Db *pDb = &pParse->db->aDb[iDb];
  64416. int j1;
  64417. int iRec = ++pParse->nMem; /* Memory cell used for record */
  64418. assert( v );
  64419. sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  64420. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  64421. sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
  64422. sqlite3VdbeJumpHere(v, j1);
  64423. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  64424. sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
  64425. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  64426. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  64427. }
  64428. }
  64429. #else
  64430. /*
  64431. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  64432. ** above are all no-ops
  64433. */
  64434. # define autoIncBegin(A,B,C) (0)
  64435. # define autoIncStep(A,B,C)
  64436. # define autoIncEnd(A,B,C,D)
  64437. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  64438. /* Forward declaration */
  64439. static int xferOptimization(
  64440. Parse *pParse, /* Parser context */
  64441. Table *pDest, /* The table we are inserting into */
  64442. Select *pSelect, /* A SELECT statement to use as the data source */
  64443. int onError, /* How to handle constraint errors */
  64444. int iDbDest /* The database of pDest */
  64445. );
  64446. /*
  64447. ** This routine is call to handle SQL of the following forms:
  64448. **
  64449. ** insert into TABLE (IDLIST) values(EXPRLIST)
  64450. ** insert into TABLE (IDLIST) select
  64451. **
  64452. ** The IDLIST following the table name is always optional. If omitted,
  64453. ** then a list of all columns for the table is substituted. The IDLIST
  64454. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  64455. **
  64456. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  64457. ** statement above, and pSelect is NULL. For the second form, pList is
  64458. ** NULL and pSelect is a pointer to the select statement used to generate
  64459. ** data for the insert.
  64460. **
  64461. ** The code generated follows one of four templates. For a simple
  64462. ** select with data coming from a VALUES clause, the code executes
  64463. ** once straight down through. Pseudo-code follows (we call this
  64464. ** the "1st template"):
  64465. **
  64466. ** open write cursor to <table> and its indices
  64467. ** puts VALUES clause expressions onto the stack
  64468. ** write the resulting record into <table>
  64469. ** cleanup
  64470. **
  64471. ** The three remaining templates assume the statement is of the form
  64472. **
  64473. ** INSERT INTO <table> SELECT ...
  64474. **
  64475. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  64476. ** in other words if the SELECT pulls all columns from a single table
  64477. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  64478. ** if <table2> and <table1> are distinct tables but have identical
  64479. ** schemas, including all the same indices, then a special optimization
  64480. ** is invoked that copies raw records from <table2> over to <table1>.
  64481. ** See the xferOptimization() function for the implementation of this
  64482. ** template. This is the 2nd template.
  64483. **
  64484. ** open a write cursor to <table>
  64485. ** open read cursor on <table2>
  64486. ** transfer all records in <table2> over to <table>
  64487. ** close cursors
  64488. ** foreach index on <table>
  64489. ** open a write cursor on the <table> index
  64490. ** open a read cursor on the corresponding <table2> index
  64491. ** transfer all records from the read to the write cursors
  64492. ** close cursors
  64493. ** end foreach
  64494. **
  64495. ** The 3rd template is for when the second template does not apply
  64496. ** and the SELECT clause does not read from <table> at any time.
  64497. ** The generated code follows this template:
  64498. **
  64499. ** EOF <- 0
  64500. ** X <- A
  64501. ** goto B
  64502. ** A: setup for the SELECT
  64503. ** loop over the rows in the SELECT
  64504. ** load values into registers R..R+n
  64505. ** yield X
  64506. ** end loop
  64507. ** cleanup after the SELECT
  64508. ** EOF <- 1
  64509. ** yield X
  64510. ** goto A
  64511. ** B: open write cursor to <table> and its indices
  64512. ** C: yield X
  64513. ** if EOF goto D
  64514. ** insert the select result into <table> from R..R+n
  64515. ** goto C
  64516. ** D: cleanup
  64517. **
  64518. ** The 4th template is used if the insert statement takes its
  64519. ** values from a SELECT but the data is being inserted into a table
  64520. ** that is also read as part of the SELECT. In the third form,
  64521. ** we have to use a intermediate table to store the results of
  64522. ** the select. The template is like this:
  64523. **
  64524. ** EOF <- 0
  64525. ** X <- A
  64526. ** goto B
  64527. ** A: setup for the SELECT
  64528. ** loop over the tables in the SELECT
  64529. ** load value into register R..R+n
  64530. ** yield X
  64531. ** end loop
  64532. ** cleanup after the SELECT
  64533. ** EOF <- 1
  64534. ** yield X
  64535. ** halt-error
  64536. ** B: open temp table
  64537. ** L: yield X
  64538. ** if EOF goto M
  64539. ** insert row from R..R+n into temp table
  64540. ** goto L
  64541. ** M: open write cursor to <table> and its indices
  64542. ** rewind temp table
  64543. ** C: loop over rows of intermediate table
  64544. ** transfer values form intermediate table into <table>
  64545. ** end loop
  64546. ** D: cleanup
  64547. */
  64548. SQLITE_PRIVATE void sqlite3Insert(
  64549. Parse *pParse, /* Parser context */
  64550. SrcList *pTabList, /* Name of table into which we are inserting */
  64551. ExprList *pList, /* List of values to be inserted */
  64552. Select *pSelect, /* A SELECT statement to use as the data source */
  64553. IdList *pColumn, /* Column names corresponding to IDLIST. */
  64554. int onError /* How to handle constraint errors */
  64555. ){
  64556. sqlite3 *db; /* The main database structure */
  64557. Table *pTab; /* The table to insert into. aka TABLE */
  64558. char *zTab; /* Name of the table into which we are inserting */
  64559. const char *zDb; /* Name of the database holding this table */
  64560. int i, j, idx; /* Loop counters */
  64561. Vdbe *v; /* Generate code into this virtual machine */
  64562. Index *pIdx; /* For looping over indices of the table */
  64563. int nColumn; /* Number of columns in the data */
  64564. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  64565. int baseCur = 0; /* VDBE Cursor number for pTab */
  64566. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  64567. int endOfLoop; /* Label for the end of the insertion loop */
  64568. int useTempTable = 0; /* Store SELECT results in intermediate table */
  64569. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  64570. int addrInsTop = 0; /* Jump to label "D" */
  64571. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  64572. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  64573. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  64574. int newIdx = -1; /* Cursor for the NEW pseudo-table */
  64575. int iDb; /* Index of database holding TABLE */
  64576. Db *pDb; /* The database containing table being inserted into */
  64577. int appendFlag = 0; /* True if the insert is likely to be an append */
  64578. /* Register allocations */
  64579. int regFromSelect = 0;/* Base register for data coming from SELECT */
  64580. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  64581. int regRowCount = 0; /* Memory cell used for the row counter */
  64582. int regIns; /* Block of regs holding rowid+data being inserted */
  64583. int regRowid; /* registers holding insert rowid */
  64584. int regData; /* register holding first column to insert */
  64585. int regRecord; /* Holds the assemblied row record */
  64586. int regEof = 0; /* Register recording end of SELECT data */
  64587. int *aRegIdx = 0; /* One register allocated to each index */
  64588. #ifndef SQLITE_OMIT_TRIGGER
  64589. int isView; /* True if attempting to insert into a view */
  64590. Trigger *pTrigger; /* List of triggers on pTab, if required */
  64591. int tmask; /* Mask of trigger times */
  64592. #endif
  64593. db = pParse->db;
  64594. memset(&dest, 0, sizeof(dest));
  64595. if( pParse->nErr || db->mallocFailed ){
  64596. goto insert_cleanup;
  64597. }
  64598. /* Locate the table into which we will be inserting new information.
  64599. */
  64600. assert( pTabList->nSrc==1 );
  64601. zTab = pTabList->a[0].zName;
  64602. if( zTab==0 ) goto insert_cleanup;
  64603. pTab = sqlite3SrcListLookup(pParse, pTabList);
  64604. if( pTab==0 ){
  64605. goto insert_cleanup;
  64606. }
  64607. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  64608. assert( iDb<db->nDb );
  64609. pDb = &db->aDb[iDb];
  64610. zDb = pDb->zName;
  64611. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  64612. goto insert_cleanup;
  64613. }
  64614. /* Figure out if we have any triggers and if the table being
  64615. ** inserted into is a view
  64616. */
  64617. #ifndef SQLITE_OMIT_TRIGGER
  64618. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  64619. isView = pTab->pSelect!=0;
  64620. #else
  64621. # define pTrigger 0
  64622. # define tmask 0
  64623. # define isView 0
  64624. #endif
  64625. #ifdef SQLITE_OMIT_VIEW
  64626. # undef isView
  64627. # define isView 0
  64628. #endif
  64629. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  64630. /* Ensure that:
  64631. * (a) the table is not read-only,
  64632. * (b) that if it is a view then ON INSERT triggers exist
  64633. */
  64634. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  64635. goto insert_cleanup;
  64636. }
  64637. assert( pTab!=0 );
  64638. /* If pTab is really a view, make sure it has been initialized.
  64639. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  64640. ** module table).
  64641. */
  64642. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  64643. goto insert_cleanup;
  64644. }
  64645. /* Allocate a VDBE
  64646. */
  64647. v = sqlite3GetVdbe(pParse);
  64648. if( v==0 ) goto insert_cleanup;
  64649. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  64650. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  64651. /* if there are row triggers, allocate a temp table for new.* references. */
  64652. if( pTrigger ){
  64653. newIdx = pParse->nTab++;
  64654. }
  64655. #ifndef SQLITE_OMIT_XFER_OPT
  64656. /* If the statement is of the form
  64657. **
  64658. ** INSERT INTO <table1> SELECT * FROM <table2>;
  64659. **
  64660. ** Then special optimizations can be applied that make the transfer
  64661. ** very fast and which reduce fragmentation of indices.
  64662. **
  64663. ** This is the 2nd template.
  64664. */
  64665. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  64666. assert( !pTrigger );
  64667. assert( pList==0 );
  64668. goto insert_cleanup;
  64669. }
  64670. #endif /* SQLITE_OMIT_XFER_OPT */
  64671. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  64672. ** sqlite_sequence table and store it in memory cell regAutoinc.
  64673. */
  64674. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  64675. /* Figure out how many columns of data are supplied. If the data
  64676. ** is coming from a SELECT statement, then generate a co-routine that
  64677. ** produces a single row of the SELECT on each invocation. The
  64678. ** co-routine is the common header to the 3rd and 4th templates.
  64679. */
  64680. if( pSelect ){
  64681. /* Data is coming from a SELECT. Generate code to implement that SELECT
  64682. ** as a co-routine. The code is common to both the 3rd and 4th
  64683. ** templates:
  64684. **
  64685. ** EOF <- 0
  64686. ** X <- A
  64687. ** goto B
  64688. ** A: setup for the SELECT
  64689. ** loop over the tables in the SELECT
  64690. ** load value into register R..R+n
  64691. ** yield X
  64692. ** end loop
  64693. ** cleanup after the SELECT
  64694. ** EOF <- 1
  64695. ** yield X
  64696. ** halt-error
  64697. **
  64698. ** On each invocation of the co-routine, it puts a single row of the
  64699. ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
  64700. ** (These output registers are allocated by sqlite3Select().) When
  64701. ** the SELECT completes, it sets the EOF flag stored in regEof.
  64702. */
  64703. int rc, j1;
  64704. regEof = ++pParse->nMem;
  64705. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  64706. VdbeComment((v, "SELECT eof flag"));
  64707. sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
  64708. addrSelect = sqlite3VdbeCurrentAddr(v)+2;
  64709. sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
  64710. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  64711. VdbeComment((v, "Jump over SELECT coroutine"));
  64712. /* Resolve the expressions in the SELECT statement and execute it. */
  64713. rc = sqlite3Select(pParse, pSelect, &dest);
  64714. if( rc || pParse->nErr || db->mallocFailed ){
  64715. goto insert_cleanup;
  64716. }
  64717. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  64718. sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
  64719. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  64720. VdbeComment((v, "End of SELECT coroutine"));
  64721. sqlite3VdbeJumpHere(v, j1); /* label B: */
  64722. regFromSelect = dest.iMem;
  64723. assert( pSelect->pEList );
  64724. nColumn = pSelect->pEList->nExpr;
  64725. assert( dest.nMem==nColumn );
  64726. /* Set useTempTable to TRUE if the result of the SELECT statement
  64727. ** should be written into a temporary table (template 4). Set to
  64728. ** FALSE if each* row of the SELECT can be written directly into
  64729. ** the destination table (template 3).
  64730. **
  64731. ** A temp table must be used if the table being updated is also one
  64732. ** of the tables being read by the SELECT statement. Also use a
  64733. ** temp table in the case of row triggers.
  64734. */
  64735. if( pTrigger || readsTable(v, addrSelect, iDb, pTab) ){
  64736. useTempTable = 1;
  64737. }
  64738. if( useTempTable ){
  64739. /* Invoke the coroutine to extract information from the SELECT
  64740. ** and add it to a transient table srcTab. The code generated
  64741. ** here is from the 4th template:
  64742. **
  64743. ** B: open temp table
  64744. ** L: yield X
  64745. ** if EOF goto M
  64746. ** insert row from R..R+n into temp table
  64747. ** goto L
  64748. ** M: ...
  64749. */
  64750. int regRec; /* Register to hold packed record */
  64751. int regTempRowid; /* Register to hold temp table ROWID */
  64752. int addrTop; /* Label "L" */
  64753. int addrIf; /* Address of jump to M */
  64754. srcTab = pParse->nTab++;
  64755. regRec = sqlite3GetTempReg(pParse);
  64756. regTempRowid = sqlite3GetTempReg(pParse);
  64757. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  64758. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
  64759. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  64760. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  64761. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  64762. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  64763. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  64764. sqlite3VdbeJumpHere(v, addrIf);
  64765. sqlite3ReleaseTempReg(pParse, regRec);
  64766. sqlite3ReleaseTempReg(pParse, regTempRowid);
  64767. }
  64768. }else{
  64769. /* This is the case if the data for the INSERT is coming from a VALUES
  64770. ** clause
  64771. */
  64772. NameContext sNC;
  64773. memset(&sNC, 0, sizeof(sNC));
  64774. sNC.pParse = pParse;
  64775. srcTab = -1;
  64776. assert( useTempTable==0 );
  64777. nColumn = pList ? pList->nExpr : 0;
  64778. for(i=0; i<nColumn; i++){
  64779. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  64780. goto insert_cleanup;
  64781. }
  64782. }
  64783. }
  64784. /* Make sure the number of columns in the source data matches the number
  64785. ** of columns to be inserted into the table.
  64786. */
  64787. if( IsVirtual(pTab) ){
  64788. for(i=0; i<pTab->nCol; i++){
  64789. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  64790. }
  64791. }
  64792. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  64793. sqlite3ErrorMsg(pParse,
  64794. "table %S has %d columns but %d values were supplied",
  64795. pTabList, 0, pTab->nCol, nColumn);
  64796. goto insert_cleanup;
  64797. }
  64798. if( pColumn!=0 && nColumn!=pColumn->nId ){
  64799. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  64800. goto insert_cleanup;
  64801. }
  64802. /* If the INSERT statement included an IDLIST term, then make sure
  64803. ** all elements of the IDLIST really are columns of the table and
  64804. ** remember the column indices.
  64805. **
  64806. ** If the table has an INTEGER PRIMARY KEY column and that column
  64807. ** is named in the IDLIST, then record in the keyColumn variable
  64808. ** the index into IDLIST of the primary key column. keyColumn is
  64809. ** the index of the primary key as it appears in IDLIST, not as
  64810. ** is appears in the original table. (The index of the primary
  64811. ** key in the original table is pTab->iPKey.)
  64812. */
  64813. if( pColumn ){
  64814. for(i=0; i<pColumn->nId; i++){
  64815. pColumn->a[i].idx = -1;
  64816. }
  64817. for(i=0; i<pColumn->nId; i++){
  64818. for(j=0; j<pTab->nCol; j++){
  64819. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  64820. pColumn->a[i].idx = j;
  64821. if( j==pTab->iPKey ){
  64822. keyColumn = i;
  64823. }
  64824. break;
  64825. }
  64826. }
  64827. if( j>=pTab->nCol ){
  64828. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  64829. keyColumn = i;
  64830. }else{
  64831. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  64832. pTabList, 0, pColumn->a[i].zName);
  64833. pParse->nErr++;
  64834. goto insert_cleanup;
  64835. }
  64836. }
  64837. }
  64838. }
  64839. /* If there is no IDLIST term but the table has an integer primary
  64840. ** key, the set the keyColumn variable to the primary key column index
  64841. ** in the original table definition.
  64842. */
  64843. if( pColumn==0 && nColumn>0 ){
  64844. keyColumn = pTab->iPKey;
  64845. }
  64846. /* Open the temp table for FOR EACH ROW triggers
  64847. */
  64848. if( pTrigger ){
  64849. sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
  64850. }
  64851. /* Initialize the count of rows to be inserted
  64852. */
  64853. if( db->flags & SQLITE_CountRows ){
  64854. regRowCount = ++pParse->nMem;
  64855. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  64856. }
  64857. /* If this is not a view, open the table and and all indices */
  64858. if( !isView ){
  64859. int nIdx;
  64860. baseCur = pParse->nTab;
  64861. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  64862. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  64863. if( aRegIdx==0 ){
  64864. goto insert_cleanup;
  64865. }
  64866. for(i=0; i<nIdx; i++){
  64867. aRegIdx[i] = ++pParse->nMem;
  64868. }
  64869. }
  64870. /* This is the top of the main insertion loop */
  64871. if( useTempTable ){
  64872. /* This block codes the top of loop only. The complete loop is the
  64873. ** following pseudocode (template 4):
  64874. **
  64875. ** rewind temp table
  64876. ** C: loop over rows of intermediate table
  64877. ** transfer values form intermediate table into <table>
  64878. ** end loop
  64879. ** D: ...
  64880. */
  64881. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  64882. addrCont = sqlite3VdbeCurrentAddr(v);
  64883. }else if( pSelect ){
  64884. /* This block codes the top of loop only. The complete loop is the
  64885. ** following pseudocode (template 3):
  64886. **
  64887. ** C: yield X
  64888. ** if EOF goto D
  64889. ** insert the select result into <table> from R..R+n
  64890. ** goto C
  64891. ** D: ...
  64892. */
  64893. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
  64894. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  64895. }
  64896. /* Allocate registers for holding the rowid of the new row,
  64897. ** the content of the new row, and the assemblied row record.
  64898. */
  64899. regRecord = ++pParse->nMem;
  64900. regRowid = regIns = pParse->nMem+1;
  64901. pParse->nMem += pTab->nCol + 1;
  64902. if( IsVirtual(pTab) ){
  64903. regRowid++;
  64904. pParse->nMem++;
  64905. }
  64906. regData = regRowid+1;
  64907. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  64908. */
  64909. endOfLoop = sqlite3VdbeMakeLabel(v);
  64910. if( tmask & TRIGGER_BEFORE ){
  64911. int regTrigRowid;
  64912. int regCols;
  64913. int regRec;
  64914. /* build the NEW.* reference row. Note that if there is an INTEGER
  64915. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  64916. ** translated into a unique ID for the row. But on a BEFORE trigger,
  64917. ** we do not know what the unique ID will be (because the insert has
  64918. ** not happened yet) so we substitute a rowid of -1
  64919. */
  64920. regTrigRowid = sqlite3GetTempReg(pParse);
  64921. if( keyColumn<0 ){
  64922. sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
  64923. }else if( useTempTable ){
  64924. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
  64925. }else{
  64926. int j1;
  64927. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  64928. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
  64929. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
  64930. sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
  64931. sqlite3VdbeJumpHere(v, j1);
  64932. sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
  64933. }
  64934. /* Cannot have triggers on a virtual table. If it were possible,
  64935. ** this block would have to account for hidden column.
  64936. */
  64937. assert(!IsVirtual(pTab));
  64938. /* Create the new column data
  64939. */
  64940. regCols = sqlite3GetTempRange(pParse, pTab->nCol);
  64941. for(i=0; i<pTab->nCol; i++){
  64942. if( pColumn==0 ){
  64943. j = i;
  64944. }else{
  64945. for(j=0; j<pColumn->nId; j++){
  64946. if( pColumn->a[j].idx==i ) break;
  64947. }
  64948. }
  64949. if( pColumn && j>=pColumn->nId ){
  64950. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
  64951. }else if( useTempTable ){
  64952. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i);
  64953. }else{
  64954. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  64955. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
  64956. }
  64957. }
  64958. regRec = sqlite3GetTempReg(pParse);
  64959. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
  64960. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  64961. ** do not attempt any conversions before assembling the record.
  64962. ** If this is a real table, attempt conversions as required by the
  64963. ** table column affinities.
  64964. */
  64965. if( !isView ){
  64966. sqlite3TableAffinityStr(v, pTab);
  64967. }
  64968. sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
  64969. sqlite3ReleaseTempReg(pParse, regRec);
  64970. sqlite3ReleaseTempReg(pParse, regTrigRowid);
  64971. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
  64972. /* Fire BEFORE or INSTEAD OF triggers */
  64973. if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  64974. pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
  64975. goto insert_cleanup;
  64976. }
  64977. }
  64978. /* Push the record number for the new entry onto the stack. The
  64979. ** record number is a randomly generate integer created by NewRowid
  64980. ** except when the table has an INTEGER PRIMARY KEY column, in which
  64981. ** case the record number is the same as that column.
  64982. */
  64983. if( !isView ){
  64984. if( IsVirtual(pTab) ){
  64985. /* The row that the VUpdate opcode will delete: none */
  64986. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  64987. }
  64988. if( keyColumn>=0 ){
  64989. if( useTempTable ){
  64990. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  64991. }else if( pSelect ){
  64992. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  64993. }else{
  64994. VdbeOp *pOp;
  64995. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  64996. pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
  64997. if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  64998. appendFlag = 1;
  64999. pOp->opcode = OP_NewRowid;
  65000. pOp->p1 = baseCur;
  65001. pOp->p2 = regRowid;
  65002. pOp->p3 = regAutoinc;
  65003. }
  65004. }
  65005. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  65006. ** to generate a unique primary key value.
  65007. */
  65008. if( !appendFlag ){
  65009. int j1;
  65010. if( !IsVirtual(pTab) ){
  65011. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  65012. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  65013. sqlite3VdbeJumpHere(v, j1);
  65014. }else{
  65015. j1 = sqlite3VdbeCurrentAddr(v);
  65016. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  65017. }
  65018. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  65019. }
  65020. }else if( IsVirtual(pTab) ){
  65021. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  65022. }else{
  65023. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  65024. appendFlag = 1;
  65025. }
  65026. autoIncStep(pParse, regAutoinc, regRowid);
  65027. /* Push onto the stack, data for all columns of the new entry, beginning
  65028. ** with the first column.
  65029. */
  65030. nHidden = 0;
  65031. for(i=0; i<pTab->nCol; i++){
  65032. int iRegStore = regRowid+1+i;
  65033. if( i==pTab->iPKey ){
  65034. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  65035. ** Whenever this column is read, the record number will be substituted
  65036. ** in its place. So will fill this column with a NULL to avoid
  65037. ** taking up data space with information that will never be used. */
  65038. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  65039. continue;
  65040. }
  65041. if( pColumn==0 ){
  65042. if( IsHiddenColumn(&pTab->aCol[i]) ){
  65043. assert( IsVirtual(pTab) );
  65044. j = -1;
  65045. nHidden++;
  65046. }else{
  65047. j = i - nHidden;
  65048. }
  65049. }else{
  65050. for(j=0; j<pColumn->nId; j++){
  65051. if( pColumn->a[j].idx==i ) break;
  65052. }
  65053. }
  65054. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  65055. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  65056. }else if( useTempTable ){
  65057. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  65058. }else if( pSelect ){
  65059. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  65060. }else{
  65061. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  65062. }
  65063. }
  65064. /* Generate code to check constraints and generate index keys and
  65065. ** do the insertion.
  65066. */
  65067. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65068. if( IsVirtual(pTab) ){
  65069. sqlite3VtabMakeWritable(pParse, pTab);
  65070. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
  65071. (const char*)pTab->pVtab, P4_VTAB);
  65072. }else
  65073. #endif
  65074. {
  65075. sqlite3GenerateConstraintChecks(
  65076. pParse,
  65077. pTab,
  65078. baseCur,
  65079. regIns,
  65080. aRegIdx,
  65081. keyColumn>=0,
  65082. 0,
  65083. onError,
  65084. endOfLoop
  65085. );
  65086. sqlite3CompleteInsertion(
  65087. pParse,
  65088. pTab,
  65089. baseCur,
  65090. regIns,
  65091. aRegIdx,
  65092. 0,
  65093. (tmask&TRIGGER_AFTER) ? newIdx : -1,
  65094. appendFlag
  65095. );
  65096. }
  65097. }
  65098. /* Update the count of rows that are inserted
  65099. */
  65100. if( (db->flags & SQLITE_CountRows)!=0 ){
  65101. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  65102. }
  65103. if( pTrigger ){
  65104. /* Code AFTER triggers */
  65105. if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  65106. pTab, newIdx, -1, onError, endOfLoop, 0, 0) ){
  65107. goto insert_cleanup;
  65108. }
  65109. }
  65110. /* The bottom of the main insertion loop, if the data source
  65111. ** is a SELECT statement.
  65112. */
  65113. sqlite3VdbeResolveLabel(v, endOfLoop);
  65114. if( useTempTable ){
  65115. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  65116. sqlite3VdbeJumpHere(v, addrInsTop);
  65117. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  65118. }else if( pSelect ){
  65119. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  65120. sqlite3VdbeJumpHere(v, addrInsTop);
  65121. }
  65122. if( !IsVirtual(pTab) && !isView ){
  65123. /* Close all tables opened */
  65124. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  65125. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  65126. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  65127. }
  65128. }
  65129. /* Update the sqlite_sequence table by storing the content of the
  65130. ** counter value in memory regAutoinc back into the sqlite_sequence
  65131. ** table.
  65132. */
  65133. autoIncEnd(pParse, iDb, pTab, regAutoinc);
  65134. /*
  65135. ** Return the number of rows inserted. If this routine is
  65136. ** generating code because of a call to sqlite3NestedParse(), do not
  65137. ** invoke the callback function.
  65138. */
  65139. if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
  65140. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  65141. sqlite3VdbeSetNumCols(v, 1);
  65142. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  65143. }
  65144. insert_cleanup:
  65145. sqlite3SrcListDelete(db, pTabList);
  65146. sqlite3ExprListDelete(db, pList);
  65147. sqlite3SelectDelete(db, pSelect);
  65148. sqlite3IdListDelete(db, pColumn);
  65149. sqlite3DbFree(db, aRegIdx);
  65150. }
  65151. /*
  65152. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  65153. **
  65154. ** The input is a range of consecutive registers as follows:
  65155. **
  65156. ** 1. The rowid of the row to be updated before the update. This
  65157. ** value is omitted unless we are doing an UPDATE that involves a
  65158. ** change to the record number or writing to a virtual table.
  65159. **
  65160. ** 2. The rowid of the row after the update.
  65161. **
  65162. ** 3. The data in the first column of the entry after the update.
  65163. **
  65164. ** i. Data from middle columns...
  65165. **
  65166. ** N. The data in the last column of the entry after the update.
  65167. **
  65168. ** The regRowid parameter is the index of the register containing (2).
  65169. **
  65170. ** The old rowid shown as entry (1) above is omitted unless both isUpdate
  65171. ** and rowidChng are 1. isUpdate is true for UPDATEs and false for
  65172. ** INSERTs. RowidChng means that the new rowid is explicitly specified by
  65173. ** the update or insert statement. If rowidChng is false, it means that
  65174. ** the rowid is computed automatically in an insert or that the rowid value
  65175. ** is not modified by the update.
  65176. **
  65177. ** The code generated by this routine store new index entries into
  65178. ** registers identified by aRegIdx[]. No index entry is created for
  65179. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  65180. ** the same as the order of indices on the linked list of indices
  65181. ** attached to the table.
  65182. **
  65183. ** This routine also generates code to check constraints. NOT NULL,
  65184. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  65185. ** then the appropriate action is performed. There are five possible
  65186. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  65187. **
  65188. ** Constraint type Action What Happens
  65189. ** --------------- ---------- ----------------------------------------
  65190. ** any ROLLBACK The current transaction is rolled back and
  65191. ** sqlite3_exec() returns immediately with a
  65192. ** return code of SQLITE_CONSTRAINT.
  65193. **
  65194. ** any ABORT Back out changes from the current command
  65195. ** only (do not do a complete rollback) then
  65196. ** cause sqlite3_exec() to return immediately
  65197. ** with SQLITE_CONSTRAINT.
  65198. **
  65199. ** any FAIL Sqlite_exec() returns immediately with a
  65200. ** return code of SQLITE_CONSTRAINT. The
  65201. ** transaction is not rolled back and any
  65202. ** prior changes are retained.
  65203. **
  65204. ** any IGNORE The record number and data is popped from
  65205. ** the stack and there is an immediate jump
  65206. ** to label ignoreDest.
  65207. **
  65208. ** NOT NULL REPLACE The NULL value is replace by the default
  65209. ** value for that column. If the default value
  65210. ** is NULL, the action is the same as ABORT.
  65211. **
  65212. ** UNIQUE REPLACE The other row that conflicts with the row
  65213. ** being inserted is removed.
  65214. **
  65215. ** CHECK REPLACE Illegal. The results in an exception.
  65216. **
  65217. ** Which action to take is determined by the overrideError parameter.
  65218. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  65219. ** is used. Or if pParse->onError==OE_Default then the onError value
  65220. ** for the constraint is used.
  65221. **
  65222. ** The calling routine must open a read/write cursor for pTab with
  65223. ** cursor number "baseCur". All indices of pTab must also have open
  65224. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  65225. ** Except, if there is no possibility of a REPLACE action then
  65226. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  65227. */
  65228. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  65229. Parse *pParse, /* The parser context */
  65230. Table *pTab, /* the table into which we are inserting */
  65231. int baseCur, /* Index of a read/write cursor pointing at pTab */
  65232. int regRowid, /* Index of the range of input registers */
  65233. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  65234. int rowidChng, /* True if the rowid might collide with existing entry */
  65235. int isUpdate, /* True for UPDATE, False for INSERT */
  65236. int overrideError, /* Override onError to this if not OE_Default */
  65237. int ignoreDest /* Jump to this label on an OE_Ignore resolution */
  65238. ){
  65239. int i;
  65240. Vdbe *v;
  65241. int nCol;
  65242. int onError;
  65243. int j1; /* Addresss of jump instruction */
  65244. int j2 = 0, j3; /* Addresses of jump instructions */
  65245. int regData; /* Register containing first data column */
  65246. int iCur;
  65247. Index *pIdx;
  65248. int seenReplace = 0;
  65249. int hasTwoRowids = (isUpdate && rowidChng);
  65250. v = sqlite3GetVdbe(pParse);
  65251. assert( v!=0 );
  65252. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  65253. nCol = pTab->nCol;
  65254. regData = regRowid + 1;
  65255. /* Test all NOT NULL constraints.
  65256. */
  65257. for(i=0; i<nCol; i++){
  65258. if( i==pTab->iPKey ){
  65259. continue;
  65260. }
  65261. onError = pTab->aCol[i].notNull;
  65262. if( onError==OE_None ) continue;
  65263. if( overrideError!=OE_Default ){
  65264. onError = overrideError;
  65265. }else if( onError==OE_Default ){
  65266. onError = OE_Abort;
  65267. }
  65268. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  65269. onError = OE_Abort;
  65270. }
  65271. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  65272. || onError==OE_Ignore || onError==OE_Replace );
  65273. switch( onError ){
  65274. case OE_Rollback:
  65275. case OE_Abort:
  65276. case OE_Fail: {
  65277. char *zMsg;
  65278. j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  65279. SQLITE_CONSTRAINT, onError, regData+i);
  65280. zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
  65281. pTab->zName, pTab->aCol[i].zName);
  65282. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  65283. break;
  65284. }
  65285. case OE_Ignore: {
  65286. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  65287. break;
  65288. }
  65289. case OE_Replace: {
  65290. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  65291. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  65292. sqlite3VdbeJumpHere(v, j1);
  65293. break;
  65294. }
  65295. }
  65296. }
  65297. /* Test all CHECK constraints
  65298. */
  65299. #ifndef SQLITE_OMIT_CHECK
  65300. if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
  65301. int allOk = sqlite3VdbeMakeLabel(v);
  65302. pParse->ckBase = regData;
  65303. sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
  65304. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  65305. if( onError==OE_Ignore ){
  65306. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  65307. }else{
  65308. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  65309. }
  65310. sqlite3VdbeResolveLabel(v, allOk);
  65311. }
  65312. #endif /* !defined(SQLITE_OMIT_CHECK) */
  65313. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  65314. ** of the new record does not previously exist. Except, if this
  65315. ** is an UPDATE and the primary key is not changing, that is OK.
  65316. */
  65317. if( rowidChng ){
  65318. onError = pTab->keyConf;
  65319. if( overrideError!=OE_Default ){
  65320. onError = overrideError;
  65321. }else if( onError==OE_Default ){
  65322. onError = OE_Abort;
  65323. }
  65324. if( onError!=OE_Replace || pTab->pIndex ){
  65325. if( isUpdate ){
  65326. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
  65327. }
  65328. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  65329. switch( onError ){
  65330. default: {
  65331. onError = OE_Abort;
  65332. /* Fall thru into the next case */
  65333. }
  65334. case OE_Rollback:
  65335. case OE_Abort:
  65336. case OE_Fail: {
  65337. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
  65338. "PRIMARY KEY must be unique", P4_STATIC);
  65339. break;
  65340. }
  65341. case OE_Replace: {
  65342. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  65343. seenReplace = 1;
  65344. break;
  65345. }
  65346. case OE_Ignore: {
  65347. assert( seenReplace==0 );
  65348. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  65349. break;
  65350. }
  65351. }
  65352. sqlite3VdbeJumpHere(v, j3);
  65353. if( isUpdate ){
  65354. sqlite3VdbeJumpHere(v, j2);
  65355. }
  65356. }
  65357. }
  65358. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  65359. ** index and making sure that duplicate entries do not already exist.
  65360. ** Add the new records to the indices as we go.
  65361. */
  65362. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  65363. int regIdx;
  65364. int regR;
  65365. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  65366. /* Create a key for accessing the index entry */
  65367. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  65368. for(i=0; i<pIdx->nColumn; i++){
  65369. int idx = pIdx->aiColumn[i];
  65370. if( idx==pTab->iPKey ){
  65371. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  65372. }else{
  65373. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  65374. }
  65375. }
  65376. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  65377. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  65378. sqlite3IndexAffinityStr(v, pIdx);
  65379. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  65380. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  65381. /* Find out what action to take in case there is an indexing conflict */
  65382. onError = pIdx->onError;
  65383. if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
  65384. if( overrideError!=OE_Default ){
  65385. onError = overrideError;
  65386. }else if( onError==OE_Default ){
  65387. onError = OE_Abort;
  65388. }
  65389. if( seenReplace ){
  65390. if( onError==OE_Ignore ) onError = OE_Replace;
  65391. else if( onError==OE_Fail ) onError = OE_Abort;
  65392. }
  65393. /* Check to see if the new index entry will be unique */
  65394. j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
  65395. regR = sqlite3GetTempReg(pParse);
  65396. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
  65397. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  65398. regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
  65399. P4_INT32);
  65400. /* Generate code that executes if the new index entry is not unique */
  65401. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  65402. || onError==OE_Ignore || onError==OE_Replace );
  65403. switch( onError ){
  65404. case OE_Rollback:
  65405. case OE_Abort:
  65406. case OE_Fail: {
  65407. int j, n1, n2;
  65408. char zErrMsg[200];
  65409. sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
  65410. pIdx->nColumn>1 ? "columns " : "column ");
  65411. n1 = sqlite3Strlen30(zErrMsg);
  65412. for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
  65413. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  65414. n2 = sqlite3Strlen30(zCol);
  65415. if( j>0 ){
  65416. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
  65417. n1 += 2;
  65418. }
  65419. if( n1+n2>ArraySize(zErrMsg)-30 ){
  65420. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
  65421. n1 += 3;
  65422. break;
  65423. }else{
  65424. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
  65425. n1 += n2;
  65426. }
  65427. }
  65428. sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
  65429. pIdx->nColumn>1 ? " are not unique" : " is not unique");
  65430. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
  65431. break;
  65432. }
  65433. case OE_Ignore: {
  65434. assert( seenReplace==0 );
  65435. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  65436. break;
  65437. }
  65438. case OE_Replace: {
  65439. sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
  65440. seenReplace = 1;
  65441. break;
  65442. }
  65443. }
  65444. sqlite3VdbeJumpHere(v, j2);
  65445. sqlite3VdbeJumpHere(v, j3);
  65446. sqlite3ReleaseTempReg(pParse, regR);
  65447. }
  65448. }
  65449. /*
  65450. ** This routine generates code to finish the INSERT or UPDATE operation
  65451. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  65452. ** A consecutive range of registers starting at regRowid contains the
  65453. ** rowid and the content to be inserted.
  65454. **
  65455. ** The arguments to this routine should be the same as the first six
  65456. ** arguments to sqlite3GenerateConstraintChecks.
  65457. */
  65458. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  65459. Parse *pParse, /* The parser context */
  65460. Table *pTab, /* the table into which we are inserting */
  65461. int baseCur, /* Index of a read/write cursor pointing at pTab */
  65462. int regRowid, /* Range of content */
  65463. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  65464. int isUpdate, /* True for UPDATE, False for INSERT */
  65465. int newIdx, /* Index of NEW table for triggers. -1 if none */
  65466. int appendBias /* True if this is likely to be an append */
  65467. ){
  65468. int i;
  65469. Vdbe *v;
  65470. int nIdx;
  65471. Index *pIdx;
  65472. u8 pik_flags;
  65473. int regData;
  65474. int regRec;
  65475. v = sqlite3GetVdbe(pParse);
  65476. assert( v!=0 );
  65477. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  65478. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  65479. for(i=nIdx-1; i>=0; i--){
  65480. if( aRegIdx[i]==0 ) continue;
  65481. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  65482. }
  65483. regData = regRowid + 1;
  65484. regRec = sqlite3GetTempReg(pParse);
  65485. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  65486. sqlite3TableAffinityStr(v, pTab);
  65487. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  65488. #ifndef SQLITE_OMIT_TRIGGER
  65489. if( newIdx>=0 ){
  65490. sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
  65491. }
  65492. #endif
  65493. if( pParse->nested ){
  65494. pik_flags = 0;
  65495. }else{
  65496. pik_flags = OPFLAG_NCHANGE;
  65497. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  65498. }
  65499. if( appendBias ){
  65500. pik_flags |= OPFLAG_APPEND;
  65501. }
  65502. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  65503. if( !pParse->nested ){
  65504. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
  65505. }
  65506. sqlite3VdbeChangeP5(v, pik_flags);
  65507. }
  65508. /*
  65509. ** Generate code that will open cursors for a table and for all
  65510. ** indices of that table. The "baseCur" parameter is the cursor number used
  65511. ** for the table. Indices are opened on subsequent cursors.
  65512. **
  65513. ** Return the number of indices on the table.
  65514. */
  65515. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  65516. Parse *pParse, /* Parsing context */
  65517. Table *pTab, /* Table to be opened */
  65518. int baseCur, /* Cursor number assigned to the table */
  65519. int op /* OP_OpenRead or OP_OpenWrite */
  65520. ){
  65521. int i;
  65522. int iDb;
  65523. Index *pIdx;
  65524. Vdbe *v;
  65525. if( IsVirtual(pTab) ) return 0;
  65526. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  65527. v = sqlite3GetVdbe(pParse);
  65528. assert( v!=0 );
  65529. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  65530. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  65531. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  65532. assert( pIdx->pSchema==pTab->pSchema );
  65533. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  65534. (char*)pKey, P4_KEYINFO_HANDOFF);
  65535. VdbeComment((v, "%s", pIdx->zName));
  65536. }
  65537. if( pParse->nTab<=baseCur+i ){
  65538. pParse->nTab = baseCur+i;
  65539. }
  65540. return i-1;
  65541. }
  65542. #ifdef SQLITE_TEST
  65543. /*
  65544. ** The following global variable is incremented whenever the
  65545. ** transfer optimization is used. This is used for testing
  65546. ** purposes only - to make sure the transfer optimization really
  65547. ** is happening when it is suppose to.
  65548. */
  65549. SQLITE_API int sqlite3_xferopt_count;
  65550. #endif /* SQLITE_TEST */
  65551. #ifndef SQLITE_OMIT_XFER_OPT
  65552. /*
  65553. ** Check to collation names to see if they are compatible.
  65554. */
  65555. static int xferCompatibleCollation(const char *z1, const char *z2){
  65556. if( z1==0 ){
  65557. return z2==0;
  65558. }
  65559. if( z2==0 ){
  65560. return 0;
  65561. }
  65562. return sqlite3StrICmp(z1, z2)==0;
  65563. }
  65564. /*
  65565. ** Check to see if index pSrc is compatible as a source of data
  65566. ** for index pDest in an insert transfer optimization. The rules
  65567. ** for a compatible index:
  65568. **
  65569. ** * The index is over the same set of columns
  65570. ** * The same DESC and ASC markings occurs on all columns
  65571. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  65572. ** * The same collating sequence on each column
  65573. */
  65574. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  65575. int i;
  65576. assert( pDest && pSrc );
  65577. assert( pDest->pTable!=pSrc->pTable );
  65578. if( pDest->nColumn!=pSrc->nColumn ){
  65579. return 0; /* Different number of columns */
  65580. }
  65581. if( pDest->onError!=pSrc->onError ){
  65582. return 0; /* Different conflict resolution strategies */
  65583. }
  65584. for(i=0; i<pSrc->nColumn; i++){
  65585. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  65586. return 0; /* Different columns indexed */
  65587. }
  65588. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  65589. return 0; /* Different sort orders */
  65590. }
  65591. if( pSrc->azColl[i]!=pDest->azColl[i] ){
  65592. return 0; /* Different collating sequences */
  65593. }
  65594. }
  65595. /* If no test above fails then the indices must be compatible */
  65596. return 1;
  65597. }
  65598. /*
  65599. ** Attempt the transfer optimization on INSERTs of the form
  65600. **
  65601. ** INSERT INTO tab1 SELECT * FROM tab2;
  65602. **
  65603. ** This optimization is only attempted if
  65604. **
  65605. ** (1) tab1 and tab2 have identical schemas including all the
  65606. ** same indices and constraints
  65607. **
  65608. ** (2) tab1 and tab2 are different tables
  65609. **
  65610. ** (3) There must be no triggers on tab1
  65611. **
  65612. ** (4) The result set of the SELECT statement is "*"
  65613. **
  65614. ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
  65615. ** or LIMIT clause.
  65616. **
  65617. ** (6) The SELECT statement is a simple (not a compound) select that
  65618. ** contains only tab2 in its FROM clause
  65619. **
  65620. ** This method for implementing the INSERT transfers raw records from
  65621. ** tab2 over to tab1. The columns are not decoded. Raw records from
  65622. ** the indices of tab2 are transfered to tab1 as well. In so doing,
  65623. ** the resulting tab1 has much less fragmentation.
  65624. **
  65625. ** This routine returns TRUE if the optimization is attempted. If any
  65626. ** of the conditions above fail so that the optimization should not
  65627. ** be attempted, then this routine returns FALSE.
  65628. */
  65629. static int xferOptimization(
  65630. Parse *pParse, /* Parser context */
  65631. Table *pDest, /* The table we are inserting into */
  65632. Select *pSelect, /* A SELECT statement to use as the data source */
  65633. int onError, /* How to handle constraint errors */
  65634. int iDbDest /* The database of pDest */
  65635. ){
  65636. ExprList *pEList; /* The result set of the SELECT */
  65637. Table *pSrc; /* The table in the FROM clause of SELECT */
  65638. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  65639. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  65640. int i; /* Loop counter */
  65641. int iDbSrc; /* The database of pSrc */
  65642. int iSrc, iDest; /* Cursors from source and destination */
  65643. int addr1, addr2; /* Loop addresses */
  65644. int emptyDestTest; /* Address of test for empty pDest */
  65645. int emptySrcTest; /* Address of test for empty pSrc */
  65646. Vdbe *v; /* The VDBE we are building */
  65647. KeyInfo *pKey; /* Key information for an index */
  65648. int regAutoinc; /* Memory register used by AUTOINC */
  65649. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  65650. int regData, regRowid; /* Registers holding data and rowid */
  65651. if( pSelect==0 ){
  65652. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  65653. }
  65654. if( sqlite3TriggerList(pParse, pDest) ){
  65655. return 0; /* tab1 must not have triggers */
  65656. }
  65657. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65658. if( pDest->tabFlags & TF_Virtual ){
  65659. return 0; /* tab1 must not be a virtual table */
  65660. }
  65661. #endif
  65662. if( onError==OE_Default ){
  65663. onError = OE_Abort;
  65664. }
  65665. if( onError!=OE_Abort && onError!=OE_Rollback ){
  65666. return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
  65667. }
  65668. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  65669. if( pSelect->pSrc->nSrc!=1 ){
  65670. return 0; /* FROM clause must have exactly one term */
  65671. }
  65672. if( pSelect->pSrc->a[0].pSelect ){
  65673. return 0; /* FROM clause cannot contain a subquery */
  65674. }
  65675. if( pSelect->pWhere ){
  65676. return 0; /* SELECT may not have a WHERE clause */
  65677. }
  65678. if( pSelect->pOrderBy ){
  65679. return 0; /* SELECT may not have an ORDER BY clause */
  65680. }
  65681. /* Do not need to test for a HAVING clause. If HAVING is present but
  65682. ** there is no ORDER BY, we will get an error. */
  65683. if( pSelect->pGroupBy ){
  65684. return 0; /* SELECT may not have a GROUP BY clause */
  65685. }
  65686. if( pSelect->pLimit ){
  65687. return 0; /* SELECT may not have a LIMIT clause */
  65688. }
  65689. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  65690. if( pSelect->pPrior ){
  65691. return 0; /* SELECT may not be a compound query */
  65692. }
  65693. if( pSelect->selFlags & SF_Distinct ){
  65694. return 0; /* SELECT may not be DISTINCT */
  65695. }
  65696. pEList = pSelect->pEList;
  65697. assert( pEList!=0 );
  65698. if( pEList->nExpr!=1 ){
  65699. return 0; /* The result set must have exactly one column */
  65700. }
  65701. assert( pEList->a[0].pExpr );
  65702. if( pEList->a[0].pExpr->op!=TK_ALL ){
  65703. return 0; /* The result set must be the special operator "*" */
  65704. }
  65705. /* At this point we have established that the statement is of the
  65706. ** correct syntactic form to participate in this optimization. Now
  65707. ** we have to check the semantics.
  65708. */
  65709. pItem = pSelect->pSrc->a;
  65710. pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  65711. if( pSrc==0 ){
  65712. return 0; /* FROM clause does not contain a real table */
  65713. }
  65714. if( pSrc==pDest ){
  65715. return 0; /* tab1 and tab2 may not be the same table */
  65716. }
  65717. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65718. if( pSrc->tabFlags & TF_Virtual ){
  65719. return 0; /* tab2 must not be a virtual table */
  65720. }
  65721. #endif
  65722. if( pSrc->pSelect ){
  65723. return 0; /* tab2 may not be a view */
  65724. }
  65725. if( pDest->nCol!=pSrc->nCol ){
  65726. return 0; /* Number of columns must be the same in tab1 and tab2 */
  65727. }
  65728. if( pDest->iPKey!=pSrc->iPKey ){
  65729. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  65730. }
  65731. for(i=0; i<pDest->nCol; i++){
  65732. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  65733. return 0; /* Affinity must be the same on all columns */
  65734. }
  65735. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  65736. return 0; /* Collating sequence must be the same on all columns */
  65737. }
  65738. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  65739. return 0; /* tab2 must be NOT NULL if tab1 is */
  65740. }
  65741. }
  65742. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  65743. if( pDestIdx->onError!=OE_None ){
  65744. destHasUniqueIdx = 1;
  65745. }
  65746. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  65747. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  65748. }
  65749. if( pSrcIdx==0 ){
  65750. return 0; /* pDestIdx has no corresponding index in pSrc */
  65751. }
  65752. }
  65753. #ifndef SQLITE_OMIT_CHECK
  65754. if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
  65755. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  65756. }
  65757. #endif
  65758. /* If we get this far, it means either:
  65759. **
  65760. ** * We can always do the transfer if the table contains an
  65761. ** an integer primary key
  65762. **
  65763. ** * We can conditionally do the transfer if the destination
  65764. ** table is empty.
  65765. */
  65766. #ifdef SQLITE_TEST
  65767. sqlite3_xferopt_count++;
  65768. #endif
  65769. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  65770. v = sqlite3GetVdbe(pParse);
  65771. sqlite3CodeVerifySchema(pParse, iDbSrc);
  65772. iSrc = pParse->nTab++;
  65773. iDest = pParse->nTab++;
  65774. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  65775. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  65776. if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
  65777. /* If tables do not have an INTEGER PRIMARY KEY and there
  65778. ** are indices to be copied and the destination is not empty,
  65779. ** we have to disallow the transfer optimization because the
  65780. ** the rowids might change which will mess up indexing.
  65781. **
  65782. ** Or if the destination has a UNIQUE index and is not empty,
  65783. ** we also disallow the transfer optimization because we cannot
  65784. ** insure that all entries in the union of DEST and SRC will be
  65785. ** unique.
  65786. */
  65787. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  65788. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  65789. sqlite3VdbeJumpHere(v, addr1);
  65790. }else{
  65791. emptyDestTest = 0;
  65792. }
  65793. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  65794. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  65795. regData = sqlite3GetTempReg(pParse);
  65796. regRowid = sqlite3GetTempReg(pParse);
  65797. if( pDest->iPKey>=0 ){
  65798. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  65799. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  65800. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
  65801. "PRIMARY KEY must be unique", P4_STATIC);
  65802. sqlite3VdbeJumpHere(v, addr2);
  65803. autoIncStep(pParse, regAutoinc, regRowid);
  65804. }else if( pDest->pIndex==0 ){
  65805. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  65806. }else{
  65807. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  65808. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  65809. }
  65810. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  65811. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  65812. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  65813. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  65814. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  65815. autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
  65816. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  65817. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  65818. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  65819. }
  65820. assert( pSrcIdx );
  65821. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  65822. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  65823. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  65824. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  65825. (char*)pKey, P4_KEYINFO_HANDOFF);
  65826. VdbeComment((v, "%s", pSrcIdx->zName));
  65827. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  65828. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  65829. (char*)pKey, P4_KEYINFO_HANDOFF);
  65830. VdbeComment((v, "%s", pDestIdx->zName));
  65831. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  65832. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  65833. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  65834. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  65835. sqlite3VdbeJumpHere(v, addr1);
  65836. }
  65837. sqlite3VdbeJumpHere(v, emptySrcTest);
  65838. sqlite3ReleaseTempReg(pParse, regRowid);
  65839. sqlite3ReleaseTempReg(pParse, regData);
  65840. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  65841. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  65842. if( emptyDestTest ){
  65843. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  65844. sqlite3VdbeJumpHere(v, emptyDestTest);
  65845. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  65846. return 0;
  65847. }else{
  65848. return 1;
  65849. }
  65850. }
  65851. #endif /* SQLITE_OMIT_XFER_OPT */
  65852. /* Make sure "isView" gets undefined in case this file becomes part of
  65853. ** the amalgamation - so that subsequent files do not see isView as a
  65854. ** macro. */
  65855. #undef isView
  65856. /************** End of insert.c **********************************************/
  65857. /************** Begin file legacy.c ******************************************/
  65858. /*
  65859. ** 2001 September 15
  65860. **
  65861. ** The author disclaims copyright to this source code. In place of
  65862. ** a legal notice, here is a blessing:
  65863. **
  65864. ** May you do good and not evil.
  65865. ** May you find forgiveness for yourself and forgive others.
  65866. ** May you share freely, never taking more than you give.
  65867. **
  65868. *************************************************************************
  65869. ** Main file for the SQLite library. The routines in this file
  65870. ** implement the programmer interface to the library. Routines in
  65871. ** other files are for internal use by SQLite and should not be
  65872. ** accessed by users of the library.
  65873. **
  65874. ** $Id: legacy.c,v 1.32 2009/03/19 18:51:07 danielk1977 Exp $
  65875. */
  65876. /*
  65877. ** Execute SQL code. Return one of the SQLITE_ success/failure
  65878. ** codes. Also write an error message into memory obtained from
  65879. ** malloc() and make *pzErrMsg point to that message.
  65880. **
  65881. ** If the SQL is a query, then for each row in the query result
  65882. ** the xCallback() function is called. pArg becomes the first
  65883. ** argument to xCallback(). If xCallback=NULL then no callback
  65884. ** is invoked, even for queries.
  65885. */
  65886. SQLITE_API int sqlite3_exec(
  65887. sqlite3 *db, /* The database on which the SQL executes */
  65888. const char *zSql, /* The SQL to be executed */
  65889. sqlite3_callback xCallback, /* Invoke this callback routine */
  65890. void *pArg, /* First argument to xCallback() */
  65891. char **pzErrMsg /* Write error messages here */
  65892. ){
  65893. int rc = SQLITE_OK;
  65894. const char *zLeftover;
  65895. sqlite3_stmt *pStmt = 0;
  65896. char **azCols = 0;
  65897. int nRetry = 0;
  65898. int nCallback;
  65899. if( zSql==0 ) zSql = "";
  65900. sqlite3_mutex_enter(db->mutex);
  65901. sqlite3Error(db, SQLITE_OK, 0);
  65902. while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
  65903. int nCol;
  65904. char **azVals = 0;
  65905. pStmt = 0;
  65906. rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
  65907. assert( rc==SQLITE_OK || pStmt==0 );
  65908. if( rc!=SQLITE_OK ){
  65909. continue;
  65910. }
  65911. if( !pStmt ){
  65912. /* this happens for a comment or white-space */
  65913. zSql = zLeftover;
  65914. continue;
  65915. }
  65916. nCallback = 0;
  65917. nCol = sqlite3_column_count(pStmt);
  65918. while( 1 ){
  65919. int i;
  65920. rc = sqlite3_step(pStmt);
  65921. /* Invoke the callback function if required */
  65922. if( xCallback && (SQLITE_ROW==rc ||
  65923. (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
  65924. if( 0==nCallback ){
  65925. if( azCols==0 ){
  65926. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  65927. if( azCols==0 ){
  65928. goto exec_out;
  65929. }
  65930. }
  65931. for(i=0; i<nCol; i++){
  65932. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  65933. /* sqlite3VdbeSetColName() installs column names as UTF8
  65934. ** strings so there is no way for sqlite3_column_name() to fail. */
  65935. assert( azCols[i]!=0 );
  65936. }
  65937. nCallback++;
  65938. }
  65939. if( rc==SQLITE_ROW ){
  65940. azVals = &azCols[nCol];
  65941. for(i=0; i<nCol; i++){
  65942. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  65943. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  65944. db->mallocFailed = 1;
  65945. goto exec_out;
  65946. }
  65947. }
  65948. }
  65949. if( xCallback(pArg, nCol, azVals, azCols) ){
  65950. rc = SQLITE_ABORT;
  65951. sqlite3VdbeFinalize((Vdbe *)pStmt);
  65952. pStmt = 0;
  65953. sqlite3Error(db, SQLITE_ABORT, 0);
  65954. goto exec_out;
  65955. }
  65956. }
  65957. if( rc!=SQLITE_ROW ){
  65958. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  65959. pStmt = 0;
  65960. if( rc!=SQLITE_SCHEMA ){
  65961. nRetry = 0;
  65962. zSql = zLeftover;
  65963. while( sqlite3Isspace(zSql[0]) ) zSql++;
  65964. }
  65965. break;
  65966. }
  65967. }
  65968. sqlite3DbFree(db, azCols);
  65969. azCols = 0;
  65970. }
  65971. exec_out:
  65972. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  65973. sqlite3DbFree(db, azCols);
  65974. rc = sqlite3ApiExit(db, rc);
  65975. if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
  65976. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  65977. *pzErrMsg = sqlite3Malloc(nErrMsg);
  65978. if( *pzErrMsg ){
  65979. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  65980. }
  65981. }else if( pzErrMsg ){
  65982. *pzErrMsg = 0;
  65983. }
  65984. assert( (rc&db->errMask)==rc );
  65985. sqlite3_mutex_leave(db->mutex);
  65986. return rc;
  65987. }
  65988. /************** End of legacy.c **********************************************/
  65989. /************** Begin file loadext.c *****************************************/
  65990. /*
  65991. ** 2006 June 7
  65992. **
  65993. ** The author disclaims copyright to this source code. In place of
  65994. ** a legal notice, here is a blessing:
  65995. **
  65996. ** May you do good and not evil.
  65997. ** May you find forgiveness for yourself and forgive others.
  65998. ** May you share freely, never taking more than you give.
  65999. **
  66000. *************************************************************************
  66001. ** This file contains code used to dynamically load extensions into
  66002. ** the SQLite library.
  66003. **
  66004. ** $Id: loadext.c,v 1.58 2009/01/20 16:53:40 danielk1977 Exp $
  66005. */
  66006. #ifndef SQLITE_CORE
  66007. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  66008. #endif
  66009. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  66010. /************** Begin file sqlite3ext.h **************************************/
  66011. /*
  66012. ** 2006 June 7
  66013. **
  66014. ** The author disclaims copyright to this source code. In place of
  66015. ** a legal notice, here is a blessing:
  66016. **
  66017. ** May you do good and not evil.
  66018. ** May you find forgiveness for yourself and forgive others.
  66019. ** May you share freely, never taking more than you give.
  66020. **
  66021. *************************************************************************
  66022. ** This header file defines the SQLite interface for use by
  66023. ** shared libraries that want to be imported as extensions into
  66024. ** an SQLite instance. Shared libraries that intend to be loaded
  66025. ** as extensions by SQLite should #include this file instead of
  66026. ** sqlite3.h.
  66027. **
  66028. ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $
  66029. */
  66030. #ifndef _SQLite3EXT_H_
  66031. #define _SQLite3EXT_H_
  66032. typedef struct sqlite3_api_routines sqlite3_api_routines;
  66033. /*
  66034. ** The following structure holds pointers to all of the SQLite API
  66035. ** routines.
  66036. **
  66037. ** WARNING: In order to maintain backwards compatibility, add new
  66038. ** interfaces to the end of this structure only. If you insert new
  66039. ** interfaces in the middle of this structure, then older different
  66040. ** versions of SQLite will not be able to load each others' shared
  66041. ** libraries!
  66042. */
  66043. struct sqlite3_api_routines {
  66044. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  66045. int (*aggregate_count)(sqlite3_context*);
  66046. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  66047. int (*bind_double)(sqlite3_stmt*,int,double);
  66048. int (*bind_int)(sqlite3_stmt*,int,int);
  66049. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  66050. int (*bind_null)(sqlite3_stmt*,int);
  66051. int (*bind_parameter_count)(sqlite3_stmt*);
  66052. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  66053. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  66054. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  66055. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  66056. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  66057. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  66058. int (*busy_timeout)(sqlite3*,int ms);
  66059. int (*changes)(sqlite3*);
  66060. int (*close)(sqlite3*);
  66061. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
  66062. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
  66063. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  66064. int (*column_bytes)(sqlite3_stmt*,int iCol);
  66065. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  66066. int (*column_count)(sqlite3_stmt*pStmt);
  66067. const char * (*column_database_name)(sqlite3_stmt*,int);
  66068. const void * (*column_database_name16)(sqlite3_stmt*,int);
  66069. const char * (*column_decltype)(sqlite3_stmt*,int i);
  66070. const void * (*column_decltype16)(sqlite3_stmt*,int);
  66071. double (*column_double)(sqlite3_stmt*,int iCol);
  66072. int (*column_int)(sqlite3_stmt*,int iCol);
  66073. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  66074. const char * (*column_name)(sqlite3_stmt*,int);
  66075. const void * (*column_name16)(sqlite3_stmt*,int);
  66076. const char * (*column_origin_name)(sqlite3_stmt*,int);
  66077. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  66078. const char * (*column_table_name)(sqlite3_stmt*,int);
  66079. const void * (*column_table_name16)(sqlite3_stmt*,int);
  66080. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  66081. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  66082. int (*column_type)(sqlite3_stmt*,int iCol);
  66083. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  66084. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  66085. int (*complete)(const char*sql);
  66086. int (*complete16)(const void*sql);
  66087. int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
  66088. int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
  66089. int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  66090. int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  66091. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  66092. int (*data_count)(sqlite3_stmt*pStmt);
  66093. sqlite3 * (*db_handle)(sqlite3_stmt*);
  66094. int (*declare_vtab)(sqlite3*,const char*);
  66095. int (*enable_shared_cache)(int);
  66096. int (*errcode)(sqlite3*db);
  66097. const char * (*errmsg)(sqlite3*);
  66098. const void * (*errmsg16)(sqlite3*);
  66099. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  66100. int (*expired)(sqlite3_stmt*);
  66101. int (*finalize)(sqlite3_stmt*pStmt);
  66102. void (*free)(void*);
  66103. void (*free_table)(char**result);
  66104. int (*get_autocommit)(sqlite3*);
  66105. void * (*get_auxdata)(sqlite3_context*,int);
  66106. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  66107. int (*global_recover)(void);
  66108. void (*interruptx)(sqlite3*);
  66109. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  66110. const char * (*libversion)(void);
  66111. int (*libversion_number)(void);
  66112. void *(*malloc)(int);
  66113. char * (*mprintf)(const char*,...);
  66114. int (*open)(const char*,sqlite3**);
  66115. int (*open16)(const void*,sqlite3**);
  66116. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  66117. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  66118. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  66119. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  66120. void *(*realloc)(void*,int);
  66121. int (*reset)(sqlite3_stmt*pStmt);
  66122. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  66123. void (*result_double)(sqlite3_context*,double);
  66124. void (*result_error)(sqlite3_context*,const char*,int);
  66125. void (*result_error16)(sqlite3_context*,const void*,int);
  66126. void (*result_int)(sqlite3_context*,int);
  66127. void (*result_int64)(sqlite3_context*,sqlite_int64);
  66128. void (*result_null)(sqlite3_context*);
  66129. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  66130. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  66131. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  66132. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  66133. void (*result_value)(sqlite3_context*,sqlite3_value*);
  66134. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  66135. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
  66136. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  66137. char * (*snprintf)(int,char*,const char*,...);
  66138. int (*step)(sqlite3_stmt*);
  66139. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
  66140. void (*thread_cleanup)(void);
  66141. int (*total_changes)(sqlite3*);
  66142. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  66143. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  66144. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
  66145. void * (*user_data)(sqlite3_context*);
  66146. const void * (*value_blob)(sqlite3_value*);
  66147. int (*value_bytes)(sqlite3_value*);
  66148. int (*value_bytes16)(sqlite3_value*);
  66149. double (*value_double)(sqlite3_value*);
  66150. int (*value_int)(sqlite3_value*);
  66151. sqlite_int64 (*value_int64)(sqlite3_value*);
  66152. int (*value_numeric_type)(sqlite3_value*);
  66153. const unsigned char * (*value_text)(sqlite3_value*);
  66154. const void * (*value_text16)(sqlite3_value*);
  66155. const void * (*value_text16be)(sqlite3_value*);
  66156. const void * (*value_text16le)(sqlite3_value*);
  66157. int (*value_type)(sqlite3_value*);
  66158. char *(*vmprintf)(const char*,va_list);
  66159. /* Added ??? */
  66160. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  66161. /* Added by 3.3.13 */
  66162. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  66163. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  66164. int (*clear_bindings)(sqlite3_stmt*);
  66165. /* Added by 3.4.1 */
  66166. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
  66167. /* Added by 3.5.0 */
  66168. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  66169. int (*blob_bytes)(sqlite3_blob*);
  66170. int (*blob_close)(sqlite3_blob*);
  66171. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
  66172. int (*blob_read)(sqlite3_blob*,void*,int,int);
  66173. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  66174. int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
  66175. int (*file_control)(sqlite3*,const char*,int,void*);
  66176. sqlite3_int64 (*memory_highwater)(int);
  66177. sqlite3_int64 (*memory_used)(void);
  66178. sqlite3_mutex *(*mutex_alloc)(int);
  66179. void (*mutex_enter)(sqlite3_mutex*);
  66180. void (*mutex_free)(sqlite3_mutex*);
  66181. void (*mutex_leave)(sqlite3_mutex*);
  66182. int (*mutex_try)(sqlite3_mutex*);
  66183. int (*open_v2)(const char*,sqlite3**,int,const char*);
  66184. int (*release_memory)(int);
  66185. void (*result_error_nomem)(sqlite3_context*);
  66186. void (*result_error_toobig)(sqlite3_context*);
  66187. int (*sleep)(int);
  66188. void (*soft_heap_limit)(int);
  66189. sqlite3_vfs *(*vfs_find)(const char*);
  66190. int (*vfs_register)(sqlite3_vfs*,int);
  66191. int (*vfs_unregister)(sqlite3_vfs*);
  66192. int (*xthreadsafe)(void);
  66193. void (*result_zeroblob)(sqlite3_context*,int);
  66194. void (*result_error_code)(sqlite3_context*,int);
  66195. int (*test_control)(int, ...);
  66196. void (*randomness)(int,void*);
  66197. sqlite3 *(*context_db_handle)(sqlite3_context*);
  66198. int (*extended_result_codes)(sqlite3*,int);
  66199. int (*limit)(sqlite3*,int,int);
  66200. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  66201. const char *(*sql)(sqlite3_stmt*);
  66202. int (*status)(int,int*,int*,int);
  66203. };
  66204. /*
  66205. ** The following macros redefine the API routines so that they are
  66206. ** redirected throught the global sqlite3_api structure.
  66207. **
  66208. ** This header file is also used by the loadext.c source file
  66209. ** (part of the main SQLite library - not an extension) so that
  66210. ** it can get access to the sqlite3_api_routines structure
  66211. ** definition. But the main library does not want to redefine
  66212. ** the API. So the redefinition macros are only valid if the
  66213. ** SQLITE_CORE macros is undefined.
  66214. */
  66215. #ifndef SQLITE_CORE
  66216. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  66217. #ifndef SQLITE_OMIT_DEPRECATED
  66218. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  66219. #endif
  66220. #define sqlite3_bind_blob sqlite3_api->bind_blob
  66221. #define sqlite3_bind_double sqlite3_api->bind_double
  66222. #define sqlite3_bind_int sqlite3_api->bind_int
  66223. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  66224. #define sqlite3_bind_null sqlite3_api->bind_null
  66225. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  66226. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  66227. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  66228. #define sqlite3_bind_text sqlite3_api->bind_text
  66229. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  66230. #define sqlite3_bind_value sqlite3_api->bind_value
  66231. #define sqlite3_busy_handler sqlite3_api->busy_handler
  66232. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  66233. #define sqlite3_changes sqlite3_api->changes
  66234. #define sqlite3_close sqlite3_api->close
  66235. #define sqlite3_collation_needed sqlite3_api->collation_needed
  66236. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  66237. #define sqlite3_column_blob sqlite3_api->column_blob
  66238. #define sqlite3_column_bytes sqlite3_api->column_bytes
  66239. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  66240. #define sqlite3_column_count sqlite3_api->column_count
  66241. #define sqlite3_column_database_name sqlite3_api->column_database_name
  66242. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  66243. #define sqlite3_column_decltype sqlite3_api->column_decltype
  66244. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  66245. #define sqlite3_column_double sqlite3_api->column_double
  66246. #define sqlite3_column_int sqlite3_api->column_int
  66247. #define sqlite3_column_int64 sqlite3_api->column_int64
  66248. #define sqlite3_column_name sqlite3_api->column_name
  66249. #define sqlite3_column_name16 sqlite3_api->column_name16
  66250. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  66251. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  66252. #define sqlite3_column_table_name sqlite3_api->column_table_name
  66253. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  66254. #define sqlite3_column_text sqlite3_api->column_text
  66255. #define sqlite3_column_text16 sqlite3_api->column_text16
  66256. #define sqlite3_column_type sqlite3_api->column_type
  66257. #define sqlite3_column_value sqlite3_api->column_value
  66258. #define sqlite3_commit_hook sqlite3_api->commit_hook
  66259. #define sqlite3_complete sqlite3_api->complete
  66260. #define sqlite3_complete16 sqlite3_api->complete16
  66261. #define sqlite3_create_collation sqlite3_api->create_collation
  66262. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  66263. #define sqlite3_create_function sqlite3_api->create_function
  66264. #define sqlite3_create_function16 sqlite3_api->create_function16
  66265. #define sqlite3_create_module sqlite3_api->create_module
  66266. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  66267. #define sqlite3_data_count sqlite3_api->data_count
  66268. #define sqlite3_db_handle sqlite3_api->db_handle
  66269. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  66270. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  66271. #define sqlite3_errcode sqlite3_api->errcode
  66272. #define sqlite3_errmsg sqlite3_api->errmsg
  66273. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  66274. #define sqlite3_exec sqlite3_api->exec
  66275. #ifndef SQLITE_OMIT_DEPRECATED
  66276. #define sqlite3_expired sqlite3_api->expired
  66277. #endif
  66278. #define sqlite3_finalize sqlite3_api->finalize
  66279. #define sqlite3_free sqlite3_api->free
  66280. #define sqlite3_free_table sqlite3_api->free_table
  66281. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  66282. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  66283. #define sqlite3_get_table sqlite3_api->get_table
  66284. #ifndef SQLITE_OMIT_DEPRECATED
  66285. #define sqlite3_global_recover sqlite3_api->global_recover
  66286. #endif
  66287. #define sqlite3_interrupt sqlite3_api->interruptx
  66288. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  66289. #define sqlite3_libversion sqlite3_api->libversion
  66290. #define sqlite3_libversion_number sqlite3_api->libversion_number
  66291. #define sqlite3_malloc sqlite3_api->malloc
  66292. #define sqlite3_mprintf sqlite3_api->mprintf
  66293. #define sqlite3_open sqlite3_api->open
  66294. #define sqlite3_open16 sqlite3_api->open16
  66295. #define sqlite3_prepare sqlite3_api->prepare
  66296. #define sqlite3_prepare16 sqlite3_api->prepare16
  66297. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  66298. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  66299. #define sqlite3_profile sqlite3_api->profile
  66300. #define sqlite3_progress_handler sqlite3_api->progress_handler
  66301. #define sqlite3_realloc sqlite3_api->realloc
  66302. #define sqlite3_reset sqlite3_api->reset
  66303. #define sqlite3_result_blob sqlite3_api->result_blob
  66304. #define sqlite3_result_double sqlite3_api->result_double
  66305. #define sqlite3_result_error sqlite3_api->result_error
  66306. #define sqlite3_result_error16 sqlite3_api->result_error16
  66307. #define sqlite3_result_int sqlite3_api->result_int
  66308. #define sqlite3_result_int64 sqlite3_api->result_int64
  66309. #define sqlite3_result_null sqlite3_api->result_null
  66310. #define sqlite3_result_text sqlite3_api->result_text
  66311. #define sqlite3_result_text16 sqlite3_api->result_text16
  66312. #define sqlite3_result_text16be sqlite3_api->result_text16be
  66313. #define sqlite3_result_text16le sqlite3_api->result_text16le
  66314. #define sqlite3_result_value sqlite3_api->result_value
  66315. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  66316. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  66317. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  66318. #define sqlite3_snprintf sqlite3_api->snprintf
  66319. #define sqlite3_step sqlite3_api->step
  66320. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  66321. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  66322. #define sqlite3_total_changes sqlite3_api->total_changes
  66323. #define sqlite3_trace sqlite3_api->trace
  66324. #ifndef SQLITE_OMIT_DEPRECATED
  66325. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  66326. #endif
  66327. #define sqlite3_update_hook sqlite3_api->update_hook
  66328. #define sqlite3_user_data sqlite3_api->user_data
  66329. #define sqlite3_value_blob sqlite3_api->value_blob
  66330. #define sqlite3_value_bytes sqlite3_api->value_bytes
  66331. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  66332. #define sqlite3_value_double sqlite3_api->value_double
  66333. #define sqlite3_value_int sqlite3_api->value_int
  66334. #define sqlite3_value_int64 sqlite3_api->value_int64
  66335. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  66336. #define sqlite3_value_text sqlite3_api->value_text
  66337. #define sqlite3_value_text16 sqlite3_api->value_text16
  66338. #define sqlite3_value_text16be sqlite3_api->value_text16be
  66339. #define sqlite3_value_text16le sqlite3_api->value_text16le
  66340. #define sqlite3_value_type sqlite3_api->value_type
  66341. #define sqlite3_vmprintf sqlite3_api->vmprintf
  66342. #define sqlite3_overload_function sqlite3_api->overload_function
  66343. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  66344. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  66345. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  66346. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  66347. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  66348. #define sqlite3_blob_close sqlite3_api->blob_close
  66349. #define sqlite3_blob_open sqlite3_api->blob_open
  66350. #define sqlite3_blob_read sqlite3_api->blob_read
  66351. #define sqlite3_blob_write sqlite3_api->blob_write
  66352. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  66353. #define sqlite3_file_control sqlite3_api->file_control
  66354. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  66355. #define sqlite3_memory_used sqlite3_api->memory_used
  66356. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  66357. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  66358. #define sqlite3_mutex_free sqlite3_api->mutex_free
  66359. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  66360. #define sqlite3_mutex_try sqlite3_api->mutex_try
  66361. #define sqlite3_open_v2 sqlite3_api->open_v2
  66362. #define sqlite3_release_memory sqlite3_api->release_memory
  66363. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  66364. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  66365. #define sqlite3_sleep sqlite3_api->sleep
  66366. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  66367. #define sqlite3_vfs_find sqlite3_api->vfs_find
  66368. #define sqlite3_vfs_register sqlite3_api->vfs_register
  66369. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  66370. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  66371. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  66372. #define sqlite3_result_error_code sqlite3_api->result_error_code
  66373. #define sqlite3_test_control sqlite3_api->test_control
  66374. #define sqlite3_randomness sqlite3_api->randomness
  66375. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  66376. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  66377. #define sqlite3_limit sqlite3_api->limit
  66378. #define sqlite3_next_stmt sqlite3_api->next_stmt
  66379. #define sqlite3_sql sqlite3_api->sql
  66380. #define sqlite3_status sqlite3_api->status
  66381. #endif /* SQLITE_CORE */
  66382. #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
  66383. #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
  66384. #endif /* _SQLite3EXT_H_ */
  66385. /************** End of sqlite3ext.h ******************************************/
  66386. /************** Continuing where we left off in loadext.c ********************/
  66387. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  66388. /*
  66389. ** Some API routines are omitted when various features are
  66390. ** excluded from a build of SQLite. Substitute a NULL pointer
  66391. ** for any missing APIs.
  66392. */
  66393. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  66394. # define sqlite3_column_database_name 0
  66395. # define sqlite3_column_database_name16 0
  66396. # define sqlite3_column_table_name 0
  66397. # define sqlite3_column_table_name16 0
  66398. # define sqlite3_column_origin_name 0
  66399. # define sqlite3_column_origin_name16 0
  66400. # define sqlite3_table_column_metadata 0
  66401. #endif
  66402. #ifdef SQLITE_OMIT_AUTHORIZATION
  66403. # define sqlite3_set_authorizer 0
  66404. #endif
  66405. #ifdef SQLITE_OMIT_UTF16
  66406. # define sqlite3_bind_text16 0
  66407. # define sqlite3_collation_needed16 0
  66408. # define sqlite3_column_decltype16 0
  66409. # define sqlite3_column_name16 0
  66410. # define sqlite3_column_text16 0
  66411. # define sqlite3_complete16 0
  66412. # define sqlite3_create_collation16 0
  66413. # define sqlite3_create_function16 0
  66414. # define sqlite3_errmsg16 0
  66415. # define sqlite3_open16 0
  66416. # define sqlite3_prepare16 0
  66417. # define sqlite3_prepare16_v2 0
  66418. # define sqlite3_result_error16 0
  66419. # define sqlite3_result_text16 0
  66420. # define sqlite3_result_text16be 0
  66421. # define sqlite3_result_text16le 0
  66422. # define sqlite3_value_text16 0
  66423. # define sqlite3_value_text16be 0
  66424. # define sqlite3_value_text16le 0
  66425. # define sqlite3_column_database_name16 0
  66426. # define sqlite3_column_table_name16 0
  66427. # define sqlite3_column_origin_name16 0
  66428. #endif
  66429. #ifdef SQLITE_OMIT_COMPLETE
  66430. # define sqlite3_complete 0
  66431. # define sqlite3_complete16 0
  66432. #endif
  66433. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  66434. # define sqlite3_progress_handler 0
  66435. #endif
  66436. #ifdef SQLITE_OMIT_VIRTUALTABLE
  66437. # define sqlite3_create_module 0
  66438. # define sqlite3_create_module_v2 0
  66439. # define sqlite3_declare_vtab 0
  66440. #endif
  66441. #ifdef SQLITE_OMIT_SHARED_CACHE
  66442. # define sqlite3_enable_shared_cache 0
  66443. #endif
  66444. #ifdef SQLITE_OMIT_TRACE
  66445. # define sqlite3_profile 0
  66446. # define sqlite3_trace 0
  66447. #endif
  66448. #ifdef SQLITE_OMIT_GET_TABLE
  66449. # define sqlite3_free_table 0
  66450. # define sqlite3_get_table 0
  66451. #endif
  66452. #ifdef SQLITE_OMIT_INCRBLOB
  66453. #define sqlite3_bind_zeroblob 0
  66454. #define sqlite3_blob_bytes 0
  66455. #define sqlite3_blob_close 0
  66456. #define sqlite3_blob_open 0
  66457. #define sqlite3_blob_read 0
  66458. #define sqlite3_blob_write 0
  66459. #endif
  66460. /*
  66461. ** The following structure contains pointers to all SQLite API routines.
  66462. ** A pointer to this structure is passed into extensions when they are
  66463. ** loaded so that the extension can make calls back into the SQLite
  66464. ** library.
  66465. **
  66466. ** When adding new APIs, add them to the bottom of this structure
  66467. ** in order to preserve backwards compatibility.
  66468. **
  66469. ** Extensions that use newer APIs should first call the
  66470. ** sqlite3_libversion_number() to make sure that the API they
  66471. ** intend to use is supported by the library. Extensions should
  66472. ** also check to make sure that the pointer to the function is
  66473. ** not NULL before calling it.
  66474. */
  66475. static const sqlite3_api_routines sqlite3Apis = {
  66476. sqlite3_aggregate_context,
  66477. #ifndef SQLITE_OMIT_DEPRECATED
  66478. sqlite3_aggregate_count,
  66479. #else
  66480. 0,
  66481. #endif
  66482. sqlite3_bind_blob,
  66483. sqlite3_bind_double,
  66484. sqlite3_bind_int,
  66485. sqlite3_bind_int64,
  66486. sqlite3_bind_null,
  66487. sqlite3_bind_parameter_count,
  66488. sqlite3_bind_parameter_index,
  66489. sqlite3_bind_parameter_name,
  66490. sqlite3_bind_text,
  66491. sqlite3_bind_text16,
  66492. sqlite3_bind_value,
  66493. sqlite3_busy_handler,
  66494. sqlite3_busy_timeout,
  66495. sqlite3_changes,
  66496. sqlite3_close,
  66497. sqlite3_collation_needed,
  66498. sqlite3_collation_needed16,
  66499. sqlite3_column_blob,
  66500. sqlite3_column_bytes,
  66501. sqlite3_column_bytes16,
  66502. sqlite3_column_count,
  66503. sqlite3_column_database_name,
  66504. sqlite3_column_database_name16,
  66505. sqlite3_column_decltype,
  66506. sqlite3_column_decltype16,
  66507. sqlite3_column_double,
  66508. sqlite3_column_int,
  66509. sqlite3_column_int64,
  66510. sqlite3_column_name,
  66511. sqlite3_column_name16,
  66512. sqlite3_column_origin_name,
  66513. sqlite3_column_origin_name16,
  66514. sqlite3_column_table_name,
  66515. sqlite3_column_table_name16,
  66516. sqlite3_column_text,
  66517. sqlite3_column_text16,
  66518. sqlite3_column_type,
  66519. sqlite3_column_value,
  66520. sqlite3_commit_hook,
  66521. sqlite3_complete,
  66522. sqlite3_complete16,
  66523. sqlite3_create_collation,
  66524. sqlite3_create_collation16,
  66525. sqlite3_create_function,
  66526. sqlite3_create_function16,
  66527. sqlite3_create_module,
  66528. sqlite3_data_count,
  66529. sqlite3_db_handle,
  66530. sqlite3_declare_vtab,
  66531. sqlite3_enable_shared_cache,
  66532. sqlite3_errcode,
  66533. sqlite3_errmsg,
  66534. sqlite3_errmsg16,
  66535. sqlite3_exec,
  66536. #ifndef SQLITE_OMIT_DEPRECATED
  66537. sqlite3_expired,
  66538. #else
  66539. 0,
  66540. #endif
  66541. sqlite3_finalize,
  66542. sqlite3_free,
  66543. sqlite3_free_table,
  66544. sqlite3_get_autocommit,
  66545. sqlite3_get_auxdata,
  66546. sqlite3_get_table,
  66547. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  66548. sqlite3_interrupt,
  66549. sqlite3_last_insert_rowid,
  66550. sqlite3_libversion,
  66551. sqlite3_libversion_number,
  66552. sqlite3_malloc,
  66553. sqlite3_mprintf,
  66554. sqlite3_open,
  66555. sqlite3_open16,
  66556. sqlite3_prepare,
  66557. sqlite3_prepare16,
  66558. sqlite3_profile,
  66559. sqlite3_progress_handler,
  66560. sqlite3_realloc,
  66561. sqlite3_reset,
  66562. sqlite3_result_blob,
  66563. sqlite3_result_double,
  66564. sqlite3_result_error,
  66565. sqlite3_result_error16,
  66566. sqlite3_result_int,
  66567. sqlite3_result_int64,
  66568. sqlite3_result_null,
  66569. sqlite3_result_text,
  66570. sqlite3_result_text16,
  66571. sqlite3_result_text16be,
  66572. sqlite3_result_text16le,
  66573. sqlite3_result_value,
  66574. sqlite3_rollback_hook,
  66575. sqlite3_set_authorizer,
  66576. sqlite3_set_auxdata,
  66577. sqlite3_snprintf,
  66578. sqlite3_step,
  66579. sqlite3_table_column_metadata,
  66580. #ifndef SQLITE_OMIT_DEPRECATED
  66581. sqlite3_thread_cleanup,
  66582. #else
  66583. 0,
  66584. #endif
  66585. sqlite3_total_changes,
  66586. sqlite3_trace,
  66587. #ifndef SQLITE_OMIT_DEPRECATED
  66588. sqlite3_transfer_bindings,
  66589. #else
  66590. 0,
  66591. #endif
  66592. sqlite3_update_hook,
  66593. sqlite3_user_data,
  66594. sqlite3_value_blob,
  66595. sqlite3_value_bytes,
  66596. sqlite3_value_bytes16,
  66597. sqlite3_value_double,
  66598. sqlite3_value_int,
  66599. sqlite3_value_int64,
  66600. sqlite3_value_numeric_type,
  66601. sqlite3_value_text,
  66602. sqlite3_value_text16,
  66603. sqlite3_value_text16be,
  66604. sqlite3_value_text16le,
  66605. sqlite3_value_type,
  66606. sqlite3_vmprintf,
  66607. /*
  66608. ** The original API set ends here. All extensions can call any
  66609. ** of the APIs above provided that the pointer is not NULL. But
  66610. ** before calling APIs that follow, extension should check the
  66611. ** sqlite3_libversion_number() to make sure they are dealing with
  66612. ** a library that is new enough to support that API.
  66613. *************************************************************************
  66614. */
  66615. sqlite3_overload_function,
  66616. /*
  66617. ** Added after 3.3.13
  66618. */
  66619. sqlite3_prepare_v2,
  66620. sqlite3_prepare16_v2,
  66621. sqlite3_clear_bindings,
  66622. /*
  66623. ** Added for 3.4.1
  66624. */
  66625. sqlite3_create_module_v2,
  66626. /*
  66627. ** Added for 3.5.0
  66628. */
  66629. sqlite3_bind_zeroblob,
  66630. sqlite3_blob_bytes,
  66631. sqlite3_blob_close,
  66632. sqlite3_blob_open,
  66633. sqlite3_blob_read,
  66634. sqlite3_blob_write,
  66635. sqlite3_create_collation_v2,
  66636. sqlite3_file_control,
  66637. sqlite3_memory_highwater,
  66638. sqlite3_memory_used,
  66639. #ifdef SQLITE_MUTEX_OMIT
  66640. 0,
  66641. 0,
  66642. 0,
  66643. 0,
  66644. 0,
  66645. #else
  66646. sqlite3_mutex_alloc,
  66647. sqlite3_mutex_enter,
  66648. sqlite3_mutex_free,
  66649. sqlite3_mutex_leave,
  66650. sqlite3_mutex_try,
  66651. #endif
  66652. sqlite3_open_v2,
  66653. sqlite3_release_memory,
  66654. sqlite3_result_error_nomem,
  66655. sqlite3_result_error_toobig,
  66656. sqlite3_sleep,
  66657. sqlite3_soft_heap_limit,
  66658. sqlite3_vfs_find,
  66659. sqlite3_vfs_register,
  66660. sqlite3_vfs_unregister,
  66661. /*
  66662. ** Added for 3.5.8
  66663. */
  66664. sqlite3_threadsafe,
  66665. sqlite3_result_zeroblob,
  66666. sqlite3_result_error_code,
  66667. sqlite3_test_control,
  66668. sqlite3_randomness,
  66669. sqlite3_context_db_handle,
  66670. /*
  66671. ** Added for 3.6.0
  66672. */
  66673. sqlite3_extended_result_codes,
  66674. sqlite3_limit,
  66675. sqlite3_next_stmt,
  66676. sqlite3_sql,
  66677. sqlite3_status,
  66678. };
  66679. /*
  66680. ** Attempt to load an SQLite extension library contained in the file
  66681. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  66682. ** default entry point name (sqlite3_extension_init) is used. Use
  66683. ** of the default name is recommended.
  66684. **
  66685. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  66686. **
  66687. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  66688. ** error message text. The calling function should free this memory
  66689. ** by calling sqlite3DbFree(db, ).
  66690. */
  66691. static int sqlite3LoadExtension(
  66692. sqlite3 *db, /* Load the extension into this database connection */
  66693. const char *zFile, /* Name of the shared library containing extension */
  66694. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  66695. char **pzErrMsg /* Put error message here if not 0 */
  66696. ){
  66697. sqlite3_vfs *pVfs = db->pVfs;
  66698. void *handle;
  66699. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  66700. char *zErrmsg = 0;
  66701. void **aHandle;
  66702. /* Ticket #1863. To avoid a creating security problems for older
  66703. ** applications that relink against newer versions of SQLite, the
  66704. ** ability to run load_extension is turned off by default. One
  66705. ** must call sqlite3_enable_load_extension() to turn on extension
  66706. ** loading. Otherwise you get the following error.
  66707. */
  66708. if( (db->flags & SQLITE_LoadExtension)==0 ){
  66709. if( pzErrMsg ){
  66710. *pzErrMsg = sqlite3_mprintf("not authorized");
  66711. }
  66712. return SQLITE_ERROR;
  66713. }
  66714. if( zProc==0 ){
  66715. zProc = "sqlite3_extension_init";
  66716. }
  66717. handle = sqlite3OsDlOpen(pVfs, zFile);
  66718. if( handle==0 ){
  66719. if( pzErrMsg ){
  66720. char zErr[256];
  66721. zErr[sizeof(zErr)-1] = '\0';
  66722. sqlite3_snprintf(sizeof(zErr)-1, zErr,
  66723. "unable to open shared library [%s]", zFile);
  66724. sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
  66725. *pzErrMsg = sqlite3DbStrDup(0, zErr);
  66726. }
  66727. return SQLITE_ERROR;
  66728. }
  66729. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  66730. sqlite3OsDlSym(pVfs, handle, zProc);
  66731. if( xInit==0 ){
  66732. if( pzErrMsg ){
  66733. char zErr[256];
  66734. zErr[sizeof(zErr)-1] = '\0';
  66735. sqlite3_snprintf(sizeof(zErr)-1, zErr,
  66736. "no entry point [%s] in shared library [%s]", zProc,zFile);
  66737. sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
  66738. *pzErrMsg = sqlite3DbStrDup(0, zErr);
  66739. sqlite3OsDlClose(pVfs, handle);
  66740. }
  66741. return SQLITE_ERROR;
  66742. }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  66743. if( pzErrMsg ){
  66744. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  66745. }
  66746. sqlite3_free(zErrmsg);
  66747. sqlite3OsDlClose(pVfs, handle);
  66748. return SQLITE_ERROR;
  66749. }
  66750. /* Append the new shared library handle to the db->aExtension array. */
  66751. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  66752. if( aHandle==0 ){
  66753. return SQLITE_NOMEM;
  66754. }
  66755. if( db->nExtension>0 ){
  66756. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  66757. }
  66758. sqlite3DbFree(db, db->aExtension);
  66759. db->aExtension = aHandle;
  66760. db->aExtension[db->nExtension++] = handle;
  66761. return SQLITE_OK;
  66762. }
  66763. SQLITE_API int sqlite3_load_extension(
  66764. sqlite3 *db, /* Load the extension into this database connection */
  66765. const char *zFile, /* Name of the shared library containing extension */
  66766. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  66767. char **pzErrMsg /* Put error message here if not 0 */
  66768. ){
  66769. int rc;
  66770. sqlite3_mutex_enter(db->mutex);
  66771. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  66772. sqlite3_mutex_leave(db->mutex);
  66773. return rc;
  66774. }
  66775. /*
  66776. ** Call this routine when the database connection is closing in order
  66777. ** to clean up loaded extensions
  66778. */
  66779. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  66780. int i;
  66781. assert( sqlite3_mutex_held(db->mutex) );
  66782. for(i=0; i<db->nExtension; i++){
  66783. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  66784. }
  66785. sqlite3DbFree(db, db->aExtension);
  66786. }
  66787. /*
  66788. ** Enable or disable extension loading. Extension loading is disabled by
  66789. ** default so as not to open security holes in older applications.
  66790. */
  66791. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  66792. sqlite3_mutex_enter(db->mutex);
  66793. if( onoff ){
  66794. db->flags |= SQLITE_LoadExtension;
  66795. }else{
  66796. db->flags &= ~SQLITE_LoadExtension;
  66797. }
  66798. sqlite3_mutex_leave(db->mutex);
  66799. return SQLITE_OK;
  66800. }
  66801. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  66802. /*
  66803. ** The auto-extension code added regardless of whether or not extension
  66804. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  66805. ** code if regular extension loading is not available. This is that
  66806. ** dummy pointer.
  66807. */
  66808. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  66809. static const sqlite3_api_routines sqlite3Apis = { 0 };
  66810. #endif
  66811. /*
  66812. ** The following object holds the list of automatically loaded
  66813. ** extensions.
  66814. **
  66815. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  66816. ** mutex must be held while accessing this list.
  66817. */
  66818. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  66819. static SQLITE_WSD struct sqlite3AutoExtList {
  66820. int nExt; /* Number of entries in aExt[] */
  66821. void (**aExt)(void); /* Pointers to the extension init functions */
  66822. } sqlite3Autoext = { 0, 0 };
  66823. /* The "wsdAutoext" macro will resolve to the autoextension
  66824. ** state vector. If writable static data is unsupported on the target,
  66825. ** we have to locate the state vector at run-time. In the more common
  66826. ** case where writable static data is supported, wsdStat can refer directly
  66827. ** to the "sqlite3Autoext" state vector declared above.
  66828. */
  66829. #ifdef SQLITE_OMIT_WSD
  66830. # define wsdAutoextInit \
  66831. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  66832. # define wsdAutoext x[0]
  66833. #else
  66834. # define wsdAutoextInit
  66835. # define wsdAutoext sqlite3Autoext
  66836. #endif
  66837. /*
  66838. ** Register a statically linked extension that is automatically
  66839. ** loaded by every new database connection.
  66840. */
  66841. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  66842. int rc = SQLITE_OK;
  66843. #ifndef SQLITE_OMIT_AUTOINIT
  66844. rc = sqlite3_initialize();
  66845. if( rc ){
  66846. return rc;
  66847. }else
  66848. #endif
  66849. {
  66850. int i;
  66851. #if SQLITE_THREADSAFE
  66852. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  66853. #endif
  66854. wsdAutoextInit;
  66855. sqlite3_mutex_enter(mutex);
  66856. for(i=0; i<wsdAutoext.nExt; i++){
  66857. if( wsdAutoext.aExt[i]==xInit ) break;
  66858. }
  66859. if( i==wsdAutoext.nExt ){
  66860. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  66861. void (**aNew)(void);
  66862. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  66863. if( aNew==0 ){
  66864. rc = SQLITE_NOMEM;
  66865. }else{
  66866. wsdAutoext.aExt = aNew;
  66867. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  66868. wsdAutoext.nExt++;
  66869. }
  66870. }
  66871. sqlite3_mutex_leave(mutex);
  66872. assert( (rc&0xff)==rc );
  66873. return rc;
  66874. }
  66875. }
  66876. /*
  66877. ** Reset the automatic extension loading mechanism.
  66878. */
  66879. SQLITE_API void sqlite3_reset_auto_extension(void){
  66880. #ifndef SQLITE_OMIT_AUTOINIT
  66881. if( sqlite3_initialize()==SQLITE_OK )
  66882. #endif
  66883. {
  66884. #if SQLITE_THREADSAFE
  66885. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  66886. #endif
  66887. wsdAutoextInit;
  66888. sqlite3_mutex_enter(mutex);
  66889. sqlite3_free(wsdAutoext.aExt);
  66890. wsdAutoext.aExt = 0;
  66891. wsdAutoext.nExt = 0;
  66892. sqlite3_mutex_leave(mutex);
  66893. }
  66894. }
  66895. /*
  66896. ** Load all automatic extensions.
  66897. */
  66898. SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
  66899. int i;
  66900. int go = 1;
  66901. int rc = SQLITE_OK;
  66902. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  66903. wsdAutoextInit;
  66904. if( wsdAutoext.nExt==0 ){
  66905. /* Common case: early out without every having to acquire a mutex */
  66906. return SQLITE_OK;
  66907. }
  66908. for(i=0; go; i++){
  66909. char *zErrmsg = 0;
  66910. #if SQLITE_THREADSAFE
  66911. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  66912. #endif
  66913. sqlite3_mutex_enter(mutex);
  66914. if( i>=wsdAutoext.nExt ){
  66915. xInit = 0;
  66916. go = 0;
  66917. }else{
  66918. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  66919. wsdAutoext.aExt[i];
  66920. }
  66921. sqlite3_mutex_leave(mutex);
  66922. if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
  66923. sqlite3Error(db, SQLITE_ERROR,
  66924. "automatic extension loading failed: %s", zErrmsg);
  66925. go = 0;
  66926. rc = SQLITE_ERROR;
  66927. sqlite3_free(zErrmsg);
  66928. }
  66929. }
  66930. return rc;
  66931. }
  66932. /************** End of loadext.c *********************************************/
  66933. /************** Begin file pragma.c ******************************************/
  66934. /*
  66935. ** 2003 April 6
  66936. **
  66937. ** The author disclaims copyright to this source code. In place of
  66938. ** a legal notice, here is a blessing:
  66939. **
  66940. ** May you do good and not evil.
  66941. ** May you find forgiveness for yourself and forgive others.
  66942. ** May you share freely, never taking more than you give.
  66943. **
  66944. *************************************************************************
  66945. ** This file contains code used to implement the PRAGMA command.
  66946. **
  66947. ** $Id: pragma.c,v 1.209 2009/04/07 22:05:43 drh Exp $
  66948. */
  66949. /* Ignore this whole file if pragmas are disabled
  66950. */
  66951. #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
  66952. /*
  66953. ** Interpret the given string as a safety level. Return 0 for OFF,
  66954. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  66955. ** unrecognized string argument.
  66956. **
  66957. ** Note that the values returned are one less that the values that
  66958. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  66959. ** to support legacy SQL code. The safety level used to be boolean
  66960. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  66961. */
  66962. static u8 getSafetyLevel(const char *z){
  66963. /* 123456789 123456789 */
  66964. static const char zText[] = "onoffalseyestruefull";
  66965. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  66966. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  66967. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  66968. int i, n;
  66969. if( sqlite3Isdigit(*z) ){
  66970. return (u8)atoi(z);
  66971. }
  66972. n = sqlite3Strlen30(z);
  66973. for(i=0; i<ArraySize(iLength); i++){
  66974. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  66975. return iValue[i];
  66976. }
  66977. }
  66978. return 1;
  66979. }
  66980. /*
  66981. ** Interpret the given string as a boolean value.
  66982. */
  66983. static u8 getBoolean(const char *z){
  66984. return getSafetyLevel(z)&1;
  66985. }
  66986. /*
  66987. ** Interpret the given string as a locking mode value.
  66988. */
  66989. static int getLockingMode(const char *z){
  66990. if( z ){
  66991. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  66992. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  66993. }
  66994. return PAGER_LOCKINGMODE_QUERY;
  66995. }
  66996. #ifndef SQLITE_OMIT_AUTOVACUUM
  66997. /*
  66998. ** Interpret the given string as an auto-vacuum mode value.
  66999. **
  67000. ** The following strings, "none", "full" and "incremental" are
  67001. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  67002. */
  67003. static int getAutoVacuum(const char *z){
  67004. int i;
  67005. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  67006. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  67007. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  67008. i = atoi(z);
  67009. return (u8)((i>=0&&i<=2)?i:0);
  67010. }
  67011. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  67012. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67013. /*
  67014. ** Interpret the given string as a temp db location. Return 1 for file
  67015. ** backed temporary databases, 2 for the Red-Black tree in memory database
  67016. ** and 0 to use the compile-time default.
  67017. */
  67018. static int getTempStore(const char *z){
  67019. if( z[0]>='0' && z[0]<='2' ){
  67020. return z[0] - '0';
  67021. }else if( sqlite3StrICmp(z, "file")==0 ){
  67022. return 1;
  67023. }else if( sqlite3StrICmp(z, "memory")==0 ){
  67024. return 2;
  67025. }else{
  67026. return 0;
  67027. }
  67028. }
  67029. #endif /* SQLITE_PAGER_PRAGMAS */
  67030. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67031. /*
  67032. ** Invalidate temp storage, either when the temp storage is changed
  67033. ** from default, or when 'file' and the temp_store_directory has changed
  67034. */
  67035. static int invalidateTempStorage(Parse *pParse){
  67036. sqlite3 *db = pParse->db;
  67037. if( db->aDb[1].pBt!=0 ){
  67038. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  67039. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  67040. "from within a transaction");
  67041. return SQLITE_ERROR;
  67042. }
  67043. sqlite3BtreeClose(db->aDb[1].pBt);
  67044. db->aDb[1].pBt = 0;
  67045. sqlite3ResetInternalSchema(db, 0);
  67046. }
  67047. return SQLITE_OK;
  67048. }
  67049. #endif /* SQLITE_PAGER_PRAGMAS */
  67050. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67051. /*
  67052. ** If the TEMP database is open, close it and mark the database schema
  67053. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  67054. ** or DEFAULT_TEMP_STORE pragmas.
  67055. */
  67056. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  67057. int ts = getTempStore(zStorageType);
  67058. sqlite3 *db = pParse->db;
  67059. if( db->temp_store==ts ) return SQLITE_OK;
  67060. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  67061. return SQLITE_ERROR;
  67062. }
  67063. db->temp_store = (u8)ts;
  67064. return SQLITE_OK;
  67065. }
  67066. #endif /* SQLITE_PAGER_PRAGMAS */
  67067. /*
  67068. ** Generate code to return a single integer value.
  67069. */
  67070. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  67071. Vdbe *v = sqlite3GetVdbe(pParse);
  67072. int mem = ++pParse->nMem;
  67073. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  67074. if( pI64 ){
  67075. memcpy(pI64, &value, sizeof(value));
  67076. }
  67077. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  67078. sqlite3VdbeSetNumCols(v, 1);
  67079. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  67080. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  67081. }
  67082. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  67083. /*
  67084. ** Check to see if zRight and zLeft refer to a pragma that queries
  67085. ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
  67086. ** Also, implement the pragma.
  67087. */
  67088. static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  67089. static const struct sPragmaType {
  67090. const char *zName; /* Name of the pragma */
  67091. int mask; /* Mask for the db->flags value */
  67092. } aPragma[] = {
  67093. { "full_column_names", SQLITE_FullColNames },
  67094. { "short_column_names", SQLITE_ShortColNames },
  67095. { "count_changes", SQLITE_CountRows },
  67096. { "empty_result_callbacks", SQLITE_NullCallback },
  67097. { "legacy_file_format", SQLITE_LegacyFileFmt },
  67098. { "fullfsync", SQLITE_FullFSync },
  67099. { "reverse_unordered_selects", SQLITE_ReverseOrder },
  67100. #ifdef SQLITE_DEBUG
  67101. { "sql_trace", SQLITE_SqlTrace },
  67102. { "vdbe_listing", SQLITE_VdbeListing },
  67103. { "vdbe_trace", SQLITE_VdbeTrace },
  67104. #endif
  67105. #ifndef SQLITE_OMIT_CHECK
  67106. { "ignore_check_constraints", SQLITE_IgnoreChecks },
  67107. #endif
  67108. /* The following is VERY experimental */
  67109. { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
  67110. { "omit_readlock", SQLITE_NoReadlock },
  67111. /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
  67112. ** flag if there are any active statements. */
  67113. { "read_uncommitted", SQLITE_ReadUncommitted },
  67114. };
  67115. int i;
  67116. const struct sPragmaType *p;
  67117. for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
  67118. if( sqlite3StrICmp(zLeft, p->zName)==0 ){
  67119. sqlite3 *db = pParse->db;
  67120. Vdbe *v;
  67121. v = sqlite3GetVdbe(pParse);
  67122. assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
  67123. if( ALWAYS(v) ){
  67124. if( zRight==0 ){
  67125. returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
  67126. }else{
  67127. if( getBoolean(zRight) ){
  67128. db->flags |= p->mask;
  67129. }else{
  67130. db->flags &= ~p->mask;
  67131. }
  67132. /* Many of the flag-pragmas modify the code generated by the SQL
  67133. ** compiler (eg. count_changes). So add an opcode to expire all
  67134. ** compiled SQL statements after modifying a pragma value.
  67135. */
  67136. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  67137. }
  67138. }
  67139. return 1;
  67140. }
  67141. }
  67142. return 0;
  67143. }
  67144. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  67145. /*
  67146. ** Return a human-readable name for a constraint resolution action.
  67147. */
  67148. static const char *actionName(u8 action){
  67149. const char *zName;
  67150. switch( action ){
  67151. case OE_SetNull: zName = "SET NULL"; break;
  67152. case OE_SetDflt: zName = "SET DEFAULT"; break;
  67153. case OE_Cascade: zName = "CASCADE"; break;
  67154. default: zName = "RESTRICT";
  67155. assert( action==OE_Restrict ); break;
  67156. }
  67157. return zName;
  67158. }
  67159. /*
  67160. ** Process a pragma statement.
  67161. **
  67162. ** Pragmas are of this form:
  67163. **
  67164. ** PRAGMA [database.]id [= value]
  67165. **
  67166. ** The identifier might also be a string. The value is a string, and
  67167. ** identifier, or a number. If minusFlag is true, then the value is
  67168. ** a number that was preceded by a minus sign.
  67169. **
  67170. ** If the left side is "database.id" then pId1 is the database name
  67171. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  67172. ** id and pId2 is any empty string.
  67173. */
  67174. SQLITE_PRIVATE void sqlite3Pragma(
  67175. Parse *pParse,
  67176. Token *pId1, /* First part of [database.]id field */
  67177. Token *pId2, /* Second part of [database.]id field, or NULL */
  67178. Token *pValue, /* Token for <value>, or NULL */
  67179. int minusFlag /* True if a '-' sign preceded <value> */
  67180. ){
  67181. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  67182. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  67183. const char *zDb = 0; /* The database name */
  67184. Token *pId; /* Pointer to <id> token */
  67185. int iDb; /* Database index for <database> */
  67186. sqlite3 *db = pParse->db;
  67187. Db *pDb;
  67188. Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
  67189. if( v==0 ) return;
  67190. pParse->nMem = 2;
  67191. /* Interpret the [database.] part of the pragma statement. iDb is the
  67192. ** index of the database this pragma is being applied to in db.aDb[]. */
  67193. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  67194. if( iDb<0 ) return;
  67195. pDb = &db->aDb[iDb];
  67196. /* If the temp database has been explicitly named as part of the
  67197. ** pragma, make sure it is open.
  67198. */
  67199. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  67200. return;
  67201. }
  67202. zLeft = sqlite3NameFromToken(db, pId);
  67203. if( !zLeft ) return;
  67204. if( minusFlag ){
  67205. zRight = sqlite3MPrintf(db, "-%T", pValue);
  67206. }else{
  67207. zRight = sqlite3NameFromToken(db, pValue);
  67208. }
  67209. assert( pId2 );
  67210. zDb = pId2->n>0 ? pDb->zName : 0;
  67211. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  67212. goto pragma_out;
  67213. }
  67214. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67215. /*
  67216. ** PRAGMA [database.]default_cache_size
  67217. ** PRAGMA [database.]default_cache_size=N
  67218. **
  67219. ** The first form reports the current persistent setting for the
  67220. ** page cache size. The value returned is the maximum number of
  67221. ** pages in the page cache. The second form sets both the current
  67222. ** page cache size value and the persistent page cache size value
  67223. ** stored in the database file.
  67224. **
  67225. ** The default cache size is stored in meta-value 2 of page 1 of the
  67226. ** database file. The cache size is actually the absolute value of
  67227. ** this memory location. The sign of meta-value 2 determines the
  67228. ** synchronous setting. A negative value means synchronous is off
  67229. ** and a positive value means synchronous is on.
  67230. */
  67231. if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
  67232. static const VdbeOpList getCacheSize[] = {
  67233. { OP_ReadCookie, 0, 1, 2}, /* 0 */
  67234. { OP_IfPos, 1, 6, 0},
  67235. { OP_Integer, 0, 2, 0},
  67236. { OP_Subtract, 1, 2, 1},
  67237. { OP_IfPos, 1, 6, 0},
  67238. { OP_Integer, 0, 1, 0}, /* 5 */
  67239. { OP_ResultRow, 1, 1, 0},
  67240. };
  67241. int addr;
  67242. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67243. sqlite3VdbeUsesBtree(v, iDb);
  67244. if( !zRight ){
  67245. sqlite3VdbeSetNumCols(v, 1);
  67246. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  67247. pParse->nMem += 2;
  67248. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  67249. sqlite3VdbeChangeP1(v, addr, iDb);
  67250. sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
  67251. }else{
  67252. int size = atoi(zRight);
  67253. if( size<0 ) size = -size;
  67254. sqlite3BeginWriteOperation(pParse, 0, iDb);
  67255. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  67256. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
  67257. addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
  67258. sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
  67259. sqlite3VdbeJumpHere(v, addr);
  67260. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
  67261. pDb->pSchema->cache_size = size;
  67262. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  67263. }
  67264. }else
  67265. /*
  67266. ** PRAGMA [database.]page_size
  67267. ** PRAGMA [database.]page_size=N
  67268. **
  67269. ** The first form reports the current setting for the
  67270. ** database page size in bytes. The second form sets the
  67271. ** database page size value. The value can only be set if
  67272. ** the database has not yet been created.
  67273. */
  67274. if( sqlite3StrICmp(zLeft,"page_size")==0 ){
  67275. Btree *pBt = pDb->pBt;
  67276. assert( pBt!=0 );
  67277. if( !zRight ){
  67278. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  67279. returnSingleInt(pParse, "page_size", size);
  67280. }else{
  67281. /* Malloc may fail when setting the page-size, as there is an internal
  67282. ** buffer that the pager module resizes using sqlite3_realloc().
  67283. */
  67284. db->nextPagesize = atoi(zRight);
  67285. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  67286. db->mallocFailed = 1;
  67287. }
  67288. }
  67289. }else
  67290. /*
  67291. ** PRAGMA [database.]max_page_count
  67292. ** PRAGMA [database.]max_page_count=N
  67293. **
  67294. ** The first form reports the current setting for the
  67295. ** maximum number of pages in the database file. The
  67296. ** second form attempts to change this setting. Both
  67297. ** forms return the current setting.
  67298. */
  67299. if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
  67300. Btree *pBt = pDb->pBt;
  67301. int newMax = 0;
  67302. assert( pBt!=0 );
  67303. if( zRight ){
  67304. newMax = atoi(zRight);
  67305. }
  67306. if( ALWAYS(pBt) ){
  67307. newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
  67308. }
  67309. returnSingleInt(pParse, "max_page_count", newMax);
  67310. }else
  67311. /*
  67312. ** PRAGMA [database.]page_count
  67313. **
  67314. ** Return the number of pages in the specified database.
  67315. */
  67316. if( sqlite3StrICmp(zLeft,"page_count")==0 ){
  67317. int iReg;
  67318. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67319. sqlite3CodeVerifySchema(pParse, iDb);
  67320. iReg = ++pParse->nMem;
  67321. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  67322. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  67323. sqlite3VdbeSetNumCols(v, 1);
  67324. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
  67325. }else
  67326. /*
  67327. ** PRAGMA [database.]locking_mode
  67328. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  67329. */
  67330. if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
  67331. const char *zRet = "normal";
  67332. int eMode = getLockingMode(zRight);
  67333. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  67334. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  67335. ** the current default locking mode (which may be different to
  67336. ** the locking-mode of the main database).
  67337. */
  67338. eMode = db->dfltLockMode;
  67339. }else{
  67340. Pager *pPager;
  67341. if( pId2->n==0 ){
  67342. /* This indicates that no database name was specified as part
  67343. ** of the PRAGMA command. In this case the locking-mode must be
  67344. ** set on all attached databases, as well as the main db file.
  67345. **
  67346. ** Also, the sqlite3.dfltLockMode variable is set so that
  67347. ** any subsequently attached databases also use the specified
  67348. ** locking mode.
  67349. */
  67350. int ii;
  67351. assert(pDb==&db->aDb[0]);
  67352. for(ii=2; ii<db->nDb; ii++){
  67353. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  67354. sqlite3PagerLockingMode(pPager, eMode);
  67355. }
  67356. db->dfltLockMode = (u8)eMode;
  67357. }
  67358. pPager = sqlite3BtreePager(pDb->pBt);
  67359. eMode = sqlite3PagerLockingMode(pPager, eMode);
  67360. }
  67361. assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
  67362. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  67363. zRet = "exclusive";
  67364. }
  67365. sqlite3VdbeSetNumCols(v, 1);
  67366. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  67367. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  67368. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  67369. }else
  67370. /*
  67371. ** PRAGMA [database.]journal_mode
  67372. ** PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
  67373. */
  67374. if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
  67375. int eMode;
  67376. static char * const azModeName[] = {
  67377. "delete", "persist", "off", "truncate", "memory"
  67378. };
  67379. if( zRight==0 ){
  67380. eMode = PAGER_JOURNALMODE_QUERY;
  67381. }else{
  67382. int n = sqlite3Strlen30(zRight);
  67383. eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
  67384. while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
  67385. eMode--;
  67386. }
  67387. }
  67388. if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
  67389. /* Simple "PRAGMA journal_mode;" statement. This is a query for
  67390. ** the current default journal mode (which may be different to
  67391. ** the journal-mode of the main database).
  67392. */
  67393. eMode = db->dfltJournalMode;
  67394. }else{
  67395. Pager *pPager;
  67396. if( pId2->n==0 ){
  67397. /* This indicates that no database name was specified as part
  67398. ** of the PRAGMA command. In this case the journal-mode must be
  67399. ** set on all attached databases, as well as the main db file.
  67400. **
  67401. ** Also, the sqlite3.dfltJournalMode variable is set so that
  67402. ** any subsequently attached databases also use the specified
  67403. ** journal mode.
  67404. */
  67405. int ii;
  67406. assert(pDb==&db->aDb[0]);
  67407. for(ii=1; ii<db->nDb; ii++){
  67408. if( db->aDb[ii].pBt ){
  67409. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  67410. sqlite3PagerJournalMode(pPager, eMode);
  67411. }
  67412. }
  67413. db->dfltJournalMode = (u8)eMode;
  67414. }
  67415. pPager = sqlite3BtreePager(pDb->pBt);
  67416. eMode = sqlite3PagerJournalMode(pPager, eMode);
  67417. }
  67418. assert( eMode==PAGER_JOURNALMODE_DELETE
  67419. || eMode==PAGER_JOURNALMODE_TRUNCATE
  67420. || eMode==PAGER_JOURNALMODE_PERSIST
  67421. || eMode==PAGER_JOURNALMODE_OFF
  67422. || eMode==PAGER_JOURNALMODE_MEMORY );
  67423. sqlite3VdbeSetNumCols(v, 1);
  67424. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  67425. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
  67426. azModeName[eMode], P4_STATIC);
  67427. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  67428. }else
  67429. /*
  67430. ** PRAGMA [database.]journal_size_limit
  67431. ** PRAGMA [database.]journal_size_limit=N
  67432. **
  67433. ** Get or set the size limit on rollback journal files.
  67434. */
  67435. if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
  67436. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  67437. i64 iLimit = -2;
  67438. if( zRight ){
  67439. sqlite3Atoi64(zRight, &iLimit);
  67440. if( iLimit<-1 ) iLimit = -1;
  67441. }
  67442. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  67443. returnSingleInt(pParse, "journal_size_limit", iLimit);
  67444. }else
  67445. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  67446. /*
  67447. ** PRAGMA [database.]auto_vacuum
  67448. ** PRAGMA [database.]auto_vacuum=N
  67449. **
  67450. ** Get or set the value of the database 'auto-vacuum' parameter.
  67451. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  67452. */
  67453. #ifndef SQLITE_OMIT_AUTOVACUUM
  67454. if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
  67455. Btree *pBt = pDb->pBt;
  67456. assert( pBt!=0 );
  67457. if( sqlite3ReadSchema(pParse) ){
  67458. goto pragma_out;
  67459. }
  67460. if( !zRight ){
  67461. int auto_vacuum;
  67462. if( ALWAYS(pBt) ){
  67463. auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
  67464. }else{
  67465. auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
  67466. }
  67467. returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
  67468. }else{
  67469. int eAuto = getAutoVacuum(zRight);
  67470. assert( eAuto>=0 && eAuto<=2 );
  67471. db->nextAutovac = (u8)eAuto;
  67472. if( ALWAYS(eAuto>=0) ){
  67473. /* Call SetAutoVacuum() to set initialize the internal auto and
  67474. ** incr-vacuum flags. This is required in case this connection
  67475. ** creates the database file. It is important that it is created
  67476. ** as an auto-vacuum capable db.
  67477. */
  67478. int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  67479. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  67480. /* When setting the auto_vacuum mode to either "full" or
  67481. ** "incremental", write the value of meta[6] in the database
  67482. ** file. Before writing to meta[6], check that meta[3] indicates
  67483. ** that this really is an auto-vacuum capable database.
  67484. */
  67485. static const VdbeOpList setMeta6[] = {
  67486. { OP_Transaction, 0, 1, 0}, /* 0 */
  67487. { OP_ReadCookie, 0, 1, 3}, /* 1 */
  67488. { OP_If, 1, 0, 0}, /* 2 */
  67489. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  67490. { OP_Integer, 0, 1, 0}, /* 4 */
  67491. { OP_SetCookie, 0, 6, 1}, /* 5 */
  67492. };
  67493. int iAddr;
  67494. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  67495. sqlite3VdbeChangeP1(v, iAddr, iDb);
  67496. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  67497. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  67498. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  67499. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  67500. sqlite3VdbeUsesBtree(v, iDb);
  67501. }
  67502. }
  67503. }
  67504. }else
  67505. #endif
  67506. /*
  67507. ** PRAGMA [database.]incremental_vacuum(N)
  67508. **
  67509. ** Do N steps of incremental vacuuming on a database.
  67510. */
  67511. #ifndef SQLITE_OMIT_AUTOVACUUM
  67512. if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
  67513. int iLimit, addr;
  67514. if( sqlite3ReadSchema(pParse) ){
  67515. goto pragma_out;
  67516. }
  67517. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  67518. iLimit = 0x7fffffff;
  67519. }
  67520. sqlite3BeginWriteOperation(pParse, 0, iDb);
  67521. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  67522. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  67523. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  67524. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  67525. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  67526. sqlite3VdbeJumpHere(v, addr);
  67527. }else
  67528. #endif
  67529. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  67530. /*
  67531. ** PRAGMA [database.]cache_size
  67532. ** PRAGMA [database.]cache_size=N
  67533. **
  67534. ** The first form reports the current local setting for the
  67535. ** page cache size. The local setting can be different from
  67536. ** the persistent cache size value that is stored in the database
  67537. ** file itself. The value returned is the maximum number of
  67538. ** pages in the page cache. The second form sets the local
  67539. ** page cache size value. It does not change the persistent
  67540. ** cache size stored on the disk so the cache size will revert
  67541. ** to its default value when the database is closed and reopened.
  67542. ** N should be a positive integer.
  67543. */
  67544. if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
  67545. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67546. if( !zRight ){
  67547. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  67548. }else{
  67549. int size = atoi(zRight);
  67550. if( size<0 ) size = -size;
  67551. pDb->pSchema->cache_size = size;
  67552. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  67553. }
  67554. }else
  67555. /*
  67556. ** PRAGMA temp_store
  67557. ** PRAGMA temp_store = "default"|"memory"|"file"
  67558. **
  67559. ** Return or set the local value of the temp_store flag. Changing
  67560. ** the local value does not make changes to the disk file and the default
  67561. ** value will be restored the next time the database is opened.
  67562. **
  67563. ** Note that it is possible for the library compile-time options to
  67564. ** override this setting
  67565. */
  67566. if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
  67567. if( !zRight ){
  67568. returnSingleInt(pParse, "temp_store", db->temp_store);
  67569. }else{
  67570. changeTempStorage(pParse, zRight);
  67571. }
  67572. }else
  67573. /*
  67574. ** PRAGMA temp_store_directory
  67575. ** PRAGMA temp_store_directory = ""|"directory_name"
  67576. **
  67577. ** Return or set the local value of the temp_store_directory flag. Changing
  67578. ** the value sets a specific directory to be used for temporary files.
  67579. ** Setting to a null string reverts to the default temporary directory search.
  67580. ** If temporary directory is changed, then invalidateTempStorage.
  67581. **
  67582. */
  67583. if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
  67584. if( !zRight ){
  67585. if( sqlite3_temp_directory ){
  67586. sqlite3VdbeSetNumCols(v, 1);
  67587. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  67588. "temp_store_directory", SQLITE_STATIC);
  67589. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  67590. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  67591. }
  67592. }else{
  67593. #ifndef SQLITE_OMIT_WSD
  67594. if( zRight[0] ){
  67595. int rc;
  67596. int res;
  67597. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  67598. if( rc!=SQLITE_OK || res==0 ){
  67599. sqlite3ErrorMsg(pParse, "not a writable directory");
  67600. goto pragma_out;
  67601. }
  67602. }
  67603. if( SQLITE_TEMP_STORE==0
  67604. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  67605. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  67606. ){
  67607. invalidateTempStorage(pParse);
  67608. }
  67609. sqlite3_free(sqlite3_temp_directory);
  67610. if( zRight[0] ){
  67611. sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
  67612. }else{
  67613. sqlite3_temp_directory = 0;
  67614. }
  67615. #endif /* SQLITE_OMIT_WSD */
  67616. }
  67617. }else
  67618. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  67619. # if defined(__APPLE__)
  67620. # define SQLITE_ENABLE_LOCKING_STYLE 1
  67621. # else
  67622. # define SQLITE_ENABLE_LOCKING_STYLE 0
  67623. # endif
  67624. #endif
  67625. #if SQLITE_ENABLE_LOCKING_STYLE
  67626. /*
  67627. ** PRAGMA [database.]lock_proxy_file
  67628. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  67629. **
  67630. ** Return or set the value of the lock_proxy_file flag. Changing
  67631. ** the value sets a specific file to be used for database access locks.
  67632. **
  67633. */
  67634. if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
  67635. if( !zRight ){
  67636. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  67637. char *proxy_file_path = NULL;
  67638. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  67639. sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
  67640. &proxy_file_path);
  67641. if( proxy_file_path ){
  67642. sqlite3VdbeSetNumCols(v, 1);
  67643. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  67644. "lock_proxy_file", SQLITE_STATIC);
  67645. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  67646. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  67647. }
  67648. }else{
  67649. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  67650. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  67651. int res;
  67652. if( zRight[0] ){
  67653. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  67654. zRight);
  67655. } else {
  67656. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  67657. NULL);
  67658. }
  67659. if( res!=SQLITE_OK ){
  67660. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  67661. goto pragma_out;
  67662. }
  67663. }
  67664. }else
  67665. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  67666. /*
  67667. ** PRAGMA [database.]synchronous
  67668. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  67669. **
  67670. ** Return or set the local value of the synchronous flag. Changing
  67671. ** the local value does not make changes to the disk file and the
  67672. ** default value will be restored the next time the database is
  67673. ** opened.
  67674. */
  67675. if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
  67676. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67677. if( !zRight ){
  67678. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  67679. }else{
  67680. if( !db->autoCommit ){
  67681. sqlite3ErrorMsg(pParse,
  67682. "Safety level may not be changed inside a transaction");
  67683. }else{
  67684. pDb->safety_level = getSafetyLevel(zRight)+1;
  67685. }
  67686. }
  67687. }else
  67688. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  67689. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  67690. if( flagPragma(pParse, zLeft, zRight) ){
  67691. /* The flagPragma() subroutine also generates any necessary code
  67692. ** there is nothing more to do here */
  67693. }else
  67694. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  67695. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  67696. /*
  67697. ** PRAGMA table_info(<table>)
  67698. **
  67699. ** Return a single row for each column of the named table. The columns of
  67700. ** the returned data set are:
  67701. **
  67702. ** cid: Column id (numbered from left to right, starting at 0)
  67703. ** name: Column name
  67704. ** type: Column declaration type.
  67705. ** notnull: True if 'NOT NULL' is part of column declaration
  67706. ** dflt_value: The default value for the column, if any.
  67707. */
  67708. if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
  67709. Table *pTab;
  67710. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67711. pTab = sqlite3FindTable(db, zRight, zDb);
  67712. if( pTab ){
  67713. int i;
  67714. int nHidden = 0;
  67715. Column *pCol;
  67716. sqlite3VdbeSetNumCols(v, 6);
  67717. pParse->nMem = 6;
  67718. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  67719. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  67720. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  67721. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  67722. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  67723. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  67724. sqlite3ViewGetColumnNames(pParse, pTab);
  67725. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  67726. if( IsHiddenColumn(pCol) ){
  67727. nHidden++;
  67728. continue;
  67729. }
  67730. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  67731. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  67732. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  67733. pCol->zType ? pCol->zType : "", 0);
  67734. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  67735. if( pCol->pDflt ){
  67736. const Token *p = &pCol->pDflt->span;
  67737. assert( p->z );
  67738. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)p->z, p->n);
  67739. }else{
  67740. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  67741. }
  67742. sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
  67743. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  67744. }
  67745. }
  67746. }else
  67747. if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
  67748. Index *pIdx;
  67749. Table *pTab;
  67750. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67751. pIdx = sqlite3FindIndex(db, zRight, zDb);
  67752. if( pIdx ){
  67753. int i;
  67754. pTab = pIdx->pTable;
  67755. sqlite3VdbeSetNumCols(v, 3);
  67756. pParse->nMem = 3;
  67757. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  67758. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  67759. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  67760. for(i=0; i<pIdx->nColumn; i++){
  67761. int cnum = pIdx->aiColumn[i];
  67762. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  67763. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  67764. assert( pTab->nCol>cnum );
  67765. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  67766. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  67767. }
  67768. }
  67769. }else
  67770. if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
  67771. Index *pIdx;
  67772. Table *pTab;
  67773. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67774. pTab = sqlite3FindTable(db, zRight, zDb);
  67775. if( pTab ){
  67776. v = sqlite3GetVdbe(pParse);
  67777. pIdx = pTab->pIndex;
  67778. if( pIdx ){
  67779. int i = 0;
  67780. sqlite3VdbeSetNumCols(v, 3);
  67781. pParse->nMem = 3;
  67782. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  67783. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  67784. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  67785. while(pIdx){
  67786. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  67787. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  67788. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  67789. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  67790. ++i;
  67791. pIdx = pIdx->pNext;
  67792. }
  67793. }
  67794. }
  67795. }else
  67796. if( sqlite3StrICmp(zLeft, "database_list")==0 ){
  67797. int i;
  67798. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67799. sqlite3VdbeSetNumCols(v, 3);
  67800. pParse->nMem = 3;
  67801. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  67802. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  67803. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  67804. for(i=0; i<db->nDb; i++){
  67805. if( db->aDb[i].pBt==0 ) continue;
  67806. assert( db->aDb[i].zName!=0 );
  67807. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  67808. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  67809. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  67810. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  67811. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  67812. }
  67813. }else
  67814. if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
  67815. int i = 0;
  67816. HashElem *p;
  67817. sqlite3VdbeSetNumCols(v, 2);
  67818. pParse->nMem = 2;
  67819. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  67820. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  67821. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  67822. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  67823. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  67824. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  67825. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  67826. }
  67827. }else
  67828. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  67829. #ifndef SQLITE_OMIT_FOREIGN_KEY
  67830. if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
  67831. FKey *pFK;
  67832. Table *pTab;
  67833. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67834. pTab = sqlite3FindTable(db, zRight, zDb);
  67835. if( pTab ){
  67836. v = sqlite3GetVdbe(pParse);
  67837. pFK = pTab->pFKey;
  67838. if( pFK ){
  67839. int i = 0;
  67840. sqlite3VdbeSetNumCols(v, 8);
  67841. pParse->nMem = 8;
  67842. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  67843. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  67844. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  67845. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  67846. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  67847. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  67848. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  67849. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  67850. while(pFK){
  67851. int j;
  67852. for(j=0; j<pFK->nCol; j++){
  67853. char *zCol = pFK->aCol[j].zCol;
  67854. char *zOnUpdate = (char *)actionName(pFK->updateConf);
  67855. char *zOnDelete = (char *)actionName(pFK->deleteConf);
  67856. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  67857. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  67858. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  67859. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  67860. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  67861. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  67862. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  67863. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  67864. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  67865. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  67866. }
  67867. ++i;
  67868. pFK = pFK->pNextFrom;
  67869. }
  67870. }
  67871. }
  67872. }else
  67873. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  67874. #ifndef NDEBUG
  67875. if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
  67876. if( zRight ){
  67877. if( getBoolean(zRight) ){
  67878. sqlite3ParserTrace(stderr, "parser: ");
  67879. }else{
  67880. sqlite3ParserTrace(0, 0);
  67881. }
  67882. }
  67883. }else
  67884. #endif
  67885. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  67886. ** used will be case sensitive or not depending on the RHS.
  67887. */
  67888. if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
  67889. if( zRight ){
  67890. sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
  67891. }
  67892. }else
  67893. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  67894. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  67895. #endif
  67896. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  67897. /* Pragma "quick_check" is an experimental reduced version of
  67898. ** integrity_check designed to detect most database corruption
  67899. ** without most of the overhead of a full integrity-check.
  67900. */
  67901. if( sqlite3StrICmp(zLeft, "integrity_check")==0
  67902. || sqlite3StrICmp(zLeft, "quick_check")==0
  67903. ){
  67904. int i, j, addr, mxErr;
  67905. /* Code that appears at the end of the integrity check. If no error
  67906. ** messages have been generated, output OK. Otherwise output the
  67907. ** error message
  67908. */
  67909. static const VdbeOpList endCode[] = {
  67910. { OP_AddImm, 1, 0, 0}, /* 0 */
  67911. { OP_IfNeg, 1, 0, 0}, /* 1 */
  67912. { OP_String8, 0, 3, 0}, /* 2 */
  67913. { OP_ResultRow, 3, 1, 0},
  67914. };
  67915. int isQuick = (zLeft[0]=='q');
  67916. /* Initialize the VDBE program */
  67917. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  67918. pParse->nMem = 6;
  67919. sqlite3VdbeSetNumCols(v, 1);
  67920. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  67921. /* Set the maximum error count */
  67922. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  67923. if( zRight ){
  67924. mxErr = atoi(zRight);
  67925. if( mxErr<=0 ){
  67926. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  67927. }
  67928. }
  67929. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  67930. /* Do an integrity check on each database file */
  67931. for(i=0; i<db->nDb; i++){
  67932. HashElem *x;
  67933. Hash *pTbls;
  67934. int cnt = 0;
  67935. if( OMIT_TEMPDB && i==1 ) continue;
  67936. sqlite3CodeVerifySchema(pParse, i);
  67937. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  67938. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  67939. sqlite3VdbeJumpHere(v, addr);
  67940. /* Do an integrity check of the B-Tree
  67941. **
  67942. ** Begin by filling registers 2, 3, ... with the root pages numbers
  67943. ** for all tables and indices in the database.
  67944. */
  67945. pTbls = &db->aDb[i].pSchema->tblHash;
  67946. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  67947. Table *pTab = sqliteHashData(x);
  67948. Index *pIdx;
  67949. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  67950. cnt++;
  67951. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  67952. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  67953. cnt++;
  67954. }
  67955. }
  67956. /* Make sure sufficient number of registers have been allocated */
  67957. if( pParse->nMem < cnt+4 ){
  67958. pParse->nMem = cnt+4;
  67959. }
  67960. /* Do the b-tree integrity checks */
  67961. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  67962. sqlite3VdbeChangeP5(v, (u8)i);
  67963. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  67964. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  67965. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  67966. P4_DYNAMIC);
  67967. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  67968. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  67969. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  67970. sqlite3VdbeJumpHere(v, addr);
  67971. /* Make sure all the indices are constructed correctly.
  67972. */
  67973. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  67974. Table *pTab = sqliteHashData(x);
  67975. Index *pIdx;
  67976. int loopTop;
  67977. if( pTab->pIndex==0 ) continue;
  67978. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  67979. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  67980. sqlite3VdbeJumpHere(v, addr);
  67981. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  67982. sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
  67983. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
  67984. sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
  67985. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  67986. int jmp2;
  67987. static const VdbeOpList idxErr[] = {
  67988. { OP_AddImm, 1, -1, 0},
  67989. { OP_String8, 0, 3, 0}, /* 1 */
  67990. { OP_Rowid, 1, 4, 0},
  67991. { OP_String8, 0, 5, 0}, /* 3 */
  67992. { OP_String8, 0, 6, 0}, /* 4 */
  67993. { OP_Concat, 4, 3, 3},
  67994. { OP_Concat, 5, 3, 3},
  67995. { OP_Concat, 6, 3, 3},
  67996. { OP_ResultRow, 3, 1, 0},
  67997. { OP_IfPos, 1, 0, 0}, /* 9 */
  67998. { OP_Halt, 0, 0, 0},
  67999. };
  68000. sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
  68001. jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
  68002. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  68003. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  68004. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  68005. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
  68006. sqlite3VdbeJumpHere(v, addr+9);
  68007. sqlite3VdbeJumpHere(v, jmp2);
  68008. }
  68009. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
  68010. sqlite3VdbeJumpHere(v, loopTop);
  68011. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  68012. static const VdbeOpList cntIdx[] = {
  68013. { OP_Integer, 0, 3, 0},
  68014. { OP_Rewind, 0, 0, 0}, /* 1 */
  68015. { OP_AddImm, 3, 1, 0},
  68016. { OP_Next, 0, 0, 0}, /* 3 */
  68017. { OP_Eq, 2, 0, 3}, /* 4 */
  68018. { OP_AddImm, 1, -1, 0},
  68019. { OP_String8, 0, 2, 0}, /* 6 */
  68020. { OP_String8, 0, 3, 0}, /* 7 */
  68021. { OP_Concat, 3, 2, 2},
  68022. { OP_ResultRow, 2, 1, 0},
  68023. };
  68024. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
  68025. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  68026. sqlite3VdbeJumpHere(v, addr);
  68027. addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  68028. sqlite3VdbeChangeP1(v, addr+1, j+2);
  68029. sqlite3VdbeChangeP2(v, addr+1, addr+4);
  68030. sqlite3VdbeChangeP1(v, addr+3, j+2);
  68031. sqlite3VdbeChangeP2(v, addr+3, addr+2);
  68032. sqlite3VdbeJumpHere(v, addr+4);
  68033. sqlite3VdbeChangeP4(v, addr+6,
  68034. "wrong # of entries in index ", P4_STATIC);
  68035. sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
  68036. }
  68037. }
  68038. }
  68039. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  68040. sqlite3VdbeChangeP2(v, addr, -mxErr);
  68041. sqlite3VdbeJumpHere(v, addr+1);
  68042. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  68043. }else
  68044. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68045. #ifndef SQLITE_OMIT_UTF16
  68046. /*
  68047. ** PRAGMA encoding
  68048. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  68049. **
  68050. ** In its first form, this pragma returns the encoding of the main
  68051. ** database. If the database is not initialized, it is initialized now.
  68052. **
  68053. ** The second form of this pragma is a no-op if the main database file
  68054. ** has not already been initialized. In this case it sets the default
  68055. ** encoding that will be used for the main database file if a new file
  68056. ** is created. If an existing main database file is opened, then the
  68057. ** default text encoding for the existing database is used.
  68058. **
  68059. ** In all cases new databases created using the ATTACH command are
  68060. ** created to use the same default text encoding as the main database. If
  68061. ** the main database has not been initialized and/or created when ATTACH
  68062. ** is executed, this is done before the ATTACH operation.
  68063. **
  68064. ** In the second form this pragma sets the text encoding to be used in
  68065. ** new database files created using this database handle. It is only
  68066. ** useful if invoked immediately after the main database i
  68067. */
  68068. if( sqlite3StrICmp(zLeft, "encoding")==0 ){
  68069. static const struct EncName {
  68070. char *zName;
  68071. u8 enc;
  68072. } encnames[] = {
  68073. { "UTF8", SQLITE_UTF8 },
  68074. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  68075. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  68076. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  68077. { "UTF16le", SQLITE_UTF16LE },
  68078. { "UTF16be", SQLITE_UTF16BE },
  68079. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  68080. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  68081. { 0, 0 }
  68082. };
  68083. const struct EncName *pEnc;
  68084. if( !zRight ){ /* "PRAGMA encoding" */
  68085. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  68086. sqlite3VdbeSetNumCols(v, 1);
  68087. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  68088. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  68089. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  68090. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  68091. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  68092. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  68093. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  68094. }else{ /* "PRAGMA encoding = XXX" */
  68095. /* Only change the value of sqlite.enc if the database handle is not
  68096. ** initialized. If the main database exists, the new sqlite.enc value
  68097. ** will be overwritten when the schema is next loaded. If it does not
  68098. ** already exists, it will be created to use the new encoding value.
  68099. */
  68100. if(
  68101. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  68102. DbHasProperty(db, 0, DB_Empty)
  68103. ){
  68104. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  68105. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  68106. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  68107. break;
  68108. }
  68109. }
  68110. if( !pEnc->zName ){
  68111. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  68112. }
  68113. }
  68114. }
  68115. }else
  68116. #endif /* SQLITE_OMIT_UTF16 */
  68117. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  68118. /*
  68119. ** PRAGMA [database.]schema_version
  68120. ** PRAGMA [database.]schema_version = <integer>
  68121. **
  68122. ** PRAGMA [database.]user_version
  68123. ** PRAGMA [database.]user_version = <integer>
  68124. **
  68125. ** The pragma's schema_version and user_version are used to set or get
  68126. ** the value of the schema-version and user-version, respectively. Both
  68127. ** the schema-version and the user-version are 32-bit signed integers
  68128. ** stored in the database header.
  68129. **
  68130. ** The schema-cookie is usually only manipulated internally by SQLite. It
  68131. ** is incremented by SQLite whenever the database schema is modified (by
  68132. ** creating or dropping a table or index). The schema version is used by
  68133. ** SQLite each time a query is executed to ensure that the internal cache
  68134. ** of the schema used when compiling the SQL query matches the schema of
  68135. ** the database against which the compiled query is actually executed.
  68136. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  68137. ** the schema-version is potentially dangerous and may lead to program
  68138. ** crashes or database corruption. Use with caution!
  68139. **
  68140. ** The user-version is not used internally by SQLite. It may be used by
  68141. ** applications for any purpose.
  68142. */
  68143. if( sqlite3StrICmp(zLeft, "schema_version")==0
  68144. || sqlite3StrICmp(zLeft, "user_version")==0
  68145. || sqlite3StrICmp(zLeft, "freelist_count")==0
  68146. ){
  68147. int iCookie; /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
  68148. sqlite3VdbeUsesBtree(v, iDb);
  68149. switch( zLeft[0] ){
  68150. case 's': case 'S':
  68151. iCookie = 0;
  68152. break;
  68153. case 'f': case 'F':
  68154. iCookie = 1;
  68155. iDb = (-1*(iDb+1));
  68156. assert(iDb<=0);
  68157. break;
  68158. default:
  68159. iCookie = 5;
  68160. break;
  68161. }
  68162. if( zRight && iDb>=0 ){
  68163. /* Write the specified cookie value */
  68164. static const VdbeOpList setCookie[] = {
  68165. { OP_Transaction, 0, 1, 0}, /* 0 */
  68166. { OP_Integer, 0, 1, 0}, /* 1 */
  68167. { OP_SetCookie, 0, 0, 1}, /* 2 */
  68168. };
  68169. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  68170. sqlite3VdbeChangeP1(v, addr, iDb);
  68171. sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
  68172. sqlite3VdbeChangeP1(v, addr+2, iDb);
  68173. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  68174. }else{
  68175. /* Read the specified cookie value */
  68176. static const VdbeOpList readCookie[] = {
  68177. { OP_ReadCookie, 0, 1, 0}, /* 0 */
  68178. { OP_ResultRow, 1, 1, 0}
  68179. };
  68180. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  68181. sqlite3VdbeChangeP1(v, addr, iDb);
  68182. sqlite3VdbeChangeP3(v, addr, iCookie);
  68183. sqlite3VdbeSetNumCols(v, 1);
  68184. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  68185. }
  68186. }else
  68187. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  68188. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  68189. /*
  68190. ** Report the current state of file logs for all databases
  68191. */
  68192. if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
  68193. static const char *const azLockName[] = {
  68194. "unlocked", "shared", "reserved", "pending", "exclusive"
  68195. };
  68196. int i;
  68197. sqlite3VdbeSetNumCols(v, 2);
  68198. pParse->nMem = 2;
  68199. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  68200. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  68201. for(i=0; i<db->nDb; i++){
  68202. Btree *pBt;
  68203. Pager *pPager;
  68204. const char *zState = "unknown";
  68205. int j;
  68206. if( db->aDb[i].zName==0 ) continue;
  68207. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  68208. pBt = db->aDb[i].pBt;
  68209. if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
  68210. zState = "closed";
  68211. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  68212. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  68213. zState = azLockName[j];
  68214. }
  68215. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  68216. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  68217. }
  68218. }else
  68219. #endif
  68220. #ifdef SQLITE_SSE
  68221. /*
  68222. ** Check to see if the sqlite_statements table exists. Create it
  68223. ** if it does not.
  68224. */
  68225. if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
  68226. extern int sqlite3CreateStatementsTable(Parse*);
  68227. sqlite3CreateStatementsTable(pParse);
  68228. }else
  68229. #endif
  68230. #if SQLITE_HAS_CODEC
  68231. if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
  68232. sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
  68233. }else
  68234. if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
  68235. sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
  68236. }else
  68237. if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
  68238. sqlite3StrICmp(zLeft, "hexrekey")==0) ){
  68239. int i, h1, h2;
  68240. char zKey[40];
  68241. for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
  68242. h1 += 9*(1&(h1>>6));
  68243. h2 += 9*(1&(h2>>6));
  68244. zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
  68245. }
  68246. if( (zLeft[3] & 0xf)==0xb ){
  68247. sqlite3_key(db, zKey, i/2);
  68248. }else{
  68249. sqlite3_rekey(db, zKey, i/2);
  68250. }
  68251. }else
  68252. #endif
  68253. #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
  68254. if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
  68255. #if SQLITE_HAS_CODEC
  68256. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  68257. extern void sqlite3_activate_see(const char*);
  68258. sqlite3_activate_see(&zRight[4]);
  68259. }
  68260. #endif
  68261. #ifdef SQLITE_ENABLE_CEROD
  68262. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  68263. extern void sqlite3_activate_cerod(const char*);
  68264. sqlite3_activate_cerod(&zRight[6]);
  68265. }
  68266. #endif
  68267. }else
  68268. #endif
  68269. {/* Empty ELSE clause */}
  68270. /* Code an OP_Expire at the end of each PRAGMA program to cause
  68271. ** the VDBE implementing the pragma to expire. Most (all?) pragmas
  68272. ** are only valid for a single execution.
  68273. */
  68274. sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
  68275. /*
  68276. ** Reset the safety level, in case the fullfsync flag or synchronous
  68277. ** setting changed.
  68278. */
  68279. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  68280. if( db->autoCommit ){
  68281. sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
  68282. (db->flags&SQLITE_FullFSync)!=0);
  68283. }
  68284. #endif
  68285. pragma_out:
  68286. sqlite3DbFree(db, zLeft);
  68287. sqlite3DbFree(db, zRight);
  68288. }
  68289. #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
  68290. /************** End of pragma.c **********************************************/
  68291. /************** Begin file prepare.c *****************************************/
  68292. /*
  68293. ** 2005 May 25
  68294. **
  68295. ** The author disclaims copyright to this source code. In place of
  68296. ** a legal notice, here is a blessing:
  68297. **
  68298. ** May you do good and not evil.
  68299. ** May you find forgiveness for yourself and forgive others.
  68300. ** May you share freely, never taking more than you give.
  68301. **
  68302. *************************************************************************
  68303. ** This file contains the implementation of the sqlite3_prepare()
  68304. ** interface, and routines that contribute to loading the database schema
  68305. ** from disk.
  68306. **
  68307. ** $Id: prepare.c,v 1.116 2009/04/02 18:32:27 drh Exp $
  68308. */
  68309. /*
  68310. ** Fill the InitData structure with an error message that indicates
  68311. ** that the database is corrupt.
  68312. */
  68313. static void corruptSchema(
  68314. InitData *pData, /* Initialization context */
  68315. const char *zObj, /* Object being parsed at the point of error */
  68316. const char *zExtra /* Error information */
  68317. ){
  68318. sqlite3 *db = pData->db;
  68319. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  68320. if( zObj==0 ) zObj = "?";
  68321. sqlite3SetString(pData->pzErrMsg, pData->db,
  68322. "malformed database schema (%s)", zObj);
  68323. if( zExtra && zExtra[0] ){
  68324. *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
  68325. *pData->pzErrMsg, zExtra);
  68326. }
  68327. }
  68328. pData->rc = SQLITE_CORRUPT;
  68329. }
  68330. /*
  68331. ** This is the callback routine for the code that initializes the
  68332. ** database. See sqlite3Init() below for additional information.
  68333. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  68334. **
  68335. ** Each callback contains the following information:
  68336. **
  68337. ** argv[0] = name of thing being created
  68338. ** argv[1] = root page number for table or index. 0 for trigger or view.
  68339. ** argv[2] = SQL text for the CREATE statement.
  68340. **
  68341. */
  68342. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  68343. InitData *pData = (InitData*)pInit;
  68344. sqlite3 *db = pData->db;
  68345. int iDb = pData->iDb;
  68346. assert( argc==3 );
  68347. UNUSED_PARAMETER2(NotUsed, argc);
  68348. assert( sqlite3_mutex_held(db->mutex) );
  68349. DbClearProperty(db, iDb, DB_Empty);
  68350. if( db->mallocFailed ){
  68351. corruptSchema(pData, argv[0], 0);
  68352. return SQLITE_NOMEM;
  68353. }
  68354. assert( iDb>=0 && iDb<db->nDb );
  68355. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  68356. if( argv[1]==0 ){
  68357. corruptSchema(pData, argv[0], 0);
  68358. }else if( argv[2] && argv[2][0] ){
  68359. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  68360. ** But because db->init.busy is set to 1, no VDBE code is generated
  68361. ** or executed. All the parser does is build the internal data
  68362. ** structures that describe the table, index, or view.
  68363. */
  68364. char *zErr;
  68365. int rc;
  68366. assert( db->init.busy );
  68367. db->init.iDb = iDb;
  68368. db->init.newTnum = atoi(argv[1]);
  68369. rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
  68370. db->init.iDb = 0;
  68371. assert( rc!=SQLITE_OK || zErr==0 );
  68372. if( SQLITE_OK!=rc ){
  68373. pData->rc = rc;
  68374. if( rc==SQLITE_NOMEM ){
  68375. db->mallocFailed = 1;
  68376. }else if( rc!=SQLITE_INTERRUPT && (rc&0xff)!=SQLITE_LOCKED ){
  68377. corruptSchema(pData, argv[0], zErr);
  68378. }
  68379. sqlite3DbFree(db, zErr);
  68380. }
  68381. }else if( argv[0]==0 ){
  68382. corruptSchema(pData, 0, 0);
  68383. }else{
  68384. /* If the SQL column is blank it means this is an index that
  68385. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  68386. ** constraint for a CREATE TABLE. The index should have already
  68387. ** been created when we processed the CREATE TABLE. All we have
  68388. ** to do here is record the root page number for that index.
  68389. */
  68390. Index *pIndex;
  68391. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  68392. if( pIndex==0 || pIndex->tnum!=0 ){
  68393. /* This can occur if there exists an index on a TEMP table which
  68394. ** has the same name as another index on a permanent index. Since
  68395. ** the permanent table is hidden by the TEMP table, we can also
  68396. ** safely ignore the index on the permanent table.
  68397. */
  68398. /* Do Nothing */;
  68399. }else{
  68400. pIndex->tnum = atoi(argv[1]);
  68401. }
  68402. }
  68403. return 0;
  68404. }
  68405. /*
  68406. ** Attempt to read the database schema and initialize internal
  68407. ** data structures for a single database file. The index of the
  68408. ** database file is given by iDb. iDb==0 is used for the main
  68409. ** database. iDb==1 should never be used. iDb>=2 is used for
  68410. ** auxiliary databases. Return one of the SQLITE_ error codes to
  68411. ** indicate success or failure.
  68412. */
  68413. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  68414. int rc;
  68415. BtCursor *curMain;
  68416. int size;
  68417. Table *pTab;
  68418. Db *pDb;
  68419. char const *azArg[4];
  68420. int meta[10];
  68421. InitData initData;
  68422. char const *zMasterSchema;
  68423. char const *zMasterName = SCHEMA_TABLE(iDb);
  68424. /*
  68425. ** The master database table has a structure like this
  68426. */
  68427. static const char master_schema[] =
  68428. "CREATE TABLE sqlite_master(\n"
  68429. " type text,\n"
  68430. " name text,\n"
  68431. " tbl_name text,\n"
  68432. " rootpage integer,\n"
  68433. " sql text\n"
  68434. ")"
  68435. ;
  68436. #ifndef SQLITE_OMIT_TEMPDB
  68437. static const char temp_master_schema[] =
  68438. "CREATE TEMP TABLE sqlite_temp_master(\n"
  68439. " type text,\n"
  68440. " name text,\n"
  68441. " tbl_name text,\n"
  68442. " rootpage integer,\n"
  68443. " sql text\n"
  68444. ")"
  68445. ;
  68446. #else
  68447. #define temp_master_schema 0
  68448. #endif
  68449. assert( iDb>=0 && iDb<db->nDb );
  68450. assert( db->aDb[iDb].pSchema );
  68451. assert( sqlite3_mutex_held(db->mutex) );
  68452. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  68453. /* zMasterSchema and zInitScript are set to point at the master schema
  68454. ** and initialisation script appropriate for the database being
  68455. ** initialised. zMasterName is the name of the master table.
  68456. */
  68457. if( !OMIT_TEMPDB && iDb==1 ){
  68458. zMasterSchema = temp_master_schema;
  68459. }else{
  68460. zMasterSchema = master_schema;
  68461. }
  68462. zMasterName = SCHEMA_TABLE(iDb);
  68463. /* Construct the schema tables. */
  68464. azArg[0] = zMasterName;
  68465. azArg[1] = "1";
  68466. azArg[2] = zMasterSchema;
  68467. azArg[3] = 0;
  68468. initData.db = db;
  68469. initData.iDb = iDb;
  68470. initData.rc = SQLITE_OK;
  68471. initData.pzErrMsg = pzErrMsg;
  68472. (void)sqlite3SafetyOff(db);
  68473. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  68474. (void)sqlite3SafetyOn(db);
  68475. if( initData.rc ){
  68476. rc = initData.rc;
  68477. goto error_out;
  68478. }
  68479. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  68480. if( pTab ){
  68481. pTab->tabFlags |= TF_Readonly;
  68482. }
  68483. /* Create a cursor to hold the database open
  68484. */
  68485. pDb = &db->aDb[iDb];
  68486. if( pDb->pBt==0 ){
  68487. if( !OMIT_TEMPDB && iDb==1 ){
  68488. DbSetProperty(db, 1, DB_SchemaLoaded);
  68489. }
  68490. return SQLITE_OK;
  68491. }
  68492. curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
  68493. if( !curMain ){
  68494. rc = SQLITE_NOMEM;
  68495. goto error_out;
  68496. }
  68497. sqlite3BtreeEnter(pDb->pBt);
  68498. rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
  68499. if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
  68500. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  68501. goto initone_error_out;
  68502. }
  68503. /* Get the database meta information.
  68504. **
  68505. ** Meta values are as follows:
  68506. ** meta[0] Schema cookie. Changes with each schema change.
  68507. ** meta[1] File format of schema layer.
  68508. ** meta[2] Size of the page cache.
  68509. ** meta[3] Use freelist if 0. Autovacuum if greater than zero.
  68510. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  68511. ** meta[5] The user cookie. Used by the application.
  68512. ** meta[6] Incremental-vacuum flag.
  68513. ** meta[7]
  68514. ** meta[8]
  68515. ** meta[9]
  68516. **
  68517. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  68518. ** the possible values of meta[4].
  68519. */
  68520. if( rc==SQLITE_OK ){
  68521. int i;
  68522. for(i=0; i<ArraySize(meta); i++){
  68523. rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  68524. if( rc ){
  68525. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  68526. goto initone_error_out;
  68527. }
  68528. }
  68529. }else{
  68530. memset(meta, 0, sizeof(meta));
  68531. }
  68532. pDb->pSchema->schema_cookie = meta[0];
  68533. /* If opening a non-empty database, check the text encoding. For the
  68534. ** main database, set sqlite3.enc to the encoding of the main database.
  68535. ** For an attached db, it is an error if the encoding is not the same
  68536. ** as sqlite3.enc.
  68537. */
  68538. if( meta[4] ){ /* text encoding */
  68539. if( iDb==0 ){
  68540. /* If opening the main database, set ENC(db). */
  68541. ENC(db) = (u8)meta[4];
  68542. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
  68543. }else{
  68544. /* If opening an attached database, the encoding much match ENC(db) */
  68545. if( meta[4]!=ENC(db) ){
  68546. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  68547. " text encoding as main database");
  68548. rc = SQLITE_ERROR;
  68549. goto initone_error_out;
  68550. }
  68551. }
  68552. }else{
  68553. DbSetProperty(db, iDb, DB_Empty);
  68554. }
  68555. pDb->pSchema->enc = ENC(db);
  68556. if( pDb->pSchema->cache_size==0 ){
  68557. size = meta[2];
  68558. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  68559. if( size<0 ) size = -size;
  68560. pDb->pSchema->cache_size = size;
  68561. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  68562. }
  68563. /*
  68564. ** file_format==1 Version 3.0.0.
  68565. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  68566. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  68567. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  68568. */
  68569. pDb->pSchema->file_format = (u8)meta[1];
  68570. if( pDb->pSchema->file_format==0 ){
  68571. pDb->pSchema->file_format = 1;
  68572. }
  68573. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  68574. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  68575. rc = SQLITE_ERROR;
  68576. goto initone_error_out;
  68577. }
  68578. /* Ticket #2804: When we open a database in the newer file format,
  68579. ** clear the legacy_file_format pragma flag so that a VACUUM will
  68580. ** not downgrade the database and thus invalidate any descending
  68581. ** indices that the user might have created.
  68582. */
  68583. if( iDb==0 && meta[1]>=4 ){
  68584. db->flags &= ~SQLITE_LegacyFileFmt;
  68585. }
  68586. /* Read the schema information out of the schema tables
  68587. */
  68588. assert( db->init.busy );
  68589. if( rc==SQLITE_EMPTY ){
  68590. /* For an empty database, there is nothing to read */
  68591. rc = SQLITE_OK;
  68592. }else{
  68593. char *zSql;
  68594. zSql = sqlite3MPrintf(db,
  68595. "SELECT name, rootpage, sql FROM '%q'.%s",
  68596. db->aDb[iDb].zName, zMasterName);
  68597. (void)sqlite3SafetyOff(db);
  68598. #ifndef SQLITE_OMIT_AUTHORIZATION
  68599. {
  68600. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  68601. xAuth = db->xAuth;
  68602. db->xAuth = 0;
  68603. #endif
  68604. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  68605. #ifndef SQLITE_OMIT_AUTHORIZATION
  68606. db->xAuth = xAuth;
  68607. }
  68608. #endif
  68609. if( rc==SQLITE_OK ) rc = initData.rc;
  68610. (void)sqlite3SafetyOn(db);
  68611. sqlite3DbFree(db, zSql);
  68612. #ifndef SQLITE_OMIT_ANALYZE
  68613. if( rc==SQLITE_OK ){
  68614. sqlite3AnalysisLoad(db, iDb);
  68615. }
  68616. #endif
  68617. }
  68618. if( db->mallocFailed ){
  68619. rc = SQLITE_NOMEM;
  68620. sqlite3ResetInternalSchema(db, 0);
  68621. }
  68622. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  68623. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  68624. ** the schema loaded, even if errors occurred. In this situation the
  68625. ** current sqlite3_prepare() operation will fail, but the following one
  68626. ** will attempt to compile the supplied statement against whatever subset
  68627. ** of the schema was loaded before the error occurred. The primary
  68628. ** purpose of this is to allow access to the sqlite_master table
  68629. ** even when its contents have been corrupted.
  68630. */
  68631. DbSetProperty(db, iDb, DB_SchemaLoaded);
  68632. rc = SQLITE_OK;
  68633. }
  68634. /* Jump here for an error that occurs after successfully allocating
  68635. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  68636. ** before that point, jump to error_out.
  68637. */
  68638. initone_error_out:
  68639. sqlite3BtreeCloseCursor(curMain);
  68640. sqlite3_free(curMain);
  68641. sqlite3BtreeLeave(pDb->pBt);
  68642. error_out:
  68643. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  68644. db->mallocFailed = 1;
  68645. }
  68646. return rc;
  68647. }
  68648. /*
  68649. ** Initialize all database files - the main database file, the file
  68650. ** used to store temporary tables, and any additional database files
  68651. ** created using ATTACH statements. Return a success code. If an
  68652. ** error occurs, write an error message into *pzErrMsg.
  68653. **
  68654. ** After a database is initialized, the DB_SchemaLoaded bit is set
  68655. ** bit is set in the flags field of the Db structure. If the database
  68656. ** file was of zero-length, then the DB_Empty flag is also set.
  68657. */
  68658. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  68659. int i, rc;
  68660. int commit_internal = !(db->flags&SQLITE_InternChanges);
  68661. assert( sqlite3_mutex_held(db->mutex) );
  68662. if( db->init.busy ) return SQLITE_OK;
  68663. rc = SQLITE_OK;
  68664. db->init.busy = 1;
  68665. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68666. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  68667. rc = sqlite3InitOne(db, i, pzErrMsg);
  68668. if( rc ){
  68669. sqlite3ResetInternalSchema(db, i);
  68670. }
  68671. }
  68672. /* Once all the other databases have been initialised, load the schema
  68673. ** for the TEMP database. This is loaded last, as the TEMP database
  68674. ** schema may contain references to objects in other databases.
  68675. */
  68676. #ifndef SQLITE_OMIT_TEMPDB
  68677. if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  68678. rc = sqlite3InitOne(db, 1, pzErrMsg);
  68679. if( rc ){
  68680. sqlite3ResetInternalSchema(db, 1);
  68681. }
  68682. }
  68683. #endif
  68684. db->init.busy = 0;
  68685. if( rc==SQLITE_OK && commit_internal ){
  68686. sqlite3CommitInternalChanges(db);
  68687. }
  68688. return rc;
  68689. }
  68690. /*
  68691. ** This routine is a no-op if the database schema is already initialised.
  68692. ** Otherwise, the schema is loaded. An error code is returned.
  68693. */
  68694. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  68695. int rc = SQLITE_OK;
  68696. sqlite3 *db = pParse->db;
  68697. assert( sqlite3_mutex_held(db->mutex) );
  68698. if( !db->init.busy ){
  68699. rc = sqlite3Init(db, &pParse->zErrMsg);
  68700. }
  68701. if( rc!=SQLITE_OK ){
  68702. pParse->rc = rc;
  68703. pParse->nErr++;
  68704. }
  68705. return rc;
  68706. }
  68707. /*
  68708. ** Check schema cookies in all databases. If any cookie is out
  68709. ** of date, return 0. If all schema cookies are current, return 1.
  68710. */
  68711. static int schemaIsValid(sqlite3 *db){
  68712. int iDb;
  68713. int rc;
  68714. BtCursor *curTemp;
  68715. int cookie;
  68716. int allOk = 1;
  68717. curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
  68718. if( curTemp ){
  68719. assert( sqlite3_mutex_held(db->mutex) );
  68720. for(iDb=0; allOk && iDb<db->nDb; iDb++){
  68721. Btree *pBt;
  68722. pBt = db->aDb[iDb].pBt;
  68723. if( pBt==0 ) continue;
  68724. memset(curTemp, 0, sqlite3BtreeCursorSize());
  68725. rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
  68726. if( rc==SQLITE_OK ){
  68727. rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
  68728. if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  68729. allOk = 0;
  68730. }
  68731. sqlite3BtreeCloseCursor(curTemp);
  68732. }
  68733. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  68734. db->mallocFailed = 1;
  68735. }
  68736. }
  68737. sqlite3_free(curTemp);
  68738. }else{
  68739. allOk = 0;
  68740. db->mallocFailed = 1;
  68741. }
  68742. return allOk;
  68743. }
  68744. /*
  68745. ** Convert a schema pointer into the iDb index that indicates
  68746. ** which database file in db->aDb[] the schema refers to.
  68747. **
  68748. ** If the same database is attached more than once, the first
  68749. ** attached database is returned.
  68750. */
  68751. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  68752. int i = -1000000;
  68753. /* If pSchema is NULL, then return -1000000. This happens when code in
  68754. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  68755. ** created by a sub-select). In this case the return value of this
  68756. ** function should never be used.
  68757. **
  68758. ** We return -1000000 instead of the more usual -1 simply because using
  68759. ** -1000000 as the incorrect index into db->aDb[] is much
  68760. ** more likely to cause a segfault than -1 (of course there are assert()
  68761. ** statements too, but it never hurts to play the odds).
  68762. */
  68763. assert( sqlite3_mutex_held(db->mutex) );
  68764. if( pSchema ){
  68765. for(i=0; ALWAYS(i<db->nDb); i++){
  68766. if( db->aDb[i].pSchema==pSchema ){
  68767. break;
  68768. }
  68769. }
  68770. assert( i>=0 && i<db->nDb );
  68771. }
  68772. return i;
  68773. }
  68774. /*
  68775. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  68776. */
  68777. static int sqlite3Prepare(
  68778. sqlite3 *db, /* Database handle. */
  68779. const char *zSql, /* UTF-8 encoded SQL statement. */
  68780. int nBytes, /* Length of zSql in bytes. */
  68781. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  68782. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  68783. const char **pzTail /* OUT: End of parsed string */
  68784. ){
  68785. Parse sParse;
  68786. char *zErrMsg = 0;
  68787. int rc = SQLITE_OK;
  68788. int i;
  68789. if( sqlite3SafetyOn(db) ) return SQLITE_MISUSE;
  68790. assert( ppStmt && *ppStmt==0 );
  68791. assert( !db->mallocFailed );
  68792. assert( sqlite3_mutex_held(db->mutex) );
  68793. /* Check to verify that it is possible to get a read lock on all
  68794. ** database schemas. The inability to get a read lock indicates that
  68795. ** some other database connection is holding a write-lock, which in
  68796. ** turn means that the other connection has made uncommitted changes
  68797. ** to the schema.
  68798. **
  68799. ** Were we to proceed and prepare the statement against the uncommitted
  68800. ** schema changes and if those schema changes are subsequently rolled
  68801. ** back and different changes are made in their place, then when this
  68802. ** prepared statement goes to run the schema cookie would fail to detect
  68803. ** the schema change. Disaster would follow.
  68804. **
  68805. ** This thread is currently holding mutexes on all Btrees (because
  68806. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  68807. ** is not possible for another thread to start a new schema change
  68808. ** while this routine is running. Hence, we do not need to hold
  68809. ** locks on the schema, we just need to make sure nobody else is
  68810. ** holding them.
  68811. **
  68812. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  68813. ** but it does *not* override schema lock detection, so this all still
  68814. ** works even if READ_UNCOMMITTED is set.
  68815. */
  68816. for(i=0; i<db->nDb; i++) {
  68817. Btree *pBt = db->aDb[i].pBt;
  68818. if( pBt ){
  68819. assert( sqlite3BtreeHoldsMutex(pBt) );
  68820. rc = sqlite3BtreeSchemaLocked(pBt);
  68821. if( rc ){
  68822. const char *zDb = db->aDb[i].zName;
  68823. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  68824. (void)sqlite3SafetyOff(db);
  68825. testcase( db->flags & SQLITE_ReadUncommitted );
  68826. return sqlite3ApiExit(db, rc);
  68827. }
  68828. }
  68829. }
  68830. memset(&sParse, 0, sizeof(sParse));
  68831. sParse.db = db;
  68832. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  68833. char *zSqlCopy;
  68834. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  68835. if( nBytes>mxLen ){
  68836. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  68837. (void)sqlite3SafetyOff(db);
  68838. return sqlite3ApiExit(db, SQLITE_TOOBIG);
  68839. }
  68840. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  68841. if( zSqlCopy ){
  68842. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  68843. sqlite3DbFree(db, zSqlCopy);
  68844. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  68845. }else{
  68846. sParse.zTail = &zSql[nBytes];
  68847. }
  68848. }else{
  68849. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  68850. }
  68851. if( db->mallocFailed ){
  68852. sParse.rc = SQLITE_NOMEM;
  68853. }
  68854. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  68855. if( sParse.checkSchema && !schemaIsValid(db) ){
  68856. sParse.rc = SQLITE_SCHEMA;
  68857. }
  68858. if( sParse.rc==SQLITE_SCHEMA ){
  68859. sqlite3ResetInternalSchema(db, 0);
  68860. }
  68861. if( db->mallocFailed ){
  68862. sParse.rc = SQLITE_NOMEM;
  68863. }
  68864. if( pzTail ){
  68865. *pzTail = sParse.zTail;
  68866. }
  68867. rc = sParse.rc;
  68868. #ifndef SQLITE_OMIT_EXPLAIN
  68869. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  68870. if( sParse.explain==2 ){
  68871. sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
  68872. sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", SQLITE_STATIC);
  68873. sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", SQLITE_STATIC);
  68874. sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", SQLITE_STATIC);
  68875. }else{
  68876. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  68877. sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", SQLITE_STATIC);
  68878. sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", SQLITE_STATIC);
  68879. sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", SQLITE_STATIC);
  68880. sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", SQLITE_STATIC);
  68881. sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", SQLITE_STATIC);
  68882. sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", SQLITE_STATIC);
  68883. sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", SQLITE_STATIC);
  68884. sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment", SQLITE_STATIC);
  68885. }
  68886. }
  68887. #endif
  68888. if( sqlite3SafetyOff(db) ){
  68889. rc = SQLITE_MISUSE;
  68890. }
  68891. assert( db->init.busy==0 || saveSqlFlag==0 );
  68892. if( db->init.busy==0 ){
  68893. Vdbe *pVdbe = sParse.pVdbe;
  68894. sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag);
  68895. }
  68896. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  68897. sqlite3VdbeFinalize(sParse.pVdbe);
  68898. assert(!(*ppStmt));
  68899. }else{
  68900. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  68901. }
  68902. if( zErrMsg ){
  68903. sqlite3Error(db, rc, "%s", zErrMsg);
  68904. sqlite3DbFree(db, zErrMsg);
  68905. }else{
  68906. sqlite3Error(db, rc, 0);
  68907. }
  68908. rc = sqlite3ApiExit(db, rc);
  68909. assert( (rc&db->errMask)==rc );
  68910. return rc;
  68911. }
  68912. static int sqlite3LockAndPrepare(
  68913. sqlite3 *db, /* Database handle. */
  68914. const char *zSql, /* UTF-8 encoded SQL statement. */
  68915. int nBytes, /* Length of zSql in bytes. */
  68916. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  68917. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  68918. const char **pzTail /* OUT: End of parsed string */
  68919. ){
  68920. int rc;
  68921. assert( ppStmt!=0 );
  68922. *ppStmt = 0;
  68923. if( !sqlite3SafetyCheckOk(db) ){
  68924. return SQLITE_MISUSE;
  68925. }
  68926. sqlite3_mutex_enter(db->mutex);
  68927. sqlite3BtreeEnterAll(db);
  68928. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
  68929. sqlite3BtreeLeaveAll(db);
  68930. sqlite3_mutex_leave(db->mutex);
  68931. return rc;
  68932. }
  68933. /*
  68934. ** Rerun the compilation of a statement after a schema change.
  68935. **
  68936. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  68937. ** if the statement cannot be recompiled because another connection has
  68938. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  68939. ** occurs, return SQLITE_SCHEMA.
  68940. */
  68941. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  68942. int rc;
  68943. sqlite3_stmt *pNew;
  68944. const char *zSql;
  68945. sqlite3 *db;
  68946. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  68947. zSql = sqlite3_sql((sqlite3_stmt *)p);
  68948. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  68949. db = sqlite3VdbeDb(p);
  68950. assert( sqlite3_mutex_held(db->mutex) );
  68951. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
  68952. if( rc ){
  68953. if( rc==SQLITE_NOMEM ){
  68954. db->mallocFailed = 1;
  68955. }
  68956. assert( pNew==0 );
  68957. return (rc==SQLITE_LOCKED) ? SQLITE_LOCKED : SQLITE_SCHEMA;
  68958. }else{
  68959. assert( pNew!=0 );
  68960. }
  68961. sqlite3VdbeSwap((Vdbe*)pNew, p);
  68962. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  68963. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  68964. sqlite3VdbeFinalize((Vdbe*)pNew);
  68965. return SQLITE_OK;
  68966. }
  68967. /*
  68968. ** Two versions of the official API. Legacy and new use. In the legacy
  68969. ** version, the original SQL text is not saved in the prepared statement
  68970. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  68971. ** sqlite3_step(). In the new version, the original SQL text is retained
  68972. ** and the statement is automatically recompiled if an schema change
  68973. ** occurs.
  68974. */
  68975. SQLITE_API int sqlite3_prepare(
  68976. sqlite3 *db, /* Database handle. */
  68977. const char *zSql, /* UTF-8 encoded SQL statement. */
  68978. int nBytes, /* Length of zSql in bytes. */
  68979. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  68980. const char **pzTail /* OUT: End of parsed string */
  68981. ){
  68982. int rc;
  68983. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
  68984. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  68985. return rc;
  68986. }
  68987. SQLITE_API int sqlite3_prepare_v2(
  68988. sqlite3 *db, /* Database handle. */
  68989. const char *zSql, /* UTF-8 encoded SQL statement. */
  68990. int nBytes, /* Length of zSql in bytes. */
  68991. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  68992. const char **pzTail /* OUT: End of parsed string */
  68993. ){
  68994. int rc;
  68995. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
  68996. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  68997. return rc;
  68998. }
  68999. #ifndef SQLITE_OMIT_UTF16
  69000. /*
  69001. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  69002. */
  69003. static int sqlite3Prepare16(
  69004. sqlite3 *db, /* Database handle. */
  69005. const void *zSql, /* UTF-8 encoded SQL statement. */
  69006. int nBytes, /* Length of zSql in bytes. */
  69007. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  69008. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  69009. const void **pzTail /* OUT: End of parsed string */
  69010. ){
  69011. /* This function currently works by first transforming the UTF-16
  69012. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  69013. ** tricky bit is figuring out the pointer to return in *pzTail.
  69014. */
  69015. char *zSql8;
  69016. const char *zTail8 = 0;
  69017. int rc = SQLITE_OK;
  69018. assert( ppStmt );
  69019. *ppStmt = 0;
  69020. if( !sqlite3SafetyCheckOk(db) ){
  69021. return SQLITE_MISUSE;
  69022. }
  69023. sqlite3_mutex_enter(db->mutex);
  69024. zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
  69025. if( zSql8 ){
  69026. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
  69027. }
  69028. if( zTail8 && pzTail ){
  69029. /* If sqlite3_prepare returns a tail pointer, we calculate the
  69030. ** equivalent pointer into the UTF-16 string by counting the unicode
  69031. ** characters between zSql8 and zTail8, and then returning a pointer
  69032. ** the same number of characters into the UTF-16 string.
  69033. */
  69034. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  69035. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  69036. }
  69037. sqlite3DbFree(db, zSql8);
  69038. rc = sqlite3ApiExit(db, rc);
  69039. sqlite3_mutex_leave(db->mutex);
  69040. return rc;
  69041. }
  69042. /*
  69043. ** Two versions of the official API. Legacy and new use. In the legacy
  69044. ** version, the original SQL text is not saved in the prepared statement
  69045. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  69046. ** sqlite3_step(). In the new version, the original SQL text is retained
  69047. ** and the statement is automatically recompiled if an schema change
  69048. ** occurs.
  69049. */
  69050. SQLITE_API int sqlite3_prepare16(
  69051. sqlite3 *db, /* Database handle. */
  69052. const void *zSql, /* UTF-8 encoded SQL statement. */
  69053. int nBytes, /* Length of zSql in bytes. */
  69054. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  69055. const void **pzTail /* OUT: End of parsed string */
  69056. ){
  69057. int rc;
  69058. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  69059. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  69060. return rc;
  69061. }
  69062. SQLITE_API int sqlite3_prepare16_v2(
  69063. sqlite3 *db, /* Database handle. */
  69064. const void *zSql, /* UTF-8 encoded SQL statement. */
  69065. int nBytes, /* Length of zSql in bytes. */
  69066. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  69067. const void **pzTail /* OUT: End of parsed string */
  69068. ){
  69069. int rc;
  69070. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  69071. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  69072. return rc;
  69073. }
  69074. #endif /* SQLITE_OMIT_UTF16 */
  69075. /************** End of prepare.c *********************************************/
  69076. /************** Begin file select.c ******************************************/
  69077. /*
  69078. ** 2001 September 15
  69079. **
  69080. ** The author disclaims copyright to this source code. In place of
  69081. ** a legal notice, here is a blessing:
  69082. **
  69083. ** May you do good and not evil.
  69084. ** May you find forgiveness for yourself and forgive others.
  69085. ** May you share freely, never taking more than you give.
  69086. **
  69087. *************************************************************************
  69088. ** This file contains C code routines that are called by the parser
  69089. ** to handle SELECT statements in SQLite.
  69090. **
  69091. ** $Id: select.c,v 1.507 2009/04/02 16:59:47 drh Exp $
  69092. */
  69093. /*
  69094. ** Delete all the content of a Select structure but do not deallocate
  69095. ** the select structure itself.
  69096. */
  69097. static void clearSelect(sqlite3 *db, Select *p){
  69098. sqlite3ExprListDelete(db, p->pEList);
  69099. sqlite3SrcListDelete(db, p->pSrc);
  69100. sqlite3ExprDelete(db, p->pWhere);
  69101. sqlite3ExprListDelete(db, p->pGroupBy);
  69102. sqlite3ExprDelete(db, p->pHaving);
  69103. sqlite3ExprListDelete(db, p->pOrderBy);
  69104. sqlite3SelectDelete(db, p->pPrior);
  69105. sqlite3ExprDelete(db, p->pLimit);
  69106. sqlite3ExprDelete(db, p->pOffset);
  69107. }
  69108. /*
  69109. ** Initialize a SelectDest structure.
  69110. */
  69111. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  69112. pDest->eDest = (u8)eDest;
  69113. pDest->iParm = iParm;
  69114. pDest->affinity = 0;
  69115. pDest->iMem = 0;
  69116. pDest->nMem = 0;
  69117. }
  69118. /*
  69119. ** Allocate a new Select structure and return a pointer to that
  69120. ** structure.
  69121. */
  69122. SQLITE_PRIVATE Select *sqlite3SelectNew(
  69123. Parse *pParse, /* Parsing context */
  69124. ExprList *pEList, /* which columns to include in the result */
  69125. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  69126. Expr *pWhere, /* the WHERE clause */
  69127. ExprList *pGroupBy, /* the GROUP BY clause */
  69128. Expr *pHaving, /* the HAVING clause */
  69129. ExprList *pOrderBy, /* the ORDER BY clause */
  69130. int isDistinct, /* true if the DISTINCT keyword is present */
  69131. Expr *pLimit, /* LIMIT value. NULL means not used */
  69132. Expr *pOffset /* OFFSET value. NULL means no offset */
  69133. ){
  69134. Select *pNew;
  69135. Select standin;
  69136. sqlite3 *db = pParse->db;
  69137. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  69138. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  69139. if( pNew==0 ){
  69140. pNew = &standin;
  69141. memset(pNew, 0, sizeof(*pNew));
  69142. }
  69143. if( pEList==0 ){
  69144. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
  69145. }
  69146. pNew->pEList = pEList;
  69147. pNew->pSrc = pSrc;
  69148. pNew->pWhere = pWhere;
  69149. pNew->pGroupBy = pGroupBy;
  69150. pNew->pHaving = pHaving;
  69151. pNew->pOrderBy = pOrderBy;
  69152. pNew->selFlags = isDistinct ? SF_Distinct : 0;
  69153. pNew->op = TK_SELECT;
  69154. pNew->pLimit = pLimit;
  69155. pNew->pOffset = pOffset;
  69156. pNew->addrOpenEphm[0] = -1;
  69157. pNew->addrOpenEphm[1] = -1;
  69158. pNew->addrOpenEphm[2] = -1;
  69159. if( db->mallocFailed ) {
  69160. clearSelect(db, pNew);
  69161. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  69162. pNew = 0;
  69163. }
  69164. return pNew;
  69165. }
  69166. /*
  69167. ** Delete the given Select structure and all of its substructures.
  69168. */
  69169. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  69170. if( p ){
  69171. clearSelect(db, p);
  69172. sqlite3DbFree(db, p);
  69173. }
  69174. }
  69175. /*
  69176. ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  69177. ** type of join. Return an integer constant that expresses that type
  69178. ** in terms of the following bit values:
  69179. **
  69180. ** JT_INNER
  69181. ** JT_CROSS
  69182. ** JT_OUTER
  69183. ** JT_NATURAL
  69184. ** JT_LEFT
  69185. ** JT_RIGHT
  69186. **
  69187. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  69188. **
  69189. ** If an illegal or unsupported join type is seen, then still return
  69190. ** a join type, but put an error in the pParse structure.
  69191. */
  69192. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  69193. int jointype = 0;
  69194. Token *apAll[3];
  69195. Token *p;
  69196. static const struct {
  69197. const char zKeyword[8];
  69198. u8 nChar;
  69199. u8 code;
  69200. } keywords[] = {
  69201. { "natural", 7, JT_NATURAL },
  69202. { "left", 4, JT_LEFT|JT_OUTER },
  69203. { "right", 5, JT_RIGHT|JT_OUTER },
  69204. { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  69205. { "outer", 5, JT_OUTER },
  69206. { "inner", 5, JT_INNER },
  69207. { "cross", 5, JT_INNER|JT_CROSS },
  69208. };
  69209. int i, j;
  69210. apAll[0] = pA;
  69211. apAll[1] = pB;
  69212. apAll[2] = pC;
  69213. for(i=0; i<3 && apAll[i]; i++){
  69214. p = apAll[i];
  69215. for(j=0; j<ArraySize(keywords); j++){
  69216. if( p->n==keywords[j].nChar
  69217. && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
  69218. jointype |= keywords[j].code;
  69219. break;
  69220. }
  69221. }
  69222. if( j>=ArraySize(keywords) ){
  69223. jointype |= JT_ERROR;
  69224. break;
  69225. }
  69226. }
  69227. if(
  69228. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  69229. (jointype & JT_ERROR)!=0
  69230. ){
  69231. const char *zSp = " ";
  69232. assert( pB!=0 );
  69233. if( pC==0 ){ zSp++; }
  69234. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  69235. "%T %T%s%T", pA, pB, zSp, pC);
  69236. jointype = JT_INNER;
  69237. }else if( jointype & JT_RIGHT ){
  69238. sqlite3ErrorMsg(pParse,
  69239. "RIGHT and FULL OUTER JOINs are not currently supported");
  69240. jointype = JT_INNER;
  69241. }
  69242. return jointype;
  69243. }
  69244. /*
  69245. ** Return the index of a column in a table. Return -1 if the column
  69246. ** is not contained in the table.
  69247. */
  69248. static int columnIndex(Table *pTab, const char *zCol){
  69249. int i;
  69250. for(i=0; i<pTab->nCol; i++){
  69251. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  69252. }
  69253. return -1;
  69254. }
  69255. /*
  69256. ** Set the value of a token to a '\000'-terminated string.
  69257. */
  69258. static void setToken(Token *p, const char *z){
  69259. p->z = (u8*)z;
  69260. p->n = z ? sqlite3Strlen30(z) : 0;
  69261. p->dyn = 0;
  69262. }
  69263. /*
  69264. ** Set the token to the double-quoted and escaped version of the string pointed
  69265. ** to by z. For example;
  69266. **
  69267. ** {a"bc} -> {"a""bc"}
  69268. */
  69269. static void setQuotedToken(Parse *pParse, Token *p, const char *z){
  69270. /* Check if the string appears to be quoted using "..." or `...`
  69271. ** or [...] or '...' or if the string contains any " characters.
  69272. ** If it does, then record a version of the string with the special
  69273. ** characters escaped.
  69274. */
  69275. const char *z2 = z;
  69276. if( *z2!='[' && *z2!='`' && *z2!='\'' ){
  69277. while( *z2 ){
  69278. if( *z2=='"' ) break;
  69279. z2++;
  69280. }
  69281. }
  69282. if( *z2 ){
  69283. /* String contains " characters - copy and quote the string. */
  69284. p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
  69285. if( p->z ){
  69286. p->n = sqlite3Strlen30((char *)p->z);
  69287. p->dyn = 1;
  69288. }
  69289. }else{
  69290. /* String contains no " characters - copy the pointer. */
  69291. p->z = (u8*)z;
  69292. p->n = (int)(z2 - z);
  69293. p->dyn = 0;
  69294. }
  69295. }
  69296. /*
  69297. ** Create an expression node for an identifier with the name of zName
  69298. */
  69299. SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
  69300. Token dummy;
  69301. setToken(&dummy, zName);
  69302. return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
  69303. }
  69304. /*
  69305. ** Add a term to the WHERE expression in *ppExpr that requires the
  69306. ** zCol column to be equal in the two tables pTab1 and pTab2.
  69307. */
  69308. static void addWhereTerm(
  69309. Parse *pParse, /* Parsing context */
  69310. const char *zCol, /* Name of the column */
  69311. const Table *pTab1, /* First table */
  69312. const char *zAlias1, /* Alias for first table. May be NULL */
  69313. const Table *pTab2, /* Second table */
  69314. const char *zAlias2, /* Alias for second table. May be NULL */
  69315. int iRightJoinTable, /* VDBE cursor for the right table */
  69316. Expr **ppExpr, /* Add the equality term to this expression */
  69317. int isOuterJoin /* True if dealing with an OUTER join */
  69318. ){
  69319. Expr *pE1a, *pE1b, *pE1c;
  69320. Expr *pE2a, *pE2b, *pE2c;
  69321. Expr *pE;
  69322. pE1a = sqlite3CreateIdExpr(pParse, zCol);
  69323. pE2a = sqlite3CreateIdExpr(pParse, zCol);
  69324. if( zAlias1==0 ){
  69325. zAlias1 = pTab1->zName;
  69326. }
  69327. pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
  69328. if( zAlias2==0 ){
  69329. zAlias2 = pTab2->zName;
  69330. }
  69331. pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
  69332. pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
  69333. pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
  69334. pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
  69335. if( pE && isOuterJoin ){
  69336. ExprSetProperty(pE, EP_FromJoin);
  69337. pE->iRightJoinTable = iRightJoinTable;
  69338. }
  69339. *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
  69340. }
  69341. /*
  69342. ** Set the EP_FromJoin property on all terms of the given expression.
  69343. ** And set the Expr.iRightJoinTable to iTable for every term in the
  69344. ** expression.
  69345. **
  69346. ** The EP_FromJoin property is used on terms of an expression to tell
  69347. ** the LEFT OUTER JOIN processing logic that this term is part of the
  69348. ** join restriction specified in the ON or USING clause and not a part
  69349. ** of the more general WHERE clause. These terms are moved over to the
  69350. ** WHERE clause during join processing but we need to remember that they
  69351. ** originated in the ON or USING clause.
  69352. **
  69353. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  69354. ** expression depends on table iRightJoinTable even if that table is not
  69355. ** explicitly mentioned in the expression. That information is needed
  69356. ** for cases like this:
  69357. **
  69358. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  69359. **
  69360. ** The where clause needs to defer the handling of the t1.x=5
  69361. ** term until after the t2 loop of the join. In that way, a
  69362. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  69363. ** defer the handling of t1.x=5, it will be processed immediately
  69364. ** after the t1 loop and rows with t1.x!=5 will never appear in
  69365. ** the output, which is incorrect.
  69366. */
  69367. static void setJoinExpr(Expr *p, int iTable){
  69368. while( p ){
  69369. ExprSetProperty(p, EP_FromJoin);
  69370. p->iRightJoinTable = iTable;
  69371. setJoinExpr(p->pLeft, iTable);
  69372. p = p->pRight;
  69373. }
  69374. }
  69375. /*
  69376. ** This routine processes the join information for a SELECT statement.
  69377. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  69378. ** NATURAL joins also create extra WHERE clause terms.
  69379. **
  69380. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  69381. ** The left most table is the first entry in Select.pSrc. The right-most
  69382. ** table is the last entry. The join operator is held in the entry to
  69383. ** the left. Thus entry 0 contains the join operator for the join between
  69384. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  69385. ** also attached to the left entry.
  69386. **
  69387. ** This routine returns the number of errors encountered.
  69388. */
  69389. static int sqliteProcessJoin(Parse *pParse, Select *p){
  69390. SrcList *pSrc; /* All tables in the FROM clause */
  69391. int i, j; /* Loop counters */
  69392. struct SrcList_item *pLeft; /* Left table being joined */
  69393. struct SrcList_item *pRight; /* Right table being joined */
  69394. pSrc = p->pSrc;
  69395. pLeft = &pSrc->a[0];
  69396. pRight = &pLeft[1];
  69397. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  69398. Table *pLeftTab = pLeft->pTab;
  69399. Table *pRightTab = pRight->pTab;
  69400. int isOuter;
  69401. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  69402. isOuter = (pRight->jointype & JT_OUTER)!=0;
  69403. /* When the NATURAL keyword is present, add WHERE clause terms for
  69404. ** every column that the two tables have in common.
  69405. */
  69406. if( pRight->jointype & JT_NATURAL ){
  69407. if( pRight->pOn || pRight->pUsing ){
  69408. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  69409. "an ON or USING clause", 0);
  69410. return 1;
  69411. }
  69412. for(j=0; j<pLeftTab->nCol; j++){
  69413. char *zName = pLeftTab->aCol[j].zName;
  69414. if( columnIndex(pRightTab, zName)>=0 ){
  69415. addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
  69416. pRightTab, pRight->zAlias,
  69417. pRight->iCursor, &p->pWhere, isOuter);
  69418. }
  69419. }
  69420. }
  69421. /* Disallow both ON and USING clauses in the same join
  69422. */
  69423. if( pRight->pOn && pRight->pUsing ){
  69424. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  69425. "clauses in the same join");
  69426. return 1;
  69427. }
  69428. /* Add the ON clause to the end of the WHERE clause, connected by
  69429. ** an AND operator.
  69430. */
  69431. if( pRight->pOn ){
  69432. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  69433. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  69434. pRight->pOn = 0;
  69435. }
  69436. /* Create extra terms on the WHERE clause for each column named
  69437. ** in the USING clause. Example: If the two tables to be joined are
  69438. ** A and B and the USING clause names X, Y, and Z, then add this
  69439. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  69440. ** Report an error if any column mentioned in the USING clause is
  69441. ** not contained in both tables to be joined.
  69442. */
  69443. if( pRight->pUsing ){
  69444. IdList *pList = pRight->pUsing;
  69445. for(j=0; j<pList->nId; j++){
  69446. char *zName = pList->a[j].zName;
  69447. if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
  69448. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  69449. "not present in both tables", zName);
  69450. return 1;
  69451. }
  69452. addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias,
  69453. pRightTab, pRight->zAlias,
  69454. pRight->iCursor, &p->pWhere, isOuter);
  69455. }
  69456. }
  69457. }
  69458. return 0;
  69459. }
  69460. /*
  69461. ** Insert code into "v" that will push the record on the top of the
  69462. ** stack into the sorter.
  69463. */
  69464. static void pushOntoSorter(
  69465. Parse *pParse, /* Parser context */
  69466. ExprList *pOrderBy, /* The ORDER BY clause */
  69467. Select *pSelect, /* The whole SELECT statement */
  69468. int regData /* Register holding data to be sorted */
  69469. ){
  69470. Vdbe *v = pParse->pVdbe;
  69471. int nExpr = pOrderBy->nExpr;
  69472. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  69473. int regRecord = sqlite3GetTempReg(pParse);
  69474. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  69475. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  69476. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  69477. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  69478. sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
  69479. sqlite3ReleaseTempReg(pParse, regRecord);
  69480. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  69481. if( pSelect->iLimit ){
  69482. int addr1, addr2;
  69483. int iLimit;
  69484. if( pSelect->iOffset ){
  69485. iLimit = pSelect->iOffset+1;
  69486. }else{
  69487. iLimit = pSelect->iLimit;
  69488. }
  69489. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  69490. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  69491. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  69492. sqlite3VdbeJumpHere(v, addr1);
  69493. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  69494. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  69495. sqlite3VdbeJumpHere(v, addr2);
  69496. pSelect->iLimit = 0;
  69497. }
  69498. }
  69499. /*
  69500. ** Add code to implement the OFFSET
  69501. */
  69502. static void codeOffset(
  69503. Vdbe *v, /* Generate code into this VM */
  69504. Select *p, /* The SELECT statement being coded */
  69505. int iContinue /* Jump here to skip the current record */
  69506. ){
  69507. if( p->iOffset && iContinue!=0 ){
  69508. int addr;
  69509. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  69510. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  69511. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  69512. VdbeComment((v, "skip OFFSET records"));
  69513. sqlite3VdbeJumpHere(v, addr);
  69514. }
  69515. }
  69516. /*
  69517. ** Add code that will check to make sure the N registers starting at iMem
  69518. ** form a distinct entry. iTab is a sorting index that holds previously
  69519. ** seen combinations of the N values. A new entry is made in iTab
  69520. ** if the current N values are new.
  69521. **
  69522. ** A jump to addrRepeat is made and the N+1 values are popped from the
  69523. ** stack if the top N elements are not distinct.
  69524. */
  69525. static void codeDistinct(
  69526. Parse *pParse, /* Parsing and code generating context */
  69527. int iTab, /* A sorting index used to test for distinctness */
  69528. int addrRepeat, /* Jump to here if not distinct */
  69529. int N, /* Number of elements */
  69530. int iMem /* First element */
  69531. ){
  69532. Vdbe *v;
  69533. int r1;
  69534. v = pParse->pVdbe;
  69535. r1 = sqlite3GetTempReg(pParse);
  69536. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  69537. sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
  69538. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  69539. sqlite3ReleaseTempReg(pParse, r1);
  69540. }
  69541. /*
  69542. ** Generate an error message when a SELECT is used within a subexpression
  69543. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  69544. ** column. We do this in a subroutine because the error occurs in multiple
  69545. ** places.
  69546. */
  69547. static int checkForMultiColumnSelectError(
  69548. Parse *pParse, /* Parse context. */
  69549. SelectDest *pDest, /* Destination of SELECT results */
  69550. int nExpr /* Number of result columns returned by SELECT */
  69551. ){
  69552. int eDest = pDest->eDest;
  69553. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  69554. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  69555. "a SELECT that is part of an expression");
  69556. return 1;
  69557. }else{
  69558. return 0;
  69559. }
  69560. }
  69561. /*
  69562. ** This routine generates the code for the inside of the inner loop
  69563. ** of a SELECT.
  69564. **
  69565. ** If srcTab and nColumn are both zero, then the pEList expressions
  69566. ** are evaluated in order to get the data for this row. If nColumn>0
  69567. ** then data is pulled from srcTab and pEList is used only to get the
  69568. ** datatypes for each column.
  69569. */
  69570. static void selectInnerLoop(
  69571. Parse *pParse, /* The parser context */
  69572. Select *p, /* The complete select statement being coded */
  69573. ExprList *pEList, /* List of values being extracted */
  69574. int srcTab, /* Pull data from this table */
  69575. int nColumn, /* Number of columns in the source table */
  69576. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  69577. int distinct, /* If >=0, make sure results are distinct */
  69578. SelectDest *pDest, /* How to dispose of the results */
  69579. int iContinue, /* Jump here to continue with next row */
  69580. int iBreak /* Jump here to break out of the inner loop */
  69581. ){
  69582. Vdbe *v = pParse->pVdbe;
  69583. int i;
  69584. int hasDistinct; /* True if the DISTINCT keyword is present */
  69585. int regResult; /* Start of memory holding result set */
  69586. int eDest = pDest->eDest; /* How to dispose of results */
  69587. int iParm = pDest->iParm; /* First argument to disposal method */
  69588. int nResultCol; /* Number of result columns */
  69589. assert( v );
  69590. if( NEVER(v==0) ) return;
  69591. assert( pEList!=0 );
  69592. hasDistinct = distinct>=0;
  69593. if( pOrderBy==0 && !hasDistinct ){
  69594. codeOffset(v, p, iContinue);
  69595. }
  69596. /* Pull the requested columns.
  69597. */
  69598. if( nColumn>0 ){
  69599. nResultCol = nColumn;
  69600. }else{
  69601. nResultCol = pEList->nExpr;
  69602. }
  69603. if( pDest->iMem==0 ){
  69604. pDest->iMem = pParse->nMem+1;
  69605. pDest->nMem = nResultCol;
  69606. pParse->nMem += nResultCol;
  69607. }else{
  69608. assert( pDest->nMem==nResultCol );
  69609. }
  69610. regResult = pDest->iMem;
  69611. if( nColumn>0 ){
  69612. for(i=0; i<nColumn; i++){
  69613. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  69614. }
  69615. }else if( eDest!=SRT_Exists ){
  69616. /* If the destination is an EXISTS(...) expression, the actual
  69617. ** values returned by the SELECT are not required.
  69618. */
  69619. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  69620. }
  69621. nColumn = nResultCol;
  69622. /* If the DISTINCT keyword was present on the SELECT statement
  69623. ** and this row has been seen before, then do not make this row
  69624. ** part of the result.
  69625. */
  69626. if( hasDistinct ){
  69627. assert( pEList!=0 );
  69628. assert( pEList->nExpr==nColumn );
  69629. codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
  69630. if( pOrderBy==0 ){
  69631. codeOffset(v, p, iContinue);
  69632. }
  69633. }
  69634. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  69635. return;
  69636. }
  69637. switch( eDest ){
  69638. /* In this mode, write each query result to the key of the temporary
  69639. ** table iParm.
  69640. */
  69641. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  69642. case SRT_Union: {
  69643. int r1;
  69644. r1 = sqlite3GetTempReg(pParse);
  69645. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  69646. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  69647. sqlite3ReleaseTempReg(pParse, r1);
  69648. break;
  69649. }
  69650. /* Construct a record from the query result, but instead of
  69651. ** saving that record, use it as a key to delete elements from
  69652. ** the temporary table iParm.
  69653. */
  69654. case SRT_Except: {
  69655. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  69656. break;
  69657. }
  69658. #endif
  69659. /* Store the result as data using a unique key.
  69660. */
  69661. case SRT_Table:
  69662. case SRT_EphemTab: {
  69663. int r1 = sqlite3GetTempReg(pParse);
  69664. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  69665. if( pOrderBy ){
  69666. pushOntoSorter(pParse, pOrderBy, p, r1);
  69667. }else{
  69668. int r2 = sqlite3GetTempReg(pParse);
  69669. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  69670. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  69671. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  69672. sqlite3ReleaseTempReg(pParse, r2);
  69673. }
  69674. sqlite3ReleaseTempReg(pParse, r1);
  69675. break;
  69676. }
  69677. #ifndef SQLITE_OMIT_SUBQUERY
  69678. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  69679. ** then there should be a single item on the stack. Write this
  69680. ** item into the set table with bogus data.
  69681. */
  69682. case SRT_Set: {
  69683. assert( nColumn==1 );
  69684. p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
  69685. if( pOrderBy ){
  69686. /* At first glance you would think we could optimize out the
  69687. ** ORDER BY in this case since the order of entries in the set
  69688. ** does not matter. But there might be a LIMIT clause, in which
  69689. ** case the order does matter */
  69690. pushOntoSorter(pParse, pOrderBy, p, regResult);
  69691. }else{
  69692. int r1 = sqlite3GetTempReg(pParse);
  69693. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
  69694. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  69695. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  69696. sqlite3ReleaseTempReg(pParse, r1);
  69697. }
  69698. break;
  69699. }
  69700. /* If any row exist in the result set, record that fact and abort.
  69701. */
  69702. case SRT_Exists: {
  69703. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  69704. /* The LIMIT clause will terminate the loop for us */
  69705. break;
  69706. }
  69707. /* If this is a scalar select that is part of an expression, then
  69708. ** store the results in the appropriate memory cell and break out
  69709. ** of the scan loop.
  69710. */
  69711. case SRT_Mem: {
  69712. assert( nColumn==1 );
  69713. if( pOrderBy ){
  69714. pushOntoSorter(pParse, pOrderBy, p, regResult);
  69715. }else{
  69716. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  69717. /* The LIMIT clause will jump out of the loop for us */
  69718. }
  69719. break;
  69720. }
  69721. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  69722. /* Send the data to the callback function or to a subroutine. In the
  69723. ** case of a subroutine, the subroutine itself is responsible for
  69724. ** popping the data from the stack.
  69725. */
  69726. case SRT_Coroutine:
  69727. case SRT_Output: {
  69728. if( pOrderBy ){
  69729. int r1 = sqlite3GetTempReg(pParse);
  69730. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  69731. pushOntoSorter(pParse, pOrderBy, p, r1);
  69732. sqlite3ReleaseTempReg(pParse, r1);
  69733. }else if( eDest==SRT_Coroutine ){
  69734. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  69735. }else{
  69736. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  69737. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  69738. }
  69739. break;
  69740. }
  69741. #if !defined(SQLITE_OMIT_TRIGGER)
  69742. /* Discard the results. This is used for SELECT statements inside
  69743. ** the body of a TRIGGER. The purpose of such selects is to call
  69744. ** user-defined functions that have side effects. We do not care
  69745. ** about the actual results of the select.
  69746. */
  69747. default: {
  69748. assert( eDest==SRT_Discard );
  69749. break;
  69750. }
  69751. #endif
  69752. }
  69753. /* Jump to the end of the loop if the LIMIT is reached.
  69754. */
  69755. if( p->iLimit ){
  69756. assert( pOrderBy==0 ); /* If there is an ORDER BY, the call to
  69757. ** pushOntoSorter() would have cleared p->iLimit */
  69758. sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
  69759. sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  69760. }
  69761. }
  69762. /*
  69763. ** Given an expression list, generate a KeyInfo structure that records
  69764. ** the collating sequence for each expression in that expression list.
  69765. **
  69766. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  69767. ** KeyInfo structure is appropriate for initializing a virtual index to
  69768. ** implement that clause. If the ExprList is the result set of a SELECT
  69769. ** then the KeyInfo structure is appropriate for initializing a virtual
  69770. ** index to implement a DISTINCT test.
  69771. **
  69772. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  69773. ** function is responsible for seeing that this structure is eventually
  69774. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  69775. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  69776. */
  69777. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  69778. sqlite3 *db = pParse->db;
  69779. int nExpr;
  69780. KeyInfo *pInfo;
  69781. struct ExprList_item *pItem;
  69782. int i;
  69783. nExpr = pList->nExpr;
  69784. pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  69785. if( pInfo ){
  69786. pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
  69787. pInfo->nField = (u16)nExpr;
  69788. pInfo->enc = ENC(db);
  69789. pInfo->db = db;
  69790. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  69791. CollSeq *pColl;
  69792. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  69793. if( !pColl ){
  69794. pColl = db->pDfltColl;
  69795. }
  69796. pInfo->aColl[i] = pColl;
  69797. pInfo->aSortOrder[i] = pItem->sortOrder;
  69798. }
  69799. }
  69800. return pInfo;
  69801. }
  69802. /*
  69803. ** If the inner loop was generated using a non-null pOrderBy argument,
  69804. ** then the results were placed in a sorter. After the loop is terminated
  69805. ** we need to run the sorter and output the results. The following
  69806. ** routine generates the code needed to do that.
  69807. */
  69808. static void generateSortTail(
  69809. Parse *pParse, /* Parsing context */
  69810. Select *p, /* The SELECT statement */
  69811. Vdbe *v, /* Generate code into this VDBE */
  69812. int nColumn, /* Number of columns of data */
  69813. SelectDest *pDest /* Write the sorted results here */
  69814. ){
  69815. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  69816. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  69817. int addr;
  69818. int iTab;
  69819. int pseudoTab = 0;
  69820. ExprList *pOrderBy = p->pOrderBy;
  69821. int eDest = pDest->eDest;
  69822. int iParm = pDest->iParm;
  69823. int regRow;
  69824. int regRowid;
  69825. iTab = pOrderBy->iECursor;
  69826. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  69827. pseudoTab = pParse->nTab++;
  69828. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output, nColumn);
  69829. }
  69830. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  69831. codeOffset(v, p, addrContinue);
  69832. regRow = sqlite3GetTempReg(pParse);
  69833. regRowid = sqlite3GetTempReg(pParse);
  69834. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
  69835. switch( eDest ){
  69836. case SRT_Table:
  69837. case SRT_EphemTab: {
  69838. testcase( eDest==SRT_Table );
  69839. testcase( eDest==SRT_EphemTab );
  69840. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  69841. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  69842. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  69843. break;
  69844. }
  69845. #ifndef SQLITE_OMIT_SUBQUERY
  69846. case SRT_Set: {
  69847. assert( nColumn==1 );
  69848. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
  69849. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  69850. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  69851. break;
  69852. }
  69853. case SRT_Mem: {
  69854. assert( nColumn==1 );
  69855. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  69856. /* The LIMIT clause will terminate the loop for us */
  69857. break;
  69858. }
  69859. #endif
  69860. case SRT_Output:
  69861. case SRT_Coroutine: {
  69862. int i;
  69863. testcase( eDest==SRT_Output );
  69864. testcase( eDest==SRT_Coroutine );
  69865. sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
  69866. sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
  69867. for(i=0; i<nColumn; i++){
  69868. assert( regRow!=pDest->iMem+i );
  69869. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
  69870. }
  69871. if( eDest==SRT_Output ){
  69872. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
  69873. sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
  69874. }else{
  69875. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  69876. }
  69877. break;
  69878. }
  69879. default: {
  69880. /* Do nothing */
  69881. break;
  69882. }
  69883. }
  69884. sqlite3ReleaseTempReg(pParse, regRow);
  69885. sqlite3ReleaseTempReg(pParse, regRowid);
  69886. /* LIMIT has been implemented by the pushOntoSorter() routine.
  69887. */
  69888. assert( p->iLimit==0 );
  69889. /* The bottom of the loop
  69890. */
  69891. sqlite3VdbeResolveLabel(v, addrContinue);
  69892. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  69893. sqlite3VdbeResolveLabel(v, addrBreak);
  69894. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  69895. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  69896. }
  69897. }
  69898. /*
  69899. ** Return a pointer to a string containing the 'declaration type' of the
  69900. ** expression pExpr. The string may be treated as static by the caller.
  69901. **
  69902. ** The declaration type is the exact datatype definition extracted from the
  69903. ** original CREATE TABLE statement if the expression is a column. The
  69904. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  69905. ** is considered a column can be complex in the presence of subqueries. The
  69906. ** result-set expression in all of the following SELECT statements is
  69907. ** considered a column by this function.
  69908. **
  69909. ** SELECT col FROM tbl;
  69910. ** SELECT (SELECT col FROM tbl;
  69911. ** SELECT (SELECT col FROM tbl);
  69912. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  69913. **
  69914. ** The declaration type for any expression other than a column is NULL.
  69915. */
  69916. static const char *columnType(
  69917. NameContext *pNC,
  69918. Expr *pExpr,
  69919. const char **pzOriginDb,
  69920. const char **pzOriginTab,
  69921. const char **pzOriginCol
  69922. ){
  69923. char const *zType = 0;
  69924. char const *zOriginDb = 0;
  69925. char const *zOriginTab = 0;
  69926. char const *zOriginCol = 0;
  69927. int j;
  69928. if( pExpr==0 || pNC->pSrcList==0 ) return 0;
  69929. switch( pExpr->op ){
  69930. case TK_AGG_COLUMN:
  69931. case TK_COLUMN: {
  69932. /* The expression is a column. Locate the table the column is being
  69933. ** extracted from in NameContext.pSrcList. This table may be real
  69934. ** database table or a subquery.
  69935. */
  69936. Table *pTab = 0; /* Table structure column is extracted from */
  69937. Select *pS = 0; /* Select the column is extracted from */
  69938. int iCol = pExpr->iColumn; /* Index of column in pTab */
  69939. while( pNC && !pTab ){
  69940. SrcList *pTabList = pNC->pSrcList;
  69941. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  69942. if( j<pTabList->nSrc ){
  69943. pTab = pTabList->a[j].pTab;
  69944. pS = pTabList->a[j].pSelect;
  69945. }else{
  69946. pNC = pNC->pNext;
  69947. }
  69948. }
  69949. if( pTab==0 ){
  69950. /* FIX ME:
  69951. ** This can occurs if you have something like "SELECT new.x;" inside
  69952. ** a trigger. In other words, if you reference the special "new"
  69953. ** table in the result set of a select. We do not have a good way
  69954. ** to find the actual table type, so call it "TEXT". This is really
  69955. ** something of a bug, but I do not know how to fix it.
  69956. **
  69957. ** This code does not produce the correct answer - it just prevents
  69958. ** a segfault. See ticket #1229.
  69959. */
  69960. zType = "TEXT";
  69961. break;
  69962. }
  69963. assert( pTab );
  69964. if( pS ){
  69965. /* The "table" is actually a sub-select or a view in the FROM clause
  69966. ** of the SELECT statement. Return the declaration type and origin
  69967. ** data for the result-set column of the sub-select.
  69968. */
  69969. if( ALWAYS(iCol>=0 && iCol<pS->pEList->nExpr) ){
  69970. /* If iCol is less than zero, then the expression requests the
  69971. ** rowid of the sub-select or view. This expression is legal (see
  69972. ** test case misc2.2.2) - it always evaluates to NULL.
  69973. */
  69974. NameContext sNC;
  69975. Expr *p = pS->pEList->a[iCol].pExpr;
  69976. sNC.pSrcList = pS->pSrc;
  69977. sNC.pNext = 0;
  69978. sNC.pParse = pNC->pParse;
  69979. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  69980. }
  69981. }else if( ALWAYS(pTab->pSchema) ){
  69982. /* A real table */
  69983. assert( !pS );
  69984. if( iCol<0 ) iCol = pTab->iPKey;
  69985. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  69986. if( iCol<0 ){
  69987. zType = "INTEGER";
  69988. zOriginCol = "rowid";
  69989. }else{
  69990. zType = pTab->aCol[iCol].zType;
  69991. zOriginCol = pTab->aCol[iCol].zName;
  69992. }
  69993. zOriginTab = pTab->zName;
  69994. if( pNC->pParse ){
  69995. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  69996. zOriginDb = pNC->pParse->db->aDb[iDb].zName;
  69997. }
  69998. }
  69999. break;
  70000. }
  70001. #ifndef SQLITE_OMIT_SUBQUERY
  70002. case TK_SELECT: {
  70003. /* The expression is a sub-select. Return the declaration type and
  70004. ** origin info for the single column in the result set of the SELECT
  70005. ** statement.
  70006. */
  70007. NameContext sNC;
  70008. Select *pS = pExpr->x.pSelect;
  70009. Expr *p = pS->pEList->a[0].pExpr;
  70010. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  70011. sNC.pSrcList = pS->pSrc;
  70012. sNC.pNext = pNC;
  70013. sNC.pParse = pNC->pParse;
  70014. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  70015. break;
  70016. }
  70017. #endif
  70018. }
  70019. if( pzOriginDb ){
  70020. assert( pzOriginTab && pzOriginCol );
  70021. *pzOriginDb = zOriginDb;
  70022. *pzOriginTab = zOriginTab;
  70023. *pzOriginCol = zOriginCol;
  70024. }
  70025. return zType;
  70026. }
  70027. /*
  70028. ** Generate code that will tell the VDBE the declaration types of columns
  70029. ** in the result set.
  70030. */
  70031. static void generateColumnTypes(
  70032. Parse *pParse, /* Parser context */
  70033. SrcList *pTabList, /* List of tables */
  70034. ExprList *pEList /* Expressions defining the result set */
  70035. ){
  70036. #ifndef SQLITE_OMIT_DECLTYPE
  70037. Vdbe *v = pParse->pVdbe;
  70038. int i;
  70039. NameContext sNC;
  70040. sNC.pSrcList = pTabList;
  70041. sNC.pParse = pParse;
  70042. for(i=0; i<pEList->nExpr; i++){
  70043. Expr *p = pEList->a[i].pExpr;
  70044. const char *zType;
  70045. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  70046. const char *zOrigDb = 0;
  70047. const char *zOrigTab = 0;
  70048. const char *zOrigCol = 0;
  70049. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  70050. /* The vdbe must make its own copy of the column-type and other
  70051. ** column specific strings, in case the schema is reset before this
  70052. ** virtual machine is deleted.
  70053. */
  70054. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  70055. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  70056. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  70057. #else
  70058. zType = columnType(&sNC, p, 0, 0, 0);
  70059. #endif
  70060. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  70061. }
  70062. #endif /* SQLITE_OMIT_DECLTYPE */
  70063. }
  70064. /*
  70065. ** Generate code that will tell the VDBE the names of columns
  70066. ** in the result set. This information is used to provide the
  70067. ** azCol[] values in the callback.
  70068. */
  70069. static void generateColumnNames(
  70070. Parse *pParse, /* Parser context */
  70071. SrcList *pTabList, /* List of tables */
  70072. ExprList *pEList /* Expressions defining the result set */
  70073. ){
  70074. Vdbe *v = pParse->pVdbe;
  70075. int i, j;
  70076. sqlite3 *db = pParse->db;
  70077. int fullNames, shortNames;
  70078. #ifndef SQLITE_OMIT_EXPLAIN
  70079. /* If this is an EXPLAIN, skip this step */
  70080. if( pParse->explain ){
  70081. return;
  70082. }
  70083. #endif
  70084. assert( v!=0 );
  70085. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  70086. pParse->colNamesSet = 1;
  70087. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  70088. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  70089. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  70090. for(i=0; i<pEList->nExpr; i++){
  70091. Expr *p;
  70092. p = pEList->a[i].pExpr;
  70093. if( p==0 ) continue;
  70094. if( pEList->a[i].zName ){
  70095. char *zName = pEList->a[i].zName;
  70096. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  70097. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  70098. Table *pTab;
  70099. char *zCol;
  70100. int iCol = p->iColumn;
  70101. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  70102. if( pTabList->a[j].iCursor==p->iTable ) break;
  70103. }
  70104. assert( j<pTabList->nSrc );
  70105. pTab = pTabList->a[j].pTab;
  70106. if( iCol<0 ) iCol = pTab->iPKey;
  70107. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  70108. if( iCol<0 ){
  70109. zCol = "rowid";
  70110. }else{
  70111. zCol = pTab->aCol[iCol].zName;
  70112. }
  70113. if( !shortNames && !fullNames ){
  70114. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  70115. sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
  70116. }else if( fullNames ){
  70117. char *zName = 0;
  70118. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  70119. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  70120. }else{
  70121. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  70122. }
  70123. }else{
  70124. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  70125. sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
  70126. }
  70127. }
  70128. generateColumnTypes(pParse, pTabList, pEList);
  70129. }
  70130. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  70131. /*
  70132. ** Name of the connection operator, used for error messages.
  70133. */
  70134. static const char *selectOpName(int id){
  70135. char *z;
  70136. switch( id ){
  70137. case TK_ALL: z = "UNION ALL"; break;
  70138. case TK_INTERSECT: z = "INTERSECT"; break;
  70139. case TK_EXCEPT: z = "EXCEPT"; break;
  70140. default: z = "UNION"; break;
  70141. }
  70142. return z;
  70143. }
  70144. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  70145. /*
  70146. ** Given a an expression list (which is really the list of expressions
  70147. ** that form the result set of a SELECT statement) compute appropriate
  70148. ** column names for a table that would hold the expression list.
  70149. **
  70150. ** All column names will be unique.
  70151. **
  70152. ** Only the column names are computed. Column.zType, Column.zColl,
  70153. ** and other fields of Column are zeroed.
  70154. **
  70155. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  70156. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  70157. */
  70158. static int selectColumnsFromExprList(
  70159. Parse *pParse, /* Parsing context */
  70160. ExprList *pEList, /* Expr list from which to derive column names */
  70161. int *pnCol, /* Write the number of columns here */
  70162. Column **paCol /* Write the new column list here */
  70163. ){
  70164. sqlite3 *db = pParse->db; /* Database connection */
  70165. int i, j; /* Loop counters */
  70166. int cnt; /* Index added to make the name unique */
  70167. Column *aCol, *pCol; /* For looping over result columns */
  70168. int nCol; /* Number of columns in the result set */
  70169. Expr *p; /* Expression for a single result column */
  70170. char *zName; /* Column name */
  70171. int nName; /* Size of name in zName[] */
  70172. *pnCol = nCol = pEList->nExpr;
  70173. aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  70174. if( aCol==0 ) return SQLITE_NOMEM;
  70175. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  70176. /* Get an appropriate name for the column
  70177. */
  70178. p = pEList->a[i].pExpr;
  70179. assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
  70180. if( (zName = pEList->a[i].zName)!=0 ){
  70181. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  70182. zName = sqlite3DbStrDup(db, zName);
  70183. }else{
  70184. Expr *pColExpr = p; /* The expression that is the result column name */
  70185. Table *pTab; /* Table associated with this expression */
  70186. while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
  70187. if( pColExpr->op==TK_COLUMN && (pTab = pColExpr->pTab)!=0 ){
  70188. /* For columns use the column name name */
  70189. int iCol = pColExpr->iColumn;
  70190. if( iCol<0 ) iCol = pTab->iPKey;
  70191. zName = sqlite3MPrintf(db, "%s",
  70192. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  70193. }else{
  70194. /* Use the original text of the column expression as its name */
  70195. Token *pToken = (pColExpr->span.z?&pColExpr->span:&pColExpr->token);
  70196. zName = sqlite3MPrintf(db, "%T", pToken);
  70197. }
  70198. }
  70199. if( db->mallocFailed ){
  70200. sqlite3DbFree(db, zName);
  70201. break;
  70202. }
  70203. sqlite3Dequote(zName);
  70204. /* Make sure the column name is unique. If the name is not unique,
  70205. ** append a integer to the name so that it becomes unique.
  70206. */
  70207. nName = sqlite3Strlen30(zName);
  70208. for(j=cnt=0; j<i; j++){
  70209. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  70210. char *zNewName;
  70211. zName[nName] = 0;
  70212. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  70213. sqlite3DbFree(db, zName);
  70214. zName = zNewName;
  70215. j = -1;
  70216. if( zName==0 ) break;
  70217. }
  70218. }
  70219. pCol->zName = zName;
  70220. }
  70221. if( db->mallocFailed ){
  70222. for(j=0; j<i; j++){
  70223. sqlite3DbFree(db, aCol[j].zName);
  70224. }
  70225. sqlite3DbFree(db, aCol);
  70226. *paCol = 0;
  70227. *pnCol = 0;
  70228. return SQLITE_NOMEM;
  70229. }
  70230. return SQLITE_OK;
  70231. }
  70232. /*
  70233. ** Add type and collation information to a column list based on
  70234. ** a SELECT statement.
  70235. **
  70236. ** The column list presumably came from selectColumnNamesFromExprList().
  70237. ** The column list has only names, not types or collations. This
  70238. ** routine goes through and adds the types and collations.
  70239. **
  70240. ** This routine requires that all identifiers in the SELECT
  70241. ** statement be resolved.
  70242. */
  70243. static void selectAddColumnTypeAndCollation(
  70244. Parse *pParse, /* Parsing contexts */
  70245. int nCol, /* Number of columns */
  70246. Column *aCol, /* List of columns */
  70247. Select *pSelect /* SELECT used to determine types and collations */
  70248. ){
  70249. sqlite3 *db = pParse->db;
  70250. NameContext sNC;
  70251. Column *pCol;
  70252. CollSeq *pColl;
  70253. int i;
  70254. Expr *p;
  70255. struct ExprList_item *a;
  70256. assert( pSelect!=0 );
  70257. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  70258. assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  70259. if( db->mallocFailed ) return;
  70260. memset(&sNC, 0, sizeof(sNC));
  70261. sNC.pSrcList = pSelect->pSrc;
  70262. a = pSelect->pEList->a;
  70263. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  70264. p = a[i].pExpr;
  70265. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  70266. pCol->affinity = sqlite3ExprAffinity(p);
  70267. pColl = sqlite3ExprCollSeq(pParse, p);
  70268. if( pColl ){
  70269. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  70270. }
  70271. }
  70272. }
  70273. /*
  70274. ** Given a SELECT statement, generate a Table structure that describes
  70275. ** the result set of that SELECT.
  70276. */
  70277. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  70278. Table *pTab;
  70279. sqlite3 *db = pParse->db;
  70280. int savedFlags;
  70281. savedFlags = db->flags;
  70282. db->flags &= ~SQLITE_FullColNames;
  70283. db->flags |= SQLITE_ShortColNames;
  70284. sqlite3SelectPrep(pParse, pSelect, 0);
  70285. if( pParse->nErr ) return 0;
  70286. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  70287. db->flags = savedFlags;
  70288. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  70289. if( pTab==0 ){
  70290. return 0;
  70291. }
  70292. pTab->dbMem = db->lookaside.bEnabled ? db : 0;
  70293. pTab->nRef = 1;
  70294. pTab->zName = 0;
  70295. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  70296. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  70297. pTab->iPKey = -1;
  70298. if( db->mallocFailed ){
  70299. sqlite3DeleteTable(pTab);
  70300. return 0;
  70301. }
  70302. return pTab;
  70303. }
  70304. /*
  70305. ** Get a VDBE for the given parser context. Create a new one if necessary.
  70306. ** If an error occurs, return NULL and leave a message in pParse.
  70307. */
  70308. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  70309. Vdbe *v = pParse->pVdbe;
  70310. if( v==0 ){
  70311. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  70312. #ifndef SQLITE_OMIT_TRACE
  70313. if( v ){
  70314. sqlite3VdbeAddOp0(v, OP_Trace);
  70315. }
  70316. #endif
  70317. }
  70318. return v;
  70319. }
  70320. /*
  70321. ** Compute the iLimit and iOffset fields of the SELECT based on the
  70322. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  70323. ** that appear in the original SQL statement after the LIMIT and OFFSET
  70324. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  70325. ** are the integer memory register numbers for counters used to compute
  70326. ** the limit and offset. If there is no limit and/or offset, then
  70327. ** iLimit and iOffset are negative.
  70328. **
  70329. ** This routine changes the values of iLimit and iOffset only if
  70330. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  70331. ** iOffset should have been preset to appropriate default values
  70332. ** (usually but not always -1) prior to calling this routine.
  70333. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  70334. ** redefined. The UNION ALL operator uses this property to force
  70335. ** the reuse of the same limit and offset registers across multiple
  70336. ** SELECT statements.
  70337. */
  70338. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  70339. Vdbe *v = 0;
  70340. int iLimit = 0;
  70341. int iOffset;
  70342. int addr1;
  70343. if( p->iLimit ) return;
  70344. /*
  70345. ** "LIMIT -1" always shows all rows. There is some
  70346. ** contraversy about what the correct behavior should be.
  70347. ** The current implementation interprets "LIMIT 0" to mean
  70348. ** no rows.
  70349. */
  70350. if( p->pLimit ){
  70351. p->iLimit = iLimit = ++pParse->nMem;
  70352. v = sqlite3GetVdbe(pParse);
  70353. if( v==0 ) return;
  70354. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  70355. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  70356. VdbeComment((v, "LIMIT counter"));
  70357. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  70358. }
  70359. if( p->pOffset ){
  70360. p->iOffset = iOffset = ++pParse->nMem;
  70361. if( p->pLimit ){
  70362. pParse->nMem++; /* Allocate an extra register for limit+offset */
  70363. }
  70364. v = sqlite3GetVdbe(pParse);
  70365. if( v==0 ) return;
  70366. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  70367. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  70368. VdbeComment((v, "OFFSET counter"));
  70369. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  70370. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  70371. sqlite3VdbeJumpHere(v, addr1);
  70372. if( p->pLimit ){
  70373. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  70374. VdbeComment((v, "LIMIT+OFFSET"));
  70375. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  70376. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  70377. sqlite3VdbeJumpHere(v, addr1);
  70378. }
  70379. }
  70380. }
  70381. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  70382. /*
  70383. ** Return the appropriate collating sequence for the iCol-th column of
  70384. ** the result set for the compound-select statement "p". Return NULL if
  70385. ** the column has no default collating sequence.
  70386. **
  70387. ** The collating sequence for the compound select is taken from the
  70388. ** left-most term of the select that has a collating sequence.
  70389. */
  70390. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  70391. CollSeq *pRet;
  70392. if( p->pPrior ){
  70393. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  70394. }else{
  70395. pRet = 0;
  70396. }
  70397. if( pRet==0 ){
  70398. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  70399. }
  70400. return pRet;
  70401. }
  70402. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  70403. /* Forward reference */
  70404. static int multiSelectOrderBy(
  70405. Parse *pParse, /* Parsing context */
  70406. Select *p, /* The right-most of SELECTs to be coded */
  70407. SelectDest *pDest /* What to do with query results */
  70408. );
  70409. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  70410. /*
  70411. ** This routine is called to process a compound query form from
  70412. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  70413. ** INTERSECT
  70414. **
  70415. ** "p" points to the right-most of the two queries. the query on the
  70416. ** left is p->pPrior. The left query could also be a compound query
  70417. ** in which case this routine will be called recursively.
  70418. **
  70419. ** The results of the total query are to be written into a destination
  70420. ** of type eDest with parameter iParm.
  70421. **
  70422. ** Example 1: Consider a three-way compound SQL statement.
  70423. **
  70424. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  70425. **
  70426. ** This statement is parsed up as follows:
  70427. **
  70428. ** SELECT c FROM t3
  70429. ** |
  70430. ** `-----> SELECT b FROM t2
  70431. ** |
  70432. ** `------> SELECT a FROM t1
  70433. **
  70434. ** The arrows in the diagram above represent the Select.pPrior pointer.
  70435. ** So if this routine is called with p equal to the t3 query, then
  70436. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  70437. **
  70438. ** Notice that because of the way SQLite parses compound SELECTs, the
  70439. ** individual selects always group from left to right.
  70440. */
  70441. static int multiSelect(
  70442. Parse *pParse, /* Parsing context */
  70443. Select *p, /* The right-most of SELECTs to be coded */
  70444. SelectDest *pDest /* What to do with query results */
  70445. ){
  70446. int rc = SQLITE_OK; /* Success code from a subroutine */
  70447. Select *pPrior; /* Another SELECT immediately to our left */
  70448. Vdbe *v; /* Generate code to this VDBE */
  70449. SelectDest dest; /* Alternative data destination */
  70450. Select *pDelete = 0; /* Chain of simple selects to delete */
  70451. sqlite3 *db; /* Database connection */
  70452. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  70453. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  70454. */
  70455. assert( p && p->pPrior ); /* Calling function guarantees this much */
  70456. db = pParse->db;
  70457. pPrior = p->pPrior;
  70458. assert( pPrior->pRightmost!=pPrior );
  70459. assert( pPrior->pRightmost==p->pRightmost );
  70460. dest = *pDest;
  70461. if( pPrior->pOrderBy ){
  70462. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  70463. selectOpName(p->op));
  70464. rc = 1;
  70465. goto multi_select_end;
  70466. }
  70467. if( pPrior->pLimit ){
  70468. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  70469. selectOpName(p->op));
  70470. rc = 1;
  70471. goto multi_select_end;
  70472. }
  70473. v = sqlite3GetVdbe(pParse);
  70474. assert( v!=0 ); /* The VDBE already created by calling function */
  70475. /* Create the destination temporary table if necessary
  70476. */
  70477. if( dest.eDest==SRT_EphemTab ){
  70478. assert( p->pEList );
  70479. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
  70480. dest.eDest = SRT_Table;
  70481. }
  70482. /* Make sure all SELECTs in the statement have the same number of elements
  70483. ** in their result sets.
  70484. */
  70485. assert( p->pEList && pPrior->pEList );
  70486. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  70487. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  70488. " do not have the same number of result columns", selectOpName(p->op));
  70489. rc = 1;
  70490. goto multi_select_end;
  70491. }
  70492. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  70493. */
  70494. if( p->pOrderBy ){
  70495. return multiSelectOrderBy(pParse, p, pDest);
  70496. }
  70497. /* Generate code for the left and right SELECT statements.
  70498. */
  70499. switch( p->op ){
  70500. case TK_ALL: {
  70501. int addr = 0;
  70502. assert( !pPrior->pLimit );
  70503. pPrior->pLimit = p->pLimit;
  70504. pPrior->pOffset = p->pOffset;
  70505. rc = sqlite3Select(pParse, pPrior, &dest);
  70506. p->pLimit = 0;
  70507. p->pOffset = 0;
  70508. if( rc ){
  70509. goto multi_select_end;
  70510. }
  70511. p->pPrior = 0;
  70512. p->iLimit = pPrior->iLimit;
  70513. p->iOffset = pPrior->iOffset;
  70514. if( p->iLimit ){
  70515. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  70516. VdbeComment((v, "Jump ahead if LIMIT reached"));
  70517. }
  70518. rc = sqlite3Select(pParse, p, &dest);
  70519. pDelete = p->pPrior;
  70520. p->pPrior = pPrior;
  70521. if( rc ){
  70522. goto multi_select_end;
  70523. }
  70524. if( addr ){
  70525. sqlite3VdbeJumpHere(v, addr);
  70526. }
  70527. break;
  70528. }
  70529. case TK_EXCEPT:
  70530. case TK_UNION: {
  70531. int unionTab; /* Cursor number of the temporary table holding result */
  70532. u8 op = 0; /* One of the SRT_ operations to apply to self */
  70533. int priorOp; /* The SRT_ operation to apply to prior selects */
  70534. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  70535. int addr;
  70536. SelectDest uniondest;
  70537. priorOp = SRT_Union;
  70538. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  70539. /* We can reuse a temporary table generated by a SELECT to our
  70540. ** right.
  70541. */
  70542. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  70543. ** of a 3-way or more compound */
  70544. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  70545. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  70546. unionTab = dest.iParm;
  70547. }else{
  70548. /* We will need to create our own temporary table to hold the
  70549. ** intermediate results.
  70550. */
  70551. unionTab = pParse->nTab++;
  70552. assert( p->pOrderBy==0 );
  70553. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  70554. assert( p->addrOpenEphm[0] == -1 );
  70555. p->addrOpenEphm[0] = addr;
  70556. p->pRightmost->selFlags |= SF_UsesEphemeral;
  70557. assert( p->pEList );
  70558. }
  70559. /* Code the SELECT statements to our left
  70560. */
  70561. assert( !pPrior->pOrderBy );
  70562. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  70563. rc = sqlite3Select(pParse, pPrior, &uniondest);
  70564. if( rc ){
  70565. goto multi_select_end;
  70566. }
  70567. /* Code the current SELECT statement
  70568. */
  70569. if( p->op==TK_EXCEPT ){
  70570. op = SRT_Except;
  70571. }else{
  70572. assert( p->op==TK_UNION );
  70573. op = SRT_Union;
  70574. }
  70575. p->pPrior = 0;
  70576. pLimit = p->pLimit;
  70577. p->pLimit = 0;
  70578. pOffset = p->pOffset;
  70579. p->pOffset = 0;
  70580. uniondest.eDest = op;
  70581. rc = sqlite3Select(pParse, p, &uniondest);
  70582. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  70583. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  70584. sqlite3ExprListDelete(db, p->pOrderBy);
  70585. pDelete = p->pPrior;
  70586. p->pPrior = pPrior;
  70587. p->pOrderBy = 0;
  70588. sqlite3ExprDelete(db, p->pLimit);
  70589. p->pLimit = pLimit;
  70590. p->pOffset = pOffset;
  70591. p->iLimit = 0;
  70592. p->iOffset = 0;
  70593. if( rc ){
  70594. goto multi_select_end;
  70595. }
  70596. /* Convert the data in the temporary table into whatever form
  70597. ** it is that we currently need.
  70598. */
  70599. if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
  70600. int iCont, iBreak, iStart;
  70601. assert( p->pEList );
  70602. if( dest.eDest==SRT_Output ){
  70603. Select *pFirst = p;
  70604. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  70605. generateColumnNames(pParse, 0, pFirst->pEList);
  70606. }
  70607. iBreak = sqlite3VdbeMakeLabel(v);
  70608. iCont = sqlite3VdbeMakeLabel(v);
  70609. computeLimitRegisters(pParse, p, iBreak);
  70610. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  70611. iStart = sqlite3VdbeCurrentAddr(v);
  70612. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  70613. 0, -1, &dest, iCont, iBreak);
  70614. sqlite3VdbeResolveLabel(v, iCont);
  70615. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  70616. sqlite3VdbeResolveLabel(v, iBreak);
  70617. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  70618. }
  70619. break;
  70620. }
  70621. case TK_INTERSECT: {
  70622. int tab1, tab2;
  70623. int iCont, iBreak, iStart;
  70624. Expr *pLimit, *pOffset;
  70625. int addr;
  70626. SelectDest intersectdest;
  70627. int r1;
  70628. /* INTERSECT is different from the others since it requires
  70629. ** two temporary tables. Hence it has its own case. Begin
  70630. ** by allocating the tables we will need.
  70631. */
  70632. tab1 = pParse->nTab++;
  70633. tab2 = pParse->nTab++;
  70634. assert( p->pOrderBy==0 );
  70635. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  70636. assert( p->addrOpenEphm[0] == -1 );
  70637. p->addrOpenEphm[0] = addr;
  70638. p->pRightmost->selFlags |= SF_UsesEphemeral;
  70639. assert( p->pEList );
  70640. /* Code the SELECTs to our left into temporary table "tab1".
  70641. */
  70642. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  70643. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  70644. if( rc ){
  70645. goto multi_select_end;
  70646. }
  70647. /* Code the current SELECT into temporary table "tab2"
  70648. */
  70649. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  70650. assert( p->addrOpenEphm[1] == -1 );
  70651. p->addrOpenEphm[1] = addr;
  70652. p->pPrior = 0;
  70653. pLimit = p->pLimit;
  70654. p->pLimit = 0;
  70655. pOffset = p->pOffset;
  70656. p->pOffset = 0;
  70657. intersectdest.iParm = tab2;
  70658. rc = sqlite3Select(pParse, p, &intersectdest);
  70659. pDelete = p->pPrior;
  70660. p->pPrior = pPrior;
  70661. sqlite3ExprDelete(db, p->pLimit);
  70662. p->pLimit = pLimit;
  70663. p->pOffset = pOffset;
  70664. if( rc ){
  70665. goto multi_select_end;
  70666. }
  70667. /* Generate code to take the intersection of the two temporary
  70668. ** tables.
  70669. */
  70670. assert( p->pEList );
  70671. if( dest.eDest==SRT_Output ){
  70672. Select *pFirst = p;
  70673. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  70674. generateColumnNames(pParse, 0, pFirst->pEList);
  70675. }
  70676. iBreak = sqlite3VdbeMakeLabel(v);
  70677. iCont = sqlite3VdbeMakeLabel(v);
  70678. computeLimitRegisters(pParse, p, iBreak);
  70679. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  70680. r1 = sqlite3GetTempReg(pParse);
  70681. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  70682. sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
  70683. sqlite3ReleaseTempReg(pParse, r1);
  70684. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  70685. 0, -1, &dest, iCont, iBreak);
  70686. sqlite3VdbeResolveLabel(v, iCont);
  70687. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  70688. sqlite3VdbeResolveLabel(v, iBreak);
  70689. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  70690. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  70691. break;
  70692. }
  70693. }
  70694. /* Compute collating sequences used by
  70695. ** temporary tables needed to implement the compound select.
  70696. ** Attach the KeyInfo structure to all temporary tables.
  70697. **
  70698. ** This section is run by the right-most SELECT statement only.
  70699. ** SELECT statements to the left always skip this part. The right-most
  70700. ** SELECT might also skip this part if it has no ORDER BY clause and
  70701. ** no temp tables are required.
  70702. */
  70703. if( p->selFlags & SF_UsesEphemeral ){
  70704. int i; /* Loop counter */
  70705. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  70706. Select *pLoop; /* For looping through SELECT statements */
  70707. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  70708. int nCol; /* Number of columns in result set */
  70709. assert( p->pRightmost==p );
  70710. nCol = p->pEList->nExpr;
  70711. pKeyInfo = sqlite3DbMallocZero(db,
  70712. sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
  70713. if( !pKeyInfo ){
  70714. rc = SQLITE_NOMEM;
  70715. goto multi_select_end;
  70716. }
  70717. pKeyInfo->enc = ENC(db);
  70718. pKeyInfo->nField = (u16)nCol;
  70719. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  70720. *apColl = multiSelectCollSeq(pParse, p, i);
  70721. if( 0==*apColl ){
  70722. *apColl = db->pDfltColl;
  70723. }
  70724. }
  70725. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  70726. for(i=0; i<2; i++){
  70727. int addr = pLoop->addrOpenEphm[i];
  70728. if( addr<0 ){
  70729. /* If [0] is unused then [1] is also unused. So we can
  70730. ** always safely abort as soon as the first unused slot is found */
  70731. assert( pLoop->addrOpenEphm[1]<0 );
  70732. break;
  70733. }
  70734. sqlite3VdbeChangeP2(v, addr, nCol);
  70735. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  70736. pLoop->addrOpenEphm[i] = -1;
  70737. }
  70738. }
  70739. sqlite3DbFree(db, pKeyInfo);
  70740. }
  70741. multi_select_end:
  70742. pDest->iMem = dest.iMem;
  70743. pDest->nMem = dest.nMem;
  70744. sqlite3SelectDelete(db, pDelete);
  70745. return rc;
  70746. }
  70747. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  70748. /*
  70749. ** Code an output subroutine for a coroutine implementation of a
  70750. ** SELECT statment.
  70751. **
  70752. ** The data to be output is contained in pIn->iMem. There are
  70753. ** pIn->nMem columns to be output. pDest is where the output should
  70754. ** be sent.
  70755. **
  70756. ** regReturn is the number of the register holding the subroutine
  70757. ** return address.
  70758. **
  70759. ** If regPrev>0 then it is a the first register in a vector that
  70760. ** records the previous output. mem[regPrev] is a flag that is false
  70761. ** if there has been no previous output. If regPrev>0 then code is
  70762. ** generated to suppress duplicates. pKeyInfo is used for comparing
  70763. ** keys.
  70764. **
  70765. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  70766. ** iBreak.
  70767. */
  70768. static int generateOutputSubroutine(
  70769. Parse *pParse, /* Parsing context */
  70770. Select *p, /* The SELECT statement */
  70771. SelectDest *pIn, /* Coroutine supplying data */
  70772. SelectDest *pDest, /* Where to send the data */
  70773. int regReturn, /* The return address register */
  70774. int regPrev, /* Previous result register. No uniqueness if 0 */
  70775. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  70776. int p4type, /* The p4 type for pKeyInfo */
  70777. int iBreak /* Jump here if we hit the LIMIT */
  70778. ){
  70779. Vdbe *v = pParse->pVdbe;
  70780. int iContinue;
  70781. int addr;
  70782. addr = sqlite3VdbeCurrentAddr(v);
  70783. iContinue = sqlite3VdbeMakeLabel(v);
  70784. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  70785. */
  70786. if( regPrev ){
  70787. int j1, j2;
  70788. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  70789. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
  70790. (char*)pKeyInfo, p4type);
  70791. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  70792. sqlite3VdbeJumpHere(v, j1);
  70793. sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
  70794. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  70795. }
  70796. if( pParse->db->mallocFailed ) return 0;
  70797. /* Suppress the the first OFFSET entries if there is an OFFSET clause
  70798. */
  70799. codeOffset(v, p, iContinue);
  70800. switch( pDest->eDest ){
  70801. /* Store the result as data using a unique key.
  70802. */
  70803. case SRT_Table:
  70804. case SRT_EphemTab: {
  70805. int r1 = sqlite3GetTempReg(pParse);
  70806. int r2 = sqlite3GetTempReg(pParse);
  70807. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
  70808. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
  70809. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
  70810. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  70811. sqlite3ReleaseTempReg(pParse, r2);
  70812. sqlite3ReleaseTempReg(pParse, r1);
  70813. break;
  70814. }
  70815. #ifndef SQLITE_OMIT_SUBQUERY
  70816. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  70817. ** then there should be a single item on the stack. Write this
  70818. ** item into the set table with bogus data.
  70819. */
  70820. case SRT_Set: {
  70821. int r1;
  70822. assert( pIn->nMem==1 );
  70823. p->affinity =
  70824. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
  70825. r1 = sqlite3GetTempReg(pParse);
  70826. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
  70827. sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
  70828. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
  70829. sqlite3ReleaseTempReg(pParse, r1);
  70830. break;
  70831. }
  70832. #if 0 /* Never occurs on an ORDER BY query */
  70833. /* If any row exist in the result set, record that fact and abort.
  70834. */
  70835. case SRT_Exists: {
  70836. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
  70837. /* The LIMIT clause will terminate the loop for us */
  70838. break;
  70839. }
  70840. #endif
  70841. /* If this is a scalar select that is part of an expression, then
  70842. ** store the results in the appropriate memory cell and break out
  70843. ** of the scan loop.
  70844. */
  70845. case SRT_Mem: {
  70846. assert( pIn->nMem==1 );
  70847. sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
  70848. /* The LIMIT clause will jump out of the loop for us */
  70849. break;
  70850. }
  70851. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  70852. /* The results are stored in a sequence of registers
  70853. ** starting at pDest->iMem. Then the co-routine yields.
  70854. */
  70855. case SRT_Coroutine: {
  70856. if( pDest->iMem==0 ){
  70857. pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
  70858. pDest->nMem = pIn->nMem;
  70859. }
  70860. sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
  70861. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  70862. break;
  70863. }
  70864. /* Results are stored in a sequence of registers. Then the
  70865. ** OP_ResultRow opcode is used to cause sqlite3_step() to return
  70866. ** the next row of result.
  70867. */
  70868. case SRT_Output: {
  70869. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
  70870. sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
  70871. break;
  70872. }
  70873. #if !defined(SQLITE_OMIT_TRIGGER)
  70874. /* Discard the results. This is used for SELECT statements inside
  70875. ** the body of a TRIGGER. The purpose of such selects is to call
  70876. ** user-defined functions that have side effects. We do not care
  70877. ** about the actual results of the select.
  70878. */
  70879. default: {
  70880. break;
  70881. }
  70882. #endif
  70883. }
  70884. /* Jump to the end of the loop if the LIMIT is reached.
  70885. */
  70886. if( p->iLimit ){
  70887. sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
  70888. sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  70889. }
  70890. /* Generate the subroutine return
  70891. */
  70892. sqlite3VdbeResolveLabel(v, iContinue);
  70893. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  70894. return addr;
  70895. }
  70896. /*
  70897. ** Alternative compound select code generator for cases when there
  70898. ** is an ORDER BY clause.
  70899. **
  70900. ** We assume a query of the following form:
  70901. **
  70902. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  70903. **
  70904. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  70905. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  70906. ** co-routines. Then run the co-routines in parallel and merge the results
  70907. ** into the output. In addition to the two coroutines (called selectA and
  70908. ** selectB) there are 7 subroutines:
  70909. **
  70910. ** outA: Move the output of the selectA coroutine into the output
  70911. ** of the compound query.
  70912. **
  70913. ** outB: Move the output of the selectB coroutine into the output
  70914. ** of the compound query. (Only generated for UNION and
  70915. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  70916. ** appears only in B.)
  70917. **
  70918. ** AltB: Called when there is data from both coroutines and A<B.
  70919. **
  70920. ** AeqB: Called when there is data from both coroutines and A==B.
  70921. **
  70922. ** AgtB: Called when there is data from both coroutines and A>B.
  70923. **
  70924. ** EofA: Called when data is exhausted from selectA.
  70925. **
  70926. ** EofB: Called when data is exhausted from selectB.
  70927. **
  70928. ** The implementation of the latter five subroutines depend on which
  70929. ** <operator> is used:
  70930. **
  70931. **
  70932. ** UNION ALL UNION EXCEPT INTERSECT
  70933. ** ------------- ----------------- -------------- -----------------
  70934. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  70935. **
  70936. ** AeqB: outA, nextA nextA nextA outA, nextA
  70937. **
  70938. ** AgtB: outB, nextB outB, nextB nextB nextB
  70939. **
  70940. ** EofA: outB, nextB outB, nextB halt halt
  70941. **
  70942. ** EofB: outA, nextA outA, nextA outA, nextA halt
  70943. **
  70944. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  70945. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  70946. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  70947. ** following nextX causes a jump to the end of the select processing.
  70948. **
  70949. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  70950. ** within the output subroutine. The regPrev register set holds the previously
  70951. ** output value. A comparison is made against this value and the output
  70952. ** is skipped if the next results would be the same as the previous.
  70953. **
  70954. ** The implementation plan is to implement the two coroutines and seven
  70955. ** subroutines first, then put the control logic at the bottom. Like this:
  70956. **
  70957. ** goto Init
  70958. ** coA: coroutine for left query (A)
  70959. ** coB: coroutine for right query (B)
  70960. ** outA: output one row of A
  70961. ** outB: output one row of B (UNION and UNION ALL only)
  70962. ** EofA: ...
  70963. ** EofB: ...
  70964. ** AltB: ...
  70965. ** AeqB: ...
  70966. ** AgtB: ...
  70967. ** Init: initialize coroutine registers
  70968. ** yield coA
  70969. ** if eof(A) goto EofA
  70970. ** yield coB
  70971. ** if eof(B) goto EofB
  70972. ** Cmpr: Compare A, B
  70973. ** Jump AltB, AeqB, AgtB
  70974. ** End: ...
  70975. **
  70976. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  70977. ** actually called using Gosub and they do not Return. EofA and EofB loop
  70978. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  70979. ** and AgtB jump to either L2 or to one of EofA or EofB.
  70980. */
  70981. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  70982. static int multiSelectOrderBy(
  70983. Parse *pParse, /* Parsing context */
  70984. Select *p, /* The right-most of SELECTs to be coded */
  70985. SelectDest *pDest /* What to do with query results */
  70986. ){
  70987. int i, j; /* Loop counters */
  70988. Select *pPrior; /* Another SELECT immediately to our left */
  70989. Vdbe *v; /* Generate code to this VDBE */
  70990. SelectDest destA; /* Destination for coroutine A */
  70991. SelectDest destB; /* Destination for coroutine B */
  70992. int regAddrA; /* Address register for select-A coroutine */
  70993. int regEofA; /* Flag to indicate when select-A is complete */
  70994. int regAddrB; /* Address register for select-B coroutine */
  70995. int regEofB; /* Flag to indicate when select-B is complete */
  70996. int addrSelectA; /* Address of the select-A coroutine */
  70997. int addrSelectB; /* Address of the select-B coroutine */
  70998. int regOutA; /* Address register for the output-A subroutine */
  70999. int regOutB; /* Address register for the output-B subroutine */
  71000. int addrOutA; /* Address of the output-A subroutine */
  71001. int addrOutB = 0; /* Address of the output-B subroutine */
  71002. int addrEofA; /* Address of the select-A-exhausted subroutine */
  71003. int addrEofB; /* Address of the select-B-exhausted subroutine */
  71004. int addrAltB; /* Address of the A<B subroutine */
  71005. int addrAeqB; /* Address of the A==B subroutine */
  71006. int addrAgtB; /* Address of the A>B subroutine */
  71007. int regLimitA; /* Limit register for select-A */
  71008. int regLimitB; /* Limit register for select-A */
  71009. int regPrev; /* A range of registers to hold previous output */
  71010. int savedLimit; /* Saved value of p->iLimit */
  71011. int savedOffset; /* Saved value of p->iOffset */
  71012. int labelCmpr; /* Label for the start of the merge algorithm */
  71013. int labelEnd; /* Label for the end of the overall SELECT stmt */
  71014. int j1; /* Jump instructions that get retargetted */
  71015. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  71016. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  71017. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  71018. sqlite3 *db; /* Database connection */
  71019. ExprList *pOrderBy; /* The ORDER BY clause */
  71020. int nOrderBy; /* Number of terms in the ORDER BY clause */
  71021. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  71022. assert( p->pOrderBy!=0 );
  71023. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  71024. db = pParse->db;
  71025. v = pParse->pVdbe;
  71026. if( v==0 ) return SQLITE_NOMEM;
  71027. labelEnd = sqlite3VdbeMakeLabel(v);
  71028. labelCmpr = sqlite3VdbeMakeLabel(v);
  71029. /* Patch up the ORDER BY clause
  71030. */
  71031. op = p->op;
  71032. pPrior = p->pPrior;
  71033. assert( pPrior->pOrderBy==0 );
  71034. pOrderBy = p->pOrderBy;
  71035. assert( pOrderBy );
  71036. nOrderBy = pOrderBy->nExpr;
  71037. /* For operators other than UNION ALL we have to make sure that
  71038. ** the ORDER BY clause covers every term of the result set. Add
  71039. ** terms to the ORDER BY clause as necessary.
  71040. */
  71041. if( op!=TK_ALL ){
  71042. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  71043. struct ExprList_item *pItem;
  71044. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  71045. assert( pItem->iCol>0 );
  71046. if( pItem->iCol==i ) break;
  71047. }
  71048. if( j==nOrderBy ){
  71049. Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
  71050. if( pNew==0 ) return SQLITE_NOMEM;
  71051. pNew->flags |= EP_IntValue;
  71052. pNew->iTable = i;
  71053. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
  71054. pOrderBy->a[nOrderBy++].iCol = (u16)i;
  71055. }
  71056. }
  71057. }
  71058. /* Compute the comparison permutation and keyinfo that is used with
  71059. ** the permutation in order to comparisons to determine if the next
  71060. ** row of results comes from selectA or selectB. Also add explicit
  71061. ** collations to the ORDER BY clause terms so that when the subqueries
  71062. ** to the right and the left are evaluated, they use the correct
  71063. ** collation.
  71064. */
  71065. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  71066. if( aPermute ){
  71067. struct ExprList_item *pItem;
  71068. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  71069. assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr );
  71070. aPermute[i] = pItem->iCol - 1;
  71071. }
  71072. pKeyMerge =
  71073. sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  71074. if( pKeyMerge ){
  71075. pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  71076. pKeyMerge->nField = (u16)nOrderBy;
  71077. pKeyMerge->enc = ENC(db);
  71078. for(i=0; i<nOrderBy; i++){
  71079. CollSeq *pColl;
  71080. Expr *pTerm = pOrderBy->a[i].pExpr;
  71081. if( pTerm->flags & EP_ExpCollate ){
  71082. pColl = pTerm->pColl;
  71083. }else{
  71084. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  71085. pTerm->flags |= EP_ExpCollate;
  71086. pTerm->pColl = pColl;
  71087. }
  71088. pKeyMerge->aColl[i] = pColl;
  71089. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  71090. }
  71091. }
  71092. }else{
  71093. pKeyMerge = 0;
  71094. }
  71095. /* Reattach the ORDER BY clause to the query.
  71096. */
  71097. p->pOrderBy = pOrderBy;
  71098. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  71099. /* Allocate a range of temporary registers and the KeyInfo needed
  71100. ** for the logic that removes duplicate result rows when the
  71101. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  71102. */
  71103. if( op==TK_ALL ){
  71104. regPrev = 0;
  71105. }else{
  71106. int nExpr = p->pEList->nExpr;
  71107. assert( nOrderBy>=nExpr || db->mallocFailed );
  71108. regPrev = sqlite3GetTempRange(pParse, nExpr+1);
  71109. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  71110. pKeyDup = sqlite3DbMallocZero(db,
  71111. sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
  71112. if( pKeyDup ){
  71113. pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  71114. pKeyDup->nField = (u16)nExpr;
  71115. pKeyDup->enc = ENC(db);
  71116. for(i=0; i<nExpr; i++){
  71117. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  71118. pKeyDup->aSortOrder[i] = 0;
  71119. }
  71120. }
  71121. }
  71122. /* Separate the left and the right query from one another
  71123. */
  71124. p->pPrior = 0;
  71125. pPrior->pRightmost = 0;
  71126. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  71127. if( pPrior->pPrior==0 ){
  71128. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  71129. }
  71130. /* Compute the limit registers */
  71131. computeLimitRegisters(pParse, p, labelEnd);
  71132. if( p->iLimit && op==TK_ALL ){
  71133. regLimitA = ++pParse->nMem;
  71134. regLimitB = ++pParse->nMem;
  71135. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  71136. regLimitA);
  71137. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  71138. }else{
  71139. regLimitA = regLimitB = 0;
  71140. }
  71141. sqlite3ExprDelete(db, p->pLimit);
  71142. p->pLimit = 0;
  71143. sqlite3ExprDelete(db, p->pOffset);
  71144. p->pOffset = 0;
  71145. regAddrA = ++pParse->nMem;
  71146. regEofA = ++pParse->nMem;
  71147. regAddrB = ++pParse->nMem;
  71148. regEofB = ++pParse->nMem;
  71149. regOutA = ++pParse->nMem;
  71150. regOutB = ++pParse->nMem;
  71151. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  71152. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  71153. /* Jump past the various subroutines and coroutines to the main
  71154. ** merge loop
  71155. */
  71156. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  71157. addrSelectA = sqlite3VdbeCurrentAddr(v);
  71158. /* Generate a coroutine to evaluate the SELECT statement to the
  71159. ** left of the compound operator - the "A" select.
  71160. */
  71161. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  71162. pPrior->iLimit = regLimitA;
  71163. sqlite3Select(pParse, pPrior, &destA);
  71164. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  71165. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  71166. VdbeNoopComment((v, "End coroutine for left SELECT"));
  71167. /* Generate a coroutine to evaluate the SELECT statement on
  71168. ** the right - the "B" select
  71169. */
  71170. addrSelectB = sqlite3VdbeCurrentAddr(v);
  71171. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  71172. savedLimit = p->iLimit;
  71173. savedOffset = p->iOffset;
  71174. p->iLimit = regLimitB;
  71175. p->iOffset = 0;
  71176. sqlite3Select(pParse, p, &destB);
  71177. p->iLimit = savedLimit;
  71178. p->iOffset = savedOffset;
  71179. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  71180. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  71181. VdbeNoopComment((v, "End coroutine for right SELECT"));
  71182. /* Generate a subroutine that outputs the current row of the A
  71183. ** select as the next output row of the compound select.
  71184. */
  71185. VdbeNoopComment((v, "Output routine for A"));
  71186. addrOutA = generateOutputSubroutine(pParse,
  71187. p, &destA, pDest, regOutA,
  71188. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  71189. /* Generate a subroutine that outputs the current row of the B
  71190. ** select as the next output row of the compound select.
  71191. */
  71192. if( op==TK_ALL || op==TK_UNION ){
  71193. VdbeNoopComment((v, "Output routine for B"));
  71194. addrOutB = generateOutputSubroutine(pParse,
  71195. p, &destB, pDest, regOutB,
  71196. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  71197. }
  71198. /* Generate a subroutine to run when the results from select A
  71199. ** are exhausted and only data in select B remains.
  71200. */
  71201. VdbeNoopComment((v, "eof-A subroutine"));
  71202. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  71203. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  71204. }else{
  71205. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  71206. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  71207. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  71208. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  71209. }
  71210. /* Generate a subroutine to run when the results from select B
  71211. ** are exhausted and only data in select A remains.
  71212. */
  71213. if( op==TK_INTERSECT ){
  71214. addrEofB = addrEofA;
  71215. }else{
  71216. VdbeNoopComment((v, "eof-B subroutine"));
  71217. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  71218. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  71219. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  71220. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  71221. }
  71222. /* Generate code to handle the case of A<B
  71223. */
  71224. VdbeNoopComment((v, "A-lt-B subroutine"));
  71225. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  71226. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  71227. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  71228. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  71229. /* Generate code to handle the case of A==B
  71230. */
  71231. if( op==TK_ALL ){
  71232. addrAeqB = addrAltB;
  71233. }else if( op==TK_INTERSECT ){
  71234. addrAeqB = addrAltB;
  71235. addrAltB++;
  71236. }else{
  71237. VdbeNoopComment((v, "A-eq-B subroutine"));
  71238. addrAeqB =
  71239. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  71240. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  71241. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  71242. }
  71243. /* Generate code to handle the case of A>B
  71244. */
  71245. VdbeNoopComment((v, "A-gt-B subroutine"));
  71246. addrAgtB = sqlite3VdbeCurrentAddr(v);
  71247. if( op==TK_ALL || op==TK_UNION ){
  71248. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  71249. }
  71250. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  71251. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  71252. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  71253. /* This code runs once to initialize everything.
  71254. */
  71255. sqlite3VdbeJumpHere(v, j1);
  71256. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  71257. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  71258. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  71259. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  71260. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  71261. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  71262. /* Implement the main merge loop
  71263. */
  71264. sqlite3VdbeResolveLabel(v, labelCmpr);
  71265. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  71266. sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
  71267. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  71268. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  71269. /* Release temporary registers
  71270. */
  71271. if( regPrev ){
  71272. sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  71273. }
  71274. /* Jump to the this point in order to terminate the query.
  71275. */
  71276. sqlite3VdbeResolveLabel(v, labelEnd);
  71277. /* Set the number of output columns
  71278. */
  71279. if( pDest->eDest==SRT_Output ){
  71280. Select *pFirst = pPrior;
  71281. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  71282. generateColumnNames(pParse, 0, pFirst->pEList);
  71283. }
  71284. /* Reassembly the compound query so that it will be freed correctly
  71285. ** by the calling function */
  71286. if( p->pPrior ){
  71287. sqlite3SelectDelete(db, p->pPrior);
  71288. }
  71289. p->pPrior = pPrior;
  71290. /*** TBD: Insert subroutine calls to close cursors on incomplete
  71291. **** subqueries ****/
  71292. return SQLITE_OK;
  71293. }
  71294. #endif
  71295. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  71296. /* Forward Declarations */
  71297. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  71298. static void substSelect(sqlite3*, Select *, int, ExprList *);
  71299. /*
  71300. ** Scan through the expression pExpr. Replace every reference to
  71301. ** a column in table number iTable with a copy of the iColumn-th
  71302. ** entry in pEList. (But leave references to the ROWID column
  71303. ** unchanged.)
  71304. **
  71305. ** This routine is part of the flattening procedure. A subquery
  71306. ** whose result set is defined by pEList appears as entry in the
  71307. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  71308. ** FORM clause entry is iTable. This routine make the necessary
  71309. ** changes to pExpr so that it refers directly to the source table
  71310. ** of the subquery rather the result set of the subquery.
  71311. */
  71312. static void substExpr(
  71313. sqlite3 *db, /* Report malloc errors to this connection */
  71314. Expr *pExpr, /* Expr in which substitution occurs */
  71315. int iTable, /* Table to be substituted */
  71316. ExprList *pEList /* Substitute expressions */
  71317. ){
  71318. if( pExpr==0 ) return;
  71319. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  71320. if( pExpr->iColumn<0 ){
  71321. pExpr->op = TK_NULL;
  71322. }else{
  71323. Expr *pNew;
  71324. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  71325. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  71326. pNew = pEList->a[pExpr->iColumn].pExpr;
  71327. assert( pNew!=0 );
  71328. pExpr->op = pNew->op;
  71329. assert( pExpr->pLeft==0 );
  71330. pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft, 0);
  71331. assert( pExpr->pRight==0 );
  71332. pExpr->pRight = sqlite3ExprDup(db, pNew->pRight, 0);
  71333. pExpr->iTable = pNew->iTable;
  71334. pExpr->pTab = pNew->pTab;
  71335. pExpr->iColumn = pNew->iColumn;
  71336. pExpr->iAgg = pNew->iAgg;
  71337. sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
  71338. sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
  71339. assert( pExpr->x.pList==0 && pExpr->x.pSelect==0 );
  71340. if( ExprHasProperty(pNew, EP_xIsSelect) ){
  71341. pExpr->x.pSelect = sqlite3SelectDup(db, pNew->x.pSelect, 0);
  71342. }else{
  71343. pExpr->x.pList = sqlite3ExprListDup(db, pNew->x.pList, 0);
  71344. }
  71345. pExpr->flags = pNew->flags;
  71346. pExpr->pAggInfo = pNew->pAggInfo;
  71347. pNew->pAggInfo = 0;
  71348. }
  71349. }else{
  71350. substExpr(db, pExpr->pLeft, iTable, pEList);
  71351. substExpr(db, pExpr->pRight, iTable, pEList);
  71352. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  71353. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  71354. }else{
  71355. substExprList(db, pExpr->x.pList, iTable, pEList);
  71356. }
  71357. }
  71358. }
  71359. static void substExprList(
  71360. sqlite3 *db, /* Report malloc errors here */
  71361. ExprList *pList, /* List to scan and in which to make substitutes */
  71362. int iTable, /* Table to be substituted */
  71363. ExprList *pEList /* Substitute values */
  71364. ){
  71365. int i;
  71366. if( pList==0 ) return;
  71367. for(i=0; i<pList->nExpr; i++){
  71368. substExpr(db, pList->a[i].pExpr, iTable, pEList);
  71369. }
  71370. }
  71371. static void substSelect(
  71372. sqlite3 *db, /* Report malloc errors here */
  71373. Select *p, /* SELECT statement in which to make substitutions */
  71374. int iTable, /* Table to be replaced */
  71375. ExprList *pEList /* Substitute values */
  71376. ){
  71377. SrcList *pSrc;
  71378. struct SrcList_item *pItem;
  71379. int i;
  71380. if( !p ) return;
  71381. substExprList(db, p->pEList, iTable, pEList);
  71382. substExprList(db, p->pGroupBy, iTable, pEList);
  71383. substExprList(db, p->pOrderBy, iTable, pEList);
  71384. substExpr(db, p->pHaving, iTable, pEList);
  71385. substExpr(db, p->pWhere, iTable, pEList);
  71386. substSelect(db, p->pPrior, iTable, pEList);
  71387. pSrc = p->pSrc;
  71388. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  71389. if( ALWAYS(pSrc) ){
  71390. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  71391. substSelect(db, pItem->pSelect, iTable, pEList);
  71392. }
  71393. }
  71394. }
  71395. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  71396. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  71397. /*
  71398. ** This routine attempts to flatten subqueries in order to speed
  71399. ** execution. It returns 1 if it makes changes and 0 if no flattening
  71400. ** occurs.
  71401. **
  71402. ** To understand the concept of flattening, consider the following
  71403. ** query:
  71404. **
  71405. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  71406. **
  71407. ** The default way of implementing this query is to execute the
  71408. ** subquery first and store the results in a temporary table, then
  71409. ** run the outer query on that temporary table. This requires two
  71410. ** passes over the data. Furthermore, because the temporary table
  71411. ** has no indices, the WHERE clause on the outer query cannot be
  71412. ** optimized.
  71413. **
  71414. ** This routine attempts to rewrite queries such as the above into
  71415. ** a single flat select, like this:
  71416. **
  71417. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  71418. **
  71419. ** The code generated for this simpification gives the same result
  71420. ** but only has to scan the data once. And because indices might
  71421. ** exist on the table t1, a complete scan of the data might be
  71422. ** avoided.
  71423. **
  71424. ** Flattening is only attempted if all of the following are true:
  71425. **
  71426. ** (1) The subquery and the outer query do not both use aggregates.
  71427. **
  71428. ** (2) The subquery is not an aggregate or the outer query is not a join.
  71429. **
  71430. ** (3) The subquery is not the right operand of a left outer join
  71431. ** (Originally ticket #306. Strenghtened by ticket #3300)
  71432. **
  71433. ** (4) The subquery is not DISTINCT or the outer query is not a join.
  71434. **
  71435. ** (5) The subquery is not DISTINCT or the outer query does not use
  71436. ** aggregates.
  71437. **
  71438. ** (6) The subquery does not use aggregates or the outer query is not
  71439. ** DISTINCT.
  71440. **
  71441. ** (7) The subquery has a FROM clause.
  71442. **
  71443. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  71444. **
  71445. ** (9) The subquery does not use LIMIT or the outer query does not use
  71446. ** aggregates.
  71447. **
  71448. ** (10) The subquery does not use aggregates or the outer query does not
  71449. ** use LIMIT.
  71450. **
  71451. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  71452. **
  71453. ** (12) Not implemented. Subsumed into restriction (3). Was previously
  71454. ** a separate restriction deriving from ticket #350.
  71455. **
  71456. ** (13) The subquery and outer query do not both use LIMIT
  71457. **
  71458. ** (14) The subquery does not use OFFSET
  71459. **
  71460. ** (15) The outer query is not part of a compound select or the
  71461. ** subquery does not have both an ORDER BY and a LIMIT clause.
  71462. ** (See ticket #2339)
  71463. **
  71464. ** (16) The outer query is not an aggregate or the subquery does
  71465. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  71466. ** until we introduced the group_concat() function.
  71467. **
  71468. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  71469. ** compound clause made up entirely of non-aggregate queries, and
  71470. ** the parent query:
  71471. **
  71472. ** * is not itself part of a compound select,
  71473. ** * is not an aggregate or DISTINCT query, and
  71474. ** * has no other tables or sub-selects in the FROM clause.
  71475. **
  71476. ** The parent and sub-query may contain WHERE clauses. Subject to
  71477. ** rules (11), (13) and (14), they may also contain ORDER BY,
  71478. ** LIMIT and OFFSET clauses.
  71479. **
  71480. ** (18) If the sub-query is a compound select, then all terms of the
  71481. ** ORDER by clause of the parent must be simple references to
  71482. ** columns of the sub-query.
  71483. **
  71484. ** (19) The subquery does not use LIMIT or the outer query does not
  71485. ** have a WHERE clause.
  71486. **
  71487. ** (20) If the sub-query is a compound select, then it must not use
  71488. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  71489. ** somewhat by saying that the terms of the ORDER BY clause must
  71490. ** appear as unmodified result columns in the outer query. But
  71491. ** have other optimizations in mind to deal with that case.
  71492. **
  71493. ** In this routine, the "p" parameter is a pointer to the outer query.
  71494. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  71495. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  71496. **
  71497. ** If flattening is not attempted, this routine is a no-op and returns 0.
  71498. ** If flattening is attempted this routine returns 1.
  71499. **
  71500. ** All of the expression analysis must occur on both the outer query and
  71501. ** the subquery before this routine runs.
  71502. */
  71503. static int flattenSubquery(
  71504. Parse *pParse, /* Parsing context */
  71505. Select *p, /* The parent or outer SELECT statement */
  71506. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  71507. int isAgg, /* True if outer SELECT uses aggregate functions */
  71508. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  71509. ){
  71510. const char *zSavedAuthContext = pParse->zAuthContext;
  71511. Select *pParent;
  71512. Select *pSub; /* The inner query or "subquery" */
  71513. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  71514. SrcList *pSrc; /* The FROM clause of the outer query */
  71515. SrcList *pSubSrc; /* The FROM clause of the subquery */
  71516. ExprList *pList; /* The result set of the outer query */
  71517. int iParent; /* VDBE cursor number of the pSub result set temp table */
  71518. int i; /* Loop counter */
  71519. Expr *pWhere; /* The WHERE clause */
  71520. struct SrcList_item *pSubitem; /* The subquery */
  71521. sqlite3 *db = pParse->db;
  71522. /* Check to see if flattening is permitted. Return 0 if not.
  71523. */
  71524. assert( p!=0 );
  71525. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  71526. pSrc = p->pSrc;
  71527. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  71528. pSubitem = &pSrc->a[iFrom];
  71529. iParent = pSubitem->iCursor;
  71530. pSub = pSubitem->pSelect;
  71531. assert( pSub!=0 );
  71532. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  71533. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  71534. pSubSrc = pSub->pSrc;
  71535. assert( pSubSrc );
  71536. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  71537. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  71538. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  71539. ** became arbitrary expressions, we were forced to add restrictions (13)
  71540. ** and (14). */
  71541. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  71542. if( pSub->pOffset ) return 0; /* Restriction (14) */
  71543. if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
  71544. return 0; /* Restriction (15) */
  71545. }
  71546. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  71547. if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
  71548. && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */
  71549. return 0;
  71550. }
  71551. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  71552. return 0; /* Restriction (6) */
  71553. }
  71554. if( p->pOrderBy && pSub->pOrderBy ){
  71555. return 0; /* Restriction (11) */
  71556. }
  71557. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  71558. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  71559. /* OBSOLETE COMMENT 1:
  71560. ** Restriction 3: If the subquery is a join, make sure the subquery is
  71561. ** not used as the right operand of an outer join. Examples of why this
  71562. ** is not allowed:
  71563. **
  71564. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  71565. **
  71566. ** If we flatten the above, we would get
  71567. **
  71568. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  71569. **
  71570. ** which is not at all the same thing.
  71571. **
  71572. ** OBSOLETE COMMENT 2:
  71573. ** Restriction 12: If the subquery is the right operand of a left outer
  71574. ** join, make sure the subquery has no WHERE clause.
  71575. ** An examples of why this is not allowed:
  71576. **
  71577. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  71578. **
  71579. ** If we flatten the above, we would get
  71580. **
  71581. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  71582. **
  71583. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  71584. ** effectively converts the OUTER JOIN into an INNER JOIN.
  71585. **
  71586. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  71587. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  71588. ** is fraught with danger. Best to avoid the whole thing. If the
  71589. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  71590. */
  71591. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  71592. return 0;
  71593. }
  71594. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  71595. ** use only the UNION ALL operator. And none of the simple select queries
  71596. ** that make up the compound SELECT are allowed to be aggregate or distinct
  71597. ** queries.
  71598. */
  71599. if( pSub->pPrior ){
  71600. if( pSub->pOrderBy ){
  71601. return 0; /* Restriction 20 */
  71602. }
  71603. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  71604. return 0;
  71605. }
  71606. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  71607. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  71608. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  71609. || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
  71610. ){
  71611. return 0;
  71612. }
  71613. }
  71614. /* Restriction 18. */
  71615. if( p->pOrderBy ){
  71616. int ii;
  71617. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  71618. if( p->pOrderBy->a[ii].iCol==0 ) return 0;
  71619. }
  71620. }
  71621. }
  71622. /***** If we reach this point, flattening is permitted. *****/
  71623. /* Authorize the subquery */
  71624. pParse->zAuthContext = pSubitem->zName;
  71625. sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  71626. pParse->zAuthContext = zSavedAuthContext;
  71627. /* If the sub-query is a compound SELECT statement, then (by restrictions
  71628. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  71629. ** be of the form:
  71630. **
  71631. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  71632. **
  71633. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  71634. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  71635. ** OFFSET clauses and joins them to the left-hand-side of the original
  71636. ** using UNION ALL operators. In this case N is the number of simple
  71637. ** select statements in the compound sub-query.
  71638. **
  71639. ** Example:
  71640. **
  71641. ** SELECT a+1 FROM (
  71642. ** SELECT x FROM tab
  71643. ** UNION ALL
  71644. ** SELECT y FROM tab
  71645. ** UNION ALL
  71646. ** SELECT abs(z*2) FROM tab2
  71647. ** ) WHERE a!=5 ORDER BY 1
  71648. **
  71649. ** Transformed into:
  71650. **
  71651. ** SELECT x+1 FROM tab WHERE x+1!=5
  71652. ** UNION ALL
  71653. ** SELECT y+1 FROM tab WHERE y+1!=5
  71654. ** UNION ALL
  71655. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  71656. ** ORDER BY 1
  71657. **
  71658. ** We call this the "compound-subquery flattening".
  71659. */
  71660. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  71661. Select *pNew;
  71662. ExprList *pOrderBy = p->pOrderBy;
  71663. Expr *pLimit = p->pLimit;
  71664. Select *pPrior = p->pPrior;
  71665. p->pOrderBy = 0;
  71666. p->pSrc = 0;
  71667. p->pPrior = 0;
  71668. p->pLimit = 0;
  71669. pNew = sqlite3SelectDup(db, p, 0);
  71670. p->pLimit = pLimit;
  71671. p->pOrderBy = pOrderBy;
  71672. p->pSrc = pSrc;
  71673. p->op = TK_ALL;
  71674. p->pRightmost = 0;
  71675. if( pNew==0 ){
  71676. pNew = pPrior;
  71677. }else{
  71678. pNew->pPrior = pPrior;
  71679. pNew->pRightmost = 0;
  71680. }
  71681. p->pPrior = pNew;
  71682. if( db->mallocFailed ) return 1;
  71683. }
  71684. /* Begin flattening the iFrom-th entry of the FROM clause
  71685. ** in the outer query.
  71686. */
  71687. pSub = pSub1 = pSubitem->pSelect;
  71688. /* Delete the transient table structure associated with the
  71689. ** subquery
  71690. */
  71691. sqlite3DbFree(db, pSubitem->zDatabase);
  71692. sqlite3DbFree(db, pSubitem->zName);
  71693. sqlite3DbFree(db, pSubitem->zAlias);
  71694. pSubitem->zDatabase = 0;
  71695. pSubitem->zName = 0;
  71696. pSubitem->zAlias = 0;
  71697. pSubitem->pSelect = 0;
  71698. /* Defer deleting the Table object associated with the
  71699. ** subquery until code generation is
  71700. ** complete, since there may still exist Expr.pTab entries that
  71701. ** refer to the subquery even after flattening. Ticket #3346.
  71702. */
  71703. if( pSubitem->pTab!=0 ){
  71704. Table *pTabToDel = pSubitem->pTab;
  71705. if( pTabToDel->nRef==1 ){
  71706. pTabToDel->pNextZombie = pParse->pZombieTab;
  71707. pParse->pZombieTab = pTabToDel;
  71708. }else{
  71709. pTabToDel->nRef--;
  71710. }
  71711. pSubitem->pTab = 0;
  71712. }
  71713. /* The following loop runs once for each term in a compound-subquery
  71714. ** flattening (as described above). If we are doing a different kind
  71715. ** of flattening - a flattening other than a compound-subquery flattening -
  71716. ** then this loop only runs once.
  71717. **
  71718. ** This loop moves all of the FROM elements of the subquery into the
  71719. ** the FROM clause of the outer query. Before doing this, remember
  71720. ** the cursor number for the original outer query FROM element in
  71721. ** iParent. The iParent cursor will never be used. Subsequent code
  71722. ** will scan expressions looking for iParent references and replace
  71723. ** those references with expressions that resolve to the subquery FROM
  71724. ** elements we are now copying in.
  71725. */
  71726. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  71727. int nSubSrc;
  71728. u8 jointype = 0;
  71729. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  71730. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  71731. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  71732. if( pSrc ){
  71733. assert( pParent==p ); /* First time through the loop */
  71734. jointype = pSubitem->jointype;
  71735. }else{
  71736. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  71737. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  71738. if( pSrc==0 ){
  71739. assert( db->mallocFailed );
  71740. break;
  71741. }
  71742. }
  71743. /* The subquery uses a single slot of the FROM clause of the outer
  71744. ** query. If the subquery has more than one element in its FROM clause,
  71745. ** then expand the outer query to make space for it to hold all elements
  71746. ** of the subquery.
  71747. **
  71748. ** Example:
  71749. **
  71750. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  71751. **
  71752. ** The outer query has 3 slots in its FROM clause. One slot of the
  71753. ** outer query (the middle slot) is used by the subquery. The next
  71754. ** block of code will expand the out query to 4 slots. The middle
  71755. ** slot is expanded to two slots in order to make space for the
  71756. ** two elements in the FROM clause of the subquery.
  71757. */
  71758. if( nSubSrc>1 ){
  71759. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  71760. if( db->mallocFailed ){
  71761. break;
  71762. }
  71763. }
  71764. /* Transfer the FROM clause terms from the subquery into the
  71765. ** outer query.
  71766. */
  71767. for(i=0; i<nSubSrc; i++){
  71768. pSrc->a[i+iFrom] = pSubSrc->a[i];
  71769. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  71770. }
  71771. pSrc->a[iFrom].jointype = jointype;
  71772. /* Now begin substituting subquery result set expressions for
  71773. ** references to the iParent in the outer query.
  71774. **
  71775. ** Example:
  71776. **
  71777. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  71778. ** \ \_____________ subquery __________/ /
  71779. ** \_____________________ outer query ______________________________/
  71780. **
  71781. ** We look at every expression in the outer query and every place we see
  71782. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  71783. */
  71784. pList = pParent->pEList;
  71785. for(i=0; i<pList->nExpr; i++){
  71786. Expr *pExpr;
  71787. if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
  71788. pList->a[i].zName =
  71789. sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
  71790. }
  71791. }
  71792. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  71793. if( isAgg ){
  71794. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  71795. substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  71796. }
  71797. if( pSub->pOrderBy ){
  71798. assert( pParent->pOrderBy==0 );
  71799. pParent->pOrderBy = pSub->pOrderBy;
  71800. pSub->pOrderBy = 0;
  71801. }else if( pParent->pOrderBy ){
  71802. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  71803. }
  71804. if( pSub->pWhere ){
  71805. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  71806. }else{
  71807. pWhere = 0;
  71808. }
  71809. if( subqueryIsAgg ){
  71810. assert( pParent->pHaving==0 );
  71811. pParent->pHaving = pParent->pWhere;
  71812. pParent->pWhere = pWhere;
  71813. substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  71814. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  71815. sqlite3ExprDup(db, pSub->pHaving, 0));
  71816. assert( pParent->pGroupBy==0 );
  71817. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  71818. }else{
  71819. substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  71820. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  71821. }
  71822. /* The flattened query is distinct if either the inner or the
  71823. ** outer query is distinct.
  71824. */
  71825. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  71826. /*
  71827. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  71828. **
  71829. ** One is tempted to try to add a and b to combine the limits. But this
  71830. ** does not work if either limit is negative.
  71831. */
  71832. if( pSub->pLimit ){
  71833. pParent->pLimit = pSub->pLimit;
  71834. pSub->pLimit = 0;
  71835. }
  71836. }
  71837. /* Finially, delete what is left of the subquery and return
  71838. ** success.
  71839. */
  71840. sqlite3SelectDelete(db, pSub1);
  71841. return 1;
  71842. }
  71843. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  71844. /*
  71845. ** Analyze the SELECT statement passed as an argument to see if it
  71846. ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
  71847. ** it is, or 0 otherwise. At present, a query is considered to be
  71848. ** a min()/max() query if:
  71849. **
  71850. ** 1. There is a single object in the FROM clause.
  71851. **
  71852. ** 2. There is a single expression in the result set, and it is
  71853. ** either min(x) or max(x), where x is a column reference.
  71854. */
  71855. static u8 minMaxQuery(Select *p){
  71856. Expr *pExpr;
  71857. ExprList *pEList = p->pEList;
  71858. if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
  71859. pExpr = pEList->a[0].pExpr;
  71860. if( ExprHasProperty(pExpr, EP_xIsSelect) ) return 0;
  71861. pEList = pExpr->x.pList;
  71862. if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
  71863. if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
  71864. if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
  71865. if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
  71866. return WHERE_ORDERBY_MIN;
  71867. }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
  71868. return WHERE_ORDERBY_MAX;
  71869. }
  71870. return WHERE_ORDERBY_NORMAL;
  71871. }
  71872. /*
  71873. ** The select statement passed as the first argument is an aggregate query.
  71874. ** The second argment is the associated aggregate-info object. This
  71875. ** function tests if the SELECT is of the form:
  71876. **
  71877. ** SELECT count(*) FROM <tbl>
  71878. **
  71879. ** where table is a database table, not a sub-select or view. If the query
  71880. ** does match this pattern, then a pointer to the Table object representing
  71881. ** <tbl> is returned. Otherwise, 0 is returned.
  71882. */
  71883. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  71884. Table *pTab;
  71885. Expr *pExpr;
  71886. assert( !p->pGroupBy );
  71887. if( p->pWhere || p->pEList->nExpr!=1
  71888. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  71889. ){
  71890. return 0;
  71891. }
  71892. pTab = p->pSrc->a[0].pTab;
  71893. pExpr = p->pEList->a[0].pExpr;
  71894. assert( pTab && !pTab->pSelect && pExpr );
  71895. if( IsVirtual(pTab) ) return 0;
  71896. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  71897. if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
  71898. if( pExpr->flags&EP_Distinct ) return 0;
  71899. return pTab;
  71900. }
  71901. /*
  71902. ** If the source-list item passed as an argument was augmented with an
  71903. ** INDEXED BY clause, then try to locate the specified index. If there
  71904. ** was such a clause and the named index cannot be found, return
  71905. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  71906. ** pFrom->pIndex and return SQLITE_OK.
  71907. */
  71908. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  71909. if( pFrom->pTab && pFrom->zIndex ){
  71910. Table *pTab = pFrom->pTab;
  71911. char *zIndex = pFrom->zIndex;
  71912. Index *pIdx;
  71913. for(pIdx=pTab->pIndex;
  71914. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  71915. pIdx=pIdx->pNext
  71916. );
  71917. if( !pIdx ){
  71918. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  71919. return SQLITE_ERROR;
  71920. }
  71921. pFrom->pIndex = pIdx;
  71922. }
  71923. return SQLITE_OK;
  71924. }
  71925. /*
  71926. ** This routine is a Walker callback for "expanding" a SELECT statement.
  71927. ** "Expanding" means to do the following:
  71928. **
  71929. ** (1) Make sure VDBE cursor numbers have been assigned to every
  71930. ** element of the FROM clause.
  71931. **
  71932. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  71933. ** defines FROM clause. When views appear in the FROM clause,
  71934. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  71935. ** that implements the view. A copy is made of the view's SELECT
  71936. ** statement so that we can freely modify or delete that statement
  71937. ** without worrying about messing up the presistent representation
  71938. ** of the view.
  71939. **
  71940. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  71941. ** on joins and the ON and USING clause of joins.
  71942. **
  71943. ** (4) Scan the list of columns in the result set (pEList) looking
  71944. ** for instances of the "*" operator or the TABLE.* operator.
  71945. ** If found, expand each "*" to be every column in every table
  71946. ** and TABLE.* to be every column in TABLE.
  71947. **
  71948. */
  71949. static int selectExpander(Walker *pWalker, Select *p){
  71950. Parse *pParse = pWalker->pParse;
  71951. int i, j, k;
  71952. SrcList *pTabList;
  71953. ExprList *pEList;
  71954. struct SrcList_item *pFrom;
  71955. sqlite3 *db = pParse->db;
  71956. if( db->mallocFailed ){
  71957. return WRC_Abort;
  71958. }
  71959. if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
  71960. return WRC_Prune;
  71961. }
  71962. p->selFlags |= SF_Expanded;
  71963. pTabList = p->pSrc;
  71964. pEList = p->pEList;
  71965. /* Make sure cursor numbers have been assigned to all entries in
  71966. ** the FROM clause of the SELECT statement.
  71967. */
  71968. sqlite3SrcListAssignCursors(pParse, pTabList);
  71969. /* Look up every table named in the FROM clause of the select. If
  71970. ** an entry of the FROM clause is a subquery instead of a table or view,
  71971. ** then create a transient table structure to describe the subquery.
  71972. */
  71973. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  71974. Table *pTab;
  71975. if( pFrom->pTab!=0 ){
  71976. /* This statement has already been prepared. There is no need
  71977. ** to go further. */
  71978. assert( i==0 );
  71979. return WRC_Prune;
  71980. }
  71981. if( pFrom->zName==0 ){
  71982. #ifndef SQLITE_OMIT_SUBQUERY
  71983. Select *pSel = pFrom->pSelect;
  71984. /* A sub-query in the FROM clause of a SELECT */
  71985. assert( pSel!=0 );
  71986. assert( pFrom->pTab==0 );
  71987. sqlite3WalkSelect(pWalker, pSel);
  71988. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  71989. if( pTab==0 ) return WRC_Abort;
  71990. pTab->dbMem = db->lookaside.bEnabled ? db : 0;
  71991. pTab->nRef = 1;
  71992. pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
  71993. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  71994. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  71995. pTab->iPKey = -1;
  71996. pTab->tabFlags |= TF_Ephemeral;
  71997. #endif
  71998. }else{
  71999. /* An ordinary table or view name in the FROM clause */
  72000. assert( pFrom->pTab==0 );
  72001. pFrom->pTab = pTab =
  72002. sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
  72003. if( pTab==0 ) return WRC_Abort;
  72004. pTab->nRef++;
  72005. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  72006. if( pTab->pSelect || IsVirtual(pTab) ){
  72007. /* We reach here if the named table is a really a view */
  72008. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  72009. /* If pFrom->pSelect!=0 it means we are dealing with a
  72010. ** view within a view. The SELECT structure has already been
  72011. ** copied by the outer view so we can skip the copy step here
  72012. ** in the inner view.
  72013. */
  72014. if( pFrom->pSelect==0 ){
  72015. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  72016. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  72017. }
  72018. }
  72019. #endif
  72020. }
  72021. /* Locate the index named by the INDEXED BY clause, if any. */
  72022. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  72023. return WRC_Abort;
  72024. }
  72025. }
  72026. /* Process NATURAL keywords, and ON and USING clauses of joins.
  72027. */
  72028. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  72029. return WRC_Abort;
  72030. }
  72031. /* For every "*" that occurs in the column list, insert the names of
  72032. ** all columns in all tables. And for every TABLE.* insert the names
  72033. ** of all columns in TABLE. The parser inserted a special expression
  72034. ** with the TK_ALL operator for each "*" that it found in the column list.
  72035. ** The following code just has to locate the TK_ALL expressions and expand
  72036. ** each one to the list of all columns in all tables.
  72037. **
  72038. ** The first loop just checks to see if there are any "*" operators
  72039. ** that need expanding.
  72040. */
  72041. for(k=0; k<pEList->nExpr; k++){
  72042. Expr *pE = pEList->a[k].pExpr;
  72043. if( pE->op==TK_ALL ) break;
  72044. if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
  72045. && pE->pLeft && pE->pLeft->op==TK_ID ) break;
  72046. }
  72047. if( k<pEList->nExpr ){
  72048. /*
  72049. ** If we get here it means the result set contains one or more "*"
  72050. ** operators that need to be expanded. Loop through each expression
  72051. ** in the result set and expand them one by one.
  72052. */
  72053. struct ExprList_item *a = pEList->a;
  72054. ExprList *pNew = 0;
  72055. int flags = pParse->db->flags;
  72056. int longNames = (flags & SQLITE_FullColNames)!=0
  72057. && (flags & SQLITE_ShortColNames)==0;
  72058. for(k=0; k<pEList->nExpr; k++){
  72059. Expr *pE = a[k].pExpr;
  72060. if( pE->op!=TK_ALL &&
  72061. (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  72062. /* This particular expression does not need to be expanded.
  72063. */
  72064. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
  72065. if( pNew ){
  72066. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  72067. }
  72068. a[k].pExpr = 0;
  72069. a[k].zName = 0;
  72070. }else{
  72071. /* This expression is a "*" or a "TABLE.*" and needs to be
  72072. ** expanded. */
  72073. int tableSeen = 0; /* Set to 1 when TABLE matches */
  72074. char *zTName; /* text of name of TABLE */
  72075. if( pE->op==TK_DOT && pE->pLeft ){
  72076. zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
  72077. }else{
  72078. zTName = 0;
  72079. }
  72080. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  72081. Table *pTab = pFrom->pTab;
  72082. char *zTabName = pFrom->zAlias;
  72083. if( zTabName==0 || zTabName[0]==0 ){
  72084. zTabName = pTab->zName;
  72085. }
  72086. if( db->mallocFailed ) break;
  72087. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  72088. continue;
  72089. }
  72090. tableSeen = 1;
  72091. for(j=0; j<pTab->nCol; j++){
  72092. Expr *pExpr, *pRight;
  72093. char *zName = pTab->aCol[j].zName;
  72094. /* If a column is marked as 'hidden' (currently only possible
  72095. ** for virtual tables), do not include it in the expanded
  72096. ** result-set list.
  72097. */
  72098. if( IsHiddenColumn(&pTab->aCol[j]) ){
  72099. assert(IsVirtual(pTab));
  72100. continue;
  72101. }
  72102. if( i>0 && zTName==0 ){
  72103. struct SrcList_item *pLeft = &pTabList->a[i-1];
  72104. if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
  72105. columnIndex(pLeft->pTab, zName)>=0 ){
  72106. /* In a NATURAL join, omit the join columns from the
  72107. ** table on the right */
  72108. continue;
  72109. }
  72110. if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
  72111. /* In a join with a USING clause, omit columns in the
  72112. ** using clause from the table on the right. */
  72113. continue;
  72114. }
  72115. }
  72116. pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  72117. if( pRight==0 ) break;
  72118. setQuotedToken(pParse, &pRight->token, zName);
  72119. if( longNames || pTabList->nSrc>1 ){
  72120. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  72121. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  72122. if( pExpr==0 ) break;
  72123. setQuotedToken(pParse, &pLeft->token, zTabName);
  72124. setToken(&pExpr->span,
  72125. sqlite3MPrintf(db, "%s.%s", zTabName, zName));
  72126. pExpr->span.dyn = 1;
  72127. pExpr->token.z = 0;
  72128. pExpr->token.n = 0;
  72129. pExpr->token.dyn = 0;
  72130. }else{
  72131. pExpr = pRight;
  72132. pExpr->span = pExpr->token;
  72133. pExpr->span.dyn = 0;
  72134. }
  72135. if( longNames ){
  72136. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
  72137. }else{
  72138. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
  72139. }
  72140. }
  72141. }
  72142. if( !tableSeen ){
  72143. if( zTName ){
  72144. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  72145. }else{
  72146. sqlite3ErrorMsg(pParse, "no tables specified");
  72147. }
  72148. }
  72149. sqlite3DbFree(db, zTName);
  72150. }
  72151. }
  72152. sqlite3ExprListDelete(db, pEList);
  72153. p->pEList = pNew;
  72154. }
  72155. #if SQLITE_MAX_COLUMN
  72156. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  72157. sqlite3ErrorMsg(pParse, "too many columns in result set");
  72158. }
  72159. #endif
  72160. return WRC_Continue;
  72161. }
  72162. /*
  72163. ** No-op routine for the parse-tree walker.
  72164. **
  72165. ** When this routine is the Walker.xExprCallback then expression trees
  72166. ** are walked without any actions being taken at each node. Presumably,
  72167. ** when this routine is used for Walker.xExprCallback then
  72168. ** Walker.xSelectCallback is set to do something useful for every
  72169. ** subquery in the parser tree.
  72170. */
  72171. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  72172. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  72173. return WRC_Continue;
  72174. }
  72175. /*
  72176. ** This routine "expands" a SELECT statement and all of its subqueries.
  72177. ** For additional information on what it means to "expand" a SELECT
  72178. ** statement, see the comment on the selectExpand worker callback above.
  72179. **
  72180. ** Expanding a SELECT statement is the first step in processing a
  72181. ** SELECT statement. The SELECT statement must be expanded before
  72182. ** name resolution is performed.
  72183. **
  72184. ** If anything goes wrong, an error message is written into pParse.
  72185. ** The calling function can detect the problem by looking at pParse->nErr
  72186. ** and/or pParse->db->mallocFailed.
  72187. */
  72188. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  72189. Walker w;
  72190. w.xSelectCallback = selectExpander;
  72191. w.xExprCallback = exprWalkNoop;
  72192. w.pParse = pParse;
  72193. sqlite3WalkSelect(&w, pSelect);
  72194. }
  72195. #ifndef SQLITE_OMIT_SUBQUERY
  72196. /*
  72197. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  72198. ** interface.
  72199. **
  72200. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  72201. ** information to the Table structure that represents the result set
  72202. ** of that subquery.
  72203. **
  72204. ** The Table structure that represents the result set was constructed
  72205. ** by selectExpander() but the type and collation information was omitted
  72206. ** at that point because identifiers had not yet been resolved. This
  72207. ** routine is called after identifier resolution.
  72208. */
  72209. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  72210. Parse *pParse;
  72211. int i;
  72212. SrcList *pTabList;
  72213. struct SrcList_item *pFrom;
  72214. assert( p->selFlags & SF_Resolved );
  72215. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  72216. p->selFlags |= SF_HasTypeInfo;
  72217. pParse = pWalker->pParse;
  72218. pTabList = p->pSrc;
  72219. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  72220. Table *pTab = pFrom->pTab;
  72221. if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  72222. /* A sub-query in the FROM clause of a SELECT */
  72223. Select *pSel = pFrom->pSelect;
  72224. assert( pSel );
  72225. while( pSel->pPrior ) pSel = pSel->pPrior;
  72226. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
  72227. }
  72228. }
  72229. }
  72230. return WRC_Continue;
  72231. }
  72232. #endif
  72233. /*
  72234. ** This routine adds datatype and collating sequence information to
  72235. ** the Table structures of all FROM-clause subqueries in a
  72236. ** SELECT statement.
  72237. **
  72238. ** Use this routine after name resolution.
  72239. */
  72240. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  72241. #ifndef SQLITE_OMIT_SUBQUERY
  72242. Walker w;
  72243. w.xSelectCallback = selectAddSubqueryTypeInfo;
  72244. w.xExprCallback = exprWalkNoop;
  72245. w.pParse = pParse;
  72246. sqlite3WalkSelect(&w, pSelect);
  72247. #endif
  72248. }
  72249. /*
  72250. ** This routine sets of a SELECT statement for processing. The
  72251. ** following is accomplished:
  72252. **
  72253. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  72254. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  72255. ** * ON and USING clauses are shifted into WHERE statements
  72256. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  72257. ** * Identifiers in expression are matched to tables.
  72258. **
  72259. ** This routine acts recursively on all subqueries within the SELECT.
  72260. */
  72261. SQLITE_PRIVATE void sqlite3SelectPrep(
  72262. Parse *pParse, /* The parser context */
  72263. Select *p, /* The SELECT statement being coded. */
  72264. NameContext *pOuterNC /* Name context for container */
  72265. ){
  72266. sqlite3 *db;
  72267. if( p==0 ) return;
  72268. db = pParse->db;
  72269. if( p->selFlags & SF_HasTypeInfo ) return;
  72270. if( pParse->nErr || db->mallocFailed ) return;
  72271. sqlite3SelectExpand(pParse, p);
  72272. if( pParse->nErr || db->mallocFailed ) return;
  72273. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  72274. if( pParse->nErr || db->mallocFailed ) return;
  72275. sqlite3SelectAddTypeInfo(pParse, p);
  72276. }
  72277. /*
  72278. ** Reset the aggregate accumulator.
  72279. **
  72280. ** The aggregate accumulator is a set of memory cells that hold
  72281. ** intermediate results while calculating an aggregate. This
  72282. ** routine simply stores NULLs in all of those memory cells.
  72283. */
  72284. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  72285. Vdbe *v = pParse->pVdbe;
  72286. int i;
  72287. struct AggInfo_func *pFunc;
  72288. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  72289. return;
  72290. }
  72291. for(i=0; i<pAggInfo->nColumn; i++){
  72292. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  72293. }
  72294. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  72295. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  72296. if( pFunc->iDistinct>=0 ){
  72297. Expr *pE = pFunc->pExpr;
  72298. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  72299. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  72300. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  72301. "argument");
  72302. pFunc->iDistinct = -1;
  72303. }else{
  72304. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  72305. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  72306. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  72307. }
  72308. }
  72309. }
  72310. }
  72311. /*
  72312. ** Invoke the OP_AggFinalize opcode for every aggregate function
  72313. ** in the AggInfo structure.
  72314. */
  72315. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  72316. Vdbe *v = pParse->pVdbe;
  72317. int i;
  72318. struct AggInfo_func *pF;
  72319. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  72320. ExprList *pList = pF->pExpr->x.pList;
  72321. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  72322. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  72323. (void*)pF->pFunc, P4_FUNCDEF);
  72324. }
  72325. }
  72326. /*
  72327. ** Update the accumulator memory cells for an aggregate based on
  72328. ** the current cursor position.
  72329. */
  72330. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  72331. Vdbe *v = pParse->pVdbe;
  72332. int i;
  72333. struct AggInfo_func *pF;
  72334. struct AggInfo_col *pC;
  72335. pAggInfo->directMode = 1;
  72336. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  72337. int nArg;
  72338. int addrNext = 0;
  72339. int regAgg;
  72340. ExprList *pList = pF->pExpr->x.pList;
  72341. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  72342. if( pList ){
  72343. nArg = pList->nExpr;
  72344. regAgg = sqlite3GetTempRange(pParse, nArg);
  72345. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
  72346. }else{
  72347. nArg = 0;
  72348. regAgg = 0;
  72349. }
  72350. if( pF->iDistinct>=0 ){
  72351. addrNext = sqlite3VdbeMakeLabel(v);
  72352. assert( nArg==1 );
  72353. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  72354. }
  72355. if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  72356. CollSeq *pColl = 0;
  72357. struct ExprList_item *pItem;
  72358. int j;
  72359. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  72360. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  72361. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  72362. }
  72363. if( !pColl ){
  72364. pColl = pParse->db->pDfltColl;
  72365. }
  72366. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  72367. }
  72368. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  72369. (void*)pF->pFunc, P4_FUNCDEF);
  72370. sqlite3VdbeChangeP5(v, (u8)nArg);
  72371. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  72372. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  72373. if( addrNext ){
  72374. sqlite3VdbeResolveLabel(v, addrNext);
  72375. }
  72376. }
  72377. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  72378. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  72379. }
  72380. pAggInfo->directMode = 0;
  72381. }
  72382. /*
  72383. ** Generate code for the SELECT statement given in the p argument.
  72384. **
  72385. ** The results are distributed in various ways depending on the
  72386. ** contents of the SelectDest structure pointed to by argument pDest
  72387. ** as follows:
  72388. **
  72389. ** pDest->eDest Result
  72390. ** ------------ -------------------------------------------
  72391. ** SRT_Output Generate a row of output (using the OP_ResultRow
  72392. ** opcode) for each row in the result set.
  72393. **
  72394. ** SRT_Mem Only valid if the result is a single column.
  72395. ** Store the first column of the first result row
  72396. ** in register pDest->iParm then abandon the rest
  72397. ** of the query. This destination implies "LIMIT 1".
  72398. **
  72399. ** SRT_Set The result must be a single column. Store each
  72400. ** row of result as the key in table pDest->iParm.
  72401. ** Apply the affinity pDest->affinity before storing
  72402. ** results. Used to implement "IN (SELECT ...)".
  72403. **
  72404. ** SRT_Union Store results as a key in a temporary table pDest->iParm.
  72405. **
  72406. ** SRT_Except Remove results from the temporary table pDest->iParm.
  72407. **
  72408. ** SRT_Table Store results in temporary table pDest->iParm.
  72409. ** This is like SRT_EphemTab except that the table
  72410. ** is assumed to already be open.
  72411. **
  72412. ** SRT_EphemTab Create an temporary table pDest->iParm and store
  72413. ** the result there. The cursor is left open after
  72414. ** returning. This is like SRT_Table except that
  72415. ** this destination uses OP_OpenEphemeral to create
  72416. ** the table first.
  72417. **
  72418. ** SRT_Coroutine Generate a co-routine that returns a new row of
  72419. ** results each time it is invoked. The entry point
  72420. ** of the co-routine is stored in register pDest->iParm.
  72421. **
  72422. ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result
  72423. ** set is not empty.
  72424. **
  72425. ** SRT_Discard Throw the results away. This is used by SELECT
  72426. ** statements within triggers whose only purpose is
  72427. ** the side-effects of functions.
  72428. **
  72429. ** This routine returns the number of errors. If any errors are
  72430. ** encountered, then an appropriate error message is left in
  72431. ** pParse->zErrMsg.
  72432. **
  72433. ** This routine does NOT free the Select structure passed in. The
  72434. ** calling function needs to do that.
  72435. */
  72436. SQLITE_PRIVATE int sqlite3Select(
  72437. Parse *pParse, /* The parser context */
  72438. Select *p, /* The SELECT statement being coded. */
  72439. SelectDest *pDest /* What to do with the query results */
  72440. ){
  72441. int i, j; /* Loop counters */
  72442. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  72443. Vdbe *v; /* The virtual machine under construction */
  72444. int isAgg; /* True for select lists like "count(*)" */
  72445. ExprList *pEList; /* List of columns to extract. */
  72446. SrcList *pTabList; /* List of tables to select from */
  72447. Expr *pWhere; /* The WHERE clause. May be NULL */
  72448. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  72449. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  72450. Expr *pHaving; /* The HAVING clause. May be NULL */
  72451. int isDistinct; /* True if the DISTINCT keyword is present */
  72452. int distinct; /* Table to use for the distinct set */
  72453. int rc = 1; /* Value to return from this function */
  72454. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  72455. AggInfo sAggInfo; /* Information used by aggregate queries */
  72456. int iEnd; /* Address of the end of the query */
  72457. sqlite3 *db; /* The database connection */
  72458. db = pParse->db;
  72459. if( p==0 || db->mallocFailed || pParse->nErr ){
  72460. return 1;
  72461. }
  72462. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  72463. memset(&sAggInfo, 0, sizeof(sAggInfo));
  72464. pOrderBy = p->pOrderBy;
  72465. if( IgnorableOrderby(pDest) ){
  72466. p->pOrderBy = 0;
  72467. /* In these cases the DISTINCT operator makes no difference to the
  72468. ** results, so remove it if it were specified.
  72469. */
  72470. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  72471. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  72472. p->selFlags &= ~SF_Distinct;
  72473. }
  72474. sqlite3SelectPrep(pParse, p, 0);
  72475. pTabList = p->pSrc;
  72476. pEList = p->pEList;
  72477. if( pParse->nErr || db->mallocFailed ){
  72478. goto select_end;
  72479. }
  72480. p->pOrderBy = pOrderBy;
  72481. isAgg = (p->selFlags & SF_Aggregate)!=0;
  72482. if( pEList==0 ) goto select_end;
  72483. /*
  72484. ** Do not even attempt to generate any code if we have already seen
  72485. ** errors before this routine starts.
  72486. */
  72487. if( pParse->nErr>0 ) goto select_end;
  72488. /* ORDER BY is ignored for some destinations.
  72489. */
  72490. if( IgnorableOrderby(pDest) ){
  72491. pOrderBy = 0;
  72492. }
  72493. /* Begin generating code.
  72494. */
  72495. v = sqlite3GetVdbe(pParse);
  72496. if( v==0 ) goto select_end;
  72497. /* Generate code for all sub-queries in the FROM clause
  72498. */
  72499. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  72500. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  72501. struct SrcList_item *pItem = &pTabList->a[i];
  72502. SelectDest dest;
  72503. Select *pSub = pItem->pSelect;
  72504. int isAggSub;
  72505. if( pSub==0 || pItem->isPopulated ) continue;
  72506. /* Increment Parse.nHeight by the height of the largest expression
  72507. ** tree refered to by this, the parent select. The child select
  72508. ** may contain expression trees of at most
  72509. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  72510. ** more conservative than necessary, but much easier than enforcing
  72511. ** an exact limit.
  72512. */
  72513. pParse->nHeight += sqlite3SelectExprHeight(p);
  72514. /* Check to see if the subquery can be absorbed into the parent. */
  72515. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  72516. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  72517. if( isAggSub ){
  72518. isAgg = 1;
  72519. p->selFlags |= SF_Aggregate;
  72520. }
  72521. i = -1;
  72522. }else{
  72523. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  72524. assert( pItem->isPopulated==0 );
  72525. sqlite3Select(pParse, pSub, &dest);
  72526. pItem->isPopulated = 1;
  72527. }
  72528. if( pParse->nErr || db->mallocFailed ){
  72529. goto select_end;
  72530. }
  72531. pParse->nHeight -= sqlite3SelectExprHeight(p);
  72532. pTabList = p->pSrc;
  72533. if( !IgnorableOrderby(pDest) ){
  72534. pOrderBy = p->pOrderBy;
  72535. }
  72536. }
  72537. pEList = p->pEList;
  72538. #endif
  72539. pWhere = p->pWhere;
  72540. pGroupBy = p->pGroupBy;
  72541. pHaving = p->pHaving;
  72542. isDistinct = (p->selFlags & SF_Distinct)!=0;
  72543. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  72544. /* If there is are a sequence of queries, do the earlier ones first.
  72545. */
  72546. if( p->pPrior ){
  72547. if( p->pRightmost==0 ){
  72548. Select *pLoop, *pRight = 0;
  72549. int cnt = 0;
  72550. int mxSelect;
  72551. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  72552. pLoop->pRightmost = p;
  72553. pLoop->pNext = pRight;
  72554. pRight = pLoop;
  72555. }
  72556. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  72557. if( mxSelect && cnt>mxSelect ){
  72558. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  72559. return 1;
  72560. }
  72561. }
  72562. return multiSelect(pParse, p, pDest);
  72563. }
  72564. #endif
  72565. /* If writing to memory or generating a set
  72566. ** only a single column may be output.
  72567. */
  72568. #ifndef SQLITE_OMIT_SUBQUERY
  72569. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  72570. goto select_end;
  72571. }
  72572. #endif
  72573. /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
  72574. ** GROUP BY might use an index, DISTINCT never does.
  72575. */
  72576. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
  72577. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  72578. pGroupBy = p->pGroupBy;
  72579. p->selFlags &= ~SF_Distinct;
  72580. isDistinct = 0;
  72581. }
  72582. /* If there is an ORDER BY clause, then this sorting
  72583. ** index might end up being unused if the data can be
  72584. ** extracted in pre-sorted order. If that is the case, then the
  72585. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  72586. ** we figure out that the sorting index is not needed. The addrSortIndex
  72587. ** variable is used to facilitate that change.
  72588. */
  72589. if( pOrderBy ){
  72590. KeyInfo *pKeyInfo;
  72591. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  72592. pOrderBy->iECursor = pParse->nTab++;
  72593. p->addrOpenEphm[2] = addrSortIndex =
  72594. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  72595. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  72596. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  72597. }else{
  72598. addrSortIndex = -1;
  72599. }
  72600. /* If the output is destined for a temporary table, open that table.
  72601. */
  72602. if( pDest->eDest==SRT_EphemTab ){
  72603. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
  72604. }
  72605. /* Set the limiter.
  72606. */
  72607. iEnd = sqlite3VdbeMakeLabel(v);
  72608. computeLimitRegisters(pParse, p, iEnd);
  72609. /* Open a virtual index to use for the distinct set.
  72610. */
  72611. if( isDistinct ){
  72612. KeyInfo *pKeyInfo;
  72613. assert( isAgg || pGroupBy );
  72614. distinct = pParse->nTab++;
  72615. pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
  72616. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
  72617. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  72618. }else{
  72619. distinct = -1;
  72620. }
  72621. /* Aggregate and non-aggregate queries are handled differently */
  72622. if( !isAgg && pGroupBy==0 ){
  72623. /* This case is for non-aggregate queries
  72624. ** Begin the database scan
  72625. */
  72626. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0, 0);
  72627. if( pWInfo==0 ) goto select_end;
  72628. /* If sorting index that was created by a prior OP_OpenEphemeral
  72629. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  72630. ** into an OP_Noop.
  72631. */
  72632. if( addrSortIndex>=0 && pOrderBy==0 ){
  72633. sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
  72634. p->addrOpenEphm[2] = -1;
  72635. }
  72636. /* Use the standard inner loop
  72637. */
  72638. assert(!isDistinct);
  72639. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
  72640. pWInfo->iContinue, pWInfo->iBreak);
  72641. /* End the database scan loop.
  72642. */
  72643. sqlite3WhereEnd(pWInfo);
  72644. }else{
  72645. /* This is the processing for aggregate queries */
  72646. NameContext sNC; /* Name context for processing aggregate information */
  72647. int iAMem; /* First Mem address for storing current GROUP BY */
  72648. int iBMem; /* First Mem address for previous GROUP BY */
  72649. int iUseFlag; /* Mem address holding flag indicating that at least
  72650. ** one row of the input to the aggregator has been
  72651. ** processed */
  72652. int iAbortFlag; /* Mem address which causes query abort if positive */
  72653. int groupBySort; /* Rows come from source in GROUP BY order */
  72654. int addrEnd; /* End of processing for this SELECT */
  72655. /* Remove any and all aliases between the result set and the
  72656. ** GROUP BY clause.
  72657. */
  72658. if( pGroupBy ){
  72659. int k; /* Loop counter */
  72660. struct ExprList_item *pItem; /* For looping over expression in a list */
  72661. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  72662. pItem->iAlias = 0;
  72663. }
  72664. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  72665. pItem->iAlias = 0;
  72666. }
  72667. }
  72668. /* Create a label to jump to when we want to abort the query */
  72669. addrEnd = sqlite3VdbeMakeLabel(v);
  72670. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  72671. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  72672. ** SELECT statement.
  72673. */
  72674. memset(&sNC, 0, sizeof(sNC));
  72675. sNC.pParse = pParse;
  72676. sNC.pSrcList = pTabList;
  72677. sNC.pAggInfo = &sAggInfo;
  72678. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  72679. sAggInfo.pGroupBy = pGroupBy;
  72680. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  72681. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  72682. if( pHaving ){
  72683. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  72684. }
  72685. sAggInfo.nAccumulator = sAggInfo.nColumn;
  72686. for(i=0; i<sAggInfo.nFunc; i++){
  72687. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  72688. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  72689. }
  72690. if( db->mallocFailed ) goto select_end;
  72691. /* Processing for aggregates with GROUP BY is very different and
  72692. ** much more complex than aggregates without a GROUP BY.
  72693. */
  72694. if( pGroupBy ){
  72695. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  72696. int j1; /* A-vs-B comparision jump */
  72697. int addrOutputRow; /* Start of subroutine that outputs a result row */
  72698. int regOutputRow; /* Return address register for output subroutine */
  72699. int addrSetAbort; /* Set the abort flag and return */
  72700. int addrTopOfLoop; /* Top of the input loop */
  72701. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  72702. int addrReset; /* Subroutine for resetting the accumulator */
  72703. int regReset; /* Return address register for reset subroutine */
  72704. /* If there is a GROUP BY clause we might need a sorting index to
  72705. ** implement it. Allocate that sorting index now. If it turns out
  72706. ** that we do not need it after all, the OpenEphemeral instruction
  72707. ** will be converted into a Noop.
  72708. */
  72709. sAggInfo.sortingIdx = pParse->nTab++;
  72710. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  72711. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  72712. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  72713. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  72714. /* Initialize memory locations used by GROUP BY aggregate processing
  72715. */
  72716. iUseFlag = ++pParse->nMem;
  72717. iAbortFlag = ++pParse->nMem;
  72718. regOutputRow = ++pParse->nMem;
  72719. addrOutputRow = sqlite3VdbeMakeLabel(v);
  72720. regReset = ++pParse->nMem;
  72721. addrReset = sqlite3VdbeMakeLabel(v);
  72722. iAMem = pParse->nMem + 1;
  72723. pParse->nMem += pGroupBy->nExpr;
  72724. iBMem = pParse->nMem + 1;
  72725. pParse->nMem += pGroupBy->nExpr;
  72726. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  72727. VdbeComment((v, "clear abort flag"));
  72728. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  72729. VdbeComment((v, "indicate accumulator empty"));
  72730. /* Begin a loop that will extract all source rows in GROUP BY order.
  72731. ** This might involve two separate loops with an OP_Sort in between, or
  72732. ** it might be a single loop that uses an index to extract information
  72733. ** in the right order to begin with.
  72734. */
  72735. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  72736. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
  72737. if( pWInfo==0 ) goto select_end;
  72738. if( pGroupBy==0 ){
  72739. /* The optimizer is able to deliver rows in group by order so
  72740. ** we do not have to sort. The OP_OpenEphemeral table will be
  72741. ** cancelled later because we still need to use the pKeyInfo
  72742. */
  72743. pGroupBy = p->pGroupBy;
  72744. groupBySort = 0;
  72745. }else{
  72746. /* Rows are coming out in undetermined order. We have to push
  72747. ** each row into a sorting index, terminate the first loop,
  72748. ** then loop over the sorting index in order to get the output
  72749. ** in sorted order
  72750. */
  72751. int regBase;
  72752. int regRecord;
  72753. int nCol;
  72754. int nGroupBy;
  72755. groupBySort = 1;
  72756. nGroupBy = pGroupBy->nExpr;
  72757. nCol = nGroupBy + 1;
  72758. j = nGroupBy+1;
  72759. for(i=0; i<sAggInfo.nColumn; i++){
  72760. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  72761. nCol++;
  72762. j++;
  72763. }
  72764. }
  72765. regBase = sqlite3GetTempRange(pParse, nCol);
  72766. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  72767. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  72768. j = nGroupBy+1;
  72769. for(i=0; i<sAggInfo.nColumn; i++){
  72770. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  72771. if( pCol->iSorterColumn>=j ){
  72772. int r1 = j + regBase;
  72773. int r2;
  72774. r2 = sqlite3ExprCodeGetColumn(pParse,
  72775. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  72776. if( r1!=r2 ){
  72777. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  72778. }
  72779. j++;
  72780. }
  72781. }
  72782. regRecord = sqlite3GetTempReg(pParse);
  72783. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  72784. sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
  72785. sqlite3ReleaseTempReg(pParse, regRecord);
  72786. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  72787. sqlite3WhereEnd(pWInfo);
  72788. sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
  72789. VdbeComment((v, "GROUP BY sort"));
  72790. sAggInfo.useSortingIdx = 1;
  72791. }
  72792. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  72793. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  72794. ** Then compare the current GROUP BY terms against the GROUP BY terms
  72795. ** from the previous row currently stored in a0, a1, a2...
  72796. */
  72797. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  72798. for(j=0; j<pGroupBy->nExpr; j++){
  72799. if( groupBySort ){
  72800. sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
  72801. }else{
  72802. sAggInfo.directMode = 1;
  72803. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  72804. }
  72805. }
  72806. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  72807. (char*)pKeyInfo, P4_KEYINFO);
  72808. j1 = sqlite3VdbeCurrentAddr(v);
  72809. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  72810. /* Generate code that runs whenever the GROUP BY changes.
  72811. ** Changes in the GROUP BY are detected by the previous code
  72812. ** block. If there were no changes, this block is skipped.
  72813. **
  72814. ** This code copies current group by terms in b0,b1,b2,...
  72815. ** over to a0,a1,a2. It then calls the output subroutine
  72816. ** and resets the aggregate accumulator registers in preparation
  72817. ** for the next GROUP BY batch.
  72818. */
  72819. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  72820. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  72821. VdbeComment((v, "output one row"));
  72822. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  72823. VdbeComment((v, "check abort flag"));
  72824. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  72825. VdbeComment((v, "reset accumulator"));
  72826. /* Update the aggregate accumulators based on the content of
  72827. ** the current row
  72828. */
  72829. sqlite3VdbeJumpHere(v, j1);
  72830. updateAccumulator(pParse, &sAggInfo);
  72831. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  72832. VdbeComment((v, "indicate data in accumulator"));
  72833. /* End of the loop
  72834. */
  72835. if( groupBySort ){
  72836. sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
  72837. }else{
  72838. sqlite3WhereEnd(pWInfo);
  72839. sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
  72840. }
  72841. /* Output the final row of result
  72842. */
  72843. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  72844. VdbeComment((v, "output final row"));
  72845. /* Jump over the subroutines
  72846. */
  72847. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  72848. /* Generate a subroutine that outputs a single row of the result
  72849. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  72850. ** is less than or equal to zero, the subroutine is a no-op. If
  72851. ** the processing calls for the query to abort, this subroutine
  72852. ** increments the iAbortFlag memory location before returning in
  72853. ** order to signal the caller to abort.
  72854. */
  72855. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  72856. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  72857. VdbeComment((v, "set abort flag"));
  72858. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  72859. sqlite3VdbeResolveLabel(v, addrOutputRow);
  72860. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  72861. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  72862. VdbeComment((v, "Groupby result generator entry point"));
  72863. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  72864. finalizeAggFunctions(pParse, &sAggInfo);
  72865. if( pHaving ){
  72866. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  72867. }
  72868. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  72869. distinct, pDest,
  72870. addrOutputRow+1, addrSetAbort);
  72871. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  72872. VdbeComment((v, "end groupby result generator"));
  72873. /* Generate a subroutine that will reset the group-by accumulator
  72874. */
  72875. sqlite3VdbeResolveLabel(v, addrReset);
  72876. resetAccumulator(pParse, &sAggInfo);
  72877. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  72878. } /* endif pGroupBy */
  72879. else {
  72880. ExprList *pDel = 0;
  72881. #ifndef SQLITE_OMIT_BTREECOUNT
  72882. Table *pTab;
  72883. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  72884. /* If isSimpleCount() returns a pointer to a Table structure, then
  72885. ** the SQL statement is of the form:
  72886. **
  72887. ** SELECT count(*) FROM <tbl>
  72888. **
  72889. ** where the Table structure returned represents table <tbl>.
  72890. **
  72891. ** This statement is so common that it is optimized specially. The
  72892. ** OP_Count instruction is executed either on the intkey table that
  72893. ** contains the data for table <tbl> or on one of its indexes. It
  72894. ** is better to execute the op on an index, as indexes are almost
  72895. ** always spread across less pages than their corresponding tables.
  72896. */
  72897. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  72898. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  72899. Index *pIdx; /* Iterator variable */
  72900. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  72901. Index *pBest = 0; /* Best index found so far */
  72902. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  72903. sqlite3CodeVerifySchema(pParse, iDb);
  72904. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  72905. /* Search for the index that has the least amount of columns. If
  72906. ** there is such an index, and it has less columns than the table
  72907. ** does, then we can assume that it consumes less space on disk and
  72908. ** will therefore be cheaper to scan to determine the query result.
  72909. ** In this case set iRoot to the root page number of the index b-tree
  72910. ** and pKeyInfo to the KeyInfo structure required to navigate the
  72911. ** index.
  72912. **
  72913. ** In practice the KeyInfo structure will not be used. It is only
  72914. ** passed to keep OP_OpenRead happy.
  72915. */
  72916. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  72917. if( !pBest || pIdx->nColumn<pBest->nColumn ){
  72918. pBest = pIdx;
  72919. }
  72920. }
  72921. if( pBest && pBest->nColumn<pTab->nCol ){
  72922. iRoot = pBest->tnum;
  72923. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  72924. }
  72925. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  72926. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  72927. if( pKeyInfo ){
  72928. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  72929. }
  72930. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  72931. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  72932. }else
  72933. #endif /* SQLITE_OMIT_BTREECOUNT */
  72934. {
  72935. /* Check if the query is of one of the following forms:
  72936. **
  72937. ** SELECT min(x) FROM ...
  72938. ** SELECT max(x) FROM ...
  72939. **
  72940. ** If it is, then ask the code in where.c to attempt to sort results
  72941. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  72942. ** If where.c is able to produce results sorted in this order, then
  72943. ** add vdbe code to break out of the processing loop after the
  72944. ** first iteration (since the first iteration of the loop is
  72945. ** guaranteed to operate on the row with the minimum or maximum
  72946. ** value of x, the only row required).
  72947. **
  72948. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  72949. ** modify behaviour as follows:
  72950. **
  72951. ** + If the query is a "SELECT min(x)", then the loop coded by
  72952. ** where.c should not iterate over any values with a NULL value
  72953. ** for x.
  72954. **
  72955. ** + The optimizer code in where.c (the thing that decides which
  72956. ** index or indices to use) should place a different priority on
  72957. ** satisfying the 'ORDER BY' clause than it does in other cases.
  72958. ** Refer to code and comments in where.c for details.
  72959. */
  72960. ExprList *pMinMax = 0;
  72961. u8 flag = minMaxQuery(p);
  72962. if( flag ){
  72963. assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
  72964. pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
  72965. pDel = pMinMax;
  72966. if( pMinMax && !db->mallocFailed ){
  72967. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  72968. pMinMax->a[0].pExpr->op = TK_COLUMN;
  72969. }
  72970. }
  72971. /* This case runs if the aggregate has no GROUP BY clause. The
  72972. ** processing is much simpler since there is only a single row
  72973. ** of output.
  72974. */
  72975. resetAccumulator(pParse, &sAggInfo);
  72976. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag, 0);
  72977. if( pWInfo==0 ){
  72978. sqlite3ExprListDelete(db, pDel);
  72979. goto select_end;
  72980. }
  72981. updateAccumulator(pParse, &sAggInfo);
  72982. if( !pMinMax && flag ){
  72983. sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
  72984. VdbeComment((v, "%s() by index",
  72985. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  72986. }
  72987. sqlite3WhereEnd(pWInfo);
  72988. finalizeAggFunctions(pParse, &sAggInfo);
  72989. }
  72990. pOrderBy = 0;
  72991. if( pHaving ){
  72992. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  72993. }
  72994. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
  72995. pDest, addrEnd, addrEnd);
  72996. sqlite3ExprListDelete(db, pDel);
  72997. }
  72998. sqlite3VdbeResolveLabel(v, addrEnd);
  72999. } /* endif aggregate query */
  73000. /* If there is an ORDER BY clause, then we need to sort the results
  73001. ** and send them to the callback one by one.
  73002. */
  73003. if( pOrderBy ){
  73004. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  73005. }
  73006. /* Jump here to skip this query
  73007. */
  73008. sqlite3VdbeResolveLabel(v, iEnd);
  73009. /* The SELECT was successfully coded. Set the return code to 0
  73010. ** to indicate no errors.
  73011. */
  73012. rc = 0;
  73013. /* Control jumps to here if an error is encountered above, or upon
  73014. ** successful coding of the SELECT.
  73015. */
  73016. select_end:
  73017. /* Identify column names if results of the SELECT are to be output.
  73018. */
  73019. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  73020. generateColumnNames(pParse, pTabList, pEList);
  73021. }
  73022. sqlite3DbFree(db, sAggInfo.aCol);
  73023. sqlite3DbFree(db, sAggInfo.aFunc);
  73024. return rc;
  73025. }
  73026. #if defined(SQLITE_DEBUG)
  73027. /*
  73028. *******************************************************************************
  73029. ** The following code is used for testing and debugging only. The code
  73030. ** that follows does not appear in normal builds.
  73031. **
  73032. ** These routines are used to print out the content of all or part of a
  73033. ** parse structures such as Select or Expr. Such printouts are useful
  73034. ** for helping to understand what is happening inside the code generator
  73035. ** during the execution of complex SELECT statements.
  73036. **
  73037. ** These routine are not called anywhere from within the normal
  73038. ** code base. Then are intended to be called from within the debugger
  73039. ** or from temporary "printf" statements inserted for debugging.
  73040. */
  73041. SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
  73042. if( p->token.z && p->token.n>0 ){
  73043. sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
  73044. }else{
  73045. sqlite3DebugPrintf("(%d", p->op);
  73046. }
  73047. if( p->pLeft ){
  73048. sqlite3DebugPrintf(" ");
  73049. sqlite3PrintExpr(p->pLeft);
  73050. }
  73051. if( p->pRight ){
  73052. sqlite3DebugPrintf(" ");
  73053. sqlite3PrintExpr(p->pRight);
  73054. }
  73055. sqlite3DebugPrintf(")");
  73056. }
  73057. SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
  73058. int i;
  73059. for(i=0; i<pList->nExpr; i++){
  73060. sqlite3PrintExpr(pList->a[i].pExpr);
  73061. if( i<pList->nExpr-1 ){
  73062. sqlite3DebugPrintf(", ");
  73063. }
  73064. }
  73065. }
  73066. SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
  73067. sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  73068. sqlite3PrintExprList(p->pEList);
  73069. sqlite3DebugPrintf("\n");
  73070. if( p->pSrc ){
  73071. char *zPrefix;
  73072. int i;
  73073. zPrefix = "FROM";
  73074. for(i=0; i<p->pSrc->nSrc; i++){
  73075. struct SrcList_item *pItem = &p->pSrc->a[i];
  73076. sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  73077. zPrefix = "";
  73078. if( pItem->pSelect ){
  73079. sqlite3DebugPrintf("(\n");
  73080. sqlite3PrintSelect(pItem->pSelect, indent+10);
  73081. sqlite3DebugPrintf("%*s)", indent+8, "");
  73082. }else if( pItem->zName ){
  73083. sqlite3DebugPrintf("%s", pItem->zName);
  73084. }
  73085. if( pItem->pTab ){
  73086. sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
  73087. }
  73088. if( pItem->zAlias ){
  73089. sqlite3DebugPrintf(" AS %s", pItem->zAlias);
  73090. }
  73091. if( i<p->pSrc->nSrc-1 ){
  73092. sqlite3DebugPrintf(",");
  73093. }
  73094. sqlite3DebugPrintf("\n");
  73095. }
  73096. }
  73097. if( p->pWhere ){
  73098. sqlite3DebugPrintf("%*s WHERE ", indent, "");
  73099. sqlite3PrintExpr(p->pWhere);
  73100. sqlite3DebugPrintf("\n");
  73101. }
  73102. if( p->pGroupBy ){
  73103. sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  73104. sqlite3PrintExprList(p->pGroupBy);
  73105. sqlite3DebugPrintf("\n");
  73106. }
  73107. if( p->pHaving ){
  73108. sqlite3DebugPrintf("%*s HAVING ", indent, "");
  73109. sqlite3PrintExpr(p->pHaving);
  73110. sqlite3DebugPrintf("\n");
  73111. }
  73112. if( p->pOrderBy ){
  73113. sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  73114. sqlite3PrintExprList(p->pOrderBy);
  73115. sqlite3DebugPrintf("\n");
  73116. }
  73117. }
  73118. /* End of the structure debug printing code
  73119. *****************************************************************************/
  73120. #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  73121. /************** End of select.c **********************************************/
  73122. /************** Begin file table.c *******************************************/
  73123. /*
  73124. ** 2001 September 15
  73125. **
  73126. ** The author disclaims copyright to this source code. In place of
  73127. ** a legal notice, here is a blessing:
  73128. **
  73129. ** May you do good and not evil.
  73130. ** May you find forgiveness for yourself and forgive others.
  73131. ** May you share freely, never taking more than you give.
  73132. **
  73133. *************************************************************************
  73134. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  73135. ** interface routines. These are just wrappers around the main
  73136. ** interface routine of sqlite3_exec().
  73137. **
  73138. ** These routines are in a separate files so that they will not be linked
  73139. ** if they are not used.
  73140. **
  73141. ** $Id: table.c,v 1.40 2009/04/10 14:28:00 drh Exp $
  73142. */
  73143. #ifndef SQLITE_OMIT_GET_TABLE
  73144. /*
  73145. ** This structure is used to pass data from sqlite3_get_table() through
  73146. ** to the callback function is uses to build the result.
  73147. */
  73148. typedef struct TabResult {
  73149. char **azResult; /* Accumulated output */
  73150. char *zErrMsg; /* Error message text, if an error occurs */
  73151. int nAlloc; /* Slots allocated for azResult[] */
  73152. int nRow; /* Number of rows in the result */
  73153. int nColumn; /* Number of columns in the result */
  73154. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  73155. int rc; /* Return code from sqlite3_exec() */
  73156. } TabResult;
  73157. /*
  73158. ** This routine is called once for each row in the result table. Its job
  73159. ** is to fill in the TabResult structure appropriately, allocating new
  73160. ** memory as necessary.
  73161. */
  73162. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  73163. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  73164. int need; /* Slots needed in p->azResult[] */
  73165. int i; /* Loop counter */
  73166. char *z; /* A single column of result */
  73167. /* Make sure there is enough space in p->azResult to hold everything
  73168. ** we need to remember from this invocation of the callback.
  73169. */
  73170. if( p->nRow==0 && argv!=0 ){
  73171. need = nCol*2;
  73172. }else{
  73173. need = nCol;
  73174. }
  73175. if( p->nData + need > p->nAlloc ){
  73176. char **azNew;
  73177. p->nAlloc = p->nAlloc*2 + need;
  73178. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  73179. if( azNew==0 ) goto malloc_failed;
  73180. p->azResult = azNew;
  73181. }
  73182. /* If this is the first row, then generate an extra row containing
  73183. ** the names of all columns.
  73184. */
  73185. if( p->nRow==0 ){
  73186. p->nColumn = nCol;
  73187. for(i=0; i<nCol; i++){
  73188. z = sqlite3_mprintf("%s", colv[i]);
  73189. if( z==0 ) goto malloc_failed;
  73190. p->azResult[p->nData++] = z;
  73191. }
  73192. }else if( p->nColumn!=nCol ){
  73193. sqlite3_free(p->zErrMsg);
  73194. p->zErrMsg = sqlite3_mprintf(
  73195. "sqlite3_get_table() called with two or more incompatible queries"
  73196. );
  73197. p->rc = SQLITE_ERROR;
  73198. return 1;
  73199. }
  73200. /* Copy over the row data
  73201. */
  73202. if( argv!=0 ){
  73203. for(i=0; i<nCol; i++){
  73204. if( argv[i]==0 ){
  73205. z = 0;
  73206. }else{
  73207. int n = sqlite3Strlen30(argv[i])+1;
  73208. z = sqlite3_malloc( n );
  73209. if( z==0 ) goto malloc_failed;
  73210. memcpy(z, argv[i], n);
  73211. }
  73212. p->azResult[p->nData++] = z;
  73213. }
  73214. p->nRow++;
  73215. }
  73216. return 0;
  73217. malloc_failed:
  73218. p->rc = SQLITE_NOMEM;
  73219. return 1;
  73220. }
  73221. /*
  73222. ** Query the database. But instead of invoking a callback for each row,
  73223. ** malloc() for space to hold the result and return the entire results
  73224. ** at the conclusion of the call.
  73225. **
  73226. ** The result that is written to ***pazResult is held in memory obtained
  73227. ** from malloc(). But the caller cannot free this memory directly.
  73228. ** Instead, the entire table should be passed to sqlite3_free_table() when
  73229. ** the calling procedure is finished using it.
  73230. */
  73231. SQLITE_API int sqlite3_get_table(
  73232. sqlite3 *db, /* The database on which the SQL executes */
  73233. const char *zSql, /* The SQL to be executed */
  73234. char ***pazResult, /* Write the result table here */
  73235. int *pnRow, /* Write the number of rows in the result here */
  73236. int *pnColumn, /* Write the number of columns of result here */
  73237. char **pzErrMsg /* Write error messages here */
  73238. ){
  73239. int rc;
  73240. TabResult res;
  73241. *pazResult = 0;
  73242. if( pnColumn ) *pnColumn = 0;
  73243. if( pnRow ) *pnRow = 0;
  73244. if( pzErrMsg ) *pzErrMsg = 0;
  73245. res.zErrMsg = 0;
  73246. res.nRow = 0;
  73247. res.nColumn = 0;
  73248. res.nData = 1;
  73249. res.nAlloc = 20;
  73250. res.rc = SQLITE_OK;
  73251. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  73252. if( res.azResult==0 ){
  73253. db->errCode = SQLITE_NOMEM;
  73254. return SQLITE_NOMEM;
  73255. }
  73256. res.azResult[0] = 0;
  73257. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  73258. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  73259. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  73260. if( (rc&0xff)==SQLITE_ABORT ){
  73261. sqlite3_free_table(&res.azResult[1]);
  73262. if( res.zErrMsg ){
  73263. if( pzErrMsg ){
  73264. sqlite3_free(*pzErrMsg);
  73265. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  73266. }
  73267. sqlite3_free(res.zErrMsg);
  73268. }
  73269. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  73270. return res.rc;
  73271. }
  73272. sqlite3_free(res.zErrMsg);
  73273. if( rc!=SQLITE_OK ){
  73274. sqlite3_free_table(&res.azResult[1]);
  73275. return rc;
  73276. }
  73277. if( res.nAlloc>res.nData ){
  73278. char **azNew;
  73279. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  73280. if( azNew==0 ){
  73281. sqlite3_free_table(&res.azResult[1]);
  73282. db->errCode = SQLITE_NOMEM;
  73283. return SQLITE_NOMEM;
  73284. }
  73285. res.azResult = azNew;
  73286. }
  73287. *pazResult = &res.azResult[1];
  73288. if( pnColumn ) *pnColumn = res.nColumn;
  73289. if( pnRow ) *pnRow = res.nRow;
  73290. return rc;
  73291. }
  73292. /*
  73293. ** This routine frees the space the sqlite3_get_table() malloced.
  73294. */
  73295. SQLITE_API void sqlite3_free_table(
  73296. char **azResult /* Result returned from from sqlite3_get_table() */
  73297. ){
  73298. if( azResult ){
  73299. int i, n;
  73300. azResult--;
  73301. assert( azResult!=0 );
  73302. n = SQLITE_PTR_TO_INT(azResult[0]);
  73303. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  73304. sqlite3_free(azResult);
  73305. }
  73306. }
  73307. #endif /* SQLITE_OMIT_GET_TABLE */
  73308. /************** End of table.c ***********************************************/
  73309. /************** Begin file trigger.c *****************************************/
  73310. /*
  73311. **
  73312. ** The author disclaims copyright to this source code. In place of
  73313. ** a legal notice, here is a blessing:
  73314. **
  73315. ** May you do good and not evil.
  73316. ** May you find forgiveness for yourself and forgive others.
  73317. ** May you share freely, never taking more than you give.
  73318. **
  73319. *************************************************************************
  73320. **
  73321. **
  73322. ** $Id: trigger.c,v 1.135 2009/02/28 10:47:42 danielk1977 Exp $
  73323. */
  73324. #ifndef SQLITE_OMIT_TRIGGER
  73325. /*
  73326. ** Delete a linked list of TriggerStep structures.
  73327. */
  73328. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  73329. while( pTriggerStep ){
  73330. TriggerStep * pTmp = pTriggerStep;
  73331. pTriggerStep = pTriggerStep->pNext;
  73332. if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
  73333. sqlite3ExprDelete(db, pTmp->pWhere);
  73334. sqlite3ExprListDelete(db, pTmp->pExprList);
  73335. sqlite3SelectDelete(db, pTmp->pSelect);
  73336. sqlite3IdListDelete(db, pTmp->pIdList);
  73337. sqlite3DbFree(db, pTmp);
  73338. }
  73339. }
  73340. /*
  73341. ** Given table pTab, return a list of all the triggers attached to
  73342. ** the table. The list is connected by Trigger.pNext pointers.
  73343. */
  73344. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  73345. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  73346. Trigger *pList = 0; /* List of triggers to return */
  73347. if( pTmpSchema!=pTab->pSchema ){
  73348. HashElem *p;
  73349. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  73350. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  73351. if( pTrig->pTabSchema==pTab->pSchema
  73352. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  73353. ){
  73354. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  73355. pList = pTrig;
  73356. }
  73357. }
  73358. }
  73359. return (pList ? pList : pTab->pTrigger);
  73360. }
  73361. /*
  73362. ** This is called by the parser when it sees a CREATE TRIGGER statement
  73363. ** up to the point of the BEGIN before the trigger actions. A Trigger
  73364. ** structure is generated based on the information available and stored
  73365. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  73366. ** sqlite3FinishTrigger() function is called to complete the trigger
  73367. ** construction process.
  73368. */
  73369. SQLITE_PRIVATE void sqlite3BeginTrigger(
  73370. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  73371. Token *pName1, /* The name of the trigger */
  73372. Token *pName2, /* The name of the trigger */
  73373. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  73374. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  73375. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  73376. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  73377. Expr *pWhen, /* WHEN clause */
  73378. int isTemp, /* True if the TEMPORARY keyword is present */
  73379. int noErr /* Suppress errors if the trigger already exists */
  73380. ){
  73381. Trigger *pTrigger = 0;
  73382. Table *pTab;
  73383. char *zName = 0; /* Name of the trigger */
  73384. sqlite3 *db = pParse->db;
  73385. int iDb; /* The database to store the trigger in */
  73386. Token *pName; /* The unqualified db name */
  73387. DbFixer sFix;
  73388. int iTabDb;
  73389. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  73390. assert( pName2!=0 );
  73391. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  73392. assert( op>0 && op<0xff );
  73393. if( isTemp ){
  73394. /* If TEMP was specified, then the trigger name may not be qualified. */
  73395. if( pName2->n>0 ){
  73396. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  73397. goto trigger_cleanup;
  73398. }
  73399. iDb = 1;
  73400. pName = pName1;
  73401. }else{
  73402. /* Figure out the db that the the trigger will be created in */
  73403. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  73404. if( iDb<0 ){
  73405. goto trigger_cleanup;
  73406. }
  73407. }
  73408. /* If the trigger name was unqualified, and the table is a temp table,
  73409. ** then set iDb to 1 to create the trigger in the temporary database.
  73410. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  73411. ** exist, the error is caught by the block below.
  73412. */
  73413. if( !pTableName || db->mallocFailed ){
  73414. goto trigger_cleanup;
  73415. }
  73416. pTab = sqlite3SrcListLookup(pParse, pTableName);
  73417. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  73418. iDb = 1;
  73419. }
  73420. /* Ensure the table name matches database name and that the table exists */
  73421. if( db->mallocFailed ) goto trigger_cleanup;
  73422. assert( pTableName->nSrc==1 );
  73423. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
  73424. sqlite3FixSrcList(&sFix, pTableName) ){
  73425. goto trigger_cleanup;
  73426. }
  73427. pTab = sqlite3SrcListLookup(pParse, pTableName);
  73428. if( !pTab ){
  73429. /* The table does not exist. */
  73430. goto trigger_cleanup;
  73431. }
  73432. if( IsVirtual(pTab) ){
  73433. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  73434. goto trigger_cleanup;
  73435. }
  73436. /* Check that the trigger name is not reserved and that no trigger of the
  73437. ** specified name exists */
  73438. zName = sqlite3NameFromToken(db, pName);
  73439. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  73440. goto trigger_cleanup;
  73441. }
  73442. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  73443. zName, sqlite3Strlen30(zName)) ){
  73444. if( !noErr ){
  73445. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  73446. }
  73447. goto trigger_cleanup;
  73448. }
  73449. /* Do not create a trigger on a system table */
  73450. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  73451. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  73452. pParse->nErr++;
  73453. goto trigger_cleanup;
  73454. }
  73455. /* INSTEAD of triggers are only for views and views only support INSTEAD
  73456. ** of triggers.
  73457. */
  73458. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  73459. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  73460. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  73461. goto trigger_cleanup;
  73462. }
  73463. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  73464. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  73465. " trigger on table: %S", pTableName, 0);
  73466. goto trigger_cleanup;
  73467. }
  73468. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73469. #ifndef SQLITE_OMIT_AUTHORIZATION
  73470. {
  73471. int code = SQLITE_CREATE_TRIGGER;
  73472. const char *zDb = db->aDb[iTabDb].zName;
  73473. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  73474. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  73475. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  73476. goto trigger_cleanup;
  73477. }
  73478. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  73479. goto trigger_cleanup;
  73480. }
  73481. }
  73482. #endif
  73483. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  73484. ** cannot appear on views. So we might as well translate every
  73485. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  73486. ** elsewhere.
  73487. */
  73488. if (tr_tm == TK_INSTEAD){
  73489. tr_tm = TK_BEFORE;
  73490. }
  73491. /* Build the Trigger object */
  73492. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  73493. if( pTrigger==0 ) goto trigger_cleanup;
  73494. pTrigger->name = zName;
  73495. zName = 0;
  73496. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  73497. pTrigger->pSchema = db->aDb[iDb].pSchema;
  73498. pTrigger->pTabSchema = pTab->pSchema;
  73499. pTrigger->op = (u8)op;
  73500. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  73501. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  73502. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  73503. sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
  73504. assert( pParse->pNewTrigger==0 );
  73505. pParse->pNewTrigger = pTrigger;
  73506. trigger_cleanup:
  73507. sqlite3DbFree(db, zName);
  73508. sqlite3SrcListDelete(db, pTableName);
  73509. sqlite3IdListDelete(db, pColumns);
  73510. sqlite3ExprDelete(db, pWhen);
  73511. if( !pParse->pNewTrigger ){
  73512. sqlite3DeleteTrigger(db, pTrigger);
  73513. }else{
  73514. assert( pParse->pNewTrigger==pTrigger );
  73515. }
  73516. }
  73517. /*
  73518. ** This routine is called after all of the trigger actions have been parsed
  73519. ** in order to complete the process of building the trigger.
  73520. */
  73521. SQLITE_PRIVATE void sqlite3FinishTrigger(
  73522. Parse *pParse, /* Parser context */
  73523. TriggerStep *pStepList, /* The triggered program */
  73524. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  73525. ){
  73526. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  73527. char *zName; /* Name of trigger */
  73528. sqlite3 *db = pParse->db; /* The database */
  73529. DbFixer sFix;
  73530. int iDb; /* Database containing the trigger */
  73531. pTrig = pParse->pNewTrigger;
  73532. pParse->pNewTrigger = 0;
  73533. if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
  73534. zName = pTrig->name;
  73535. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  73536. pTrig->step_list = pStepList;
  73537. while( pStepList ){
  73538. pStepList->pTrig = pTrig;
  73539. pStepList = pStepList->pNext;
  73540. }
  73541. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken)
  73542. && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
  73543. goto triggerfinish_cleanup;
  73544. }
  73545. /* if we are not initializing, and this trigger is not on a TEMP table,
  73546. ** build the sqlite_master entry
  73547. */
  73548. if( !db->init.busy ){
  73549. Vdbe *v;
  73550. char *z;
  73551. /* Make an entry in the sqlite_master table */
  73552. v = sqlite3GetVdbe(pParse);
  73553. if( v==0 ) goto triggerfinish_cleanup;
  73554. sqlite3BeginWriteOperation(pParse, 0, iDb);
  73555. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  73556. sqlite3NestedParse(pParse,
  73557. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  73558. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  73559. pTrig->table, z);
  73560. sqlite3DbFree(db, z);
  73561. sqlite3ChangeCookie(pParse, iDb);
  73562. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
  73563. db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
  73564. );
  73565. }
  73566. if( db->init.busy ){
  73567. Trigger *pLink = pTrig;
  73568. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  73569. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  73570. if( pTrig ){
  73571. db->mallocFailed = 1;
  73572. }else if( pLink->pSchema==pLink->pTabSchema ){
  73573. Table *pTab;
  73574. int n = sqlite3Strlen30(pLink->table) + 1;
  73575. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  73576. assert( pTab!=0 );
  73577. pLink->pNext = pTab->pTrigger;
  73578. pTab->pTrigger = pLink;
  73579. }
  73580. }
  73581. triggerfinish_cleanup:
  73582. sqlite3DeleteTrigger(db, pTrig);
  73583. assert( !pParse->pNewTrigger );
  73584. sqlite3DeleteTriggerStep(db, pStepList);
  73585. }
  73586. /*
  73587. ** Make a copy of all components of the given trigger step. This has
  73588. ** the effect of copying all Expr.token.z values into memory obtained
  73589. ** from sqlite3_malloc(). As initially created, the Expr.token.z values
  73590. ** all point to the input string that was fed to the parser. But that
  73591. ** string is ephemeral - it will go away as soon as the sqlite3_exec()
  73592. ** call that started the parser exits. This routine makes a persistent
  73593. ** copy of all the Expr.token.z strings so that the TriggerStep structure
  73594. ** will be valid even after the sqlite3_exec() call returns.
  73595. */
  73596. static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
  73597. if( p->target.z ){
  73598. p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
  73599. p->target.dyn = 1;
  73600. }
  73601. if( p->pSelect ){
  73602. Select *pNew = sqlite3SelectDup(db, p->pSelect, 1);
  73603. sqlite3SelectDelete(db, p->pSelect);
  73604. p->pSelect = pNew;
  73605. }
  73606. if( p->pWhere ){
  73607. Expr *pNew = sqlite3ExprDup(db, p->pWhere, EXPRDUP_REDUCE);
  73608. sqlite3ExprDelete(db, p->pWhere);
  73609. p->pWhere = pNew;
  73610. }
  73611. if( p->pExprList ){
  73612. ExprList *pNew = sqlite3ExprListDup(db, p->pExprList, 1);
  73613. sqlite3ExprListDelete(db, p->pExprList);
  73614. p->pExprList = pNew;
  73615. }
  73616. if( p->pIdList ){
  73617. IdList *pNew = sqlite3IdListDup(db, p->pIdList);
  73618. sqlite3IdListDelete(db, p->pIdList);
  73619. p->pIdList = pNew;
  73620. }
  73621. }
  73622. /*
  73623. ** Turn a SELECT statement (that the pSelect parameter points to) into
  73624. ** a trigger step. Return a pointer to a TriggerStep structure.
  73625. **
  73626. ** The parser calls this routine when it finds a SELECT statement in
  73627. ** body of a TRIGGER.
  73628. */
  73629. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  73630. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  73631. if( pTriggerStep==0 ) {
  73632. sqlite3SelectDelete(db, pSelect);
  73633. return 0;
  73634. }
  73635. pTriggerStep->op = TK_SELECT;
  73636. pTriggerStep->pSelect = pSelect;
  73637. pTriggerStep->orconf = OE_Default;
  73638. sqlitePersistTriggerStep(db, pTriggerStep);
  73639. return pTriggerStep;
  73640. }
  73641. /*
  73642. ** Build a trigger step out of an INSERT statement. Return a pointer
  73643. ** to the new trigger step.
  73644. **
  73645. ** The parser calls this routine when it sees an INSERT inside the
  73646. ** body of a trigger.
  73647. */
  73648. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  73649. sqlite3 *db, /* The database connection */
  73650. Token *pTableName, /* Name of the table into which we insert */
  73651. IdList *pColumn, /* List of columns in pTableName to insert into */
  73652. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  73653. Select *pSelect, /* A SELECT statement that supplies values */
  73654. int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  73655. ){
  73656. TriggerStep *pTriggerStep;
  73657. assert(pEList == 0 || pSelect == 0);
  73658. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  73659. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  73660. if( pTriggerStep ){
  73661. pTriggerStep->op = TK_INSERT;
  73662. pTriggerStep->pSelect = pSelect;
  73663. pTriggerStep->target = *pTableName;
  73664. pTriggerStep->pIdList = pColumn;
  73665. pTriggerStep->pExprList = pEList;
  73666. pTriggerStep->orconf = orconf;
  73667. sqlitePersistTriggerStep(db, pTriggerStep);
  73668. }else{
  73669. sqlite3IdListDelete(db, pColumn);
  73670. sqlite3ExprListDelete(db, pEList);
  73671. sqlite3SelectDelete(db, pSelect);
  73672. }
  73673. return pTriggerStep;
  73674. }
  73675. /*
  73676. ** Construct a trigger step that implements an UPDATE statement and return
  73677. ** a pointer to that trigger step. The parser calls this routine when it
  73678. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  73679. */
  73680. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  73681. sqlite3 *db, /* The database connection */
  73682. Token *pTableName, /* Name of the table to be updated */
  73683. ExprList *pEList, /* The SET clause: list of column and new values */
  73684. Expr *pWhere, /* The WHERE clause */
  73685. int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  73686. ){
  73687. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  73688. if( pTriggerStep==0 ){
  73689. sqlite3ExprListDelete(db, pEList);
  73690. sqlite3ExprDelete(db, pWhere);
  73691. return 0;
  73692. }
  73693. pTriggerStep->op = TK_UPDATE;
  73694. pTriggerStep->target = *pTableName;
  73695. pTriggerStep->pExprList = pEList;
  73696. pTriggerStep->pWhere = pWhere;
  73697. pTriggerStep->orconf = orconf;
  73698. sqlitePersistTriggerStep(db, pTriggerStep);
  73699. return pTriggerStep;
  73700. }
  73701. /*
  73702. ** Construct a trigger step that implements a DELETE statement and return
  73703. ** a pointer to that trigger step. The parser calls this routine when it
  73704. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  73705. */
  73706. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  73707. sqlite3 *db, /* Database connection */
  73708. Token *pTableName, /* The table from which rows are deleted */
  73709. Expr *pWhere /* The WHERE clause */
  73710. ){
  73711. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  73712. if( pTriggerStep==0 ){
  73713. sqlite3ExprDelete(db, pWhere);
  73714. return 0;
  73715. }
  73716. pTriggerStep->op = TK_DELETE;
  73717. pTriggerStep->target = *pTableName;
  73718. pTriggerStep->pWhere = pWhere;
  73719. pTriggerStep->orconf = OE_Default;
  73720. sqlitePersistTriggerStep(db, pTriggerStep);
  73721. return pTriggerStep;
  73722. }
  73723. /*
  73724. ** Recursively delete a Trigger structure
  73725. */
  73726. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  73727. if( pTrigger==0 ) return;
  73728. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  73729. sqlite3DbFree(db, pTrigger->name);
  73730. sqlite3DbFree(db, pTrigger->table);
  73731. sqlite3ExprDelete(db, pTrigger->pWhen);
  73732. sqlite3IdListDelete(db, pTrigger->pColumns);
  73733. if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
  73734. sqlite3DbFree(db, pTrigger);
  73735. }
  73736. /*
  73737. ** This function is called to drop a trigger from the database schema.
  73738. **
  73739. ** This may be called directly from the parser and therefore identifies
  73740. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  73741. ** same job as this routine except it takes a pointer to the trigger
  73742. ** instead of the trigger name.
  73743. **/
  73744. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  73745. Trigger *pTrigger = 0;
  73746. int i;
  73747. const char *zDb;
  73748. const char *zName;
  73749. int nName;
  73750. sqlite3 *db = pParse->db;
  73751. if( db->mallocFailed ) goto drop_trigger_cleanup;
  73752. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  73753. goto drop_trigger_cleanup;
  73754. }
  73755. assert( pName->nSrc==1 );
  73756. zDb = pName->a[0].zDatabase;
  73757. zName = pName->a[0].zName;
  73758. nName = sqlite3Strlen30(zName);
  73759. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  73760. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  73761. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  73762. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  73763. if( pTrigger ) break;
  73764. }
  73765. if( !pTrigger ){
  73766. if( !noErr ){
  73767. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  73768. }
  73769. goto drop_trigger_cleanup;
  73770. }
  73771. sqlite3DropTriggerPtr(pParse, pTrigger);
  73772. drop_trigger_cleanup:
  73773. sqlite3SrcListDelete(db, pName);
  73774. }
  73775. /*
  73776. ** Return a pointer to the Table structure for the table that a trigger
  73777. ** is set on.
  73778. */
  73779. static Table *tableOfTrigger(Trigger *pTrigger){
  73780. int n = sqlite3Strlen30(pTrigger->table) + 1;
  73781. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  73782. }
  73783. /*
  73784. ** Drop a trigger given a pointer to that trigger.
  73785. */
  73786. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  73787. Table *pTable;
  73788. Vdbe *v;
  73789. sqlite3 *db = pParse->db;
  73790. int iDb;
  73791. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  73792. assert( iDb>=0 && iDb<db->nDb );
  73793. pTable = tableOfTrigger(pTrigger);
  73794. assert( pTable );
  73795. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  73796. #ifndef SQLITE_OMIT_AUTHORIZATION
  73797. {
  73798. int code = SQLITE_DROP_TRIGGER;
  73799. const char *zDb = db->aDb[iDb].zName;
  73800. const char *zTab = SCHEMA_TABLE(iDb);
  73801. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  73802. if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
  73803. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  73804. return;
  73805. }
  73806. }
  73807. #endif
  73808. /* Generate code to destroy the database record of the trigger.
  73809. */
  73810. assert( pTable!=0 );
  73811. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  73812. int base;
  73813. static const VdbeOpList dropTrigger[] = {
  73814. { OP_Rewind, 0, ADDR(9), 0},
  73815. { OP_String8, 0, 1, 0}, /* 1 */
  73816. { OP_Column, 0, 1, 2},
  73817. { OP_Ne, 2, ADDR(8), 1},
  73818. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  73819. { OP_Column, 0, 0, 2},
  73820. { OP_Ne, 2, ADDR(8), 1},
  73821. { OP_Delete, 0, 0, 0},
  73822. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  73823. };
  73824. sqlite3BeginWriteOperation(pParse, 0, iDb);
  73825. sqlite3OpenMasterTable(pParse, iDb);
  73826. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  73827. sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
  73828. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  73829. sqlite3ChangeCookie(pParse, iDb);
  73830. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  73831. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
  73832. if( pParse->nMem<3 ){
  73833. pParse->nMem = 3;
  73834. }
  73835. }
  73836. }
  73837. /*
  73838. ** Remove a trigger from the hash tables of the sqlite* pointer.
  73839. */
  73840. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  73841. Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
  73842. Trigger *pTrigger;
  73843. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  73844. if( pTrigger ){
  73845. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  73846. Table *pTab = tableOfTrigger(pTrigger);
  73847. Trigger **pp;
  73848. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  73849. *pp = (*pp)->pNext;
  73850. }
  73851. sqlite3DeleteTrigger(db, pTrigger);
  73852. db->flags |= SQLITE_InternChanges;
  73853. }
  73854. }
  73855. /*
  73856. ** pEList is the SET clause of an UPDATE statement. Each entry
  73857. ** in pEList is of the format <id>=<expr>. If any of the entries
  73858. ** in pEList have an <id> which matches an identifier in pIdList,
  73859. ** then return TRUE. If pIdList==NULL, then it is considered a
  73860. ** wildcard that matches anything. Likewise if pEList==NULL then
  73861. ** it matches anything so always return true. Return false only
  73862. ** if there is no match.
  73863. */
  73864. static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
  73865. int e;
  73866. if( !pIdList || !pEList ) return 1;
  73867. for(e=0; e<pEList->nExpr; e++){
  73868. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  73869. }
  73870. return 0;
  73871. }
  73872. /*
  73873. ** Return a list of all triggers on table pTab if there exists at least
  73874. ** one trigger that must be fired when an operation of type 'op' is
  73875. ** performed on the table, and, if that operation is an UPDATE, if at
  73876. ** least one of the columns in pChanges is being modified.
  73877. */
  73878. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  73879. Parse *pParse, /* Parse context */
  73880. Table *pTab, /* The table the contains the triggers */
  73881. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  73882. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  73883. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  73884. ){
  73885. int mask = 0;
  73886. Trigger *pList = sqlite3TriggerList(pParse, pTab);
  73887. Trigger *p;
  73888. assert( pList==0 || IsVirtual(pTab)==0 );
  73889. for(p=pList; p; p=p->pNext){
  73890. if( p->op==op && checkColumnOverLap(p->pColumns, pChanges) ){
  73891. mask |= p->tr_tm;
  73892. }
  73893. }
  73894. if( pMask ){
  73895. *pMask = mask;
  73896. }
  73897. return (mask ? pList : 0);
  73898. }
  73899. /*
  73900. ** Convert the pStep->target token into a SrcList and return a pointer
  73901. ** to that SrcList.
  73902. **
  73903. ** This routine adds a specific database name, if needed, to the target when
  73904. ** forming the SrcList. This prevents a trigger in one database from
  73905. ** referring to a target in another database. An exception is when the
  73906. ** trigger is in TEMP in which case it can refer to any other database it
  73907. ** wants.
  73908. */
  73909. static SrcList *targetSrcList(
  73910. Parse *pParse, /* The parsing context */
  73911. TriggerStep *pStep /* The trigger containing the target token */
  73912. ){
  73913. Token sDb; /* Dummy database name token */
  73914. int iDb; /* Index of the database to use */
  73915. SrcList *pSrc; /* SrcList to be returned */
  73916. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  73917. if( iDb==0 || iDb>=2 ){
  73918. assert( iDb<pParse->db->nDb );
  73919. sDb.z = (u8*)pParse->db->aDb[iDb].zName;
  73920. sDb.n = sqlite3Strlen30((char*)sDb.z);
  73921. pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
  73922. } else {
  73923. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  73924. }
  73925. return pSrc;
  73926. }
  73927. /*
  73928. ** Generate VDBE code for zero or more statements inside the body of a
  73929. ** trigger.
  73930. */
  73931. static int codeTriggerProgram(
  73932. Parse *pParse, /* The parser context */
  73933. TriggerStep *pStepList, /* List of statements inside the trigger body */
  73934. int orconfin /* Conflict algorithm. (OE_Abort, etc) */
  73935. ){
  73936. TriggerStep * pTriggerStep = pStepList;
  73937. int orconf;
  73938. Vdbe *v = pParse->pVdbe;
  73939. sqlite3 *db = pParse->db;
  73940. assert( pTriggerStep!=0 );
  73941. assert( v!=0 );
  73942. sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
  73943. VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
  73944. while( pTriggerStep ){
  73945. sqlite3ExprClearColumnCache(pParse, -1);
  73946. orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
  73947. pParse->trigStack->orconf = orconf;
  73948. switch( pTriggerStep->op ){
  73949. case TK_SELECT: {
  73950. Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0);
  73951. if( ss ){
  73952. SelectDest dest;
  73953. sqlite3SelectDestInit(&dest, SRT_Discard, 0);
  73954. sqlite3Select(pParse, ss, &dest);
  73955. sqlite3SelectDelete(db, ss);
  73956. }
  73957. break;
  73958. }
  73959. case TK_UPDATE: {
  73960. SrcList *pSrc;
  73961. pSrc = targetSrcList(pParse, pTriggerStep);
  73962. sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
  73963. sqlite3Update(pParse, pSrc,
  73964. sqlite3ExprListDup(db, pTriggerStep->pExprList, 0),
  73965. sqlite3ExprDup(db, pTriggerStep->pWhere, 0), orconf);
  73966. sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
  73967. break;
  73968. }
  73969. case TK_INSERT: {
  73970. SrcList *pSrc;
  73971. pSrc = targetSrcList(pParse, pTriggerStep);
  73972. sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
  73973. sqlite3Insert(pParse, pSrc,
  73974. sqlite3ExprListDup(db, pTriggerStep->pExprList, 0),
  73975. sqlite3SelectDup(db, pTriggerStep->pSelect, 0),
  73976. sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
  73977. sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
  73978. break;
  73979. }
  73980. case TK_DELETE: {
  73981. SrcList *pSrc;
  73982. sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
  73983. pSrc = targetSrcList(pParse, pTriggerStep);
  73984. sqlite3DeleteFrom(pParse, pSrc,
  73985. sqlite3ExprDup(db, pTriggerStep->pWhere, 0));
  73986. sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
  73987. break;
  73988. }
  73989. default:
  73990. assert(0);
  73991. }
  73992. pTriggerStep = pTriggerStep->pNext;
  73993. }
  73994. sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
  73995. VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
  73996. return 0;
  73997. }
  73998. /*
  73999. ** This is called to code FOR EACH ROW triggers.
  74000. **
  74001. ** When the code that this function generates is executed, the following
  74002. ** must be true:
  74003. **
  74004. ** 1. No cursors may be open in the main database. (But newIdx and oldIdx
  74005. ** can be indices of cursors in temporary tables. See below.)
  74006. **
  74007. ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
  74008. ** a temporary vdbe cursor (index newIdx) must be open and pointing at
  74009. ** a row containing values to be substituted for new.* expressions in the
  74010. ** trigger program(s).
  74011. **
  74012. ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
  74013. ** a temporary vdbe cursor (index oldIdx) must be open and pointing at
  74014. ** a row containing values to be substituted for old.* expressions in the
  74015. ** trigger program(s).
  74016. **
  74017. ** If they are not NULL, the piOldColMask and piNewColMask output variables
  74018. ** are set to values that describe the columns used by the trigger program
  74019. ** in the OLD.* and NEW.* tables respectively. If column N of the
  74020. ** pseudo-table is read at least once, the corresponding bit of the output
  74021. ** mask is set. If a column with an index greater than 32 is read, the
  74022. ** output mask is set to the special value 0xffffffff.
  74023. **
  74024. */
  74025. SQLITE_PRIVATE int sqlite3CodeRowTrigger(
  74026. Parse *pParse, /* Parse context */
  74027. Trigger *pTrigger, /* List of triggers on table pTab */
  74028. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  74029. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  74030. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  74031. Table *pTab, /* The table to code triggers from */
  74032. int newIdx, /* The indice of the "new" row to access */
  74033. int oldIdx, /* The indice of the "old" row to access */
  74034. int orconf, /* ON CONFLICT policy */
  74035. int ignoreJump, /* Instruction to jump to for RAISE(IGNORE) */
  74036. u32 *piOldColMask, /* OUT: Mask of columns used from the OLD.* table */
  74037. u32 *piNewColMask /* OUT: Mask of columns used from the NEW.* table */
  74038. ){
  74039. Trigger *p;
  74040. sqlite3 *db = pParse->db;
  74041. TriggerStack trigStackEntry;
  74042. trigStackEntry.oldColMask = 0;
  74043. trigStackEntry.newColMask = 0;
  74044. assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
  74045. assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
  74046. assert(newIdx != -1 || oldIdx != -1);
  74047. for(p=pTrigger; p; p=p->pNext){
  74048. int fire_this = 0;
  74049. /* Determine whether we should code this trigger */
  74050. if(
  74051. p->op==op &&
  74052. p->tr_tm==tr_tm &&
  74053. (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
  74054. (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
  74055. ){
  74056. TriggerStack *pS; /* Pointer to trigger-stack entry */
  74057. for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
  74058. if( !pS ){
  74059. fire_this = 1;
  74060. }
  74061. #if 0 /* Give no warning for recursive triggers. Just do not do them */
  74062. else{
  74063. sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
  74064. p->name);
  74065. return SQLITE_ERROR;
  74066. }
  74067. #endif
  74068. }
  74069. if( fire_this ){
  74070. int endTrigger;
  74071. Expr * whenExpr;
  74072. AuthContext sContext;
  74073. NameContext sNC;
  74074. #ifndef SQLITE_OMIT_TRACE
  74075. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
  74076. sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
  74077. P4_DYNAMIC);
  74078. #endif
  74079. memset(&sNC, 0, sizeof(sNC));
  74080. sNC.pParse = pParse;
  74081. /* Push an entry on to the trigger stack */
  74082. trigStackEntry.pTrigger = p;
  74083. trigStackEntry.newIdx = newIdx;
  74084. trigStackEntry.oldIdx = oldIdx;
  74085. trigStackEntry.pTab = pTab;
  74086. trigStackEntry.pNext = pParse->trigStack;
  74087. trigStackEntry.ignoreJump = ignoreJump;
  74088. pParse->trigStack = &trigStackEntry;
  74089. sqlite3AuthContextPush(pParse, &sContext, p->name);
  74090. /* code the WHEN clause */
  74091. endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
  74092. whenExpr = sqlite3ExprDup(db, p->pWhen, 0);
  74093. if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
  74094. pParse->trigStack = trigStackEntry.pNext;
  74095. sqlite3ExprDelete(db, whenExpr);
  74096. return 1;
  74097. }
  74098. sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
  74099. sqlite3ExprDelete(db, whenExpr);
  74100. codeTriggerProgram(pParse, p->step_list, orconf);
  74101. /* Pop the entry off the trigger stack */
  74102. pParse->trigStack = trigStackEntry.pNext;
  74103. sqlite3AuthContextPop(&sContext);
  74104. sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
  74105. }
  74106. }
  74107. if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
  74108. if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
  74109. return 0;
  74110. }
  74111. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  74112. /************** End of trigger.c *********************************************/
  74113. /************** Begin file update.c ******************************************/
  74114. /*
  74115. ** 2001 September 15
  74116. **
  74117. ** The author disclaims copyright to this source code. In place of
  74118. ** a legal notice, here is a blessing:
  74119. **
  74120. ** May you do good and not evil.
  74121. ** May you find forgiveness for yourself and forgive others.
  74122. ** May you share freely, never taking more than you give.
  74123. **
  74124. *************************************************************************
  74125. ** This file contains C code routines that are called by the parser
  74126. ** to handle UPDATE statements.
  74127. **
  74128. ** $Id: update.c,v 1.196 2009/02/28 10:47:42 danielk1977 Exp $
  74129. */
  74130. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74131. /* Forward declaration */
  74132. static void updateVirtualTable(
  74133. Parse *pParse, /* The parsing context */
  74134. SrcList *pSrc, /* The virtual table to be modified */
  74135. Table *pTab, /* The virtual table */
  74136. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  74137. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  74138. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  74139. Expr *pWhere /* WHERE clause of the UPDATE statement */
  74140. );
  74141. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74142. /*
  74143. ** The most recently coded instruction was an OP_Column to retrieve the
  74144. ** i-th column of table pTab. This routine sets the P4 parameter of the
  74145. ** OP_Column to the default value, if any.
  74146. **
  74147. ** The default value of a column is specified by a DEFAULT clause in the
  74148. ** column definition. This was either supplied by the user when the table
  74149. ** was created, or added later to the table definition by an ALTER TABLE
  74150. ** command. If the latter, then the row-records in the table btree on disk
  74151. ** may not contain a value for the column and the default value, taken
  74152. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  74153. ** If the former, then all row-records are guaranteed to include a value
  74154. ** for the column and the P4 value is not required.
  74155. **
  74156. ** Column definitions created by an ALTER TABLE command may only have
  74157. ** literal default values specified: a number, null or a string. (If a more
  74158. ** complicated default expression value was provided, it is evaluated
  74159. ** when the ALTER TABLE is executed and one of the literal values written
  74160. ** into the sqlite_master table.)
  74161. **
  74162. ** Therefore, the P4 parameter is only required if the default value for
  74163. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  74164. ** function is capable of transforming these types of expressions into
  74165. ** sqlite3_value objects.
  74166. */
  74167. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
  74168. if( pTab && !pTab->pSelect ){
  74169. sqlite3_value *pValue;
  74170. u8 enc = ENC(sqlite3VdbeDb(v));
  74171. Column *pCol = &pTab->aCol[i];
  74172. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  74173. assert( i<pTab->nCol );
  74174. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  74175. pCol->affinity, &pValue);
  74176. if( pValue ){
  74177. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  74178. }
  74179. }
  74180. }
  74181. /*
  74182. ** Process an UPDATE statement.
  74183. **
  74184. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  74185. ** \_______/ \________/ \______/ \________________/
  74186. * onError pTabList pChanges pWhere
  74187. */
  74188. SQLITE_PRIVATE void sqlite3Update(
  74189. Parse *pParse, /* The parser context */
  74190. SrcList *pTabList, /* The table in which we should change things */
  74191. ExprList *pChanges, /* Things to be changed */
  74192. Expr *pWhere, /* The WHERE clause. May be null */
  74193. int onError /* How to handle constraint errors */
  74194. ){
  74195. int i, j; /* Loop counters */
  74196. Table *pTab; /* The table to be updated */
  74197. int addr = 0; /* VDBE instruction address of the start of the loop */
  74198. WhereInfo *pWInfo; /* Information about the WHERE clause */
  74199. Vdbe *v; /* The virtual database engine */
  74200. Index *pIdx; /* For looping over indices */
  74201. int nIdx; /* Number of indices that need updating */
  74202. int iCur; /* VDBE Cursor number of pTab */
  74203. sqlite3 *db; /* The database structure */
  74204. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  74205. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  74206. ** an expression for the i-th column of the table.
  74207. ** aXRef[i]==-1 if the i-th column is not changed. */
  74208. int chngRowid; /* True if the record number is being changed */
  74209. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  74210. int openAll = 0; /* True if all indices need to be opened */
  74211. AuthContext sContext; /* The authorization context */
  74212. NameContext sNC; /* The name-context to resolve expressions in */
  74213. int iDb; /* Database containing the table being updated */
  74214. int j1; /* Addresses of jump instructions */
  74215. int okOnePass; /* True for one-pass algorithm without the FIFO */
  74216. #ifndef SQLITE_OMIT_TRIGGER
  74217. int isView; /* Trying to update a view */
  74218. Trigger *pTrigger; /* List of triggers on pTab, if required */
  74219. #endif
  74220. int iBeginAfterTrigger = 0; /* Address of after trigger program */
  74221. int iEndAfterTrigger = 0; /* Exit of after trigger program */
  74222. int iBeginBeforeTrigger = 0; /* Address of before trigger program */
  74223. int iEndBeforeTrigger = 0; /* Exit of before trigger program */
  74224. u32 old_col_mask = 0; /* Mask of OLD.* columns in use */
  74225. u32 new_col_mask = 0; /* Mask of NEW.* columns in use */
  74226. int newIdx = -1; /* index of trigger "new" temp table */
  74227. int oldIdx = -1; /* index of trigger "old" temp table */
  74228. /* Register Allocations */
  74229. int regRowCount = 0; /* A count of rows changed */
  74230. int regOldRowid; /* The old rowid */
  74231. int regNewRowid; /* The new rowid */
  74232. int regData; /* New data for the row */
  74233. int regRowSet = 0; /* Rowset of rows to be updated */
  74234. sContext.pParse = 0;
  74235. db = pParse->db;
  74236. if( pParse->nErr || db->mallocFailed ){
  74237. goto update_cleanup;
  74238. }
  74239. assert( pTabList->nSrc==1 );
  74240. /* Locate the table which we want to update.
  74241. */
  74242. pTab = sqlite3SrcListLookup(pParse, pTabList);
  74243. if( pTab==0 ) goto update_cleanup;
  74244. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  74245. /* Figure out if we have any triggers and if the table being
  74246. ** updated is a view
  74247. */
  74248. #ifndef SQLITE_OMIT_TRIGGER
  74249. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, 0);
  74250. isView = pTab->pSelect!=0;
  74251. #else
  74252. # define pTrigger 0
  74253. # define isView 0
  74254. #endif
  74255. #ifdef SQLITE_OMIT_VIEW
  74256. # undef isView
  74257. # define isView 0
  74258. #endif
  74259. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  74260. goto update_cleanup;
  74261. }
  74262. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  74263. goto update_cleanup;
  74264. }
  74265. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  74266. if( aXRef==0 ) goto update_cleanup;
  74267. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  74268. /* If there are FOR EACH ROW triggers, allocate cursors for the
  74269. ** special OLD and NEW tables
  74270. */
  74271. if( pTrigger ){
  74272. newIdx = pParse->nTab++;
  74273. oldIdx = pParse->nTab++;
  74274. }
  74275. /* Allocate a cursors for the main database table and for all indices.
  74276. ** The index cursors might not be used, but if they are used they
  74277. ** need to occur right after the database cursor. So go ahead and
  74278. ** allocate enough space, just in case.
  74279. */
  74280. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  74281. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  74282. pParse->nTab++;
  74283. }
  74284. /* Initialize the name-context */
  74285. memset(&sNC, 0, sizeof(sNC));
  74286. sNC.pParse = pParse;
  74287. sNC.pSrcList = pTabList;
  74288. /* Resolve the column names in all the expressions of the
  74289. ** of the UPDATE statement. Also find the column index
  74290. ** for each column to be updated in the pChanges array. For each
  74291. ** column to be updated, make sure we have authorization to change
  74292. ** that column.
  74293. */
  74294. chngRowid = 0;
  74295. for(i=0; i<pChanges->nExpr; i++){
  74296. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  74297. goto update_cleanup;
  74298. }
  74299. for(j=0; j<pTab->nCol; j++){
  74300. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  74301. if( j==pTab->iPKey ){
  74302. chngRowid = 1;
  74303. pRowidExpr = pChanges->a[i].pExpr;
  74304. }
  74305. aXRef[j] = i;
  74306. break;
  74307. }
  74308. }
  74309. if( j>=pTab->nCol ){
  74310. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  74311. chngRowid = 1;
  74312. pRowidExpr = pChanges->a[i].pExpr;
  74313. }else{
  74314. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  74315. goto update_cleanup;
  74316. }
  74317. }
  74318. #ifndef SQLITE_OMIT_AUTHORIZATION
  74319. {
  74320. int rc;
  74321. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  74322. pTab->aCol[j].zName, db->aDb[iDb].zName);
  74323. if( rc==SQLITE_DENY ){
  74324. goto update_cleanup;
  74325. }else if( rc==SQLITE_IGNORE ){
  74326. aXRef[j] = -1;
  74327. }
  74328. }
  74329. #endif
  74330. }
  74331. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  74332. ** array for each index associated with table being updated. Fill in
  74333. ** the value with a register number for indices that are to be used
  74334. ** and with zero for unused indices.
  74335. */
  74336. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  74337. if( nIdx>0 ){
  74338. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  74339. if( aRegIdx==0 ) goto update_cleanup;
  74340. }
  74341. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  74342. int reg;
  74343. if( chngRowid ){
  74344. reg = ++pParse->nMem;
  74345. }else{
  74346. reg = 0;
  74347. for(i=0; i<pIdx->nColumn; i++){
  74348. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  74349. reg = ++pParse->nMem;
  74350. break;
  74351. }
  74352. }
  74353. }
  74354. aRegIdx[j] = reg;
  74355. }
  74356. /* Allocate a block of register used to store the change record
  74357. ** sent to sqlite3GenerateConstraintChecks(). There are either
  74358. ** one or two registers for holding the rowid. One rowid register
  74359. ** is used if chngRowid is false and two are used if chngRowid is
  74360. ** true. Following these are pTab->nCol register holding column
  74361. ** data.
  74362. */
  74363. regOldRowid = regNewRowid = pParse->nMem + 1;
  74364. pParse->nMem += pTab->nCol + 1;
  74365. if( chngRowid ){
  74366. regNewRowid++;
  74367. pParse->nMem++;
  74368. }
  74369. regData = regNewRowid+1;
  74370. /* Begin generating code.
  74371. */
  74372. v = sqlite3GetVdbe(pParse);
  74373. if( v==0 ) goto update_cleanup;
  74374. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  74375. sqlite3BeginWriteOperation(pParse, 1, iDb);
  74376. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74377. /* Virtual tables must be handled separately */
  74378. if( IsVirtual(pTab) ){
  74379. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  74380. pWhere);
  74381. pWhere = 0;
  74382. pTabList = 0;
  74383. goto update_cleanup;
  74384. }
  74385. #endif
  74386. /* Start the view context
  74387. */
  74388. if( isView ){
  74389. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  74390. }
  74391. /* Generate the code for triggers.
  74392. */
  74393. if( pTrigger ){
  74394. int iGoto;
  74395. /* Create pseudo-tables for NEW and OLD
  74396. */
  74397. sqlite3VdbeAddOp3(v, OP_OpenPseudo, oldIdx, 0, pTab->nCol);
  74398. sqlite3VdbeAddOp3(v, OP_OpenPseudo, newIdx, 0, pTab->nCol);
  74399. iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  74400. addr = sqlite3VdbeMakeLabel(v);
  74401. iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
  74402. if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  74403. TRIGGER_BEFORE, pTab, newIdx, oldIdx, onError, addr,
  74404. &old_col_mask, &new_col_mask) ){
  74405. goto update_cleanup;
  74406. }
  74407. iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  74408. iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
  74409. if( sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  74410. TRIGGER_AFTER, pTab, newIdx, oldIdx, onError, addr,
  74411. &old_col_mask, &new_col_mask) ){
  74412. goto update_cleanup;
  74413. }
  74414. iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  74415. sqlite3VdbeJumpHere(v, iGoto);
  74416. }
  74417. /* If we are trying to update a view, realize that view into
  74418. ** a ephemeral table.
  74419. */
  74420. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  74421. if( isView ){
  74422. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  74423. }
  74424. #endif
  74425. /* Resolve the column names in all the expressions in the
  74426. ** WHERE clause.
  74427. */
  74428. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  74429. goto update_cleanup;
  74430. }
  74431. /* Begin the database scan
  74432. */
  74433. sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
  74434. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
  74435. WHERE_ONEPASS_DESIRED, 0);
  74436. if( pWInfo==0 ) goto update_cleanup;
  74437. okOnePass = pWInfo->okOnePass;
  74438. /* Remember the rowid of every item to be updated.
  74439. */
  74440. sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
  74441. if( !okOnePass ){
  74442. regRowSet = ++pParse->nMem;
  74443. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  74444. }
  74445. /* End the database scan loop.
  74446. */
  74447. sqlite3WhereEnd(pWInfo);
  74448. /* Initialize the count of updated rows
  74449. */
  74450. if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
  74451. regRowCount = ++pParse->nMem;
  74452. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  74453. }
  74454. if( !isView && !IsVirtual(pTab) ){
  74455. /*
  74456. ** Open every index that needs updating. Note that if any
  74457. ** index could potentially invoke a REPLACE conflict resolution
  74458. ** action, then we need to open all indices because we might need
  74459. ** to be deleting some records.
  74460. */
  74461. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  74462. if( onError==OE_Replace ){
  74463. openAll = 1;
  74464. }else{
  74465. openAll = 0;
  74466. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  74467. if( pIdx->onError==OE_Replace ){
  74468. openAll = 1;
  74469. break;
  74470. }
  74471. }
  74472. }
  74473. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  74474. if( openAll || aRegIdx[i]>0 ){
  74475. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  74476. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  74477. (char*)pKey, P4_KEYINFO_HANDOFF);
  74478. assert( pParse->nTab>iCur+i+1 );
  74479. }
  74480. }
  74481. }
  74482. /* Jump back to this point if a trigger encounters an IGNORE constraint. */
  74483. if( pTrigger ){
  74484. sqlite3VdbeResolveLabel(v, addr);
  74485. }
  74486. /* Top of the update loop */
  74487. if( okOnePass ){
  74488. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  74489. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  74490. sqlite3VdbeJumpHere(v, a1);
  74491. }else{
  74492. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  74493. }
  74494. if( pTrigger ){
  74495. int regRowid;
  74496. int regRow;
  74497. int regCols;
  74498. /* Make cursor iCur point to the record that is being updated.
  74499. */
  74500. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  74501. /* Generate the OLD table
  74502. */
  74503. regRowid = sqlite3GetTempReg(pParse);
  74504. regRow = sqlite3GetTempReg(pParse);
  74505. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
  74506. if( !old_col_mask ){
  74507. sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
  74508. }else{
  74509. sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
  74510. }
  74511. sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
  74512. /* Generate the NEW table
  74513. */
  74514. if( chngRowid ){
  74515. sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
  74516. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  74517. }else{
  74518. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
  74519. }
  74520. regCols = sqlite3GetTempRange(pParse, pTab->nCol);
  74521. for(i=0; i<pTab->nCol; i++){
  74522. if( i==pTab->iPKey ){
  74523. sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
  74524. continue;
  74525. }
  74526. j = aXRef[i];
  74527. if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
  74528. if( j<0 ){
  74529. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
  74530. sqlite3ColumnDefault(v, pTab, i);
  74531. }else{
  74532. sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
  74533. }
  74534. }else{
  74535. sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
  74536. }
  74537. }
  74538. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
  74539. if( !isView ){
  74540. sqlite3TableAffinityStr(v, pTab);
  74541. sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
  74542. }
  74543. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
  74544. /* if( pParse->nErr ) goto update_cleanup; */
  74545. sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
  74546. sqlite3ReleaseTempReg(pParse, regRowid);
  74547. sqlite3ReleaseTempReg(pParse, regRow);
  74548. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
  74549. sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
  74550. }
  74551. if( !isView && !IsVirtual(pTab) ){
  74552. /* Loop over every record that needs updating. We have to load
  74553. ** the old data for each record to be updated because some columns
  74554. ** might not change and we will need to copy the old value.
  74555. ** Also, the old data is needed to delete the old index entries.
  74556. ** So make the cursor point at the old record.
  74557. */
  74558. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  74559. /* If the record number will change, push the record number as it
  74560. ** will be after the update. (The old record number is currently
  74561. ** on top of the stack.)
  74562. */
  74563. if( chngRowid ){
  74564. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  74565. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  74566. }
  74567. /* Compute new data for this record.
  74568. */
  74569. for(i=0; i<pTab->nCol; i++){
  74570. if( i==pTab->iPKey ){
  74571. sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
  74572. continue;
  74573. }
  74574. j = aXRef[i];
  74575. if( j<0 ){
  74576. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
  74577. sqlite3ColumnDefault(v, pTab, i);
  74578. }else{
  74579. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
  74580. }
  74581. }
  74582. /* Do constraint checks
  74583. */
  74584. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  74585. aRegIdx, chngRowid, 1,
  74586. onError, addr);
  74587. /* Delete the old indices for the current record.
  74588. */
  74589. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  74590. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  74591. /* If changing the record number, delete the old record.
  74592. */
  74593. if( chngRowid ){
  74594. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  74595. }
  74596. sqlite3VdbeJumpHere(v, j1);
  74597. /* Create the new index entries and the new record.
  74598. */
  74599. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid,
  74600. aRegIdx, 1, -1, 0);
  74601. }
  74602. /* Increment the row counter
  74603. */
  74604. if( db->flags & SQLITE_CountRows && !pParse->trigStack){
  74605. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  74606. }
  74607. /* If there are triggers, close all the cursors after each iteration
  74608. ** through the loop. The fire the after triggers.
  74609. */
  74610. if( pTrigger ){
  74611. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
  74612. sqlite3VdbeJumpHere(v, iEndAfterTrigger);
  74613. }
  74614. /* Repeat the above with the next record to be updated, until
  74615. ** all record selected by the WHERE clause have been updated.
  74616. */
  74617. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  74618. sqlite3VdbeJumpHere(v, addr);
  74619. /* Close all tables */
  74620. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  74621. if( openAll || aRegIdx[i]>0 ){
  74622. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  74623. }
  74624. }
  74625. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  74626. if( pTrigger ){
  74627. sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
  74628. sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
  74629. }
  74630. /*
  74631. ** Return the number of rows that were changed. If this routine is
  74632. ** generating code because of a call to sqlite3NestedParse(), do not
  74633. ** invoke the callback function.
  74634. */
  74635. if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
  74636. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  74637. sqlite3VdbeSetNumCols(v, 1);
  74638. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  74639. }
  74640. update_cleanup:
  74641. sqlite3AuthContextPop(&sContext);
  74642. sqlite3DbFree(db, aRegIdx);
  74643. sqlite3DbFree(db, aXRef);
  74644. sqlite3SrcListDelete(db, pTabList);
  74645. sqlite3ExprListDelete(db, pChanges);
  74646. sqlite3ExprDelete(db, pWhere);
  74647. return;
  74648. }
  74649. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74650. /*
  74651. ** Generate code for an UPDATE of a virtual table.
  74652. **
  74653. ** The strategy is that we create an ephemerial table that contains
  74654. ** for each row to be changed:
  74655. **
  74656. ** (A) The original rowid of that row.
  74657. ** (B) The revised rowid for the row. (note1)
  74658. ** (C) The content of every column in the row.
  74659. **
  74660. ** Then we loop over this ephemeral table and for each row in
  74661. ** the ephermeral table call VUpdate.
  74662. **
  74663. ** When finished, drop the ephemeral table.
  74664. **
  74665. ** (note1) Actually, if we know in advance that (A) is always the same
  74666. ** as (B) we only store (A), then duplicate (A) when pulling
  74667. ** it out of the ephemeral table before calling VUpdate.
  74668. */
  74669. static void updateVirtualTable(
  74670. Parse *pParse, /* The parsing context */
  74671. SrcList *pSrc, /* The virtual table to be modified */
  74672. Table *pTab, /* The virtual table */
  74673. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  74674. Expr *pRowid, /* Expression used to recompute the rowid */
  74675. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  74676. Expr *pWhere /* WHERE clause of the UPDATE statement */
  74677. ){
  74678. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  74679. ExprList *pEList = 0; /* The result set of the SELECT statement */
  74680. Select *pSelect = 0; /* The SELECT statement */
  74681. Expr *pExpr; /* Temporary expression */
  74682. int ephemTab; /* Table holding the result of the SELECT */
  74683. int i; /* Loop counter */
  74684. int addr; /* Address of top of loop */
  74685. int iReg; /* First register in set passed to OP_VUpdate */
  74686. sqlite3 *db = pParse->db; /* Database connection */
  74687. const char *pVtab = (const char*)pTab->pVtab;
  74688. SelectDest dest;
  74689. /* Construct the SELECT statement that will find the new values for
  74690. ** all updated rows.
  74691. */
  74692. pEList = sqlite3ExprListAppend(pParse, 0,
  74693. sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
  74694. if( pRowid ){
  74695. pEList = sqlite3ExprListAppend(pParse, pEList,
  74696. sqlite3ExprDup(db, pRowid, 0), 0);
  74697. }
  74698. assert( pTab->iPKey<0 );
  74699. for(i=0; i<pTab->nCol; i++){
  74700. if( aXRef[i]>=0 ){
  74701. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  74702. }else{
  74703. pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
  74704. }
  74705. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
  74706. }
  74707. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  74708. /* Create the ephemeral table into which the update results will
  74709. ** be stored.
  74710. */
  74711. assert( v );
  74712. ephemTab = pParse->nTab++;
  74713. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  74714. /* fill the ephemeral table
  74715. */
  74716. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  74717. sqlite3Select(pParse, pSelect, &dest);
  74718. /* Generate code to scan the ephemeral table and call VUpdate. */
  74719. iReg = ++pParse->nMem;
  74720. pParse->nMem += pTab->nCol+1;
  74721. sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  74722. addr = sqlite3VdbeCurrentAddr(v);
  74723. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  74724. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  74725. for(i=0; i<pTab->nCol; i++){
  74726. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  74727. }
  74728. sqlite3VtabMakeWritable(pParse, pTab);
  74729. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
  74730. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
  74731. sqlite3VdbeJumpHere(v, addr-1);
  74732. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  74733. /* Cleanup */
  74734. sqlite3SelectDelete(db, pSelect);
  74735. }
  74736. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74737. /* Make sure "isView" gets undefined in case this file becomes part of
  74738. ** the amalgamation - so that subsequent files do not see isView as a
  74739. ** macro. */
  74740. #undef isView
  74741. /************** End of update.c **********************************************/
  74742. /************** Begin file vacuum.c ******************************************/
  74743. /*
  74744. ** 2003 April 6
  74745. **
  74746. ** The author disclaims copyright to this source code. In place of
  74747. ** a legal notice, here is a blessing:
  74748. **
  74749. ** May you do good and not evil.
  74750. ** May you find forgiveness for yourself and forgive others.
  74751. ** May you share freely, never taking more than you give.
  74752. **
  74753. *************************************************************************
  74754. ** This file contains code used to implement the VACUUM command.
  74755. **
  74756. ** Most of the code in this file may be omitted by defining the
  74757. ** SQLITE_OMIT_VACUUM macro.
  74758. **
  74759. ** $Id: vacuum.c,v 1.87 2009/04/02 20:16:59 drh Exp $
  74760. */
  74761. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  74762. /*
  74763. ** Execute zSql on database db. Return an error code.
  74764. */
  74765. static int execSql(sqlite3 *db, const char *zSql){
  74766. sqlite3_stmt *pStmt;
  74767. if( !zSql ){
  74768. return SQLITE_NOMEM;
  74769. }
  74770. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  74771. return sqlite3_errcode(db);
  74772. }
  74773. while( SQLITE_ROW==sqlite3_step(pStmt) ){}
  74774. return sqlite3_finalize(pStmt);
  74775. }
  74776. /*
  74777. ** Execute zSql on database db. The statement returns exactly
  74778. ** one column. Execute this as SQL on the same database.
  74779. */
  74780. static int execExecSql(sqlite3 *db, const char *zSql){
  74781. sqlite3_stmt *pStmt;
  74782. int rc;
  74783. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  74784. if( rc!=SQLITE_OK ) return rc;
  74785. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  74786. rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
  74787. if( rc!=SQLITE_OK ){
  74788. sqlite3_finalize(pStmt);
  74789. return rc;
  74790. }
  74791. }
  74792. return sqlite3_finalize(pStmt);
  74793. }
  74794. /*
  74795. ** The non-standard VACUUM command is used to clean up the database,
  74796. ** collapse free space, etc. It is modelled after the VACUUM command
  74797. ** in PostgreSQL.
  74798. **
  74799. ** In version 1.0.x of SQLite, the VACUUM command would call
  74800. ** gdbm_reorganize() on all the database tables. But beginning
  74801. ** with 2.0.0, SQLite no longer uses GDBM so this command has
  74802. ** become a no-op.
  74803. */
  74804. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  74805. Vdbe *v = sqlite3GetVdbe(pParse);
  74806. if( v ){
  74807. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  74808. }
  74809. return;
  74810. }
  74811. /*
  74812. ** This routine implements the OP_Vacuum opcode of the VDBE.
  74813. */
  74814. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  74815. int rc = SQLITE_OK; /* Return code from service routines */
  74816. Btree *pMain; /* The database being vacuumed */
  74817. Pager *pMainPager; /* Pager for database being vacuumed */
  74818. Btree *pTemp; /* The temporary database we vacuum into */
  74819. char *zSql = 0; /* SQL statements */
  74820. int saved_flags; /* Saved value of the db->flags */
  74821. int saved_nChange; /* Saved value of db->nChange */
  74822. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  74823. Db *pDb = 0; /* Database to detach at end of vacuum */
  74824. int isMemDb; /* True is vacuuming a :memory: database */
  74825. int nRes;
  74826. if( !db->autoCommit ){
  74827. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  74828. return SQLITE_ERROR;
  74829. }
  74830. /* Save the current value of the write-schema flag before setting it. */
  74831. saved_flags = db->flags;
  74832. saved_nChange = db->nChange;
  74833. saved_nTotalChange = db->nTotalChange;
  74834. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  74835. pMain = db->aDb[0].pBt;
  74836. pMainPager = sqlite3BtreePager(pMain);
  74837. isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;
  74838. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  74839. ** can be set to 'off' for this file, as it is not recovered if a crash
  74840. ** occurs anyway. The integrity of the database is maintained by a
  74841. ** (possibly synchronous) transaction opened on the main database before
  74842. ** sqlite3BtreeCopyFile() is called.
  74843. **
  74844. ** An optimisation would be to use a non-journaled pager.
  74845. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  74846. ** that actually made the VACUUM run slower. Very little journalling
  74847. ** actually occurs when doing a vacuum since the vacuum_db is initially
  74848. ** empty. Only the journal header is written. Apparently it takes more
  74849. ** time to parse and run the PRAGMA to turn journalling off than it does
  74850. ** to write the journal header file.
  74851. */
  74852. zSql = "ATTACH '' AS vacuum_db;";
  74853. rc = execSql(db, zSql);
  74854. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74855. pDb = &db->aDb[db->nDb-1];
  74856. assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
  74857. pTemp = db->aDb[db->nDb-1].pBt;
  74858. nRes = sqlite3BtreeGetReserve(pMain);
  74859. /* A VACUUM cannot change the pagesize of an encrypted database. */
  74860. #ifdef SQLITE_HAS_CODEC
  74861. if( db->nextPagesize ){
  74862. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  74863. int nKey;
  74864. char *zKey;
  74865. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  74866. if( nKey ) db->nextPagesize = 0;
  74867. }
  74868. #endif
  74869. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  74870. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  74871. || db->mallocFailed
  74872. ){
  74873. rc = SQLITE_NOMEM;
  74874. goto end_of_vacuum;
  74875. }
  74876. rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
  74877. if( rc!=SQLITE_OK ){
  74878. goto end_of_vacuum;
  74879. }
  74880. #ifndef SQLITE_OMIT_AUTOVACUUM
  74881. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  74882. sqlite3BtreeGetAutoVacuum(pMain));
  74883. #endif
  74884. /* Begin a transaction */
  74885. rc = execSql(db, "BEGIN EXCLUSIVE;");
  74886. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74887. /* Query the schema of the main database. Create a mirror schema
  74888. ** in the temporary database.
  74889. */
  74890. rc = execExecSql(db,
  74891. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  74892. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  74893. " AND rootpage>0"
  74894. );
  74895. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74896. rc = execExecSql(db,
  74897. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  74898. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  74899. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74900. rc = execExecSql(db,
  74901. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  74902. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  74903. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74904. /* Loop through the tables in the main database. For each, do
  74905. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
  74906. ** the contents to the temporary database.
  74907. */
  74908. rc = execExecSql(db,
  74909. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  74910. "|| ' SELECT * FROM ' || quote(name) || ';'"
  74911. "FROM sqlite_master "
  74912. "WHERE type = 'table' AND name!='sqlite_sequence' "
  74913. " AND rootpage>0"
  74914. );
  74915. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74916. /* Copy over the sequence table
  74917. */
  74918. rc = execExecSql(db,
  74919. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  74920. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  74921. );
  74922. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74923. rc = execExecSql(db,
  74924. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  74925. "|| ' SELECT * FROM ' || quote(name) || ';' "
  74926. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  74927. );
  74928. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74929. /* Copy the triggers, views, and virtual tables from the main database
  74930. ** over to the temporary database. None of these objects has any
  74931. ** associated storage, so all we have to do is copy their entries
  74932. ** from the SQLITE_MASTER table.
  74933. */
  74934. rc = execSql(db,
  74935. "INSERT INTO vacuum_db.sqlite_master "
  74936. " SELECT type, name, tbl_name, rootpage, sql"
  74937. " FROM sqlite_master"
  74938. " WHERE type='view' OR type='trigger'"
  74939. " OR (type='table' AND rootpage=0)"
  74940. );
  74941. if( rc ) goto end_of_vacuum;
  74942. /* At this point, unless the main db was completely empty, there is now a
  74943. ** transaction open on the vacuum database, but not on the main database.
  74944. ** Open a btree level transaction on the main database. This allows a
  74945. ** call to sqlite3BtreeCopyFile(). The main database btree level
  74946. ** transaction is then committed, so the SQL level never knows it was
  74947. ** opened for writing. This way, the SQL transaction used to create the
  74948. ** temporary database never needs to be committed.
  74949. */
  74950. if( rc==SQLITE_OK ){
  74951. u32 meta;
  74952. int i;
  74953. /* This array determines which meta meta values are preserved in the
  74954. ** vacuum. Even entries are the meta value number and odd entries
  74955. ** are an increment to apply to the meta value after the vacuum.
  74956. ** The increment is used to increase the schema cookie so that other
  74957. ** connections to the same database will know to reread the schema.
  74958. */
  74959. static const unsigned char aCopy[] = {
  74960. 1, 1, /* Add one to the old schema cookie */
  74961. 3, 0, /* Preserve the default page cache size */
  74962. 5, 0, /* Preserve the default text encoding */
  74963. 6, 0, /* Preserve the user version */
  74964. };
  74965. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  74966. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  74967. /* Copy Btree meta values */
  74968. for(i=0; i<ArraySize(aCopy); i+=2){
  74969. rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  74970. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74971. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  74972. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74973. }
  74974. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  74975. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74976. rc = sqlite3BtreeCommit(pTemp);
  74977. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  74978. #ifndef SQLITE_OMIT_AUTOVACUUM
  74979. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  74980. #endif
  74981. }
  74982. if( rc==SQLITE_OK ){
  74983. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  74984. }
  74985. end_of_vacuum:
  74986. /* Restore the original value of db->flags */
  74987. db->flags = saved_flags;
  74988. db->nChange = saved_nChange;
  74989. db->nTotalChange = saved_nTotalChange;
  74990. /* Currently there is an SQL level transaction open on the vacuum
  74991. ** database. No locks are held on any other files (since the main file
  74992. ** was committed at the btree level). So it safe to end the transaction
  74993. ** by manually setting the autoCommit flag to true and detaching the
  74994. ** vacuum database. The vacuum_db journal file is deleted when the pager
  74995. ** is closed by the DETACH.
  74996. */
  74997. db->autoCommit = 1;
  74998. if( pDb ){
  74999. sqlite3BtreeClose(pDb->pBt);
  75000. pDb->pBt = 0;
  75001. pDb->pSchema = 0;
  75002. }
  75003. sqlite3ResetInternalSchema(db, 0);
  75004. return rc;
  75005. }
  75006. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  75007. /************** End of vacuum.c **********************************************/
  75008. /************** Begin file vtab.c ********************************************/
  75009. /*
  75010. ** 2006 June 10
  75011. **
  75012. ** The author disclaims copyright to this source code. In place of
  75013. ** a legal notice, here is a blessing:
  75014. **
  75015. ** May you do good and not evil.
  75016. ** May you find forgiveness for yourself and forgive others.
  75017. ** May you share freely, never taking more than you give.
  75018. **
  75019. *************************************************************************
  75020. ** This file contains code used to help implement virtual tables.
  75021. **
  75022. ** $Id: vtab.c,v 1.85 2009/04/11 16:27:20 drh Exp $
  75023. */
  75024. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75025. /*
  75026. ** The actual function that does the work of creating a new module.
  75027. ** This function implements the sqlite3_create_module() and
  75028. ** sqlite3_create_module_v2() interfaces.
  75029. */
  75030. static int createModule(
  75031. sqlite3 *db, /* Database in which module is registered */
  75032. const char *zName, /* Name assigned to this module */
  75033. const sqlite3_module *pModule, /* The definition of the module */
  75034. void *pAux, /* Context pointer for xCreate/xConnect */
  75035. void (*xDestroy)(void *) /* Module destructor function */
  75036. ) {
  75037. int rc, nName;
  75038. Module *pMod;
  75039. sqlite3_mutex_enter(db->mutex);
  75040. nName = sqlite3Strlen30(zName);
  75041. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  75042. if( pMod ){
  75043. Module *pDel;
  75044. char *zCopy = (char *)(&pMod[1]);
  75045. memcpy(zCopy, zName, nName+1);
  75046. pMod->zName = zCopy;
  75047. pMod->pModule = pModule;
  75048. pMod->pAux = pAux;
  75049. pMod->xDestroy = xDestroy;
  75050. pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
  75051. if( pDel && pDel->xDestroy ){
  75052. pDel->xDestroy(pDel->pAux);
  75053. }
  75054. sqlite3DbFree(db, pDel);
  75055. if( pDel==pMod ){
  75056. db->mallocFailed = 1;
  75057. }
  75058. sqlite3ResetInternalSchema(db, 0);
  75059. }else if( xDestroy ){
  75060. xDestroy(pAux);
  75061. }
  75062. rc = sqlite3ApiExit(db, SQLITE_OK);
  75063. sqlite3_mutex_leave(db->mutex);
  75064. return rc;
  75065. }
  75066. /*
  75067. ** External API function used to create a new virtual-table module.
  75068. */
  75069. SQLITE_API int sqlite3_create_module(
  75070. sqlite3 *db, /* Database in which module is registered */
  75071. const char *zName, /* Name assigned to this module */
  75072. const sqlite3_module *pModule, /* The definition of the module */
  75073. void *pAux /* Context pointer for xCreate/xConnect */
  75074. ){
  75075. return createModule(db, zName, pModule, pAux, 0);
  75076. }
  75077. /*
  75078. ** External API function used to create a new virtual-table module.
  75079. */
  75080. SQLITE_API int sqlite3_create_module_v2(
  75081. sqlite3 *db, /* Database in which module is registered */
  75082. const char *zName, /* Name assigned to this module */
  75083. const sqlite3_module *pModule, /* The definition of the module */
  75084. void *pAux, /* Context pointer for xCreate/xConnect */
  75085. void (*xDestroy)(void *) /* Module destructor function */
  75086. ){
  75087. return createModule(db, zName, pModule, pAux, xDestroy);
  75088. }
  75089. /*
  75090. ** Lock the virtual table so that it cannot be disconnected.
  75091. ** Locks nest. Every lock should have a corresponding unlock.
  75092. ** If an unlock is omitted, resources leaks will occur.
  75093. **
  75094. ** If a disconnect is attempted while a virtual table is locked,
  75095. ** the disconnect is deferred until all locks have been removed.
  75096. */
  75097. SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
  75098. pVtab->nRef++;
  75099. }
  75100. /*
  75101. ** Unlock a virtual table. When the last lock is removed,
  75102. ** disconnect the virtual table.
  75103. */
  75104. SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
  75105. assert( pVtab->nRef>0 );
  75106. pVtab->nRef--;
  75107. assert(db);
  75108. assert( sqlite3SafetyCheckOk(db) );
  75109. if( pVtab->nRef==0 ){
  75110. if( db->magic==SQLITE_MAGIC_BUSY ){
  75111. (void)sqlite3SafetyOff(db);
  75112. pVtab->pModule->xDisconnect(pVtab);
  75113. (void)sqlite3SafetyOn(db);
  75114. } else {
  75115. pVtab->pModule->xDisconnect(pVtab);
  75116. }
  75117. }
  75118. }
  75119. /*
  75120. ** Clear any and all virtual-table information from the Table record.
  75121. ** This routine is called, for example, just before deleting the Table
  75122. ** record.
  75123. */
  75124. SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
  75125. sqlite3_vtab *pVtab = p->pVtab;
  75126. Schema *pSchema = p->pSchema;
  75127. sqlite3 *db = pSchema ? pSchema->db : 0;
  75128. if( pVtab ){
  75129. assert( p->pMod && p->pMod->pModule );
  75130. sqlite3VtabUnlock(db, pVtab);
  75131. p->pVtab = 0;
  75132. }
  75133. if( p->azModuleArg ){
  75134. int i;
  75135. for(i=0; i<p->nModuleArg; i++){
  75136. sqlite3DbFree(db, p->azModuleArg[i]);
  75137. }
  75138. sqlite3DbFree(db, p->azModuleArg);
  75139. }
  75140. }
  75141. /*
  75142. ** Add a new module argument to pTable->azModuleArg[].
  75143. ** The string is not copied - the pointer is stored. The
  75144. ** string will be freed automatically when the table is
  75145. ** deleted.
  75146. */
  75147. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  75148. int i = pTable->nModuleArg++;
  75149. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  75150. char **azModuleArg;
  75151. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  75152. if( azModuleArg==0 ){
  75153. int j;
  75154. for(j=0; j<i; j++){
  75155. sqlite3DbFree(db, pTable->azModuleArg[j]);
  75156. }
  75157. sqlite3DbFree(db, zArg);
  75158. sqlite3DbFree(db, pTable->azModuleArg);
  75159. pTable->nModuleArg = 0;
  75160. }else{
  75161. azModuleArg[i] = zArg;
  75162. azModuleArg[i+1] = 0;
  75163. }
  75164. pTable->azModuleArg = azModuleArg;
  75165. }
  75166. /*
  75167. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  75168. ** statement. The module name has been parsed, but the optional list
  75169. ** of parameters that follow the module name are still pending.
  75170. */
  75171. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  75172. Parse *pParse, /* Parsing context */
  75173. Token *pName1, /* Name of new table, or database name */
  75174. Token *pName2, /* Name of new table or NULL */
  75175. Token *pModuleName /* Name of the module for the virtual table */
  75176. ){
  75177. int iDb; /* The database the table is being created in */
  75178. Table *pTable; /* The new virtual table */
  75179. sqlite3 *db; /* Database connection */
  75180. if( pParse->db->flags & SQLITE_SharedCache ){
  75181. sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
  75182. return;
  75183. }
  75184. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
  75185. pTable = pParse->pNewTable;
  75186. if( pTable==0 || pParse->nErr ) return;
  75187. assert( 0==pTable->pIndex );
  75188. db = pParse->db;
  75189. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  75190. assert( iDb>=0 );
  75191. pTable->tabFlags |= TF_Virtual;
  75192. pTable->nModuleArg = 0;
  75193. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  75194. addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
  75195. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  75196. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  75197. #ifndef SQLITE_OMIT_AUTHORIZATION
  75198. /* Creating a virtual table invokes the authorization callback twice.
  75199. ** The first invocation, to obtain permission to INSERT a row into the
  75200. ** sqlite_master table, has already been made by sqlite3StartTable().
  75201. ** The second call, to obtain permission to create the table, is made now.
  75202. */
  75203. if( pTable->azModuleArg ){
  75204. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  75205. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  75206. }
  75207. #endif
  75208. }
  75209. /*
  75210. ** This routine takes the module argument that has been accumulating
  75211. ** in pParse->zArg[] and appends it to the list of arguments on the
  75212. ** virtual table currently under construction in pParse->pTable.
  75213. */
  75214. static void addArgumentToVtab(Parse *pParse){
  75215. if( pParse->sArg.z && pParse->pNewTable ){
  75216. const char *z = (const char*)pParse->sArg.z;
  75217. int n = pParse->sArg.n;
  75218. sqlite3 *db = pParse->db;
  75219. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  75220. }
  75221. }
  75222. /*
  75223. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  75224. ** has been completely parsed.
  75225. */
  75226. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  75227. Table *pTab; /* The table being constructed */
  75228. sqlite3 *db; /* The database connection */
  75229. char *zModule; /* The module name of the table: USING modulename */
  75230. Module *pMod = 0;
  75231. addArgumentToVtab(pParse);
  75232. pParse->sArg.z = 0;
  75233. /* Lookup the module name. */
  75234. pTab = pParse->pNewTable;
  75235. if( pTab==0 ) return;
  75236. db = pParse->db;
  75237. if( pTab->nModuleArg<1 ) return;
  75238. zModule = pTab->azModuleArg[0];
  75239. pMod = (Module*)sqlite3HashFind(&db->aModule, zModule,
  75240. sqlite3Strlen30(zModule));
  75241. pTab->pMod = pMod;
  75242. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  75243. ** first time (in other words if the virtual table is actually being
  75244. ** created now instead of just being read out of sqlite_master) then
  75245. ** do additional initialization work and store the statement text
  75246. ** in the sqlite_master table.
  75247. */
  75248. if( !db->init.busy ){
  75249. char *zStmt;
  75250. char *zWhere;
  75251. int iDb;
  75252. Vdbe *v;
  75253. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  75254. if( pEnd ){
  75255. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  75256. }
  75257. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  75258. /* A slot for the record has already been allocated in the
  75259. ** SQLITE_MASTER table. We just need to update that slot with all
  75260. ** the information we've collected.
  75261. **
  75262. ** The VM register number pParse->regRowid holds the rowid of an
  75263. ** entry in the sqlite_master table tht was created for this vtab
  75264. ** by sqlite3StartTable().
  75265. */
  75266. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75267. sqlite3NestedParse(pParse,
  75268. "UPDATE %Q.%s "
  75269. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  75270. "WHERE rowid=#%d",
  75271. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  75272. pTab->zName,
  75273. pTab->zName,
  75274. zStmt,
  75275. pParse->regRowid
  75276. );
  75277. sqlite3DbFree(db, zStmt);
  75278. v = sqlite3GetVdbe(pParse);
  75279. sqlite3ChangeCookie(pParse, iDb);
  75280. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  75281. zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
  75282. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
  75283. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  75284. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  75285. }
  75286. /* If we are rereading the sqlite_master table create the in-memory
  75287. ** record of the table. If the module has already been registered,
  75288. ** also call the xConnect method here.
  75289. */
  75290. else {
  75291. Table *pOld;
  75292. Schema *pSchema = pTab->pSchema;
  75293. const char *zName = pTab->zName;
  75294. int nName = sqlite3Strlen30(zName) + 1;
  75295. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  75296. if( pOld ){
  75297. db->mallocFailed = 1;
  75298. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  75299. return;
  75300. }
  75301. pSchema->db = pParse->db;
  75302. pParse->pNewTable = 0;
  75303. }
  75304. }
  75305. /*
  75306. ** The parser calls this routine when it sees the first token
  75307. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  75308. */
  75309. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  75310. addArgumentToVtab(pParse);
  75311. pParse->sArg.z = 0;
  75312. pParse->sArg.n = 0;
  75313. }
  75314. /*
  75315. ** The parser calls this routine for each token after the first token
  75316. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  75317. */
  75318. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  75319. Token *pArg = &pParse->sArg;
  75320. if( pArg->z==0 ){
  75321. pArg->z = p->z;
  75322. pArg->n = p->n;
  75323. }else{
  75324. assert(pArg->z < p->z);
  75325. pArg->n = (int)(&p->z[p->n] - pArg->z);
  75326. }
  75327. }
  75328. /*
  75329. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  75330. ** pointer to the function to invoke is passed as the fourth parameter
  75331. ** to this procedure.
  75332. */
  75333. static int vtabCallConstructor(
  75334. sqlite3 *db,
  75335. Table *pTab,
  75336. Module *pMod,
  75337. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  75338. char **pzErr
  75339. ){
  75340. int rc;
  75341. int rc2;
  75342. sqlite3_vtab *pVtab = 0;
  75343. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  75344. int nArg = pTab->nModuleArg;
  75345. char *zErr = 0;
  75346. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  75347. if( !zModuleName ){
  75348. return SQLITE_NOMEM;
  75349. }
  75350. assert( !db->pVTab );
  75351. assert( xConstruct );
  75352. db->pVTab = pTab;
  75353. rc = sqlite3SafetyOff(db);
  75354. assert( rc==SQLITE_OK );
  75355. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
  75356. rc2 = sqlite3SafetyOn(db);
  75357. if( rc==SQLITE_OK && pVtab ){
  75358. pVtab->pModule = pMod->pModule;
  75359. pVtab->nRef = 1;
  75360. pTab->pVtab = pVtab;
  75361. }
  75362. if( SQLITE_OK!=rc ){
  75363. if( zErr==0 ){
  75364. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  75365. }else {
  75366. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  75367. sqlite3DbFree(db, zErr);
  75368. }
  75369. }else if( db->pVTab ){
  75370. const char *zFormat = "vtable constructor did not declare schema: %s";
  75371. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  75372. rc = SQLITE_ERROR;
  75373. }
  75374. if( rc==SQLITE_OK ){
  75375. rc = rc2;
  75376. }
  75377. db->pVTab = 0;
  75378. sqlite3DbFree(db, zModuleName);
  75379. /* If everything went according to plan, loop through the columns
  75380. ** of the table to see if any of them contain the token "hidden".
  75381. ** If so, set the Column.isHidden flag and remove the token from
  75382. ** the type string.
  75383. */
  75384. if( rc==SQLITE_OK ){
  75385. int iCol;
  75386. for(iCol=0; iCol<pTab->nCol; iCol++){
  75387. char *zType = pTab->aCol[iCol].zType;
  75388. int nType;
  75389. int i = 0;
  75390. if( !zType ) continue;
  75391. nType = sqlite3Strlen30(zType);
  75392. if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
  75393. for(i=0; i<nType; i++){
  75394. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  75395. && (zType[i+7]=='\0' || zType[i+7]==' ')
  75396. ){
  75397. i++;
  75398. break;
  75399. }
  75400. }
  75401. }
  75402. if( i<nType ){
  75403. int j;
  75404. int nDel = 6 + (zType[i+6] ? 1 : 0);
  75405. for(j=i; (j+nDel)<=nType; j++){
  75406. zType[j] = zType[j+nDel];
  75407. }
  75408. if( zType[i]=='\0' && i>0 ){
  75409. assert(zType[i-1]==' ');
  75410. zType[i-1] = '\0';
  75411. }
  75412. pTab->aCol[iCol].isHidden = 1;
  75413. }
  75414. }
  75415. }
  75416. return rc;
  75417. }
  75418. /*
  75419. ** This function is invoked by the parser to call the xConnect() method
  75420. ** of the virtual table pTab. If an error occurs, an error code is returned
  75421. ** and an error left in pParse.
  75422. **
  75423. ** This call is a no-op if table pTab is not a virtual table.
  75424. */
  75425. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  75426. Module *pMod;
  75427. int rc = SQLITE_OK;
  75428. if( !pTab || (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
  75429. return SQLITE_OK;
  75430. }
  75431. pMod = pTab->pMod;
  75432. if( !pMod ){
  75433. const char *zModule = pTab->azModuleArg[0];
  75434. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  75435. rc = SQLITE_ERROR;
  75436. } else {
  75437. char *zErr = 0;
  75438. sqlite3 *db = pParse->db;
  75439. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  75440. if( rc!=SQLITE_OK ){
  75441. sqlite3ErrorMsg(pParse, "%s", zErr);
  75442. }
  75443. sqlite3DbFree(db, zErr);
  75444. }
  75445. return rc;
  75446. }
  75447. /*
  75448. ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
  75449. */
  75450. static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
  75451. const int ARRAY_INCR = 5;
  75452. /* Grow the sqlite3.aVTrans array if required */
  75453. if( (db->nVTrans%ARRAY_INCR)==0 ){
  75454. sqlite3_vtab **aVTrans;
  75455. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  75456. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  75457. if( !aVTrans ){
  75458. return SQLITE_NOMEM;
  75459. }
  75460. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  75461. db->aVTrans = aVTrans;
  75462. }
  75463. /* Add pVtab to the end of sqlite3.aVTrans */
  75464. db->aVTrans[db->nVTrans++] = pVtab;
  75465. sqlite3VtabLock(pVtab);
  75466. return SQLITE_OK;
  75467. }
  75468. /*
  75469. ** This function is invoked by the vdbe to call the xCreate method
  75470. ** of the virtual table named zTab in database iDb.
  75471. **
  75472. ** If an error occurs, *pzErr is set to point an an English language
  75473. ** description of the error and an SQLITE_XXX error code is returned.
  75474. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  75475. */
  75476. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  75477. int rc = SQLITE_OK;
  75478. Table *pTab;
  75479. Module *pMod;
  75480. const char *zModule;
  75481. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  75482. assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
  75483. pMod = pTab->pMod;
  75484. zModule = pTab->azModuleArg[0];
  75485. /* If the module has been registered and includes a Create method,
  75486. ** invoke it now. If the module has not been registered, return an
  75487. ** error. Otherwise, do nothing.
  75488. */
  75489. if( !pMod ){
  75490. *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
  75491. rc = SQLITE_ERROR;
  75492. }else{
  75493. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  75494. }
  75495. if( rc==SQLITE_OK && pTab->pVtab ){
  75496. rc = addToVTrans(db, pTab->pVtab);
  75497. }
  75498. return rc;
  75499. }
  75500. /*
  75501. ** This function is used to set the schema of a virtual table. It is only
  75502. ** valid to call this function from within the xCreate() or xConnect() of a
  75503. ** virtual table module.
  75504. */
  75505. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  75506. Parse sParse;
  75507. int rc = SQLITE_OK;
  75508. Table *pTab;
  75509. char *zErr = 0;
  75510. sqlite3_mutex_enter(db->mutex);
  75511. pTab = db->pVTab;
  75512. if( !pTab ){
  75513. sqlite3Error(db, SQLITE_MISUSE, 0);
  75514. sqlite3_mutex_leave(db->mutex);
  75515. return SQLITE_MISUSE;
  75516. }
  75517. assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
  75518. memset(&sParse, 0, sizeof(Parse));
  75519. sParse.declareVtab = 1;
  75520. sParse.db = db;
  75521. if(
  75522. SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) &&
  75523. sParse.pNewTable &&
  75524. !sParse.pNewTable->pSelect &&
  75525. (sParse.pNewTable->tabFlags & TF_Virtual)==0
  75526. ){
  75527. pTab->aCol = sParse.pNewTable->aCol;
  75528. pTab->nCol = sParse.pNewTable->nCol;
  75529. sParse.pNewTable->nCol = 0;
  75530. sParse.pNewTable->aCol = 0;
  75531. db->pVTab = 0;
  75532. } else {
  75533. sqlite3Error(db, SQLITE_ERROR, zErr);
  75534. sqlite3DbFree(db, zErr);
  75535. rc = SQLITE_ERROR;
  75536. }
  75537. sParse.declareVtab = 0;
  75538. if( sParse.pVdbe ){
  75539. sqlite3VdbeFinalize(sParse.pVdbe);
  75540. }
  75541. sqlite3DeleteTable(sParse.pNewTable);
  75542. sParse.pNewTable = 0;
  75543. assert( (rc&0xff)==rc );
  75544. rc = sqlite3ApiExit(db, rc);
  75545. sqlite3_mutex_leave(db->mutex);
  75546. return rc;
  75547. }
  75548. /*
  75549. ** This function is invoked by the vdbe to call the xDestroy method
  75550. ** of the virtual table named zTab in database iDb. This occurs
  75551. ** when a DROP TABLE is mentioned.
  75552. **
  75553. ** This call is a no-op if zTab is not a virtual table.
  75554. */
  75555. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
  75556. {
  75557. int rc = SQLITE_OK;
  75558. Table *pTab;
  75559. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  75560. assert(pTab);
  75561. if( pTab->pVtab ){
  75562. int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
  75563. rc = sqlite3SafetyOff(db);
  75564. assert( rc==SQLITE_OK );
  75565. if( xDestroy ){
  75566. rc = xDestroy(pTab->pVtab);
  75567. }
  75568. (void)sqlite3SafetyOn(db);
  75569. if( rc==SQLITE_OK ){
  75570. int i;
  75571. for(i=0; i<db->nVTrans; i++){
  75572. if( db->aVTrans[i]==pTab->pVtab ){
  75573. db->aVTrans[i] = db->aVTrans[--db->nVTrans];
  75574. break;
  75575. }
  75576. }
  75577. pTab->pVtab = 0;
  75578. }
  75579. }
  75580. return rc;
  75581. }
  75582. /*
  75583. ** This function invokes either the xRollback or xCommit method
  75584. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  75585. ** called is identified by the second argument, "offset", which is
  75586. ** the offset of the method to call in the sqlite3_module structure.
  75587. **
  75588. ** The array is cleared after invoking the callbacks.
  75589. */
  75590. static void callFinaliser(sqlite3 *db, int offset){
  75591. int i;
  75592. if( db->aVTrans ){
  75593. for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
  75594. sqlite3_vtab *pVtab = db->aVTrans[i];
  75595. int (*x)(sqlite3_vtab *);
  75596. x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
  75597. if( x ) x(pVtab);
  75598. sqlite3VtabUnlock(db, pVtab);
  75599. }
  75600. sqlite3DbFree(db, db->aVTrans);
  75601. db->nVTrans = 0;
  75602. db->aVTrans = 0;
  75603. }
  75604. }
  75605. /*
  75606. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  75607. ** array. Return the error code for the first error that occurs, or
  75608. ** SQLITE_OK if all xSync operations are successful.
  75609. **
  75610. ** Set *pzErrmsg to point to a buffer that should be released using
  75611. ** sqlite3DbFree() containing an error message, if one is available.
  75612. */
  75613. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
  75614. int i;
  75615. int rc = SQLITE_OK;
  75616. int rcsafety;
  75617. sqlite3_vtab **aVTrans = db->aVTrans;
  75618. rc = sqlite3SafetyOff(db);
  75619. db->aVTrans = 0;
  75620. for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
  75621. sqlite3_vtab *pVtab = aVTrans[i];
  75622. int (*x)(sqlite3_vtab *);
  75623. x = pVtab->pModule->xSync;
  75624. if( x ){
  75625. rc = x(pVtab);
  75626. sqlite3DbFree(db, *pzErrmsg);
  75627. *pzErrmsg = pVtab->zErrMsg;
  75628. pVtab->zErrMsg = 0;
  75629. }
  75630. }
  75631. db->aVTrans = aVTrans;
  75632. rcsafety = sqlite3SafetyOn(db);
  75633. if( rc==SQLITE_OK ){
  75634. rc = rcsafety;
  75635. }
  75636. return rc;
  75637. }
  75638. /*
  75639. ** Invoke the xRollback method of all virtual tables in the
  75640. ** sqlite3.aVTrans array. Then clear the array itself.
  75641. */
  75642. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  75643. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  75644. return SQLITE_OK;
  75645. }
  75646. /*
  75647. ** Invoke the xCommit method of all virtual tables in the
  75648. ** sqlite3.aVTrans array. Then clear the array itself.
  75649. */
  75650. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  75651. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  75652. return SQLITE_OK;
  75653. }
  75654. /*
  75655. ** If the virtual table pVtab supports the transaction interface
  75656. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  75657. ** not currently open, invoke the xBegin method now.
  75658. **
  75659. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  75660. ** in the sqlite3.aVTrans array.
  75661. */
  75662. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
  75663. int rc = SQLITE_OK;
  75664. const sqlite3_module *pModule;
  75665. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  75666. ** than zero, then this function is being called from within a
  75667. ** virtual module xSync() callback. It is illegal to write to
  75668. ** virtual module tables in this case, so return SQLITE_MISUSE.
  75669. */
  75670. if( sqlite3VtabInSync(db) ){
  75671. return SQLITE_LOCKED;
  75672. }
  75673. if( !pVtab ){
  75674. return SQLITE_OK;
  75675. }
  75676. pModule = pVtab->pModule;
  75677. if( pModule->xBegin ){
  75678. int i;
  75679. /* If pVtab is already in the aVTrans array, return early */
  75680. for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
  75681. if( db->aVTrans[i]==pVtab ){
  75682. return SQLITE_OK;
  75683. }
  75684. }
  75685. /* Invoke the xBegin method */
  75686. rc = pModule->xBegin(pVtab);
  75687. if( rc==SQLITE_OK ){
  75688. rc = addToVTrans(db, pVtab);
  75689. }
  75690. }
  75691. return rc;
  75692. }
  75693. /*
  75694. ** The first parameter (pDef) is a function implementation. The
  75695. ** second parameter (pExpr) is the first argument to this function.
  75696. ** If pExpr is a column in a virtual table, then let the virtual
  75697. ** table implementation have an opportunity to overload the function.
  75698. **
  75699. ** This routine is used to allow virtual table implementations to
  75700. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  75701. **
  75702. ** Return either the pDef argument (indicating no change) or a
  75703. ** new FuncDef structure that is marked as ephemeral using the
  75704. ** SQLITE_FUNC_EPHEM flag.
  75705. */
  75706. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  75707. sqlite3 *db, /* Database connection for reporting malloc problems */
  75708. FuncDef *pDef, /* Function to possibly overload */
  75709. int nArg, /* Number of arguments to the function */
  75710. Expr *pExpr /* First argument to the function */
  75711. ){
  75712. Table *pTab;
  75713. sqlite3_vtab *pVtab;
  75714. sqlite3_module *pMod;
  75715. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  75716. void *pArg = 0;
  75717. FuncDef *pNew;
  75718. int rc = 0;
  75719. char *zLowerName;
  75720. unsigned char *z;
  75721. /* Check to see the left operand is a column in a virtual table */
  75722. if( pExpr==0 ) return pDef;
  75723. if( pExpr->op!=TK_COLUMN ) return pDef;
  75724. pTab = pExpr->pTab;
  75725. if( pTab==0 ) return pDef;
  75726. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  75727. pVtab = pTab->pVtab;
  75728. assert( pVtab!=0 );
  75729. assert( pVtab->pModule!=0 );
  75730. pMod = (sqlite3_module *)pVtab->pModule;
  75731. if( pMod->xFindFunction==0 ) return pDef;
  75732. /* Call the xFindFunction method on the virtual table implementation
  75733. ** to see if the implementation wants to overload this function
  75734. */
  75735. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  75736. if( zLowerName ){
  75737. for(z=(unsigned char*)zLowerName; *z; z++){
  75738. *z = sqlite3UpperToLower[*z];
  75739. }
  75740. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  75741. sqlite3DbFree(db, zLowerName);
  75742. if( pVtab->zErrMsg ){
  75743. sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
  75744. sqlite3DbFree(db, pVtab->zErrMsg);
  75745. pVtab->zErrMsg = 0;
  75746. }
  75747. }
  75748. if( rc==0 ){
  75749. return pDef;
  75750. }
  75751. /* Create a new ephemeral function definition for the overloaded
  75752. ** function */
  75753. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  75754. + sqlite3Strlen30(pDef->zName) );
  75755. if( pNew==0 ){
  75756. return pDef;
  75757. }
  75758. *pNew = *pDef;
  75759. pNew->zName = (char *)&pNew[1];
  75760. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  75761. pNew->xFunc = xFunc;
  75762. pNew->pUserData = pArg;
  75763. pNew->flags |= SQLITE_FUNC_EPHEM;
  75764. return pNew;
  75765. }
  75766. /*
  75767. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  75768. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  75769. ** array if it is missing. If pTab is already in the array, this routine
  75770. ** is a no-op.
  75771. */
  75772. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  75773. int i, n;
  75774. assert( IsVirtual(pTab) );
  75775. for(i=0; i<pParse->nVtabLock; i++){
  75776. if( pTab==pParse->apVtabLock[i] ) return;
  75777. }
  75778. n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
  75779. pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
  75780. if( pParse->apVtabLock ){
  75781. pParse->apVtabLock[pParse->nVtabLock++] = pTab;
  75782. }else{
  75783. pParse->db->mallocFailed = 1;
  75784. }
  75785. }
  75786. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75787. /************** End of vtab.c ************************************************/
  75788. /************** Begin file where.c *******************************************/
  75789. /*
  75790. ** 2001 September 15
  75791. **
  75792. ** The author disclaims copyright to this source code. In place of
  75793. ** a legal notice, here is a blessing:
  75794. **
  75795. ** May you do good and not evil.
  75796. ** May you find forgiveness for yourself and forgive others.
  75797. ** May you share freely, never taking more than you give.
  75798. **
  75799. *************************************************************************
  75800. ** This module contains C code that generates VDBE code used to process
  75801. ** the WHERE clause of SQL statements. This module is responsible for
  75802. ** generating the code that loops through a table looking for applicable
  75803. ** rows. Indices are selected and used to speed the search when doing
  75804. ** so is applicable. Because this module is responsible for selecting
  75805. ** indices, you might also think of this module as the "query optimizer".
  75806. **
  75807. ** $Id: where.c,v 1.382 2009/04/07 13:48:12 drh Exp $
  75808. */
  75809. /*
  75810. ** Trace output macros
  75811. */
  75812. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  75813. SQLITE_PRIVATE int sqlite3WhereTrace = 0;
  75814. #endif
  75815. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  75816. # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
  75817. #else
  75818. # define WHERETRACE(X)
  75819. #endif
  75820. /* Forward reference
  75821. */
  75822. typedef struct WhereClause WhereClause;
  75823. typedef struct WhereMaskSet WhereMaskSet;
  75824. typedef struct WhereOrInfo WhereOrInfo;
  75825. typedef struct WhereAndInfo WhereAndInfo;
  75826. typedef struct WhereCost WhereCost;
  75827. /*
  75828. ** The query generator uses an array of instances of this structure to
  75829. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  75830. ** clause subexpression is separated from the others by AND operators.
  75831. ** (Note: the same data structure is also reused to hold a group of terms
  75832. ** separated by OR operators. But at the top-level, everything is AND
  75833. ** separated.)
  75834. **
  75835. ** All WhereTerms are collected into a single WhereClause structure.
  75836. ** The following identity holds:
  75837. **
  75838. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  75839. **
  75840. ** When a term is of the form:
  75841. **
  75842. ** X <op> <expr>
  75843. **
  75844. ** where X is a column name and <op> is one of certain operators,
  75845. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  75846. ** cursor number and column number for X. WhereTerm.eOperator records
  75847. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  75848. ** use of a bitmask encoding for the operator allows us to search
  75849. ** quickly for terms that match any of several different operators.
  75850. **
  75851. ** A WhereTerm might also be two or more subterms connected by OR:
  75852. **
  75853. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  75854. **
  75855. ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
  75856. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  75857. ** is collected about the
  75858. **
  75859. ** If a term in the WHERE clause does not match either of the two previous
  75860. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  75861. ** to the original subexpression content and wtFlags is set up appropriately
  75862. ** but no other fields in the WhereTerm object are meaningful.
  75863. **
  75864. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  75865. ** but they do so indirectly. A single WhereMaskSet structure translates
  75866. ** cursor number into bits and the translated bit is stored in the prereq
  75867. ** fields. The translation is used in order to maximize the number of
  75868. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  75869. ** spread out over the non-negative integers. For example, the cursor
  75870. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  75871. ** translates these sparse cursor numbers into consecutive integers
  75872. ** beginning with 0 in order to make the best possible use of the available
  75873. ** bits in the Bitmask. So, in the example above, the cursor numbers
  75874. ** would be mapped into integers 0 through 7.
  75875. **
  75876. ** The number of terms in a join is limited by the number of bits
  75877. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  75878. ** is only able to process joins with 64 or fewer tables.
  75879. */
  75880. typedef struct WhereTerm WhereTerm;
  75881. struct WhereTerm {
  75882. Expr *pExpr; /* Pointer to the subexpression that is this term */
  75883. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  75884. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  75885. union {
  75886. int leftColumn; /* Column number of X in "X <op> <expr>" */
  75887. WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
  75888. WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
  75889. } u;
  75890. u16 eOperator; /* A WO_xx value describing <op> */
  75891. u8 wtFlags; /* TERM_xxx bit flags. See below */
  75892. u8 nChild; /* Number of children that must disable us */
  75893. WhereClause *pWC; /* The clause this term is part of */
  75894. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  75895. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  75896. };
  75897. /*
  75898. ** Allowed values of WhereTerm.wtFlags
  75899. */
  75900. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  75901. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  75902. #define TERM_CODED 0x04 /* This term is already coded */
  75903. #define TERM_COPIED 0x08 /* Has a child */
  75904. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  75905. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  75906. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  75907. /*
  75908. ** An instance of the following structure holds all information about a
  75909. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  75910. */
  75911. struct WhereClause {
  75912. Parse *pParse; /* The parser context */
  75913. WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
  75914. u8 op; /* Split operator. TK_AND or TK_OR */
  75915. int nTerm; /* Number of terms */
  75916. int nSlot; /* Number of entries in a[] */
  75917. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  75918. WhereTerm aStatic[4]; /* Initial static space for a[] */
  75919. };
  75920. /*
  75921. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  75922. ** a dynamically allocated instance of the following structure.
  75923. */
  75924. struct WhereOrInfo {
  75925. WhereClause wc; /* Decomposition into subterms */
  75926. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  75927. };
  75928. /*
  75929. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  75930. ** a dynamically allocated instance of the following structure.
  75931. */
  75932. struct WhereAndInfo {
  75933. WhereClause wc; /* The subexpression broken out */
  75934. };
  75935. /*
  75936. ** An instance of the following structure keeps track of a mapping
  75937. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  75938. **
  75939. ** The VDBE cursor numbers are small integers contained in
  75940. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  75941. ** clause, the cursor numbers might not begin with 0 and they might
  75942. ** contain gaps in the numbering sequence. But we want to make maximum
  75943. ** use of the bits in our bitmasks. This structure provides a mapping
  75944. ** from the sparse cursor numbers into consecutive integers beginning
  75945. ** with 0.
  75946. **
  75947. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  75948. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  75949. **
  75950. ** For example, if the WHERE clause expression used these VDBE
  75951. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  75952. ** would map those cursor numbers into bits 0 through 5.
  75953. **
  75954. ** Note that the mapping is not necessarily ordered. In the example
  75955. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  75956. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  75957. ** does not really matter. What is important is that sparse cursor
  75958. ** numbers all get mapped into bit numbers that begin with 0 and contain
  75959. ** no gaps.
  75960. */
  75961. struct WhereMaskSet {
  75962. int n; /* Number of assigned cursor values */
  75963. int ix[BMS]; /* Cursor assigned to each bit */
  75964. };
  75965. /*
  75966. ** A WhereCost object records a lookup strategy and the estimated
  75967. ** cost of pursuing that strategy.
  75968. */
  75969. struct WhereCost {
  75970. WherePlan plan; /* The lookup strategy */
  75971. double rCost; /* Overall cost of pursuing this search strategy */
  75972. double nRow; /* Estimated number of output rows */
  75973. };
  75974. /*
  75975. ** Bitmasks for the operators that indices are able to exploit. An
  75976. ** OR-ed combination of these values can be used when searching for
  75977. ** terms in the where clause.
  75978. */
  75979. #define WO_IN 0x001
  75980. #define WO_EQ 0x002
  75981. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  75982. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  75983. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  75984. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  75985. #define WO_MATCH 0x040
  75986. #define WO_ISNULL 0x080
  75987. #define WO_OR 0x100 /* Two or more OR-connected terms */
  75988. #define WO_AND 0x200 /* Two or more AND-connected terms */
  75989. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  75990. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  75991. /*
  75992. ** Value for wsFlags returned by bestIndex() and stored in
  75993. ** WhereLevel.wsFlags. These flags determine which search
  75994. ** strategies are appropriate.
  75995. **
  75996. ** The least significant 12 bits is reserved as a mask for WO_ values above.
  75997. ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  75998. ** But if the table is the right table of a left join, WhereLevel.wsFlags
  75999. ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
  76000. ** the "op" parameter to findTerm when we are resolving equality constraints.
  76001. ** ISNULL constraints will then not be used on the right table of a left
  76002. ** join. Tickets #2177 and #2189.
  76003. */
  76004. #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
  76005. #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
  76006. #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) */
  76007. #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
  76008. #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
  76009. #define WHERE_INDEXED 0x00070000 /* Anything that uses an index */
  76010. #define WHERE_IN_ABLE 0x00071000 /* Able to support an IN operator */
  76011. #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
  76012. #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
  76013. #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
  76014. #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
  76015. #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
  76016. #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
  76017. #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
  76018. #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
  76019. /*
  76020. ** Initialize a preallocated WhereClause structure.
  76021. */
  76022. static void whereClauseInit(
  76023. WhereClause *pWC, /* The WhereClause to be initialized */
  76024. Parse *pParse, /* The parsing context */
  76025. WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */
  76026. ){
  76027. pWC->pParse = pParse;
  76028. pWC->pMaskSet = pMaskSet;
  76029. pWC->nTerm = 0;
  76030. pWC->nSlot = ArraySize(pWC->aStatic);
  76031. pWC->a = pWC->aStatic;
  76032. }
  76033. /* Forward reference */
  76034. static void whereClauseClear(WhereClause*);
  76035. /*
  76036. ** Deallocate all memory associated with a WhereOrInfo object.
  76037. */
  76038. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  76039. whereClauseClear(&p->wc);
  76040. sqlite3DbFree(db, p);
  76041. }
  76042. /*
  76043. ** Deallocate all memory associated with a WhereAndInfo object.
  76044. */
  76045. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  76046. whereClauseClear(&p->wc);
  76047. sqlite3DbFree(db, p);
  76048. }
  76049. /*
  76050. ** Deallocate a WhereClause structure. The WhereClause structure
  76051. ** itself is not freed. This routine is the inverse of whereClauseInit().
  76052. */
  76053. static void whereClauseClear(WhereClause *pWC){
  76054. int i;
  76055. WhereTerm *a;
  76056. sqlite3 *db = pWC->pParse->db;
  76057. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  76058. if( a->wtFlags & TERM_DYNAMIC ){
  76059. sqlite3ExprDelete(db, a->pExpr);
  76060. }
  76061. if( a->wtFlags & TERM_ORINFO ){
  76062. whereOrInfoDelete(db, a->u.pOrInfo);
  76063. }else if( a->wtFlags & TERM_ANDINFO ){
  76064. whereAndInfoDelete(db, a->u.pAndInfo);
  76065. }
  76066. }
  76067. if( pWC->a!=pWC->aStatic ){
  76068. sqlite3DbFree(db, pWC->a);
  76069. }
  76070. }
  76071. /*
  76072. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  76073. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  76074. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  76075. ** 0 is returned if the new WhereTerm could not be added due to a memory
  76076. ** allocation error. The memory allocation failure will be recorded in
  76077. ** the db->mallocFailed flag so that higher-level functions can detect it.
  76078. **
  76079. ** This routine will increase the size of the pWC->a[] array as necessary.
  76080. **
  76081. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  76082. ** for freeing the expression p is assumed by the WhereClause object pWC.
  76083. ** This is true even if this routine fails to allocate a new WhereTerm.
  76084. **
  76085. ** WARNING: This routine might reallocate the space used to store
  76086. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  76087. ** calling this routine. Such pointers may be reinitialized by referencing
  76088. ** the pWC->a[] array.
  76089. */
  76090. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  76091. WhereTerm *pTerm;
  76092. int idx;
  76093. if( pWC->nTerm>=pWC->nSlot ){
  76094. WhereTerm *pOld = pWC->a;
  76095. sqlite3 *db = pWC->pParse->db;
  76096. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  76097. if( pWC->a==0 ){
  76098. if( wtFlags & TERM_DYNAMIC ){
  76099. sqlite3ExprDelete(db, p);
  76100. }
  76101. pWC->a = pOld;
  76102. return 0;
  76103. }
  76104. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  76105. if( pOld!=pWC->aStatic ){
  76106. sqlite3DbFree(db, pOld);
  76107. }
  76108. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  76109. }
  76110. pTerm = &pWC->a[idx = pWC->nTerm++];
  76111. pTerm->pExpr = p;
  76112. pTerm->wtFlags = wtFlags;
  76113. pTerm->pWC = pWC;
  76114. pTerm->iParent = -1;
  76115. return idx;
  76116. }
  76117. /*
  76118. ** This routine identifies subexpressions in the WHERE clause where
  76119. ** each subexpression is separated by the AND operator or some other
  76120. ** operator specified in the op parameter. The WhereClause structure
  76121. ** is filled with pointers to subexpressions. For example:
  76122. **
  76123. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  76124. ** \________/ \_______________/ \________________/
  76125. ** slot[0] slot[1] slot[2]
  76126. **
  76127. ** The original WHERE clause in pExpr is unaltered. All this routine
  76128. ** does is make slot[] entries point to substructure within pExpr.
  76129. **
  76130. ** In the previous sentence and in the diagram, "slot[]" refers to
  76131. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  76132. ** all terms of the WHERE clause.
  76133. */
  76134. static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  76135. pWC->op = (u8)op;
  76136. if( pExpr==0 ) return;
  76137. if( pExpr->op!=op ){
  76138. whereClauseInsert(pWC, pExpr, 0);
  76139. }else{
  76140. whereSplit(pWC, pExpr->pLeft, op);
  76141. whereSplit(pWC, pExpr->pRight, op);
  76142. }
  76143. }
  76144. /*
  76145. ** Initialize an expression mask set
  76146. */
  76147. #define initMaskSet(P) memset(P, 0, sizeof(*P))
  76148. /*
  76149. ** Return the bitmask for the given cursor number. Return 0 if
  76150. ** iCursor is not in the set.
  76151. */
  76152. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  76153. int i;
  76154. for(i=0; i<pMaskSet->n; i++){
  76155. if( pMaskSet->ix[i]==iCursor ){
  76156. return ((Bitmask)1)<<i;
  76157. }
  76158. }
  76159. return 0;
  76160. }
  76161. /*
  76162. ** Create a new mask for cursor iCursor.
  76163. **
  76164. ** There is one cursor per table in the FROM clause. The number of
  76165. ** tables in the FROM clause is limited by a test early in the
  76166. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  76167. ** array will never overflow.
  76168. */
  76169. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  76170. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  76171. pMaskSet->ix[pMaskSet->n++] = iCursor;
  76172. }
  76173. /*
  76174. ** This routine walks (recursively) an expression tree and generates
  76175. ** a bitmask indicating which tables are used in that expression
  76176. ** tree.
  76177. **
  76178. ** In order for this routine to work, the calling function must have
  76179. ** previously invoked sqlite3ResolveExprNames() on the expression. See
  76180. ** the header comment on that routine for additional information.
  76181. ** The sqlite3ResolveExprNames() routines looks for column names and
  76182. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  76183. ** the VDBE cursor number of the table. This routine just has to
  76184. ** translate the cursor numbers into bitmask values and OR all
  76185. ** the bitmasks together.
  76186. */
  76187. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  76188. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  76189. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  76190. Bitmask mask = 0;
  76191. if( p==0 ) return 0;
  76192. if( p->op==TK_COLUMN ){
  76193. mask = getMask(pMaskSet, p->iTable);
  76194. return mask;
  76195. }
  76196. mask = exprTableUsage(pMaskSet, p->pRight);
  76197. mask |= exprTableUsage(pMaskSet, p->pLeft);
  76198. if( ExprHasProperty(p, EP_xIsSelect) ){
  76199. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  76200. }else{
  76201. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  76202. }
  76203. return mask;
  76204. }
  76205. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  76206. int i;
  76207. Bitmask mask = 0;
  76208. if( pList ){
  76209. for(i=0; i<pList->nExpr; i++){
  76210. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  76211. }
  76212. }
  76213. return mask;
  76214. }
  76215. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  76216. Bitmask mask = 0;
  76217. while( pS ){
  76218. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  76219. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  76220. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  76221. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  76222. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  76223. pS = pS->pPrior;
  76224. }
  76225. return mask;
  76226. }
  76227. /*
  76228. ** Return TRUE if the given operator is one of the operators that is
  76229. ** allowed for an indexable WHERE clause term. The allowed operators are
  76230. ** "=", "<", ">", "<=", ">=", and "IN".
  76231. */
  76232. static int allowedOp(int op){
  76233. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  76234. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  76235. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  76236. assert( TK_GE==TK_EQ+4 );
  76237. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  76238. }
  76239. /*
  76240. ** Swap two objects of type TYPE.
  76241. */
  76242. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  76243. /*
  76244. ** Commute a comparison operator. Expressions of the form "X op Y"
  76245. ** are converted into "Y op X".
  76246. **
  76247. ** If a collation sequence is associated with either the left or right
  76248. ** side of the comparison, it remains associated with the same side after
  76249. ** the commutation. So "Y collate NOCASE op X" becomes
  76250. ** "X collate NOCASE op Y". This is because any collation sequence on
  76251. ** the left hand side of a comparison overrides any collation sequence
  76252. ** attached to the right. For the same reason the EP_ExpCollate flag
  76253. ** is not commuted.
  76254. */
  76255. static void exprCommute(Parse *pParse, Expr *pExpr){
  76256. u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
  76257. u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
  76258. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  76259. pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  76260. pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  76261. SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
  76262. pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
  76263. pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
  76264. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  76265. if( pExpr->op>=TK_GT ){
  76266. assert( TK_LT==TK_GT+2 );
  76267. assert( TK_GE==TK_LE+2 );
  76268. assert( TK_GT>TK_EQ );
  76269. assert( TK_GT<TK_LE );
  76270. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  76271. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  76272. }
  76273. }
  76274. /*
  76275. ** Translate from TK_xx operator to WO_xx bitmask.
  76276. */
  76277. static u16 operatorMask(int op){
  76278. u16 c;
  76279. assert( allowedOp(op) );
  76280. if( op==TK_IN ){
  76281. c = WO_IN;
  76282. }else if( op==TK_ISNULL ){
  76283. c = WO_ISNULL;
  76284. }else{
  76285. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  76286. c = (u16)(WO_EQ<<(op-TK_EQ));
  76287. }
  76288. assert( op!=TK_ISNULL || c==WO_ISNULL );
  76289. assert( op!=TK_IN || c==WO_IN );
  76290. assert( op!=TK_EQ || c==WO_EQ );
  76291. assert( op!=TK_LT || c==WO_LT );
  76292. assert( op!=TK_LE || c==WO_LE );
  76293. assert( op!=TK_GT || c==WO_GT );
  76294. assert( op!=TK_GE || c==WO_GE );
  76295. return c;
  76296. }
  76297. /*
  76298. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  76299. ** where X is a reference to the iColumn of table iCur and <op> is one of
  76300. ** the WO_xx operator codes specified by the op parameter.
  76301. ** Return a pointer to the term. Return 0 if not found.
  76302. */
  76303. static WhereTerm *findTerm(
  76304. WhereClause *pWC, /* The WHERE clause to be searched */
  76305. int iCur, /* Cursor number of LHS */
  76306. int iColumn, /* Column number of LHS */
  76307. Bitmask notReady, /* RHS must not overlap with this mask */
  76308. u32 op, /* Mask of WO_xx values describing operator */
  76309. Index *pIdx /* Must be compatible with this index, if not NULL */
  76310. ){
  76311. WhereTerm *pTerm;
  76312. int k;
  76313. assert( iCur>=0 );
  76314. op &= WO_ALL;
  76315. for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
  76316. if( pTerm->leftCursor==iCur
  76317. && (pTerm->prereqRight & notReady)==0
  76318. && pTerm->u.leftColumn==iColumn
  76319. && (pTerm->eOperator & op)!=0
  76320. ){
  76321. if( pIdx && pTerm->eOperator!=WO_ISNULL ){
  76322. Expr *pX = pTerm->pExpr;
  76323. CollSeq *pColl;
  76324. char idxaff;
  76325. int j;
  76326. Parse *pParse = pWC->pParse;
  76327. idxaff = pIdx->pTable->aCol[iColumn].affinity;
  76328. if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
  76329. /* Figure out the collation sequence required from an index for
  76330. ** it to be useful for optimising expression pX. Store this
  76331. ** value in variable pColl.
  76332. */
  76333. assert(pX->pLeft);
  76334. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  76335. assert(pColl || pParse->nErr);
  76336. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  76337. if( NEVER(j>=pIdx->nColumn) ) return 0;
  76338. }
  76339. if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
  76340. }
  76341. return pTerm;
  76342. }
  76343. }
  76344. return 0;
  76345. }
  76346. /* Forward reference */
  76347. static void exprAnalyze(SrcList*, WhereClause*, int);
  76348. /*
  76349. ** Call exprAnalyze on all terms in a WHERE clause.
  76350. **
  76351. **
  76352. */
  76353. static void exprAnalyzeAll(
  76354. SrcList *pTabList, /* the FROM clause */
  76355. WhereClause *pWC /* the WHERE clause to be analyzed */
  76356. ){
  76357. int i;
  76358. for(i=pWC->nTerm-1; i>=0; i--){
  76359. exprAnalyze(pTabList, pWC, i);
  76360. }
  76361. }
  76362. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  76363. /*
  76364. ** Check to see if the given expression is a LIKE or GLOB operator that
  76365. ** can be optimized using inequality constraints. Return TRUE if it is
  76366. ** so and false if not.
  76367. **
  76368. ** In order for the operator to be optimizible, the RHS must be a string
  76369. ** literal that does not begin with a wildcard.
  76370. */
  76371. static int isLikeOrGlob(
  76372. Parse *pParse, /* Parsing and code generating context */
  76373. Expr *pExpr, /* Test this expression */
  76374. int *pnPattern, /* Number of non-wildcard prefix characters */
  76375. int *pisComplete, /* True if the only wildcard is % in the last character */
  76376. int *pnoCase /* True if uppercase is equivalent to lowercase */
  76377. ){
  76378. const char *z; /* String on RHS of LIKE operator */
  76379. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  76380. ExprList *pList; /* List of operands to the LIKE operator */
  76381. int c; /* One character in z[] */
  76382. int cnt; /* Number of non-wildcard prefix characters */
  76383. char wc[3]; /* Wildcard characters */
  76384. CollSeq *pColl; /* Collating sequence for LHS */
  76385. sqlite3 *db = pParse->db; /* Database connection */
  76386. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  76387. return 0;
  76388. }
  76389. #ifdef SQLITE_EBCDIC
  76390. if( *pnoCase ) return 0;
  76391. #endif
  76392. pList = pExpr->x.pList;
  76393. pRight = pList->a[0].pExpr;
  76394. if( pRight->op!=TK_STRING ){
  76395. return 0;
  76396. }
  76397. pLeft = pList->a[1].pExpr;
  76398. if( pLeft->op!=TK_COLUMN ){
  76399. return 0;
  76400. }
  76401. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  76402. assert( pColl!=0 || pLeft->iColumn==-1 );
  76403. if( pColl==0 ){
  76404. /* No collation is defined for the ROWID. Use the default. */
  76405. pColl = db->pDfltColl;
  76406. }
  76407. if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
  76408. (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
  76409. return 0;
  76410. }
  76411. sqlite3DequoteExpr(pRight);
  76412. z = (char *)pRight->token.z;
  76413. cnt = 0;
  76414. if( z ){
  76415. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
  76416. }
  76417. if( cnt==0 || 255==(u8)z[cnt-1] ){
  76418. return 0;
  76419. }
  76420. *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
  76421. *pnPattern = cnt;
  76422. return 1;
  76423. }
  76424. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  76425. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76426. /*
  76427. ** Check to see if the given expression is of the form
  76428. **
  76429. ** column MATCH expr
  76430. **
  76431. ** If it is then return TRUE. If not, return FALSE.
  76432. */
  76433. static int isMatchOfColumn(
  76434. Expr *pExpr /* Test this expression */
  76435. ){
  76436. ExprList *pList;
  76437. if( pExpr->op!=TK_FUNCTION ){
  76438. return 0;
  76439. }
  76440. if( pExpr->token.n!=5 ||
  76441. sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
  76442. return 0;
  76443. }
  76444. pList = pExpr->x.pList;
  76445. if( pList->nExpr!=2 ){
  76446. return 0;
  76447. }
  76448. if( pList->a[1].pExpr->op != TK_COLUMN ){
  76449. return 0;
  76450. }
  76451. return 1;
  76452. }
  76453. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  76454. /*
  76455. ** If the pBase expression originated in the ON or USING clause of
  76456. ** a join, then transfer the appropriate markings over to derived.
  76457. */
  76458. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  76459. pDerived->flags |= pBase->flags & EP_FromJoin;
  76460. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  76461. }
  76462. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  76463. /*
  76464. ** Analyze a term that consists of two or more OR-connected
  76465. ** subterms. So in:
  76466. **
  76467. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  76468. ** ^^^^^^^^^^^^^^^^^^^^
  76469. **
  76470. ** This routine analyzes terms such as the middle term in the above example.
  76471. ** A WhereOrTerm object is computed and attached to the term under
  76472. ** analysis, regardless of the outcome of the analysis. Hence:
  76473. **
  76474. ** WhereTerm.wtFlags |= TERM_ORINFO
  76475. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  76476. **
  76477. ** The term being analyzed must have two or more of OR-connected subterms.
  76478. ** A single subterm might be a set of AND-connected sub-subterms.
  76479. ** Examples of terms under analysis:
  76480. **
  76481. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  76482. ** (B) x=expr1 OR expr2=x OR x=expr3
  76483. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  76484. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  76485. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  76486. **
  76487. ** CASE 1:
  76488. **
  76489. ** If all subterms are of the form T.C=expr for some single column of C
  76490. ** a single table T (as shown in example B above) then create a new virtual
  76491. ** term that is an equivalent IN expression. In other words, if the term
  76492. ** being analyzed is:
  76493. **
  76494. ** x = expr1 OR expr2 = x OR x = expr3
  76495. **
  76496. ** then create a new virtual term like this:
  76497. **
  76498. ** x IN (expr1,expr2,expr3)
  76499. **
  76500. ** CASE 2:
  76501. **
  76502. ** If all subterms are indexable by a single table T, then set
  76503. **
  76504. ** WhereTerm.eOperator = WO_OR
  76505. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  76506. **
  76507. ** A subterm is "indexable" if it is of the form
  76508. ** "T.C <op> <expr>" where C is any column of table T and
  76509. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  76510. ** A subterm is also indexable if it is an AND of two or more
  76511. ** subsubterms at least one of which is indexable. Indexable AND
  76512. ** subterms have their eOperator set to WO_AND and they have
  76513. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  76514. **
  76515. ** From another point of view, "indexable" means that the subterm could
  76516. ** potentially be used with an index if an appropriate index exists.
  76517. ** This analysis does not consider whether or not the index exists; that
  76518. ** is something the bestIndex() routine will determine. This analysis
  76519. ** only looks at whether subterms appropriate for indexing exist.
  76520. **
  76521. ** All examples A through E above all satisfy case 2. But if a term
  76522. ** also statisfies case 1 (such as B) we know that the optimizer will
  76523. ** always prefer case 1, so in that case we pretend that case 2 is not
  76524. ** satisfied.
  76525. **
  76526. ** It might be the case that multiple tables are indexable. For example,
  76527. ** (E) above is indexable on tables P, Q, and R.
  76528. **
  76529. ** Terms that satisfy case 2 are candidates for lookup by using
  76530. ** separate indices to find rowids for each subterm and composing
  76531. ** the union of all rowids using a RowSet object. This is similar
  76532. ** to "bitmap indices" in other database engines.
  76533. **
  76534. ** OTHERWISE:
  76535. **
  76536. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  76537. ** zero. This term is not useful for search.
  76538. */
  76539. static void exprAnalyzeOrTerm(
  76540. SrcList *pSrc, /* the FROM clause */
  76541. WhereClause *pWC, /* the complete WHERE clause */
  76542. int idxTerm /* Index of the OR-term to be analyzed */
  76543. ){
  76544. Parse *pParse = pWC->pParse; /* Parser context */
  76545. sqlite3 *db = pParse->db; /* Database connection */
  76546. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  76547. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  76548. WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
  76549. int i; /* Loop counters */
  76550. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  76551. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  76552. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  76553. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  76554. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  76555. /*
  76556. ** Break the OR clause into its separate subterms. The subterms are
  76557. ** stored in a WhereClause structure containing within the WhereOrInfo
  76558. ** object that is attached to the original OR clause term.
  76559. */
  76560. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  76561. assert( pExpr->op==TK_OR );
  76562. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  76563. if( pOrInfo==0 ) return;
  76564. pTerm->wtFlags |= TERM_ORINFO;
  76565. pOrWc = &pOrInfo->wc;
  76566. whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
  76567. whereSplit(pOrWc, pExpr, TK_OR);
  76568. exprAnalyzeAll(pSrc, pOrWc);
  76569. if( db->mallocFailed ) return;
  76570. assert( pOrWc->nTerm>=2 );
  76571. /*
  76572. ** Compute the set of tables that might satisfy cases 1 or 2.
  76573. */
  76574. indexable = chngToIN = ~(Bitmask)0;
  76575. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  76576. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  76577. WhereAndInfo *pAndInfo;
  76578. assert( pOrTerm->eOperator==0 );
  76579. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  76580. chngToIN = 0;
  76581. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  76582. if( pAndInfo ){
  76583. WhereClause *pAndWC;
  76584. WhereTerm *pAndTerm;
  76585. int j;
  76586. Bitmask b = 0;
  76587. pOrTerm->u.pAndInfo = pAndInfo;
  76588. pOrTerm->wtFlags |= TERM_ANDINFO;
  76589. pOrTerm->eOperator = WO_AND;
  76590. pAndWC = &pAndInfo->wc;
  76591. whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
  76592. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  76593. exprAnalyzeAll(pSrc, pAndWC);
  76594. testcase( db->mallocFailed );
  76595. if( !db->mallocFailed ){
  76596. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  76597. assert( pAndTerm->pExpr );
  76598. if( allowedOp(pAndTerm->pExpr->op) ){
  76599. b |= getMask(pMaskSet, pAndTerm->leftCursor);
  76600. }
  76601. }
  76602. }
  76603. indexable &= b;
  76604. }
  76605. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  76606. /* Skip this term for now. We revisit it when we process the
  76607. ** corresponding TERM_VIRTUAL term */
  76608. }else{
  76609. Bitmask b;
  76610. b = getMask(pMaskSet, pOrTerm->leftCursor);
  76611. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  76612. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  76613. b |= getMask(pMaskSet, pOther->leftCursor);
  76614. }
  76615. indexable &= b;
  76616. if( pOrTerm->eOperator!=WO_EQ ){
  76617. chngToIN = 0;
  76618. }else{
  76619. chngToIN &= b;
  76620. }
  76621. }
  76622. }
  76623. /*
  76624. ** Record the set of tables that satisfy case 2. The set might be
  76625. ** empty.
  76626. */
  76627. pOrInfo->indexable = indexable;
  76628. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  76629. /*
  76630. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  76631. ** we have to do some additional checking to see if case 1 really
  76632. ** is satisfied.
  76633. */
  76634. if( chngToIN ){
  76635. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  76636. int iColumn = -1; /* Column index on lhs of IN operator */
  76637. int iCursor = -1; /* Table cursor common to all terms */
  76638. int j = 0; /* Loop counter */
  76639. /* Search for a table and column that appears on one side or the
  76640. ** other of the == operator in every subterm. That table and column
  76641. ** will be recorded in iCursor and iColumn. There might not be any
  76642. ** such table and column. Set okToChngToIN if an appropriate table
  76643. ** and column is found but leave okToChngToIN false if not found.
  76644. */
  76645. for(j=0; j<2 && !okToChngToIN; j++){
  76646. pOrTerm = pOrWc->a;
  76647. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  76648. assert( pOrTerm->eOperator==WO_EQ );
  76649. pOrTerm->wtFlags &= ~TERM_OR_OK;
  76650. if( pOrTerm->leftCursor==iColumn ) continue;
  76651. if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ) continue;
  76652. iColumn = pOrTerm->u.leftColumn;
  76653. iCursor = pOrTerm->leftCursor;
  76654. break;
  76655. }
  76656. if( i<0 ){
  76657. assert( j==1 );
  76658. assert( (chngToIN&(chngToIN-1))==0 );
  76659. assert( chngToIN==getMask(pMaskSet, iColumn) );
  76660. break;
  76661. }
  76662. okToChngToIN = 1;
  76663. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  76664. assert( pOrTerm->eOperator==WO_EQ );
  76665. if( pOrTerm->leftCursor!=iCursor ){
  76666. pOrTerm->wtFlags &= ~TERM_OR_OK;
  76667. }else if( pOrTerm->u.leftColumn!=iColumn ){
  76668. okToChngToIN = 0;
  76669. }else{
  76670. int affLeft, affRight;
  76671. /* If the right-hand side is also a column, then the affinities
  76672. ** of both right and left sides must be such that no type
  76673. ** conversions are required on the right. (Ticket #2249)
  76674. */
  76675. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  76676. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  76677. if( affRight!=0 && affRight!=affLeft ){
  76678. okToChngToIN = 0;
  76679. }else{
  76680. pOrTerm->wtFlags |= TERM_OR_OK;
  76681. }
  76682. }
  76683. }
  76684. }
  76685. /* At this point, okToChngToIN is true if original pTerm satisfies
  76686. ** case 1. In that case, construct a new virtual term that is
  76687. ** pTerm converted into an IN operator.
  76688. */
  76689. if( okToChngToIN ){
  76690. Expr *pDup; /* A transient duplicate expression */
  76691. ExprList *pList = 0; /* The RHS of the IN operator */
  76692. Expr *pLeft = 0; /* The LHS of the IN operator */
  76693. Expr *pNew; /* The complete IN operator */
  76694. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  76695. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  76696. assert( pOrTerm->eOperator==WO_EQ );
  76697. assert( pOrTerm->leftCursor==iCursor );
  76698. assert( pOrTerm->u.leftColumn==iColumn );
  76699. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  76700. pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
  76701. pLeft = pOrTerm->pExpr->pLeft;
  76702. }
  76703. assert( pLeft!=0 );
  76704. pDup = sqlite3ExprDup(db, pLeft, 0);
  76705. pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
  76706. if( pNew ){
  76707. int idxNew;
  76708. transferJoinMarkings(pNew, pExpr);
  76709. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  76710. pNew->x.pList = pList;
  76711. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  76712. testcase( idxNew==0 );
  76713. exprAnalyze(pSrc, pWC, idxNew);
  76714. pTerm = &pWC->a[idxTerm];
  76715. pWC->a[idxNew].iParent = idxTerm;
  76716. pTerm->nChild = 1;
  76717. }else{
  76718. sqlite3ExprListDelete(db, pList);
  76719. }
  76720. pTerm->eOperator = 0; /* case 1 trumps case 2 */
  76721. }
  76722. }
  76723. }
  76724. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  76725. /*
  76726. ** The input to this routine is an WhereTerm structure with only the
  76727. ** "pExpr" field filled in. The job of this routine is to analyze the
  76728. ** subexpression and populate all the other fields of the WhereTerm
  76729. ** structure.
  76730. **
  76731. ** If the expression is of the form "<expr> <op> X" it gets commuted
  76732. ** to the standard form of "X <op> <expr>".
  76733. **
  76734. ** If the expression is of the form "X <op> Y" where both X and Y are
  76735. ** columns, then the original expression is unchanged and a new virtual
  76736. ** term of the form "Y <op> X" is added to the WHERE clause and
  76737. ** analyzed separately. The original term is marked with TERM_COPIED
  76738. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  76739. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  76740. ** is a commuted copy of a prior term.) The original term has nChild=1
  76741. ** and the copy has idxParent set to the index of the original term.
  76742. */
  76743. static void exprAnalyze(
  76744. SrcList *pSrc, /* the FROM clause */
  76745. WhereClause *pWC, /* the WHERE clause */
  76746. int idxTerm /* Index of the term to be analyzed */
  76747. ){
  76748. WhereTerm *pTerm; /* The term to be analyzed */
  76749. WhereMaskSet *pMaskSet; /* Set of table index masks */
  76750. Expr *pExpr; /* The expression to be analyzed */
  76751. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  76752. Bitmask prereqAll; /* Prerequesites of pExpr */
  76753. Bitmask extraRight = 0;
  76754. int nPattern;
  76755. int isComplete;
  76756. int noCase;
  76757. int op; /* Top-level operator. pExpr->op */
  76758. Parse *pParse = pWC->pParse; /* Parsing context */
  76759. sqlite3 *db = pParse->db; /* Database connection */
  76760. if( db->mallocFailed ){
  76761. return;
  76762. }
  76763. pTerm = &pWC->a[idxTerm];
  76764. pMaskSet = pWC->pMaskSet;
  76765. pExpr = pTerm->pExpr;
  76766. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  76767. op = pExpr->op;
  76768. if( op==TK_IN ){
  76769. assert( pExpr->pRight==0 );
  76770. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  76771. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  76772. }else{
  76773. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  76774. }
  76775. }else if( op==TK_ISNULL ){
  76776. pTerm->prereqRight = 0;
  76777. }else{
  76778. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  76779. }
  76780. prereqAll = exprTableUsage(pMaskSet, pExpr);
  76781. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  76782. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  76783. prereqAll |= x;
  76784. extraRight = x-1; /* ON clause terms may not be used with an index
  76785. ** on left table of a LEFT JOIN. Ticket #3015 */
  76786. }
  76787. pTerm->prereqAll = prereqAll;
  76788. pTerm->leftCursor = -1;
  76789. pTerm->iParent = -1;
  76790. pTerm->eOperator = 0;
  76791. if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
  76792. Expr *pLeft = pExpr->pLeft;
  76793. Expr *pRight = pExpr->pRight;
  76794. if( pLeft->op==TK_COLUMN ){
  76795. pTerm->leftCursor = pLeft->iTable;
  76796. pTerm->u.leftColumn = pLeft->iColumn;
  76797. pTerm->eOperator = operatorMask(op);
  76798. }
  76799. if( pRight && pRight->op==TK_COLUMN ){
  76800. WhereTerm *pNew;
  76801. Expr *pDup;
  76802. if( pTerm->leftCursor>=0 ){
  76803. int idxNew;
  76804. pDup = sqlite3ExprDup(db, pExpr, 0);
  76805. if( db->mallocFailed ){
  76806. sqlite3ExprDelete(db, pDup);
  76807. return;
  76808. }
  76809. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  76810. if( idxNew==0 ) return;
  76811. pNew = &pWC->a[idxNew];
  76812. pNew->iParent = idxTerm;
  76813. pTerm = &pWC->a[idxTerm];
  76814. pTerm->nChild = 1;
  76815. pTerm->wtFlags |= TERM_COPIED;
  76816. }else{
  76817. pDup = pExpr;
  76818. pNew = pTerm;
  76819. }
  76820. exprCommute(pParse, pDup);
  76821. pLeft = pDup->pLeft;
  76822. pNew->leftCursor = pLeft->iTable;
  76823. pNew->u.leftColumn = pLeft->iColumn;
  76824. pNew->prereqRight = prereqLeft;
  76825. pNew->prereqAll = prereqAll;
  76826. pNew->eOperator = operatorMask(pDup->op);
  76827. }
  76828. }
  76829. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  76830. /* If a term is the BETWEEN operator, create two new virtual terms
  76831. ** that define the range that the BETWEEN implements. For example:
  76832. **
  76833. ** a BETWEEN b AND c
  76834. **
  76835. ** is converted into:
  76836. **
  76837. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  76838. **
  76839. ** The two new terms are added onto the end of the WhereClause object.
  76840. ** The new terms are "dynamic" and are children of the original BETWEEN
  76841. ** term. That means that if the BETWEEN term is coded, the children are
  76842. ** skipped. Or, if the children are satisfied by an index, the original
  76843. ** BETWEEN term is skipped.
  76844. */
  76845. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  76846. ExprList *pList = pExpr->x.pList;
  76847. int i;
  76848. static const u8 ops[] = {TK_GE, TK_LE};
  76849. assert( pList!=0 );
  76850. assert( pList->nExpr==2 );
  76851. for(i=0; i<2; i++){
  76852. Expr *pNewExpr;
  76853. int idxNew;
  76854. pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft, 0),
  76855. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  76856. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  76857. testcase( idxNew==0 );
  76858. exprAnalyze(pSrc, pWC, idxNew);
  76859. pTerm = &pWC->a[idxTerm];
  76860. pWC->a[idxNew].iParent = idxTerm;
  76861. }
  76862. pTerm->nChild = 2;
  76863. }
  76864. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  76865. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  76866. /* Analyze a term that is composed of two or more subterms connected by
  76867. ** an OR operator.
  76868. */
  76869. else if( pExpr->op==TK_OR ){
  76870. assert( pWC->op==TK_AND );
  76871. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  76872. }
  76873. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  76874. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  76875. /* Add constraints to reduce the search space on a LIKE or GLOB
  76876. ** operator.
  76877. **
  76878. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  76879. **
  76880. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  76881. **
  76882. ** The last character of the prefix "abc" is incremented to form the
  76883. ** termination condition "abd".
  76884. */
  76885. if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase)
  76886. && pWC->op==TK_AND ){
  76887. Expr *pLeft, *pRight;
  76888. Expr *pStr1, *pStr2;
  76889. Expr *pNewExpr1, *pNewExpr2;
  76890. int idxNew1, idxNew2;
  76891. pLeft = pExpr->x.pList->a[1].pExpr;
  76892. pRight = pExpr->x.pList->a[0].pExpr;
  76893. pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
  76894. if( pStr1 ){
  76895. sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
  76896. pStr1->token.n = nPattern;
  76897. pStr1->flags = EP_Dequoted;
  76898. }
  76899. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  76900. if( !db->mallocFailed ){
  76901. u8 c, *pC;
  76902. /* assert( pStr2->token.dyn ); */
  76903. pC = (u8*)&pStr2->token.z[nPattern-1];
  76904. c = *pC;
  76905. if( noCase ){
  76906. if( c=='@' ) isComplete = 0;
  76907. c = sqlite3UpperToLower[c];
  76908. }
  76909. *pC = c + 1;
  76910. }
  76911. pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
  76912. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  76913. testcase( idxNew1==0 );
  76914. exprAnalyze(pSrc, pWC, idxNew1);
  76915. pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
  76916. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  76917. testcase( idxNew2==0 );
  76918. exprAnalyze(pSrc, pWC, idxNew2);
  76919. pTerm = &pWC->a[idxTerm];
  76920. if( isComplete ){
  76921. pWC->a[idxNew1].iParent = idxTerm;
  76922. pWC->a[idxNew2].iParent = idxTerm;
  76923. pTerm->nChild = 2;
  76924. }
  76925. }
  76926. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  76927. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76928. /* Add a WO_MATCH auxiliary term to the constraint set if the
  76929. ** current expression is of the form: column MATCH expr.
  76930. ** This information is used by the xBestIndex methods of
  76931. ** virtual tables. The native query optimizer does not attempt
  76932. ** to do anything with MATCH functions.
  76933. */
  76934. if( isMatchOfColumn(pExpr) ){
  76935. int idxNew;
  76936. Expr *pRight, *pLeft;
  76937. WhereTerm *pNewTerm;
  76938. Bitmask prereqColumn, prereqExpr;
  76939. pRight = pExpr->x.pList->a[0].pExpr;
  76940. pLeft = pExpr->x.pList->a[1].pExpr;
  76941. prereqExpr = exprTableUsage(pMaskSet, pRight);
  76942. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  76943. if( (prereqExpr & prereqColumn)==0 ){
  76944. Expr *pNewExpr;
  76945. pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight, 0), 0);
  76946. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  76947. testcase( idxNew==0 );
  76948. pNewTerm = &pWC->a[idxNew];
  76949. pNewTerm->prereqRight = prereqExpr;
  76950. pNewTerm->leftCursor = pLeft->iTable;
  76951. pNewTerm->u.leftColumn = pLeft->iColumn;
  76952. pNewTerm->eOperator = WO_MATCH;
  76953. pNewTerm->iParent = idxTerm;
  76954. pTerm = &pWC->a[idxTerm];
  76955. pTerm->nChild = 1;
  76956. pTerm->wtFlags |= TERM_COPIED;
  76957. pNewTerm->prereqAll = pTerm->prereqAll;
  76958. }
  76959. }
  76960. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  76961. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  76962. ** an index for tables to the left of the join.
  76963. */
  76964. pTerm->prereqRight |= extraRight;
  76965. }
  76966. /*
  76967. ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
  76968. ** a reference to any table other than the iBase table.
  76969. */
  76970. static int referencesOtherTables(
  76971. ExprList *pList, /* Search expressions in ths list */
  76972. WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
  76973. int iFirst, /* Be searching with the iFirst-th expression */
  76974. int iBase /* Ignore references to this table */
  76975. ){
  76976. Bitmask allowed = ~getMask(pMaskSet, iBase);
  76977. while( iFirst<pList->nExpr ){
  76978. if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
  76979. return 1;
  76980. }
  76981. }
  76982. return 0;
  76983. }
  76984. /*
  76985. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  76986. ** clause. If it can, it returns 1. If pIdx cannot satisfy the
  76987. ** ORDER BY clause, this routine returns 0.
  76988. **
  76989. ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
  76990. ** left-most table in the FROM clause of that same SELECT statement and
  76991. ** the table has a cursor number of "base". pIdx is an index on pTab.
  76992. **
  76993. ** nEqCol is the number of columns of pIdx that are used as equality
  76994. ** constraints. Any of these columns may be missing from the ORDER BY
  76995. ** clause and the match can still be a success.
  76996. **
  76997. ** All terms of the ORDER BY that match against the index must be either
  76998. ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
  76999. ** index do not need to satisfy this constraint.) The *pbRev value is
  77000. ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
  77001. ** the ORDER BY clause is all ASC.
  77002. */
  77003. static int isSortingIndex(
  77004. Parse *pParse, /* Parsing context */
  77005. WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
  77006. Index *pIdx, /* The index we are testing */
  77007. int base, /* Cursor number for the table to be sorted */
  77008. ExprList *pOrderBy, /* The ORDER BY clause */
  77009. int nEqCol, /* Number of index columns with == constraints */
  77010. int *pbRev /* Set to 1 if ORDER BY is DESC */
  77011. ){
  77012. int i, j; /* Loop counters */
  77013. int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
  77014. int nTerm; /* Number of ORDER BY terms */
  77015. struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
  77016. sqlite3 *db = pParse->db;
  77017. assert( pOrderBy!=0 );
  77018. nTerm = pOrderBy->nExpr;
  77019. assert( nTerm>0 );
  77020. /* Match terms of the ORDER BY clause against columns of
  77021. ** the index.
  77022. **
  77023. ** Note that indices have pIdx->nColumn regular columns plus
  77024. ** one additional column containing the rowid. The rowid column
  77025. ** of the index is also allowed to match against the ORDER BY
  77026. ** clause.
  77027. */
  77028. for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
  77029. Expr *pExpr; /* The expression of the ORDER BY pTerm */
  77030. CollSeq *pColl; /* The collating sequence of pExpr */
  77031. int termSortOrder; /* Sort order for this term */
  77032. int iColumn; /* The i-th column of the index. -1 for rowid */
  77033. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  77034. const char *zColl; /* Name of the collating sequence for i-th index term */
  77035. pExpr = pTerm->pExpr;
  77036. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
  77037. /* Can not use an index sort on anything that is not a column in the
  77038. ** left-most table of the FROM clause */
  77039. break;
  77040. }
  77041. pColl = sqlite3ExprCollSeq(pParse, pExpr);
  77042. if( !pColl ){
  77043. pColl = db->pDfltColl;
  77044. }
  77045. if( i<pIdx->nColumn ){
  77046. iColumn = pIdx->aiColumn[i];
  77047. if( iColumn==pIdx->pTable->iPKey ){
  77048. iColumn = -1;
  77049. }
  77050. iSortOrder = pIdx->aSortOrder[i];
  77051. zColl = pIdx->azColl[i];
  77052. }else{
  77053. iColumn = -1;
  77054. iSortOrder = 0;
  77055. zColl = pColl->zName;
  77056. }
  77057. if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
  77058. /* Term j of the ORDER BY clause does not match column i of the index */
  77059. if( i<nEqCol ){
  77060. /* If an index column that is constrained by == fails to match an
  77061. ** ORDER BY term, that is OK. Just ignore that column of the index
  77062. */
  77063. continue;
  77064. }else if( i==pIdx->nColumn ){
  77065. /* Index column i is the rowid. All other terms match. */
  77066. break;
  77067. }else{
  77068. /* If an index column fails to match and is not constrained by ==
  77069. ** then the index cannot satisfy the ORDER BY constraint.
  77070. */
  77071. return 0;
  77072. }
  77073. }
  77074. assert( pIdx->aSortOrder!=0 );
  77075. assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
  77076. assert( iSortOrder==0 || iSortOrder==1 );
  77077. termSortOrder = iSortOrder ^ pTerm->sortOrder;
  77078. if( i>nEqCol ){
  77079. if( termSortOrder!=sortOrder ){
  77080. /* Indices can only be used if all ORDER BY terms past the
  77081. ** equality constraints are all either DESC or ASC. */
  77082. return 0;
  77083. }
  77084. }else{
  77085. sortOrder = termSortOrder;
  77086. }
  77087. j++;
  77088. pTerm++;
  77089. if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  77090. /* If the indexed column is the primary key and everything matches
  77091. ** so far and none of the ORDER BY terms to the right reference other
  77092. ** tables in the join, then we are assured that the index can be used
  77093. ** to sort because the primary key is unique and so none of the other
  77094. ** columns will make any difference
  77095. */
  77096. j = nTerm;
  77097. }
  77098. }
  77099. *pbRev = sortOrder!=0;
  77100. if( j>=nTerm ){
  77101. /* All terms of the ORDER BY clause are covered by this index so
  77102. ** this index can be used for sorting. */
  77103. return 1;
  77104. }
  77105. if( pIdx->onError!=OE_None && i==pIdx->nColumn
  77106. && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  77107. /* All terms of this index match some prefix of the ORDER BY clause
  77108. ** and the index is UNIQUE and no terms on the tail of the ORDER BY
  77109. ** clause reference other tables in a join. If this is all true then
  77110. ** the order by clause is superfluous. */
  77111. return 1;
  77112. }
  77113. return 0;
  77114. }
  77115. /*
  77116. ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
  77117. ** by sorting in order of ROWID. Return true if so and set *pbRev to be
  77118. ** true for reverse ROWID and false for forward ROWID order.
  77119. */
  77120. static int sortableByRowid(
  77121. int base, /* Cursor number for table to be sorted */
  77122. ExprList *pOrderBy, /* The ORDER BY clause */
  77123. WhereMaskSet *pMaskSet, /* Mapping from table cursors to bitmaps */
  77124. int *pbRev /* Set to 1 if ORDER BY is DESC */
  77125. ){
  77126. Expr *p;
  77127. assert( pOrderBy!=0 );
  77128. assert( pOrderBy->nExpr>0 );
  77129. p = pOrderBy->a[0].pExpr;
  77130. if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
  77131. && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
  77132. *pbRev = pOrderBy->a[0].sortOrder;
  77133. return 1;
  77134. }
  77135. return 0;
  77136. }
  77137. /*
  77138. ** Prepare a crude estimate of the logarithm of the input value.
  77139. ** The results need not be exact. This is only used for estimating
  77140. ** the total cost of performing operations with O(logN) or O(NlogN)
  77141. ** complexity. Because N is just a guess, it is no great tragedy if
  77142. ** logN is a little off.
  77143. */
  77144. static double estLog(double N){
  77145. double logN = 1;
  77146. double x = 10;
  77147. while( N>x ){
  77148. logN += 1;
  77149. x *= 10;
  77150. }
  77151. return logN;
  77152. }
  77153. /*
  77154. ** Two routines for printing the content of an sqlite3_index_info
  77155. ** structure. Used for testing and debugging only. If neither
  77156. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  77157. ** are no-ops.
  77158. */
  77159. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
  77160. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  77161. int i;
  77162. if( !sqlite3WhereTrace ) return;
  77163. for(i=0; i<p->nConstraint; i++){
  77164. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  77165. i,
  77166. p->aConstraint[i].iColumn,
  77167. p->aConstraint[i].iTermOffset,
  77168. p->aConstraint[i].op,
  77169. p->aConstraint[i].usable);
  77170. }
  77171. for(i=0; i<p->nOrderBy; i++){
  77172. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  77173. i,
  77174. p->aOrderBy[i].iColumn,
  77175. p->aOrderBy[i].desc);
  77176. }
  77177. }
  77178. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  77179. int i;
  77180. if( !sqlite3WhereTrace ) return;
  77181. for(i=0; i<p->nConstraint; i++){
  77182. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  77183. i,
  77184. p->aConstraintUsage[i].argvIndex,
  77185. p->aConstraintUsage[i].omit);
  77186. }
  77187. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  77188. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  77189. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  77190. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  77191. }
  77192. #else
  77193. #define TRACE_IDX_INPUTS(A)
  77194. #define TRACE_IDX_OUTPUTS(A)
  77195. #endif
  77196. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77197. /*
  77198. ** Compute the best index for a virtual table.
  77199. **
  77200. ** The best index is computed by the xBestIndex method of the virtual
  77201. ** table module. This routine is really just a wrapper that sets up
  77202. ** the sqlite3_index_info structure that is used to communicate with
  77203. ** xBestIndex.
  77204. **
  77205. ** In a join, this routine might be called multiple times for the
  77206. ** same virtual table. The sqlite3_index_info structure is created
  77207. ** and initialized on the first invocation and reused on all subsequent
  77208. ** invocations. The sqlite3_index_info structure is also used when
  77209. ** code is generated to access the virtual table. The whereInfoDelete()
  77210. ** routine takes care of freeing the sqlite3_index_info structure after
  77211. ** everybody has finished with it.
  77212. */
  77213. static double bestVirtualIndex(
  77214. Parse *pParse, /* The parsing context */
  77215. WhereClause *pWC, /* The WHERE clause */
  77216. struct SrcList_item *pSrc, /* The FROM clause term to search */
  77217. Bitmask notReady, /* Mask of cursors that are not available */
  77218. ExprList *pOrderBy, /* The order by clause */
  77219. int orderByUsable, /* True if we can potential sort */
  77220. sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
  77221. ){
  77222. Table *pTab = pSrc->pTab;
  77223. sqlite3_vtab *pVtab = pTab->pVtab;
  77224. sqlite3_index_info *pIdxInfo;
  77225. struct sqlite3_index_constraint *pIdxCons;
  77226. struct sqlite3_index_orderby *pIdxOrderBy;
  77227. struct sqlite3_index_constraint_usage *pUsage;
  77228. WhereTerm *pTerm;
  77229. int i, j;
  77230. int nOrderBy;
  77231. int rc;
  77232. /* If the sqlite3_index_info structure has not been previously
  77233. ** allocated and initialized for this virtual table, then allocate
  77234. ** and initialize it now
  77235. */
  77236. pIdxInfo = *ppIdxInfo;
  77237. if( pIdxInfo==0 ){
  77238. int nTerm;
  77239. WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
  77240. /* Count the number of possible WHERE clause constraints referring
  77241. ** to this virtual table */
  77242. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  77243. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  77244. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  77245. testcase( pTerm->eOperator==WO_IN );
  77246. testcase( pTerm->eOperator==WO_ISNULL );
  77247. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  77248. nTerm++;
  77249. }
  77250. /* If the ORDER BY clause contains only columns in the current
  77251. ** virtual table then allocate space for the aOrderBy part of
  77252. ** the sqlite3_index_info structure.
  77253. */
  77254. nOrderBy = 0;
  77255. if( pOrderBy ){
  77256. for(i=0; i<pOrderBy->nExpr; i++){
  77257. Expr *pExpr = pOrderBy->a[i].pExpr;
  77258. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  77259. }
  77260. if( i==pOrderBy->nExpr ){
  77261. nOrderBy = pOrderBy->nExpr;
  77262. }
  77263. }
  77264. /* Allocate the sqlite3_index_info structure
  77265. */
  77266. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  77267. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  77268. + sizeof(*pIdxOrderBy)*nOrderBy );
  77269. if( pIdxInfo==0 ){
  77270. sqlite3ErrorMsg(pParse, "out of memory");
  77271. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  77272. return (double)0;
  77273. }
  77274. *ppIdxInfo = pIdxInfo;
  77275. /* Initialize the structure. The sqlite3_index_info structure contains
  77276. ** many fields that are declared "const" to prevent xBestIndex from
  77277. ** changing them. We have to do some funky casting in order to
  77278. ** initialize those fields.
  77279. */
  77280. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  77281. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  77282. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  77283. *(int*)&pIdxInfo->nConstraint = nTerm;
  77284. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  77285. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  77286. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  77287. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  77288. pUsage;
  77289. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  77290. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  77291. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  77292. testcase( pTerm->eOperator==WO_IN );
  77293. testcase( pTerm->eOperator==WO_ISNULL );
  77294. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  77295. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  77296. pIdxCons[j].iTermOffset = i;
  77297. pIdxCons[j].op = (u8)pTerm->eOperator;
  77298. /* The direct assignment in the previous line is possible only because
  77299. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  77300. ** following asserts verify this fact. */
  77301. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  77302. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  77303. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  77304. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  77305. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  77306. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  77307. assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  77308. j++;
  77309. }
  77310. for(i=0; i<nOrderBy; i++){
  77311. Expr *pExpr = pOrderBy->a[i].pExpr;
  77312. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  77313. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  77314. }
  77315. }
  77316. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  77317. ** to will have been initialized, either during the current invocation or
  77318. ** during some prior invocation. Now we just have to customize the
  77319. ** details of pIdxInfo for the current invocation and pass it to
  77320. ** xBestIndex.
  77321. */
  77322. /* The module name must be defined. Also, by this point there must
  77323. ** be a pointer to an sqlite3_vtab structure. Otherwise
  77324. ** sqlite3ViewGetColumnNames() would have picked up the error.
  77325. */
  77326. assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  77327. assert( pVtab );
  77328. #if 0
  77329. if( pTab->pVtab==0 ){
  77330. sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
  77331. pTab->azModuleArg[0], pTab->zName);
  77332. return 0.0;
  77333. }
  77334. #endif
  77335. /* Set the aConstraint[].usable fields and initialize all
  77336. ** output variables to zero.
  77337. **
  77338. ** aConstraint[].usable is true for constraints where the right-hand
  77339. ** side contains only references to tables to the left of the current
  77340. ** table. In other words, if the constraint is of the form:
  77341. **
  77342. ** column = expr
  77343. **
  77344. ** and we are evaluating a join, then the constraint on column is
  77345. ** only valid if all tables referenced in expr occur to the left
  77346. ** of the table containing column.
  77347. **
  77348. ** The aConstraints[] array contains entries for all constraints
  77349. ** on the current table. That way we only have to compute it once
  77350. ** even though we might try to pick the best index multiple times.
  77351. ** For each attempt at picking an index, the order of tables in the
  77352. ** join might be different so we have to recompute the usable flag
  77353. ** each time.
  77354. */
  77355. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  77356. pUsage = pIdxInfo->aConstraintUsage;
  77357. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  77358. j = pIdxCons->iTermOffset;
  77359. pTerm = &pWC->a[j];
  77360. pIdxCons->usable = (pTerm->prereqRight & notReady)==0 ?1:0;
  77361. }
  77362. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  77363. if( pIdxInfo->needToFreeIdxStr ){
  77364. sqlite3_free(pIdxInfo->idxStr);
  77365. }
  77366. pIdxInfo->idxStr = 0;
  77367. pIdxInfo->idxNum = 0;
  77368. pIdxInfo->needToFreeIdxStr = 0;
  77369. pIdxInfo->orderByConsumed = 0;
  77370. /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
  77371. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
  77372. nOrderBy = pIdxInfo->nOrderBy;
  77373. if( pIdxInfo->nOrderBy && !orderByUsable ){
  77374. *(int*)&pIdxInfo->nOrderBy = 0;
  77375. }
  77376. (void)sqlite3SafetyOff(pParse->db);
  77377. WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  77378. TRACE_IDX_INPUTS(pIdxInfo);
  77379. rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
  77380. TRACE_IDX_OUTPUTS(pIdxInfo);
  77381. (void)sqlite3SafetyOn(pParse->db);
  77382. if( rc!=SQLITE_OK ){
  77383. if( rc==SQLITE_NOMEM ){
  77384. pParse->db->mallocFailed = 1;
  77385. }else if( !pVtab->zErrMsg ){
  77386. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  77387. }else{
  77388. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  77389. }
  77390. }
  77391. sqlite3DbFree(pParse->db, pVtab->zErrMsg);
  77392. pVtab->zErrMsg = 0;
  77393. for(i=0; i<pIdxInfo->nConstraint; i++){
  77394. if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
  77395. sqlite3ErrorMsg(pParse,
  77396. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  77397. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  77398. return (double)0;
  77399. }
  77400. }
  77401. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  77402. return pIdxInfo->estimatedCost;
  77403. }
  77404. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  77405. /*
  77406. ** Find the query plan for accessing a particular table. Write the
  77407. ** best query plan and its cost into the WhereCost object supplied as the
  77408. ** last parameter.
  77409. **
  77410. ** The lowest cost plan wins. The cost is an estimate of the amount of
  77411. ** CPU and disk I/O need to process the request using the selected plan.
  77412. ** Factors that influence cost include:
  77413. **
  77414. ** * The estimated number of rows that will be retrieved. (The
  77415. ** fewer the better.)
  77416. **
  77417. ** * Whether or not sorting must occur.
  77418. **
  77419. ** * Whether or not there must be separate lookups in the
  77420. ** index and in the main table.
  77421. **
  77422. ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
  77423. ** the SQL statement, then this function only considers plans using the
  77424. ** named index. If no such plan is found, then the returned cost is
  77425. ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
  77426. ** then the cost is calculated in the usual way.
  77427. **
  77428. ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
  77429. ** in the SELECT statement, then no indexes are considered. However, the
  77430. ** selected plan may still take advantage of the tables built-in rowid
  77431. ** index.
  77432. */
  77433. static void bestIndex(
  77434. Parse *pParse, /* The parsing context */
  77435. WhereClause *pWC, /* The WHERE clause */
  77436. struct SrcList_item *pSrc, /* The FROM clause term to search */
  77437. Bitmask notReady, /* Mask of cursors that are not available */
  77438. ExprList *pOrderBy, /* The ORDER BY clause */
  77439. WhereCost *pCost /* Lowest cost query plan */
  77440. ){
  77441. WhereTerm *pTerm; /* A single term of the WHERE clause */
  77442. int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  77443. Index *pProbe; /* An index we are evaluating */
  77444. int rev; /* True to scan in reverse order */
  77445. int wsFlags; /* Flags associated with pProbe */
  77446. int nEq; /* Number of == or IN constraints */
  77447. int eqTermMask; /* Mask of valid equality operators */
  77448. double cost; /* Cost of using pProbe */
  77449. double nRow; /* Estimated number of rows in result set */
  77450. int i; /* Loop counter */
  77451. Bitmask maskSrc; /* Bitmask for the pSrc table */
  77452. WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
  77453. pProbe = pSrc->pTab->pIndex;
  77454. if( pSrc->notIndexed ){
  77455. pProbe = 0;
  77456. }
  77457. /* If the table has no indices and there are no terms in the where
  77458. ** clause that refer to the ROWID, then we will never be able to do
  77459. ** anything other than a full table scan on this table. We might as
  77460. ** well put it first in the join order. That way, perhaps it can be
  77461. ** referenced by other tables in the join.
  77462. */
  77463. memset(pCost, 0, sizeof(*pCost));
  77464. if( pProbe==0 &&
  77465. findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
  77466. (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
  77467. if( pParse->db->flags & SQLITE_ReverseOrder ){
  77468. /* For application testing, randomly reverse the output order for
  77469. ** SELECT statements that omit the ORDER BY clause. This will help
  77470. ** to find cases where
  77471. */
  77472. pCost->plan.wsFlags |= WHERE_REVERSE;
  77473. }
  77474. return;
  77475. }
  77476. pCost->rCost = SQLITE_BIG_DBL;
  77477. /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
  77478. ** an INDEXED BY clause attached to this table, skip this step.
  77479. */
  77480. if( !pSrc->pIndex ){
  77481. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  77482. if( pTerm ){
  77483. Expr *pExpr;
  77484. pCost->plan.wsFlags = WHERE_ROWID_EQ;
  77485. if( pTerm->eOperator & WO_EQ ){
  77486. /* Rowid== is always the best pick. Look no further. Because only
  77487. ** a single row is generated, output is always in sorted order */
  77488. pCost->plan.wsFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
  77489. pCost->plan.nEq = 1;
  77490. WHERETRACE(("... best is rowid\n"));
  77491. pCost->rCost = 0;
  77492. pCost->nRow = 1;
  77493. return;
  77494. }else if( !ExprHasProperty((pExpr = pTerm->pExpr), EP_xIsSelect)
  77495. && pExpr->x.pList
  77496. ){
  77497. /* Rowid IN (LIST): cost is NlogN where N is the number of list
  77498. ** elements. */
  77499. pCost->rCost = pCost->nRow = pExpr->x.pList->nExpr;
  77500. pCost->rCost *= estLog(pCost->rCost);
  77501. }else{
  77502. /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
  77503. ** in the result of the inner select. We have no way to estimate
  77504. ** that value so make a wild guess. */
  77505. pCost->nRow = 100;
  77506. pCost->rCost = 200;
  77507. }
  77508. WHERETRACE(("... rowid IN cost: %.9g\n", pCost->rCost));
  77509. }
  77510. /* Estimate the cost of a table scan. If we do not know how many
  77511. ** entries are in the table, use 1 million as a guess.
  77512. */
  77513. cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
  77514. WHERETRACE(("... table scan base cost: %.9g\n", cost));
  77515. wsFlags = WHERE_ROWID_RANGE;
  77516. /* Check for constraints on a range of rowids in a table scan.
  77517. */
  77518. pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
  77519. if( pTerm ){
  77520. if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
  77521. wsFlags |= WHERE_TOP_LIMIT;
  77522. cost /= 3; /* Guess that rowid<EXPR eliminates two-thirds of rows */
  77523. }
  77524. if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
  77525. wsFlags |= WHERE_BTM_LIMIT;
  77526. cost /= 3; /* Guess that rowid>EXPR eliminates two-thirds of rows */
  77527. }
  77528. WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
  77529. }else{
  77530. wsFlags = 0;
  77531. }
  77532. nRow = cost;
  77533. /* If the table scan does not satisfy the ORDER BY clause, increase
  77534. ** the cost by NlogN to cover the expense of sorting. */
  77535. if( pOrderBy ){
  77536. if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
  77537. wsFlags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
  77538. if( rev ){
  77539. wsFlags |= WHERE_REVERSE;
  77540. }
  77541. }else{
  77542. cost += cost*estLog(cost);
  77543. WHERETRACE(("... sorting increases cost to %.9g\n", cost));
  77544. }
  77545. }else if( pParse->db->flags & SQLITE_ReverseOrder ){
  77546. /* For application testing, randomly reverse the output order for
  77547. ** SELECT statements that omit the ORDER BY clause. This will help
  77548. ** to find cases where
  77549. */
  77550. wsFlags |= WHERE_REVERSE;
  77551. }
  77552. /* Remember this case if it is the best so far */
  77553. if( cost<pCost->rCost ){
  77554. pCost->rCost = cost;
  77555. pCost->nRow = nRow;
  77556. pCost->plan.wsFlags = wsFlags;
  77557. }
  77558. }
  77559. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  77560. /* Search for an OR-clause that can be used to look up the table.
  77561. */
  77562. maskSrc = getMask(pWC->pMaskSet, iCur);
  77563. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  77564. WhereClause tempWC;
  77565. tempWC = *pWC;
  77566. if( pTerm->eOperator==WO_OR
  77567. && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
  77568. && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 ){
  77569. WhereClause *pOrWC = &pTerm->u.pOrInfo->wc;
  77570. WhereTerm *pOrTerm;
  77571. int j;
  77572. int sortable = 0;
  77573. double rTotal = 0;
  77574. nRow = 0;
  77575. for(j=0, pOrTerm=pOrWC->a; j<pOrWC->nTerm; j++, pOrTerm++){
  77576. WhereCost sTermCost;
  77577. WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", j,i));
  77578. if( pOrTerm->eOperator==WO_AND ){
  77579. WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
  77580. bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
  77581. }else if( pOrTerm->leftCursor==iCur ){
  77582. tempWC.a = pOrTerm;
  77583. tempWC.nTerm = 1;
  77584. bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
  77585. }else{
  77586. continue;
  77587. }
  77588. rTotal += sTermCost.rCost;
  77589. nRow += sTermCost.nRow;
  77590. if( rTotal>=pCost->rCost ) break;
  77591. }
  77592. if( pOrderBy!=0 ){
  77593. if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) && !rev ){
  77594. sortable = 1;
  77595. }else{
  77596. rTotal += nRow*estLog(nRow);
  77597. WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
  77598. }
  77599. }
  77600. WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n",
  77601. rTotal, nRow));
  77602. if( rTotal<pCost->rCost ){
  77603. pCost->rCost = rTotal;
  77604. pCost->nRow = nRow;
  77605. pCost->plan.wsFlags = WHERE_MULTI_OR;
  77606. pCost->plan.u.pTerm = pTerm;
  77607. if( sortable ){
  77608. pCost->plan.wsFlags = WHERE_ORDERBY|WHERE_MULTI_OR;
  77609. }
  77610. }
  77611. }
  77612. }
  77613. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  77614. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  77615. ** use an index to satisfy IS NULL constraints on that table. This is
  77616. ** because columns might end up being NULL if the table does not match -
  77617. ** a circumstance which the index cannot help us discover. Ticket #2177.
  77618. */
  77619. if( (pSrc->jointype & JT_LEFT)!=0 ){
  77620. eqTermMask = WO_EQ|WO_IN;
  77621. }else{
  77622. eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  77623. }
  77624. /* Look at each index.
  77625. */
  77626. if( pSrc->pIndex ){
  77627. pProbe = pSrc->pIndex;
  77628. }
  77629. for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
  77630. double inMultiplier = 1; /* Number of equality look-ups needed */
  77631. int inMultIsEst = 0; /* True if inMultiplier is an estimate */
  77632. WHERETRACE(("... index %s:\n", pProbe->zName));
  77633. /* Count the number of columns in the index that are satisfied
  77634. ** by x=EXPR constraints or x IN (...) constraints. For a term
  77635. ** of the form x=EXPR we only have to do a single binary search.
  77636. ** But for x IN (...) we have to do a number of binary searched
  77637. ** equal to the number of entries on the RHS of the IN operator.
  77638. ** The inMultipler variable with try to estimate the number of
  77639. ** binary searches needed.
  77640. */
  77641. wsFlags = 0;
  77642. for(i=0; i<pProbe->nColumn; i++){
  77643. int j = pProbe->aiColumn[i];
  77644. pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
  77645. if( pTerm==0 ) break;
  77646. wsFlags |= WHERE_COLUMN_EQ;
  77647. if( pTerm->eOperator & WO_IN ){
  77648. Expr *pExpr = pTerm->pExpr;
  77649. wsFlags |= WHERE_COLUMN_IN;
  77650. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77651. inMultiplier *= 25;
  77652. inMultIsEst = 1;
  77653. }else if( pExpr->x.pList ){
  77654. inMultiplier *= pExpr->x.pList->nExpr + 1;
  77655. }
  77656. }
  77657. }
  77658. nRow = pProbe->aiRowEst[i] * inMultiplier;
  77659. /* If inMultiplier is an estimate and that estimate results in an
  77660. ** nRow it that is more than half number of rows in the table,
  77661. ** then reduce inMultipler */
  77662. if( inMultIsEst && nRow*2 > pProbe->aiRowEst[0] ){
  77663. nRow = pProbe->aiRowEst[0]/2;
  77664. inMultiplier = nRow/pProbe->aiRowEst[i];
  77665. }
  77666. cost = nRow + inMultiplier*estLog(pProbe->aiRowEst[0]);
  77667. nEq = i;
  77668. if( pProbe->onError!=OE_None && (wsFlags & WHERE_COLUMN_IN)==0
  77669. && nEq==pProbe->nColumn ){
  77670. wsFlags |= WHERE_UNIQUE;
  77671. }
  77672. WHERETRACE(("...... nEq=%d inMult=%.9g nRow=%.9g cost=%.9g\n",
  77673. nEq, inMultiplier, nRow, cost));
  77674. /* Look for range constraints. Assume that each range constraint
  77675. ** makes the search space 1/3rd smaller.
  77676. */
  77677. if( nEq<pProbe->nColumn ){
  77678. int j = pProbe->aiColumn[nEq];
  77679. pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
  77680. if( pTerm ){
  77681. wsFlags |= WHERE_COLUMN_RANGE;
  77682. if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
  77683. wsFlags |= WHERE_TOP_LIMIT;
  77684. cost /= 3;
  77685. nRow /= 3;
  77686. }
  77687. if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
  77688. wsFlags |= WHERE_BTM_LIMIT;
  77689. cost /= 3;
  77690. nRow /= 3;
  77691. }
  77692. WHERETRACE(("...... range reduces nRow to %.9g and cost to %.9g\n",
  77693. nRow, cost));
  77694. }
  77695. }
  77696. /* Add the additional cost of sorting if that is a factor.
  77697. */
  77698. if( pOrderBy ){
  77699. if( (wsFlags & WHERE_COLUMN_IN)==0 &&
  77700. isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
  77701. if( wsFlags==0 ){
  77702. wsFlags = WHERE_COLUMN_RANGE;
  77703. }
  77704. wsFlags |= WHERE_ORDERBY;
  77705. if( rev ){
  77706. wsFlags |= WHERE_REVERSE;
  77707. }
  77708. }else{
  77709. cost += cost*estLog(cost);
  77710. WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
  77711. }
  77712. }else if( pParse->db->flags & SQLITE_ReverseOrder ){
  77713. /* For application testing, randomly reverse the output order for
  77714. ** SELECT statements that omit the ORDER BY clause. This will help
  77715. ** to find cases where
  77716. */
  77717. wsFlags |= WHERE_REVERSE;
  77718. }
  77719. /* Check to see if we can get away with using just the index without
  77720. ** ever reading the table. If that is the case, then halve the
  77721. ** cost of this index.
  77722. */
  77723. if( wsFlags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
  77724. Bitmask m = pSrc->colUsed;
  77725. int j;
  77726. for(j=0; j<pProbe->nColumn; j++){
  77727. int x = pProbe->aiColumn[j];
  77728. if( x<BMS-1 ){
  77729. m &= ~(((Bitmask)1)<<x);
  77730. }
  77731. }
  77732. if( m==0 ){
  77733. wsFlags |= WHERE_IDX_ONLY;
  77734. cost /= 2;
  77735. WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
  77736. }
  77737. }
  77738. /* If this index has achieved the lowest cost so far, then use it.
  77739. */
  77740. if( wsFlags!=0 && cost < pCost->rCost ){
  77741. pCost->rCost = cost;
  77742. pCost->nRow = nRow;
  77743. pCost->plan.wsFlags = wsFlags;
  77744. pCost->plan.nEq = nEq;
  77745. assert( pCost->plan.wsFlags & WHERE_INDEXED );
  77746. pCost->plan.u.pIdx = pProbe;
  77747. }
  77748. }
  77749. /* Report the best result
  77750. */
  77751. pCost->plan.wsFlags |= eqTermMask;
  77752. WHERETRACE(("best index is %s, cost=%.9g, nrow=%.9g, wsFlags=%x, nEq=%d\n",
  77753. (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
  77754. pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
  77755. pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
  77756. }
  77757. /*
  77758. ** Disable a term in the WHERE clause. Except, do not disable the term
  77759. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  77760. ** or USING clause of that join.
  77761. **
  77762. ** Consider the term t2.z='ok' in the following queries:
  77763. **
  77764. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  77765. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  77766. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  77767. **
  77768. ** The t2.z='ok' is disabled in the in (2) because it originates
  77769. ** in the ON clause. The term is disabled in (3) because it is not part
  77770. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  77771. **
  77772. ** Disabling a term causes that term to not be tested in the inner loop
  77773. ** of the join. Disabling is an optimization. When terms are satisfied
  77774. ** by indices, we disable them to prevent redundant tests in the inner
  77775. ** loop. We would get the correct results if nothing were ever disabled,
  77776. ** but joins might run a little slower. The trick is to disable as much
  77777. ** as we can without disabling too much. If we disabled in (1), we'd get
  77778. ** the wrong answer. See ticket #813.
  77779. */
  77780. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  77781. if( pTerm
  77782. && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
  77783. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  77784. ){
  77785. pTerm->wtFlags |= TERM_CODED;
  77786. if( pTerm->iParent>=0 ){
  77787. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  77788. if( (--pOther->nChild)==0 ){
  77789. disableTerm(pLevel, pOther);
  77790. }
  77791. }
  77792. }
  77793. }
  77794. /*
  77795. ** Apply the affinities associated with the first n columns of index
  77796. ** pIdx to the values in the n registers starting at base.
  77797. */
  77798. static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
  77799. if( n>0 ){
  77800. Vdbe *v = pParse->pVdbe;
  77801. assert( v!=0 );
  77802. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  77803. sqlite3IndexAffinityStr(v, pIdx);
  77804. sqlite3ExprCacheAffinityChange(pParse, base, n);
  77805. }
  77806. }
  77807. /*
  77808. ** Generate code for a single equality term of the WHERE clause. An equality
  77809. ** term can be either X=expr or X IN (...). pTerm is the term to be
  77810. ** coded.
  77811. **
  77812. ** The current value for the constraint is left in register iReg.
  77813. **
  77814. ** For a constraint of the form X=expr, the expression is evaluated and its
  77815. ** result is left on the stack. For constraints of the form X IN (...)
  77816. ** this routine sets up a loop that will iterate over all values of X.
  77817. */
  77818. static int codeEqualityTerm(
  77819. Parse *pParse, /* The parsing context */
  77820. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  77821. WhereLevel *pLevel, /* When level of the FROM clause we are working on */
  77822. int iTarget /* Attempt to leave results in this register */
  77823. ){
  77824. Expr *pX = pTerm->pExpr;
  77825. Vdbe *v = pParse->pVdbe;
  77826. int iReg; /* Register holding results */
  77827. assert( iTarget>0 );
  77828. if( pX->op==TK_EQ ){
  77829. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  77830. }else if( pX->op==TK_ISNULL ){
  77831. iReg = iTarget;
  77832. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  77833. #ifndef SQLITE_OMIT_SUBQUERY
  77834. }else{
  77835. int eType;
  77836. int iTab;
  77837. struct InLoop *pIn;
  77838. assert( pX->op==TK_IN );
  77839. iReg = iTarget;
  77840. eType = sqlite3FindInIndex(pParse, pX, 0);
  77841. iTab = pX->iTable;
  77842. sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  77843. VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
  77844. assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
  77845. if( pLevel->u.in.nIn==0 ){
  77846. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  77847. }
  77848. pLevel->u.in.nIn++;
  77849. pLevel->u.in.aInLoop =
  77850. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  77851. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  77852. pIn = pLevel->u.in.aInLoop;
  77853. if( pIn ){
  77854. pIn += pLevel->u.in.nIn - 1;
  77855. pIn->iCur = iTab;
  77856. if( eType==IN_INDEX_ROWID ){
  77857. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  77858. }else{
  77859. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  77860. }
  77861. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  77862. }else{
  77863. pLevel->u.in.nIn = 0;
  77864. }
  77865. #endif
  77866. }
  77867. disableTerm(pLevel, pTerm);
  77868. return iReg;
  77869. }
  77870. /*
  77871. ** Generate code that will evaluate all == and IN constraints for an
  77872. ** index. The values for all constraints are left on the stack.
  77873. **
  77874. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  77875. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  77876. ** The index has as many as three equality constraints, but in this
  77877. ** example, the third "c" value is an inequality. So only two
  77878. ** constraints are coded. This routine will generate code to evaluate
  77879. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  77880. ** in consecutive registers and the index of the first register is returned.
  77881. **
  77882. ** In the example above nEq==2. But this subroutine works for any value
  77883. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  77884. ** The only thing it does is allocate the pLevel->iMem memory cell.
  77885. **
  77886. ** This routine always allocates at least one memory cell and returns
  77887. ** the index of that memory cell. The code that
  77888. ** calls this routine will use that memory cell to store the termination
  77889. ** key value of the loop. If one or more IN operators appear, then
  77890. ** this routine allocates an additional nEq memory cells for internal
  77891. ** use.
  77892. */
  77893. static int codeAllEqualityTerms(
  77894. Parse *pParse, /* Parsing context */
  77895. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  77896. WhereClause *pWC, /* The WHERE clause */
  77897. Bitmask notReady, /* Which parts of FROM have not yet been coded */
  77898. int nExtraReg /* Number of extra registers to allocate */
  77899. ){
  77900. int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
  77901. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  77902. Index *pIdx; /* The index being used for this loop */
  77903. int iCur = pLevel->iTabCur; /* The cursor of the table */
  77904. WhereTerm *pTerm; /* A single constraint term */
  77905. int j; /* Loop counter */
  77906. int regBase; /* Base register */
  77907. int nReg; /* Number of registers to allocate */
  77908. /* This module is only called on query plans that use an index. */
  77909. assert( pLevel->plan.wsFlags & WHERE_INDEXED );
  77910. pIdx = pLevel->plan.u.pIdx;
  77911. /* Figure out how many memory cells we will need then allocate them.
  77912. */
  77913. regBase = pParse->nMem + 1;
  77914. nReg = pLevel->plan.nEq + nExtraReg;
  77915. pParse->nMem += nReg;
  77916. /* Evaluate the equality constraints
  77917. */
  77918. assert( pIdx->nColumn>=nEq );
  77919. for(j=0; j<nEq; j++){
  77920. int r1;
  77921. int k = pIdx->aiColumn[j];
  77922. pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
  77923. if( NEVER(pTerm==0) ) break;
  77924. assert( (pTerm->wtFlags & TERM_CODED)==0 );
  77925. r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
  77926. if( r1!=regBase+j ){
  77927. if( nReg==1 ){
  77928. sqlite3ReleaseTempReg(pParse, regBase);
  77929. regBase = r1;
  77930. }else{
  77931. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  77932. }
  77933. }
  77934. testcase( pTerm->eOperator & WO_ISNULL );
  77935. testcase( pTerm->eOperator & WO_IN );
  77936. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  77937. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  77938. }
  77939. }
  77940. return regBase;
  77941. }
  77942. /*
  77943. ** Return TRUE if the WhereClause pWC contains no terms that
  77944. ** are not virtual and which have not been coded.
  77945. **
  77946. ** To put it another way, return TRUE if no additional WHERE clauses
  77947. ** tests are required in order to establish that the current row
  77948. ** should go to output and return FALSE if there are some terms of
  77949. ** the WHERE clause that need to be validated before outputing the row.
  77950. */
  77951. static int whereRowReadyForOutput(WhereClause *pWC){
  77952. WhereTerm *pTerm;
  77953. int j;
  77954. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  77955. if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED))==0 ) return 0;
  77956. }
  77957. return 1;
  77958. }
  77959. /*
  77960. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  77961. ** implementation described by pWInfo.
  77962. */
  77963. static Bitmask codeOneLoopStart(
  77964. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  77965. int iLevel, /* Which level of pWInfo->a[] should be coded */
  77966. u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  77967. Bitmask notReady /* Which tables are currently available */
  77968. ){
  77969. int j, k; /* Loop counters */
  77970. int iCur; /* The VDBE cursor for the table */
  77971. int addrNxt; /* Where to jump to continue with the next IN case */
  77972. int omitTable; /* True if we use the index only */
  77973. int bRev; /* True if we need to scan in reverse order */
  77974. WhereLevel *pLevel; /* The where level to be coded */
  77975. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  77976. WhereTerm *pTerm; /* A WHERE clause term */
  77977. Parse *pParse; /* Parsing context */
  77978. Vdbe *v; /* The prepared stmt under constructions */
  77979. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  77980. int addrBrk; /* Jump here to break out of the loop */
  77981. int addrCont; /* Jump here to continue with next cycle */
  77982. int regRowSet; /* Write rowids to this RowSet if non-negative */
  77983. int codeRowSetEarly; /* True if index fully constrains the search */
  77984. pParse = pWInfo->pParse;
  77985. v = pParse->pVdbe;
  77986. pWC = pWInfo->pWC;
  77987. pLevel = &pWInfo->a[iLevel];
  77988. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  77989. iCur = pTabItem->iCursor;
  77990. bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  77991. omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0;
  77992. regRowSet = pWInfo->regRowSet;
  77993. codeRowSetEarly = 0;
  77994. /* Create labels for the "break" and "continue" instructions
  77995. ** for the current loop. Jump to addrBrk to break out of a loop.
  77996. ** Jump to cont to go immediately to the next iteration of the
  77997. ** loop.
  77998. **
  77999. ** When there is an IN operator, we also have a "addrNxt" label that
  78000. ** means to continue with the next IN value combination. When
  78001. ** there are no IN operators in the constraints, the "addrNxt" label
  78002. ** is the same as "addrBrk".
  78003. */
  78004. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  78005. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  78006. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  78007. ** initialize a memory cell that records if this table matches any
  78008. ** row of the left table of the join.
  78009. */
  78010. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  78011. pLevel->iLeftJoin = ++pParse->nMem;
  78012. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  78013. VdbeComment((v, "init LEFT JOIN no-match flag"));
  78014. }
  78015. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78016. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  78017. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  78018. ** to access the data.
  78019. */
  78020. int iReg; /* P3 Value for OP_VFilter */
  78021. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  78022. int nConstraint = pVtabIdx->nConstraint;
  78023. struct sqlite3_index_constraint_usage *aUsage =
  78024. pVtabIdx->aConstraintUsage;
  78025. const struct sqlite3_index_constraint *aConstraint =
  78026. pVtabIdx->aConstraint;
  78027. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  78028. pParse->disableColCache++;
  78029. for(j=1; j<=nConstraint; j++){
  78030. for(k=0; k<nConstraint; k++){
  78031. if( aUsage[k].argvIndex==j ){
  78032. int iTerm = aConstraint[k].iTermOffset;
  78033. assert( pParse->disableColCache );
  78034. sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
  78035. break;
  78036. }
  78037. }
  78038. if( k==nConstraint ) break;
  78039. }
  78040. assert( pParse->disableColCache );
  78041. pParse->disableColCache--;
  78042. sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
  78043. sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
  78044. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
  78045. pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
  78046. pVtabIdx->needToFreeIdxStr = 0;
  78047. for(j=0; j<nConstraint; j++){
  78048. if( aUsage[j].omit ){
  78049. int iTerm = aConstraint[j].iTermOffset;
  78050. disableTerm(pLevel, &pWC->a[iTerm]);
  78051. }
  78052. }
  78053. pLevel->op = OP_VNext;
  78054. pLevel->p1 = iCur;
  78055. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  78056. codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
  78057. if( codeRowSetEarly ){
  78058. sqlite3VdbeAddOp2(v, OP_VRowid, iCur, iReg);
  78059. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, iReg);
  78060. }
  78061. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  78062. }else
  78063. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  78064. if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
  78065. /* Case 1: We can directly reference a single row using an
  78066. ** equality comparison against the ROWID field. Or
  78067. ** we reference multiple rows using a "rowid IN (...)"
  78068. ** construct.
  78069. */
  78070. int r1;
  78071. int rtmp = sqlite3GetTempReg(pParse);
  78072. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  78073. assert( pTerm!=0 );
  78074. assert( pTerm->pExpr!=0 );
  78075. assert( pTerm->leftCursor==iCur );
  78076. assert( omitTable==0 );
  78077. r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
  78078. addrNxt = pLevel->addrNxt;
  78079. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, addrNxt);
  78080. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, r1);
  78081. codeRowSetEarly = (pWC->nTerm==1 && regRowSet>=0) ?1:0;
  78082. if( codeRowSetEarly ){
  78083. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  78084. }
  78085. sqlite3ReleaseTempReg(pParse, rtmp);
  78086. VdbeComment((v, "pk"));
  78087. pLevel->op = OP_Noop;
  78088. }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
  78089. /* Case 2: We have an inequality comparison against the ROWID field.
  78090. */
  78091. int testOp = OP_Noop;
  78092. int start;
  78093. int memEndValue = 0;
  78094. WhereTerm *pStart, *pEnd;
  78095. assert( omitTable==0 );
  78096. pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
  78097. pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
  78098. if( bRev ){
  78099. pTerm = pStart;
  78100. pStart = pEnd;
  78101. pEnd = pTerm;
  78102. }
  78103. if( pStart ){
  78104. Expr *pX; /* The expression that defines the start bound */
  78105. int r1, rTemp; /* Registers for holding the start boundary */
  78106. /* The following constant maps TK_xx codes into corresponding
  78107. ** seek opcodes. It depends on a particular ordering of TK_xx
  78108. */
  78109. const u8 aMoveOp[] = {
  78110. /* TK_GT */ OP_SeekGt,
  78111. /* TK_LE */ OP_SeekLe,
  78112. /* TK_LT */ OP_SeekLt,
  78113. /* TK_GE */ OP_SeekGe
  78114. };
  78115. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  78116. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  78117. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  78118. pX = pStart->pExpr;
  78119. assert( pX!=0 );
  78120. assert( pStart->leftCursor==iCur );
  78121. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  78122. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  78123. VdbeComment((v, "pk"));
  78124. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  78125. sqlite3ReleaseTempReg(pParse, rTemp);
  78126. disableTerm(pLevel, pStart);
  78127. }else{
  78128. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  78129. }
  78130. if( pEnd ){
  78131. Expr *pX;
  78132. pX = pEnd->pExpr;
  78133. assert( pX!=0 );
  78134. assert( pEnd->leftCursor==iCur );
  78135. memEndValue = ++pParse->nMem;
  78136. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  78137. if( pX->op==TK_LT || pX->op==TK_GT ){
  78138. testOp = bRev ? OP_Le : OP_Ge;
  78139. }else{
  78140. testOp = bRev ? OP_Lt : OP_Gt;
  78141. }
  78142. disableTerm(pLevel, pEnd);
  78143. }
  78144. start = sqlite3VdbeCurrentAddr(v);
  78145. pLevel->op = bRev ? OP_Prev : OP_Next;
  78146. pLevel->p1 = iCur;
  78147. pLevel->p2 = start;
  78148. pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
  78149. codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
  78150. if( codeRowSetEarly || testOp!=OP_Noop ){
  78151. int r1 = sqlite3GetTempReg(pParse);
  78152. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
  78153. if( testOp!=OP_Noop ){
  78154. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, r1);
  78155. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  78156. }
  78157. if( codeRowSetEarly ){
  78158. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  78159. }
  78160. sqlite3ReleaseTempReg(pParse, r1);
  78161. }
  78162. }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
  78163. /* Case 3: A scan using an index.
  78164. **
  78165. ** The WHERE clause may contain zero or more equality
  78166. ** terms ("==" or "IN" operators) that refer to the N
  78167. ** left-most columns of the index. It may also contain
  78168. ** inequality constraints (>, <, >= or <=) on the indexed
  78169. ** column that immediately follows the N equalities. Only
  78170. ** the right-most column can be an inequality - the rest must
  78171. ** use the "==" and "IN" operators. For example, if the
  78172. ** index is on (x,y,z), then the following clauses are all
  78173. ** optimized:
  78174. **
  78175. ** x=5
  78176. ** x=5 AND y=10
  78177. ** x=5 AND y<10
  78178. ** x=5 AND y>5 AND y<10
  78179. ** x=5 AND y=5 AND z<=10
  78180. **
  78181. ** The z<10 term of the following cannot be used, only
  78182. ** the x=5 term:
  78183. **
  78184. ** x=5 AND z<10
  78185. **
  78186. ** N may be zero if there are inequality constraints.
  78187. ** If there are no inequality constraints, then N is at
  78188. ** least one.
  78189. **
  78190. ** This case is also used when there are no WHERE clause
  78191. ** constraints but an index is selected anyway, in order
  78192. ** to force the output order to conform to an ORDER BY.
  78193. */
  78194. int aStartOp[] = {
  78195. 0,
  78196. 0,
  78197. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  78198. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  78199. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  78200. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  78201. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  78202. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  78203. };
  78204. int aEndOp[] = {
  78205. OP_Noop, /* 0: (!end_constraints) */
  78206. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  78207. OP_IdxLT /* 2: (end_constraints && bRev) */
  78208. };
  78209. int nEq = pLevel->plan.nEq;
  78210. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  78211. int regBase; /* Base register holding constraint values */
  78212. int r1; /* Temp register */
  78213. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  78214. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  78215. int startEq; /* True if range start uses ==, >= or <= */
  78216. int endEq; /* True if range end uses ==, >= or <= */
  78217. int start_constraints; /* Start of range is constrained */
  78218. int nConstraint; /* Number of constraint terms */
  78219. Index *pIdx; /* The index we will be using */
  78220. int iIdxCur; /* The VDBE cursor for the index */
  78221. int nExtraReg = 0; /* Number of extra registers needed */
  78222. int op; /* Instruction opcode */
  78223. pIdx = pLevel->plan.u.pIdx;
  78224. iIdxCur = pLevel->iIdxCur;
  78225. k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
  78226. /* If this loop satisfies a sort order (pOrderBy) request that
  78227. ** was passed to this function to implement a "SELECT min(x) ..."
  78228. ** query, then the caller will only allow the loop to run for
  78229. ** a single iteration. This means that the first row returned
  78230. ** should not have a NULL value stored in 'x'. If column 'x' is
  78231. ** the first one after the nEq equality constraints in the index,
  78232. ** this requires some special handling.
  78233. */
  78234. if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
  78235. && (pLevel->plan.wsFlags&WHERE_ORDERBY)
  78236. && (pIdx->nColumn>nEq)
  78237. ){
  78238. /* assert( pOrderBy->nExpr==1 ); */
  78239. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  78240. isMinQuery = 1;
  78241. nExtraReg = 1;
  78242. }
  78243. /* Find any inequality constraint terms for the start and end
  78244. ** of the range.
  78245. */
  78246. if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
  78247. pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
  78248. nExtraReg = 1;
  78249. }
  78250. if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
  78251. pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
  78252. nExtraReg = 1;
  78253. }
  78254. /* Generate code to evaluate all constraint terms using == or IN
  78255. ** and store the values of those terms in an array of registers
  78256. ** starting at regBase.
  78257. */
  78258. regBase = codeAllEqualityTerms(pParse, pLevel, pWC, notReady, nExtraReg);
  78259. addrNxt = pLevel->addrNxt;
  78260. /* If we are doing a reverse order scan on an ascending index, or
  78261. ** a forward order scan on a descending index, interchange the
  78262. ** start and end terms (pRangeStart and pRangeEnd).
  78263. */
  78264. if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
  78265. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  78266. }
  78267. testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
  78268. testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
  78269. testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
  78270. testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
  78271. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  78272. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  78273. start_constraints = pRangeStart || nEq>0;
  78274. /* Seek the index cursor to the start of the range. */
  78275. nConstraint = nEq;
  78276. if( pRangeStart ){
  78277. int dcc = pParse->disableColCache;
  78278. if( pRangeEnd ){
  78279. pParse->disableColCache++;
  78280. }
  78281. sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
  78282. pParse->disableColCache = dcc;
  78283. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  78284. nConstraint++;
  78285. }else if( isMinQuery ){
  78286. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  78287. nConstraint++;
  78288. startEq = 0;
  78289. start_constraints = 1;
  78290. }
  78291. codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
  78292. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  78293. assert( op!=0 );
  78294. testcase( op==OP_Rewind );
  78295. testcase( op==OP_Last );
  78296. testcase( op==OP_SeekGt );
  78297. testcase( op==OP_SeekGe );
  78298. testcase( op==OP_SeekLe );
  78299. testcase( op==OP_SeekLt );
  78300. sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
  78301. SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
  78302. /* Load the value for the inequality constraint at the end of the
  78303. ** range (if any).
  78304. */
  78305. nConstraint = nEq;
  78306. if( pRangeEnd ){
  78307. sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
  78308. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  78309. codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
  78310. nConstraint++;
  78311. }
  78312. /* Top of the loop body */
  78313. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  78314. /* Check if the index cursor is past the end of the range. */
  78315. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  78316. testcase( op==OP_Noop );
  78317. testcase( op==OP_IdxGE );
  78318. testcase( op==OP_IdxLT );
  78319. if( op!=OP_Noop ){
  78320. sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
  78321. SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
  78322. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  78323. }
  78324. /* If there are inequality constraints, check that the value
  78325. ** of the table column that the inequality contrains is not NULL.
  78326. ** If it is, jump to the next iteration of the loop.
  78327. */
  78328. r1 = sqlite3GetTempReg(pParse);
  78329. testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
  78330. testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
  78331. if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
  78332. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  78333. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  78334. }
  78335. /* Seek the table cursor, if required */
  78336. disableTerm(pLevel, pRangeStart);
  78337. disableTerm(pLevel, pRangeEnd);
  78338. codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
  78339. if( !omitTable || codeRowSetEarly ){
  78340. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
  78341. if( codeRowSetEarly ){
  78342. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  78343. }else{
  78344. sqlite3VdbeAddOp2(v, OP_Seek, iCur, r1); /* Deferred seek */
  78345. }
  78346. }
  78347. sqlite3ReleaseTempReg(pParse, r1);
  78348. /* Record the instruction used to terminate the loop. Disable
  78349. ** WHERE clause terms made redundant by the index range scan.
  78350. */
  78351. pLevel->op = bRev ? OP_Prev : OP_Next;
  78352. pLevel->p1 = iIdxCur;
  78353. }else
  78354. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  78355. if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  78356. /* Case 4: Two or more separately indexed terms connected by OR
  78357. **
  78358. ** Example:
  78359. **
  78360. ** CREATE TABLE t1(a,b,c,d);
  78361. ** CREATE INDEX i1 ON t1(a);
  78362. ** CREATE INDEX i2 ON t1(b);
  78363. ** CREATE INDEX i3 ON t1(c);
  78364. **
  78365. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  78366. **
  78367. ** In the example, there are three indexed terms connected by OR.
  78368. ** The top of the loop is constructed by creating a RowSet object
  78369. ** and populating it. Then looping over elements of the rowset.
  78370. **
  78371. ** Null 1
  78372. ** # fill RowSet 1 with entries where a=5 using i1
  78373. ** # fill Rowset 1 with entries where b=7 using i2
  78374. ** # fill Rowset 1 with entries where c=11 and d=13 i3 and t1
  78375. ** A: RowSetRead 1, B, 2
  78376. ** Seek i, 2
  78377. **
  78378. ** The bottom of the loop looks like this:
  78379. **
  78380. ** Goto 0, A
  78381. ** B:
  78382. */
  78383. int regOrRowset; /* Register holding the RowSet object */
  78384. int regNextRowid; /* Register holding next rowid */
  78385. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  78386. WhereTerm *pOrTerm; /* A single subterm within the OR-clause */
  78387. SrcList oneTab; /* Shortened table list */
  78388. pTerm = pLevel->plan.u.pTerm;
  78389. assert( pTerm!=0 );
  78390. assert( pTerm->eOperator==WO_OR );
  78391. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  78392. pOrWc = &pTerm->u.pOrInfo->wc;
  78393. codeRowSetEarly = (regRowSet>=0 && pWC->nTerm==1) ?1:0;
  78394. if( codeRowSetEarly ){
  78395. regOrRowset = regRowSet;
  78396. }else{
  78397. regOrRowset = sqlite3GetTempReg(pParse);
  78398. sqlite3VdbeAddOp2(v, OP_Null, 0, regOrRowset);
  78399. }
  78400. oneTab.nSrc = 1;
  78401. oneTab.nAlloc = 1;
  78402. oneTab.a[0] = *pTabItem;
  78403. for(j=0, pOrTerm=pOrWc->a; j<pOrWc->nTerm; j++, pOrTerm++){
  78404. WhereInfo *pSubWInfo;
  78405. if( pOrTerm->leftCursor!=iCur && pOrTerm->eOperator!=WO_AND ) continue;
  78406. pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
  78407. WHERE_FILL_ROWSET | WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE,
  78408. regOrRowset);
  78409. if( pSubWInfo ){
  78410. sqlite3WhereEnd(pSubWInfo);
  78411. }
  78412. }
  78413. sqlite3VdbeResolveLabel(v, addrCont);
  78414. if( !codeRowSetEarly ){
  78415. regNextRowid = sqlite3GetTempReg(pParse);
  78416. addrCont =
  78417. sqlite3VdbeAddOp3(v, OP_RowSetRead, regOrRowset,addrBrk,regNextRowid);
  78418. sqlite3VdbeAddOp2(v, OP_Seek, iCur, regNextRowid);
  78419. sqlite3ReleaseTempReg(pParse, regNextRowid);
  78420. /* sqlite3ReleaseTempReg(pParse, regOrRowset); // Preserve the RowSet */
  78421. pLevel->op = OP_Goto;
  78422. pLevel->p2 = addrCont;
  78423. }else{
  78424. pLevel->op = OP_Noop;
  78425. }
  78426. disableTerm(pLevel, pTerm);
  78427. }else
  78428. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  78429. {
  78430. /* Case 5: There is no usable index. We must do a complete
  78431. ** scan of the entire table.
  78432. */
  78433. static const u8 aStep[] = { OP_Next, OP_Prev };
  78434. static const u8 aStart[] = { OP_Rewind, OP_Last };
  78435. assert( bRev==0 || bRev==1 );
  78436. assert( omitTable==0 );
  78437. pLevel->op = aStep[bRev];
  78438. pLevel->p1 = iCur;
  78439. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  78440. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  78441. codeRowSetEarly = 0;
  78442. }
  78443. notReady &= ~getMask(pWC->pMaskSet, iCur);
  78444. /* Insert code to test every subexpression that can be completely
  78445. ** computed using the current set of tables.
  78446. */
  78447. k = 0;
  78448. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  78449. Expr *pE;
  78450. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  78451. testcase( pTerm->wtFlags & TERM_CODED );
  78452. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  78453. if( (pTerm->prereqAll & notReady)!=0 ) continue;
  78454. pE = pTerm->pExpr;
  78455. assert( pE!=0 );
  78456. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  78457. continue;
  78458. }
  78459. pParse->disableColCache += k;
  78460. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  78461. pParse->disableColCache -= k;
  78462. k = 1;
  78463. pTerm->wtFlags |= TERM_CODED;
  78464. }
  78465. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  78466. ** at least one row of the right table has matched the left table.
  78467. */
  78468. if( pLevel->iLeftJoin ){
  78469. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  78470. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  78471. VdbeComment((v, "record LEFT JOIN hit"));
  78472. sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
  78473. sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
  78474. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  78475. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  78476. testcase( pTerm->wtFlags & TERM_CODED );
  78477. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  78478. if( (pTerm->prereqAll & notReady)!=0 ) continue;
  78479. assert( pTerm->pExpr );
  78480. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  78481. pTerm->wtFlags |= TERM_CODED;
  78482. }
  78483. }
  78484. /*
  78485. ** If it was requested to store the results in a rowset and that has
  78486. ** not already been do, then do so now.
  78487. */
  78488. if( regRowSet>=0 && !codeRowSetEarly ){
  78489. int r1 = sqlite3GetTempReg(pParse);
  78490. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78491. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  78492. sqlite3VdbeAddOp2(v, OP_VRowid, iCur, r1);
  78493. }else
  78494. #endif
  78495. {
  78496. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
  78497. }
  78498. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
  78499. sqlite3ReleaseTempReg(pParse, r1);
  78500. }
  78501. return notReady;
  78502. }
  78503. #if defined(SQLITE_TEST)
  78504. /*
  78505. ** The following variable holds a text description of query plan generated
  78506. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  78507. ** overwrites the previous. This information is used for testing and
  78508. ** analysis only.
  78509. */
  78510. SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  78511. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  78512. #endif /* SQLITE_TEST */
  78513. /*
  78514. ** Free a WhereInfo structure
  78515. */
  78516. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  78517. if( pWInfo ){
  78518. int i;
  78519. for(i=0; i<pWInfo->nLevel; i++){
  78520. sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
  78521. if( pInfo ){
  78522. assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed );
  78523. if( pInfo->needToFreeIdxStr ){
  78524. sqlite3_free(pInfo->idxStr);
  78525. }
  78526. sqlite3DbFree(db, pInfo);
  78527. }
  78528. }
  78529. whereClauseClear(pWInfo->pWC);
  78530. sqlite3DbFree(db, pWInfo);
  78531. }
  78532. }
  78533. /*
  78534. ** Generate the beginning of the loop used for WHERE clause processing.
  78535. ** The return value is a pointer to an opaque structure that contains
  78536. ** information needed to terminate the loop. Later, the calling routine
  78537. ** should invoke sqlite3WhereEnd() with the return value of this function
  78538. ** in order to complete the WHERE clause processing.
  78539. **
  78540. ** If an error occurs, this routine returns NULL.
  78541. **
  78542. ** The basic idea is to do a nested loop, one loop for each table in
  78543. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  78544. ** same as a SELECT with only a single table in the FROM clause.) For
  78545. ** example, if the SQL is this:
  78546. **
  78547. ** SELECT * FROM t1, t2, t3 WHERE ...;
  78548. **
  78549. ** Then the code generated is conceptually like the following:
  78550. **
  78551. ** foreach row1 in t1 do \ Code generated
  78552. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  78553. ** foreach row3 in t3 do /
  78554. ** ...
  78555. ** end \ Code generated
  78556. ** end |-- by sqlite3WhereEnd()
  78557. ** end /
  78558. **
  78559. ** Note that the loops might not be nested in the order in which they
  78560. ** appear in the FROM clause if a different order is better able to make
  78561. ** use of indices. Note also that when the IN operator appears in
  78562. ** the WHERE clause, it might result in additional nested loops for
  78563. ** scanning through all values on the right-hand side of the IN.
  78564. **
  78565. ** There are Btree cursors associated with each table. t1 uses cursor
  78566. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  78567. ** And so forth. This routine generates code to open those VDBE cursors
  78568. ** and sqlite3WhereEnd() generates the code to close them.
  78569. **
  78570. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  78571. ** in pTabList pointing at their appropriate entries. The [...] code
  78572. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  78573. ** data from the various tables of the loop.
  78574. **
  78575. ** If the WHERE clause is empty, the foreach loops must each scan their
  78576. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  78577. ** the tables have indices and there are terms in the WHERE clause that
  78578. ** refer to those indices, a complete table scan can be avoided and the
  78579. ** code will run much faster. Most of the work of this routine is checking
  78580. ** to see if there are indices that can be used to speed up the loop.
  78581. **
  78582. ** Terms of the WHERE clause are also used to limit which rows actually
  78583. ** make it to the "..." in the middle of the loop. After each "foreach",
  78584. ** terms of the WHERE clause that use only terms in that loop and outer
  78585. ** loops are evaluated and if false a jump is made around all subsequent
  78586. ** inner loops (or around the "..." if the test occurs within the inner-
  78587. ** most loop)
  78588. **
  78589. ** OUTER JOINS
  78590. **
  78591. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  78592. **
  78593. ** foreach row1 in t1 do
  78594. ** flag = 0
  78595. ** foreach row2 in t2 do
  78596. ** start:
  78597. ** ...
  78598. ** flag = 1
  78599. ** end
  78600. ** if flag==0 then
  78601. ** move the row2 cursor to a null row
  78602. ** goto start
  78603. ** fi
  78604. ** end
  78605. **
  78606. ** ORDER BY CLAUSE PROCESSING
  78607. **
  78608. ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  78609. ** if there is one. If there is no ORDER BY clause or if this routine
  78610. ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
  78611. **
  78612. ** If an index can be used so that the natural output order of the table
  78613. ** scan is correct for the ORDER BY clause, then that index is used and
  78614. ** *ppOrderBy is set to NULL. This is an optimization that prevents an
  78615. ** unnecessary sort of the result set if an index appropriate for the
  78616. ** ORDER BY clause already exists.
  78617. **
  78618. ** If the where clause loops cannot be arranged to provide the correct
  78619. ** output order, then the *ppOrderBy is unchanged.
  78620. */
  78621. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  78622. Parse *pParse, /* The parser context */
  78623. SrcList *pTabList, /* A list of all tables to be scanned */
  78624. Expr *pWhere, /* The WHERE clause */
  78625. ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
  78626. u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  78627. int regRowSet /* Register hold RowSet if WHERE_FILL_ROWSET is set */
  78628. ){
  78629. int i; /* Loop counter */
  78630. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  78631. WhereInfo *pWInfo; /* Will become the return value of this function */
  78632. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  78633. Bitmask notReady; /* Cursors that are not yet positioned */
  78634. WhereMaskSet *pMaskSet; /* The expression mask set */
  78635. WhereClause *pWC; /* Decomposition of the WHERE clause */
  78636. struct SrcList_item *pTabItem; /* A single entry from pTabList */
  78637. WhereLevel *pLevel; /* A single level in the pWInfo list */
  78638. int iFrom; /* First unused FROM clause element */
  78639. int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
  78640. sqlite3 *db; /* Database connection */
  78641. ExprList *pOrderBy = 0;
  78642. /* The number of tables in the FROM clause is limited by the number of
  78643. ** bits in a Bitmask
  78644. */
  78645. if( pTabList->nSrc>BMS ){
  78646. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  78647. return 0;
  78648. }
  78649. if( ppOrderBy ){
  78650. pOrderBy = *ppOrderBy;
  78651. }
  78652. /* Allocate and initialize the WhereInfo structure that will become the
  78653. ** return value. A single allocation is used to store the WhereInfo
  78654. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  78655. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  78656. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  78657. ** some architectures. Hence the ROUND8() below.
  78658. */
  78659. db = pParse->db;
  78660. nByteWInfo = ROUND8(sizeof(WhereInfo)+(pTabList->nSrc-1)*sizeof(WhereLevel));
  78661. pWInfo = sqlite3DbMallocZero(db,
  78662. nByteWInfo +
  78663. sizeof(WhereClause) +
  78664. sizeof(WhereMaskSet)
  78665. );
  78666. if( db->mallocFailed ){
  78667. goto whereBeginError;
  78668. }
  78669. pWInfo->nLevel = pTabList->nSrc;
  78670. pWInfo->pParse = pParse;
  78671. pWInfo->pTabList = pTabList;
  78672. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  78673. pWInfo->regRowSet = (wctrlFlags & WHERE_FILL_ROWSET) ? regRowSet : -1;
  78674. pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
  78675. pWInfo->wctrlFlags = wctrlFlags;
  78676. pMaskSet = (WhereMaskSet*)&pWC[1];
  78677. /* Split the WHERE clause into separate subexpressions where each
  78678. ** subexpression is separated by an AND operator.
  78679. */
  78680. initMaskSet(pMaskSet);
  78681. whereClauseInit(pWC, pParse, pMaskSet);
  78682. sqlite3ExprCodeConstants(pParse, pWhere);
  78683. whereSplit(pWC, pWhere, TK_AND);
  78684. /* Special case: a WHERE clause that is constant. Evaluate the
  78685. ** expression and either jump over all of the code or fall thru.
  78686. */
  78687. if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  78688. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  78689. pWhere = 0;
  78690. }
  78691. /* Assign a bit from the bitmask to every term in the FROM clause.
  78692. **
  78693. ** When assigning bitmask values to FROM clause cursors, it must be
  78694. ** the case that if X is the bitmask for the N-th FROM clause term then
  78695. ** the bitmask for all FROM clause terms to the left of the N-th term
  78696. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  78697. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  78698. ** of the join. Subtracting one from the right table bitmask gives a
  78699. ** bitmask for all tables to the left of the join. Knowing the bitmask
  78700. ** for all tables to the left of a left join is important. Ticket #3015.
  78701. */
  78702. for(i=0; i<pTabList->nSrc; i++){
  78703. createMask(pMaskSet, pTabList->a[i].iCursor);
  78704. }
  78705. #ifndef NDEBUG
  78706. {
  78707. Bitmask toTheLeft = 0;
  78708. for(i=0; i<pTabList->nSrc; i++){
  78709. Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
  78710. assert( (m-1)==toTheLeft );
  78711. toTheLeft |= m;
  78712. }
  78713. }
  78714. #endif
  78715. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  78716. ** add new virtual terms onto the end of the WHERE clause. We do not
  78717. ** want to analyze these virtual terms, so start analyzing at the end
  78718. ** and work forward so that the added virtual terms are never processed.
  78719. */
  78720. exprAnalyzeAll(pTabList, pWC);
  78721. if( db->mallocFailed ){
  78722. goto whereBeginError;
  78723. }
  78724. /* Chose the best index to use for each table in the FROM clause.
  78725. **
  78726. ** This loop fills in the following fields:
  78727. **
  78728. ** pWInfo->a[].pIdx The index to use for this level of the loop.
  78729. ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
  78730. ** pWInfo->a[].nEq The number of == and IN constraints
  78731. ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
  78732. ** pWInfo->a[].iTabCur The VDBE cursor for the database table
  78733. ** pWInfo->a[].iIdxCur The VDBE cursor for the index
  78734. ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
  78735. **
  78736. ** This loop also figures out the nesting order of tables in the FROM
  78737. ** clause.
  78738. */
  78739. notReady = ~(Bitmask)0;
  78740. pTabItem = pTabList->a;
  78741. pLevel = pWInfo->a;
  78742. andFlags = ~0;
  78743. WHERETRACE(("*** Optimizer Start ***\n"));
  78744. for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  78745. WhereCost bestPlan; /* Most efficient plan seen so far */
  78746. Index *pIdx; /* Index for FROM table at pTabItem */
  78747. int j; /* For looping over FROM tables */
  78748. int bestJ = 0; /* The value of j */
  78749. Bitmask m; /* Bitmask value for j or bestJ */
  78750. int once = 0; /* True when first table is seen */
  78751. memset(&bestPlan, 0, sizeof(bestPlan));
  78752. bestPlan.rCost = SQLITE_BIG_DBL;
  78753. for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
  78754. int doNotReorder; /* True if this table should not be reordered */
  78755. WhereCost sCost; /* Cost information from bestIndex() */
  78756. doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
  78757. if( once && doNotReorder ) break;
  78758. m = getMask(pMaskSet, pTabItem->iCursor);
  78759. if( (m & notReady)==0 ){
  78760. if( j==iFrom ) iFrom++;
  78761. continue;
  78762. }
  78763. assert( pTabItem->pTab );
  78764. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78765. if( IsVirtual(pTabItem->pTab) ){
  78766. sqlite3_index_info *pVtabIdx; /* Current virtual index */
  78767. sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
  78768. sCost.rCost = bestVirtualIndex(pParse, pWC, pTabItem, notReady,
  78769. ppOrderBy ? *ppOrderBy : 0, i==0,
  78770. ppIdxInfo);
  78771. sCost.plan.wsFlags = WHERE_VIRTUALTABLE;
  78772. sCost.plan.u.pVtabIdx = pVtabIdx = *ppIdxInfo;
  78773. if( pVtabIdx && pVtabIdx->orderByConsumed ){
  78774. sCost.plan.wsFlags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
  78775. }
  78776. sCost.plan.nEq = 0;
  78777. /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
  78778. if( (SQLITE_BIG_DBL/((double)2))<sCost.rCost ){
  78779. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  78780. ** inital value of lowestCost in this loop. If it is, then
  78781. ** the (cost<lowestCost) test below will never be true.
  78782. */
  78783. /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
  78784. sCost.rCost = (SQLITE_BIG_DBL/((double)2));
  78785. }
  78786. }else
  78787. #endif
  78788. {
  78789. bestIndex(pParse, pWC, pTabItem, notReady,
  78790. (i==0 && ppOrderBy) ? *ppOrderBy : 0, &sCost);
  78791. }
  78792. if( once==0 || sCost.rCost<bestPlan.rCost ){
  78793. once = 1;
  78794. bestPlan = sCost;
  78795. bestJ = j;
  78796. }
  78797. if( doNotReorder ) break;
  78798. }
  78799. assert( once );
  78800. assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
  78801. WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
  78802. pLevel-pWInfo->a));
  78803. if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
  78804. *ppOrderBy = 0;
  78805. }
  78806. andFlags &= bestPlan.plan.wsFlags;
  78807. pLevel->plan = bestPlan.plan;
  78808. if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
  78809. pLevel->iIdxCur = pParse->nTab++;
  78810. }else{
  78811. pLevel->iIdxCur = -1;
  78812. }
  78813. notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
  78814. pLevel->iFrom = (u8)bestJ;
  78815. /* Check that if the table scanned by this loop iteration had an
  78816. ** INDEXED BY clause attached to it, that the named index is being
  78817. ** used for the scan. If not, then query compilation has failed.
  78818. ** Return an error.
  78819. */
  78820. pIdx = pTabList->a[bestJ].pIndex;
  78821. if( pIdx ){
  78822. if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
  78823. sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
  78824. goto whereBeginError;
  78825. }else{
  78826. /* If an INDEXED BY clause is used, the bestIndex() function is
  78827. ** guaranteed to find the index specified in the INDEXED BY clause
  78828. ** if it find an index at all. */
  78829. assert( bestPlan.plan.u.pIdx==pIdx );
  78830. }
  78831. }
  78832. }
  78833. WHERETRACE(("*** Optimizer Finished ***\n"));
  78834. if( db->mallocFailed ){
  78835. goto whereBeginError;
  78836. }
  78837. /* If the total query only selects a single row, then the ORDER BY
  78838. ** clause is irrelevant.
  78839. */
  78840. if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
  78841. *ppOrderBy = 0;
  78842. }
  78843. /* If the caller is an UPDATE or DELETE statement that is requesting
  78844. ** to use a one-pass algorithm, determine if this is appropriate.
  78845. ** The one-pass algorithm only works if the WHERE clause constraints
  78846. ** the statement to update a single row.
  78847. */
  78848. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  78849. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
  78850. pWInfo->okOnePass = 1;
  78851. pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
  78852. }
  78853. /* Open all tables in the pTabList and any indices selected for
  78854. ** searching those tables.
  78855. */
  78856. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  78857. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  78858. Table *pTab; /* Table to open */
  78859. int iDb; /* Index of database containing table/index */
  78860. #ifndef SQLITE_OMIT_EXPLAIN
  78861. if( pParse->explain==2 ){
  78862. char *zMsg;
  78863. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  78864. zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
  78865. if( pItem->zAlias ){
  78866. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  78867. }
  78868. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  78869. zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
  78870. zMsg, pLevel->plan.u.pIdx->zName);
  78871. }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  78872. zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
  78873. }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  78874. zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
  78875. }
  78876. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78877. else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  78878. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  78879. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  78880. pVtabIdx->idxNum, pVtabIdx->idxStr);
  78881. }
  78882. #endif
  78883. if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
  78884. zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
  78885. }
  78886. sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
  78887. }
  78888. #endif /* SQLITE_OMIT_EXPLAIN */
  78889. pTabItem = &pTabList->a[pLevel->iFrom];
  78890. pTab = pTabItem->pTab;
  78891. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78892. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
  78893. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78894. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  78895. int iCur = pTabItem->iCursor;
  78896. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
  78897. (const char*)pTab->pVtab, P4_VTAB);
  78898. }else
  78899. #endif
  78900. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  78901. && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
  78902. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  78903. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  78904. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  78905. Bitmask b = pTabItem->colUsed;
  78906. int n = 0;
  78907. for(; b; b=b>>1, n++){}
  78908. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, SQLITE_INT_TO_PTR(n), P4_INT32);
  78909. assert( n<=pTab->nCol );
  78910. }
  78911. }else{
  78912. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  78913. }
  78914. pLevel->iTabCur = pTabItem->iCursor;
  78915. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  78916. Index *pIx = pLevel->plan.u.pIdx;
  78917. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  78918. int iIdxCur = pLevel->iIdxCur;
  78919. assert( pIx->pSchema==pTab->pSchema );
  78920. assert( iIdxCur>=0 );
  78921. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
  78922. (char*)pKey, P4_KEYINFO_HANDOFF);
  78923. VdbeComment((v, "%s", pIx->zName));
  78924. }
  78925. sqlite3CodeVerifySchema(pParse, iDb);
  78926. }
  78927. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  78928. /* Generate the code to do the search. Each iteration of the for
  78929. ** loop below generates code for a single nested loop of the VM
  78930. ** program.
  78931. */
  78932. notReady = ~(Bitmask)0;
  78933. for(i=0; i<pTabList->nSrc; i++){
  78934. notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
  78935. pWInfo->iContinue = pWInfo->a[i].addrCont;
  78936. }
  78937. #ifdef SQLITE_TEST /* For testing and debugging use only */
  78938. /* Record in the query plan information about the current table
  78939. ** and the index used to access it (if any). If the table itself
  78940. ** is not used, its name is just '{}'. If no index is used
  78941. ** the index is listed as "{}". If the primary key is used the
  78942. ** index name is '*'.
  78943. */
  78944. for(i=0; i<pTabList->nSrc; i++){
  78945. char *z;
  78946. int n;
  78947. pLevel = &pWInfo->a[i];
  78948. pTabItem = &pTabList->a[pLevel->iFrom];
  78949. z = pTabItem->zAlias;
  78950. if( z==0 ) z = pTabItem->pTab->zName;
  78951. n = sqlite3Strlen30(z);
  78952. if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
  78953. if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
  78954. memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
  78955. nQPlan += 2;
  78956. }else{
  78957. memcpy(&sqlite3_query_plan[nQPlan], z, n);
  78958. nQPlan += n;
  78959. }
  78960. sqlite3_query_plan[nQPlan++] = ' ';
  78961. }
  78962. testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
  78963. testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
  78964. if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  78965. memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  78966. nQPlan += 2;
  78967. }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  78968. n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
  78969. if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
  78970. memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
  78971. nQPlan += n;
  78972. sqlite3_query_plan[nQPlan++] = ' ';
  78973. }
  78974. }else{
  78975. memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
  78976. nQPlan += 3;
  78977. }
  78978. }
  78979. while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  78980. sqlite3_query_plan[--nQPlan] = 0;
  78981. }
  78982. sqlite3_query_plan[nQPlan] = 0;
  78983. nQPlan = 0;
  78984. #endif /* SQLITE_TEST // Testing and debugging use only */
  78985. /* Record the continuation address in the WhereInfo structure. Then
  78986. ** clean up and return.
  78987. */
  78988. return pWInfo;
  78989. /* Jump here if malloc fails */
  78990. whereBeginError:
  78991. whereInfoFree(db, pWInfo);
  78992. return 0;
  78993. }
  78994. /*
  78995. ** Generate the end of the WHERE loop. See comments on
  78996. ** sqlite3WhereBegin() for additional information.
  78997. */
  78998. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  78999. Parse *pParse = pWInfo->pParse;
  79000. Vdbe *v = pParse->pVdbe;
  79001. int i;
  79002. WhereLevel *pLevel;
  79003. SrcList *pTabList = pWInfo->pTabList;
  79004. sqlite3 *db = pParse->db;
  79005. /* Generate loop termination code.
  79006. */
  79007. sqlite3ExprClearColumnCache(pParse, -1);
  79008. for(i=pTabList->nSrc-1; i>=0; i--){
  79009. pLevel = &pWInfo->a[i];
  79010. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  79011. if( pLevel->op!=OP_Noop ){
  79012. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  79013. sqlite3VdbeChangeP5(v, pLevel->p5);
  79014. }
  79015. if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  79016. struct InLoop *pIn;
  79017. int j;
  79018. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  79019. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  79020. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  79021. sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
  79022. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  79023. }
  79024. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  79025. }
  79026. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  79027. if( pLevel->iLeftJoin ){
  79028. int addr;
  79029. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  79030. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  79031. if( pLevel->iIdxCur>=0 ){
  79032. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  79033. }
  79034. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  79035. sqlite3VdbeJumpHere(v, addr);
  79036. }
  79037. }
  79038. /* The "break" point is here, just past the end of the outer loop.
  79039. ** Set it.
  79040. */
  79041. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  79042. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  79043. */
  79044. for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
  79045. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  79046. Table *pTab = pTabItem->pTab;
  79047. assert( pTab!=0 );
  79048. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
  79049. if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
  79050. if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
  79051. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  79052. }
  79053. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  79054. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  79055. }
  79056. }
  79057. /* If this scan uses an index, make code substitutions to read data
  79058. ** from the index in preference to the table. Sometimes, this means
  79059. ** the table need never be read from. This is a performance boost,
  79060. ** as the vdbe level waits until the table is read before actually
  79061. ** seeking the table cursor to the record corresponding to the current
  79062. ** position in the index.
  79063. **
  79064. ** Calls to the code generator in between sqlite3WhereBegin and
  79065. ** sqlite3WhereEnd will have created code that references the table
  79066. ** directly. This loop scans all that code looking for opcodes
  79067. ** that reference the table and converts them into opcodes that
  79068. ** reference the index.
  79069. */
  79070. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  79071. int k, j, last;
  79072. VdbeOp *pOp;
  79073. Index *pIdx = pLevel->plan.u.pIdx;
  79074. int useIndexOnly = pLevel->plan.wsFlags & WHERE_IDX_ONLY;
  79075. assert( pIdx!=0 );
  79076. pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
  79077. last = sqlite3VdbeCurrentAddr(v);
  79078. for(k=pWInfo->iTop; k<last; k++, pOp++){
  79079. if( pOp->p1!=pLevel->iTabCur ) continue;
  79080. if( pOp->opcode==OP_Column ){
  79081. for(j=0; j<pIdx->nColumn; j++){
  79082. if( pOp->p2==pIdx->aiColumn[j] ){
  79083. pOp->p2 = j;
  79084. pOp->p1 = pLevel->iIdxCur;
  79085. break;
  79086. }
  79087. }
  79088. assert(!useIndexOnly || j<pIdx->nColumn);
  79089. }else if( pOp->opcode==OP_Rowid ){
  79090. pOp->p1 = pLevel->iIdxCur;
  79091. pOp->opcode = OP_IdxRowid;
  79092. }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
  79093. pOp->opcode = OP_Noop;
  79094. }
  79095. }
  79096. }
  79097. }
  79098. /* Final cleanup
  79099. */
  79100. whereInfoFree(db, pWInfo);
  79101. return;
  79102. }
  79103. /************** End of where.c ***********************************************/
  79104. /************** Begin file parse.c *******************************************/
  79105. /* Driver template for the LEMON parser generator.
  79106. ** The author disclaims copyright to this source code.
  79107. */
  79108. /* First off, code is included that follows the "include" declaration
  79109. ** in the input grammar file. */
  79110. /*
  79111. ** An instance of this structure holds information about the
  79112. ** LIMIT clause of a SELECT statement.
  79113. */
  79114. struct LimitVal {
  79115. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  79116. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  79117. };
  79118. /*
  79119. ** An instance of this structure is used to store the LIKE,
  79120. ** GLOB, NOT LIKE, and NOT GLOB operators.
  79121. */
  79122. struct LikeOp {
  79123. Token eOperator; /* "like" or "glob" or "regexp" */
  79124. int not; /* True if the NOT keyword is present */
  79125. };
  79126. /*
  79127. ** An instance of the following structure describes the event of a
  79128. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  79129. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  79130. **
  79131. ** UPDATE ON (a,b,c)
  79132. **
  79133. ** Then the "b" IdList records the list "a,b,c".
  79134. */
  79135. struct TrigEvent { int a; IdList * b; };
  79136. /*
  79137. ** An instance of this structure holds the ATTACH key and the key type.
  79138. */
  79139. struct AttachKey { int type; Token key; };
  79140. /* Next is all token values, in a form suitable for use by makeheaders.
  79141. ** This section will be null unless lemon is run with the -m switch.
  79142. */
  79143. /*
  79144. ** These constants (all generated automatically by the parser generator)
  79145. ** specify the various kinds of tokens (terminals) that the parser
  79146. ** understands.
  79147. **
  79148. ** Each symbol here is a terminal symbol in the grammar.
  79149. */
  79150. /* Make sure the INTERFACE macro is defined.
  79151. */
  79152. #ifndef INTERFACE
  79153. # define INTERFACE 1
  79154. #endif
  79155. /* The next thing included is series of defines which control
  79156. ** various aspects of the generated parser.
  79157. ** YYCODETYPE is the data type used for storing terminal
  79158. ** and nonterminal numbers. "unsigned char" is
  79159. ** used if there are fewer than 250 terminals
  79160. ** and nonterminals. "int" is used otherwise.
  79161. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  79162. ** to no legal terminal or nonterminal number. This
  79163. ** number is used to fill in empty slots of the hash
  79164. ** table.
  79165. ** YYFALLBACK If defined, this indicates that one or more tokens
  79166. ** have fall-back values which should be used if the
  79167. ** original value of the token will not parse.
  79168. ** YYACTIONTYPE is the data type used for storing terminal
  79169. ** and nonterminal numbers. "unsigned char" is
  79170. ** used if there are fewer than 250 rules and
  79171. ** states combined. "int" is used otherwise.
  79172. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  79173. ** directly to the parser from the tokenizer.
  79174. ** YYMINORTYPE is the data type used for all minor tokens.
  79175. ** This is typically a union of many types, one of
  79176. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  79177. ** for base tokens is called "yy0".
  79178. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  79179. ** zero the stack is dynamically sized using realloc()
  79180. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  79181. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  79182. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  79183. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  79184. ** YYNSTATE the combined number of states.
  79185. ** YYNRULE the number of rules in the grammar
  79186. ** YYERRORSYMBOL is the code number of the error symbol. If not
  79187. ** defined, then do no error processing.
  79188. */
  79189. #define YYCODETYPE unsigned short int
  79190. #define YYNOCODE 252
  79191. #define YYACTIONTYPE unsigned short int
  79192. #define YYWILDCARD 65
  79193. #define sqlite3ParserTOKENTYPE Token
  79194. typedef union {
  79195. int yyinit;
  79196. sqlite3ParserTOKENTYPE yy0;
  79197. Expr* yy72;
  79198. TriggerStep* yy145;
  79199. ExprList* yy148;
  79200. SrcList* yy185;
  79201. int yy194;
  79202. Select* yy243;
  79203. IdList* yy254;
  79204. struct TrigEvent yy332;
  79205. struct LimitVal yy354;
  79206. struct LikeOp yy392;
  79207. struct {int value; int mask;} yy497;
  79208. } YYMINORTYPE;
  79209. #ifndef YYSTACKDEPTH
  79210. #define YYSTACKDEPTH 100
  79211. #endif
  79212. #define sqlite3ParserARG_SDECL Parse *pParse;
  79213. #define sqlite3ParserARG_PDECL ,Parse *pParse
  79214. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  79215. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  79216. #define YYNSTATE 616
  79217. #define YYNRULE 323
  79218. #define YYFALLBACK 1
  79219. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  79220. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  79221. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  79222. /* The yyzerominor constant is used to initialize instances of
  79223. ** YYMINORTYPE objects to zero. */
  79224. static const YYMINORTYPE yyzerominor = { 0 };
  79225. /* Next are the tables used to determine what action to take based on the
  79226. ** current state and lookahead token. These tables are used to implement
  79227. ** functions that take a state number and lookahead value and return an
  79228. ** action integer.
  79229. **
  79230. ** Suppose the action integer is N. Then the action is determined as
  79231. ** follows
  79232. **
  79233. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  79234. ** token onto the stack and goto state N.
  79235. **
  79236. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  79237. **
  79238. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  79239. **
  79240. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  79241. **
  79242. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  79243. ** slots in the yy_action[] table.
  79244. **
  79245. ** The action table is constructed as a single large table named yy_action[].
  79246. ** Given state S and lookahead X, the action is computed as
  79247. **
  79248. ** yy_action[ yy_shift_ofst[S] + X ]
  79249. **
  79250. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  79251. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  79252. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  79253. ** and that yy_default[S] should be used instead.
  79254. **
  79255. ** The formula above is for computing the action when the lookahead is
  79256. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  79257. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  79258. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  79259. ** YY_SHIFT_USE_DFLT.
  79260. **
  79261. ** The following are the tables generated in this section:
  79262. **
  79263. ** yy_action[] A single table containing all actions.
  79264. ** yy_lookahead[] A table containing the lookahead for each entry in
  79265. ** yy_action. Used to detect hash collisions.
  79266. ** yy_shift_ofst[] For each state, the offset into yy_action for
  79267. ** shifting terminals.
  79268. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  79269. ** shifting non-terminals after a reduce.
  79270. ** yy_default[] Default action for each state.
  79271. */
  79272. static const YYACTIONTYPE yy_action[] = {
  79273. /* 0 */ 304, 940, 176, 615, 2, 150, 214, 439, 24, 24,
  79274. /* 10 */ 24, 24, 488, 26, 26, 26, 26, 27, 27, 28,
  79275. /* 20 */ 28, 28, 29, 216, 413, 414, 212, 413, 414, 446,
  79276. /* 30 */ 452, 31, 26, 26, 26, 26, 27, 27, 28, 28,
  79277. /* 40 */ 28, 29, 216, 30, 483, 32, 134, 23, 22, 308,
  79278. /* 50 */ 456, 457, 453, 453, 25, 25, 24, 24, 24, 24,
  79279. /* 60 */ 436, 26, 26, 26, 26, 27, 27, 28, 28, 28,
  79280. /* 70 */ 29, 216, 304, 216, 311, 439, 512, 490, 45, 26,
  79281. /* 80 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 216,
  79282. /* 90 */ 413, 414, 416, 417, 156, 416, 417, 360, 363, 364,
  79283. /* 100 */ 311, 446, 452, 385, 514, 21, 186, 495, 365, 27,
  79284. /* 110 */ 27, 28, 28, 28, 29, 216, 413, 414, 415, 23,
  79285. /* 120 */ 22, 308, 456, 457, 453, 453, 25, 25, 24, 24,
  79286. /* 130 */ 24, 24, 555, 26, 26, 26, 26, 27, 27, 28,
  79287. /* 140 */ 28, 28, 29, 216, 304, 228, 504, 135, 468, 218,
  79288. /* 150 */ 548, 145, 132, 256, 358, 261, 359, 153, 416, 417,
  79289. /* 160 */ 241, 598, 331, 30, 265, 32, 134, 439, 596, 597,
  79290. /* 170 */ 230, 228, 490, 446, 452, 57, 506, 328, 132, 256,
  79291. /* 180 */ 358, 261, 359, 153, 416, 417, 435, 78, 408, 405,
  79292. /* 190 */ 265, 23, 22, 308, 456, 457, 453, 453, 25, 25,
  79293. /* 200 */ 24, 24, 24, 24, 342, 26, 26, 26, 26, 27,
  79294. /* 210 */ 27, 28, 28, 28, 29, 216, 304, 214, 534, 547,
  79295. /* 220 */ 307, 127, 489, 595, 30, 331, 32, 134, 345, 387,
  79296. /* 230 */ 429, 63, 331, 355, 415, 439, 507, 331, 415, 535,
  79297. /* 240 */ 328, 215, 193, 594, 593, 446, 452, 328, 18, 435,
  79298. /* 250 */ 85, 16, 328, 183, 190, 556, 435, 78, 309, 463,
  79299. /* 260 */ 464, 435, 85, 23, 22, 308, 456, 457, 453, 453,
  79300. /* 270 */ 25, 25, 24, 24, 24, 24, 436, 26, 26, 26,
  79301. /* 280 */ 26, 27, 27, 28, 28, 28, 29, 216, 304, 347,
  79302. /* 290 */ 221, 313, 595, 191, 378, 331, 472, 234, 345, 381,
  79303. /* 300 */ 324, 410, 220, 344, 592, 217, 213, 415, 112, 331,
  79304. /* 310 */ 328, 4, 594, 399, 211, 554, 529, 446, 452, 435,
  79305. /* 320 */ 79, 217, 553, 515, 328, 334, 513, 459, 459, 469,
  79306. /* 330 */ 441, 572, 432, 435, 78, 23, 22, 308, 456, 457,
  79307. /* 340 */ 453, 453, 25, 25, 24, 24, 24, 24, 436, 26,
  79308. /* 350 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 216,
  79309. /* 360 */ 304, 443, 443, 443, 156, 468, 218, 360, 363, 364,
  79310. /* 370 */ 331, 247, 395, 398, 217, 349, 331, 30, 365, 32,
  79311. /* 380 */ 134, 388, 282, 281, 39, 328, 41, 430, 545, 446,
  79312. /* 390 */ 452, 328, 214, 531, 435, 93, 542, 601, 1, 404,
  79313. /* 400 */ 435, 93, 413, 414, 495, 40, 536, 23, 22, 308,
  79314. /* 410 */ 456, 457, 453, 453, 25, 25, 24, 24, 24, 24,
  79315. /* 420 */ 573, 26, 26, 26, 26, 27, 27, 28, 28, 28,
  79316. /* 430 */ 29, 216, 304, 276, 331, 179, 508, 490, 210, 547,
  79317. /* 440 */ 319, 413, 414, 222, 192, 385, 320, 240, 415, 328,
  79318. /* 450 */ 557, 63, 413, 414, 415, 616, 408, 405, 435, 71,
  79319. /* 460 */ 415, 446, 452, 611, 572, 28, 28, 28, 29, 216,
  79320. /* 470 */ 416, 417, 436, 336, 463, 464, 401, 43, 436, 23,
  79321. /* 480 */ 22, 308, 456, 457, 453, 453, 25, 25, 24, 24,
  79322. /* 490 */ 24, 24, 495, 26, 26, 26, 26, 27, 27, 28,
  79323. /* 500 */ 28, 28, 29, 216, 304, 612, 209, 135, 511, 416,
  79324. /* 510 */ 417, 431, 233, 64, 388, 282, 281, 439, 66, 542,
  79325. /* 520 */ 416, 417, 413, 414, 156, 214, 403, 360, 363, 364,
  79326. /* 530 */ 547, 252, 490, 446, 452, 491, 217, 8, 365, 495,
  79327. /* 540 */ 436, 606, 63, 537, 299, 415, 492, 470, 546, 200,
  79328. /* 550 */ 196, 23, 22, 308, 456, 457, 453, 453, 25, 25,
  79329. /* 560 */ 24, 24, 24, 24, 386, 26, 26, 26, 26, 27,
  79330. /* 570 */ 27, 28, 28, 28, 29, 216, 304, 477, 254, 354,
  79331. /* 580 */ 528, 60, 517, 518, 436, 439, 389, 331, 356, 7,
  79332. /* 590 */ 416, 417, 331, 478, 328, 208, 197, 137, 460, 499,
  79333. /* 600 */ 447, 448, 328, 435, 9, 446, 452, 328, 479, 485,
  79334. /* 610 */ 519, 435, 72, 567, 415, 434, 435, 67, 486, 433,
  79335. /* 620 */ 520, 450, 451, 23, 22, 308, 456, 457, 453, 453,
  79336. /* 630 */ 25, 25, 24, 24, 24, 24, 331, 26, 26, 26,
  79337. /* 640 */ 26, 27, 27, 28, 28, 28, 29, 216, 304, 331,
  79338. /* 650 */ 449, 328, 268, 390, 461, 331, 65, 331, 368, 434,
  79339. /* 660 */ 435, 76, 310, 433, 328, 150, 427, 439, 473, 331,
  79340. /* 670 */ 328, 499, 328, 435, 97, 29, 216, 446, 452, 435,
  79341. /* 680 */ 96, 435, 101, 353, 328, 372, 415, 334, 154, 459,
  79342. /* 690 */ 459, 352, 569, 435, 99, 23, 22, 308, 456, 457,
  79343. /* 700 */ 453, 453, 25, 25, 24, 24, 24, 24, 331, 26,
  79344. /* 710 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 216,
  79345. /* 720 */ 304, 331, 248, 328, 264, 56, 334, 331, 459, 459,
  79346. /* 730 */ 861, 333, 435, 104, 376, 439, 328, 415, 331, 415,
  79347. /* 740 */ 565, 331, 328, 306, 564, 435, 105, 185, 265, 446,
  79348. /* 750 */ 452, 435, 126, 328, 570, 518, 328, 334, 377, 459,
  79349. /* 760 */ 459, 314, 435, 128, 194, 435, 59, 23, 22, 308,
  79350. /* 770 */ 456, 457, 453, 453, 25, 25, 24, 24, 24, 24,
  79351. /* 780 */ 331, 26, 26, 26, 26, 27, 27, 28, 28, 28,
  79352. /* 790 */ 29, 216, 304, 331, 136, 328, 242, 477, 436, 331,
  79353. /* 800 */ 350, 331, 609, 303, 435, 102, 201, 137, 328, 415,
  79354. /* 810 */ 454, 178, 331, 478, 328, 415, 328, 435, 77, 440,
  79355. /* 820 */ 249, 446, 452, 435, 100, 435, 68, 328, 479, 465,
  79356. /* 830 */ 341, 613, 931, 484, 931, 415, 435, 98, 467, 23,
  79357. /* 840 */ 22, 308, 456, 457, 453, 453, 25, 25, 24, 24,
  79358. /* 850 */ 24, 24, 331, 26, 26, 26, 26, 27, 27, 28,
  79359. /* 860 */ 28, 28, 29, 216, 304, 331, 397, 328, 164, 264,
  79360. /* 870 */ 205, 331, 264, 332, 610, 339, 435, 129, 407, 2,
  79361. /* 880 */ 328, 322, 175, 331, 415, 214, 328, 415, 415, 435,
  79362. /* 890 */ 130, 466, 466, 446, 452, 435, 131, 396, 328, 257,
  79363. /* 900 */ 334, 487, 459, 459, 436, 154, 229, 435, 69, 315,
  79364. /* 910 */ 258, 23, 33, 308, 456, 457, 453, 453, 25, 25,
  79365. /* 920 */ 24, 24, 24, 24, 331, 26, 26, 26, 26, 27,
  79366. /* 930 */ 27, 28, 28, 28, 29, 216, 304, 331, 497, 328,
  79367. /* 940 */ 151, 264, 412, 331, 264, 470, 337, 200, 435, 80,
  79368. /* 950 */ 250, 155, 328, 523, 524, 331, 415, 415, 328, 415,
  79369. /* 960 */ 306, 435, 81, 533, 532, 446, 452, 435, 70, 47,
  79370. /* 970 */ 328, 613, 930, 259, 930, 418, 419, 420, 316, 435,
  79371. /* 980 */ 82, 317, 206, 539, 22, 308, 456, 457, 453, 453,
  79372. /* 990 */ 25, 25, 24, 24, 24, 24, 331, 26, 26, 26,
  79373. /* 1000 */ 26, 27, 27, 28, 28, 28, 29, 216, 304, 331,
  79374. /* 1010 */ 209, 328, 529, 540, 610, 331, 436, 563, 375, 563,
  79375. /* 1020 */ 435, 83, 362, 538, 328, 155, 541, 331, 499, 526,
  79376. /* 1030 */ 328, 331, 575, 435, 84, 424, 543, 446, 452, 435,
  79377. /* 1040 */ 86, 290, 328, 415, 436, 267, 328, 155, 394, 141,
  79378. /* 1050 */ 415, 435, 87, 588, 411, 435, 88, 308, 456, 457,
  79379. /* 1060 */ 453, 453, 25, 25, 24, 24, 24, 24, 386, 26,
  79380. /* 1070 */ 26, 26, 26, 27, 27, 28, 28, 28, 29, 216,
  79381. /* 1080 */ 35, 338, 286, 3, 331, 270, 331, 327, 414, 421,
  79382. /* 1090 */ 382, 318, 276, 422, 325, 35, 338, 335, 3, 328,
  79383. /* 1100 */ 423, 328, 327, 414, 142, 144, 276, 415, 435, 73,
  79384. /* 1110 */ 435, 74, 335, 331, 6, 340, 425, 331, 326, 331,
  79385. /* 1120 */ 367, 415, 155, 437, 289, 472, 287, 274, 328, 272,
  79386. /* 1130 */ 340, 415, 328, 47, 328, 277, 276, 435, 89, 348,
  79387. /* 1140 */ 472, 435, 90, 435, 91, 38, 37, 243, 331, 582,
  79388. /* 1150 */ 244, 415, 426, 276, 36, 329, 330, 46, 245, 441,
  79389. /* 1160 */ 38, 37, 505, 328, 202, 203, 204, 415, 415, 36,
  79390. /* 1170 */ 329, 330, 435, 92, 441, 198, 568, 214, 155, 584,
  79391. /* 1180 */ 235, 236, 237, 143, 239, 346, 133, 581, 438, 246,
  79392. /* 1190 */ 443, 443, 443, 444, 445, 10, 585, 276, 20, 42,
  79393. /* 1200 */ 172, 415, 294, 331, 288, 443, 443, 443, 444, 445,
  79394. /* 1210 */ 10, 295, 415, 35, 338, 219, 3, 149, 328, 482,
  79395. /* 1220 */ 327, 414, 331, 170, 276, 572, 48, 435, 75, 169,
  79396. /* 1230 */ 335, 19, 171, 251, 442, 413, 414, 328, 331, 415,
  79397. /* 1240 */ 586, 343, 276, 177, 351, 496, 435, 17, 340, 415,
  79398. /* 1250 */ 481, 253, 255, 328, 276, 502, 415, 415, 472, 331,
  79399. /* 1260 */ 503, 357, 435, 94, 576, 415, 151, 231, 312, 415,
  79400. /* 1270 */ 577, 516, 54, 472, 328, 393, 291, 281, 38, 37,
  79401. /* 1280 */ 494, 305, 521, 435, 95, 232, 214, 36, 329, 330,
  79402. /* 1290 */ 526, 498, 441, 188, 189, 415, 500, 292, 522, 262,
  79403. /* 1300 */ 530, 260, 263, 513, 549, 269, 415, 441, 589, 400,
  79404. /* 1310 */ 54, 415, 525, 527, 415, 415, 271, 415, 273, 415,
  79405. /* 1320 */ 415, 275, 280, 443, 443, 443, 444, 445, 10, 107,
  79406. /* 1330 */ 380, 415, 383, 415, 384, 283, 415, 415, 443, 443,
  79407. /* 1340 */ 443, 284, 285, 580, 300, 415, 591, 415, 293, 415,
  79408. /* 1350 */ 415, 296, 297, 605, 226, 550, 415, 415, 415, 225,
  79409. /* 1360 */ 608, 415, 302, 415, 551, 227, 415, 415, 415, 301,
  79410. /* 1370 */ 544, 552, 369, 158, 373, 558, 159, 278, 371, 160,
  79411. /* 1380 */ 51, 207, 560, 561, 161, 140, 379, 117, 571, 163,
  79412. /* 1390 */ 391, 392, 181, 180, 321, 602, 578, 118, 119, 120,
  79413. /* 1400 */ 121, 123, 55, 587, 58, 603, 604, 607, 62, 174,
  79414. /* 1410 */ 103, 224, 111, 409, 238, 428, 199, 323, 657, 658,
  79415. /* 1420 */ 659, 146, 147, 455, 458, 34, 474, 462, 471, 182,
  79416. /* 1430 */ 195, 148, 475, 476, 480, 5, 12, 493, 44, 11,
  79417. /* 1440 */ 106, 138, 509, 510, 501, 223, 49, 361, 108, 109,
  79418. /* 1450 */ 152, 266, 50, 110, 157, 258, 370, 184, 559, 139,
  79419. /* 1460 */ 151, 113, 279, 162, 115, 374, 15, 574, 116, 165,
  79420. /* 1470 */ 52, 13, 366, 579, 53, 167, 168, 166, 583, 124,
  79421. /* 1480 */ 114, 122, 562, 566, 14, 61, 599, 600, 125, 173,
  79422. /* 1490 */ 298, 590, 187, 406, 941, 614, 941, 402,
  79423. };
  79424. static const YYCODETYPE yy_lookahead[] = {
  79425. /* 0 */ 19, 142, 143, 144, 145, 24, 116, 26, 75, 76,
  79426. /* 10 */ 77, 78, 25, 80, 81, 82, 83, 84, 85, 86,
  79427. /* 20 */ 87, 88, 89, 90, 26, 27, 160, 26, 27, 48,
  79428. /* 30 */ 49, 79, 80, 81, 82, 83, 84, 85, 86, 87,
  79429. /* 40 */ 88, 89, 90, 222, 223, 224, 225, 66, 67, 68,
  79430. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  79431. /* 60 */ 194, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  79432. /* 70 */ 89, 90, 19, 90, 19, 94, 174, 25, 25, 80,
  79433. /* 80 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  79434. /* 90 */ 26, 27, 94, 95, 96, 94, 95, 99, 100, 101,
  79435. /* 100 */ 19, 48, 49, 150, 174, 52, 119, 166, 110, 84,
  79436. /* 110 */ 85, 86, 87, 88, 89, 90, 26, 27, 165, 66,
  79437. /* 120 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  79438. /* 130 */ 77, 78, 186, 80, 81, 82, 83, 84, 85, 86,
  79439. /* 140 */ 87, 88, 89, 90, 19, 90, 205, 95, 84, 85,
  79440. /* 150 */ 186, 96, 97, 98, 99, 100, 101, 102, 94, 95,
  79441. /* 160 */ 195, 97, 150, 222, 109, 224, 225, 26, 104, 105,
  79442. /* 170 */ 217, 90, 120, 48, 49, 50, 86, 165, 97, 98,
  79443. /* 180 */ 99, 100, 101, 102, 94, 95, 174, 175, 1, 2,
  79444. /* 190 */ 109, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  79445. /* 200 */ 75, 76, 77, 78, 191, 80, 81, 82, 83, 84,
  79446. /* 210 */ 85, 86, 87, 88, 89, 90, 19, 116, 35, 150,
  79447. /* 220 */ 155, 24, 208, 150, 222, 150, 224, 225, 216, 128,
  79448. /* 230 */ 161, 162, 150, 221, 165, 94, 23, 150, 165, 56,
  79449. /* 240 */ 165, 197, 160, 170, 171, 48, 49, 165, 204, 174,
  79450. /* 250 */ 175, 22, 165, 24, 185, 186, 174, 175, 169, 170,
  79451. /* 260 */ 171, 174, 175, 66, 67, 68, 69, 70, 71, 72,
  79452. /* 270 */ 73, 74, 75, 76, 77, 78, 194, 80, 81, 82,
  79453. /* 280 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 214,
  79454. /* 290 */ 215, 108, 150, 25, 229, 150, 64, 148, 216, 234,
  79455. /* 300 */ 146, 147, 215, 221, 231, 232, 152, 165, 154, 150,
  79456. /* 310 */ 165, 196, 170, 171, 160, 181, 182, 48, 49, 174,
  79457. /* 320 */ 175, 232, 188, 165, 165, 112, 94, 114, 115, 166,
  79458. /* 330 */ 98, 55, 174, 174, 175, 66, 67, 68, 69, 70,
  79459. /* 340 */ 71, 72, 73, 74, 75, 76, 77, 78, 194, 80,
  79460. /* 350 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  79461. /* 360 */ 19, 129, 130, 131, 96, 84, 85, 99, 100, 101,
  79462. /* 370 */ 150, 226, 218, 231, 232, 216, 150, 222, 110, 224,
  79463. /* 380 */ 225, 105, 106, 107, 135, 165, 137, 172, 173, 48,
  79464. /* 390 */ 49, 165, 116, 183, 174, 175, 181, 242, 22, 245,
  79465. /* 400 */ 174, 175, 26, 27, 166, 136, 183, 66, 67, 68,
  79466. /* 410 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  79467. /* 420 */ 11, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  79468. /* 430 */ 89, 90, 19, 150, 150, 23, 23, 25, 160, 150,
  79469. /* 440 */ 220, 26, 27, 205, 160, 150, 220, 158, 165, 165,
  79470. /* 450 */ 161, 162, 26, 27, 165, 0, 1, 2, 174, 175,
  79471. /* 460 */ 165, 48, 49, 23, 55, 86, 87, 88, 89, 90,
  79472. /* 470 */ 94, 95, 194, 169, 170, 171, 193, 136, 194, 66,
  79473. /* 480 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  79474. /* 490 */ 77, 78, 166, 80, 81, 82, 83, 84, 85, 86,
  79475. /* 500 */ 87, 88, 89, 90, 19, 65, 160, 95, 23, 94,
  79476. /* 510 */ 95, 173, 217, 22, 105, 106, 107, 26, 22, 181,
  79477. /* 520 */ 94, 95, 26, 27, 96, 116, 243, 99, 100, 101,
  79478. /* 530 */ 150, 205, 120, 48, 49, 120, 232, 22, 110, 166,
  79479. /* 540 */ 194, 161, 162, 183, 163, 165, 120, 166, 167, 168,
  79480. /* 550 */ 160, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  79481. /* 560 */ 75, 76, 77, 78, 218, 80, 81, 82, 83, 84,
  79482. /* 570 */ 85, 86, 87, 88, 89, 90, 19, 12, 205, 150,
  79483. /* 580 */ 23, 235, 190, 191, 194, 94, 240, 150, 86, 74,
  79484. /* 590 */ 94, 95, 150, 28, 165, 236, 206, 207, 23, 150,
  79485. /* 600 */ 48, 49, 165, 174, 175, 48, 49, 165, 43, 31,
  79486. /* 610 */ 45, 174, 175, 21, 165, 113, 174, 175, 40, 117,
  79487. /* 620 */ 55, 69, 70, 66, 67, 68, 69, 70, 71, 72,
  79488. /* 630 */ 73, 74, 75, 76, 77, 78, 150, 80, 81, 82,
  79489. /* 640 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 150,
  79490. /* 650 */ 98, 165, 23, 61, 23, 150, 25, 150, 19, 113,
  79491. /* 660 */ 174, 175, 213, 117, 165, 24, 153, 26, 23, 150,
  79492. /* 670 */ 165, 150, 165, 174, 175, 89, 90, 48, 49, 174,
  79493. /* 680 */ 175, 174, 175, 19, 165, 237, 165, 112, 49, 114,
  79494. /* 690 */ 115, 27, 100, 174, 175, 66, 67, 68, 69, 70,
  79495. /* 700 */ 71, 72, 73, 74, 75, 76, 77, 78, 150, 80,
  79496. /* 710 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  79497. /* 720 */ 19, 150, 150, 165, 150, 24, 112, 150, 114, 115,
  79498. /* 730 */ 138, 19, 174, 175, 213, 94, 165, 165, 150, 165,
  79499. /* 740 */ 29, 150, 165, 104, 33, 174, 175, 196, 109, 48,
  79500. /* 750 */ 49, 174, 175, 165, 190, 191, 165, 112, 47, 114,
  79501. /* 760 */ 115, 187, 174, 175, 160, 174, 175, 66, 67, 68,
  79502. /* 770 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  79503. /* 780 */ 150, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  79504. /* 790 */ 89, 90, 19, 150, 150, 165, 198, 12, 194, 150,
  79505. /* 800 */ 150, 150, 248, 249, 174, 175, 206, 207, 165, 165,
  79506. /* 810 */ 98, 23, 150, 28, 165, 165, 165, 174, 175, 166,
  79507. /* 820 */ 150, 48, 49, 174, 175, 174, 175, 165, 43, 233,
  79508. /* 830 */ 45, 22, 23, 177, 25, 165, 174, 175, 233, 66,
  79509. /* 840 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  79510. /* 850 */ 77, 78, 150, 80, 81, 82, 83, 84, 85, 86,
  79511. /* 860 */ 87, 88, 89, 90, 19, 150, 97, 165, 25, 150,
  79512. /* 870 */ 160, 150, 150, 150, 65, 228, 174, 175, 144, 145,
  79513. /* 880 */ 165, 246, 247, 150, 165, 116, 165, 165, 165, 174,
  79514. /* 890 */ 175, 129, 130, 48, 49, 174, 175, 128, 165, 98,
  79515. /* 900 */ 112, 177, 114, 115, 194, 49, 187, 174, 175, 187,
  79516. /* 910 */ 109, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  79517. /* 920 */ 75, 76, 77, 78, 150, 80, 81, 82, 83, 84,
  79518. /* 930 */ 85, 86, 87, 88, 89, 90, 19, 150, 23, 165,
  79519. /* 940 */ 25, 150, 150, 150, 150, 166, 167, 168, 174, 175,
  79520. /* 950 */ 209, 25, 165, 7, 8, 150, 165, 165, 165, 165,
  79521. /* 960 */ 104, 174, 175, 97, 98, 48, 49, 174, 175, 126,
  79522. /* 970 */ 165, 22, 23, 177, 25, 7, 8, 9, 187, 174,
  79523. /* 980 */ 175, 187, 160, 177, 67, 68, 69, 70, 71, 72,
  79524. /* 990 */ 73, 74, 75, 76, 77, 78, 150, 80, 81, 82,
  79525. /* 1000 */ 83, 84, 85, 86, 87, 88, 89, 90, 19, 150,
  79526. /* 1010 */ 160, 165, 182, 166, 65, 150, 194, 105, 106, 107,
  79527. /* 1020 */ 174, 175, 178, 23, 165, 25, 177, 150, 150, 103,
  79528. /* 1030 */ 165, 150, 199, 174, 175, 150, 166, 48, 49, 174,
  79529. /* 1040 */ 175, 209, 165, 165, 194, 23, 165, 25, 209, 6,
  79530. /* 1050 */ 165, 174, 175, 199, 149, 174, 175, 68, 69, 70,
  79531. /* 1060 */ 71, 72, 73, 74, 75, 76, 77, 78, 218, 80,
  79532. /* 1070 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  79533. /* 1080 */ 19, 20, 16, 22, 150, 16, 150, 26, 27, 149,
  79534. /* 1090 */ 240, 213, 150, 149, 149, 19, 20, 36, 22, 165,
  79535. /* 1100 */ 13, 165, 26, 27, 151, 151, 150, 165, 174, 175,
  79536. /* 1110 */ 174, 175, 36, 150, 25, 54, 150, 150, 159, 150,
  79537. /* 1120 */ 23, 165, 25, 194, 58, 64, 60, 58, 165, 60,
  79538. /* 1130 */ 54, 165, 165, 126, 165, 193, 150, 174, 175, 123,
  79539. /* 1140 */ 64, 174, 175, 174, 175, 84, 85, 199, 150, 193,
  79540. /* 1150 */ 200, 165, 150, 150, 93, 94, 95, 124, 201, 98,
  79541. /* 1160 */ 84, 85, 86, 165, 105, 106, 107, 165, 165, 93,
  79542. /* 1170 */ 94, 95, 174, 175, 98, 5, 23, 116, 25, 193,
  79543. /* 1180 */ 10, 11, 12, 13, 14, 122, 150, 17, 203, 202,
  79544. /* 1190 */ 129, 130, 131, 132, 133, 134, 193, 150, 125, 135,
  79545. /* 1200 */ 30, 165, 32, 150, 138, 129, 130, 131, 132, 133,
  79546. /* 1210 */ 134, 41, 165, 19, 20, 227, 22, 118, 165, 157,
  79547. /* 1220 */ 26, 27, 150, 53, 150, 55, 104, 174, 175, 59,
  79548. /* 1230 */ 36, 22, 62, 210, 150, 26, 27, 165, 150, 165,
  79549. /* 1240 */ 193, 150, 150, 157, 121, 211, 174, 175, 54, 165,
  79550. /* 1250 */ 150, 210, 210, 165, 150, 211, 165, 165, 64, 150,
  79551. /* 1260 */ 211, 104, 174, 175, 23, 165, 25, 193, 46, 165,
  79552. /* 1270 */ 23, 176, 25, 64, 165, 105, 106, 107, 84, 85,
  79553. /* 1280 */ 150, 111, 176, 174, 175, 193, 116, 93, 94, 95,
  79554. /* 1290 */ 103, 150, 98, 84, 85, 165, 150, 193, 184, 150,
  79555. /* 1300 */ 150, 176, 150, 94, 150, 150, 165, 98, 23, 139,
  79556. /* 1310 */ 25, 165, 178, 176, 165, 165, 150, 165, 150, 165,
  79557. /* 1320 */ 165, 150, 150, 129, 130, 131, 132, 133, 134, 22,
  79558. /* 1330 */ 150, 165, 150, 165, 150, 150, 165, 165, 129, 130,
  79559. /* 1340 */ 131, 150, 150, 150, 179, 165, 150, 165, 150, 165,
  79560. /* 1350 */ 165, 150, 150, 150, 90, 176, 165, 165, 165, 230,
  79561. /* 1360 */ 23, 165, 25, 165, 176, 230, 165, 165, 165, 179,
  79562. /* 1370 */ 184, 176, 18, 156, 44, 157, 156, 238, 157, 156,
  79563. /* 1380 */ 135, 157, 157, 239, 156, 66, 157, 22, 189, 189,
  79564. /* 1390 */ 157, 18, 219, 219, 157, 39, 199, 192, 192, 192,
  79565. /* 1400 */ 192, 189, 241, 199, 241, 157, 157, 37, 244, 247,
  79566. /* 1410 */ 164, 180, 180, 1, 15, 23, 22, 250, 118, 118,
  79567. /* 1420 */ 118, 118, 118, 98, 113, 22, 11, 23, 23, 22,
  79568. /* 1430 */ 22, 25, 23, 23, 23, 34, 34, 120, 25, 25,
  79569. /* 1440 */ 22, 118, 23, 23, 27, 50, 22, 50, 22, 22,
  79570. /* 1450 */ 34, 23, 22, 22, 102, 109, 19, 24, 20, 38,
  79571. /* 1460 */ 25, 104, 138, 104, 22, 42, 5, 1, 108, 127,
  79572. /* 1470 */ 74, 22, 50, 1, 74, 16, 121, 119, 20, 108,
  79573. /* 1480 */ 51, 119, 57, 51, 22, 16, 23, 23, 127, 15,
  79574. /* 1490 */ 140, 128, 22, 3, 251, 4, 251, 63,
  79575. };
  79576. #define YY_SHIFT_USE_DFLT (-111)
  79577. #define YY_SHIFT_MAX 406
  79578. static const short yy_shift_ofst[] = {
  79579. /* 0 */ 187, 1061, 1170, 1061, 1194, 1194, -2, 64, 64, -19,
  79580. /* 10 */ 1194, 1194, 1194, 1194, 1194, 276, 1, 125, 1076, 1194,
  79581. /* 20 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
  79582. /* 30 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
  79583. /* 40 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
  79584. /* 50 */ 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, -48,
  79585. /* 60 */ 409, 1, 1, 141, 281, 281, -110, 53, 197, 269,
  79586. /* 70 */ 341, 413, 485, 557, 629, 701, 773, 845, 773, 773,
  79587. /* 80 */ 773, 773, 773, 773, 773, 773, 773, 773, 773, 773,
  79588. /* 90 */ 773, 773, 773, 773, 773, 773, 917, 989, 989, -67,
  79589. /* 100 */ -67, -1, -1, 55, 25, 379, 1, 1, 1, 1,
  79590. /* 110 */ 1, 639, 592, 1, 1, 1, 1, 1, 1, 1,
  79591. /* 120 */ 1, 1, 1, 1, 1, 1, 586, 141, -17, -111,
  79592. /* 130 */ -111, -111, 1209, 81, 376, 415, 426, 496, 90, 565,
  79593. /* 140 */ 565, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  79594. /* 150 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  79595. /* 160 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  79596. /* 170 */ 1, 1, 1, 1, 809, 949, 455, 641, 641, 641,
  79597. /* 180 */ 769, 101, -110, -110, -110, -111, -111, -111, 232, 232,
  79598. /* 190 */ 268, 428, 213, 575, 645, 785, 788, 412, 968, 502,
  79599. /* 200 */ 491, 52, 183, 183, 183, 614, 614, 711, 912, 614,
  79600. /* 210 */ 614, 614, 614, 229, 546, -13, 141, 762, 762, 249,
  79601. /* 220 */ 578, 578, 664, 578, 856, 578, 141, 578, 141, 926,
  79602. /* 230 */ 843, 664, 664, 843, 1043, 1043, 1043, 1043, 1087, 1087,
  79603. /* 240 */ 1089, -110, 1007, 1016, 1033, 1063, 1073, 1064, 1099, 1099,
  79604. /* 250 */ 1122, 1123, 1122, 1123, 1122, 1123, 1157, 1157, 1222, 1157,
  79605. /* 260 */ 1187, 1157, 1307, 1264, 1264, 1222, 1157, 1157, 1157, 1307,
  79606. /* 270 */ 1354, 1099, 1354, 1099, 1354, 1099, 1099, 1330, 1245, 1354,
  79607. /* 280 */ 1099, 1319, 1319, 1365, 1007, 1099, 1373, 1373, 1373, 1373,
  79608. /* 290 */ 1007, 1319, 1365, 1099, 1356, 1356, 1099, 1099, 1370, -111,
  79609. /* 300 */ -111, -111, -111, -111, 552, 1066, 1059, 1069, 712, 631,
  79610. /* 310 */ 915, 801, 946, 866, 1000, 1022, 1097, 1153, 1241, 1247,
  79611. /* 320 */ 1285, 515, 1337, 440, 1412, 1399, 1392, 1394, 1300, 1301,
  79612. /* 330 */ 1302, 1303, 1304, 1325, 1311, 1403, 1404, 1405, 1407, 1415,
  79613. /* 340 */ 1408, 1409, 1406, 1410, 1411, 1413, 1401, 1414, 1402, 1413,
  79614. /* 350 */ 1317, 1418, 1416, 1417, 1323, 1419, 1420, 1421, 1395, 1424,
  79615. /* 360 */ 1397, 1426, 1428, 1427, 1430, 1422, 1431, 1352, 1346, 1437,
  79616. /* 370 */ 1438, 1433, 1357, 1423, 1425, 1429, 1435, 1432, 1324, 1359,
  79617. /* 380 */ 1442, 1461, 1466, 1360, 1396, 1400, 1342, 1449, 1358, 1472,
  79618. /* 390 */ 1459, 1355, 1458, 1362, 1371, 1361, 1462, 1363, 1463, 1464,
  79619. /* 400 */ 1469, 1434, 1474, 1350, 1470, 1490, 1491,
  79620. };
  79621. #define YY_REDUCE_USE_DFLT (-180)
  79622. #define YY_REDUCE_MAX 303
  79623. static const short yy_reduce_ofst[] = {
  79624. /* 0 */ -141, 82, 154, 284, 12, 75, 69, 73, 142, -59,
  79625. /* 10 */ 145, 87, 159, 220, 226, 346, 289, 155, 429, 437,
  79626. /* 20 */ 442, 486, 499, 505, 507, 519, 558, 571, 577, 588,
  79627. /* 30 */ 591, 630, 643, 649, 651, 662, 702, 715, 721, 733,
  79628. /* 40 */ 774, 787, 793, 805, 846, 859, 865, 877, 881, 934,
  79629. /* 50 */ 936, 963, 967, 969, 998, 1053, 1072, 1088, 1109, -179,
  79630. /* 60 */ 850, 283, 380, 381, 89, 304, 390, 2, 2, 2,
  79631. /* 70 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  79632. /* 80 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  79633. /* 90 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  79634. /* 100 */ 2, 2, 2, 215, 2, 2, 449, 574, 719, 722,
  79635. /* 110 */ 791, 134, 65, 942, 521, 794, -47, 878, 956, 986,
  79636. /* 120 */ 1003, 1047, 1074, 1092, 295, 1104, 2, 779, 2, 2,
  79637. /* 130 */ 2, 2, 158, 338, 572, 644, 650, 670, 723, 392,
  79638. /* 140 */ 564, 792, 885, 966, 1002, 1036, 723, 1084, 1091, 1100,
  79639. /* 150 */ 1130, 1141, 1146, 1149, 1150, 1152, 1154, 1155, 1166, 1168,
  79640. /* 160 */ 1171, 1172, 1180, 1182, 1184, 1185, 1191, 1192, 1193, 1196,
  79641. /* 170 */ 1198, 1201, 1202, 1203, 554, 554, 734, 238, 326, 373,
  79642. /* 180 */ -134, 278, 604, 710, 822, 44, 600, 635, -98, -70,
  79643. /* 190 */ -54, -36, -35, -35, -35, 13, -35, 14, 149, 115,
  79644. /* 200 */ 163, 14, 210, 223, 360, -35, -35, 359, 448, -35,
  79645. /* 210 */ -35, -35, -35, 513, 551, 598, 653, 596, 605, 647,
  79646. /* 220 */ 656, 724, 741, 796, 830, 806, 847, 849, 870, 844,
  79647. /* 230 */ 833, 832, 839, 854, 905, 940, 944, 945, 953, 954,
  79648. /* 240 */ 959, 929, 948, 950, 957, 987, 985, 988, 1062, 1086,
  79649. /* 250 */ 1023, 1034, 1041, 1044, 1042, 1049, 1095, 1106, 1114, 1125,
  79650. /* 260 */ 1134, 1137, 1165, 1129, 1135, 1186, 1179, 1188, 1195, 1190,
  79651. /* 270 */ 1217, 1218, 1220, 1221, 1223, 1224, 1225, 1139, 1144, 1228,
  79652. /* 280 */ 1229, 1199, 1200, 1173, 1197, 1233, 1205, 1206, 1207, 1208,
  79653. /* 290 */ 1204, 1212, 1174, 1237, 1161, 1163, 1248, 1249, 1164, 1246,
  79654. /* 300 */ 1231, 1232, 1162, 1167,
  79655. };
  79656. static const YYACTIONTYPE yy_default[] = {
  79657. /* 0 */ 621, 856, 939, 939, 856, 939, 939, 885, 885, 744,
  79658. /* 10 */ 854, 939, 939, 939, 939, 939, 939, 914, 939, 939,
  79659. /* 20 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79660. /* 30 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79661. /* 40 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79662. /* 50 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 828,
  79663. /* 60 */ 939, 939, 939, 660, 885, 885, 748, 779, 939, 939,
  79664. /* 70 */ 939, 939, 939, 939, 939, 939, 780, 939, 858, 853,
  79665. /* 80 */ 849, 851, 850, 857, 781, 770, 777, 784, 759, 898,
  79666. /* 90 */ 786, 787, 793, 794, 915, 913, 816, 815, 834, 818,
  79667. /* 100 */ 840, 817, 827, 652, 819, 820, 939, 939, 939, 939,
  79668. /* 110 */ 939, 713, 647, 939, 939, 939, 939, 939, 939, 939,
  79669. /* 120 */ 939, 939, 939, 939, 939, 939, 821, 939, 822, 835,
  79670. /* 130 */ 836, 837, 939, 939, 939, 939, 939, 939, 939, 939,
  79671. /* 140 */ 939, 627, 939, 939, 939, 939, 939, 939, 939, 939,
  79672. /* 150 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79673. /* 160 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 869,
  79674. /* 170 */ 939, 918, 920, 939, 939, 939, 621, 744, 744, 744,
  79675. /* 180 */ 939, 939, 939, 939, 939, 738, 748, 932, 939, 939,
  79676. /* 190 */ 704, 939, 939, 939, 939, 939, 939, 939, 629, 736,
  79677. /* 200 */ 662, 746, 939, 939, 939, 649, 725, 891, 939, 905,
  79678. /* 210 */ 903, 727, 789, 939, 736, 745, 939, 939, 939, 852,
  79679. /* 220 */ 773, 773, 761, 773, 683, 773, 939, 773, 939, 686,
  79680. /* 230 */ 783, 761, 761, 783, 626, 626, 626, 626, 637, 637,
  79681. /* 240 */ 703, 939, 783, 774, 776, 766, 778, 939, 752, 752,
  79682. /* 250 */ 760, 765, 760, 765, 760, 765, 715, 715, 700, 715,
  79683. /* 260 */ 686, 715, 862, 866, 866, 700, 715, 715, 715, 862,
  79684. /* 270 */ 644, 752, 644, 752, 644, 752, 752, 895, 897, 644,
  79685. /* 280 */ 752, 717, 717, 795, 783, 752, 724, 724, 724, 724,
  79686. /* 290 */ 783, 717, 795, 752, 917, 917, 752, 752, 925, 670,
  79687. /* 300 */ 688, 688, 932, 937, 939, 939, 939, 939, 939, 939,
  79688. /* 310 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79689. /* 320 */ 939, 871, 939, 939, 939, 635, 939, 654, 802, 807,
  79690. /* 330 */ 803, 939, 804, 939, 730, 939, 939, 939, 939, 939,
  79691. /* 340 */ 939, 939, 939, 939, 939, 855, 939, 767, 939, 775,
  79692. /* 350 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79693. /* 360 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79694. /* 370 */ 939, 939, 939, 939, 939, 893, 894, 939, 939, 939,
  79695. /* 380 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79696. /* 390 */ 939, 939, 939, 939, 939, 939, 939, 939, 939, 939,
  79697. /* 400 */ 939, 924, 939, 939, 927, 622, 939, 617, 619, 620,
  79698. /* 410 */ 624, 625, 628, 654, 655, 657, 658, 659, 630, 631,
  79699. /* 420 */ 632, 633, 634, 636, 640, 638, 639, 641, 648, 650,
  79700. /* 430 */ 669, 671, 673, 734, 735, 799, 728, 729, 733, 656,
  79701. /* 440 */ 810, 801, 805, 806, 808, 809, 823, 824, 826, 832,
  79702. /* 450 */ 839, 842, 825, 830, 831, 833, 838, 841, 731, 732,
  79703. /* 460 */ 845, 663, 664, 667, 668, 881, 883, 882, 884, 666,
  79704. /* 470 */ 665, 811, 814, 847, 848, 906, 907, 908, 909, 910,
  79705. /* 480 */ 843, 753, 846, 829, 768, 771, 772, 769, 737, 747,
  79706. /* 490 */ 755, 756, 757, 758, 742, 743, 749, 764, 797, 798,
  79707. /* 500 */ 762, 763, 750, 751, 739, 740, 741, 844, 800, 812,
  79708. /* 510 */ 813, 674, 675, 807, 676, 677, 678, 716, 719, 720,
  79709. /* 520 */ 721, 679, 698, 701, 702, 680, 687, 681, 682, 689,
  79710. /* 530 */ 690, 691, 694, 695, 696, 697, 692, 693, 863, 864,
  79711. /* 540 */ 867, 865, 684, 685, 699, 672, 661, 653, 705, 708,
  79712. /* 550 */ 709, 710, 711, 712, 714, 706, 707, 651, 642, 645,
  79713. /* 560 */ 754, 887, 896, 892, 888, 889, 890, 646, 859, 860,
  79714. /* 570 */ 718, 791, 792, 886, 899, 901, 796, 902, 904, 900,
  79715. /* 580 */ 929, 643, 722, 723, 726, 868, 911, 782, 785, 788,
  79716. /* 590 */ 790, 870, 872, 874, 876, 877, 878, 879, 880, 873,
  79717. /* 600 */ 875, 912, 916, 919, 921, 922, 923, 926, 928, 933,
  79718. /* 610 */ 934, 935, 938, 936, 623, 618,
  79719. };
  79720. #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
  79721. /* The next table maps tokens into fallback tokens. If a construct
  79722. ** like the following:
  79723. **
  79724. ** %fallback ID X Y Z.
  79725. **
  79726. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  79727. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  79728. ** but it does not parse, the type of the token is changed to ID and
  79729. ** the parse is retried before an error is thrown.
  79730. */
  79731. #ifdef YYFALLBACK
  79732. static const YYCODETYPE yyFallback[] = {
  79733. 0, /* $ => nothing */
  79734. 0, /* SEMI => nothing */
  79735. 26, /* EXPLAIN => ID */
  79736. 26, /* QUERY => ID */
  79737. 26, /* PLAN => ID */
  79738. 26, /* BEGIN => ID */
  79739. 0, /* TRANSACTION => nothing */
  79740. 26, /* DEFERRED => ID */
  79741. 26, /* IMMEDIATE => ID */
  79742. 26, /* EXCLUSIVE => ID */
  79743. 0, /* COMMIT => nothing */
  79744. 26, /* END => ID */
  79745. 26, /* ROLLBACK => ID */
  79746. 26, /* SAVEPOINT => ID */
  79747. 26, /* RELEASE => ID */
  79748. 0, /* TO => nothing */
  79749. 0, /* TABLE => nothing */
  79750. 0, /* CREATE => nothing */
  79751. 26, /* IF => ID */
  79752. 0, /* NOT => nothing */
  79753. 0, /* EXISTS => nothing */
  79754. 26, /* TEMP => ID */
  79755. 0, /* LP => nothing */
  79756. 0, /* RP => nothing */
  79757. 0, /* AS => nothing */
  79758. 0, /* COMMA => nothing */
  79759. 0, /* ID => nothing */
  79760. 0, /* INDEXED => nothing */
  79761. 26, /* ABORT => ID */
  79762. 26, /* AFTER => ID */
  79763. 26, /* ANALYZE => ID */
  79764. 26, /* ASC => ID */
  79765. 26, /* ATTACH => ID */
  79766. 26, /* BEFORE => ID */
  79767. 26, /* BY => ID */
  79768. 26, /* CASCADE => ID */
  79769. 26, /* CAST => ID */
  79770. 26, /* COLUMNKW => ID */
  79771. 26, /* CONFLICT => ID */
  79772. 26, /* DATABASE => ID */
  79773. 26, /* DESC => ID */
  79774. 26, /* DETACH => ID */
  79775. 26, /* EACH => ID */
  79776. 26, /* FAIL => ID */
  79777. 26, /* FOR => ID */
  79778. 26, /* IGNORE => ID */
  79779. 26, /* INITIALLY => ID */
  79780. 26, /* INSTEAD => ID */
  79781. 26, /* LIKE_KW => ID */
  79782. 26, /* MATCH => ID */
  79783. 26, /* KEY => ID */
  79784. 26, /* OF => ID */
  79785. 26, /* OFFSET => ID */
  79786. 26, /* PRAGMA => ID */
  79787. 26, /* RAISE => ID */
  79788. 26, /* REPLACE => ID */
  79789. 26, /* RESTRICT => ID */
  79790. 26, /* ROW => ID */
  79791. 26, /* TRIGGER => ID */
  79792. 26, /* VACUUM => ID */
  79793. 26, /* VIEW => ID */
  79794. 26, /* VIRTUAL => ID */
  79795. 26, /* REINDEX => ID */
  79796. 26, /* RENAME => ID */
  79797. 26, /* CTIME_KW => ID */
  79798. 0, /* ANY => nothing */
  79799. 0, /* OR => nothing */
  79800. 0, /* AND => nothing */
  79801. 0, /* IS => nothing */
  79802. 0, /* BETWEEN => nothing */
  79803. 0, /* IN => nothing */
  79804. 0, /* ISNULL => nothing */
  79805. 0, /* NOTNULL => nothing */
  79806. 0, /* NE => nothing */
  79807. 0, /* EQ => nothing */
  79808. 0, /* GT => nothing */
  79809. 0, /* LE => nothing */
  79810. 0, /* LT => nothing */
  79811. 0, /* GE => nothing */
  79812. 0, /* ESCAPE => nothing */
  79813. 0, /* BITAND => nothing */
  79814. 0, /* BITOR => nothing */
  79815. 0, /* LSHIFT => nothing */
  79816. 0, /* RSHIFT => nothing */
  79817. 0, /* PLUS => nothing */
  79818. 0, /* MINUS => nothing */
  79819. 0, /* STAR => nothing */
  79820. 0, /* SLASH => nothing */
  79821. 0, /* REM => nothing */
  79822. 0, /* CONCAT => nothing */
  79823. 0, /* COLLATE => nothing */
  79824. 0, /* UMINUS => nothing */
  79825. 0, /* UPLUS => nothing */
  79826. 0, /* BITNOT => nothing */
  79827. 0, /* STRING => nothing */
  79828. 0, /* JOIN_KW => nothing */
  79829. 0, /* CONSTRAINT => nothing */
  79830. 0, /* DEFAULT => nothing */
  79831. 0, /* NULL => nothing */
  79832. 0, /* PRIMARY => nothing */
  79833. 0, /* UNIQUE => nothing */
  79834. 0, /* CHECK => nothing */
  79835. 0, /* REFERENCES => nothing */
  79836. 0, /* AUTOINCR => nothing */
  79837. 0, /* ON => nothing */
  79838. 0, /* DELETE => nothing */
  79839. 0, /* UPDATE => nothing */
  79840. 0, /* INSERT => nothing */
  79841. 0, /* SET => nothing */
  79842. 0, /* DEFERRABLE => nothing */
  79843. 0, /* FOREIGN => nothing */
  79844. 0, /* DROP => nothing */
  79845. 0, /* UNION => nothing */
  79846. 0, /* ALL => nothing */
  79847. 0, /* EXCEPT => nothing */
  79848. 0, /* INTERSECT => nothing */
  79849. 0, /* SELECT => nothing */
  79850. 0, /* DISTINCT => nothing */
  79851. 0, /* DOT => nothing */
  79852. 0, /* FROM => nothing */
  79853. 0, /* JOIN => nothing */
  79854. 0, /* USING => nothing */
  79855. 0, /* ORDER => nothing */
  79856. 0, /* GROUP => nothing */
  79857. 0, /* HAVING => nothing */
  79858. 0, /* LIMIT => nothing */
  79859. 0, /* WHERE => nothing */
  79860. 0, /* INTO => nothing */
  79861. 0, /* VALUES => nothing */
  79862. 0, /* INTEGER => nothing */
  79863. 0, /* FLOAT => nothing */
  79864. 0, /* BLOB => nothing */
  79865. 0, /* REGISTER => nothing */
  79866. 0, /* VARIABLE => nothing */
  79867. 0, /* CASE => nothing */
  79868. 0, /* WHEN => nothing */
  79869. 0, /* THEN => nothing */
  79870. 0, /* ELSE => nothing */
  79871. 0, /* INDEX => nothing */
  79872. 0, /* ALTER => nothing */
  79873. 0, /* ADD => nothing */
  79874. };
  79875. #endif /* YYFALLBACK */
  79876. /* The following structure represents a single element of the
  79877. ** parser's stack. Information stored includes:
  79878. **
  79879. ** + The state number for the parser at this level of the stack.
  79880. **
  79881. ** + The value of the token stored at this level of the stack.
  79882. ** (In other words, the "major" token.)
  79883. **
  79884. ** + The semantic value stored at this level of the stack. This is
  79885. ** the information used by the action routines in the grammar.
  79886. ** It is sometimes called the "minor" token.
  79887. */
  79888. struct yyStackEntry {
  79889. YYACTIONTYPE stateno; /* The state-number */
  79890. YYCODETYPE major; /* The major token value. This is the code
  79891. ** number for the token at this stack level */
  79892. YYMINORTYPE minor; /* The user-supplied minor token value. This
  79893. ** is the value of the token */
  79894. };
  79895. typedef struct yyStackEntry yyStackEntry;
  79896. /* The state of the parser is completely contained in an instance of
  79897. ** the following structure */
  79898. struct yyParser {
  79899. int yyidx; /* Index of top element in stack */
  79900. #ifdef YYTRACKMAXSTACKDEPTH
  79901. int yyidxMax; /* Maximum value of yyidx */
  79902. #endif
  79903. int yyerrcnt; /* Shifts left before out of the error */
  79904. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  79905. #if YYSTACKDEPTH<=0
  79906. int yystksz; /* Current side of the stack */
  79907. yyStackEntry *yystack; /* The parser's stack */
  79908. #else
  79909. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  79910. #endif
  79911. };
  79912. typedef struct yyParser yyParser;
  79913. #ifndef NDEBUG
  79914. static FILE *yyTraceFILE = 0;
  79915. static char *yyTracePrompt = 0;
  79916. #endif /* NDEBUG */
  79917. #ifndef NDEBUG
  79918. /*
  79919. ** Turn parser tracing on by giving a stream to which to write the trace
  79920. ** and a prompt to preface each trace message. Tracing is turned off
  79921. ** by making either argument NULL
  79922. **
  79923. ** Inputs:
  79924. ** <ul>
  79925. ** <li> A FILE* to which trace output should be written.
  79926. ** If NULL, then tracing is turned off.
  79927. ** <li> A prefix string written at the beginning of every
  79928. ** line of trace output. If NULL, then tracing is
  79929. ** turned off.
  79930. ** </ul>
  79931. **
  79932. ** Outputs:
  79933. ** None.
  79934. */
  79935. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  79936. yyTraceFILE = TraceFILE;
  79937. yyTracePrompt = zTracePrompt;
  79938. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  79939. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  79940. }
  79941. #endif /* NDEBUG */
  79942. #ifndef NDEBUG
  79943. /* For tracing shifts, the names of all terminals and nonterminals
  79944. ** are required. The following table supplies these names */
  79945. static const char *const yyTokenName[] = {
  79946. "$", "SEMI", "EXPLAIN", "QUERY",
  79947. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  79948. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  79949. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  79950. "TABLE", "CREATE", "IF", "NOT",
  79951. "EXISTS", "TEMP", "LP", "RP",
  79952. "AS", "COMMA", "ID", "INDEXED",
  79953. "ABORT", "AFTER", "ANALYZE", "ASC",
  79954. "ATTACH", "BEFORE", "BY", "CASCADE",
  79955. "CAST", "COLUMNKW", "CONFLICT", "DATABASE",
  79956. "DESC", "DETACH", "EACH", "FAIL",
  79957. "FOR", "IGNORE", "INITIALLY", "INSTEAD",
  79958. "LIKE_KW", "MATCH", "KEY", "OF",
  79959. "OFFSET", "PRAGMA", "RAISE", "REPLACE",
  79960. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  79961. "VIEW", "VIRTUAL", "REINDEX", "RENAME",
  79962. "CTIME_KW", "ANY", "OR", "AND",
  79963. "IS", "BETWEEN", "IN", "ISNULL",
  79964. "NOTNULL", "NE", "EQ", "GT",
  79965. "LE", "LT", "GE", "ESCAPE",
  79966. "BITAND", "BITOR", "LSHIFT", "RSHIFT",
  79967. "PLUS", "MINUS", "STAR", "SLASH",
  79968. "REM", "CONCAT", "COLLATE", "UMINUS",
  79969. "UPLUS", "BITNOT", "STRING", "JOIN_KW",
  79970. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  79971. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  79972. "ON", "DELETE", "UPDATE", "INSERT",
  79973. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  79974. "UNION", "ALL", "EXCEPT", "INTERSECT",
  79975. "SELECT", "DISTINCT", "DOT", "FROM",
  79976. "JOIN", "USING", "ORDER", "GROUP",
  79977. "HAVING", "LIMIT", "WHERE", "INTO",
  79978. "VALUES", "INTEGER", "FLOAT", "BLOB",
  79979. "REGISTER", "VARIABLE", "CASE", "WHEN",
  79980. "THEN", "ELSE", "INDEX", "ALTER",
  79981. "ADD", "error", "input", "cmdlist",
  79982. "ecmd", "explain", "cmdx", "cmd",
  79983. "transtype", "trans_opt", "nm", "savepoint_opt",
  79984. "create_table", "create_table_args", "createkw", "temp",
  79985. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  79986. "select", "column", "columnid", "type",
  79987. "carglist", "id", "ids", "typetoken",
  79988. "typename", "signed", "plus_num", "minus_num",
  79989. "carg", "ccons", "term", "expr",
  79990. "onconf", "sortorder", "autoinc", "idxlist_opt",
  79991. "refargs", "defer_subclause", "refarg", "refact",
  79992. "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
  79993. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  79994. "ifexists", "fullname", "oneselect", "multiselect_op",
  79995. "distinct", "selcollist", "from", "where_opt",
  79996. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  79997. "sclp", "as", "seltablist", "stl_prefix",
  79998. "joinop", "indexed_opt", "on_opt", "using_opt",
  79999. "joinop2", "inscollist", "sortlist", "sortitem",
  80000. "nexprlist", "setlist", "insert_cmd", "inscollist_opt",
  80001. "itemlist", "exprlist", "likeop", "escape",
  80002. "between_op", "in_op", "case_operand", "case_exprlist",
  80003. "case_else", "uniqueflag", "collate", "nmnum",
  80004. "plus_opt", "number", "trigger_decl", "trigger_cmd_list",
  80005. "trigger_time", "trigger_event", "foreach_clause", "when_clause",
  80006. "trigger_cmd", "database_kw_opt", "key_opt", "add_column_fullname",
  80007. "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg",
  80008. "vtabargtoken", "lp", "anylist",
  80009. };
  80010. #endif /* NDEBUG */
  80011. #ifndef NDEBUG
  80012. /* For tracing reduce actions, the names of all rules are required.
  80013. */
  80014. static const char *const yyRuleName[] = {
  80015. /* 0 */ "input ::= cmdlist",
  80016. /* 1 */ "cmdlist ::= cmdlist ecmd",
  80017. /* 2 */ "cmdlist ::= ecmd",
  80018. /* 3 */ "ecmd ::= SEMI",
  80019. /* 4 */ "ecmd ::= explain cmdx SEMI",
  80020. /* 5 */ "explain ::=",
  80021. /* 6 */ "explain ::= EXPLAIN",
  80022. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  80023. /* 8 */ "cmdx ::= cmd",
  80024. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  80025. /* 10 */ "trans_opt ::=",
  80026. /* 11 */ "trans_opt ::= TRANSACTION",
  80027. /* 12 */ "trans_opt ::= TRANSACTION nm",
  80028. /* 13 */ "transtype ::=",
  80029. /* 14 */ "transtype ::= DEFERRED",
  80030. /* 15 */ "transtype ::= IMMEDIATE",
  80031. /* 16 */ "transtype ::= EXCLUSIVE",
  80032. /* 17 */ "cmd ::= COMMIT trans_opt",
  80033. /* 18 */ "cmd ::= END trans_opt",
  80034. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  80035. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  80036. /* 21 */ "savepoint_opt ::=",
  80037. /* 22 */ "cmd ::= SAVEPOINT nm",
  80038. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  80039. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  80040. /* 25 */ "cmd ::= create_table create_table_args",
  80041. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  80042. /* 27 */ "createkw ::= CREATE",
  80043. /* 28 */ "ifnotexists ::=",
  80044. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  80045. /* 30 */ "temp ::= TEMP",
  80046. /* 31 */ "temp ::=",
  80047. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  80048. /* 33 */ "create_table_args ::= AS select",
  80049. /* 34 */ "columnlist ::= columnlist COMMA column",
  80050. /* 35 */ "columnlist ::= column",
  80051. /* 36 */ "column ::= columnid type carglist",
  80052. /* 37 */ "columnid ::= nm",
  80053. /* 38 */ "id ::= ID",
  80054. /* 39 */ "id ::= INDEXED",
  80055. /* 40 */ "ids ::= ID|STRING",
  80056. /* 41 */ "nm ::= id",
  80057. /* 42 */ "nm ::= STRING",
  80058. /* 43 */ "nm ::= JOIN_KW",
  80059. /* 44 */ "type ::=",
  80060. /* 45 */ "type ::= typetoken",
  80061. /* 46 */ "typetoken ::= typename",
  80062. /* 47 */ "typetoken ::= typename LP signed RP",
  80063. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  80064. /* 49 */ "typename ::= ids",
  80065. /* 50 */ "typename ::= typename ids",
  80066. /* 51 */ "signed ::= plus_num",
  80067. /* 52 */ "signed ::= minus_num",
  80068. /* 53 */ "carglist ::= carglist carg",
  80069. /* 54 */ "carglist ::=",
  80070. /* 55 */ "carg ::= CONSTRAINT nm ccons",
  80071. /* 56 */ "carg ::= ccons",
  80072. /* 57 */ "ccons ::= DEFAULT term",
  80073. /* 58 */ "ccons ::= DEFAULT LP expr RP",
  80074. /* 59 */ "ccons ::= DEFAULT PLUS term",
  80075. /* 60 */ "ccons ::= DEFAULT MINUS term",
  80076. /* 61 */ "ccons ::= DEFAULT id",
  80077. /* 62 */ "ccons ::= NULL onconf",
  80078. /* 63 */ "ccons ::= NOT NULL onconf",
  80079. /* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  80080. /* 65 */ "ccons ::= UNIQUE onconf",
  80081. /* 66 */ "ccons ::= CHECK LP expr RP",
  80082. /* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  80083. /* 68 */ "ccons ::= defer_subclause",
  80084. /* 69 */ "ccons ::= COLLATE ids",
  80085. /* 70 */ "autoinc ::=",
  80086. /* 71 */ "autoinc ::= AUTOINCR",
  80087. /* 72 */ "refargs ::=",
  80088. /* 73 */ "refargs ::= refargs refarg",
  80089. /* 74 */ "refarg ::= MATCH nm",
  80090. /* 75 */ "refarg ::= ON DELETE refact",
  80091. /* 76 */ "refarg ::= ON UPDATE refact",
  80092. /* 77 */ "refarg ::= ON INSERT refact",
  80093. /* 78 */ "refact ::= SET NULL",
  80094. /* 79 */ "refact ::= SET DEFAULT",
  80095. /* 80 */ "refact ::= CASCADE",
  80096. /* 81 */ "refact ::= RESTRICT",
  80097. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  80098. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  80099. /* 84 */ "init_deferred_pred_opt ::=",
  80100. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  80101. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  80102. /* 87 */ "conslist_opt ::=",
  80103. /* 88 */ "conslist_opt ::= COMMA conslist",
  80104. /* 89 */ "conslist ::= conslist COMMA tcons",
  80105. /* 90 */ "conslist ::= conslist tcons",
  80106. /* 91 */ "conslist ::= tcons",
  80107. /* 92 */ "tcons ::= CONSTRAINT nm",
  80108. /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  80109. /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  80110. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  80111. /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  80112. /* 97 */ "defer_subclause_opt ::=",
  80113. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  80114. /* 99 */ "onconf ::=",
  80115. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  80116. /* 101 */ "orconf ::=",
  80117. /* 102 */ "orconf ::= OR resolvetype",
  80118. /* 103 */ "resolvetype ::= raisetype",
  80119. /* 104 */ "resolvetype ::= IGNORE",
  80120. /* 105 */ "resolvetype ::= REPLACE",
  80121. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  80122. /* 107 */ "ifexists ::= IF EXISTS",
  80123. /* 108 */ "ifexists ::=",
  80124. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  80125. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  80126. /* 111 */ "cmd ::= select",
  80127. /* 112 */ "select ::= oneselect",
  80128. /* 113 */ "select ::= select multiselect_op oneselect",
  80129. /* 114 */ "multiselect_op ::= UNION",
  80130. /* 115 */ "multiselect_op ::= UNION ALL",
  80131. /* 116 */ "multiselect_op ::= EXCEPT|INTERSECT",
  80132. /* 117 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  80133. /* 118 */ "distinct ::= DISTINCT",
  80134. /* 119 */ "distinct ::= ALL",
  80135. /* 120 */ "distinct ::=",
  80136. /* 121 */ "sclp ::= selcollist COMMA",
  80137. /* 122 */ "sclp ::=",
  80138. /* 123 */ "selcollist ::= sclp expr as",
  80139. /* 124 */ "selcollist ::= sclp STAR",
  80140. /* 125 */ "selcollist ::= sclp nm DOT STAR",
  80141. /* 126 */ "as ::= AS nm",
  80142. /* 127 */ "as ::= ids",
  80143. /* 128 */ "as ::=",
  80144. /* 129 */ "from ::=",
  80145. /* 130 */ "from ::= FROM seltablist",
  80146. /* 131 */ "stl_prefix ::= seltablist joinop",
  80147. /* 132 */ "stl_prefix ::=",
  80148. /* 133 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  80149. /* 134 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  80150. /* 135 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  80151. /* 136 */ "dbnm ::=",
  80152. /* 137 */ "dbnm ::= DOT nm",
  80153. /* 138 */ "fullname ::= nm dbnm",
  80154. /* 139 */ "joinop ::= COMMA|JOIN",
  80155. /* 140 */ "joinop ::= JOIN_KW JOIN",
  80156. /* 141 */ "joinop ::= JOIN_KW nm JOIN",
  80157. /* 142 */ "joinop ::= JOIN_KW nm nm JOIN",
  80158. /* 143 */ "on_opt ::= ON expr",
  80159. /* 144 */ "on_opt ::=",
  80160. /* 145 */ "indexed_opt ::=",
  80161. /* 146 */ "indexed_opt ::= INDEXED BY nm",
  80162. /* 147 */ "indexed_opt ::= NOT INDEXED",
  80163. /* 148 */ "using_opt ::= USING LP inscollist RP",
  80164. /* 149 */ "using_opt ::=",
  80165. /* 150 */ "orderby_opt ::=",
  80166. /* 151 */ "orderby_opt ::= ORDER BY sortlist",
  80167. /* 152 */ "sortlist ::= sortlist COMMA sortitem sortorder",
  80168. /* 153 */ "sortlist ::= sortitem sortorder",
  80169. /* 154 */ "sortitem ::= expr",
  80170. /* 155 */ "sortorder ::= ASC",
  80171. /* 156 */ "sortorder ::= DESC",
  80172. /* 157 */ "sortorder ::=",
  80173. /* 158 */ "groupby_opt ::=",
  80174. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  80175. /* 160 */ "having_opt ::=",
  80176. /* 161 */ "having_opt ::= HAVING expr",
  80177. /* 162 */ "limit_opt ::=",
  80178. /* 163 */ "limit_opt ::= LIMIT expr",
  80179. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  80180. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  80181. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  80182. /* 167 */ "where_opt ::=",
  80183. /* 168 */ "where_opt ::= WHERE expr",
  80184. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  80185. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  80186. /* 171 */ "setlist ::= nm EQ expr",
  80187. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
  80188. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  80189. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  80190. /* 175 */ "insert_cmd ::= INSERT orconf",
  80191. /* 176 */ "insert_cmd ::= REPLACE",
  80192. /* 177 */ "itemlist ::= itemlist COMMA expr",
  80193. /* 178 */ "itemlist ::= expr",
  80194. /* 179 */ "inscollist_opt ::=",
  80195. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  80196. /* 181 */ "inscollist ::= inscollist COMMA nm",
  80197. /* 182 */ "inscollist ::= nm",
  80198. /* 183 */ "expr ::= term",
  80199. /* 184 */ "expr ::= LP expr RP",
  80200. /* 185 */ "term ::= NULL",
  80201. /* 186 */ "expr ::= id",
  80202. /* 187 */ "expr ::= JOIN_KW",
  80203. /* 188 */ "expr ::= nm DOT nm",
  80204. /* 189 */ "expr ::= nm DOT nm DOT nm",
  80205. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  80206. /* 191 */ "term ::= STRING",
  80207. /* 192 */ "expr ::= REGISTER",
  80208. /* 193 */ "expr ::= VARIABLE",
  80209. /* 194 */ "expr ::= expr COLLATE ids",
  80210. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  80211. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  80212. /* 197 */ "expr ::= ID LP STAR RP",
  80213. /* 198 */ "term ::= CTIME_KW",
  80214. /* 199 */ "expr ::= expr AND expr",
  80215. /* 200 */ "expr ::= expr OR expr",
  80216. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  80217. /* 202 */ "expr ::= expr EQ|NE expr",
  80218. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  80219. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  80220. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  80221. /* 206 */ "expr ::= expr CONCAT expr",
  80222. /* 207 */ "likeop ::= LIKE_KW",
  80223. /* 208 */ "likeop ::= NOT LIKE_KW",
  80224. /* 209 */ "likeop ::= MATCH",
  80225. /* 210 */ "likeop ::= NOT MATCH",
  80226. /* 211 */ "escape ::= ESCAPE expr",
  80227. /* 212 */ "escape ::=",
  80228. /* 213 */ "expr ::= expr likeop expr escape",
  80229. /* 214 */ "expr ::= expr ISNULL|NOTNULL",
  80230. /* 215 */ "expr ::= expr IS NULL",
  80231. /* 216 */ "expr ::= expr NOT NULL",
  80232. /* 217 */ "expr ::= expr IS NOT NULL",
  80233. /* 218 */ "expr ::= NOT expr",
  80234. /* 219 */ "expr ::= BITNOT expr",
  80235. /* 220 */ "expr ::= MINUS expr",
  80236. /* 221 */ "expr ::= PLUS expr",
  80237. /* 222 */ "between_op ::= BETWEEN",
  80238. /* 223 */ "between_op ::= NOT BETWEEN",
  80239. /* 224 */ "expr ::= expr between_op expr AND expr",
  80240. /* 225 */ "in_op ::= IN",
  80241. /* 226 */ "in_op ::= NOT IN",
  80242. /* 227 */ "expr ::= expr in_op LP exprlist RP",
  80243. /* 228 */ "expr ::= LP select RP",
  80244. /* 229 */ "expr ::= expr in_op LP select RP",
  80245. /* 230 */ "expr ::= expr in_op nm dbnm",
  80246. /* 231 */ "expr ::= EXISTS LP select RP",
  80247. /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
  80248. /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  80249. /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
  80250. /* 235 */ "case_else ::= ELSE expr",
  80251. /* 236 */ "case_else ::=",
  80252. /* 237 */ "case_operand ::= expr",
  80253. /* 238 */ "case_operand ::=",
  80254. /* 239 */ "exprlist ::= nexprlist",
  80255. /* 240 */ "exprlist ::=",
  80256. /* 241 */ "nexprlist ::= nexprlist COMMA expr",
  80257. /* 242 */ "nexprlist ::= expr",
  80258. /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
  80259. /* 244 */ "uniqueflag ::= UNIQUE",
  80260. /* 245 */ "uniqueflag ::=",
  80261. /* 246 */ "idxlist_opt ::=",
  80262. /* 247 */ "idxlist_opt ::= LP idxlist RP",
  80263. /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  80264. /* 249 */ "idxlist ::= nm collate sortorder",
  80265. /* 250 */ "collate ::=",
  80266. /* 251 */ "collate ::= COLLATE ids",
  80267. /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
  80268. /* 253 */ "cmd ::= VACUUM",
  80269. /* 254 */ "cmd ::= VACUUM nm",
  80270. /* 255 */ "cmd ::= PRAGMA nm dbnm",
  80271. /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  80272. /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  80273. /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  80274. /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  80275. /* 260 */ "nmnum ::= plus_num",
  80276. /* 261 */ "nmnum ::= nm",
  80277. /* 262 */ "nmnum ::= ON",
  80278. /* 263 */ "nmnum ::= DELETE",
  80279. /* 264 */ "nmnum ::= DEFAULT",
  80280. /* 265 */ "plus_num ::= plus_opt number",
  80281. /* 266 */ "minus_num ::= MINUS number",
  80282. /* 267 */ "number ::= INTEGER|FLOAT",
  80283. /* 268 */ "plus_opt ::= PLUS",
  80284. /* 269 */ "plus_opt ::=",
  80285. /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  80286. /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  80287. /* 272 */ "trigger_time ::= BEFORE",
  80288. /* 273 */ "trigger_time ::= AFTER",
  80289. /* 274 */ "trigger_time ::= INSTEAD OF",
  80290. /* 275 */ "trigger_time ::=",
  80291. /* 276 */ "trigger_event ::= DELETE|INSERT",
  80292. /* 277 */ "trigger_event ::= UPDATE",
  80293. /* 278 */ "trigger_event ::= UPDATE OF inscollist",
  80294. /* 279 */ "foreach_clause ::=",
  80295. /* 280 */ "foreach_clause ::= FOR EACH ROW",
  80296. /* 281 */ "when_clause ::=",
  80297. /* 282 */ "when_clause ::= WHEN expr",
  80298. /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  80299. /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  80300. /* 285 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
  80301. /* 286 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
  80302. /* 287 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
  80303. /* 288 */ "trigger_cmd ::= DELETE FROM nm where_opt",
  80304. /* 289 */ "trigger_cmd ::= select",
  80305. /* 290 */ "expr ::= RAISE LP IGNORE RP",
  80306. /* 291 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  80307. /* 292 */ "raisetype ::= ROLLBACK",
  80308. /* 293 */ "raisetype ::= ABORT",
  80309. /* 294 */ "raisetype ::= FAIL",
  80310. /* 295 */ "cmd ::= DROP TRIGGER ifexists fullname",
  80311. /* 296 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  80312. /* 297 */ "cmd ::= DETACH database_kw_opt expr",
  80313. /* 298 */ "key_opt ::=",
  80314. /* 299 */ "key_opt ::= KEY expr",
  80315. /* 300 */ "database_kw_opt ::= DATABASE",
  80316. /* 301 */ "database_kw_opt ::=",
  80317. /* 302 */ "cmd ::= REINDEX",
  80318. /* 303 */ "cmd ::= REINDEX nm dbnm",
  80319. /* 304 */ "cmd ::= ANALYZE",
  80320. /* 305 */ "cmd ::= ANALYZE nm dbnm",
  80321. /* 306 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  80322. /* 307 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  80323. /* 308 */ "add_column_fullname ::= fullname",
  80324. /* 309 */ "kwcolumn_opt ::=",
  80325. /* 310 */ "kwcolumn_opt ::= COLUMNKW",
  80326. /* 311 */ "cmd ::= create_vtab",
  80327. /* 312 */ "cmd ::= create_vtab LP vtabarglist RP",
  80328. /* 313 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
  80329. /* 314 */ "vtabarglist ::= vtabarg",
  80330. /* 315 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  80331. /* 316 */ "vtabarg ::=",
  80332. /* 317 */ "vtabarg ::= vtabarg vtabargtoken",
  80333. /* 318 */ "vtabargtoken ::= ANY",
  80334. /* 319 */ "vtabargtoken ::= lp anylist RP",
  80335. /* 320 */ "lp ::= LP",
  80336. /* 321 */ "anylist ::=",
  80337. /* 322 */ "anylist ::= anylist ANY",
  80338. };
  80339. #endif /* NDEBUG */
  80340. #if YYSTACKDEPTH<=0
  80341. /*
  80342. ** Try to increase the size of the parser stack.
  80343. */
  80344. static void yyGrowStack(yyParser *p){
  80345. int newSize;
  80346. yyStackEntry *pNew;
  80347. newSize = p->yystksz*2 + 100;
  80348. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  80349. if( pNew ){
  80350. p->yystack = pNew;
  80351. p->yystksz = newSize;
  80352. #ifndef NDEBUG
  80353. if( yyTraceFILE ){
  80354. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  80355. yyTracePrompt, p->yystksz);
  80356. }
  80357. #endif
  80358. }
  80359. }
  80360. #endif
  80361. /*
  80362. ** This function allocates a new parser.
  80363. ** The only argument is a pointer to a function which works like
  80364. ** malloc.
  80365. **
  80366. ** Inputs:
  80367. ** A pointer to the function used to allocate memory.
  80368. **
  80369. ** Outputs:
  80370. ** A pointer to a parser. This pointer is used in subsequent calls
  80371. ** to sqlite3Parser and sqlite3ParserFree.
  80372. */
  80373. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  80374. yyParser *pParser;
  80375. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  80376. if( pParser ){
  80377. pParser->yyidx = -1;
  80378. #ifdef YYTRACKMAXSTACKDEPTH
  80379. pParser->yyidxMax = 0;
  80380. #endif
  80381. #if YYSTACKDEPTH<=0
  80382. pParser->yystack = NULL;
  80383. pParser->yystksz = 0;
  80384. yyGrowStack(pParser);
  80385. #endif
  80386. }
  80387. return pParser;
  80388. }
  80389. /* The following function deletes the value associated with a
  80390. ** symbol. The symbol can be either a terminal or nonterminal.
  80391. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  80392. ** the value.
  80393. */
  80394. static void yy_destructor(
  80395. yyParser *yypParser, /* The parser */
  80396. YYCODETYPE yymajor, /* Type code for object to destroy */
  80397. YYMINORTYPE *yypminor /* The object to be destroyed */
  80398. ){
  80399. sqlite3ParserARG_FETCH;
  80400. switch( yymajor ){
  80401. /* Here is inserted the actions which take place when a
  80402. ** terminal or non-terminal is destroyed. This can happen
  80403. ** when the symbol is popped from the stack during a
  80404. ** reduce or during error processing or when a parser is
  80405. ** being destroyed before it is finished parsing.
  80406. **
  80407. ** Note: during a reduce, the only symbols destroyed are those
  80408. ** which appear on the RHS of the rule, but which are not used
  80409. ** inside the C code.
  80410. */
  80411. case 160: /* select */
  80412. case 194: /* oneselect */
  80413. {
  80414. sqlite3SelectDelete(pParse->db, (yypminor->yy243));
  80415. }
  80416. break;
  80417. case 174: /* term */
  80418. case 175: /* expr */
  80419. case 199: /* where_opt */
  80420. case 201: /* having_opt */
  80421. case 210: /* on_opt */
  80422. case 215: /* sortitem */
  80423. case 223: /* escape */
  80424. case 226: /* case_operand */
  80425. case 228: /* case_else */
  80426. case 239: /* when_clause */
  80427. case 242: /* key_opt */
  80428. {
  80429. sqlite3ExprDelete(pParse->db, (yypminor->yy72));
  80430. }
  80431. break;
  80432. case 179: /* idxlist_opt */
  80433. case 187: /* idxlist */
  80434. case 197: /* selcollist */
  80435. case 200: /* groupby_opt */
  80436. case 202: /* orderby_opt */
  80437. case 204: /* sclp */
  80438. case 214: /* sortlist */
  80439. case 216: /* nexprlist */
  80440. case 217: /* setlist */
  80441. case 220: /* itemlist */
  80442. case 221: /* exprlist */
  80443. case 227: /* case_exprlist */
  80444. {
  80445. sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
  80446. }
  80447. break;
  80448. case 193: /* fullname */
  80449. case 198: /* from */
  80450. case 206: /* seltablist */
  80451. case 207: /* stl_prefix */
  80452. {
  80453. sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
  80454. }
  80455. break;
  80456. case 211: /* using_opt */
  80457. case 213: /* inscollist */
  80458. case 219: /* inscollist_opt */
  80459. {
  80460. sqlite3IdListDelete(pParse->db, (yypminor->yy254));
  80461. }
  80462. break;
  80463. case 235: /* trigger_cmd_list */
  80464. case 240: /* trigger_cmd */
  80465. {
  80466. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
  80467. }
  80468. break;
  80469. case 237: /* trigger_event */
  80470. {
  80471. sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
  80472. }
  80473. break;
  80474. default: break; /* If no destructor action specified: do nothing */
  80475. }
  80476. }
  80477. /*
  80478. ** Pop the parser's stack once.
  80479. **
  80480. ** If there is a destructor routine associated with the token which
  80481. ** is popped from the stack, then call it.
  80482. **
  80483. ** Return the major token number for the symbol popped.
  80484. */
  80485. static int yy_pop_parser_stack(yyParser *pParser){
  80486. YYCODETYPE yymajor;
  80487. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  80488. if( pParser->yyidx<0 ) return 0;
  80489. #ifndef NDEBUG
  80490. if( yyTraceFILE && pParser->yyidx>=0 ){
  80491. fprintf(yyTraceFILE,"%sPopping %s\n",
  80492. yyTracePrompt,
  80493. yyTokenName[yytos->major]);
  80494. }
  80495. #endif
  80496. yymajor = yytos->major;
  80497. yy_destructor(pParser, yymajor, &yytos->minor);
  80498. pParser->yyidx--;
  80499. return yymajor;
  80500. }
  80501. /*
  80502. ** Deallocate and destroy a parser. Destructors are all called for
  80503. ** all stack elements before shutting the parser down.
  80504. **
  80505. ** Inputs:
  80506. ** <ul>
  80507. ** <li> A pointer to the parser. This should be a pointer
  80508. ** obtained from sqlite3ParserAlloc.
  80509. ** <li> A pointer to a function used to reclaim memory obtained
  80510. ** from malloc.
  80511. ** </ul>
  80512. */
  80513. SQLITE_PRIVATE void sqlite3ParserFree(
  80514. void *p, /* The parser to be deleted */
  80515. void (*freeProc)(void*) /* Function used to reclaim memory */
  80516. ){
  80517. yyParser *pParser = (yyParser*)p;
  80518. if( pParser==0 ) return;
  80519. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  80520. #if YYSTACKDEPTH<=0
  80521. free(pParser->yystack);
  80522. #endif
  80523. (*freeProc)((void*)pParser);
  80524. }
  80525. /*
  80526. ** Return the peak depth of the stack for a parser.
  80527. */
  80528. #ifdef YYTRACKMAXSTACKDEPTH
  80529. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  80530. yyParser *pParser = (yyParser*)p;
  80531. return pParser->yyidxMax;
  80532. }
  80533. #endif
  80534. /*
  80535. ** Find the appropriate action for a parser given the terminal
  80536. ** look-ahead token iLookAhead.
  80537. **
  80538. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  80539. ** independent of the look-ahead. If it is, return the action, otherwise
  80540. ** return YY_NO_ACTION.
  80541. */
  80542. static int yy_find_shift_action(
  80543. yyParser *pParser, /* The parser */
  80544. YYCODETYPE iLookAhead /* The look-ahead token */
  80545. ){
  80546. int i;
  80547. int stateno = pParser->yystack[pParser->yyidx].stateno;
  80548. if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  80549. return yy_default[stateno];
  80550. }
  80551. assert( iLookAhead!=YYNOCODE );
  80552. i += iLookAhead;
  80553. if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
  80554. if( iLookAhead>0 ){
  80555. #ifdef YYFALLBACK
  80556. YYCODETYPE iFallback; /* Fallback token */
  80557. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  80558. && (iFallback = yyFallback[iLookAhead])!=0 ){
  80559. #ifndef NDEBUG
  80560. if( yyTraceFILE ){
  80561. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  80562. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  80563. }
  80564. #endif
  80565. return yy_find_shift_action(pParser, iFallback);
  80566. }
  80567. #endif
  80568. #ifdef YYWILDCARD
  80569. {
  80570. int j = i - iLookAhead + YYWILDCARD;
  80571. if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
  80572. #ifndef NDEBUG
  80573. if( yyTraceFILE ){
  80574. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  80575. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  80576. }
  80577. #endif /* NDEBUG */
  80578. return yy_action[j];
  80579. }
  80580. }
  80581. #endif /* YYWILDCARD */
  80582. }
  80583. return yy_default[stateno];
  80584. }else{
  80585. return yy_action[i];
  80586. }
  80587. }
  80588. /*
  80589. ** Find the appropriate action for a parser given the non-terminal
  80590. ** look-ahead token iLookAhead.
  80591. **
  80592. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  80593. ** independent of the look-ahead. If it is, return the action, otherwise
  80594. ** return YY_NO_ACTION.
  80595. */
  80596. static int yy_find_reduce_action(
  80597. int stateno, /* Current state number */
  80598. YYCODETYPE iLookAhead /* The look-ahead token */
  80599. ){
  80600. int i;
  80601. #ifdef YYERRORSYMBOL
  80602. if( stateno>YY_REDUCE_MAX ){
  80603. return yy_default[stateno];
  80604. }
  80605. #else
  80606. assert( stateno<=YY_REDUCE_MAX );
  80607. #endif
  80608. i = yy_reduce_ofst[stateno];
  80609. assert( i!=YY_REDUCE_USE_DFLT );
  80610. assert( iLookAhead!=YYNOCODE );
  80611. i += iLookAhead;
  80612. #ifdef YYERRORSYMBOL
  80613. if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
  80614. return yy_default[stateno];
  80615. }
  80616. #else
  80617. assert( i>=0 && i<YY_SZ_ACTTAB );
  80618. assert( yy_lookahead[i]==iLookAhead );
  80619. #endif
  80620. return yy_action[i];
  80621. }
  80622. /*
  80623. ** The following routine is called if the stack overflows.
  80624. */
  80625. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  80626. sqlite3ParserARG_FETCH;
  80627. yypParser->yyidx--;
  80628. #ifndef NDEBUG
  80629. if( yyTraceFILE ){
  80630. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  80631. }
  80632. #endif
  80633. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  80634. /* Here code is inserted which will execute if the parser
  80635. ** stack every overflows */
  80636. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  80637. sqlite3ErrorMsg(pParse, "parser stack overflow");
  80638. pParse->parseError = 1;
  80639. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  80640. }
  80641. /*
  80642. ** Perform a shift action.
  80643. */
  80644. static void yy_shift(
  80645. yyParser *yypParser, /* The parser to be shifted */
  80646. int yyNewState, /* The new state to shift in */
  80647. int yyMajor, /* The major token to shift in */
  80648. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  80649. ){
  80650. yyStackEntry *yytos;
  80651. yypParser->yyidx++;
  80652. #ifdef YYTRACKMAXSTACKDEPTH
  80653. if( yypParser->yyidx>yypParser->yyidxMax ){
  80654. yypParser->yyidxMax = yypParser->yyidx;
  80655. }
  80656. #endif
  80657. #if YYSTACKDEPTH>0
  80658. if( yypParser->yyidx>=YYSTACKDEPTH ){
  80659. yyStackOverflow(yypParser, yypMinor);
  80660. return;
  80661. }
  80662. #else
  80663. if( yypParser->yyidx>=yypParser->yystksz ){
  80664. yyGrowStack(yypParser);
  80665. if( yypParser->yyidx>=yypParser->yystksz ){
  80666. yyStackOverflow(yypParser, yypMinor);
  80667. return;
  80668. }
  80669. }
  80670. #endif
  80671. yytos = &yypParser->yystack[yypParser->yyidx];
  80672. yytos->stateno = (YYACTIONTYPE)yyNewState;
  80673. yytos->major = (YYCODETYPE)yyMajor;
  80674. yytos->minor = *yypMinor;
  80675. #ifndef NDEBUG
  80676. if( yyTraceFILE && yypParser->yyidx>0 ){
  80677. int i;
  80678. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  80679. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  80680. for(i=1; i<=yypParser->yyidx; i++)
  80681. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  80682. fprintf(yyTraceFILE,"\n");
  80683. }
  80684. #endif
  80685. }
  80686. /* The following table contains information about every rule that
  80687. ** is used during the reduce.
  80688. */
  80689. static const struct {
  80690. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  80691. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  80692. } yyRuleInfo[] = {
  80693. { 142, 1 },
  80694. { 143, 2 },
  80695. { 143, 1 },
  80696. { 144, 1 },
  80697. { 144, 3 },
  80698. { 145, 0 },
  80699. { 145, 1 },
  80700. { 145, 3 },
  80701. { 146, 1 },
  80702. { 147, 3 },
  80703. { 149, 0 },
  80704. { 149, 1 },
  80705. { 149, 2 },
  80706. { 148, 0 },
  80707. { 148, 1 },
  80708. { 148, 1 },
  80709. { 148, 1 },
  80710. { 147, 2 },
  80711. { 147, 2 },
  80712. { 147, 2 },
  80713. { 151, 1 },
  80714. { 151, 0 },
  80715. { 147, 2 },
  80716. { 147, 3 },
  80717. { 147, 5 },
  80718. { 147, 2 },
  80719. { 152, 6 },
  80720. { 154, 1 },
  80721. { 156, 0 },
  80722. { 156, 3 },
  80723. { 155, 1 },
  80724. { 155, 0 },
  80725. { 153, 4 },
  80726. { 153, 2 },
  80727. { 158, 3 },
  80728. { 158, 1 },
  80729. { 161, 3 },
  80730. { 162, 1 },
  80731. { 165, 1 },
  80732. { 165, 1 },
  80733. { 166, 1 },
  80734. { 150, 1 },
  80735. { 150, 1 },
  80736. { 150, 1 },
  80737. { 163, 0 },
  80738. { 163, 1 },
  80739. { 167, 1 },
  80740. { 167, 4 },
  80741. { 167, 6 },
  80742. { 168, 1 },
  80743. { 168, 2 },
  80744. { 169, 1 },
  80745. { 169, 1 },
  80746. { 164, 2 },
  80747. { 164, 0 },
  80748. { 172, 3 },
  80749. { 172, 1 },
  80750. { 173, 2 },
  80751. { 173, 4 },
  80752. { 173, 3 },
  80753. { 173, 3 },
  80754. { 173, 2 },
  80755. { 173, 2 },
  80756. { 173, 3 },
  80757. { 173, 5 },
  80758. { 173, 2 },
  80759. { 173, 4 },
  80760. { 173, 4 },
  80761. { 173, 1 },
  80762. { 173, 2 },
  80763. { 178, 0 },
  80764. { 178, 1 },
  80765. { 180, 0 },
  80766. { 180, 2 },
  80767. { 182, 2 },
  80768. { 182, 3 },
  80769. { 182, 3 },
  80770. { 182, 3 },
  80771. { 183, 2 },
  80772. { 183, 2 },
  80773. { 183, 1 },
  80774. { 183, 1 },
  80775. { 181, 3 },
  80776. { 181, 2 },
  80777. { 184, 0 },
  80778. { 184, 2 },
  80779. { 184, 2 },
  80780. { 159, 0 },
  80781. { 159, 2 },
  80782. { 185, 3 },
  80783. { 185, 2 },
  80784. { 185, 1 },
  80785. { 186, 2 },
  80786. { 186, 7 },
  80787. { 186, 5 },
  80788. { 186, 5 },
  80789. { 186, 10 },
  80790. { 188, 0 },
  80791. { 188, 1 },
  80792. { 176, 0 },
  80793. { 176, 3 },
  80794. { 189, 0 },
  80795. { 189, 2 },
  80796. { 190, 1 },
  80797. { 190, 1 },
  80798. { 190, 1 },
  80799. { 147, 4 },
  80800. { 192, 2 },
  80801. { 192, 0 },
  80802. { 147, 8 },
  80803. { 147, 4 },
  80804. { 147, 1 },
  80805. { 160, 1 },
  80806. { 160, 3 },
  80807. { 195, 1 },
  80808. { 195, 2 },
  80809. { 195, 1 },
  80810. { 194, 9 },
  80811. { 196, 1 },
  80812. { 196, 1 },
  80813. { 196, 0 },
  80814. { 204, 2 },
  80815. { 204, 0 },
  80816. { 197, 3 },
  80817. { 197, 2 },
  80818. { 197, 4 },
  80819. { 205, 2 },
  80820. { 205, 1 },
  80821. { 205, 0 },
  80822. { 198, 0 },
  80823. { 198, 2 },
  80824. { 207, 2 },
  80825. { 207, 0 },
  80826. { 206, 7 },
  80827. { 206, 7 },
  80828. { 206, 7 },
  80829. { 157, 0 },
  80830. { 157, 2 },
  80831. { 193, 2 },
  80832. { 208, 1 },
  80833. { 208, 2 },
  80834. { 208, 3 },
  80835. { 208, 4 },
  80836. { 210, 2 },
  80837. { 210, 0 },
  80838. { 209, 0 },
  80839. { 209, 3 },
  80840. { 209, 2 },
  80841. { 211, 4 },
  80842. { 211, 0 },
  80843. { 202, 0 },
  80844. { 202, 3 },
  80845. { 214, 4 },
  80846. { 214, 2 },
  80847. { 215, 1 },
  80848. { 177, 1 },
  80849. { 177, 1 },
  80850. { 177, 0 },
  80851. { 200, 0 },
  80852. { 200, 3 },
  80853. { 201, 0 },
  80854. { 201, 2 },
  80855. { 203, 0 },
  80856. { 203, 2 },
  80857. { 203, 4 },
  80858. { 203, 4 },
  80859. { 147, 5 },
  80860. { 199, 0 },
  80861. { 199, 2 },
  80862. { 147, 7 },
  80863. { 217, 5 },
  80864. { 217, 3 },
  80865. { 147, 8 },
  80866. { 147, 5 },
  80867. { 147, 6 },
  80868. { 218, 2 },
  80869. { 218, 1 },
  80870. { 220, 3 },
  80871. { 220, 1 },
  80872. { 219, 0 },
  80873. { 219, 3 },
  80874. { 213, 3 },
  80875. { 213, 1 },
  80876. { 175, 1 },
  80877. { 175, 3 },
  80878. { 174, 1 },
  80879. { 175, 1 },
  80880. { 175, 1 },
  80881. { 175, 3 },
  80882. { 175, 5 },
  80883. { 174, 1 },
  80884. { 174, 1 },
  80885. { 175, 1 },
  80886. { 175, 1 },
  80887. { 175, 3 },
  80888. { 175, 6 },
  80889. { 175, 5 },
  80890. { 175, 4 },
  80891. { 174, 1 },
  80892. { 175, 3 },
  80893. { 175, 3 },
  80894. { 175, 3 },
  80895. { 175, 3 },
  80896. { 175, 3 },
  80897. { 175, 3 },
  80898. { 175, 3 },
  80899. { 175, 3 },
  80900. { 222, 1 },
  80901. { 222, 2 },
  80902. { 222, 1 },
  80903. { 222, 2 },
  80904. { 223, 2 },
  80905. { 223, 0 },
  80906. { 175, 4 },
  80907. { 175, 2 },
  80908. { 175, 3 },
  80909. { 175, 3 },
  80910. { 175, 4 },
  80911. { 175, 2 },
  80912. { 175, 2 },
  80913. { 175, 2 },
  80914. { 175, 2 },
  80915. { 224, 1 },
  80916. { 224, 2 },
  80917. { 175, 5 },
  80918. { 225, 1 },
  80919. { 225, 2 },
  80920. { 175, 5 },
  80921. { 175, 3 },
  80922. { 175, 5 },
  80923. { 175, 4 },
  80924. { 175, 4 },
  80925. { 175, 5 },
  80926. { 227, 5 },
  80927. { 227, 4 },
  80928. { 228, 2 },
  80929. { 228, 0 },
  80930. { 226, 1 },
  80931. { 226, 0 },
  80932. { 221, 1 },
  80933. { 221, 0 },
  80934. { 216, 3 },
  80935. { 216, 1 },
  80936. { 147, 11 },
  80937. { 229, 1 },
  80938. { 229, 0 },
  80939. { 179, 0 },
  80940. { 179, 3 },
  80941. { 187, 5 },
  80942. { 187, 3 },
  80943. { 230, 0 },
  80944. { 230, 2 },
  80945. { 147, 4 },
  80946. { 147, 1 },
  80947. { 147, 2 },
  80948. { 147, 3 },
  80949. { 147, 5 },
  80950. { 147, 6 },
  80951. { 147, 5 },
  80952. { 147, 6 },
  80953. { 231, 1 },
  80954. { 231, 1 },
  80955. { 231, 1 },
  80956. { 231, 1 },
  80957. { 231, 1 },
  80958. { 170, 2 },
  80959. { 171, 2 },
  80960. { 233, 1 },
  80961. { 232, 1 },
  80962. { 232, 0 },
  80963. { 147, 5 },
  80964. { 234, 11 },
  80965. { 236, 1 },
  80966. { 236, 1 },
  80967. { 236, 2 },
  80968. { 236, 0 },
  80969. { 237, 1 },
  80970. { 237, 1 },
  80971. { 237, 3 },
  80972. { 238, 0 },
  80973. { 238, 3 },
  80974. { 239, 0 },
  80975. { 239, 2 },
  80976. { 235, 3 },
  80977. { 235, 2 },
  80978. { 240, 6 },
  80979. { 240, 8 },
  80980. { 240, 5 },
  80981. { 240, 4 },
  80982. { 240, 1 },
  80983. { 175, 4 },
  80984. { 175, 6 },
  80985. { 191, 1 },
  80986. { 191, 1 },
  80987. { 191, 1 },
  80988. { 147, 4 },
  80989. { 147, 6 },
  80990. { 147, 3 },
  80991. { 242, 0 },
  80992. { 242, 2 },
  80993. { 241, 1 },
  80994. { 241, 0 },
  80995. { 147, 1 },
  80996. { 147, 3 },
  80997. { 147, 1 },
  80998. { 147, 3 },
  80999. { 147, 6 },
  81000. { 147, 6 },
  81001. { 243, 1 },
  81002. { 244, 0 },
  81003. { 244, 1 },
  81004. { 147, 1 },
  81005. { 147, 4 },
  81006. { 245, 7 },
  81007. { 246, 1 },
  81008. { 246, 3 },
  81009. { 247, 0 },
  81010. { 247, 2 },
  81011. { 248, 1 },
  81012. { 248, 3 },
  81013. { 249, 1 },
  81014. { 250, 0 },
  81015. { 250, 2 },
  81016. };
  81017. static void yy_accept(yyParser*); /* Forward Declaration */
  81018. /*
  81019. ** Perform a reduce action and the shift that must immediately
  81020. ** follow the reduce.
  81021. */
  81022. static void yy_reduce(
  81023. yyParser *yypParser, /* The parser */
  81024. int yyruleno /* Number of the rule by which to reduce */
  81025. ){
  81026. int yygoto; /* The next state */
  81027. int yyact; /* The next action */
  81028. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  81029. yyStackEntry *yymsp; /* The top of the parser's stack */
  81030. int yysize; /* Amount to pop the stack */
  81031. sqlite3ParserARG_FETCH;
  81032. yymsp = &yypParser->yystack[yypParser->yyidx];
  81033. #ifndef NDEBUG
  81034. if( yyTraceFILE && yyruleno>=0
  81035. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  81036. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  81037. yyRuleName[yyruleno]);
  81038. }
  81039. #endif /* NDEBUG */
  81040. /* Silence complaints from purify about yygotominor being uninitialized
  81041. ** in some cases when it is copied into the stack after the following
  81042. ** switch. yygotominor is uninitialized when a rule reduces that does
  81043. ** not set the value of its left-hand side nonterminal. Leaving the
  81044. ** value of the nonterminal uninitialized is utterly harmless as long
  81045. ** as the value is never used. So really the only thing this code
  81046. ** accomplishes is to quieten purify.
  81047. **
  81048. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  81049. ** without this code, their parser segfaults. I'm not sure what there
  81050. ** parser is doing to make this happen. This is the second bug report
  81051. ** from wireshark this week. Clearly they are stressing Lemon in ways
  81052. ** that it has not been previously stressed... (SQLite ticket #2172)
  81053. */
  81054. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  81055. yygotominor = yyzerominor;
  81056. switch( yyruleno ){
  81057. /* Beginning here are the reduction cases. A typical example
  81058. ** follows:
  81059. ** case 0:
  81060. ** #line <lineno> <grammarfile>
  81061. ** { ... } // User supplied code
  81062. ** #line <lineno> <thisfile>
  81063. ** break;
  81064. */
  81065. case 0: /* input ::= cmdlist */
  81066. case 1: /* cmdlist ::= cmdlist ecmd */
  81067. case 2: /* cmdlist ::= ecmd */
  81068. case 3: /* ecmd ::= SEMI */
  81069. case 4: /* ecmd ::= explain cmdx SEMI */
  81070. case 10: /* trans_opt ::= */
  81071. case 11: /* trans_opt ::= TRANSACTION */
  81072. case 12: /* trans_opt ::= TRANSACTION nm */
  81073. case 20: /* savepoint_opt ::= SAVEPOINT */
  81074. case 21: /* savepoint_opt ::= */
  81075. case 25: /* cmd ::= create_table create_table_args */
  81076. case 34: /* columnlist ::= columnlist COMMA column */
  81077. case 35: /* columnlist ::= column */
  81078. case 44: /* type ::= */
  81079. case 51: /* signed ::= plus_num */
  81080. case 52: /* signed ::= minus_num */
  81081. case 53: /* carglist ::= carglist carg */
  81082. case 54: /* carglist ::= */
  81083. case 55: /* carg ::= CONSTRAINT nm ccons */
  81084. case 56: /* carg ::= ccons */
  81085. case 62: /* ccons ::= NULL onconf */
  81086. case 89: /* conslist ::= conslist COMMA tcons */
  81087. case 90: /* conslist ::= conslist tcons */
  81088. case 91: /* conslist ::= tcons */
  81089. case 92: /* tcons ::= CONSTRAINT nm */
  81090. case 268: /* plus_opt ::= PLUS */
  81091. case 269: /* plus_opt ::= */
  81092. case 279: /* foreach_clause ::= */
  81093. case 280: /* foreach_clause ::= FOR EACH ROW */
  81094. case 300: /* database_kw_opt ::= DATABASE */
  81095. case 301: /* database_kw_opt ::= */
  81096. case 309: /* kwcolumn_opt ::= */
  81097. case 310: /* kwcolumn_opt ::= COLUMNKW */
  81098. case 314: /* vtabarglist ::= vtabarg */
  81099. case 315: /* vtabarglist ::= vtabarglist COMMA vtabarg */
  81100. case 317: /* vtabarg ::= vtabarg vtabargtoken */
  81101. case 321: /* anylist ::= */
  81102. {
  81103. }
  81104. break;
  81105. case 5: /* explain ::= */
  81106. { sqlite3BeginParse(pParse, 0); }
  81107. break;
  81108. case 6: /* explain ::= EXPLAIN */
  81109. { sqlite3BeginParse(pParse, 1); }
  81110. break;
  81111. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  81112. { sqlite3BeginParse(pParse, 2); }
  81113. break;
  81114. case 8: /* cmdx ::= cmd */
  81115. { sqlite3FinishCoding(pParse); }
  81116. break;
  81117. case 9: /* cmd ::= BEGIN transtype trans_opt */
  81118. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
  81119. break;
  81120. case 13: /* transtype ::= */
  81121. {yygotominor.yy194 = TK_DEFERRED;}
  81122. break;
  81123. case 14: /* transtype ::= DEFERRED */
  81124. case 15: /* transtype ::= IMMEDIATE */
  81125. case 16: /* transtype ::= EXCLUSIVE */
  81126. case 114: /* multiselect_op ::= UNION */
  81127. case 116: /* multiselect_op ::= EXCEPT|INTERSECT */
  81128. {yygotominor.yy194 = yymsp[0].major;}
  81129. break;
  81130. case 17: /* cmd ::= COMMIT trans_opt */
  81131. case 18: /* cmd ::= END trans_opt */
  81132. {sqlite3CommitTransaction(pParse);}
  81133. break;
  81134. case 19: /* cmd ::= ROLLBACK trans_opt */
  81135. {sqlite3RollbackTransaction(pParse);}
  81136. break;
  81137. case 22: /* cmd ::= SAVEPOINT nm */
  81138. {
  81139. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  81140. }
  81141. break;
  81142. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  81143. {
  81144. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  81145. }
  81146. break;
  81147. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  81148. {
  81149. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  81150. }
  81151. break;
  81152. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  81153. {
  81154. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
  81155. }
  81156. break;
  81157. case 27: /* createkw ::= CREATE */
  81158. {
  81159. pParse->db->lookaside.bEnabled = 0;
  81160. yygotominor.yy0 = yymsp[0].minor.yy0;
  81161. }
  81162. break;
  81163. case 28: /* ifnotexists ::= */
  81164. case 31: /* temp ::= */
  81165. case 70: /* autoinc ::= */
  81166. case 84: /* init_deferred_pred_opt ::= */
  81167. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  81168. case 97: /* defer_subclause_opt ::= */
  81169. case 108: /* ifexists ::= */
  81170. case 119: /* distinct ::= ALL */
  81171. case 120: /* distinct ::= */
  81172. case 222: /* between_op ::= BETWEEN */
  81173. case 225: /* in_op ::= IN */
  81174. {yygotominor.yy194 = 0;}
  81175. break;
  81176. case 29: /* ifnotexists ::= IF NOT EXISTS */
  81177. case 30: /* temp ::= TEMP */
  81178. case 71: /* autoinc ::= AUTOINCR */
  81179. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  81180. case 107: /* ifexists ::= IF EXISTS */
  81181. case 118: /* distinct ::= DISTINCT */
  81182. case 223: /* between_op ::= NOT BETWEEN */
  81183. case 226: /* in_op ::= NOT IN */
  81184. {yygotominor.yy194 = 1;}
  81185. break;
  81186. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  81187. {
  81188. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  81189. }
  81190. break;
  81191. case 33: /* create_table_args ::= AS select */
  81192. {
  81193. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy243);
  81194. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  81195. }
  81196. break;
  81197. case 36: /* column ::= columnid type carglist */
  81198. {
  81199. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  81200. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  81201. }
  81202. break;
  81203. case 37: /* columnid ::= nm */
  81204. {
  81205. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  81206. yygotominor.yy0 = yymsp[0].minor.yy0;
  81207. }
  81208. break;
  81209. case 38: /* id ::= ID */
  81210. case 39: /* id ::= INDEXED */
  81211. case 40: /* ids ::= ID|STRING */
  81212. case 41: /* nm ::= id */
  81213. case 42: /* nm ::= STRING */
  81214. case 43: /* nm ::= JOIN_KW */
  81215. case 46: /* typetoken ::= typename */
  81216. case 49: /* typename ::= ids */
  81217. case 126: /* as ::= AS nm */
  81218. case 127: /* as ::= ids */
  81219. case 137: /* dbnm ::= DOT nm */
  81220. case 146: /* indexed_opt ::= INDEXED BY nm */
  81221. case 251: /* collate ::= COLLATE ids */
  81222. case 260: /* nmnum ::= plus_num */
  81223. case 261: /* nmnum ::= nm */
  81224. case 262: /* nmnum ::= ON */
  81225. case 263: /* nmnum ::= DELETE */
  81226. case 264: /* nmnum ::= DEFAULT */
  81227. case 265: /* plus_num ::= plus_opt number */
  81228. case 266: /* minus_num ::= MINUS number */
  81229. case 267: /* number ::= INTEGER|FLOAT */
  81230. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  81231. break;
  81232. case 45: /* type ::= typetoken */
  81233. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  81234. break;
  81235. case 47: /* typetoken ::= typename LP signed RP */
  81236. {
  81237. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  81238. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  81239. }
  81240. break;
  81241. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  81242. {
  81243. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  81244. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  81245. }
  81246. break;
  81247. case 50: /* typename ::= typename ids */
  81248. {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);}
  81249. break;
  81250. case 57: /* ccons ::= DEFAULT term */
  81251. case 59: /* ccons ::= DEFAULT PLUS term */
  81252. {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy72);}
  81253. break;
  81254. case 58: /* ccons ::= DEFAULT LP expr RP */
  81255. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy72);}
  81256. break;
  81257. case 60: /* ccons ::= DEFAULT MINUS term */
  81258. {
  81259. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy72, 0, 0);
  81260. sqlite3ExprSpan(p,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy72->span);
  81261. sqlite3AddDefaultValue(pParse,p);
  81262. }
  81263. break;
  81264. case 61: /* ccons ::= DEFAULT id */
  81265. {
  81266. Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
  81267. sqlite3AddDefaultValue(pParse,p);
  81268. }
  81269. break;
  81270. case 63: /* ccons ::= NOT NULL onconf */
  81271. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
  81272. break;
  81273. case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  81274. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
  81275. break;
  81276. case 65: /* ccons ::= UNIQUE onconf */
  81277. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0);}
  81278. break;
  81279. case 66: /* ccons ::= CHECK LP expr RP */
  81280. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy72);}
  81281. break;
  81282. case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  81283. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
  81284. break;
  81285. case 68: /* ccons ::= defer_subclause */
  81286. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
  81287. break;
  81288. case 69: /* ccons ::= COLLATE ids */
  81289. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  81290. break;
  81291. case 72: /* refargs ::= */
  81292. { yygotominor.yy194 = OE_Restrict * 0x010101; }
  81293. break;
  81294. case 73: /* refargs ::= refargs refarg */
  81295. { yygotominor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
  81296. break;
  81297. case 74: /* refarg ::= MATCH nm */
  81298. { yygotominor.yy497.value = 0; yygotominor.yy497.mask = 0x000000; }
  81299. break;
  81300. case 75: /* refarg ::= ON DELETE refact */
  81301. { yygotominor.yy497.value = yymsp[0].minor.yy194; yygotominor.yy497.mask = 0x0000ff; }
  81302. break;
  81303. case 76: /* refarg ::= ON UPDATE refact */
  81304. { yygotominor.yy497.value = yymsp[0].minor.yy194<<8; yygotominor.yy497.mask = 0x00ff00; }
  81305. break;
  81306. case 77: /* refarg ::= ON INSERT refact */
  81307. { yygotominor.yy497.value = yymsp[0].minor.yy194<<16; yygotominor.yy497.mask = 0xff0000; }
  81308. break;
  81309. case 78: /* refact ::= SET NULL */
  81310. { yygotominor.yy194 = OE_SetNull; }
  81311. break;
  81312. case 79: /* refact ::= SET DEFAULT */
  81313. { yygotominor.yy194 = OE_SetDflt; }
  81314. break;
  81315. case 80: /* refact ::= CASCADE */
  81316. { yygotominor.yy194 = OE_Cascade; }
  81317. break;
  81318. case 81: /* refact ::= RESTRICT */
  81319. { yygotominor.yy194 = OE_Restrict; }
  81320. break;
  81321. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  81322. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  81323. case 98: /* defer_subclause_opt ::= defer_subclause */
  81324. case 100: /* onconf ::= ON CONFLICT resolvetype */
  81325. case 102: /* orconf ::= OR resolvetype */
  81326. case 103: /* resolvetype ::= raisetype */
  81327. case 175: /* insert_cmd ::= INSERT orconf */
  81328. {yygotominor.yy194 = yymsp[0].minor.yy194;}
  81329. break;
  81330. case 87: /* conslist_opt ::= */
  81331. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  81332. break;
  81333. case 88: /* conslist_opt ::= COMMA conslist */
  81334. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  81335. break;
  81336. case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  81337. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
  81338. break;
  81339. case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
  81340. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0);}
  81341. break;
  81342. case 95: /* tcons ::= CHECK LP expr RP onconf */
  81343. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy72);}
  81344. break;
  81345. case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  81346. {
  81347. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
  81348. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
  81349. }
  81350. break;
  81351. case 99: /* onconf ::= */
  81352. case 101: /* orconf ::= */
  81353. {yygotominor.yy194 = OE_Default;}
  81354. break;
  81355. case 104: /* resolvetype ::= IGNORE */
  81356. {yygotominor.yy194 = OE_Ignore;}
  81357. break;
  81358. case 105: /* resolvetype ::= REPLACE */
  81359. case 176: /* insert_cmd ::= REPLACE */
  81360. {yygotominor.yy194 = OE_Replace;}
  81361. break;
  81362. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  81363. {
  81364. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
  81365. }
  81366. break;
  81367. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  81368. {
  81369. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy243, yymsp[-6].minor.yy194, yymsp[-4].minor.yy194);
  81370. }
  81371. break;
  81372. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  81373. {
  81374. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
  81375. }
  81376. break;
  81377. case 111: /* cmd ::= select */
  81378. {
  81379. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  81380. sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
  81381. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  81382. }
  81383. break;
  81384. case 112: /* select ::= oneselect */
  81385. {yygotominor.yy243 = yymsp[0].minor.yy243;}
  81386. break;
  81387. case 113: /* select ::= select multiselect_op oneselect */
  81388. {
  81389. if( yymsp[0].minor.yy243 ){
  81390. yymsp[0].minor.yy243->op = (u8)yymsp[-1].minor.yy194;
  81391. yymsp[0].minor.yy243->pPrior = yymsp[-2].minor.yy243;
  81392. }else{
  81393. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy243);
  81394. }
  81395. yygotominor.yy243 = yymsp[0].minor.yy243;
  81396. }
  81397. break;
  81398. case 115: /* multiselect_op ::= UNION ALL */
  81399. {yygotominor.yy194 = TK_ALL;}
  81400. break;
  81401. case 117: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  81402. {
  81403. yygotominor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
  81404. }
  81405. break;
  81406. case 121: /* sclp ::= selcollist COMMA */
  81407. case 247: /* idxlist_opt ::= LP idxlist RP */
  81408. {yygotominor.yy148 = yymsp[-1].minor.yy148;}
  81409. break;
  81410. case 122: /* sclp ::= */
  81411. case 150: /* orderby_opt ::= */
  81412. case 158: /* groupby_opt ::= */
  81413. case 240: /* exprlist ::= */
  81414. case 246: /* idxlist_opt ::= */
  81415. {yygotominor.yy148 = 0;}
  81416. break;
  81417. case 123: /* selcollist ::= sclp expr as */
  81418. {
  81419. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
  81420. }
  81421. break;
  81422. case 124: /* selcollist ::= sclp STAR */
  81423. {
  81424. Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
  81425. yygotominor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p, 0);
  81426. }
  81427. break;
  81428. case 125: /* selcollist ::= sclp nm DOT STAR */
  81429. {
  81430. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  81431. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  81432. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  81433. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot, 0);
  81434. }
  81435. break;
  81436. case 128: /* as ::= */
  81437. {yygotominor.yy0.n = 0;}
  81438. break;
  81439. case 129: /* from ::= */
  81440. {yygotominor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy185));}
  81441. break;
  81442. case 130: /* from ::= FROM seltablist */
  81443. {
  81444. yygotominor.yy185 = yymsp[0].minor.yy185;
  81445. sqlite3SrcListShiftJoinType(yygotominor.yy185);
  81446. }
  81447. break;
  81448. case 131: /* stl_prefix ::= seltablist joinop */
  81449. {
  81450. yygotominor.yy185 = yymsp[-1].minor.yy185;
  81451. if( yygotominor.yy185 && yygotominor.yy185->nSrc>0 ) yygotominor.yy185->a[yygotominor.yy185->nSrc-1].jointype = (u8)yymsp[0].minor.yy194;
  81452. }
  81453. break;
  81454. case 132: /* stl_prefix ::= */
  81455. {yygotominor.yy185 = 0;}
  81456. break;
  81457. case 133: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  81458. {
  81459. yygotominor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  81460. sqlite3SrcListIndexedBy(pParse, yygotominor.yy185, &yymsp[-2].minor.yy0);
  81461. }
  81462. break;
  81463. case 134: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  81464. {
  81465. yygotominor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  81466. }
  81467. break;
  81468. case 135: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  81469. {
  81470. if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
  81471. yygotominor.yy185 = yymsp[-4].minor.yy185;
  81472. }else{
  81473. Select *pSubquery;
  81474. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
  81475. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,0,0,0);
  81476. yygotominor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  81477. }
  81478. }
  81479. break;
  81480. case 136: /* dbnm ::= */
  81481. case 145: /* indexed_opt ::= */
  81482. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  81483. break;
  81484. case 138: /* fullname ::= nm dbnm */
  81485. {yygotominor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  81486. break;
  81487. case 139: /* joinop ::= COMMA|JOIN */
  81488. { yygotominor.yy194 = JT_INNER; }
  81489. break;
  81490. case 140: /* joinop ::= JOIN_KW JOIN */
  81491. { yygotominor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  81492. break;
  81493. case 141: /* joinop ::= JOIN_KW nm JOIN */
  81494. { yygotominor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  81495. break;
  81496. case 142: /* joinop ::= JOIN_KW nm nm JOIN */
  81497. { yygotominor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  81498. break;
  81499. case 143: /* on_opt ::= ON expr */
  81500. case 154: /* sortitem ::= expr */
  81501. case 161: /* having_opt ::= HAVING expr */
  81502. case 168: /* where_opt ::= WHERE expr */
  81503. case 183: /* expr ::= term */
  81504. case 211: /* escape ::= ESCAPE expr */
  81505. case 235: /* case_else ::= ELSE expr */
  81506. case 237: /* case_operand ::= expr */
  81507. {yygotominor.yy72 = yymsp[0].minor.yy72;}
  81508. break;
  81509. case 144: /* on_opt ::= */
  81510. case 160: /* having_opt ::= */
  81511. case 167: /* where_opt ::= */
  81512. case 212: /* escape ::= */
  81513. case 236: /* case_else ::= */
  81514. case 238: /* case_operand ::= */
  81515. {yygotominor.yy72 = 0;}
  81516. break;
  81517. case 147: /* indexed_opt ::= NOT INDEXED */
  81518. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  81519. break;
  81520. case 148: /* using_opt ::= USING LP inscollist RP */
  81521. case 180: /* inscollist_opt ::= LP inscollist RP */
  81522. {yygotominor.yy254 = yymsp[-1].minor.yy254;}
  81523. break;
  81524. case 149: /* using_opt ::= */
  81525. case 179: /* inscollist_opt ::= */
  81526. {yygotominor.yy254 = 0;}
  81527. break;
  81528. case 151: /* orderby_opt ::= ORDER BY sortlist */
  81529. case 159: /* groupby_opt ::= GROUP BY nexprlist */
  81530. case 239: /* exprlist ::= nexprlist */
  81531. {yygotominor.yy148 = yymsp[0].minor.yy148;}
  81532. break;
  81533. case 152: /* sortlist ::= sortlist COMMA sortitem sortorder */
  81534. {
  81535. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy72,0);
  81536. if( yygotominor.yy148 ) yygotominor.yy148->a[yygotominor.yy148->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy194;
  81537. }
  81538. break;
  81539. case 153: /* sortlist ::= sortitem sortorder */
  81540. {
  81541. yygotominor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy72,0);
  81542. if( yygotominor.yy148 && yygotominor.yy148->a ) yygotominor.yy148->a[0].sortOrder = (u8)yymsp[0].minor.yy194;
  81543. }
  81544. break;
  81545. case 155: /* sortorder ::= ASC */
  81546. case 157: /* sortorder ::= */
  81547. {yygotominor.yy194 = SQLITE_SO_ASC;}
  81548. break;
  81549. case 156: /* sortorder ::= DESC */
  81550. {yygotominor.yy194 = SQLITE_SO_DESC;}
  81551. break;
  81552. case 162: /* limit_opt ::= */
  81553. {yygotominor.yy354.pLimit = 0; yygotominor.yy354.pOffset = 0;}
  81554. break;
  81555. case 163: /* limit_opt ::= LIMIT expr */
  81556. {yygotominor.yy354.pLimit = yymsp[0].minor.yy72; yygotominor.yy354.pOffset = 0;}
  81557. break;
  81558. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  81559. {yygotominor.yy354.pLimit = yymsp[-2].minor.yy72; yygotominor.yy354.pOffset = yymsp[0].minor.yy72;}
  81560. break;
  81561. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  81562. {yygotominor.yy354.pOffset = yymsp[-2].minor.yy72; yygotominor.yy354.pLimit = yymsp[0].minor.yy72;}
  81563. break;
  81564. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  81565. {
  81566. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
  81567. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
  81568. }
  81569. break;
  81570. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  81571. {
  81572. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
  81573. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
  81574. sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
  81575. }
  81576. break;
  81577. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  81578. {yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148,yymsp[0].minor.yy72,&yymsp[-2].minor.yy0);}
  81579. break;
  81580. case 171: /* setlist ::= nm EQ expr */
  81581. {yygotominor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy72,&yymsp[-2].minor.yy0);}
  81582. break;
  81583. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
  81584. {sqlite3Insert(pParse, yymsp[-5].minor.yy185, yymsp[-1].minor.yy148, 0, yymsp[-4].minor.yy254, yymsp[-7].minor.yy194);}
  81585. break;
  81586. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  81587. {sqlite3Insert(pParse, yymsp[-2].minor.yy185, 0, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);}
  81588. break;
  81589. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  81590. {sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);}
  81591. break;
  81592. case 177: /* itemlist ::= itemlist COMMA expr */
  81593. case 241: /* nexprlist ::= nexprlist COMMA expr */
  81594. {yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy72,0);}
  81595. break;
  81596. case 178: /* itemlist ::= expr */
  81597. case 242: /* nexprlist ::= expr */
  81598. {yygotominor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy72,0);}
  81599. break;
  81600. case 181: /* inscollist ::= inscollist COMMA nm */
  81601. {yygotominor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
  81602. break;
  81603. case 182: /* inscollist ::= nm */
  81604. {yygotominor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  81605. break;
  81606. case 184: /* expr ::= LP expr RP */
  81607. {yygotominor.yy72 = yymsp[-1].minor.yy72; sqlite3ExprSpan(yygotominor.yy72,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
  81608. break;
  81609. case 185: /* term ::= NULL */
  81610. case 190: /* term ::= INTEGER|FLOAT|BLOB */
  81611. case 191: /* term ::= STRING */
  81612. {yygotominor.yy72 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
  81613. break;
  81614. case 186: /* expr ::= id */
  81615. case 187: /* expr ::= JOIN_KW */
  81616. {yygotominor.yy72 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
  81617. break;
  81618. case 188: /* expr ::= nm DOT nm */
  81619. {
  81620. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  81621. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  81622. yygotominor.yy72 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  81623. }
  81624. break;
  81625. case 189: /* expr ::= nm DOT nm DOT nm */
  81626. {
  81627. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  81628. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  81629. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  81630. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  81631. yygotominor.yy72 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  81632. }
  81633. break;
  81634. case 192: /* expr ::= REGISTER */
  81635. {yygotominor.yy72 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
  81636. break;
  81637. case 193: /* expr ::= VARIABLE */
  81638. {
  81639. Token *pToken = &yymsp[0].minor.yy0;
  81640. Expr *pExpr = yygotominor.yy72 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
  81641. sqlite3ExprAssignVarNumber(pParse, pExpr);
  81642. }
  81643. break;
  81644. case 194: /* expr ::= expr COLLATE ids */
  81645. {
  81646. yygotominor.yy72 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy72, &yymsp[0].minor.yy0);
  81647. }
  81648. break;
  81649. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  81650. {
  81651. yygotominor.yy72 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy72, 0, &yymsp[-1].minor.yy0);
  81652. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  81653. }
  81654. break;
  81655. case 196: /* expr ::= ID LP distinct exprlist RP */
  81656. {
  81657. if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>SQLITE_MAX_FUNCTION_ARG ){
  81658. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  81659. }
  81660. yygotominor.yy72 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
  81661. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  81662. if( yymsp[-2].minor.yy194 && yygotominor.yy72 ){
  81663. yygotominor.yy72->flags |= EP_Distinct;
  81664. }
  81665. }
  81666. break;
  81667. case 197: /* expr ::= ID LP STAR RP */
  81668. {
  81669. yygotominor.yy72 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  81670. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  81671. }
  81672. break;
  81673. case 198: /* term ::= CTIME_KW */
  81674. {
  81675. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  81676. ** treated as functions that return constants */
  81677. yygotominor.yy72 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  81678. if( yygotominor.yy72 ){
  81679. yygotominor.yy72->op = TK_CONST_FUNC;
  81680. yygotominor.yy72->span = yymsp[0].minor.yy0;
  81681. }
  81682. }
  81683. break;
  81684. case 199: /* expr ::= expr AND expr */
  81685. case 200: /* expr ::= expr OR expr */
  81686. case 201: /* expr ::= expr LT|GT|GE|LE expr */
  81687. case 202: /* expr ::= expr EQ|NE expr */
  81688. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  81689. case 204: /* expr ::= expr PLUS|MINUS expr */
  81690. case 205: /* expr ::= expr STAR|SLASH|REM expr */
  81691. case 206: /* expr ::= expr CONCAT expr */
  81692. {yygotominor.yy72 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy72,yymsp[0].minor.yy72,0);}
  81693. break;
  81694. case 207: /* likeop ::= LIKE_KW */
  81695. case 209: /* likeop ::= MATCH */
  81696. {yygotominor.yy392.eOperator = yymsp[0].minor.yy0; yygotominor.yy392.not = 0;}
  81697. break;
  81698. case 208: /* likeop ::= NOT LIKE_KW */
  81699. case 210: /* likeop ::= NOT MATCH */
  81700. {yygotominor.yy392.eOperator = yymsp[0].minor.yy0; yygotominor.yy392.not = 1;}
  81701. break;
  81702. case 213: /* expr ::= expr likeop expr escape */
  81703. {
  81704. ExprList *pList;
  81705. pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy72, 0);
  81706. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy72, 0);
  81707. if( yymsp[0].minor.yy72 ){
  81708. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy72, 0);
  81709. }
  81710. yygotominor.yy72 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy392.eOperator);
  81711. if( yymsp[-2].minor.yy392.not ) yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy72, 0, 0);
  81712. sqlite3ExprSpan(yygotominor.yy72, &yymsp[-3].minor.yy72->span, &yymsp[-1].minor.yy72->span);
  81713. if( yygotominor.yy72 ) yygotominor.yy72->flags |= EP_InfixFunc;
  81714. }
  81715. break;
  81716. case 214: /* expr ::= expr ISNULL|NOTNULL */
  81717. {
  81718. yygotominor.yy72 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy72, 0, 0);
  81719. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-1].minor.yy72->span,&yymsp[0].minor.yy0);
  81720. }
  81721. break;
  81722. case 215: /* expr ::= expr IS NULL */
  81723. {
  81724. yygotominor.yy72 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy72, 0, 0);
  81725. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-2].minor.yy72->span,&yymsp[0].minor.yy0);
  81726. }
  81727. break;
  81728. case 216: /* expr ::= expr NOT NULL */
  81729. {
  81730. yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy72, 0, 0);
  81731. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-2].minor.yy72->span,&yymsp[0].minor.yy0);
  81732. }
  81733. break;
  81734. case 217: /* expr ::= expr IS NOT NULL */
  81735. {
  81736. yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy72, 0, 0);
  81737. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-3].minor.yy72->span,&yymsp[0].minor.yy0);
  81738. }
  81739. break;
  81740. case 218: /* expr ::= NOT expr */
  81741. case 219: /* expr ::= BITNOT expr */
  81742. {
  81743. yygotominor.yy72 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy72, 0, 0);
  81744. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy72->span);
  81745. }
  81746. break;
  81747. case 220: /* expr ::= MINUS expr */
  81748. {
  81749. yygotominor.yy72 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy72, 0, 0);
  81750. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy72->span);
  81751. }
  81752. break;
  81753. case 221: /* expr ::= PLUS expr */
  81754. {
  81755. yygotominor.yy72 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy72, 0, 0);
  81756. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy72->span);
  81757. }
  81758. break;
  81759. case 224: /* expr ::= expr between_op expr AND expr */
  81760. {
  81761. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy72, 0);
  81762. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy72, 0);
  81763. yygotominor.yy72 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy72, 0, 0);
  81764. if( yygotominor.yy72 ){
  81765. yygotominor.yy72->x.pList = pList;
  81766. }else{
  81767. sqlite3ExprListDelete(pParse->db, pList);
  81768. }
  81769. if( yymsp[-3].minor.yy194 ) yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy72, 0, 0);
  81770. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-4].minor.yy72->span,&yymsp[0].minor.yy72->span);
  81771. }
  81772. break;
  81773. case 227: /* expr ::= expr in_op LP exprlist RP */
  81774. {
  81775. yygotominor.yy72 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy72, 0, 0);
  81776. if( yygotominor.yy72 ){
  81777. yygotominor.yy72->x.pList = yymsp[-1].minor.yy148;
  81778. sqlite3ExprSetHeight(pParse, yygotominor.yy72);
  81779. }else{
  81780. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  81781. }
  81782. if( yymsp[-3].minor.yy194 ) yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy72, 0, 0);
  81783. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-4].minor.yy72->span,&yymsp[0].minor.yy0);
  81784. }
  81785. break;
  81786. case 228: /* expr ::= LP select RP */
  81787. {
  81788. yygotominor.yy72 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  81789. if( yygotominor.yy72 ){
  81790. yygotominor.yy72->x.pSelect = yymsp[-1].minor.yy243;
  81791. ExprSetProperty(yygotominor.yy72, EP_xIsSelect);
  81792. sqlite3ExprSetHeight(pParse, yygotominor.yy72);
  81793. }else{
  81794. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy243);
  81795. }
  81796. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  81797. }
  81798. break;
  81799. case 229: /* expr ::= expr in_op LP select RP */
  81800. {
  81801. yygotominor.yy72 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy72, 0, 0);
  81802. if( yygotominor.yy72 ){
  81803. yygotominor.yy72->x.pSelect = yymsp[-1].minor.yy243;
  81804. ExprSetProperty(yygotominor.yy72, EP_xIsSelect);
  81805. sqlite3ExprSetHeight(pParse, yygotominor.yy72);
  81806. }else{
  81807. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy243);
  81808. }
  81809. if( yymsp[-3].minor.yy194 ) yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy72, 0, 0);
  81810. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-4].minor.yy72->span,&yymsp[0].minor.yy0);
  81811. }
  81812. break;
  81813. case 230: /* expr ::= expr in_op nm dbnm */
  81814. {
  81815. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  81816. yygotominor.yy72 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy72, 0, 0);
  81817. if( yygotominor.yy72 ){
  81818. yygotominor.yy72->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  81819. ExprSetProperty(yygotominor.yy72, EP_xIsSelect);
  81820. sqlite3ExprSetHeight(pParse, yygotominor.yy72);
  81821. }else{
  81822. sqlite3SrcListDelete(pParse->db, pSrc);
  81823. }
  81824. if( yymsp[-2].minor.yy194 ) yygotominor.yy72 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy72, 0, 0);
  81825. sqlite3ExprSpan(yygotominor.yy72,&yymsp[-3].minor.yy72->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
  81826. }
  81827. break;
  81828. case 231: /* expr ::= EXISTS LP select RP */
  81829. {
  81830. Expr *p = yygotominor.yy72 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  81831. if( p ){
  81832. p->x.pSelect = yymsp[-1].minor.yy243;
  81833. ExprSetProperty(yygotominor.yy72, EP_xIsSelect);
  81834. sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  81835. sqlite3ExprSetHeight(pParse, yygotominor.yy72);
  81836. }else{
  81837. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy243);
  81838. }
  81839. }
  81840. break;
  81841. case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
  81842. {
  81843. yygotominor.yy72 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, yymsp[-1].minor.yy72, 0);
  81844. if( yygotominor.yy72 ){
  81845. yygotominor.yy72->x.pList = yymsp[-2].minor.yy148;
  81846. sqlite3ExprSetHeight(pParse, yygotominor.yy72);
  81847. }else{
  81848. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
  81849. }
  81850. sqlite3ExprSpan(yygotominor.yy72, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
  81851. }
  81852. break;
  81853. case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  81854. {
  81855. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy72, 0);
  81856. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yygotominor.yy148, yymsp[0].minor.yy72, 0);
  81857. }
  81858. break;
  81859. case 234: /* case_exprlist ::= WHEN expr THEN expr */
  81860. {
  81861. yygotominor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy72, 0);
  81862. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yygotominor.yy148, yymsp[0].minor.yy72, 0);
  81863. }
  81864. break;
  81865. case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
  81866. {
  81867. sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
  81868. sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy148, yymsp[-9].minor.yy194,
  81869. &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy194);
  81870. }
  81871. break;
  81872. case 244: /* uniqueflag ::= UNIQUE */
  81873. case 293: /* raisetype ::= ABORT */
  81874. {yygotominor.yy194 = OE_Abort;}
  81875. break;
  81876. case 245: /* uniqueflag ::= */
  81877. {yygotominor.yy194 = OE_None;}
  81878. break;
  81879. case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
  81880. {
  81881. Expr *p = 0;
  81882. if( yymsp[-1].minor.yy0.n>0 ){
  81883. p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  81884. sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  81885. }
  81886. yygotominor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, p, &yymsp[-2].minor.yy0);
  81887. sqlite3ExprListCheckLength(pParse, yygotominor.yy148, "index");
  81888. if( yygotominor.yy148 ) yygotominor.yy148->a[yygotominor.yy148->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy194;
  81889. }
  81890. break;
  81891. case 249: /* idxlist ::= nm collate sortorder */
  81892. {
  81893. Expr *p = 0;
  81894. if( yymsp[-1].minor.yy0.n>0 ){
  81895. p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  81896. sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  81897. }
  81898. yygotominor.yy148 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
  81899. sqlite3ExprListCheckLength(pParse, yygotominor.yy148, "index");
  81900. if( yygotominor.yy148 ) yygotominor.yy148->a[yygotominor.yy148->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy194;
  81901. }
  81902. break;
  81903. case 250: /* collate ::= */
  81904. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  81905. break;
  81906. case 252: /* cmd ::= DROP INDEX ifexists fullname */
  81907. {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
  81908. break;
  81909. case 253: /* cmd ::= VACUUM */
  81910. case 254: /* cmd ::= VACUUM nm */
  81911. {sqlite3Vacuum(pParse);}
  81912. break;
  81913. case 255: /* cmd ::= PRAGMA nm dbnm */
  81914. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  81915. break;
  81916. case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  81917. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  81918. break;
  81919. case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  81920. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  81921. break;
  81922. case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  81923. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  81924. break;
  81925. case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  81926. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  81927. break;
  81928. case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  81929. {
  81930. Token all;
  81931. all.z = yymsp[-3].minor.yy0.z;
  81932. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  81933. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
  81934. }
  81935. break;
  81936. case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  81937. {
  81938. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
  81939. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  81940. }
  81941. break;
  81942. case 272: /* trigger_time ::= BEFORE */
  81943. case 275: /* trigger_time ::= */
  81944. { yygotominor.yy194 = TK_BEFORE; }
  81945. break;
  81946. case 273: /* trigger_time ::= AFTER */
  81947. { yygotominor.yy194 = TK_AFTER; }
  81948. break;
  81949. case 274: /* trigger_time ::= INSTEAD OF */
  81950. { yygotominor.yy194 = TK_INSTEAD;}
  81951. break;
  81952. case 276: /* trigger_event ::= DELETE|INSERT */
  81953. case 277: /* trigger_event ::= UPDATE */
  81954. {yygotominor.yy332.a = yymsp[0].major; yygotominor.yy332.b = 0;}
  81955. break;
  81956. case 278: /* trigger_event ::= UPDATE OF inscollist */
  81957. {yygotominor.yy332.a = TK_UPDATE; yygotominor.yy332.b = yymsp[0].minor.yy254;}
  81958. break;
  81959. case 281: /* when_clause ::= */
  81960. case 298: /* key_opt ::= */
  81961. { yygotominor.yy72 = 0; }
  81962. break;
  81963. case 282: /* when_clause ::= WHEN expr */
  81964. case 299: /* key_opt ::= KEY expr */
  81965. { yygotominor.yy72 = yymsp[0].minor.yy72; }
  81966. break;
  81967. case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  81968. {
  81969. /*
  81970. if( yymsp[-2].minor.yy145 ){
  81971. yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
  81972. }else{
  81973. yymsp[-2].minor.yy145 = yymsp[-1].minor.yy145;
  81974. }
  81975. */
  81976. assert( yymsp[-2].minor.yy145!=0 );
  81977. yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
  81978. yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
  81979. yygotominor.yy145 = yymsp[-2].minor.yy145;
  81980. }
  81981. break;
  81982. case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
  81983. {
  81984. /* if( yymsp[-1].minor.yy145 ) */
  81985. assert( yymsp[-1].minor.yy145!=0 );
  81986. yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
  81987. yygotominor.yy145 = yymsp[-1].minor.yy145;
  81988. }
  81989. break;
  81990. case 285: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
  81991. { yygotominor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-4].minor.yy194); }
  81992. break;
  81993. case 286: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
  81994. {yygotominor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy254, yymsp[-1].minor.yy148, 0, yymsp[-7].minor.yy194);}
  81995. break;
  81996. case 287: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
  81997. {yygotominor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, 0, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);}
  81998. break;
  81999. case 288: /* trigger_cmd ::= DELETE FROM nm where_opt */
  82000. {yygotominor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy72);}
  82001. break;
  82002. case 289: /* trigger_cmd ::= select */
  82003. {yygotominor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); }
  82004. break;
  82005. case 290: /* expr ::= RAISE LP IGNORE RP */
  82006. {
  82007. yygotominor.yy72 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  82008. if( yygotominor.yy72 ){
  82009. yygotominor.yy72->affinity = OE_Ignore;
  82010. sqlite3ExprSpan(yygotominor.yy72, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
  82011. }
  82012. }
  82013. break;
  82014. case 291: /* expr ::= RAISE LP raisetype COMMA nm RP */
  82015. {
  82016. yygotominor.yy72 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  82017. if( yygotominor.yy72 ) {
  82018. yygotominor.yy72->affinity = (char)yymsp[-3].minor.yy194;
  82019. sqlite3ExprSpan(yygotominor.yy72, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  82020. }
  82021. }
  82022. break;
  82023. case 292: /* raisetype ::= ROLLBACK */
  82024. {yygotominor.yy194 = OE_Rollback;}
  82025. break;
  82026. case 294: /* raisetype ::= FAIL */
  82027. {yygotominor.yy194 = OE_Fail;}
  82028. break;
  82029. case 295: /* cmd ::= DROP TRIGGER ifexists fullname */
  82030. {
  82031. sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
  82032. }
  82033. break;
  82034. case 296: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  82035. {
  82036. sqlite3Attach(pParse, yymsp[-3].minor.yy72, yymsp[-1].minor.yy72, yymsp[0].minor.yy72);
  82037. }
  82038. break;
  82039. case 297: /* cmd ::= DETACH database_kw_opt expr */
  82040. {
  82041. sqlite3Detach(pParse, yymsp[0].minor.yy72);
  82042. }
  82043. break;
  82044. case 302: /* cmd ::= REINDEX */
  82045. {sqlite3Reindex(pParse, 0, 0);}
  82046. break;
  82047. case 303: /* cmd ::= REINDEX nm dbnm */
  82048. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  82049. break;
  82050. case 304: /* cmd ::= ANALYZE */
  82051. {sqlite3Analyze(pParse, 0, 0);}
  82052. break;
  82053. case 305: /* cmd ::= ANALYZE nm dbnm */
  82054. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  82055. break;
  82056. case 306: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  82057. {
  82058. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
  82059. }
  82060. break;
  82061. case 307: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  82062. {
  82063. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  82064. }
  82065. break;
  82066. case 308: /* add_column_fullname ::= fullname */
  82067. {
  82068. pParse->db->lookaside.bEnabled = 0;
  82069. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
  82070. }
  82071. break;
  82072. case 311: /* cmd ::= create_vtab */
  82073. {sqlite3VtabFinishParse(pParse,0);}
  82074. break;
  82075. case 312: /* cmd ::= create_vtab LP vtabarglist RP */
  82076. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  82077. break;
  82078. case 313: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
  82079. {
  82080. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  82081. }
  82082. break;
  82083. case 316: /* vtabarg ::= */
  82084. {sqlite3VtabArgInit(pParse);}
  82085. break;
  82086. case 318: /* vtabargtoken ::= ANY */
  82087. case 319: /* vtabargtoken ::= lp anylist RP */
  82088. case 320: /* lp ::= LP */
  82089. case 322: /* anylist ::= anylist ANY */
  82090. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  82091. break;
  82092. };
  82093. yygoto = yyRuleInfo[yyruleno].lhs;
  82094. yysize = yyRuleInfo[yyruleno].nrhs;
  82095. yypParser->yyidx -= yysize;
  82096. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  82097. if( yyact < YYNSTATE ){
  82098. #ifdef NDEBUG
  82099. /* If we are not debugging and the reduce action popped at least
  82100. ** one element off the stack, then we can push the new element back
  82101. ** onto the stack here, and skip the stack overflow test in yy_shift().
  82102. ** That gives a significant speed improvement. */
  82103. if( yysize ){
  82104. yypParser->yyidx++;
  82105. yymsp -= yysize-1;
  82106. yymsp->stateno = (YYACTIONTYPE)yyact;
  82107. yymsp->major = (YYCODETYPE)yygoto;
  82108. yymsp->minor = yygotominor;
  82109. }else
  82110. #endif
  82111. {
  82112. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  82113. }
  82114. }else{
  82115. assert( yyact == YYNSTATE + YYNRULE + 1 );
  82116. yy_accept(yypParser);
  82117. }
  82118. }
  82119. /*
  82120. ** The following code executes when the parse fails
  82121. */
  82122. static void yy_parse_failed(
  82123. yyParser *yypParser /* The parser */
  82124. ){
  82125. sqlite3ParserARG_FETCH;
  82126. #ifndef NDEBUG
  82127. if( yyTraceFILE ){
  82128. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  82129. }
  82130. #endif
  82131. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  82132. /* Here code is inserted which will be executed whenever the
  82133. ** parser fails */
  82134. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  82135. }
  82136. /*
  82137. ** The following code executes when a syntax error first occurs.
  82138. */
  82139. static void yy_syntax_error(
  82140. yyParser *yypParser, /* The parser */
  82141. int yymajor, /* The major type of the error token */
  82142. YYMINORTYPE yyminor /* The minor type of the error token */
  82143. ){
  82144. sqlite3ParserARG_FETCH;
  82145. #define TOKEN (yyminor.yy0)
  82146. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  82147. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  82148. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  82149. pParse->parseError = 1;
  82150. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  82151. }
  82152. /*
  82153. ** The following is executed when the parser accepts
  82154. */
  82155. static void yy_accept(
  82156. yyParser *yypParser /* The parser */
  82157. ){
  82158. sqlite3ParserARG_FETCH;
  82159. #ifndef NDEBUG
  82160. if( yyTraceFILE ){
  82161. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  82162. }
  82163. #endif
  82164. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  82165. /* Here code is inserted which will be executed whenever the
  82166. ** parser accepts */
  82167. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  82168. }
  82169. /* The main parser program.
  82170. ** The first argument is a pointer to a structure obtained from
  82171. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  82172. ** The second argument is the major token number. The third is
  82173. ** the minor token. The fourth optional argument is whatever the
  82174. ** user wants (and specified in the grammar) and is available for
  82175. ** use by the action routines.
  82176. **
  82177. ** Inputs:
  82178. ** <ul>
  82179. ** <li> A pointer to the parser (an opaque structure.)
  82180. ** <li> The major token number.
  82181. ** <li> The minor token number.
  82182. ** <li> An option argument of a grammar-specified type.
  82183. ** </ul>
  82184. **
  82185. ** Outputs:
  82186. ** None.
  82187. */
  82188. SQLITE_PRIVATE void sqlite3Parser(
  82189. void *yyp, /* The parser */
  82190. int yymajor, /* The major token code number */
  82191. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  82192. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  82193. ){
  82194. YYMINORTYPE yyminorunion;
  82195. int yyact; /* The parser action. */
  82196. int yyendofinput; /* True if we are at the end of input */
  82197. #ifdef YYERRORSYMBOL
  82198. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  82199. #endif
  82200. yyParser *yypParser; /* The parser */
  82201. /* (re)initialize the parser, if necessary */
  82202. yypParser = (yyParser*)yyp;
  82203. if( yypParser->yyidx<0 ){
  82204. #if YYSTACKDEPTH<=0
  82205. if( yypParser->yystksz <=0 ){
  82206. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  82207. yyminorunion = yyzerominor;
  82208. yyStackOverflow(yypParser, &yyminorunion);
  82209. return;
  82210. }
  82211. #endif
  82212. yypParser->yyidx = 0;
  82213. yypParser->yyerrcnt = -1;
  82214. yypParser->yystack[0].stateno = 0;
  82215. yypParser->yystack[0].major = 0;
  82216. }
  82217. yyminorunion.yy0 = yyminor;
  82218. yyendofinput = (yymajor==0);
  82219. sqlite3ParserARG_STORE;
  82220. #ifndef NDEBUG
  82221. if( yyTraceFILE ){
  82222. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  82223. }
  82224. #endif
  82225. do{
  82226. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  82227. if( yyact<YYNSTATE ){
  82228. assert( !yyendofinput ); /* Impossible to shift the $ token */
  82229. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  82230. yypParser->yyerrcnt--;
  82231. yymajor = YYNOCODE;
  82232. }else if( yyact < YYNSTATE + YYNRULE ){
  82233. yy_reduce(yypParser,yyact-YYNSTATE);
  82234. }else{
  82235. assert( yyact == YY_ERROR_ACTION );
  82236. #ifdef YYERRORSYMBOL
  82237. int yymx;
  82238. #endif
  82239. #ifndef NDEBUG
  82240. if( yyTraceFILE ){
  82241. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  82242. }
  82243. #endif
  82244. #ifdef YYERRORSYMBOL
  82245. /* A syntax error has occurred.
  82246. ** The response to an error depends upon whether or not the
  82247. ** grammar defines an error token "ERROR".
  82248. **
  82249. ** This is what we do if the grammar does define ERROR:
  82250. **
  82251. ** * Call the %syntax_error function.
  82252. **
  82253. ** * Begin popping the stack until we enter a state where
  82254. ** it is legal to shift the error symbol, then shift
  82255. ** the error symbol.
  82256. **
  82257. ** * Set the error count to three.
  82258. **
  82259. ** * Begin accepting and shifting new tokens. No new error
  82260. ** processing will occur until three tokens have been
  82261. ** shifted successfully.
  82262. **
  82263. */
  82264. if( yypParser->yyerrcnt<0 ){
  82265. yy_syntax_error(yypParser,yymajor,yyminorunion);
  82266. }
  82267. yymx = yypParser->yystack[yypParser->yyidx].major;
  82268. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  82269. #ifndef NDEBUG
  82270. if( yyTraceFILE ){
  82271. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  82272. yyTracePrompt,yyTokenName[yymajor]);
  82273. }
  82274. #endif
  82275. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  82276. yymajor = YYNOCODE;
  82277. }else{
  82278. while(
  82279. yypParser->yyidx >= 0 &&
  82280. yymx != YYERRORSYMBOL &&
  82281. (yyact = yy_find_reduce_action(
  82282. yypParser->yystack[yypParser->yyidx].stateno,
  82283. YYERRORSYMBOL)) >= YYNSTATE
  82284. ){
  82285. yy_pop_parser_stack(yypParser);
  82286. }
  82287. if( yypParser->yyidx < 0 || yymajor==0 ){
  82288. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  82289. yy_parse_failed(yypParser);
  82290. yymajor = YYNOCODE;
  82291. }else if( yymx!=YYERRORSYMBOL ){
  82292. YYMINORTYPE u2;
  82293. u2.YYERRSYMDT = 0;
  82294. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  82295. }
  82296. }
  82297. yypParser->yyerrcnt = 3;
  82298. yyerrorhit = 1;
  82299. #else /* YYERRORSYMBOL is not defined */
  82300. /* This is what we do if the grammar does not define ERROR:
  82301. **
  82302. ** * Report an error message, and throw away the input token.
  82303. **
  82304. ** * If the input token is $, then fail the parse.
  82305. **
  82306. ** As before, subsequent error messages are suppressed until
  82307. ** three input tokens have been successfully shifted.
  82308. */
  82309. if( yypParser->yyerrcnt<=0 ){
  82310. yy_syntax_error(yypParser,yymajor,yyminorunion);
  82311. }
  82312. yypParser->yyerrcnt = 3;
  82313. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  82314. if( yyendofinput ){
  82315. yy_parse_failed(yypParser);
  82316. }
  82317. yymajor = YYNOCODE;
  82318. #endif
  82319. }
  82320. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  82321. return;
  82322. }
  82323. /************** End of parse.c ***********************************************/
  82324. /************** Begin file tokenize.c ****************************************/
  82325. /*
  82326. ** 2001 September 15
  82327. **
  82328. ** The author disclaims copyright to this source code. In place of
  82329. ** a legal notice, here is a blessing:
  82330. **
  82331. ** May you do good and not evil.
  82332. ** May you find forgiveness for yourself and forgive others.
  82333. ** May you share freely, never taking more than you give.
  82334. **
  82335. *************************************************************************
  82336. ** An tokenizer for SQL
  82337. **
  82338. ** This file contains C code that splits an SQL input string up into
  82339. ** individual tokens and sends those tokens one-by-one over to the
  82340. ** parser for analysis.
  82341. **
  82342. ** $Id: tokenize.c,v 1.155 2009/03/31 03:41:57 shane Exp $
  82343. */
  82344. /*
  82345. ** The charMap() macro maps alphabetic characters into their
  82346. ** lower-case ASCII equivalent. On ASCII machines, this is just
  82347. ** an upper-to-lower case map. On EBCDIC machines we also need
  82348. ** to adjust the encoding. Only alphabetic characters and underscores
  82349. ** need to be translated.
  82350. */
  82351. #ifdef SQLITE_ASCII
  82352. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  82353. #endif
  82354. #ifdef SQLITE_EBCDIC
  82355. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  82356. const unsigned char ebcdicToAscii[] = {
  82357. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  82358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  82359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  82360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  82361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  82362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  82363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  82364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  82365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  82366. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  82367. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  82368. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  82369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  82370. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  82371. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  82372. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  82373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  82374. };
  82375. #endif
  82376. /*
  82377. ** The sqlite3KeywordCode function looks up an identifier to determine if
  82378. ** it is a keyword. If it is a keyword, the token code of that keyword is
  82379. ** returned. If the input is not a keyword, TK_ID is returned.
  82380. **
  82381. ** The implementation of this routine was generated by a program,
  82382. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  82383. ** The output of the mkkeywordhash.c program is written into a file
  82384. ** named keywordhash.h and then included into this source file by
  82385. ** the #include below.
  82386. */
  82387. /************** Include keywordhash.h in the middle of tokenize.c ************/
  82388. /************** Begin file keywordhash.h *************************************/
  82389. /***** This file contains automatically generated code ******
  82390. **
  82391. ** The code in this file has been automatically generated by
  82392. **
  82393. ** $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.37 2009/02/01 00:00:46 drh Exp $
  82394. **
  82395. ** The code in this file implements a function that determines whether
  82396. ** or not a given identifier is really an SQL keyword. The same thing
  82397. ** might be implemented more directly using a hand-written hash table.
  82398. ** But by using this automatically generated code, the size of the code
  82399. ** is substantially reduced. This is important for embedded applications
  82400. ** on platforms with limited memory.
  82401. */
  82402. /* Hash score: 171 */
  82403. static int keywordCode(const char *z, int n){
  82404. /* zText[] encodes 801 bytes of keywords in 541 bytes */
  82405. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  82406. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  82407. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  82408. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  82409. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  82410. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  82411. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  82412. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  82413. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  82414. /* INITIALLY */
  82415. static const char zText[540] = {
  82416. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  82417. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  82418. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  82419. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  82420. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  82421. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  82422. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  82423. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  82424. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  82425. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  82426. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  82427. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  82428. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  82429. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  82430. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  82431. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  82432. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  82433. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  82434. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  82435. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  82436. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  82437. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  82438. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  82439. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  82440. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  82441. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  82442. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  82443. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  82444. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  82445. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  82446. };
  82447. static const unsigned char aHash[127] = {
  82448. 70, 99, 112, 68, 0, 43, 0, 0, 76, 0, 71, 0, 0,
  82449. 41, 12, 72, 15, 0, 111, 79, 49, 106, 0, 19, 0, 0,
  82450. 116, 0, 114, 109, 0, 22, 87, 0, 9, 0, 0, 64, 65,
  82451. 0, 63, 6, 0, 47, 84, 96, 0, 113, 95, 0, 0, 44,
  82452. 0, 97, 24, 0, 17, 0, 117, 48, 23, 0, 5, 104, 25,
  82453. 90, 0, 0, 119, 100, 55, 118, 52, 7, 50, 0, 85, 0,
  82454. 94, 26, 0, 93, 0, 0, 0, 89, 86, 91, 82, 103, 14,
  82455. 38, 102, 0, 75, 0, 18, 83, 105, 31, 0, 115, 74, 107,
  82456. 57, 45, 78, 0, 0, 88, 39, 0, 110, 0, 35, 0, 0,
  82457. 28, 0, 80, 53, 58, 0, 20, 56, 0, 51,
  82458. };
  82459. static const unsigned char aNext[119] = {
  82460. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  82461. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  82462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  82463. 0, 0, 0, 0, 32, 21, 0, 0, 0, 42, 3, 46, 0,
  82464. 0, 0, 0, 29, 0, 0, 37, 0, 0, 0, 1, 60, 0,
  82465. 0, 61, 0, 40, 0, 0, 0, 0, 0, 0, 0, 59, 0,
  82466. 0, 0, 0, 30, 54, 16, 33, 10, 0, 0, 0, 0, 0,
  82467. 0, 0, 11, 66, 73, 0, 8, 0, 98, 92, 0, 101, 0,
  82468. 81, 0, 69, 0, 0, 108, 27, 36, 67, 77, 0, 34, 62,
  82469. 0, 0,
  82470. };
  82471. static const unsigned char aLen[119] = {
  82472. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  82473. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  82474. 11, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, 4,
  82475. 6, 2, 3, 4, 9, 2, 6, 5, 6, 6, 5, 6, 5,
  82476. 5, 7, 7, 7, 3, 4, 4, 7, 3, 6, 4, 7, 6,
  82477. 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5,
  82478. 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6,
  82479. 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4, 4, 4,
  82480. 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4,
  82481. 9, 3,
  82482. };
  82483. static const unsigned short int aOffset[119] = {
  82484. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  82485. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  82486. 86, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159,
  82487. 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, 203,
  82488. 206, 210, 217, 223, 223, 226, 229, 233, 234, 238, 244, 248, 255,
  82489. 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, 326, 332,
  82490. 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, 387, 393,
  82491. 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, 462, 466,
  82492. 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, 521, 527,
  82493. 531, 536,
  82494. };
  82495. static const unsigned char aCode[119] = {
  82496. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  82497. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  82498. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  82499. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  82500. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  82501. TK_EXCEPT, TK_TRANSACTION,TK_ON, TK_JOIN_KW, TK_ALTER,
  82502. TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, TK_INTERSECT,
  82503. TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, TK_OFFSET,
  82504. TK_OF, TK_SET, TK_TEMP, TK_TEMP, TK_OR,
  82505. TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING, TK_GROUP,
  82506. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE, TK_BETWEEN,
  82507. TK_NOTNULL, TK_NOT, TK_NULL, TK_LIKE_KW, TK_CASCADE,
  82508. TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE,
  82509. TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT,
  82510. TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT,
  82511. TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_WHERE,
  82512. TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT,
  82513. TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW,
  82514. TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW,
  82515. TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP,
  82516. TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY,
  82517. TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW,
  82518. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  82519. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  82520. };
  82521. int h, i;
  82522. if( n<2 ) return TK_ID;
  82523. h = ((charMap(z[0])*4) ^
  82524. (charMap(z[n-1])*3) ^
  82525. n) % 127;
  82526. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  82527. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  82528. testcase( i==0 ); /* TK_REINDEX */
  82529. testcase( i==1 ); /* TK_INDEXED */
  82530. testcase( i==2 ); /* TK_INDEX */
  82531. testcase( i==3 ); /* TK_DESC */
  82532. testcase( i==4 ); /* TK_ESCAPE */
  82533. testcase( i==5 ); /* TK_EACH */
  82534. testcase( i==6 ); /* TK_CHECK */
  82535. testcase( i==7 ); /* TK_KEY */
  82536. testcase( i==8 ); /* TK_BEFORE */
  82537. testcase( i==9 ); /* TK_FOREIGN */
  82538. testcase( i==10 ); /* TK_FOR */
  82539. testcase( i==11 ); /* TK_IGNORE */
  82540. testcase( i==12 ); /* TK_LIKE_KW */
  82541. testcase( i==13 ); /* TK_EXPLAIN */
  82542. testcase( i==14 ); /* TK_INSTEAD */
  82543. testcase( i==15 ); /* TK_ADD */
  82544. testcase( i==16 ); /* TK_DATABASE */
  82545. testcase( i==17 ); /* TK_AS */
  82546. testcase( i==18 ); /* TK_SELECT */
  82547. testcase( i==19 ); /* TK_TABLE */
  82548. testcase( i==20 ); /* TK_JOIN_KW */
  82549. testcase( i==21 ); /* TK_THEN */
  82550. testcase( i==22 ); /* TK_END */
  82551. testcase( i==23 ); /* TK_DEFERRABLE */
  82552. testcase( i==24 ); /* TK_ELSE */
  82553. testcase( i==25 ); /* TK_EXCEPT */
  82554. testcase( i==26 ); /* TK_TRANSACTION */
  82555. testcase( i==27 ); /* TK_ON */
  82556. testcase( i==28 ); /* TK_JOIN_KW */
  82557. testcase( i==29 ); /* TK_ALTER */
  82558. testcase( i==30 ); /* TK_RAISE */
  82559. testcase( i==31 ); /* TK_EXCLUSIVE */
  82560. testcase( i==32 ); /* TK_EXISTS */
  82561. testcase( i==33 ); /* TK_SAVEPOINT */
  82562. testcase( i==34 ); /* TK_INTERSECT */
  82563. testcase( i==35 ); /* TK_TRIGGER */
  82564. testcase( i==36 ); /* TK_REFERENCES */
  82565. testcase( i==37 ); /* TK_CONSTRAINT */
  82566. testcase( i==38 ); /* TK_INTO */
  82567. testcase( i==39 ); /* TK_OFFSET */
  82568. testcase( i==40 ); /* TK_OF */
  82569. testcase( i==41 ); /* TK_SET */
  82570. testcase( i==42 ); /* TK_TEMP */
  82571. testcase( i==43 ); /* TK_TEMP */
  82572. testcase( i==44 ); /* TK_OR */
  82573. testcase( i==45 ); /* TK_UNIQUE */
  82574. testcase( i==46 ); /* TK_QUERY */
  82575. testcase( i==47 ); /* TK_ATTACH */
  82576. testcase( i==48 ); /* TK_HAVING */
  82577. testcase( i==49 ); /* TK_GROUP */
  82578. testcase( i==50 ); /* TK_UPDATE */
  82579. testcase( i==51 ); /* TK_BEGIN */
  82580. testcase( i==52 ); /* TK_JOIN_KW */
  82581. testcase( i==53 ); /* TK_RELEASE */
  82582. testcase( i==54 ); /* TK_BETWEEN */
  82583. testcase( i==55 ); /* TK_NOTNULL */
  82584. testcase( i==56 ); /* TK_NOT */
  82585. testcase( i==57 ); /* TK_NULL */
  82586. testcase( i==58 ); /* TK_LIKE_KW */
  82587. testcase( i==59 ); /* TK_CASCADE */
  82588. testcase( i==60 ); /* TK_ASC */
  82589. testcase( i==61 ); /* TK_DELETE */
  82590. testcase( i==62 ); /* TK_CASE */
  82591. testcase( i==63 ); /* TK_COLLATE */
  82592. testcase( i==64 ); /* TK_CREATE */
  82593. testcase( i==65 ); /* TK_CTIME_KW */
  82594. testcase( i==66 ); /* TK_DETACH */
  82595. testcase( i==67 ); /* TK_IMMEDIATE */
  82596. testcase( i==68 ); /* TK_JOIN */
  82597. testcase( i==69 ); /* TK_INSERT */
  82598. testcase( i==70 ); /* TK_MATCH */
  82599. testcase( i==71 ); /* TK_PLAN */
  82600. testcase( i==72 ); /* TK_ANALYZE */
  82601. testcase( i==73 ); /* TK_PRAGMA */
  82602. testcase( i==74 ); /* TK_ABORT */
  82603. testcase( i==75 ); /* TK_VALUES */
  82604. testcase( i==76 ); /* TK_VIRTUAL */
  82605. testcase( i==77 ); /* TK_LIMIT */
  82606. testcase( i==78 ); /* TK_WHEN */
  82607. testcase( i==79 ); /* TK_WHERE */
  82608. testcase( i==80 ); /* TK_RENAME */
  82609. testcase( i==81 ); /* TK_AFTER */
  82610. testcase( i==82 ); /* TK_REPLACE */
  82611. testcase( i==83 ); /* TK_AND */
  82612. testcase( i==84 ); /* TK_DEFAULT */
  82613. testcase( i==85 ); /* TK_AUTOINCR */
  82614. testcase( i==86 ); /* TK_TO */
  82615. testcase( i==87 ); /* TK_IN */
  82616. testcase( i==88 ); /* TK_CAST */
  82617. testcase( i==89 ); /* TK_COLUMNKW */
  82618. testcase( i==90 ); /* TK_COMMIT */
  82619. testcase( i==91 ); /* TK_CONFLICT */
  82620. testcase( i==92 ); /* TK_JOIN_KW */
  82621. testcase( i==93 ); /* TK_CTIME_KW */
  82622. testcase( i==94 ); /* TK_CTIME_KW */
  82623. testcase( i==95 ); /* TK_PRIMARY */
  82624. testcase( i==96 ); /* TK_DEFERRED */
  82625. testcase( i==97 ); /* TK_DISTINCT */
  82626. testcase( i==98 ); /* TK_IS */
  82627. testcase( i==99 ); /* TK_DROP */
  82628. testcase( i==100 ); /* TK_FAIL */
  82629. testcase( i==101 ); /* TK_FROM */
  82630. testcase( i==102 ); /* TK_JOIN_KW */
  82631. testcase( i==103 ); /* TK_LIKE_KW */
  82632. testcase( i==104 ); /* TK_BY */
  82633. testcase( i==105 ); /* TK_IF */
  82634. testcase( i==106 ); /* TK_ISNULL */
  82635. testcase( i==107 ); /* TK_ORDER */
  82636. testcase( i==108 ); /* TK_RESTRICT */
  82637. testcase( i==109 ); /* TK_JOIN_KW */
  82638. testcase( i==110 ); /* TK_JOIN_KW */
  82639. testcase( i==111 ); /* TK_ROLLBACK */
  82640. testcase( i==112 ); /* TK_ROW */
  82641. testcase( i==113 ); /* TK_UNION */
  82642. testcase( i==114 ); /* TK_USING */
  82643. testcase( i==115 ); /* TK_VACUUM */
  82644. testcase( i==116 ); /* TK_VIEW */
  82645. testcase( i==117 ); /* TK_INITIALLY */
  82646. testcase( i==118 ); /* TK_ALL */
  82647. return aCode[i];
  82648. }
  82649. }
  82650. return TK_ID;
  82651. }
  82652. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  82653. return keywordCode((char*)z, n);
  82654. }
  82655. /************** End of keywordhash.h *****************************************/
  82656. /************** Continuing where we left off in tokenize.c *******************/
  82657. /*
  82658. ** If X is a character that can be used in an identifier then
  82659. ** IdChar(X) will be true. Otherwise it is false.
  82660. **
  82661. ** For ASCII, any character with the high-order bit set is
  82662. ** allowed in an identifier. For 7-bit characters,
  82663. ** sqlite3IsIdChar[X] must be 1.
  82664. **
  82665. ** For EBCDIC, the rules are more complex but have the same
  82666. ** end result.
  82667. **
  82668. ** Ticket #1066. the SQL standard does not allow '$' in the
  82669. ** middle of identfiers. But many SQL implementations do.
  82670. ** SQLite will allow '$' in identifiers for compatibility.
  82671. ** But the feature is undocumented.
  82672. */
  82673. #ifdef SQLITE_ASCII
  82674. SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
  82675. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  82676. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  82677. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  82678. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  82679. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  82680. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  82681. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  82682. };
  82683. #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
  82684. #endif
  82685. #ifdef SQLITE_EBCDIC
  82686. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  82687. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  82688. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  82689. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  82690. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  82691. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  82692. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  82693. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  82694. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  82695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  82696. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  82697. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  82698. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  82699. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  82700. };
  82701. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  82702. #endif
  82703. /*
  82704. ** Return the length of the token that begins at z[0].
  82705. ** Store the token type in *tokenType before returning.
  82706. */
  82707. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  82708. int i, c;
  82709. switch( *z ){
  82710. case ' ': case '\t': case '\n': case '\f': case '\r': {
  82711. for(i=1; sqlite3Isspace(z[i]); i++){}
  82712. *tokenType = TK_SPACE;
  82713. return i;
  82714. }
  82715. case '-': {
  82716. if( z[1]=='-' ){
  82717. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  82718. *tokenType = TK_SPACE;
  82719. return i;
  82720. }
  82721. *tokenType = TK_MINUS;
  82722. return 1;
  82723. }
  82724. case '(': {
  82725. *tokenType = TK_LP;
  82726. return 1;
  82727. }
  82728. case ')': {
  82729. *tokenType = TK_RP;
  82730. return 1;
  82731. }
  82732. case ';': {
  82733. *tokenType = TK_SEMI;
  82734. return 1;
  82735. }
  82736. case '+': {
  82737. *tokenType = TK_PLUS;
  82738. return 1;
  82739. }
  82740. case '*': {
  82741. *tokenType = TK_STAR;
  82742. return 1;
  82743. }
  82744. case '/': {
  82745. if( z[1]!='*' || z[2]==0 ){
  82746. *tokenType = TK_SLASH;
  82747. return 1;
  82748. }
  82749. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  82750. if( c ) i++;
  82751. *tokenType = TK_SPACE;
  82752. return i;
  82753. }
  82754. case '%': {
  82755. *tokenType = TK_REM;
  82756. return 1;
  82757. }
  82758. case '=': {
  82759. *tokenType = TK_EQ;
  82760. return 1 + (z[1]=='=');
  82761. }
  82762. case '<': {
  82763. if( (c=z[1])=='=' ){
  82764. *tokenType = TK_LE;
  82765. return 2;
  82766. }else if( c=='>' ){
  82767. *tokenType = TK_NE;
  82768. return 2;
  82769. }else if( c=='<' ){
  82770. *tokenType = TK_LSHIFT;
  82771. return 2;
  82772. }else{
  82773. *tokenType = TK_LT;
  82774. return 1;
  82775. }
  82776. }
  82777. case '>': {
  82778. if( (c=z[1])=='=' ){
  82779. *tokenType = TK_GE;
  82780. return 2;
  82781. }else if( c=='>' ){
  82782. *tokenType = TK_RSHIFT;
  82783. return 2;
  82784. }else{
  82785. *tokenType = TK_GT;
  82786. return 1;
  82787. }
  82788. }
  82789. case '!': {
  82790. if( z[1]!='=' ){
  82791. *tokenType = TK_ILLEGAL;
  82792. return 2;
  82793. }else{
  82794. *tokenType = TK_NE;
  82795. return 2;
  82796. }
  82797. }
  82798. case '|': {
  82799. if( z[1]!='|' ){
  82800. *tokenType = TK_BITOR;
  82801. return 1;
  82802. }else{
  82803. *tokenType = TK_CONCAT;
  82804. return 2;
  82805. }
  82806. }
  82807. case ',': {
  82808. *tokenType = TK_COMMA;
  82809. return 1;
  82810. }
  82811. case '&': {
  82812. *tokenType = TK_BITAND;
  82813. return 1;
  82814. }
  82815. case '~': {
  82816. *tokenType = TK_BITNOT;
  82817. return 1;
  82818. }
  82819. case '`':
  82820. case '\'':
  82821. case '"': {
  82822. int delim = z[0];
  82823. for(i=1; (c=z[i])!=0; i++){
  82824. if( c==delim ){
  82825. if( z[i+1]==delim ){
  82826. i++;
  82827. }else{
  82828. break;
  82829. }
  82830. }
  82831. }
  82832. if( c=='\'' ){
  82833. *tokenType = TK_STRING;
  82834. return i+1;
  82835. }else if( c!=0 ){
  82836. *tokenType = TK_ID;
  82837. return i+1;
  82838. }else{
  82839. *tokenType = TK_ILLEGAL;
  82840. return i;
  82841. }
  82842. }
  82843. case '.': {
  82844. #ifndef SQLITE_OMIT_FLOATING_POINT
  82845. if( !sqlite3Isdigit(z[1]) )
  82846. #endif
  82847. {
  82848. *tokenType = TK_DOT;
  82849. return 1;
  82850. }
  82851. /* If the next character is a digit, this is a floating point
  82852. ** number that begins with ".". Fall thru into the next case */
  82853. }
  82854. case '0': case '1': case '2': case '3': case '4':
  82855. case '5': case '6': case '7': case '8': case '9': {
  82856. *tokenType = TK_INTEGER;
  82857. for(i=0; sqlite3Isdigit(z[i]); i++){}
  82858. #ifndef SQLITE_OMIT_FLOATING_POINT
  82859. if( z[i]=='.' ){
  82860. i++;
  82861. while( sqlite3Isdigit(z[i]) ){ i++; }
  82862. *tokenType = TK_FLOAT;
  82863. }
  82864. if( (z[i]=='e' || z[i]=='E') &&
  82865. ( sqlite3Isdigit(z[i+1])
  82866. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  82867. )
  82868. ){
  82869. i += 2;
  82870. while( sqlite3Isdigit(z[i]) ){ i++; }
  82871. *tokenType = TK_FLOAT;
  82872. }
  82873. #endif
  82874. while( IdChar(z[i]) ){
  82875. *tokenType = TK_ILLEGAL;
  82876. i++;
  82877. }
  82878. return i;
  82879. }
  82880. case '[': {
  82881. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  82882. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  82883. return i;
  82884. }
  82885. case '?': {
  82886. *tokenType = TK_VARIABLE;
  82887. for(i=1; sqlite3Isdigit(z[i]); i++){}
  82888. return i;
  82889. }
  82890. case '#': {
  82891. for(i=1; sqlite3Isdigit(z[i]); i++){}
  82892. if( i>1 ){
  82893. /* Parameters of the form #NNN (where NNN is a number) are used
  82894. ** internally by sqlite3NestedParse. */
  82895. *tokenType = TK_REGISTER;
  82896. return i;
  82897. }
  82898. /* Fall through into the next case if the '#' is not followed by
  82899. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  82900. }
  82901. #ifndef SQLITE_OMIT_TCL_VARIABLE
  82902. case '$':
  82903. #endif
  82904. case '@': /* For compatibility with MS SQL Server */
  82905. case ':': {
  82906. int n = 0;
  82907. *tokenType = TK_VARIABLE;
  82908. for(i=1; (c=z[i])!=0; i++){
  82909. if( IdChar(c) ){
  82910. n++;
  82911. #ifndef SQLITE_OMIT_TCL_VARIABLE
  82912. }else if( c=='(' && n>0 ){
  82913. do{
  82914. i++;
  82915. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  82916. if( c==')' ){
  82917. i++;
  82918. }else{
  82919. *tokenType = TK_ILLEGAL;
  82920. }
  82921. break;
  82922. }else if( c==':' && z[i+1]==':' ){
  82923. i++;
  82924. #endif
  82925. }else{
  82926. break;
  82927. }
  82928. }
  82929. if( n==0 ) *tokenType = TK_ILLEGAL;
  82930. return i;
  82931. }
  82932. #ifndef SQLITE_OMIT_BLOB_LITERAL
  82933. case 'x': case 'X': {
  82934. if( z[1]=='\'' ){
  82935. *tokenType = TK_BLOB;
  82936. for(i=2; (c=z[i])!=0 && c!='\''; i++){
  82937. if( !sqlite3Isxdigit(c) ){
  82938. *tokenType = TK_ILLEGAL;
  82939. }
  82940. }
  82941. if( i%2 || !c ) *tokenType = TK_ILLEGAL;
  82942. if( c ) i++;
  82943. return i;
  82944. }
  82945. /* Otherwise fall through to the next case */
  82946. }
  82947. #endif
  82948. default: {
  82949. if( !IdChar(*z) ){
  82950. break;
  82951. }
  82952. for(i=1; IdChar(z[i]); i++){}
  82953. *tokenType = keywordCode((char*)z, i);
  82954. return i;
  82955. }
  82956. }
  82957. *tokenType = TK_ILLEGAL;
  82958. return 1;
  82959. }
  82960. /*
  82961. ** Run the parser on the given SQL string. The parser structure is
  82962. ** passed in. An SQLITE_ status code is returned. If an error occurs
  82963. ** then an and attempt is made to write an error message into
  82964. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  82965. ** error message.
  82966. */
  82967. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  82968. int nErr = 0; /* Number of errors encountered */
  82969. int i; /* Loop counter */
  82970. void *pEngine; /* The LEMON-generated LALR(1) parser */
  82971. int tokenType; /* type of the next token */
  82972. int lastTokenParsed = -1; /* type of the previous token */
  82973. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  82974. sqlite3 *db = pParse->db; /* The database connection */
  82975. int mxSqlLen; /* Max length of an SQL string */
  82976. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  82977. if( db->activeVdbeCnt==0 ){
  82978. db->u1.isInterrupted = 0;
  82979. }
  82980. pParse->rc = SQLITE_OK;
  82981. pParse->zTail = pParse->zSql = zSql;
  82982. i = 0;
  82983. assert( pzErrMsg!=0 );
  82984. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  82985. if( pEngine==0 ){
  82986. db->mallocFailed = 1;
  82987. return SQLITE_NOMEM;
  82988. }
  82989. assert( pParse->sLastToken.dyn==0 );
  82990. assert( pParse->pNewTable==0 );
  82991. assert( pParse->pNewTrigger==0 );
  82992. assert( pParse->nVar==0 );
  82993. assert( pParse->nVarExpr==0 );
  82994. assert( pParse->nVarExprAlloc==0 );
  82995. assert( pParse->apVarExpr==0 );
  82996. enableLookaside = db->lookaside.bEnabled;
  82997. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  82998. while( !db->mallocFailed && zSql[i]!=0 ){
  82999. assert( i>=0 );
  83000. pParse->sLastToken.z = (u8*)&zSql[i];
  83001. assert( pParse->sLastToken.dyn==0 );
  83002. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  83003. i += pParse->sLastToken.n;
  83004. if( i>mxSqlLen ){
  83005. pParse->rc = SQLITE_TOOBIG;
  83006. break;
  83007. }
  83008. switch( tokenType ){
  83009. case TK_SPACE: {
  83010. if( db->u1.isInterrupted ){
  83011. pParse->rc = SQLITE_INTERRUPT;
  83012. sqlite3SetString(pzErrMsg, db, "interrupt");
  83013. goto abort_parse;
  83014. }
  83015. break;
  83016. }
  83017. case TK_ILLEGAL: {
  83018. sqlite3DbFree(db, *pzErrMsg);
  83019. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  83020. &pParse->sLastToken);
  83021. nErr++;
  83022. goto abort_parse;
  83023. }
  83024. case TK_SEMI: {
  83025. pParse->zTail = &zSql[i];
  83026. /* Fall thru into the default case */
  83027. }
  83028. default: {
  83029. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  83030. lastTokenParsed = tokenType;
  83031. if( pParse->rc!=SQLITE_OK ){
  83032. goto abort_parse;
  83033. }
  83034. break;
  83035. }
  83036. }
  83037. }
  83038. abort_parse:
  83039. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  83040. if( lastTokenParsed!=TK_SEMI ){
  83041. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  83042. pParse->zTail = &zSql[i];
  83043. }
  83044. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  83045. }
  83046. #ifdef YYTRACKMAXSTACKDEPTH
  83047. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  83048. sqlite3ParserStackPeak(pEngine)
  83049. );
  83050. #endif /* YYDEBUG */
  83051. sqlite3ParserFree(pEngine, sqlite3_free);
  83052. db->lookaside.bEnabled = enableLookaside;
  83053. if( db->mallocFailed ){
  83054. pParse->rc = SQLITE_NOMEM;
  83055. }
  83056. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  83057. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  83058. }
  83059. if( pParse->zErrMsg ){
  83060. if( *pzErrMsg==0 ){
  83061. *pzErrMsg = pParse->zErrMsg;
  83062. }else{
  83063. sqlite3DbFree(db, pParse->zErrMsg);
  83064. }
  83065. pParse->zErrMsg = 0;
  83066. nErr++;
  83067. }
  83068. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  83069. sqlite3VdbeDelete(pParse->pVdbe);
  83070. pParse->pVdbe = 0;
  83071. }
  83072. #ifndef SQLITE_OMIT_SHARED_CACHE
  83073. if( pParse->nested==0 ){
  83074. sqlite3DbFree(db, pParse->aTableLock);
  83075. pParse->aTableLock = 0;
  83076. pParse->nTableLock = 0;
  83077. }
  83078. #endif
  83079. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83080. sqlite3DbFree(db, pParse->apVtabLock);
  83081. #endif
  83082. if( !IN_DECLARE_VTAB ){
  83083. /* If the pParse->declareVtab flag is set, do not delete any table
  83084. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  83085. ** will take responsibility for freeing the Table structure.
  83086. */
  83087. sqlite3DeleteTable(pParse->pNewTable);
  83088. }
  83089. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  83090. sqlite3DbFree(db, pParse->apVarExpr);
  83091. sqlite3DbFree(db, pParse->aAlias);
  83092. while( pParse->pZombieTab ){
  83093. Table *p = pParse->pZombieTab;
  83094. pParse->pZombieTab = p->pNextZombie;
  83095. sqlite3DeleteTable(p);
  83096. }
  83097. if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
  83098. pParse->rc = SQLITE_ERROR;
  83099. }
  83100. return nErr;
  83101. }
  83102. /************** End of tokenize.c ********************************************/
  83103. /************** Begin file complete.c ****************************************/
  83104. /*
  83105. ** 2001 September 15
  83106. **
  83107. ** The author disclaims copyright to this source code. In place of
  83108. ** a legal notice, here is a blessing:
  83109. **
  83110. ** May you do good and not evil.
  83111. ** May you find forgiveness for yourself and forgive others.
  83112. ** May you share freely, never taking more than you give.
  83113. **
  83114. *************************************************************************
  83115. ** An tokenizer for SQL
  83116. **
  83117. ** This file contains C code that implements the sqlite3_complete() API.
  83118. ** This code used to be part of the tokenizer.c source file. But by
  83119. ** separating it out, the code will be automatically omitted from
  83120. ** static links that do not use it.
  83121. **
  83122. ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
  83123. */
  83124. #ifndef SQLITE_OMIT_COMPLETE
  83125. /*
  83126. ** This is defined in tokenize.c. We just have to import the definition.
  83127. */
  83128. #ifndef SQLITE_AMALGAMATION
  83129. #ifdef SQLITE_ASCII
  83130. SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
  83131. #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
  83132. #endif
  83133. #ifdef SQLITE_EBCDIC
  83134. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  83135. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  83136. #endif
  83137. #endif /* SQLITE_AMALGAMATION */
  83138. /*
  83139. ** Token types used by the sqlite3_complete() routine. See the header
  83140. ** comments on that procedure for additional information.
  83141. */
  83142. #define tkSEMI 0
  83143. #define tkWS 1
  83144. #define tkOTHER 2
  83145. #define tkEXPLAIN 3
  83146. #define tkCREATE 4
  83147. #define tkTEMP 5
  83148. #define tkTRIGGER 6
  83149. #define tkEND 7
  83150. /*
  83151. ** Return TRUE if the given SQL string ends in a semicolon.
  83152. **
  83153. ** Special handling is require for CREATE TRIGGER statements.
  83154. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  83155. ** must end with ";END;".
  83156. **
  83157. ** This implementation uses a state machine with 7 states:
  83158. **
  83159. ** (0) START At the beginning or end of an SQL statement. This routine
  83160. ** returns 1 if it ends in the START state and 0 if it ends
  83161. ** in any other state.
  83162. **
  83163. ** (1) NORMAL We are in the middle of statement which ends with a single
  83164. ** semicolon.
  83165. **
  83166. ** (2) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  83167. ** a statement.
  83168. **
  83169. ** (3) CREATE The keyword CREATE has been seen at the beginning of a
  83170. ** statement, possibly preceeded by EXPLAIN and/or followed by
  83171. ** TEMP or TEMPORARY
  83172. **
  83173. ** (4) TRIGGER We are in the middle of a trigger definition that must be
  83174. ** ended by a semicolon, the keyword END, and another semicolon.
  83175. **
  83176. ** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at
  83177. ** the end of a trigger definition.
  83178. **
  83179. ** (6) END We've seen the ";END" of the ";END;" that occurs at the end
  83180. ** of a trigger difinition.
  83181. **
  83182. ** Transitions between states above are determined by tokens extracted
  83183. ** from the input. The following tokens are significant:
  83184. **
  83185. ** (0) tkSEMI A semicolon.
  83186. ** (1) tkWS Whitespace
  83187. ** (2) tkOTHER Any other SQL token.
  83188. ** (3) tkEXPLAIN The "explain" keyword.
  83189. ** (4) tkCREATE The "create" keyword.
  83190. ** (5) tkTEMP The "temp" or "temporary" keyword.
  83191. ** (6) tkTRIGGER The "trigger" keyword.
  83192. ** (7) tkEND The "end" keyword.
  83193. **
  83194. ** Whitespace never causes a state transition and is always ignored.
  83195. **
  83196. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  83197. ** to recognize the end of a trigger can be omitted. All we have to do
  83198. ** is look for a semicolon that is not part of an string or comment.
  83199. */
  83200. SQLITE_API int sqlite3_complete(const char *zSql){
  83201. u8 state = 0; /* Current state, using numbers defined in header comment */
  83202. u8 token; /* Value of the next token */
  83203. #ifndef SQLITE_OMIT_TRIGGER
  83204. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  83205. ** statement. This is the normal case.
  83206. */
  83207. static const u8 trans[7][8] = {
  83208. /* Token: */
  83209. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  83210. /* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
  83211. /* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
  83212. /* 2 EXPLAIN: */ { 0, 2, 1, 1, 3, 1, 1, 1, },
  83213. /* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
  83214. /* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
  83215. /* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
  83216. /* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
  83217. };
  83218. #else
  83219. /* If triggers are not suppored by this compile then the statement machine
  83220. ** used to detect the end of a statement is much simplier
  83221. */
  83222. static const u8 trans[2][3] = {
  83223. /* Token: */
  83224. /* State: ** SEMI WS OTHER */
  83225. /* 0 START: */ { 0, 0, 1, },
  83226. /* 1 NORMAL: */ { 0, 1, 1, },
  83227. };
  83228. #endif /* SQLITE_OMIT_TRIGGER */
  83229. while( *zSql ){
  83230. switch( *zSql ){
  83231. case ';': { /* A semicolon */
  83232. token = tkSEMI;
  83233. break;
  83234. }
  83235. case ' ':
  83236. case '\r':
  83237. case '\t':
  83238. case '\n':
  83239. case '\f': { /* White space is ignored */
  83240. token = tkWS;
  83241. break;
  83242. }
  83243. case '/': { /* C-style comments */
  83244. if( zSql[1]!='*' ){
  83245. token = tkOTHER;
  83246. break;
  83247. }
  83248. zSql += 2;
  83249. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  83250. if( zSql[0]==0 ) return 0;
  83251. zSql++;
  83252. token = tkWS;
  83253. break;
  83254. }
  83255. case '-': { /* SQL-style comments from "--" to end of line */
  83256. if( zSql[1]!='-' ){
  83257. token = tkOTHER;
  83258. break;
  83259. }
  83260. while( *zSql && *zSql!='\n' ){ zSql++; }
  83261. if( *zSql==0 ) return state==0;
  83262. token = tkWS;
  83263. break;
  83264. }
  83265. case '[': { /* Microsoft-style identifiers in [...] */
  83266. zSql++;
  83267. while( *zSql && *zSql!=']' ){ zSql++; }
  83268. if( *zSql==0 ) return 0;
  83269. token = tkOTHER;
  83270. break;
  83271. }
  83272. case '`': /* Grave-accent quoted symbols used by MySQL */
  83273. case '"': /* single- and double-quoted strings */
  83274. case '\'': {
  83275. int c = *zSql;
  83276. zSql++;
  83277. while( *zSql && *zSql!=c ){ zSql++; }
  83278. if( *zSql==0 ) return 0;
  83279. token = tkOTHER;
  83280. break;
  83281. }
  83282. default: {
  83283. int c;
  83284. if( IdChar((u8)*zSql) ){
  83285. /* Keywords and unquoted identifiers */
  83286. int nId;
  83287. for(nId=1; IdChar(zSql[nId]); nId++){}
  83288. #ifdef SQLITE_OMIT_TRIGGER
  83289. token = tkOTHER;
  83290. #else
  83291. switch( *zSql ){
  83292. case 'c': case 'C': {
  83293. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  83294. token = tkCREATE;
  83295. }else{
  83296. token = tkOTHER;
  83297. }
  83298. break;
  83299. }
  83300. case 't': case 'T': {
  83301. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  83302. token = tkTRIGGER;
  83303. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  83304. token = tkTEMP;
  83305. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  83306. token = tkTEMP;
  83307. }else{
  83308. token = tkOTHER;
  83309. }
  83310. break;
  83311. }
  83312. case 'e': case 'E': {
  83313. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  83314. token = tkEND;
  83315. }else
  83316. #ifndef SQLITE_OMIT_EXPLAIN
  83317. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  83318. token = tkEXPLAIN;
  83319. }else
  83320. #endif
  83321. {
  83322. token = tkOTHER;
  83323. }
  83324. break;
  83325. }
  83326. default: {
  83327. token = tkOTHER;
  83328. break;
  83329. }
  83330. }
  83331. #endif /* SQLITE_OMIT_TRIGGER */
  83332. zSql += nId-1;
  83333. }else{
  83334. /* Operators and special symbols */
  83335. token = tkOTHER;
  83336. }
  83337. break;
  83338. }
  83339. }
  83340. state = trans[state][token];
  83341. zSql++;
  83342. }
  83343. return state==0;
  83344. }
  83345. #ifndef SQLITE_OMIT_UTF16
  83346. /*
  83347. ** This routine is the same as the sqlite3_complete() routine described
  83348. ** above, except that the parameter is required to be UTF-16 encoded, not
  83349. ** UTF-8.
  83350. */
  83351. SQLITE_API int sqlite3_complete16(const void *zSql){
  83352. sqlite3_value *pVal;
  83353. char const *zSql8;
  83354. int rc = SQLITE_NOMEM;
  83355. #ifndef SQLITE_OMIT_AUTOINIT
  83356. rc = sqlite3_initialize();
  83357. if( rc ) return rc;
  83358. #endif
  83359. pVal = sqlite3ValueNew(0);
  83360. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  83361. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  83362. if( zSql8 ){
  83363. rc = sqlite3_complete(zSql8);
  83364. }else{
  83365. rc = SQLITE_NOMEM;
  83366. }
  83367. sqlite3ValueFree(pVal);
  83368. return sqlite3ApiExit(0, rc);
  83369. }
  83370. #endif /* SQLITE_OMIT_UTF16 */
  83371. #endif /* SQLITE_OMIT_COMPLETE */
  83372. /************** End of complete.c ********************************************/
  83373. /************** Begin file main.c ********************************************/
  83374. /*
  83375. ** 2001 September 15
  83376. **
  83377. ** The author disclaims copyright to this source code. In place of
  83378. ** a legal notice, here is a blessing:
  83379. **
  83380. ** May you do good and not evil.
  83381. ** May you find forgiveness for yourself and forgive others.
  83382. ** May you share freely, never taking more than you give.
  83383. **
  83384. *************************************************************************
  83385. ** Main file for the SQLite library. The routines in this file
  83386. ** implement the programmer interface to the library. Routines in
  83387. ** other files are for internal use by SQLite and should not be
  83388. ** accessed by users of the library.
  83389. **
  83390. ** $Id: main.c,v 1.536 2009/04/09 01:23:49 drh Exp $
  83391. */
  83392. #ifdef SQLITE_ENABLE_FTS3
  83393. /************** Include fts3.h in the middle of main.c ***********************/
  83394. /************** Begin file fts3.h ********************************************/
  83395. /*
  83396. ** 2006 Oct 10
  83397. **
  83398. ** The author disclaims copyright to this source code. In place of
  83399. ** a legal notice, here is a blessing:
  83400. **
  83401. ** May you do good and not evil.
  83402. ** May you find forgiveness for yourself and forgive others.
  83403. ** May you share freely, never taking more than you give.
  83404. **
  83405. ******************************************************************************
  83406. **
  83407. ** This header file is used by programs that want to link against the
  83408. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  83409. */
  83410. #if 0
  83411. extern "C" {
  83412. #endif /* __cplusplus */
  83413. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  83414. #if 0
  83415. } /* extern "C" */
  83416. #endif /* __cplusplus */
  83417. /************** End of fts3.h ************************************************/
  83418. /************** Continuing where we left off in main.c ***********************/
  83419. #endif
  83420. #ifdef SQLITE_ENABLE_RTREE
  83421. /************** Include rtree.h in the middle of main.c **********************/
  83422. /************** Begin file rtree.h *******************************************/
  83423. /*
  83424. ** 2008 May 26
  83425. **
  83426. ** The author disclaims copyright to this source code. In place of
  83427. ** a legal notice, here is a blessing:
  83428. **
  83429. ** May you do good and not evil.
  83430. ** May you find forgiveness for yourself and forgive others.
  83431. ** May you share freely, never taking more than you give.
  83432. **
  83433. ******************************************************************************
  83434. **
  83435. ** This header file is used by programs that want to link against the
  83436. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  83437. */
  83438. #if 0
  83439. extern "C" {
  83440. #endif /* __cplusplus */
  83441. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  83442. #if 0
  83443. } /* extern "C" */
  83444. #endif /* __cplusplus */
  83445. /************** End of rtree.h ***********************************************/
  83446. /************** Continuing where we left off in main.c ***********************/
  83447. #endif
  83448. #ifdef SQLITE_ENABLE_ICU
  83449. /************** Include sqliteicu.h in the middle of main.c ******************/
  83450. /************** Begin file sqliteicu.h ***************************************/
  83451. /*
  83452. ** 2008 May 26
  83453. **
  83454. ** The author disclaims copyright to this source code. In place of
  83455. ** a legal notice, here is a blessing:
  83456. **
  83457. ** May you do good and not evil.
  83458. ** May you find forgiveness for yourself and forgive others.
  83459. ** May you share freely, never taking more than you give.
  83460. **
  83461. ******************************************************************************
  83462. **
  83463. ** This header file is used by programs that want to link against the
  83464. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  83465. */
  83466. #if 0
  83467. extern "C" {
  83468. #endif /* __cplusplus */
  83469. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  83470. #if 0
  83471. } /* extern "C" */
  83472. #endif /* __cplusplus */
  83473. /************** End of sqliteicu.h *******************************************/
  83474. /************** Continuing where we left off in main.c ***********************/
  83475. #endif
  83476. /*
  83477. ** The version of the library
  83478. */
  83479. #ifndef SQLITE_AMALGAMATION
  83480. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  83481. #endif
  83482. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  83483. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  83484. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  83485. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  83486. /*
  83487. ** If the following function pointer is not NULL and if
  83488. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  83489. ** I/O active are written using this function. These messages
  83490. ** are intended for debugging activity only.
  83491. */
  83492. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  83493. #endif
  83494. /*
  83495. ** If the following global variable points to a string which is the
  83496. ** name of a directory, then that directory will be used to store
  83497. ** temporary files.
  83498. **
  83499. ** See also the "PRAGMA temp_store_directory" SQL command.
  83500. */
  83501. SQLITE_API char *sqlite3_temp_directory = 0;
  83502. /*
  83503. ** Initialize SQLite.
  83504. **
  83505. ** This routine must be called to initialize the memory allocation,
  83506. ** VFS, and mutex subsystems prior to doing any serious work with
  83507. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  83508. ** this routine will be called automatically by key routines such as
  83509. ** sqlite3_open().
  83510. **
  83511. ** This routine is a no-op except on its very first call for the process,
  83512. ** or for the first call after a call to sqlite3_shutdown.
  83513. **
  83514. ** The first thread to call this routine runs the initialization to
  83515. ** completion. If subsequent threads call this routine before the first
  83516. ** thread has finished the initialization process, then the subsequent
  83517. ** threads must block until the first thread finishes with the initialization.
  83518. **
  83519. ** The first thread might call this routine recursively. Recursive
  83520. ** calls to this routine should not block, of course. Otherwise the
  83521. ** initialization process would never complete.
  83522. **
  83523. ** Let X be the first thread to enter this routine. Let Y be some other
  83524. ** thread. Then while the initial invocation of this routine by X is
  83525. ** incomplete, it is required that:
  83526. **
  83527. ** * Calls to this routine from Y must block until the outer-most
  83528. ** call by X completes.
  83529. **
  83530. ** * Recursive calls to this routine from thread X return immediately
  83531. ** without blocking.
  83532. */
  83533. SQLITE_API int sqlite3_initialize(void){
  83534. sqlite3_mutex *pMaster; /* The main static mutex */
  83535. int rc; /* Result code */
  83536. #ifdef SQLITE_OMIT_WSD
  83537. rc = sqlite3_wsd_init(4096, 24);
  83538. if( rc!=SQLITE_OK ){
  83539. return rc;
  83540. }
  83541. #endif
  83542. /* If SQLite is already completely initialized, then this call
  83543. ** to sqlite3_initialize() should be a no-op. But the initialization
  83544. ** must be complete. So isInit must not be set until the very end
  83545. ** of this routine.
  83546. */
  83547. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  83548. /* Make sure the mutex subsystem is initialized. If unable to
  83549. ** initialize the mutex subsystem, return early with the error.
  83550. ** If the system is so sick that we are unable to allocate a mutex,
  83551. ** there is not much SQLite is going to be able to do.
  83552. **
  83553. ** The mutex subsystem must take care of serializing its own
  83554. ** initialization.
  83555. */
  83556. rc = sqlite3MutexInit();
  83557. if( rc ) return rc;
  83558. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  83559. ** This operation is protected by the STATIC_MASTER mutex. Note that
  83560. ** MutexAlloc() is called for a static mutex prior to initializing the
  83561. ** malloc subsystem - this implies that the allocation of a static
  83562. ** mutex must not require support from the malloc subsystem.
  83563. */
  83564. pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  83565. sqlite3_mutex_enter(pMaster);
  83566. if( !sqlite3GlobalConfig.isMallocInit ){
  83567. rc = sqlite3MallocInit();
  83568. }
  83569. if( rc==SQLITE_OK ){
  83570. sqlite3GlobalConfig.isMallocInit = 1;
  83571. if( !sqlite3GlobalConfig.pInitMutex ){
  83572. sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  83573. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  83574. rc = SQLITE_NOMEM;
  83575. }
  83576. }
  83577. }
  83578. if( rc==SQLITE_OK ){
  83579. sqlite3GlobalConfig.nRefInitMutex++;
  83580. }
  83581. sqlite3_mutex_leave(pMaster);
  83582. /* If unable to initialize the malloc subsystem, then return early.
  83583. ** There is little hope of getting SQLite to run if the malloc
  83584. ** subsystem cannot be initialized.
  83585. */
  83586. if( rc!=SQLITE_OK ){
  83587. return rc;
  83588. }
  83589. /* Do the rest of the initialization under the recursive mutex so
  83590. ** that we will be able to handle recursive calls into
  83591. ** sqlite3_initialize(). The recursive calls normally come through
  83592. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  83593. ** recursive calls might also be possible.
  83594. */
  83595. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  83596. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  83597. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  83598. sqlite3GlobalConfig.inProgress = 1;
  83599. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  83600. sqlite3RegisterGlobalFunctions();
  83601. rc = sqlite3_os_init();
  83602. if( rc==SQLITE_OK ){
  83603. rc = sqlite3PcacheInitialize();
  83604. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  83605. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  83606. }
  83607. sqlite3GlobalConfig.inProgress = 0;
  83608. sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
  83609. }
  83610. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  83611. /* Go back under the static mutex and clean up the recursive
  83612. ** mutex to prevent a resource leak.
  83613. */
  83614. sqlite3_mutex_enter(pMaster);
  83615. sqlite3GlobalConfig.nRefInitMutex--;
  83616. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  83617. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  83618. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  83619. sqlite3GlobalConfig.pInitMutex = 0;
  83620. }
  83621. sqlite3_mutex_leave(pMaster);
  83622. /* The following is just a sanity check to make sure SQLite has
  83623. ** been compiled correctly. It is important to run this code, but
  83624. ** we don't want to run it too often and soak up CPU cycles for no
  83625. ** reason. So we run it once during initialization.
  83626. */
  83627. #ifndef NDEBUG
  83628. #ifndef SQLITE_OMIT_FLOATING_POINT
  83629. /* This section of code's only "output" is via assert() statements. */
  83630. if ( rc==SQLITE_OK ){
  83631. u64 x = (((u64)1)<<63)-1;
  83632. double y;
  83633. assert(sizeof(x)==8);
  83634. assert(sizeof(x)==sizeof(y));
  83635. memcpy(&y, &x, 8);
  83636. assert( sqlite3IsNaN(y) );
  83637. }
  83638. #endif
  83639. #endif
  83640. return rc;
  83641. }
  83642. /*
  83643. ** Undo the effects of sqlite3_initialize(). Must not be called while
  83644. ** there are outstanding database connections or memory allocations or
  83645. ** while any part of SQLite is otherwise in use in any thread. This
  83646. ** routine is not threadsafe. Not by a long shot.
  83647. */
  83648. SQLITE_API int sqlite3_shutdown(void){
  83649. sqlite3GlobalConfig.isMallocInit = 0;
  83650. sqlite3PcacheShutdown();
  83651. if( sqlite3GlobalConfig.isInit ){
  83652. sqlite3_os_end();
  83653. }
  83654. sqlite3_reset_auto_extension();
  83655. sqlite3MallocEnd();
  83656. sqlite3MutexEnd();
  83657. sqlite3GlobalConfig.isInit = 0;
  83658. return SQLITE_OK;
  83659. }
  83660. /*
  83661. ** This API allows applications to modify the global configuration of
  83662. ** the SQLite library at run-time.
  83663. **
  83664. ** This routine should only be called when there are no outstanding
  83665. ** database connections or memory allocations. This routine is not
  83666. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  83667. ** behavior.
  83668. */
  83669. SQLITE_API int sqlite3_config(int op, ...){
  83670. va_list ap;
  83671. int rc = SQLITE_OK;
  83672. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  83673. ** the SQLite library is in use. */
  83674. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
  83675. va_start(ap, op);
  83676. switch( op ){
  83677. /* Mutex configuration options are only available in a threadsafe
  83678. ** compile.
  83679. */
  83680. #if SQLITE_THREADSAFE
  83681. case SQLITE_CONFIG_SINGLETHREAD: {
  83682. /* Disable all mutexing */
  83683. sqlite3GlobalConfig.bCoreMutex = 0;
  83684. sqlite3GlobalConfig.bFullMutex = 0;
  83685. break;
  83686. }
  83687. case SQLITE_CONFIG_MULTITHREAD: {
  83688. /* Disable mutexing of database connections */
  83689. /* Enable mutexing of core data structures */
  83690. sqlite3GlobalConfig.bCoreMutex = 1;
  83691. sqlite3GlobalConfig.bFullMutex = 0;
  83692. break;
  83693. }
  83694. case SQLITE_CONFIG_SERIALIZED: {
  83695. /* Enable all mutexing */
  83696. sqlite3GlobalConfig.bCoreMutex = 1;
  83697. sqlite3GlobalConfig.bFullMutex = 1;
  83698. break;
  83699. }
  83700. case SQLITE_CONFIG_MUTEX: {
  83701. /* Specify an alternative mutex implementation */
  83702. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  83703. break;
  83704. }
  83705. case SQLITE_CONFIG_GETMUTEX: {
  83706. /* Retrieve the current mutex implementation */
  83707. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  83708. break;
  83709. }
  83710. #endif
  83711. case SQLITE_CONFIG_MALLOC: {
  83712. /* Specify an alternative malloc implementation */
  83713. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  83714. break;
  83715. }
  83716. case SQLITE_CONFIG_GETMALLOC: {
  83717. /* Retrieve the current malloc() implementation */
  83718. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  83719. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  83720. break;
  83721. }
  83722. case SQLITE_CONFIG_MEMSTATUS: {
  83723. /* Enable or disable the malloc status collection */
  83724. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  83725. break;
  83726. }
  83727. case SQLITE_CONFIG_SCRATCH: {
  83728. /* Designate a buffer for scratch memory space */
  83729. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  83730. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  83731. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  83732. break;
  83733. }
  83734. case SQLITE_CONFIG_PAGECACHE: {
  83735. /* Designate a buffer for scratch memory space */
  83736. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  83737. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  83738. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  83739. break;
  83740. }
  83741. case SQLITE_CONFIG_PCACHE: {
  83742. /* Specify an alternative malloc implementation */
  83743. sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
  83744. break;
  83745. }
  83746. case SQLITE_CONFIG_GETPCACHE: {
  83747. if( sqlite3GlobalConfig.pcache.xInit==0 ){
  83748. sqlite3PCacheSetDefault();
  83749. }
  83750. *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
  83751. break;
  83752. }
  83753. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  83754. case SQLITE_CONFIG_HEAP: {
  83755. /* Designate a buffer for heap memory space */
  83756. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  83757. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  83758. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  83759. if( sqlite3GlobalConfig.pHeap==0 ){
  83760. /* If the heap pointer is NULL, then restore the malloc implementation
  83761. ** back to NULL pointers too. This will cause the malloc to go
  83762. ** back to its default implementation when sqlite3_initialize() is
  83763. ** run.
  83764. */
  83765. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  83766. }else{
  83767. /* The heap pointer is not NULL, then install one of the
  83768. ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
  83769. ** ENABLE_MEMSYS5 is defined, return an error.
  83770. ** the default case and return an error.
  83771. */
  83772. #ifdef SQLITE_ENABLE_MEMSYS3
  83773. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  83774. #endif
  83775. #ifdef SQLITE_ENABLE_MEMSYS5
  83776. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  83777. #endif
  83778. }
  83779. break;
  83780. }
  83781. #endif
  83782. case SQLITE_CONFIG_LOOKASIDE: {
  83783. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  83784. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  83785. break;
  83786. }
  83787. default: {
  83788. rc = SQLITE_ERROR;
  83789. break;
  83790. }
  83791. }
  83792. va_end(ap);
  83793. return rc;
  83794. }
  83795. /*
  83796. ** Set up the lookaside buffers for a database connection.
  83797. ** Return SQLITE_OK on success.
  83798. ** If lookaside is already active, return SQLITE_BUSY.
  83799. **
  83800. ** The sz parameter is the number of bytes in each lookaside slot.
  83801. ** The cnt parameter is the number of slots. If pStart is NULL the
  83802. ** space for the lookaside memory is obtained from sqlite3_malloc().
  83803. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  83804. ** the lookaside memory.
  83805. */
  83806. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  83807. void *pStart;
  83808. if( db->lookaside.nOut ){
  83809. return SQLITE_BUSY;
  83810. }
  83811. /* Free any existing lookaside buffer for this handle before
  83812. ** allocating a new one so we don't have to have space for
  83813. ** both at the same time.
  83814. */
  83815. if( db->lookaside.bMalloced ){
  83816. sqlite3_free(db->lookaside.pStart);
  83817. }
  83818. /* The size of a lookaside slot needs to be larger than a pointer
  83819. ** to be useful.
  83820. */
  83821. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  83822. if( cnt<0 ) cnt = 0;
  83823. if( sz==0 || cnt==0 ){
  83824. sz = 0;
  83825. pStart = 0;
  83826. }else if( pBuf==0 ){
  83827. sz = ROUND8(sz);
  83828. sqlite3BeginBenignMalloc();
  83829. pStart = sqlite3Malloc( sz*cnt );
  83830. sqlite3EndBenignMalloc();
  83831. }else{
  83832. sz = ROUNDDOWN8(sz);
  83833. pStart = pBuf;
  83834. }
  83835. db->lookaside.pStart = pStart;
  83836. db->lookaside.pFree = 0;
  83837. db->lookaside.sz = (u16)sz;
  83838. if( pStart ){
  83839. int i;
  83840. LookasideSlot *p;
  83841. assert( sz > (int)sizeof(LookasideSlot*) );
  83842. p = (LookasideSlot*)pStart;
  83843. for(i=cnt-1; i>=0; i--){
  83844. p->pNext = db->lookaside.pFree;
  83845. db->lookaside.pFree = p;
  83846. p = (LookasideSlot*)&((u8*)p)[sz];
  83847. }
  83848. db->lookaside.pEnd = p;
  83849. db->lookaside.bEnabled = 1;
  83850. db->lookaside.bMalloced = pBuf==0 ?1:0;
  83851. }else{
  83852. db->lookaside.pEnd = 0;
  83853. db->lookaside.bEnabled = 0;
  83854. db->lookaside.bMalloced = 0;
  83855. }
  83856. return SQLITE_OK;
  83857. }
  83858. /*
  83859. ** Return the mutex associated with a database connection.
  83860. */
  83861. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  83862. return db->mutex;
  83863. }
  83864. /*
  83865. ** Configuration settings for an individual database connection
  83866. */
  83867. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  83868. va_list ap;
  83869. int rc;
  83870. va_start(ap, op);
  83871. switch( op ){
  83872. case SQLITE_DBCONFIG_LOOKASIDE: {
  83873. void *pBuf = va_arg(ap, void*);
  83874. int sz = va_arg(ap, int);
  83875. int cnt = va_arg(ap, int);
  83876. rc = setupLookaside(db, pBuf, sz, cnt);
  83877. break;
  83878. }
  83879. default: {
  83880. rc = SQLITE_ERROR;
  83881. break;
  83882. }
  83883. }
  83884. va_end(ap);
  83885. return rc;
  83886. }
  83887. /*
  83888. ** Return true if the buffer z[0..n-1] contains all spaces.
  83889. */
  83890. static int allSpaces(const char *z, int n){
  83891. while( n>0 && z[n-1]==' ' ){ n--; }
  83892. return n==0;
  83893. }
  83894. /*
  83895. ** This is the default collating function named "BINARY" which is always
  83896. ** available.
  83897. **
  83898. ** If the padFlag argument is not NULL then space padding at the end
  83899. ** of strings is ignored. This implements the RTRIM collation.
  83900. */
  83901. static int binCollFunc(
  83902. void *padFlag,
  83903. int nKey1, const void *pKey1,
  83904. int nKey2, const void *pKey2
  83905. ){
  83906. int rc, n;
  83907. n = nKey1<nKey2 ? nKey1 : nKey2;
  83908. rc = memcmp(pKey1, pKey2, n);
  83909. if( rc==0 ){
  83910. if( padFlag
  83911. && allSpaces(((char*)pKey1)+n, nKey1-n)
  83912. && allSpaces(((char*)pKey2)+n, nKey2-n)
  83913. ){
  83914. /* Leave rc unchanged at 0 */
  83915. }else{
  83916. rc = nKey1 - nKey2;
  83917. }
  83918. }
  83919. return rc;
  83920. }
  83921. /*
  83922. ** Another built-in collating sequence: NOCASE.
  83923. **
  83924. ** This collating sequence is intended to be used for "case independant
  83925. ** comparison". SQLite's knowledge of upper and lower case equivalents
  83926. ** extends only to the 26 characters used in the English language.
  83927. **
  83928. ** At the moment there is only a UTF-8 implementation.
  83929. */
  83930. static int nocaseCollatingFunc(
  83931. void *NotUsed,
  83932. int nKey1, const void *pKey1,
  83933. int nKey2, const void *pKey2
  83934. ){
  83935. int r = sqlite3StrNICmp(
  83936. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  83937. UNUSED_PARAMETER(NotUsed);
  83938. if( 0==r ){
  83939. r = nKey1-nKey2;
  83940. }
  83941. return r;
  83942. }
  83943. /*
  83944. ** Return the ROWID of the most recent insert
  83945. */
  83946. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  83947. return db->lastRowid;
  83948. }
  83949. /*
  83950. ** Return the number of changes in the most recent call to sqlite3_exec().
  83951. */
  83952. SQLITE_API int sqlite3_changes(sqlite3 *db){
  83953. return db->nChange;
  83954. }
  83955. /*
  83956. ** Return the number of changes since the database handle was opened.
  83957. */
  83958. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  83959. return db->nTotalChange;
  83960. }
  83961. /*
  83962. ** Close all open savepoints. This function only manipulates fields of the
  83963. ** database handle object, it does not close any savepoints that may be open
  83964. ** at the b-tree/pager level.
  83965. */
  83966. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  83967. while( db->pSavepoint ){
  83968. Savepoint *pTmp = db->pSavepoint;
  83969. db->pSavepoint = pTmp->pNext;
  83970. sqlite3DbFree(db, pTmp);
  83971. }
  83972. db->nSavepoint = 0;
  83973. db->nStatement = 0;
  83974. db->isTransactionSavepoint = 0;
  83975. }
  83976. /*
  83977. ** Close an existing SQLite database
  83978. */
  83979. SQLITE_API int sqlite3_close(sqlite3 *db){
  83980. HashElem *i;
  83981. int j;
  83982. if( !db ){
  83983. return SQLITE_OK;
  83984. }
  83985. if( !sqlite3SafetyCheckSickOrOk(db) ){
  83986. return SQLITE_MISUSE;
  83987. }
  83988. sqlite3_mutex_enter(db->mutex);
  83989. #ifdef SQLITE_SSE
  83990. {
  83991. extern void sqlite3SseCleanup(sqlite3*);
  83992. sqlite3SseCleanup(db);
  83993. }
  83994. #endif
  83995. sqlite3ResetInternalSchema(db, 0);
  83996. /* If a transaction is open, the ResetInternalSchema() call above
  83997. ** will not have called the xDisconnect() method on any virtual
  83998. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  83999. ** call will do so. We need to do this before the check for active
  84000. ** SQL statements below, as the v-table implementation may be storing
  84001. ** some prepared statements internally.
  84002. */
  84003. sqlite3VtabRollback(db);
  84004. /* If there are any outstanding VMs, return SQLITE_BUSY. */
  84005. if( db->pVdbe ){
  84006. sqlite3Error(db, SQLITE_BUSY,
  84007. "unable to close due to unfinalised statements");
  84008. sqlite3_mutex_leave(db->mutex);
  84009. return SQLITE_BUSY;
  84010. }
  84011. assert( sqlite3SafetyCheckSickOrOk(db) );
  84012. for(j=0; j<db->nDb; j++){
  84013. Btree *pBt = db->aDb[j].pBt;
  84014. if( pBt && sqlite3BtreeIsInBackup(pBt) ){
  84015. sqlite3Error(db, SQLITE_BUSY,
  84016. "unable to close due to unfinished backup operation");
  84017. sqlite3_mutex_leave(db->mutex);
  84018. return SQLITE_BUSY;
  84019. }
  84020. }
  84021. /* Free any outstanding Savepoint structures. */
  84022. sqlite3CloseSavepoints(db);
  84023. for(j=0; j<db->nDb; j++){
  84024. struct Db *pDb = &db->aDb[j];
  84025. if( pDb->pBt ){
  84026. sqlite3BtreeClose(pDb->pBt);
  84027. pDb->pBt = 0;
  84028. if( j!=1 ){
  84029. pDb->pSchema = 0;
  84030. }
  84031. }
  84032. }
  84033. sqlite3ResetInternalSchema(db, 0);
  84034. /* Tell the code in notify.c that the connection no longer holds any
  84035. ** locks and does not require any further unlock-notify callbacks.
  84036. */
  84037. sqlite3ConnectionClosed(db);
  84038. assert( db->nDb<=2 );
  84039. assert( db->aDb==db->aDbStatic );
  84040. for(j=0; j<ArraySize(db->aFunc.a); j++){
  84041. FuncDef *pNext, *pHash, *p;
  84042. for(p=db->aFunc.a[j]; p; p=pHash){
  84043. pHash = p->pHash;
  84044. while( p ){
  84045. pNext = p->pNext;
  84046. sqlite3DbFree(db, p);
  84047. p = pNext;
  84048. }
  84049. }
  84050. }
  84051. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  84052. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  84053. /* Invoke any destructors registered for collation sequence user data. */
  84054. for(j=0; j<3; j++){
  84055. if( pColl[j].xDel ){
  84056. pColl[j].xDel(pColl[j].pUser);
  84057. }
  84058. }
  84059. sqlite3DbFree(db, pColl);
  84060. }
  84061. sqlite3HashClear(&db->aCollSeq);
  84062. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84063. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  84064. Module *pMod = (Module *)sqliteHashData(i);
  84065. if( pMod->xDestroy ){
  84066. pMod->xDestroy(pMod->pAux);
  84067. }
  84068. sqlite3DbFree(db, pMod);
  84069. }
  84070. sqlite3HashClear(&db->aModule);
  84071. #endif
  84072. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  84073. if( db->pErr ){
  84074. sqlite3ValueFree(db->pErr);
  84075. }
  84076. sqlite3CloseExtensions(db);
  84077. db->magic = SQLITE_MAGIC_ERROR;
  84078. /* The temp-database schema is allocated differently from the other schema
  84079. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  84080. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  84081. ** the same sqliteMalloc() as the one that allocates the database
  84082. ** structure?
  84083. */
  84084. sqlite3DbFree(db, db->aDb[1].pSchema);
  84085. sqlite3_mutex_leave(db->mutex);
  84086. db->magic = SQLITE_MAGIC_CLOSED;
  84087. sqlite3_mutex_free(db->mutex);
  84088. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  84089. if( db->lookaside.bMalloced ){
  84090. sqlite3_free(db->lookaside.pStart);
  84091. }
  84092. sqlite3_free(db);
  84093. return SQLITE_OK;
  84094. }
  84095. /*
  84096. ** Rollback all database files.
  84097. */
  84098. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
  84099. int i;
  84100. int inTrans = 0;
  84101. assert( sqlite3_mutex_held(db->mutex) );
  84102. sqlite3BeginBenignMalloc();
  84103. for(i=0; i<db->nDb; i++){
  84104. if( db->aDb[i].pBt ){
  84105. if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
  84106. inTrans = 1;
  84107. }
  84108. sqlite3BtreeRollback(db->aDb[i].pBt);
  84109. db->aDb[i].inTrans = 0;
  84110. }
  84111. }
  84112. sqlite3VtabRollback(db);
  84113. sqlite3EndBenignMalloc();
  84114. if( db->flags&SQLITE_InternChanges ){
  84115. sqlite3ExpirePreparedStatements(db);
  84116. sqlite3ResetInternalSchema(db, 0);
  84117. }
  84118. /* If one has been configured, invoke the rollback-hook callback */
  84119. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  84120. db->xRollbackCallback(db->pRollbackArg);
  84121. }
  84122. }
  84123. /*
  84124. ** Return a static string that describes the kind of error specified in the
  84125. ** argument.
  84126. */
  84127. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  84128. const char *z;
  84129. switch( rc & 0xff ){
  84130. case SQLITE_ROW:
  84131. case SQLITE_DONE:
  84132. case SQLITE_OK: z = "not an error"; break;
  84133. case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
  84134. case SQLITE_PERM: z = "access permission denied"; break;
  84135. case SQLITE_ABORT: z = "callback requested query abort"; break;
  84136. case SQLITE_BUSY: z = "database is locked"; break;
  84137. case SQLITE_LOCKED: z = "database table is locked"; break;
  84138. case SQLITE_NOMEM: z = "out of memory"; break;
  84139. case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
  84140. case SQLITE_INTERRUPT: z = "interrupted"; break;
  84141. case SQLITE_IOERR: z = "disk I/O error"; break;
  84142. case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
  84143. case SQLITE_FULL: z = "database or disk is full"; break;
  84144. case SQLITE_CANTOPEN: z = "unable to open database file"; break;
  84145. case SQLITE_EMPTY: z = "table contains no data"; break;
  84146. case SQLITE_SCHEMA: z = "database schema has changed"; break;
  84147. case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
  84148. case SQLITE_CONSTRAINT: z = "constraint failed"; break;
  84149. case SQLITE_MISMATCH: z = "datatype mismatch"; break;
  84150. case SQLITE_MISUSE: z = "library routine called out of sequence";break;
  84151. case SQLITE_NOLFS: z = "large file support is disabled"; break;
  84152. case SQLITE_AUTH: z = "authorization denied"; break;
  84153. case SQLITE_FORMAT: z = "auxiliary database format error"; break;
  84154. case SQLITE_RANGE: z = "bind or column index out of range"; break;
  84155. case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
  84156. default: z = "unknown error"; break;
  84157. }
  84158. return z;
  84159. }
  84160. /*
  84161. ** This routine implements a busy callback that sleeps and tries
  84162. ** again until a timeout value is reached. The timeout value is
  84163. ** an integer number of milliseconds passed in as the first
  84164. ** argument.
  84165. */
  84166. static int sqliteDefaultBusyCallback(
  84167. void *ptr, /* Database connection */
  84168. int count /* Number of times table has been busy */
  84169. ){
  84170. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  84171. static const u8 delays[] =
  84172. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  84173. static const u8 totals[] =
  84174. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  84175. # define NDELAY (sizeof(delays)/sizeof(delays[0]))
  84176. sqlite3 *db = (sqlite3 *)ptr;
  84177. int timeout = db->busyTimeout;
  84178. int delay, prior;
  84179. assert( count>=0 );
  84180. if( count < NDELAY ){
  84181. delay = delays[count];
  84182. prior = totals[count];
  84183. }else{
  84184. delay = delays[NDELAY-1];
  84185. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  84186. }
  84187. if( prior + delay > timeout ){
  84188. delay = timeout - prior;
  84189. if( delay<=0 ) return 0;
  84190. }
  84191. sqlite3OsSleep(db->pVfs, delay*1000);
  84192. return 1;
  84193. #else
  84194. sqlite3 *db = (sqlite3 *)ptr;
  84195. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  84196. if( (count+1)*1000 > timeout ){
  84197. return 0;
  84198. }
  84199. sqlite3OsSleep(db->pVfs, 1000000);
  84200. return 1;
  84201. #endif
  84202. }
  84203. /*
  84204. ** Invoke the given busy handler.
  84205. **
  84206. ** This routine is called when an operation failed with a lock.
  84207. ** If this routine returns non-zero, the lock is retried. If it
  84208. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  84209. */
  84210. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  84211. int rc;
  84212. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  84213. rc = p->xFunc(p->pArg, p->nBusy);
  84214. if( rc==0 ){
  84215. p->nBusy = -1;
  84216. }else{
  84217. p->nBusy++;
  84218. }
  84219. return rc;
  84220. }
  84221. /*
  84222. ** This routine sets the busy callback for an Sqlite database to the
  84223. ** given callback function with the given argument.
  84224. */
  84225. SQLITE_API int sqlite3_busy_handler(
  84226. sqlite3 *db,
  84227. int (*xBusy)(void*,int),
  84228. void *pArg
  84229. ){
  84230. sqlite3_mutex_enter(db->mutex);
  84231. db->busyHandler.xFunc = xBusy;
  84232. db->busyHandler.pArg = pArg;
  84233. db->busyHandler.nBusy = 0;
  84234. sqlite3_mutex_leave(db->mutex);
  84235. return SQLITE_OK;
  84236. }
  84237. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  84238. /*
  84239. ** This routine sets the progress callback for an Sqlite database to the
  84240. ** given callback function with the given argument. The progress callback will
  84241. ** be invoked every nOps opcodes.
  84242. */
  84243. SQLITE_API void sqlite3_progress_handler(
  84244. sqlite3 *db,
  84245. int nOps,
  84246. int (*xProgress)(void*),
  84247. void *pArg
  84248. ){
  84249. sqlite3_mutex_enter(db->mutex);
  84250. if( nOps>0 ){
  84251. db->xProgress = xProgress;
  84252. db->nProgressOps = nOps;
  84253. db->pProgressArg = pArg;
  84254. }else{
  84255. db->xProgress = 0;
  84256. db->nProgressOps = 0;
  84257. db->pProgressArg = 0;
  84258. }
  84259. sqlite3_mutex_leave(db->mutex);
  84260. }
  84261. #endif
  84262. /*
  84263. ** This routine installs a default busy handler that waits for the
  84264. ** specified number of milliseconds before returning 0.
  84265. */
  84266. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  84267. if( ms>0 ){
  84268. db->busyTimeout = ms;
  84269. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  84270. }else{
  84271. sqlite3_busy_handler(db, 0, 0);
  84272. }
  84273. return SQLITE_OK;
  84274. }
  84275. /*
  84276. ** Cause any pending operation to stop at its earliest opportunity.
  84277. */
  84278. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  84279. db->u1.isInterrupted = 1;
  84280. }
  84281. /*
  84282. ** This function is exactly the same as sqlite3_create_function(), except
  84283. ** that it is designed to be called by internal code. The difference is
  84284. ** that if a malloc() fails in sqlite3_create_function(), an error code
  84285. ** is returned and the mallocFailed flag cleared.
  84286. */
  84287. SQLITE_PRIVATE int sqlite3CreateFunc(
  84288. sqlite3 *db,
  84289. const char *zFunctionName,
  84290. int nArg,
  84291. int enc,
  84292. void *pUserData,
  84293. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  84294. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  84295. void (*xFinal)(sqlite3_context*)
  84296. ){
  84297. FuncDef *p;
  84298. int nName;
  84299. assert( sqlite3_mutex_held(db->mutex) );
  84300. if( zFunctionName==0 ||
  84301. (xFunc && (xFinal || xStep)) ||
  84302. (!xFunc && (xFinal && !xStep)) ||
  84303. (!xFunc && (!xFinal && xStep)) ||
  84304. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  84305. (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
  84306. sqlite3Error(db, SQLITE_ERROR, "bad parameters");
  84307. return SQLITE_ERROR;
  84308. }
  84309. #ifndef SQLITE_OMIT_UTF16
  84310. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  84311. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  84312. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  84313. **
  84314. ** If SQLITE_ANY is specified, add three versions of the function
  84315. ** to the hash table.
  84316. */
  84317. if( enc==SQLITE_UTF16 ){
  84318. enc = SQLITE_UTF16NATIVE;
  84319. }else if( enc==SQLITE_ANY ){
  84320. int rc;
  84321. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  84322. pUserData, xFunc, xStep, xFinal);
  84323. if( rc==SQLITE_OK ){
  84324. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  84325. pUserData, xFunc, xStep, xFinal);
  84326. }
  84327. if( rc!=SQLITE_OK ){
  84328. return rc;
  84329. }
  84330. enc = SQLITE_UTF16BE;
  84331. }
  84332. #else
  84333. enc = SQLITE_UTF8;
  84334. #endif
  84335. /* Check if an existing function is being overridden or deleted. If so,
  84336. ** and there are active VMs, then return SQLITE_BUSY. If a function
  84337. ** is being overridden/deleted but there are no active VMs, allow the
  84338. ** operation to continue but invalidate all precompiled statements.
  84339. */
  84340. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  84341. if( p && p->iPrefEnc==enc && p->nArg==nArg ){
  84342. if( db->activeVdbeCnt ){
  84343. sqlite3Error(db, SQLITE_BUSY,
  84344. "unable to delete/modify user-function due to active statements");
  84345. assert( !db->mallocFailed );
  84346. return SQLITE_BUSY;
  84347. }else{
  84348. sqlite3ExpirePreparedStatements(db);
  84349. }
  84350. }
  84351. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  84352. assert(p || db->mallocFailed);
  84353. if( !p ){
  84354. return SQLITE_NOMEM;
  84355. }
  84356. p->flags = 0;
  84357. p->xFunc = xFunc;
  84358. p->xStep = xStep;
  84359. p->xFinalize = xFinal;
  84360. p->pUserData = pUserData;
  84361. p->nArg = (u16)nArg;
  84362. return SQLITE_OK;
  84363. }
  84364. /*
  84365. ** Create new user functions.
  84366. */
  84367. SQLITE_API int sqlite3_create_function(
  84368. sqlite3 *db,
  84369. const char *zFunctionName,
  84370. int nArg,
  84371. int enc,
  84372. void *p,
  84373. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  84374. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  84375. void (*xFinal)(sqlite3_context*)
  84376. ){
  84377. int rc;
  84378. sqlite3_mutex_enter(db->mutex);
  84379. rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
  84380. rc = sqlite3ApiExit(db, rc);
  84381. sqlite3_mutex_leave(db->mutex);
  84382. return rc;
  84383. }
  84384. #ifndef SQLITE_OMIT_UTF16
  84385. SQLITE_API int sqlite3_create_function16(
  84386. sqlite3 *db,
  84387. const void *zFunctionName,
  84388. int nArg,
  84389. int eTextRep,
  84390. void *p,
  84391. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  84392. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  84393. void (*xFinal)(sqlite3_context*)
  84394. ){
  84395. int rc;
  84396. char *zFunc8;
  84397. sqlite3_mutex_enter(db->mutex);
  84398. assert( !db->mallocFailed );
  84399. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
  84400. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
  84401. sqlite3DbFree(db, zFunc8);
  84402. rc = sqlite3ApiExit(db, rc);
  84403. sqlite3_mutex_leave(db->mutex);
  84404. return rc;
  84405. }
  84406. #endif
  84407. /*
  84408. ** Declare that a function has been overloaded by a virtual table.
  84409. **
  84410. ** If the function already exists as a regular global function, then
  84411. ** this routine is a no-op. If the function does not exist, then create
  84412. ** a new one that always throws a run-time error.
  84413. **
  84414. ** When virtual tables intend to provide an overloaded function, they
  84415. ** should call this routine to make sure the global function exists.
  84416. ** A global function must exist in order for name resolution to work
  84417. ** properly.
  84418. */
  84419. SQLITE_API int sqlite3_overload_function(
  84420. sqlite3 *db,
  84421. const char *zName,
  84422. int nArg
  84423. ){
  84424. int nName = sqlite3Strlen(db, zName);
  84425. int rc;
  84426. sqlite3_mutex_enter(db->mutex);
  84427. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  84428. sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  84429. 0, sqlite3InvalidFunction, 0, 0);
  84430. }
  84431. rc = sqlite3ApiExit(db, SQLITE_OK);
  84432. sqlite3_mutex_leave(db->mutex);
  84433. return rc;
  84434. }
  84435. #ifndef SQLITE_OMIT_TRACE
  84436. /*
  84437. ** Register a trace function. The pArg from the previously registered trace
  84438. ** is returned.
  84439. **
  84440. ** A NULL trace function means that no tracing is executes. A non-NULL
  84441. ** trace is a pointer to a function that is invoked at the start of each
  84442. ** SQL statement.
  84443. */
  84444. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  84445. void *pOld;
  84446. sqlite3_mutex_enter(db->mutex);
  84447. pOld = db->pTraceArg;
  84448. db->xTrace = xTrace;
  84449. db->pTraceArg = pArg;
  84450. sqlite3_mutex_leave(db->mutex);
  84451. return pOld;
  84452. }
  84453. /*
  84454. ** Register a profile function. The pArg from the previously registered
  84455. ** profile function is returned.
  84456. **
  84457. ** A NULL profile function means that no profiling is executes. A non-NULL
  84458. ** profile is a pointer to a function that is invoked at the conclusion of
  84459. ** each SQL statement that is run.
  84460. */
  84461. SQLITE_API void *sqlite3_profile(
  84462. sqlite3 *db,
  84463. void (*xProfile)(void*,const char*,sqlite_uint64),
  84464. void *pArg
  84465. ){
  84466. void *pOld;
  84467. sqlite3_mutex_enter(db->mutex);
  84468. pOld = db->pProfileArg;
  84469. db->xProfile = xProfile;
  84470. db->pProfileArg = pArg;
  84471. sqlite3_mutex_leave(db->mutex);
  84472. return pOld;
  84473. }
  84474. #endif /* SQLITE_OMIT_TRACE */
  84475. /*** EXPERIMENTAL ***
  84476. **
  84477. ** Register a function to be invoked when a transaction comments.
  84478. ** If the invoked function returns non-zero, then the commit becomes a
  84479. ** rollback.
  84480. */
  84481. SQLITE_API void *sqlite3_commit_hook(
  84482. sqlite3 *db, /* Attach the hook to this database */
  84483. int (*xCallback)(void*), /* Function to invoke on each commit */
  84484. void *pArg /* Argument to the function */
  84485. ){
  84486. void *pOld;
  84487. sqlite3_mutex_enter(db->mutex);
  84488. pOld = db->pCommitArg;
  84489. db->xCommitCallback = xCallback;
  84490. db->pCommitArg = pArg;
  84491. sqlite3_mutex_leave(db->mutex);
  84492. return pOld;
  84493. }
  84494. /*
  84495. ** Register a callback to be invoked each time a row is updated,
  84496. ** inserted or deleted using this database connection.
  84497. */
  84498. SQLITE_API void *sqlite3_update_hook(
  84499. sqlite3 *db, /* Attach the hook to this database */
  84500. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  84501. void *pArg /* Argument to the function */
  84502. ){
  84503. void *pRet;
  84504. sqlite3_mutex_enter(db->mutex);
  84505. pRet = db->pUpdateArg;
  84506. db->xUpdateCallback = xCallback;
  84507. db->pUpdateArg = pArg;
  84508. sqlite3_mutex_leave(db->mutex);
  84509. return pRet;
  84510. }
  84511. /*
  84512. ** Register a callback to be invoked each time a transaction is rolled
  84513. ** back by this database connection.
  84514. */
  84515. SQLITE_API void *sqlite3_rollback_hook(
  84516. sqlite3 *db, /* Attach the hook to this database */
  84517. void (*xCallback)(void*), /* Callback function */
  84518. void *pArg /* Argument to the function */
  84519. ){
  84520. void *pRet;
  84521. sqlite3_mutex_enter(db->mutex);
  84522. pRet = db->pRollbackArg;
  84523. db->xRollbackCallback = xCallback;
  84524. db->pRollbackArg = pArg;
  84525. sqlite3_mutex_leave(db->mutex);
  84526. return pRet;
  84527. }
  84528. /*
  84529. ** This routine is called to create a connection to a database BTree
  84530. ** driver. If zFilename is the name of a file, then that file is
  84531. ** opened and used. If zFilename is the magic name ":memory:" then
  84532. ** the database is stored in memory (and is thus forgotten as soon as
  84533. ** the connection is closed.) If zFilename is NULL then the database
  84534. ** is a "virtual" database for transient use only and is deleted as
  84535. ** soon as the connection is closed.
  84536. **
  84537. ** A virtual database can be either a disk file (that is automatically
  84538. ** deleted when the file is closed) or it an be held entirely in memory,
  84539. ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
  84540. ** db->temp_store variable, according to the following chart:
  84541. **
  84542. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  84543. ** ----------------- -------------- ------------------------------
  84544. ** 0 any file
  84545. ** 1 1 file
  84546. ** 1 2 memory
  84547. ** 1 0 file
  84548. ** 2 1 file
  84549. ** 2 2 memory
  84550. ** 2 0 memory
  84551. ** 3 any memory
  84552. */
  84553. SQLITE_PRIVATE int sqlite3BtreeFactory(
  84554. const sqlite3 *db, /* Main database when opening aux otherwise 0 */
  84555. const char *zFilename, /* Name of the file containing the BTree database */
  84556. int omitJournal, /* if TRUE then do not journal this file */
  84557. int nCache, /* How many pages in the page cache */
  84558. int vfsFlags, /* Flags passed through to vfsOpen */
  84559. Btree **ppBtree /* Pointer to new Btree object written here */
  84560. ){
  84561. int btFlags = 0;
  84562. int rc;
  84563. assert( sqlite3_mutex_held(db->mutex) );
  84564. assert( ppBtree != 0);
  84565. if( omitJournal ){
  84566. btFlags |= BTREE_OMIT_JOURNAL;
  84567. }
  84568. if( db->flags & SQLITE_NoReadlock ){
  84569. btFlags |= BTREE_NO_READLOCK;
  84570. }
  84571. if( zFilename==0 ){
  84572. #if SQLITE_TEMP_STORE==0
  84573. /* Do nothing */
  84574. #endif
  84575. #ifndef SQLITE_OMIT_MEMORYDB
  84576. #if SQLITE_TEMP_STORE==1
  84577. if( db->temp_store==2 ) zFilename = ":memory:";
  84578. #endif
  84579. #if SQLITE_TEMP_STORE==2
  84580. if( db->temp_store!=1 ) zFilename = ":memory:";
  84581. #endif
  84582. #if SQLITE_TEMP_STORE==3
  84583. zFilename = ":memory:";
  84584. #endif
  84585. #endif /* SQLITE_OMIT_MEMORYDB */
  84586. }
  84587. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
  84588. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  84589. }
  84590. rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
  84591. /* If the B-Tree was successfully opened, set the pager-cache size to the
  84592. ** default value. Except, if the call to BtreeOpen() returned a handle
  84593. ** open on an existing shared pager-cache, do not change the pager-cache
  84594. ** size.
  84595. */
  84596. if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
  84597. sqlite3BtreeSetCacheSize(*ppBtree, nCache);
  84598. }
  84599. return rc;
  84600. }
  84601. /*
  84602. ** Return UTF-8 encoded English language explanation of the most recent
  84603. ** error.
  84604. */
  84605. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  84606. const char *z;
  84607. if( !db ){
  84608. return sqlite3ErrStr(SQLITE_NOMEM);
  84609. }
  84610. if( !sqlite3SafetyCheckSickOrOk(db) ){
  84611. return sqlite3ErrStr(SQLITE_MISUSE);
  84612. }
  84613. sqlite3_mutex_enter(db->mutex);
  84614. if( db->mallocFailed ){
  84615. z = sqlite3ErrStr(SQLITE_NOMEM);
  84616. }else{
  84617. z = (char*)sqlite3_value_text(db->pErr);
  84618. assert( !db->mallocFailed );
  84619. if( z==0 ){
  84620. z = sqlite3ErrStr(db->errCode);
  84621. }
  84622. }
  84623. sqlite3_mutex_leave(db->mutex);
  84624. return z;
  84625. }
  84626. #ifndef SQLITE_OMIT_UTF16
  84627. /*
  84628. ** Return UTF-16 encoded English language explanation of the most recent
  84629. ** error.
  84630. */
  84631. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  84632. static const u16 outOfMem[] = {
  84633. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  84634. };
  84635. static const u16 misuse[] = {
  84636. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  84637. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  84638. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  84639. 'o', 'u', 't', ' ',
  84640. 'o', 'f', ' ',
  84641. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  84642. };
  84643. const void *z;
  84644. if( !db ){
  84645. return (void *)outOfMem;
  84646. }
  84647. if( !sqlite3SafetyCheckSickOrOk(db) ){
  84648. return (void *)misuse;
  84649. }
  84650. sqlite3_mutex_enter(db->mutex);
  84651. if( db->mallocFailed ){
  84652. z = (void *)outOfMem;
  84653. }else{
  84654. z = sqlite3_value_text16(db->pErr);
  84655. if( z==0 ){
  84656. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  84657. SQLITE_UTF8, SQLITE_STATIC);
  84658. z = sqlite3_value_text16(db->pErr);
  84659. }
  84660. /* A malloc() may have failed within the call to sqlite3_value_text16()
  84661. ** above. If this is the case, then the db->mallocFailed flag needs to
  84662. ** be cleared before returning. Do this directly, instead of via
  84663. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  84664. */
  84665. db->mallocFailed = 0;
  84666. }
  84667. sqlite3_mutex_leave(db->mutex);
  84668. return z;
  84669. }
  84670. #endif /* SQLITE_OMIT_UTF16 */
  84671. /*
  84672. ** Return the most recent error code generated by an SQLite routine. If NULL is
  84673. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  84674. */
  84675. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  84676. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  84677. return SQLITE_MISUSE;
  84678. }
  84679. if( !db || db->mallocFailed ){
  84680. return SQLITE_NOMEM;
  84681. }
  84682. return db->errCode & db->errMask;
  84683. }
  84684. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  84685. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  84686. return SQLITE_MISUSE;
  84687. }
  84688. if( !db || db->mallocFailed ){
  84689. return SQLITE_NOMEM;
  84690. }
  84691. return db->errCode;
  84692. }
  84693. /*
  84694. ** Create a new collating function for database "db". The name is zName
  84695. ** and the encoding is enc.
  84696. */
  84697. static int createCollation(
  84698. sqlite3* db,
  84699. const char *zName,
  84700. int enc,
  84701. void* pCtx,
  84702. int(*xCompare)(void*,int,const void*,int,const void*),
  84703. void(*xDel)(void*)
  84704. ){
  84705. CollSeq *pColl;
  84706. int enc2;
  84707. int nName;
  84708. assert( sqlite3_mutex_held(db->mutex) );
  84709. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  84710. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  84711. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  84712. */
  84713. enc2 = enc & ~SQLITE_UTF16_ALIGNED;
  84714. if( enc2==SQLITE_UTF16 ){
  84715. enc2 = SQLITE_UTF16NATIVE;
  84716. }
  84717. if( (enc2&~3)!=0 ){
  84718. return SQLITE_MISUSE;
  84719. }
  84720. /* Check if this call is removing or replacing an existing collation
  84721. ** sequence. If so, and there are active VMs, return busy. If there
  84722. ** are no active VMs, invalidate any pre-compiled statements.
  84723. */
  84724. nName = sqlite3Strlen(db, zName);
  84725. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
  84726. if( pColl && pColl->xCmp ){
  84727. if( db->activeVdbeCnt ){
  84728. sqlite3Error(db, SQLITE_BUSY,
  84729. "unable to delete/modify collation sequence due to active statements");
  84730. return SQLITE_BUSY;
  84731. }
  84732. sqlite3ExpirePreparedStatements(db);
  84733. /* If collation sequence pColl was created directly by a call to
  84734. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  84735. ** then any copies made by synthCollSeq() need to be invalidated.
  84736. ** Also, collation destructor - CollSeq.xDel() - function may need
  84737. ** to be called.
  84738. */
  84739. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  84740. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  84741. int j;
  84742. for(j=0; j<3; j++){
  84743. CollSeq *p = &aColl[j];
  84744. if( p->enc==pColl->enc ){
  84745. if( p->xDel ){
  84746. p->xDel(p->pUser);
  84747. }
  84748. p->xCmp = 0;
  84749. }
  84750. }
  84751. }
  84752. }
  84753. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
  84754. if( pColl ){
  84755. pColl->xCmp = xCompare;
  84756. pColl->pUser = pCtx;
  84757. pColl->xDel = xDel;
  84758. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  84759. }
  84760. sqlite3Error(db, SQLITE_OK, 0);
  84761. return SQLITE_OK;
  84762. }
  84763. /*
  84764. ** This array defines hard upper bounds on limit values. The
  84765. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  84766. ** #defines in sqlite3.h.
  84767. */
  84768. static const int aHardLimit[] = {
  84769. SQLITE_MAX_LENGTH,
  84770. SQLITE_MAX_SQL_LENGTH,
  84771. SQLITE_MAX_COLUMN,
  84772. SQLITE_MAX_EXPR_DEPTH,
  84773. SQLITE_MAX_COMPOUND_SELECT,
  84774. SQLITE_MAX_VDBE_OP,
  84775. SQLITE_MAX_FUNCTION_ARG,
  84776. SQLITE_MAX_ATTACHED,
  84777. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  84778. SQLITE_MAX_VARIABLE_NUMBER,
  84779. };
  84780. /*
  84781. ** Make sure the hard limits are set to reasonable values
  84782. */
  84783. #if SQLITE_MAX_LENGTH<100
  84784. # error SQLITE_MAX_LENGTH must be at least 100
  84785. #endif
  84786. #if SQLITE_MAX_SQL_LENGTH<100
  84787. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  84788. #endif
  84789. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  84790. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  84791. #endif
  84792. #if SQLITE_MAX_COMPOUND_SELECT<2
  84793. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  84794. #endif
  84795. #if SQLITE_MAX_VDBE_OP<40
  84796. # error SQLITE_MAX_VDBE_OP must be at least 40
  84797. #endif
  84798. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  84799. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  84800. #endif
  84801. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
  84802. # error SQLITE_MAX_ATTACHED must be between 0 and 30
  84803. #endif
  84804. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  84805. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  84806. #endif
  84807. #if SQLITE_MAX_VARIABLE_NUMBER<1
  84808. # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
  84809. #endif
  84810. #if SQLITE_MAX_COLUMN>32767
  84811. # error SQLITE_MAX_COLUMN must not exceed 32767
  84812. #endif
  84813. /*
  84814. ** Change the value of a limit. Report the old value.
  84815. ** If an invalid limit index is supplied, report -1.
  84816. ** Make no changes but still report the old value if the
  84817. ** new limit is negative.
  84818. **
  84819. ** A new lower limit does not shrink existing constructs.
  84820. ** It merely prevents new constructs that exceed the limit
  84821. ** from forming.
  84822. */
  84823. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  84824. int oldLimit;
  84825. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  84826. return -1;
  84827. }
  84828. oldLimit = db->aLimit[limitId];
  84829. if( newLimit>=0 ){
  84830. if( newLimit>aHardLimit[limitId] ){
  84831. newLimit = aHardLimit[limitId];
  84832. }
  84833. db->aLimit[limitId] = newLimit;
  84834. }
  84835. return oldLimit;
  84836. }
  84837. /*
  84838. ** This routine does the work of opening a database on behalf of
  84839. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  84840. ** is UTF-8 encoded.
  84841. */
  84842. static int openDatabase(
  84843. const char *zFilename, /* Database filename UTF-8 encoded */
  84844. sqlite3 **ppDb, /* OUT: Returned database handle */
  84845. unsigned flags, /* Operational flags */
  84846. const char *zVfs /* Name of the VFS to use */
  84847. ){
  84848. sqlite3 *db;
  84849. int rc;
  84850. CollSeq *pColl;
  84851. int isThreadsafe;
  84852. #ifndef SQLITE_OMIT_AUTOINIT
  84853. rc = sqlite3_initialize();
  84854. if( rc ) return rc;
  84855. #endif
  84856. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  84857. isThreadsafe = 0;
  84858. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  84859. isThreadsafe = 0;
  84860. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  84861. isThreadsafe = 1;
  84862. }else{
  84863. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  84864. }
  84865. /* Remove harmful bits from the flags parameter */
  84866. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  84867. SQLITE_OPEN_MAIN_DB |
  84868. SQLITE_OPEN_TEMP_DB |
  84869. SQLITE_OPEN_TRANSIENT_DB |
  84870. SQLITE_OPEN_MAIN_JOURNAL |
  84871. SQLITE_OPEN_TEMP_JOURNAL |
  84872. SQLITE_OPEN_SUBJOURNAL |
  84873. SQLITE_OPEN_MASTER_JOURNAL |
  84874. SQLITE_OPEN_NOMUTEX |
  84875. SQLITE_OPEN_FULLMUTEX
  84876. );
  84877. /* Allocate the sqlite data structure */
  84878. db = sqlite3MallocZero( sizeof(sqlite3) );
  84879. if( db==0 ) goto opendb_out;
  84880. if( isThreadsafe ){
  84881. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  84882. if( db->mutex==0 ){
  84883. sqlite3_free(db);
  84884. db = 0;
  84885. goto opendb_out;
  84886. }
  84887. }
  84888. sqlite3_mutex_enter(db->mutex);
  84889. db->errMask = 0xff;
  84890. db->priorNewRowid = 0;
  84891. db->nDb = 2;
  84892. db->magic = SQLITE_MAGIC_BUSY;
  84893. db->aDb = db->aDbStatic;
  84894. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  84895. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  84896. db->autoCommit = 1;
  84897. db->nextAutovac = -1;
  84898. db->nextPagesize = 0;
  84899. db->flags |= SQLITE_ShortColNames
  84900. #if SQLITE_DEFAULT_FILE_FORMAT<4
  84901. | SQLITE_LegacyFileFmt
  84902. #endif
  84903. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  84904. | SQLITE_LoadExtension
  84905. #endif
  84906. ;
  84907. sqlite3HashInit(&db->aCollSeq, 0);
  84908. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84909. sqlite3HashInit(&db->aModule, 0);
  84910. #endif
  84911. db->pVfs = sqlite3_vfs_find(zVfs);
  84912. if( !db->pVfs ){
  84913. rc = SQLITE_ERROR;
  84914. sqlite3Error(db, rc, "no such vfs: %s", zVfs);
  84915. goto opendb_out;
  84916. }
  84917. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  84918. ** and UTF-16, so add a version for each to avoid any unnecessary
  84919. ** conversions. The only error that can occur here is a malloc() failure.
  84920. */
  84921. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  84922. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  84923. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  84924. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  84925. if( db->mallocFailed ){
  84926. goto opendb_out;
  84927. }
  84928. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
  84929. assert( db->pDfltColl!=0 );
  84930. /* Also add a UTF-8 case-insensitive collation sequence. */
  84931. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  84932. /* Set flags on the built-in collating sequences */
  84933. db->pDfltColl->type = SQLITE_COLL_BINARY;
  84934. pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
  84935. if( pColl ){
  84936. pColl->type = SQLITE_COLL_NOCASE;
  84937. }
  84938. /* Open the backend database driver */
  84939. db->openFlags = flags;
  84940. rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
  84941. flags | SQLITE_OPEN_MAIN_DB,
  84942. &db->aDb[0].pBt);
  84943. if( rc!=SQLITE_OK ){
  84944. if( rc==SQLITE_IOERR_NOMEM ){
  84945. rc = SQLITE_NOMEM;
  84946. }
  84947. sqlite3Error(db, rc, 0);
  84948. goto opendb_out;
  84949. }
  84950. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  84951. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  84952. /* The default safety_level for the main database is 'full'; for the temp
  84953. ** database it is 'NONE'. This matches the pager layer defaults.
  84954. */
  84955. db->aDb[0].zName = "main";
  84956. db->aDb[0].safety_level = 3;
  84957. #ifndef SQLITE_OMIT_TEMPDB
  84958. db->aDb[1].zName = "temp";
  84959. db->aDb[1].safety_level = 1;
  84960. #endif
  84961. db->magic = SQLITE_MAGIC_OPEN;
  84962. if( db->mallocFailed ){
  84963. goto opendb_out;
  84964. }
  84965. /* Register all built-in functions, but do not attempt to read the
  84966. ** database schema yet. This is delayed until the first time the database
  84967. ** is accessed.
  84968. */
  84969. sqlite3Error(db, SQLITE_OK, 0);
  84970. sqlite3RegisterBuiltinFunctions(db);
  84971. /* Load automatic extensions - extensions that have been registered
  84972. ** using the sqlite3_automatic_extension() API.
  84973. */
  84974. (void)sqlite3AutoLoadExtensions(db);
  84975. if( sqlite3_errcode(db)!=SQLITE_OK ){
  84976. goto opendb_out;
  84977. }
  84978. #ifdef SQLITE_ENABLE_FTS1
  84979. if( !db->mallocFailed ){
  84980. extern int sqlite3Fts1Init(sqlite3*);
  84981. rc = sqlite3Fts1Init(db);
  84982. }
  84983. #endif
  84984. #ifdef SQLITE_ENABLE_FTS2
  84985. if( !db->mallocFailed && rc==SQLITE_OK ){
  84986. extern int sqlite3Fts2Init(sqlite3*);
  84987. rc = sqlite3Fts2Init(db);
  84988. }
  84989. #endif
  84990. #ifdef SQLITE_ENABLE_FTS3
  84991. if( !db->mallocFailed && rc==SQLITE_OK ){
  84992. rc = sqlite3Fts3Init(db);
  84993. }
  84994. #endif
  84995. #ifdef SQLITE_ENABLE_ICU
  84996. if( !db->mallocFailed && rc==SQLITE_OK ){
  84997. rc = sqlite3IcuInit(db);
  84998. }
  84999. #endif
  85000. #ifdef SQLITE_ENABLE_RTREE
  85001. if( !db->mallocFailed && rc==SQLITE_OK){
  85002. rc = sqlite3RtreeInit(db);
  85003. }
  85004. #endif
  85005. sqlite3Error(db, rc, 0);
  85006. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  85007. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  85008. ** mode. Doing nothing at all also makes NORMAL the default.
  85009. */
  85010. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  85011. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  85012. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  85013. SQLITE_DEFAULT_LOCKING_MODE);
  85014. #endif
  85015. /* Enable the lookaside-malloc subsystem */
  85016. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  85017. sqlite3GlobalConfig.nLookaside);
  85018. opendb_out:
  85019. if( db ){
  85020. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  85021. sqlite3_mutex_leave(db->mutex);
  85022. }
  85023. rc = sqlite3_errcode(db);
  85024. if( rc==SQLITE_NOMEM ){
  85025. sqlite3_close(db);
  85026. db = 0;
  85027. }else if( rc!=SQLITE_OK ){
  85028. db->magic = SQLITE_MAGIC_SICK;
  85029. }
  85030. *ppDb = db;
  85031. return sqlite3ApiExit(0, rc);
  85032. }
  85033. /*
  85034. ** Open a new database handle.
  85035. */
  85036. SQLITE_API int sqlite3_open(
  85037. const char *zFilename,
  85038. sqlite3 **ppDb
  85039. ){
  85040. return openDatabase(zFilename, ppDb,
  85041. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  85042. }
  85043. SQLITE_API int sqlite3_open_v2(
  85044. const char *filename, /* Database filename (UTF-8) */
  85045. sqlite3 **ppDb, /* OUT: SQLite db handle */
  85046. int flags, /* Flags */
  85047. const char *zVfs /* Name of VFS module to use */
  85048. ){
  85049. return openDatabase(filename, ppDb, flags, zVfs);
  85050. }
  85051. #ifndef SQLITE_OMIT_UTF16
  85052. /*
  85053. ** Open a new database handle.
  85054. */
  85055. SQLITE_API int sqlite3_open16(
  85056. const void *zFilename,
  85057. sqlite3 **ppDb
  85058. ){
  85059. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  85060. sqlite3_value *pVal;
  85061. int rc;
  85062. assert( zFilename );
  85063. assert( ppDb );
  85064. *ppDb = 0;
  85065. #ifndef SQLITE_OMIT_AUTOINIT
  85066. rc = sqlite3_initialize();
  85067. if( rc ) return rc;
  85068. #endif
  85069. pVal = sqlite3ValueNew(0);
  85070. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  85071. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  85072. if( zFilename8 ){
  85073. rc = openDatabase(zFilename8, ppDb,
  85074. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  85075. assert( *ppDb || rc==SQLITE_NOMEM );
  85076. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  85077. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  85078. }
  85079. }else{
  85080. rc = SQLITE_NOMEM;
  85081. }
  85082. sqlite3ValueFree(pVal);
  85083. return sqlite3ApiExit(0, rc);
  85084. }
  85085. #endif /* SQLITE_OMIT_UTF16 */
  85086. /*
  85087. ** Register a new collation sequence with the database handle db.
  85088. */
  85089. SQLITE_API int sqlite3_create_collation(
  85090. sqlite3* db,
  85091. const char *zName,
  85092. int enc,
  85093. void* pCtx,
  85094. int(*xCompare)(void*,int,const void*,int,const void*)
  85095. ){
  85096. int rc;
  85097. sqlite3_mutex_enter(db->mutex);
  85098. assert( !db->mallocFailed );
  85099. rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
  85100. rc = sqlite3ApiExit(db, rc);
  85101. sqlite3_mutex_leave(db->mutex);
  85102. return rc;
  85103. }
  85104. /*
  85105. ** Register a new collation sequence with the database handle db.
  85106. */
  85107. SQLITE_API int sqlite3_create_collation_v2(
  85108. sqlite3* db,
  85109. const char *zName,
  85110. int enc,
  85111. void* pCtx,
  85112. int(*xCompare)(void*,int,const void*,int,const void*),
  85113. void(*xDel)(void*)
  85114. ){
  85115. int rc;
  85116. sqlite3_mutex_enter(db->mutex);
  85117. assert( !db->mallocFailed );
  85118. rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
  85119. rc = sqlite3ApiExit(db, rc);
  85120. sqlite3_mutex_leave(db->mutex);
  85121. return rc;
  85122. }
  85123. #ifndef SQLITE_OMIT_UTF16
  85124. /*
  85125. ** Register a new collation sequence with the database handle db.
  85126. */
  85127. SQLITE_API int sqlite3_create_collation16(
  85128. sqlite3* db,
  85129. const void *zName,
  85130. int enc,
  85131. void* pCtx,
  85132. int(*xCompare)(void*,int,const void*,int,const void*)
  85133. ){
  85134. int rc = SQLITE_OK;
  85135. char *zName8;
  85136. sqlite3_mutex_enter(db->mutex);
  85137. assert( !db->mallocFailed );
  85138. zName8 = sqlite3Utf16to8(db, zName, -1);
  85139. if( zName8 ){
  85140. rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
  85141. sqlite3DbFree(db, zName8);
  85142. }
  85143. rc = sqlite3ApiExit(db, rc);
  85144. sqlite3_mutex_leave(db->mutex);
  85145. return rc;
  85146. }
  85147. #endif /* SQLITE_OMIT_UTF16 */
  85148. /*
  85149. ** Register a collation sequence factory callback with the database handle
  85150. ** db. Replace any previously installed collation sequence factory.
  85151. */
  85152. SQLITE_API int sqlite3_collation_needed(
  85153. sqlite3 *db,
  85154. void *pCollNeededArg,
  85155. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  85156. ){
  85157. sqlite3_mutex_enter(db->mutex);
  85158. db->xCollNeeded = xCollNeeded;
  85159. db->xCollNeeded16 = 0;
  85160. db->pCollNeededArg = pCollNeededArg;
  85161. sqlite3_mutex_leave(db->mutex);
  85162. return SQLITE_OK;
  85163. }
  85164. #ifndef SQLITE_OMIT_UTF16
  85165. /*
  85166. ** Register a collation sequence factory callback with the database handle
  85167. ** db. Replace any previously installed collation sequence factory.
  85168. */
  85169. SQLITE_API int sqlite3_collation_needed16(
  85170. sqlite3 *db,
  85171. void *pCollNeededArg,
  85172. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  85173. ){
  85174. sqlite3_mutex_enter(db->mutex);
  85175. db->xCollNeeded = 0;
  85176. db->xCollNeeded16 = xCollNeeded16;
  85177. db->pCollNeededArg = pCollNeededArg;
  85178. sqlite3_mutex_leave(db->mutex);
  85179. return SQLITE_OK;
  85180. }
  85181. #endif /* SQLITE_OMIT_UTF16 */
  85182. #ifndef SQLITE_OMIT_GLOBALRECOVER
  85183. #ifndef SQLITE_OMIT_DEPRECATED
  85184. /*
  85185. ** This function is now an anachronism. It used to be used to recover from a
  85186. ** malloc() failure, but SQLite now does this automatically.
  85187. */
  85188. SQLITE_API int sqlite3_global_recover(void){
  85189. return SQLITE_OK;
  85190. }
  85191. #endif
  85192. #endif
  85193. /*
  85194. ** Test to see whether or not the database connection is in autocommit
  85195. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  85196. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  85197. ** by the next COMMIT or ROLLBACK.
  85198. **
  85199. ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  85200. */
  85201. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  85202. return db->autoCommit;
  85203. }
  85204. #ifdef SQLITE_DEBUG
  85205. /*
  85206. ** The following routine is subtituted for constant SQLITE_CORRUPT in
  85207. ** debugging builds. This provides a way to set a breakpoint for when
  85208. ** corruption is first detected.
  85209. */
  85210. SQLITE_PRIVATE int sqlite3Corrupt(void){
  85211. return SQLITE_CORRUPT;
  85212. }
  85213. #endif
  85214. #ifndef SQLITE_OMIT_DEPRECATED
  85215. /*
  85216. ** This is a convenience routine that makes sure that all thread-specific
  85217. ** data for this thread has been deallocated.
  85218. **
  85219. ** SQLite no longer uses thread-specific data so this routine is now a
  85220. ** no-op. It is retained for historical compatibility.
  85221. */
  85222. SQLITE_API void sqlite3_thread_cleanup(void){
  85223. }
  85224. #endif
  85225. /*
  85226. ** Return meta information about a specific column of a database table.
  85227. ** See comment in sqlite3.h (sqlite.h.in) for details.
  85228. */
  85229. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  85230. SQLITE_API int sqlite3_table_column_metadata(
  85231. sqlite3 *db, /* Connection handle */
  85232. const char *zDbName, /* Database name or NULL */
  85233. const char *zTableName, /* Table name */
  85234. const char *zColumnName, /* Column name */
  85235. char const **pzDataType, /* OUTPUT: Declared data type */
  85236. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  85237. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  85238. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  85239. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  85240. ){
  85241. int rc;
  85242. char *zErrMsg = 0;
  85243. Table *pTab = 0;
  85244. Column *pCol = 0;
  85245. int iCol;
  85246. char const *zDataType = 0;
  85247. char const *zCollSeq = 0;
  85248. int notnull = 0;
  85249. int primarykey = 0;
  85250. int autoinc = 0;
  85251. /* Ensure the database schema has been loaded */
  85252. sqlite3_mutex_enter(db->mutex);
  85253. (void)sqlite3SafetyOn(db);
  85254. sqlite3BtreeEnterAll(db);
  85255. rc = sqlite3Init(db, &zErrMsg);
  85256. if( SQLITE_OK!=rc ){
  85257. goto error_out;
  85258. }
  85259. /* Locate the table in question */
  85260. pTab = sqlite3FindTable(db, zTableName, zDbName);
  85261. if( !pTab || pTab->pSelect ){
  85262. pTab = 0;
  85263. goto error_out;
  85264. }
  85265. /* Find the column for which info is requested */
  85266. if( sqlite3IsRowid(zColumnName) ){
  85267. iCol = pTab->iPKey;
  85268. if( iCol>=0 ){
  85269. pCol = &pTab->aCol[iCol];
  85270. }
  85271. }else{
  85272. for(iCol=0; iCol<pTab->nCol; iCol++){
  85273. pCol = &pTab->aCol[iCol];
  85274. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  85275. break;
  85276. }
  85277. }
  85278. if( iCol==pTab->nCol ){
  85279. pTab = 0;
  85280. goto error_out;
  85281. }
  85282. }
  85283. /* The following block stores the meta information that will be returned
  85284. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  85285. ** and autoinc. At this point there are two possibilities:
  85286. **
  85287. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  85288. ** and there is no explicitly declared IPK column.
  85289. **
  85290. ** 2. The table is not a view and the column name identified an
  85291. ** explicitly declared column. Copy meta information from *pCol.
  85292. */
  85293. if( pCol ){
  85294. zDataType = pCol->zType;
  85295. zCollSeq = pCol->zColl;
  85296. notnull = pCol->notNull!=0;
  85297. primarykey = pCol->isPrimKey!=0;
  85298. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  85299. }else{
  85300. zDataType = "INTEGER";
  85301. primarykey = 1;
  85302. }
  85303. if( !zCollSeq ){
  85304. zCollSeq = "BINARY";
  85305. }
  85306. error_out:
  85307. sqlite3BtreeLeaveAll(db);
  85308. (void)sqlite3SafetyOff(db);
  85309. /* Whether the function call succeeded or failed, set the output parameters
  85310. ** to whatever their local counterparts contain. If an error did occur,
  85311. ** this has the effect of zeroing all output parameters.
  85312. */
  85313. if( pzDataType ) *pzDataType = zDataType;
  85314. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  85315. if( pNotNull ) *pNotNull = notnull;
  85316. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  85317. if( pAutoinc ) *pAutoinc = autoinc;
  85318. if( SQLITE_OK==rc && !pTab ){
  85319. sqlite3DbFree(db, zErrMsg);
  85320. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  85321. zColumnName);
  85322. rc = SQLITE_ERROR;
  85323. }
  85324. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  85325. sqlite3DbFree(db, zErrMsg);
  85326. rc = sqlite3ApiExit(db, rc);
  85327. sqlite3_mutex_leave(db->mutex);
  85328. return rc;
  85329. }
  85330. #endif
  85331. /*
  85332. ** Sleep for a little while. Return the amount of time slept.
  85333. */
  85334. SQLITE_API int sqlite3_sleep(int ms){
  85335. sqlite3_vfs *pVfs;
  85336. int rc;
  85337. pVfs = sqlite3_vfs_find(0);
  85338. if( pVfs==0 ) return 0;
  85339. /* This function works in milliseconds, but the underlying OsSleep()
  85340. ** API uses microseconds. Hence the 1000's.
  85341. */
  85342. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  85343. return rc;
  85344. }
  85345. /*
  85346. ** Enable or disable the extended result codes.
  85347. */
  85348. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  85349. sqlite3_mutex_enter(db->mutex);
  85350. db->errMask = onoff ? 0xffffffff : 0xff;
  85351. sqlite3_mutex_leave(db->mutex);
  85352. return SQLITE_OK;
  85353. }
  85354. /*
  85355. ** Invoke the xFileControl method on a particular database.
  85356. */
  85357. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  85358. int rc = SQLITE_ERROR;
  85359. int iDb;
  85360. sqlite3_mutex_enter(db->mutex);
  85361. if( zDbName==0 ){
  85362. iDb = 0;
  85363. }else{
  85364. for(iDb=0; iDb<db->nDb; iDb++){
  85365. if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
  85366. }
  85367. }
  85368. if( iDb<db->nDb ){
  85369. Btree *pBtree = db->aDb[iDb].pBt;
  85370. if( pBtree ){
  85371. Pager *pPager;
  85372. sqlite3_file *fd;
  85373. sqlite3BtreeEnter(pBtree);
  85374. pPager = sqlite3BtreePager(pBtree);
  85375. assert( pPager!=0 );
  85376. fd = sqlite3PagerFile(pPager);
  85377. assert( fd!=0 );
  85378. if( fd->pMethods ){
  85379. rc = sqlite3OsFileControl(fd, op, pArg);
  85380. }
  85381. sqlite3BtreeLeave(pBtree);
  85382. }
  85383. }
  85384. sqlite3_mutex_leave(db->mutex);
  85385. return rc;
  85386. }
  85387. /*
  85388. ** Interface to the testing logic.
  85389. */
  85390. SQLITE_API int sqlite3_test_control(int op, ...){
  85391. int rc = 0;
  85392. #ifndef SQLITE_OMIT_BUILTIN_TEST
  85393. va_list ap;
  85394. va_start(ap, op);
  85395. switch( op ){
  85396. /*
  85397. ** Save the current state of the PRNG.
  85398. */
  85399. case SQLITE_TESTCTRL_PRNG_SAVE: {
  85400. sqlite3PrngSaveState();
  85401. break;
  85402. }
  85403. /*
  85404. ** Restore the state of the PRNG to the last state saved using
  85405. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  85406. ** this verb acts like PRNG_RESET.
  85407. */
  85408. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  85409. sqlite3PrngRestoreState();
  85410. break;
  85411. }
  85412. /*
  85413. ** Reset the PRNG back to its uninitialized state. The next call
  85414. ** to sqlite3_randomness() will reseed the PRNG using a single call
  85415. ** to the xRandomness method of the default VFS.
  85416. */
  85417. case SQLITE_TESTCTRL_PRNG_RESET: {
  85418. sqlite3PrngResetState();
  85419. break;
  85420. }
  85421. /*
  85422. ** sqlite3_test_control(BITVEC_TEST, size, program)
  85423. **
  85424. ** Run a test against a Bitvec object of size. The program argument
  85425. ** is an array of integers that defines the test. Return -1 on a
  85426. ** memory allocation error, 0 on success, or non-zero for an error.
  85427. ** See the sqlite3BitvecBuiltinTest() for additional information.
  85428. */
  85429. case SQLITE_TESTCTRL_BITVEC_TEST: {
  85430. int sz = va_arg(ap, int);
  85431. int *aProg = va_arg(ap, int*);
  85432. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  85433. break;
  85434. }
  85435. /*
  85436. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  85437. **
  85438. ** Register hooks to call to indicate which malloc() failures
  85439. ** are benign.
  85440. */
  85441. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  85442. typedef void (*void_function)(void);
  85443. void_function xBenignBegin;
  85444. void_function xBenignEnd;
  85445. xBenignBegin = va_arg(ap, void_function);
  85446. xBenignEnd = va_arg(ap, void_function);
  85447. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  85448. break;
  85449. }
  85450. /*
  85451. ** sqlite3_test_control(PENDING_BYTE, unsigned int X)
  85452. **
  85453. ** Set the PENDING byte to the value in the argument, if X>0.
  85454. ** Make no changes if X==0. Return the value of the pending byte
  85455. ** as it existing before this routine was called.
  85456. **
  85457. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  85458. ** an incompatible database file format. Changing the PENDING byte
  85459. ** while any database connection is open results in undefined and
  85460. ** dileterious behavior.
  85461. */
  85462. case SQLITE_TESTCTRL_PENDING_BYTE: {
  85463. unsigned int newVal = va_arg(ap, unsigned int);
  85464. rc = sqlite3PendingByte;
  85465. if( newVal ) sqlite3PendingByte = newVal;
  85466. break;
  85467. }
  85468. }
  85469. va_end(ap);
  85470. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  85471. return rc;
  85472. }
  85473. /************** End of main.c ************************************************/
  85474. /************** Begin file notify.c ******************************************/
  85475. /*
  85476. ** 2009 March 3
  85477. **
  85478. ** The author disclaims copyright to this source code. In place of
  85479. ** a legal notice, here is a blessing:
  85480. **
  85481. ** May you do good and not evil.
  85482. ** May you find forgiveness for yourself and forgive others.
  85483. ** May you share freely, never taking more than you give.
  85484. **
  85485. *************************************************************************
  85486. **
  85487. ** This file contains the implementation of the sqlite3_unlock_notify()
  85488. ** API method and its associated functionality.
  85489. **
  85490. ** $Id: notify.c,v 1.4 2009/04/07 22:06:57 drh Exp $
  85491. */
  85492. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  85493. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  85494. /*
  85495. ** Public interfaces:
  85496. **
  85497. ** sqlite3ConnectionBlocked()
  85498. ** sqlite3ConnectionUnlocked()
  85499. ** sqlite3ConnectionClosed()
  85500. ** sqlite3_unlock_notify()
  85501. */
  85502. #define assertMutexHeld() \
  85503. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  85504. /*
  85505. ** Head of a linked list of all sqlite3 objects created by this process
  85506. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  85507. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  85508. ** mutex is held.
  85509. */
  85510. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  85511. #ifndef NDEBUG
  85512. /*
  85513. ** This function is a complex assert() that verifies the following
  85514. ** properties of the blocked connections list:
  85515. **
  85516. ** 1) Each entry in the list has a non-NULL value for either
  85517. ** pUnlockConnection or pBlockingConnection, or both.
  85518. **
  85519. ** 2) All entries in the list that share a common value for
  85520. ** xUnlockNotify are grouped together.
  85521. **
  85522. ** 3) If the argument db is not NULL, then none of the entries in the
  85523. ** blocked connections list have pUnlockConnection or pBlockingConnection
  85524. ** set to db. This is used when closing connection db.
  85525. */
  85526. static void checkListProperties(sqlite3 *db){
  85527. sqlite3 *p;
  85528. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  85529. int seen = 0;
  85530. sqlite3 *p2;
  85531. /* Verify property (1) */
  85532. assert( p->pUnlockConnection || p->pBlockingConnection );
  85533. /* Verify property (2) */
  85534. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  85535. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  85536. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  85537. assert( db==0 || p->pUnlockConnection!=db );
  85538. assert( db==0 || p->pBlockingConnection!=db );
  85539. }
  85540. }
  85541. }
  85542. #else
  85543. # define checkListProperties(x)
  85544. #endif
  85545. /*
  85546. ** Remove connection db from the blocked connections list. If connection
  85547. ** db is not currently a part of the list, this function is a no-op.
  85548. */
  85549. static void removeFromBlockedList(sqlite3 *db){
  85550. sqlite3 **pp;
  85551. assertMutexHeld();
  85552. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  85553. if( *pp==db ){
  85554. *pp = (*pp)->pNextBlocked;
  85555. break;
  85556. }
  85557. }
  85558. }
  85559. /*
  85560. ** Add connection db to the blocked connections list. It is assumed
  85561. ** that it is not already a part of the list.
  85562. */
  85563. static void addToBlockedList(sqlite3 *db){
  85564. sqlite3 **pp;
  85565. assertMutexHeld();
  85566. for(
  85567. pp=&sqlite3BlockedList;
  85568. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  85569. pp=&(*pp)->pNextBlocked
  85570. );
  85571. db->pNextBlocked = *pp;
  85572. *pp = db;
  85573. }
  85574. /*
  85575. ** Obtain the STATIC_MASTER mutex.
  85576. */
  85577. static void enterMutex(void){
  85578. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  85579. checkListProperties(0);
  85580. }
  85581. /*
  85582. ** Release the STATIC_MASTER mutex.
  85583. */
  85584. static void leaveMutex(void){
  85585. assertMutexHeld();
  85586. checkListProperties(0);
  85587. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  85588. }
  85589. /*
  85590. ** Register an unlock-notify callback.
  85591. **
  85592. ** This is called after connection "db" has attempted some operation
  85593. ** but has received an SQLITE_LOCKED error because another connection
  85594. ** (call it pOther) in the same process was busy using the same shared
  85595. ** cache. pOther is found by looking at db->pBlockingConnection.
  85596. **
  85597. ** If there is no blocking connection, the callback is invoked immediately,
  85598. ** before this routine returns.
  85599. **
  85600. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  85601. ** a deadlock.
  85602. **
  85603. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  85604. ** its locks.
  85605. **
  85606. ** Each call to this routine overrides any prior callbacks registered
  85607. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  85608. ** cancelled.
  85609. */
  85610. SQLITE_API int sqlite3_unlock_notify(
  85611. sqlite3 *db,
  85612. void (*xNotify)(void **, int),
  85613. void *pArg
  85614. ){
  85615. int rc = SQLITE_OK;
  85616. sqlite3_mutex_enter(db->mutex);
  85617. enterMutex();
  85618. if( xNotify==0 ){
  85619. removeFromBlockedList(db);
  85620. db->pUnlockConnection = 0;
  85621. db->xUnlockNotify = 0;
  85622. db->pUnlockArg = 0;
  85623. }else if( 0==db->pBlockingConnection ){
  85624. /* The blocking transaction has been concluded. Or there never was a
  85625. ** blocking transaction. In either case, invoke the notify callback
  85626. ** immediately.
  85627. */
  85628. xNotify(&pArg, 1);
  85629. }else{
  85630. sqlite3 *p;
  85631. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  85632. if( p ){
  85633. rc = SQLITE_LOCKED; /* Deadlock detected. */
  85634. }else{
  85635. db->pUnlockConnection = db->pBlockingConnection;
  85636. db->xUnlockNotify = xNotify;
  85637. db->pUnlockArg = pArg;
  85638. removeFromBlockedList(db);
  85639. addToBlockedList(db);
  85640. }
  85641. }
  85642. leaveMutex();
  85643. assert( !db->mallocFailed );
  85644. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  85645. sqlite3_mutex_leave(db->mutex);
  85646. return rc;
  85647. }
  85648. /*
  85649. ** This function is called while stepping or preparing a statement
  85650. ** associated with connection db. The operation will return SQLITE_LOCKED
  85651. ** to the user because it requires a lock that will not be available
  85652. ** until connection pBlocker concludes its current transaction.
  85653. */
  85654. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  85655. enterMutex();
  85656. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  85657. addToBlockedList(db);
  85658. }
  85659. db->pBlockingConnection = pBlocker;
  85660. leaveMutex();
  85661. }
  85662. /*
  85663. ** This function is called when
  85664. ** the transaction opened by database db has just finished. Locks held
  85665. ** by database connection db have been released.
  85666. **
  85667. ** This function loops through each entry in the blocked connections
  85668. ** list and does the following:
  85669. **
  85670. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  85671. ** set to db, then set pBlockingConnection=0.
  85672. **
  85673. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  85674. ** set to db, then invoke the configured unlock-notify callback and
  85675. ** set pUnlockConnection=0.
  85676. **
  85677. ** 3) If the two steps above mean that pBlockingConnection==0 and
  85678. ** pUnlockConnection==0, remove the entry from the blocked connections
  85679. ** list.
  85680. */
  85681. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  85682. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  85683. int nArg = 0; /* Number of entries in aArg[] */
  85684. sqlite3 **pp; /* Iterator variable */
  85685. void **aArg; /* Arguments to the unlock callback */
  85686. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  85687. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  85688. aArg = aStatic;
  85689. enterMutex(); /* Enter STATIC_MASTER mutex */
  85690. /* This loop runs once for each entry in the blocked-connections list. */
  85691. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  85692. sqlite3 *p = *pp;
  85693. /* Step 1. */
  85694. if( p->pBlockingConnection==db ){
  85695. p->pBlockingConnection = 0;
  85696. }
  85697. /* Step 2. */
  85698. if( p->pUnlockConnection==db ){
  85699. assert( p->xUnlockNotify );
  85700. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  85701. xUnlockNotify(aArg, nArg);
  85702. nArg = 0;
  85703. }
  85704. sqlite3BeginBenignMalloc();
  85705. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  85706. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  85707. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  85708. || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
  85709. ){
  85710. /* The aArg[] array needs to grow. */
  85711. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  85712. if( pNew ){
  85713. memcpy(pNew, aArg, nArg*sizeof(void *));
  85714. sqlite3_free(aDyn);
  85715. aDyn = aArg = pNew;
  85716. }else{
  85717. /* This occurs when the array of context pointers that need to
  85718. ** be passed to the unlock-notify callback is larger than the
  85719. ** aStatic[] array allocated on the stack and the attempt to
  85720. ** allocate a larger array from the heap has failed.
  85721. **
  85722. ** This is a difficult situation to handle. Returning an error
  85723. ** code to the caller is insufficient, as even if an error code
  85724. ** is returned the transaction on connection db will still be
  85725. ** closed and the unlock-notify callbacks on blocked connections
  85726. ** will go unissued. This might cause the application to wait
  85727. ** indefinitely for an unlock-notify callback that will never
  85728. ** arrive.
  85729. **
  85730. ** Instead, invoke the unlock-notify callback with the context
  85731. ** array already accumulated. We can then clear the array and
  85732. ** begin accumulating any further context pointers without
  85733. ** requiring any dynamic allocation. This is sub-optimal because
  85734. ** it means that instead of one callback with a large array of
  85735. ** context pointers the application will receive two or more
  85736. ** callbacks with smaller arrays of context pointers, which will
  85737. ** reduce the applications ability to prioritize multiple
  85738. ** connections. But it is the best that can be done under the
  85739. ** circumstances.
  85740. */
  85741. xUnlockNotify(aArg, nArg);
  85742. nArg = 0;
  85743. }
  85744. }
  85745. sqlite3EndBenignMalloc();
  85746. aArg[nArg++] = p->pUnlockArg;
  85747. xUnlockNotify = p->xUnlockNotify;
  85748. p->pUnlockConnection = 0;
  85749. p->xUnlockNotify = 0;
  85750. p->pUnlockArg = 0;
  85751. }
  85752. /* Step 3. */
  85753. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  85754. /* Remove connection p from the blocked connections list. */
  85755. *pp = p->pNextBlocked;
  85756. p->pNextBlocked = 0;
  85757. }else{
  85758. pp = &p->pNextBlocked;
  85759. }
  85760. }
  85761. if( nArg!=0 ){
  85762. xUnlockNotify(aArg, nArg);
  85763. }
  85764. sqlite3_free(aDyn);
  85765. leaveMutex(); /* Leave STATIC_MASTER mutex */
  85766. }
  85767. /*
  85768. ** This is called when the database connection passed as an argument is
  85769. ** being closed. The connection is removed from the blocked list.
  85770. */
  85771. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  85772. sqlite3ConnectionUnlocked(db);
  85773. enterMutex();
  85774. removeFromBlockedList(db);
  85775. checkListProperties(db);
  85776. leaveMutex();
  85777. }
  85778. #endif
  85779. /************** End of notify.c **********************************************/
  85780. /************** Begin file fts3.c ********************************************/
  85781. /*
  85782. ** 2006 Oct 10
  85783. **
  85784. ** The author disclaims copyright to this source code. In place of
  85785. ** a legal notice, here is a blessing:
  85786. **
  85787. ** May you do good and not evil.
  85788. ** May you find forgiveness for yourself and forgive others.
  85789. ** May you share freely, never taking more than you give.
  85790. **
  85791. ******************************************************************************
  85792. **
  85793. ** This is an SQLite module implementing full-text search.
  85794. */
  85795. /*
  85796. ** The code in this file is only compiled if:
  85797. **
  85798. ** * The FTS3 module is being built as an extension
  85799. ** (in which case SQLITE_CORE is not defined), or
  85800. **
  85801. ** * The FTS3 module is being built into the core of
  85802. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  85803. */
  85804. /* TODO(shess) Consider exporting this comment to an HTML file or the
  85805. ** wiki.
  85806. */
  85807. /* The full-text index is stored in a series of b+tree (-like)
  85808. ** structures called segments which map terms to doclists. The
  85809. ** structures are like b+trees in layout, but are constructed from the
  85810. ** bottom up in optimal fashion and are not updatable. Since trees
  85811. ** are built from the bottom up, things will be described from the
  85812. ** bottom up.
  85813. **
  85814. **
  85815. **** Varints ****
  85816. ** The basic unit of encoding is a variable-length integer called a
  85817. ** varint. We encode variable-length integers in little-endian order
  85818. ** using seven bits * per byte as follows:
  85819. **
  85820. ** KEY:
  85821. ** A = 0xxxxxxx 7 bits of data and one flag bit
  85822. ** B = 1xxxxxxx 7 bits of data and one flag bit
  85823. **
  85824. ** 7 bits - A
  85825. ** 14 bits - BA
  85826. ** 21 bits - BBA
  85827. ** and so on.
  85828. **
  85829. ** This is identical to how sqlite encodes varints (see util.c).
  85830. **
  85831. **
  85832. **** Document lists ****
  85833. ** A doclist (document list) holds a docid-sorted list of hits for a
  85834. ** given term. Doclists hold docids, and can optionally associate
  85835. ** token positions and offsets with docids.
  85836. **
  85837. ** A DL_POSITIONS_OFFSETS doclist is stored like this:
  85838. **
  85839. ** array {
  85840. ** varint docid;
  85841. ** array { (position list for column 0)
  85842. ** varint position; (delta from previous position plus POS_BASE)
  85843. ** varint startOffset; (delta from previous startOffset)
  85844. ** varint endOffset; (delta from startOffset)
  85845. ** }
  85846. ** array {
  85847. ** varint POS_COLUMN; (marks start of position list for new column)
  85848. ** varint column; (index of new column)
  85849. ** array {
  85850. ** varint position; (delta from previous position plus POS_BASE)
  85851. ** varint startOffset;(delta from previous startOffset)
  85852. ** varint endOffset; (delta from startOffset)
  85853. ** }
  85854. ** }
  85855. ** varint POS_END; (marks end of positions for this document.
  85856. ** }
  85857. **
  85858. ** Here, array { X } means zero or more occurrences of X, adjacent in
  85859. ** memory. A "position" is an index of a token in the token stream
  85860. ** generated by the tokenizer, while an "offset" is a byte offset,
  85861. ** both based at 0. Note that POS_END and POS_COLUMN occur in the
  85862. ** same logical place as the position element, and act as sentinals
  85863. ** ending a position list array.
  85864. **
  85865. ** A DL_POSITIONS doclist omits the startOffset and endOffset
  85866. ** information. A DL_DOCIDS doclist omits both the position and
  85867. ** offset information, becoming an array of varint-encoded docids.
  85868. **
  85869. ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
  85870. ** the type. Due to how deletion is implemented in the segmentation
  85871. ** system, on-disk doclists MUST store at least positions.
  85872. **
  85873. **
  85874. **** Segment leaf nodes ****
  85875. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  85876. ** nodes are written using LeafWriter, and read using LeafReader (to
  85877. ** iterate through a single leaf node's data) and LeavesReader (to
  85878. ** iterate through a segment's entire leaf layer). Leaf nodes have
  85879. ** the format:
  85880. **
  85881. ** varint iHeight; (height from leaf level, always 0)
  85882. ** varint nTerm; (length of first term)
  85883. ** char pTerm[nTerm]; (content of first term)
  85884. ** varint nDoclist; (length of term's associated doclist)
  85885. ** char pDoclist[nDoclist]; (content of doclist)
  85886. ** array {
  85887. ** (further terms are delta-encoded)
  85888. ** varint nPrefix; (length of prefix shared with previous term)
  85889. ** varint nSuffix; (length of unshared suffix)
  85890. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  85891. ** varint nDoclist; (length of term's associated doclist)
  85892. ** char pDoclist[nDoclist]; (content of doclist)
  85893. ** }
  85894. **
  85895. ** Here, array { X } means zero or more occurrences of X, adjacent in
  85896. ** memory.
  85897. **
  85898. ** Leaf nodes are broken into blocks which are stored contiguously in
  85899. ** the %_segments table in sorted order. This means that when the end
  85900. ** of a node is reached, the next term is in the node with the next
  85901. ** greater node id.
  85902. **
  85903. ** New data is spilled to a new leaf node when the current node
  85904. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  85905. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  85906. ** node (a leaf node with a single term and doclist). The goal of
  85907. ** these settings is to pack together groups of small doclists while
  85908. ** making it efficient to directly access large doclists. The
  85909. ** assumption is that large doclists represent terms which are more
  85910. ** likely to be query targets.
  85911. **
  85912. ** TODO(shess) It may be useful for blocking decisions to be more
  85913. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  85914. ** node rather than splitting into 2k and .5k nodes. My intuition is
  85915. ** that this might extend through 2x or 4x the pagesize.
  85916. **
  85917. **
  85918. **** Segment interior nodes ****
  85919. ** Segment interior nodes store blockids for subtree nodes and terms
  85920. ** to describe what data is stored by the each subtree. Interior
  85921. ** nodes are written using InteriorWriter, and read using
  85922. ** InteriorReader. InteriorWriters are created as needed when
  85923. ** SegmentWriter creates new leaf nodes, or when an interior node
  85924. ** itself grows too big and must be split. The format of interior
  85925. ** nodes:
  85926. **
  85927. ** varint iHeight; (height from leaf level, always >0)
  85928. ** varint iBlockid; (block id of node's leftmost subtree)
  85929. ** optional {
  85930. ** varint nTerm; (length of first term)
  85931. ** char pTerm[nTerm]; (content of first term)
  85932. ** array {
  85933. ** (further terms are delta-encoded)
  85934. ** varint nPrefix; (length of shared prefix with previous term)
  85935. ** varint nSuffix; (length of unshared suffix)
  85936. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  85937. ** }
  85938. ** }
  85939. **
  85940. ** Here, optional { X } means an optional element, while array { X }
  85941. ** means zero or more occurrences of X, adjacent in memory.
  85942. **
  85943. ** An interior node encodes n terms separating n+1 subtrees. The
  85944. ** subtree blocks are contiguous, so only the first subtree's blockid
  85945. ** is encoded. The subtree at iBlockid will contain all terms less
  85946. ** than the first term encoded (or all terms if no term is encoded).
  85947. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  85948. ** than pTerm[i+1], the subtree for that term will be rooted at
  85949. ** iBlockid+i. Interior nodes only store enough term data to
  85950. ** distinguish adjacent children (if the rightmost term of the left
  85951. ** child is "something", and the leftmost term of the right child is
  85952. ** "wicked", only "w" is stored).
  85953. **
  85954. ** New data is spilled to a new interior node at the same height when
  85955. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  85956. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  85957. ** interior nodes and making the tree too skinny. The interior nodes
  85958. ** at a given height are naturally tracked by interior nodes at
  85959. ** height+1, and so on.
  85960. **
  85961. **
  85962. **** Segment directory ****
  85963. ** The segment directory in table %_segdir stores meta-information for
  85964. ** merging and deleting segments, and also the root node of the
  85965. ** segment's tree.
  85966. **
  85967. ** The root node is the top node of the segment's tree after encoding
  85968. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  85969. ** This could be either a leaf node or an interior node. If the top
  85970. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  85971. ** and a new root interior node is generated (which should always fit
  85972. ** within ROOT_MAX because it only needs space for 2 varints, the
  85973. ** height and the blockid of the previous root).
  85974. **
  85975. ** The meta-information in the segment directory is:
  85976. ** level - segment level (see below)
  85977. ** idx - index within level
  85978. ** - (level,idx uniquely identify a segment)
  85979. ** start_block - first leaf node
  85980. ** leaves_end_block - last leaf node
  85981. ** end_block - last block (including interior nodes)
  85982. ** root - contents of root node
  85983. **
  85984. ** If the root node is a leaf node, then start_block,
  85985. ** leaves_end_block, and end_block are all 0.
  85986. **
  85987. **
  85988. **** Segment merging ****
  85989. ** To amortize update costs, segments are grouped into levels and
  85990. ** merged in batches. Each increase in level represents exponentially
  85991. ** more documents.
  85992. **
  85993. ** New documents (actually, document updates) are tokenized and
  85994. ** written individually (using LeafWriter) to a level 0 segment, with
  85995. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  85996. ** level 0 segments are merged into a single level 1 segment. Level 1
  85997. ** is populated like level 0, and eventually MERGE_COUNT level 1
  85998. ** segments are merged to a single level 2 segment (representing
  85999. ** MERGE_COUNT^2 updates), and so on.
  86000. **
  86001. ** A segment merge traverses all segments at a given level in
  86002. ** parallel, performing a straightforward sorted merge. Since segment
  86003. ** leaf nodes are written in to the %_segments table in order, this
  86004. ** merge traverses the underlying sqlite disk structures efficiently.
  86005. ** After the merge, all segment blocks from the merged level are
  86006. ** deleted.
  86007. **
  86008. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  86009. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  86010. ** very similar performance numbers to 16 on insertion, though they're
  86011. ** a tiny bit slower (perhaps due to more overhead in merge-time
  86012. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  86013. ** 16, 2 about 66% slower than 16.
  86014. **
  86015. ** At query time, high MERGE_COUNT increases the number of segments
  86016. ** which need to be scanned and merged. For instance, with 100k docs
  86017. ** inserted:
  86018. **
  86019. ** MERGE_COUNT segments
  86020. ** 16 25
  86021. ** 8 12
  86022. ** 4 10
  86023. ** 2 6
  86024. **
  86025. ** This appears to have only a moderate impact on queries for very
  86026. ** frequent terms (which are somewhat dominated by segment merge
  86027. ** costs), and infrequent and non-existent terms still seem to be fast
  86028. ** even with many segments.
  86029. **
  86030. ** TODO(shess) That said, it would be nice to have a better query-side
  86031. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  86032. ** optimizations to things like doclist merging will swing the sweet
  86033. ** spot around.
  86034. **
  86035. **
  86036. **
  86037. **** Handling of deletions and updates ****
  86038. ** Since we're using a segmented structure, with no docid-oriented
  86039. ** index into the term index, we clearly cannot simply update the term
  86040. ** index when a document is deleted or updated. For deletions, we
  86041. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  86042. ** we simply write the new doclist. Segment merges overwrite older
  86043. ** data for a particular docid with newer data, so deletes or updates
  86044. ** will eventually overtake the earlier data and knock it out. The
  86045. ** query logic likewise merges doclists so that newer data knocks out
  86046. ** older data.
  86047. **
  86048. ** TODO(shess) Provide a VACUUM type operation to clear out all
  86049. ** deletions and duplications. This would basically be a forced merge
  86050. ** into a single segment.
  86051. */
  86052. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  86053. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  86054. # define SQLITE_CORE 1
  86055. #endif
  86056. /************** Include fts3_expr.h in the middle of fts3.c ******************/
  86057. /************** Begin file fts3_expr.h ***************************************/
  86058. /*
  86059. ** 2008 Nov 28
  86060. **
  86061. ** The author disclaims copyright to this source code. In place of
  86062. ** a legal notice, here is a blessing:
  86063. **
  86064. ** May you do good and not evil.
  86065. ** May you find forgiveness for yourself and forgive others.
  86066. ** May you share freely, never taking more than you give.
  86067. **
  86068. ******************************************************************************
  86069. **
  86070. */
  86071. /************** Include fts3_tokenizer.h in the middle of fts3_expr.h ********/
  86072. /************** Begin file fts3_tokenizer.h **********************************/
  86073. /*
  86074. ** 2006 July 10
  86075. **
  86076. ** The author disclaims copyright to this source code.
  86077. **
  86078. *************************************************************************
  86079. ** Defines the interface to tokenizers used by fulltext-search. There
  86080. ** are three basic components:
  86081. **
  86082. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  86083. ** interface functions. This is essentially the class structure for
  86084. ** tokenizers.
  86085. **
  86086. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  86087. ** including customization information defined at creation time.
  86088. **
  86089. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  86090. ** tokens from a particular input.
  86091. */
  86092. #ifndef _FTS3_TOKENIZER_H_
  86093. #define _FTS3_TOKENIZER_H_
  86094. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  86095. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  86096. ** we will need a way to register the API consistently.
  86097. */
  86098. /*
  86099. ** Structures used by the tokenizer interface. When a new tokenizer
  86100. ** implementation is registered, the caller provides a pointer to
  86101. ** an sqlite3_tokenizer_module containing pointers to the callback
  86102. ** functions that make up an implementation.
  86103. **
  86104. ** When an fts3 table is created, it passes any arguments passed to
  86105. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  86106. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  86107. ** implementation. The xCreate() function in turn returns an
  86108. ** sqlite3_tokenizer structure representing the specific tokenizer to
  86109. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  86110. **
  86111. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  86112. ** method is called. It returns an sqlite3_tokenizer_cursor object
  86113. ** that may be used to tokenize a specific input buffer based on
  86114. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  86115. ** object.
  86116. */
  86117. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  86118. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  86119. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  86120. struct sqlite3_tokenizer_module {
  86121. /*
  86122. ** Structure version. Should always be set to 0.
  86123. */
  86124. int iVersion;
  86125. /*
  86126. ** Create a new tokenizer. The values in the argv[] array are the
  86127. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  86128. ** TABLE statement that created the fts3 table. For example, if
  86129. ** the following SQL is executed:
  86130. **
  86131. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  86132. **
  86133. ** then argc is set to 2, and the argv[] array contains pointers
  86134. ** to the strings "arg1" and "arg2".
  86135. **
  86136. ** This method should return either SQLITE_OK (0), or an SQLite error
  86137. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  86138. ** to point at the newly created tokenizer structure. The generic
  86139. ** sqlite3_tokenizer.pModule variable should not be initialised by
  86140. ** this callback. The caller will do so.
  86141. */
  86142. int (*xCreate)(
  86143. int argc, /* Size of argv array */
  86144. const char *const*argv, /* Tokenizer argument strings */
  86145. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  86146. );
  86147. /*
  86148. ** Destroy an existing tokenizer. The fts3 module calls this method
  86149. ** exactly once for each successful call to xCreate().
  86150. */
  86151. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  86152. /*
  86153. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  86154. ** is responsible for ensuring that the input buffer remains valid
  86155. ** until the cursor is closed (using the xClose() method).
  86156. */
  86157. int (*xOpen)(
  86158. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  86159. const char *pInput, int nBytes, /* Input buffer */
  86160. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  86161. );
  86162. /*
  86163. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  86164. ** method exactly once for each successful call to xOpen().
  86165. */
  86166. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  86167. /*
  86168. ** Retrieve the next token from the tokenizer cursor pCursor. This
  86169. ** method should either return SQLITE_OK and set the values of the
  86170. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  86171. ** the end of the buffer has been reached, or an SQLite error code.
  86172. **
  86173. ** *ppToken should be set to point at a buffer containing the
  86174. ** normalized version of the token (i.e. after any case-folding and/or
  86175. ** stemming has been performed). *pnBytes should be set to the length
  86176. ** of this buffer in bytes. The input text that generated the token is
  86177. ** identified by the byte offsets returned in *piStartOffset and
  86178. ** *piEndOffset. *piStartOffset should be set to the index of the first
  86179. ** byte of the token in the input buffer. *piEndOffset should be set
  86180. ** to the index of the first byte just past the end of the token in
  86181. ** the input buffer.
  86182. **
  86183. ** The buffer *ppToken is set to point at is managed by the tokenizer
  86184. ** implementation. It is only required to be valid until the next call
  86185. ** to xNext() or xClose().
  86186. */
  86187. /* TODO(shess) current implementation requires pInput to be
  86188. ** nul-terminated. This should either be fixed, or pInput/nBytes
  86189. ** should be converted to zInput.
  86190. */
  86191. int (*xNext)(
  86192. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  86193. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  86194. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  86195. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  86196. int *piPosition /* OUT: Number of tokens returned before this one */
  86197. );
  86198. };
  86199. struct sqlite3_tokenizer {
  86200. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  86201. /* Tokenizer implementations will typically add additional fields */
  86202. };
  86203. struct sqlite3_tokenizer_cursor {
  86204. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  86205. /* Tokenizer implementations will typically add additional fields */
  86206. };
  86207. #endif /* _FTS3_TOKENIZER_H_ */
  86208. /************** End of fts3_tokenizer.h **************************************/
  86209. /************** Continuing where we left off in fts3_expr.h ******************/
  86210. /*
  86211. ** The following describes the syntax supported by the fts3 MATCH
  86212. ** operator in a similar format to that used by the lemon parser
  86213. ** generator. This module does not use actually lemon, it uses a
  86214. ** custom parser.
  86215. **
  86216. ** query ::= andexpr (OR andexpr)*.
  86217. **
  86218. ** andexpr ::= notexpr (AND? notexpr)*.
  86219. **
  86220. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  86221. ** notexpr ::= LP query RP.
  86222. **
  86223. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  86224. **
  86225. ** distance_opt ::= .
  86226. ** distance_opt ::= / INTEGER.
  86227. **
  86228. ** phrase ::= TOKEN.
  86229. ** phrase ::= COLUMN:TOKEN.
  86230. ** phrase ::= "TOKEN TOKEN TOKEN...".
  86231. */
  86232. typedef struct Fts3Expr Fts3Expr;
  86233. typedef struct Fts3Phrase Fts3Phrase;
  86234. /*
  86235. ** A "phrase" is a sequence of one or more tokens that must match in
  86236. ** sequence. A single token is the base case and the most common case.
  86237. ** For a sequence of tokens contained in "...", nToken will be the number
  86238. ** of tokens in the string.
  86239. */
  86240. struct Fts3Phrase {
  86241. int nToken; /* Number of tokens in the phrase */
  86242. int iColumn; /* Index of column this phrase must match */
  86243. int isNot; /* Phrase prefixed by unary not (-) operator */
  86244. struct PhraseToken {
  86245. char *z; /* Text of the token */
  86246. int n; /* Number of bytes in buffer pointed to by z */
  86247. int isPrefix; /* True if token ends in with a "*" character */
  86248. } aToken[1]; /* One entry for each token in the phrase */
  86249. };
  86250. /*
  86251. ** A tree of these objects forms the RHS of a MATCH operator.
  86252. */
  86253. struct Fts3Expr {
  86254. int eType; /* One of the FTSQUERY_XXX values defined below */
  86255. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  86256. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  86257. Fts3Expr *pLeft; /* Left operand */
  86258. Fts3Expr *pRight; /* Right operand */
  86259. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  86260. };
  86261. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, char **, int, int,
  86262. const char *, int, Fts3Expr **);
  86263. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  86264. /*
  86265. ** Candidate values for Fts3Query.eType. Note that the order of the first
  86266. ** four values is in order of precedence when parsing expressions. For
  86267. ** example, the following:
  86268. **
  86269. ** "a OR b AND c NOT d NEAR e"
  86270. **
  86271. ** is equivalent to:
  86272. **
  86273. ** "a OR (b AND (c NOT (d NEAR e)))"
  86274. */
  86275. #define FTSQUERY_NEAR 1
  86276. #define FTSQUERY_NOT 2
  86277. #define FTSQUERY_AND 3
  86278. #define FTSQUERY_OR 4
  86279. #define FTSQUERY_PHRASE 5
  86280. #ifdef SQLITE_TEST
  86281. SQLITE_PRIVATE void sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  86282. #endif
  86283. /************** End of fts3_expr.h *******************************************/
  86284. /************** Continuing where we left off in fts3.c ***********************/
  86285. /************** Include fts3_hash.h in the middle of fts3.c ******************/
  86286. /************** Begin file fts3_hash.h ***************************************/
  86287. /*
  86288. ** 2001 September 22
  86289. **
  86290. ** The author disclaims copyright to this source code. In place of
  86291. ** a legal notice, here is a blessing:
  86292. **
  86293. ** May you do good and not evil.
  86294. ** May you find forgiveness for yourself and forgive others.
  86295. ** May you share freely, never taking more than you give.
  86296. **
  86297. *************************************************************************
  86298. ** This is the header file for the generic hash-table implemenation
  86299. ** used in SQLite. We've modified it slightly to serve as a standalone
  86300. ** hash table implementation for the full-text indexing module.
  86301. **
  86302. */
  86303. #ifndef _FTS3_HASH_H_
  86304. #define _FTS3_HASH_H_
  86305. /* Forward declarations of structures. */
  86306. typedef struct fts3Hash fts3Hash;
  86307. typedef struct fts3HashElem fts3HashElem;
  86308. /* A complete hash table is an instance of the following structure.
  86309. ** The internals of this structure are intended to be opaque -- client
  86310. ** code should not attempt to access or modify the fields of this structure
  86311. ** directly. Change this structure only by using the routines below.
  86312. ** However, many of the "procedures" and "functions" for modifying and
  86313. ** accessing this structure are really macros, so we can't really make
  86314. ** this structure opaque.
  86315. */
  86316. struct fts3Hash {
  86317. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  86318. char copyKey; /* True if copy of key made on insert */
  86319. int count; /* Number of entries in this table */
  86320. fts3HashElem *first; /* The first element of the array */
  86321. int htsize; /* Number of buckets in the hash table */
  86322. struct _fts3ht { /* the hash table */
  86323. int count; /* Number of entries with this hash */
  86324. fts3HashElem *chain; /* Pointer to first entry with this hash */
  86325. } *ht;
  86326. };
  86327. /* Each element in the hash table is an instance of the following
  86328. ** structure. All elements are stored on a single doubly-linked list.
  86329. **
  86330. ** Again, this structure is intended to be opaque, but it can't really
  86331. ** be opaque because it is used by macros.
  86332. */
  86333. struct fts3HashElem {
  86334. fts3HashElem *next, *prev; /* Next and previous elements in the table */
  86335. void *data; /* Data associated with this element */
  86336. void *pKey; int nKey; /* Key associated with this element */
  86337. };
  86338. /*
  86339. ** There are 2 different modes of operation for a hash table:
  86340. **
  86341. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  86342. ** (including the null-terminator, if any). Case
  86343. ** is respected in comparisons.
  86344. **
  86345. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  86346. ** memcmp() is used to compare keys.
  86347. **
  86348. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  86349. */
  86350. #define FTS3_HASH_STRING 1
  86351. #define FTS3_HASH_BINARY 2
  86352. /*
  86353. ** Access routines. To delete, insert a NULL pointer.
  86354. */
  86355. SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
  86356. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
  86357. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
  86358. SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
  86359. /*
  86360. ** Shorthand for the functions above
  86361. */
  86362. #define fts3HashInit sqlite3Fts3HashInit
  86363. #define fts3HashInsert sqlite3Fts3HashInsert
  86364. #define fts3HashFind sqlite3Fts3HashFind
  86365. #define fts3HashClear sqlite3Fts3HashClear
  86366. /*
  86367. ** Macros for looping over all elements of a hash table. The idiom is
  86368. ** like this:
  86369. **
  86370. ** fts3Hash h;
  86371. ** fts3HashElem *p;
  86372. ** ...
  86373. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  86374. ** SomeStructure *pData = fts3HashData(p);
  86375. ** // do something with pData
  86376. ** }
  86377. */
  86378. #define fts3HashFirst(H) ((H)->first)
  86379. #define fts3HashNext(E) ((E)->next)
  86380. #define fts3HashData(E) ((E)->data)
  86381. #define fts3HashKey(E) ((E)->pKey)
  86382. #define fts3HashKeysize(E) ((E)->nKey)
  86383. /*
  86384. ** Number of entries in a hash table
  86385. */
  86386. #define fts3HashCount(H) ((H)->count)
  86387. #endif /* _FTS3_HASH_H_ */
  86388. /************** End of fts3_hash.h *******************************************/
  86389. /************** Continuing where we left off in fts3.c ***********************/
  86390. #ifndef SQLITE_CORE
  86391. SQLITE_EXTENSION_INIT1
  86392. #endif
  86393. /* TODO(shess) MAN, this thing needs some refactoring. At minimum, it
  86394. ** would be nice to order the file better, perhaps something along the
  86395. ** lines of:
  86396. **
  86397. ** - utility functions
  86398. ** - table setup functions
  86399. ** - table update functions
  86400. ** - table query functions
  86401. **
  86402. ** Put the query functions last because they're likely to reference
  86403. ** typedefs or functions from the table update section.
  86404. */
  86405. #if 0
  86406. # define FTSTRACE(A) printf A; fflush(stdout)
  86407. #else
  86408. # define FTSTRACE(A)
  86409. #endif
  86410. /* It is not safe to call isspace(), tolower(), or isalnum() on
  86411. ** hi-bit-set characters. This is the same solution used in the
  86412. ** tokenizer.
  86413. */
  86414. /* TODO(shess) The snippet-generation code should be using the
  86415. ** tokenizer-generated tokens rather than doing its own local
  86416. ** tokenization.
  86417. */
  86418. /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
  86419. static int safe_isspace(char c){
  86420. return (c&0x80)==0 ? isspace(c) : 0;
  86421. }
  86422. static int safe_tolower(char c){
  86423. return (c&0x80)==0 ? tolower(c) : c;
  86424. }
  86425. static int safe_isalnum(char c){
  86426. return (c&0x80)==0 ? isalnum(c) : 0;
  86427. }
  86428. typedef enum DocListType {
  86429. DL_DOCIDS, /* docids only */
  86430. DL_POSITIONS, /* docids + positions */
  86431. DL_POSITIONS_OFFSETS /* docids + positions + offsets */
  86432. } DocListType;
  86433. /*
  86434. ** By default, only positions and not offsets are stored in the doclists.
  86435. ** To change this so that offsets are stored too, compile with
  86436. **
  86437. ** -DDL_DEFAULT=DL_POSITIONS_OFFSETS
  86438. **
  86439. ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
  86440. ** into (no deletes or updates).
  86441. */
  86442. #ifndef DL_DEFAULT
  86443. # define DL_DEFAULT DL_POSITIONS
  86444. #endif
  86445. enum {
  86446. POS_END = 0, /* end of this position list */
  86447. POS_COLUMN, /* followed by new column number */
  86448. POS_BASE
  86449. };
  86450. /* MERGE_COUNT controls how often we merge segments (see comment at
  86451. ** top of file).
  86452. */
  86453. #define MERGE_COUNT 16
  86454. /* utility functions */
  86455. /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
  86456. ** record to prevent errors of the form:
  86457. **
  86458. ** my_function(SomeType *b){
  86459. ** memset(b, '\0', sizeof(b)); // sizeof(b)!=sizeof(*b)
  86460. ** }
  86461. */
  86462. /* TODO(shess) Obvious candidates for a header file. */
  86463. #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
  86464. #ifndef NDEBUG
  86465. # define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
  86466. #else
  86467. # define SCRAMBLE(b)
  86468. #endif
  86469. /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
  86470. #define VARINT_MAX 10
  86471. /* Write a 64-bit variable-length integer to memory starting at p[0].
  86472. * The length of data written will be between 1 and VARINT_MAX bytes.
  86473. * The number of bytes written is returned. */
  86474. static int fts3PutVarint(char *p, sqlite_int64 v){
  86475. unsigned char *q = (unsigned char *) p;
  86476. sqlite_uint64 vu = v;
  86477. do{
  86478. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  86479. vu >>= 7;
  86480. }while( vu!=0 );
  86481. q[-1] &= 0x7f; /* turn off high bit in final byte */
  86482. assert( q - (unsigned char *)p <= VARINT_MAX );
  86483. return (int) (q - (unsigned char *)p);
  86484. }
  86485. /* Read a 64-bit variable-length integer from memory starting at p[0].
  86486. * Return the number of bytes read, or 0 on error.
  86487. * The value is stored in *v. */
  86488. static int fts3GetVarint(const char *p, sqlite_int64 *v){
  86489. const unsigned char *q = (const unsigned char *) p;
  86490. sqlite_uint64 x = 0, y = 1;
  86491. while( (*q & 0x80) == 0x80 ){
  86492. x += y * (*q++ & 0x7f);
  86493. y <<= 7;
  86494. if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */
  86495. assert( 0 );
  86496. return 0;
  86497. }
  86498. }
  86499. x += y * (*q++);
  86500. *v = (sqlite_int64) x;
  86501. return (int) (q - (unsigned char *)p);
  86502. }
  86503. static int fts3GetVarint32(const char *p, int *pi){
  86504. sqlite_int64 i;
  86505. int ret = fts3GetVarint(p, &i);
  86506. *pi = (int) i;
  86507. assert( *pi==i );
  86508. return ret;
  86509. }
  86510. /*******************************************************************/
  86511. /* DataBuffer is used to collect data into a buffer in piecemeal
  86512. ** fashion. It implements the usual distinction between amount of
  86513. ** data currently stored (nData) and buffer capacity (nCapacity).
  86514. **
  86515. ** dataBufferInit - create a buffer with given initial capacity.
  86516. ** dataBufferReset - forget buffer's data, retaining capacity.
  86517. ** dataBufferDestroy - free buffer's data.
  86518. ** dataBufferSwap - swap contents of two buffers.
  86519. ** dataBufferExpand - expand capacity without adding data.
  86520. ** dataBufferAppend - append data.
  86521. ** dataBufferAppend2 - append two pieces of data at once.
  86522. ** dataBufferReplace - replace buffer's data.
  86523. */
  86524. typedef struct DataBuffer {
  86525. char *pData; /* Pointer to malloc'ed buffer. */
  86526. int nCapacity; /* Size of pData buffer. */
  86527. int nData; /* End of data loaded into pData. */
  86528. } DataBuffer;
  86529. static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
  86530. assert( nCapacity>=0 );
  86531. pBuffer->nData = 0;
  86532. pBuffer->nCapacity = nCapacity;
  86533. pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
  86534. }
  86535. static void dataBufferReset(DataBuffer *pBuffer){
  86536. pBuffer->nData = 0;
  86537. }
  86538. static void dataBufferDestroy(DataBuffer *pBuffer){
  86539. if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
  86540. SCRAMBLE(pBuffer);
  86541. }
  86542. static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
  86543. DataBuffer tmp = *pBuffer1;
  86544. *pBuffer1 = *pBuffer2;
  86545. *pBuffer2 = tmp;
  86546. }
  86547. static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
  86548. assert( nAddCapacity>0 );
  86549. /* TODO(shess) Consider expanding more aggressively. Note that the
  86550. ** underlying malloc implementation may take care of such things for
  86551. ** us already.
  86552. */
  86553. if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
  86554. pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
  86555. pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
  86556. }
  86557. }
  86558. static void dataBufferAppend(DataBuffer *pBuffer,
  86559. const char *pSource, int nSource){
  86560. assert( nSource>0 && pSource!=NULL );
  86561. dataBufferExpand(pBuffer, nSource);
  86562. memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
  86563. pBuffer->nData += nSource;
  86564. }
  86565. static void dataBufferAppend2(DataBuffer *pBuffer,
  86566. const char *pSource1, int nSource1,
  86567. const char *pSource2, int nSource2){
  86568. assert( nSource1>0 && pSource1!=NULL );
  86569. assert( nSource2>0 && pSource2!=NULL );
  86570. dataBufferExpand(pBuffer, nSource1+nSource2);
  86571. memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
  86572. memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
  86573. pBuffer->nData += nSource1+nSource2;
  86574. }
  86575. static void dataBufferReplace(DataBuffer *pBuffer,
  86576. const char *pSource, int nSource){
  86577. dataBufferReset(pBuffer);
  86578. dataBufferAppend(pBuffer, pSource, nSource);
  86579. }
  86580. /* StringBuffer is a null-terminated version of DataBuffer. */
  86581. typedef struct StringBuffer {
  86582. DataBuffer b; /* Includes null terminator. */
  86583. } StringBuffer;
  86584. static void initStringBuffer(StringBuffer *sb){
  86585. dataBufferInit(&sb->b, 100);
  86586. dataBufferReplace(&sb->b, "", 1);
  86587. }
  86588. static int stringBufferLength(StringBuffer *sb){
  86589. return sb->b.nData-1;
  86590. }
  86591. static char *stringBufferData(StringBuffer *sb){
  86592. return sb->b.pData;
  86593. }
  86594. static void stringBufferDestroy(StringBuffer *sb){
  86595. dataBufferDestroy(&sb->b);
  86596. }
  86597. static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
  86598. assert( sb->b.nData>0 );
  86599. if( nFrom>0 ){
  86600. sb->b.nData--;
  86601. dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
  86602. }
  86603. }
  86604. static void append(StringBuffer *sb, const char *zFrom){
  86605. nappend(sb, zFrom, strlen(zFrom));
  86606. }
  86607. /* Append a list of strings separated by commas. */
  86608. static void appendList(StringBuffer *sb, int nString, char **azString){
  86609. int i;
  86610. for(i=0; i<nString; ++i){
  86611. if( i>0 ) append(sb, ", ");
  86612. append(sb, azString[i]);
  86613. }
  86614. }
  86615. static int endsInWhiteSpace(StringBuffer *p){
  86616. return stringBufferLength(p)>0 &&
  86617. safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
  86618. }
  86619. /* If the StringBuffer ends in something other than white space, add a
  86620. ** single space character to the end.
  86621. */
  86622. static void appendWhiteSpace(StringBuffer *p){
  86623. if( stringBufferLength(p)==0 ) return;
  86624. if( !endsInWhiteSpace(p) ) append(p, " ");
  86625. }
  86626. /* Remove white space from the end of the StringBuffer */
  86627. static void trimWhiteSpace(StringBuffer *p){
  86628. while( endsInWhiteSpace(p) ){
  86629. p->b.pData[--p->b.nData-1] = '\0';
  86630. }
  86631. }
  86632. /*******************************************************************/
  86633. /* DLReader is used to read document elements from a doclist. The
  86634. ** current docid is cached, so dlrDocid() is fast. DLReader does not
  86635. ** own the doclist buffer.
  86636. **
  86637. ** dlrAtEnd - true if there's no more data to read.
  86638. ** dlrDocid - docid of current document.
  86639. ** dlrDocData - doclist data for current document (including docid).
  86640. ** dlrDocDataBytes - length of same.
  86641. ** dlrAllDataBytes - length of all remaining data.
  86642. ** dlrPosData - position data for current document.
  86643. ** dlrPosDataLen - length of pos data for current document (incl POS_END).
  86644. ** dlrStep - step to current document.
  86645. ** dlrInit - initial for doclist of given type against given data.
  86646. ** dlrDestroy - clean up.
  86647. **
  86648. ** Expected usage is something like:
  86649. **
  86650. ** DLReader reader;
  86651. ** dlrInit(&reader, pData, nData);
  86652. ** while( !dlrAtEnd(&reader) ){
  86653. ** // calls to dlrDocid() and kin.
  86654. ** dlrStep(&reader);
  86655. ** }
  86656. ** dlrDestroy(&reader);
  86657. */
  86658. typedef struct DLReader {
  86659. DocListType iType;
  86660. const char *pData;
  86661. int nData;
  86662. sqlite_int64 iDocid;
  86663. int nElement;
  86664. } DLReader;
  86665. static int dlrAtEnd(DLReader *pReader){
  86666. assert( pReader->nData>=0 );
  86667. return pReader->nData==0;
  86668. }
  86669. static sqlite_int64 dlrDocid(DLReader *pReader){
  86670. assert( !dlrAtEnd(pReader) );
  86671. return pReader->iDocid;
  86672. }
  86673. static const char *dlrDocData(DLReader *pReader){
  86674. assert( !dlrAtEnd(pReader) );
  86675. return pReader->pData;
  86676. }
  86677. static int dlrDocDataBytes(DLReader *pReader){
  86678. assert( !dlrAtEnd(pReader) );
  86679. return pReader->nElement;
  86680. }
  86681. static int dlrAllDataBytes(DLReader *pReader){
  86682. assert( !dlrAtEnd(pReader) );
  86683. return pReader->nData;
  86684. }
  86685. /* TODO(shess) Consider adding a field to track iDocid varint length
  86686. ** to make these two functions faster. This might matter (a tiny bit)
  86687. ** for queries.
  86688. */
  86689. static const char *dlrPosData(DLReader *pReader){
  86690. sqlite_int64 iDummy;
  86691. int n = fts3GetVarint(pReader->pData, &iDummy);
  86692. assert( !dlrAtEnd(pReader) );
  86693. return pReader->pData+n;
  86694. }
  86695. static int dlrPosDataLen(DLReader *pReader){
  86696. sqlite_int64 iDummy;
  86697. int n = fts3GetVarint(pReader->pData, &iDummy);
  86698. assert( !dlrAtEnd(pReader) );
  86699. return pReader->nElement-n;
  86700. }
  86701. static void dlrStep(DLReader *pReader){
  86702. assert( !dlrAtEnd(pReader) );
  86703. /* Skip past current doclist element. */
  86704. assert( pReader->nElement<=pReader->nData );
  86705. pReader->pData += pReader->nElement;
  86706. pReader->nData -= pReader->nElement;
  86707. /* If there is more data, read the next doclist element. */
  86708. if( pReader->nData!=0 ){
  86709. sqlite_int64 iDocidDelta;
  86710. int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
  86711. pReader->iDocid += iDocidDelta;
  86712. if( pReader->iType>=DL_POSITIONS ){
  86713. assert( n<pReader->nData );
  86714. while( 1 ){
  86715. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  86716. assert( n<=pReader->nData );
  86717. if( iDummy==POS_END ) break;
  86718. if( iDummy==POS_COLUMN ){
  86719. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  86720. assert( n<pReader->nData );
  86721. }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
  86722. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  86723. n += fts3GetVarint32(pReader->pData+n, &iDummy);
  86724. assert( n<pReader->nData );
  86725. }
  86726. }
  86727. }
  86728. pReader->nElement = n;
  86729. assert( pReader->nElement<=pReader->nData );
  86730. }
  86731. }
  86732. static void dlrInit(DLReader *pReader, DocListType iType,
  86733. const char *pData, int nData){
  86734. assert( pData!=NULL && nData!=0 );
  86735. pReader->iType = iType;
  86736. pReader->pData = pData;
  86737. pReader->nData = nData;
  86738. pReader->nElement = 0;
  86739. pReader->iDocid = 0;
  86740. /* Load the first element's data. There must be a first element. */
  86741. dlrStep(pReader);
  86742. }
  86743. static void dlrDestroy(DLReader *pReader){
  86744. SCRAMBLE(pReader);
  86745. }
  86746. #ifndef NDEBUG
  86747. /* Verify that the doclist can be validly decoded. Also returns the
  86748. ** last docid found because it is convenient in other assertions for
  86749. ** DLWriter.
  86750. */
  86751. static void docListValidate(DocListType iType, const char *pData, int nData,
  86752. sqlite_int64 *pLastDocid){
  86753. sqlite_int64 iPrevDocid = 0;
  86754. assert( nData>0 );
  86755. assert( pData!=0 );
  86756. assert( pData+nData>pData );
  86757. while( nData!=0 ){
  86758. sqlite_int64 iDocidDelta;
  86759. int n = fts3GetVarint(pData, &iDocidDelta);
  86760. iPrevDocid += iDocidDelta;
  86761. if( iType>DL_DOCIDS ){
  86762. int iDummy;
  86763. while( 1 ){
  86764. n += fts3GetVarint32(pData+n, &iDummy);
  86765. if( iDummy==POS_END ) break;
  86766. if( iDummy==POS_COLUMN ){
  86767. n += fts3GetVarint32(pData+n, &iDummy);
  86768. }else if( iType>DL_POSITIONS ){
  86769. n += fts3GetVarint32(pData+n, &iDummy);
  86770. n += fts3GetVarint32(pData+n, &iDummy);
  86771. }
  86772. assert( n<=nData );
  86773. }
  86774. }
  86775. assert( n<=nData );
  86776. pData += n;
  86777. nData -= n;
  86778. }
  86779. if( pLastDocid ) *pLastDocid = iPrevDocid;
  86780. }
  86781. #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
  86782. #else
  86783. #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
  86784. #endif
  86785. /*******************************************************************/
  86786. /* DLWriter is used to write doclist data to a DataBuffer. DLWriter
  86787. ** always appends to the buffer and does not own it.
  86788. **
  86789. ** dlwInit - initialize to write a given type doclistto a buffer.
  86790. ** dlwDestroy - clear the writer's memory. Does not free buffer.
  86791. ** dlwAppend - append raw doclist data to buffer.
  86792. ** dlwCopy - copy next doclist from reader to writer.
  86793. ** dlwAdd - construct doclist element and append to buffer.
  86794. ** Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
  86795. */
  86796. typedef struct DLWriter {
  86797. DocListType iType;
  86798. DataBuffer *b;
  86799. sqlite_int64 iPrevDocid;
  86800. #ifndef NDEBUG
  86801. int has_iPrevDocid;
  86802. #endif
  86803. } DLWriter;
  86804. static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
  86805. pWriter->b = b;
  86806. pWriter->iType = iType;
  86807. pWriter->iPrevDocid = 0;
  86808. #ifndef NDEBUG
  86809. pWriter->has_iPrevDocid = 0;
  86810. #endif
  86811. }
  86812. static void dlwDestroy(DLWriter *pWriter){
  86813. SCRAMBLE(pWriter);
  86814. }
  86815. /* iFirstDocid is the first docid in the doclist in pData. It is
  86816. ** needed because pData may point within a larger doclist, in which
  86817. ** case the first item would be delta-encoded.
  86818. **
  86819. ** iLastDocid is the final docid in the doclist in pData. It is
  86820. ** needed to create the new iPrevDocid for future delta-encoding. The
  86821. ** code could decode the passed doclist to recreate iLastDocid, but
  86822. ** the only current user (docListMerge) already has decoded this
  86823. ** information.
  86824. */
  86825. /* TODO(shess) This has become just a helper for docListMerge.
  86826. ** Consider a refactor to make this cleaner.
  86827. */
  86828. static void dlwAppend(DLWriter *pWriter,
  86829. const char *pData, int nData,
  86830. sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
  86831. sqlite_int64 iDocid = 0;
  86832. char c[VARINT_MAX];
  86833. int nFirstOld, nFirstNew; /* Old and new varint len of first docid. */
  86834. #ifndef NDEBUG
  86835. sqlite_int64 iLastDocidDelta;
  86836. #endif
  86837. /* Recode the initial docid as delta from iPrevDocid. */
  86838. nFirstOld = fts3GetVarint(pData, &iDocid);
  86839. assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
  86840. nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
  86841. /* Verify that the incoming doclist is valid AND that it ends with
  86842. ** the expected docid. This is essential because we'll trust this
  86843. ** docid in future delta-encoding.
  86844. */
  86845. ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
  86846. assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
  86847. /* Append recoded initial docid and everything else. Rest of docids
  86848. ** should have been delta-encoded from previous initial docid.
  86849. */
  86850. if( nFirstOld<nData ){
  86851. dataBufferAppend2(pWriter->b, c, nFirstNew,
  86852. pData+nFirstOld, nData-nFirstOld);
  86853. }else{
  86854. dataBufferAppend(pWriter->b, c, nFirstNew);
  86855. }
  86856. pWriter->iPrevDocid = iLastDocid;
  86857. }
  86858. static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
  86859. dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
  86860. dlrDocid(pReader), dlrDocid(pReader));
  86861. }
  86862. static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
  86863. char c[VARINT_MAX];
  86864. int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
  86865. /* Docids must ascend. */
  86866. assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
  86867. assert( pWriter->iType==DL_DOCIDS );
  86868. dataBufferAppend(pWriter->b, c, n);
  86869. pWriter->iPrevDocid = iDocid;
  86870. #ifndef NDEBUG
  86871. pWriter->has_iPrevDocid = 1;
  86872. #endif
  86873. }
  86874. /*******************************************************************/
  86875. /* PLReader is used to read data from a document's position list. As
  86876. ** the caller steps through the list, data is cached so that varints
  86877. ** only need to be decoded once.
  86878. **
  86879. ** plrInit, plrDestroy - create/destroy a reader.
  86880. ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
  86881. ** plrAtEnd - at end of stream, only call plrDestroy once true.
  86882. ** plrStep - step to the next element.
  86883. */
  86884. typedef struct PLReader {
  86885. /* These refer to the next position's data. nData will reach 0 when
  86886. ** reading the last position, so plrStep() signals EOF by setting
  86887. ** pData to NULL.
  86888. */
  86889. const char *pData;
  86890. int nData;
  86891. DocListType iType;
  86892. int iColumn; /* the last column read */
  86893. int iPosition; /* the last position read */
  86894. int iStartOffset; /* the last start offset read */
  86895. int iEndOffset; /* the last end offset read */
  86896. } PLReader;
  86897. static int plrAtEnd(PLReader *pReader){
  86898. return pReader->pData==NULL;
  86899. }
  86900. static int plrColumn(PLReader *pReader){
  86901. assert( !plrAtEnd(pReader) );
  86902. return pReader->iColumn;
  86903. }
  86904. static int plrPosition(PLReader *pReader){
  86905. assert( !plrAtEnd(pReader) );
  86906. return pReader->iPosition;
  86907. }
  86908. static int plrStartOffset(PLReader *pReader){
  86909. assert( !plrAtEnd(pReader) );
  86910. return pReader->iStartOffset;
  86911. }
  86912. static int plrEndOffset(PLReader *pReader){
  86913. assert( !plrAtEnd(pReader) );
  86914. return pReader->iEndOffset;
  86915. }
  86916. static void plrStep(PLReader *pReader){
  86917. int i, n;
  86918. assert( !plrAtEnd(pReader) );
  86919. if( pReader->nData==0 ){
  86920. pReader->pData = NULL;
  86921. return;
  86922. }
  86923. n = fts3GetVarint32(pReader->pData, &i);
  86924. if( i==POS_COLUMN ){
  86925. n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
  86926. pReader->iPosition = 0;
  86927. pReader->iStartOffset = 0;
  86928. n += fts3GetVarint32(pReader->pData+n, &i);
  86929. }
  86930. /* Should never see adjacent column changes. */
  86931. assert( i!=POS_COLUMN );
  86932. if( i==POS_END ){
  86933. pReader->nData = 0;
  86934. pReader->pData = NULL;
  86935. return;
  86936. }
  86937. pReader->iPosition += i-POS_BASE;
  86938. if( pReader->iType==DL_POSITIONS_OFFSETS ){
  86939. n += fts3GetVarint32(pReader->pData+n, &i);
  86940. pReader->iStartOffset += i;
  86941. n += fts3GetVarint32(pReader->pData+n, &i);
  86942. pReader->iEndOffset = pReader->iStartOffset+i;
  86943. }
  86944. assert( n<=pReader->nData );
  86945. pReader->pData += n;
  86946. pReader->nData -= n;
  86947. }
  86948. static void plrInit(PLReader *pReader, DLReader *pDLReader){
  86949. pReader->pData = dlrPosData(pDLReader);
  86950. pReader->nData = dlrPosDataLen(pDLReader);
  86951. pReader->iType = pDLReader->iType;
  86952. pReader->iColumn = 0;
  86953. pReader->iPosition = 0;
  86954. pReader->iStartOffset = 0;
  86955. pReader->iEndOffset = 0;
  86956. plrStep(pReader);
  86957. }
  86958. static void plrDestroy(PLReader *pReader){
  86959. SCRAMBLE(pReader);
  86960. }
  86961. /*******************************************************************/
  86962. /* PLWriter is used in constructing a document's position list. As a
  86963. ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
  86964. ** PLWriter writes to the associated DLWriter's buffer.
  86965. **
  86966. ** plwInit - init for writing a document's poslist.
  86967. ** plwDestroy - clear a writer.
  86968. ** plwAdd - append position and offset information.
  86969. ** plwCopy - copy next position's data from reader to writer.
  86970. ** plwTerminate - add any necessary doclist terminator.
  86971. **
  86972. ** Calling plwAdd() after plwTerminate() may result in a corrupt
  86973. ** doclist.
  86974. */
  86975. /* TODO(shess) Until we've written the second item, we can cache the
  86976. ** first item's information. Then we'd have three states:
  86977. **
  86978. ** - initialized with docid, no positions.
  86979. ** - docid and one position.
  86980. ** - docid and multiple positions.
  86981. **
  86982. ** Only the last state needs to actually write to dlw->b, which would
  86983. ** be an improvement in the DLCollector case.
  86984. */
  86985. typedef struct PLWriter {
  86986. DLWriter *dlw;
  86987. int iColumn; /* the last column written */
  86988. int iPos; /* the last position written */
  86989. int iOffset; /* the last start offset written */
  86990. } PLWriter;
  86991. /* TODO(shess) In the case where the parent is reading these values
  86992. ** from a PLReader, we could optimize to a copy if that PLReader has
  86993. ** the same type as pWriter.
  86994. */
  86995. static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
  86996. int iStartOffset, int iEndOffset){
  86997. /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
  86998. ** iStartOffsetDelta, and iEndOffsetDelta.
  86999. */
  87000. char c[5*VARINT_MAX];
  87001. int n = 0;
  87002. /* Ban plwAdd() after plwTerminate(). */
  87003. assert( pWriter->iPos!=-1 );
  87004. if( pWriter->dlw->iType==DL_DOCIDS ) return;
  87005. if( iColumn!=pWriter->iColumn ){
  87006. n += fts3PutVarint(c+n, POS_COLUMN);
  87007. n += fts3PutVarint(c+n, iColumn);
  87008. pWriter->iColumn = iColumn;
  87009. pWriter->iPos = 0;
  87010. pWriter->iOffset = 0;
  87011. }
  87012. assert( iPos>=pWriter->iPos );
  87013. n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
  87014. pWriter->iPos = iPos;
  87015. if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
  87016. assert( iStartOffset>=pWriter->iOffset );
  87017. n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
  87018. pWriter->iOffset = iStartOffset;
  87019. assert( iEndOffset>=iStartOffset );
  87020. n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
  87021. }
  87022. dataBufferAppend(pWriter->dlw->b, c, n);
  87023. }
  87024. static void plwCopy(PLWriter *pWriter, PLReader *pReader){
  87025. plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
  87026. plrStartOffset(pReader), plrEndOffset(pReader));
  87027. }
  87028. static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
  87029. char c[VARINT_MAX];
  87030. int n;
  87031. pWriter->dlw = dlw;
  87032. /* Docids must ascend. */
  87033. assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
  87034. n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
  87035. dataBufferAppend(pWriter->dlw->b, c, n);
  87036. pWriter->dlw->iPrevDocid = iDocid;
  87037. #ifndef NDEBUG
  87038. pWriter->dlw->has_iPrevDocid = 1;
  87039. #endif
  87040. pWriter->iColumn = 0;
  87041. pWriter->iPos = 0;
  87042. pWriter->iOffset = 0;
  87043. }
  87044. /* TODO(shess) Should plwDestroy() also terminate the doclist? But
  87045. ** then plwDestroy() would no longer be just a destructor, it would
  87046. ** also be doing work, which isn't consistent with the overall idiom.
  87047. ** Another option would be for plwAdd() to always append any necessary
  87048. ** terminator, so that the output is always correct. But that would
  87049. ** add incremental work to the common case with the only benefit being
  87050. ** API elegance. Punt for now.
  87051. */
  87052. static void plwTerminate(PLWriter *pWriter){
  87053. if( pWriter->dlw->iType>DL_DOCIDS ){
  87054. char c[VARINT_MAX];
  87055. int n = fts3PutVarint(c, POS_END);
  87056. dataBufferAppend(pWriter->dlw->b, c, n);
  87057. }
  87058. #ifndef NDEBUG
  87059. /* Mark as terminated for assert in plwAdd(). */
  87060. pWriter->iPos = -1;
  87061. #endif
  87062. }
  87063. static void plwDestroy(PLWriter *pWriter){
  87064. SCRAMBLE(pWriter);
  87065. }
  87066. /*******************************************************************/
  87067. /* DLCollector wraps PLWriter and DLWriter to provide a
  87068. ** dynamically-allocated doclist area to use during tokenization.
  87069. **
  87070. ** dlcNew - malloc up and initialize a collector.
  87071. ** dlcDelete - destroy a collector and all contained items.
  87072. ** dlcAddPos - append position and offset information.
  87073. ** dlcAddDoclist - add the collected doclist to the given buffer.
  87074. ** dlcNext - terminate the current document and open another.
  87075. */
  87076. typedef struct DLCollector {
  87077. DataBuffer b;
  87078. DLWriter dlw;
  87079. PLWriter plw;
  87080. } DLCollector;
  87081. /* TODO(shess) This could also be done by calling plwTerminate() and
  87082. ** dataBufferAppend(). I tried that, expecting nominal performance
  87083. ** differences, but it seemed to pretty reliably be worth 1% to code
  87084. ** it this way. I suspect it is the incremental malloc overhead (some
  87085. ** percentage of the plwTerminate() calls will cause a realloc), so
  87086. ** this might be worth revisiting if the DataBuffer implementation
  87087. ** changes.
  87088. */
  87089. static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
  87090. if( pCollector->dlw.iType>DL_DOCIDS ){
  87091. char c[VARINT_MAX];
  87092. int n = fts3PutVarint(c, POS_END);
  87093. dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
  87094. }else{
  87095. dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
  87096. }
  87097. }
  87098. static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
  87099. plwTerminate(&pCollector->plw);
  87100. plwDestroy(&pCollector->plw);
  87101. plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  87102. }
  87103. static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
  87104. int iStartOffset, int iEndOffset){
  87105. plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
  87106. }
  87107. static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
  87108. DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
  87109. dataBufferInit(&pCollector->b, 0);
  87110. dlwInit(&pCollector->dlw, iType, &pCollector->b);
  87111. plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  87112. return pCollector;
  87113. }
  87114. static void dlcDelete(DLCollector *pCollector){
  87115. plwDestroy(&pCollector->plw);
  87116. dlwDestroy(&pCollector->dlw);
  87117. dataBufferDestroy(&pCollector->b);
  87118. SCRAMBLE(pCollector);
  87119. sqlite3_free(pCollector);
  87120. }
  87121. /* Copy the doclist data of iType in pData/nData into *out, trimming
  87122. ** unnecessary data as we go. Only columns matching iColumn are
  87123. ** copied, all columns copied if iColumn is -1. Elements with no
  87124. ** matching columns are dropped. The output is an iOutType doclist.
  87125. */
  87126. /* NOTE(shess) This code is only valid after all doclists are merged.
  87127. ** If this is run before merges, then doclist items which represent
  87128. ** deletion will be trimmed, and will thus not effect a deletion
  87129. ** during the merge.
  87130. */
  87131. static void docListTrim(DocListType iType, const char *pData, int nData,
  87132. int iColumn, DocListType iOutType, DataBuffer *out){
  87133. DLReader dlReader;
  87134. DLWriter dlWriter;
  87135. assert( iOutType<=iType );
  87136. dlrInit(&dlReader, iType, pData, nData);
  87137. dlwInit(&dlWriter, iOutType, out);
  87138. while( !dlrAtEnd(&dlReader) ){
  87139. PLReader plReader;
  87140. PLWriter plWriter;
  87141. int match = 0;
  87142. plrInit(&plReader, &dlReader);
  87143. while( !plrAtEnd(&plReader) ){
  87144. if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
  87145. if( !match ){
  87146. plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
  87147. match = 1;
  87148. }
  87149. plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
  87150. plrStartOffset(&plReader), plrEndOffset(&plReader));
  87151. }
  87152. plrStep(&plReader);
  87153. }
  87154. if( match ){
  87155. plwTerminate(&plWriter);
  87156. plwDestroy(&plWriter);
  87157. }
  87158. plrDestroy(&plReader);
  87159. dlrStep(&dlReader);
  87160. }
  87161. dlwDestroy(&dlWriter);
  87162. dlrDestroy(&dlReader);
  87163. }
  87164. /* Used by docListMerge() to keep doclists in the ascending order by
  87165. ** docid, then ascending order by age (so the newest comes first).
  87166. */
  87167. typedef struct OrderedDLReader {
  87168. DLReader *pReader;
  87169. /* TODO(shess) If we assume that docListMerge pReaders is ordered by
  87170. ** age (which we do), then we could use pReader comparisons to break
  87171. ** ties.
  87172. */
  87173. int idx;
  87174. } OrderedDLReader;
  87175. /* Order eof to end, then by docid asc, idx desc. */
  87176. static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
  87177. if( dlrAtEnd(r1->pReader) ){
  87178. if( dlrAtEnd(r2->pReader) ) return 0; /* Both atEnd(). */
  87179. return 1; /* Only r1 atEnd(). */
  87180. }
  87181. if( dlrAtEnd(r2->pReader) ) return -1; /* Only r2 atEnd(). */
  87182. if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
  87183. if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
  87184. /* Descending on idx. */
  87185. return r2->idx-r1->idx;
  87186. }
  87187. /* Bubble p[0] to appropriate place in p[1..n-1]. Assumes that
  87188. ** p[1..n-1] is already sorted.
  87189. */
  87190. /* TODO(shess) Is this frequent enough to warrant a binary search?
  87191. ** Before implementing that, instrument the code to check. In most
  87192. ** current usage, I expect that p[0] will be less than p[1] a very
  87193. ** high proportion of the time.
  87194. */
  87195. static void orderedDLReaderReorder(OrderedDLReader *p, int n){
  87196. while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
  87197. OrderedDLReader tmp = p[0];
  87198. p[0] = p[1];
  87199. p[1] = tmp;
  87200. n--;
  87201. p++;
  87202. }
  87203. }
  87204. /* Given an array of doclist readers, merge their doclist elements
  87205. ** into out in sorted order (by docid), dropping elements from older
  87206. ** readers when there is a duplicate docid. pReaders is assumed to be
  87207. ** ordered by age, oldest first.
  87208. */
  87209. /* TODO(shess) nReaders must be <= MERGE_COUNT. This should probably
  87210. ** be fixed.
  87211. */
  87212. static void docListMerge(DataBuffer *out,
  87213. DLReader *pReaders, int nReaders){
  87214. OrderedDLReader readers[MERGE_COUNT];
  87215. DLWriter writer;
  87216. int i, n;
  87217. const char *pStart = 0;
  87218. int nStart = 0;
  87219. sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
  87220. assert( nReaders>0 );
  87221. if( nReaders==1 ){
  87222. dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
  87223. return;
  87224. }
  87225. assert( nReaders<=MERGE_COUNT );
  87226. n = 0;
  87227. for(i=0; i<nReaders; i++){
  87228. assert( pReaders[i].iType==pReaders[0].iType );
  87229. readers[i].pReader = pReaders+i;
  87230. readers[i].idx = i;
  87231. n += dlrAllDataBytes(&pReaders[i]);
  87232. }
  87233. /* Conservatively size output to sum of inputs. Output should end
  87234. ** up strictly smaller than input.
  87235. */
  87236. dataBufferExpand(out, n);
  87237. /* Get the readers into sorted order. */
  87238. while( i-->0 ){
  87239. orderedDLReaderReorder(readers+i, nReaders-i);
  87240. }
  87241. dlwInit(&writer, pReaders[0].iType, out);
  87242. while( !dlrAtEnd(readers[0].pReader) ){
  87243. sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
  87244. /* If this is a continuation of the current buffer to copy, extend
  87245. ** that buffer. memcpy() seems to be more efficient if it has a
  87246. ** lots of data to copy.
  87247. */
  87248. if( dlrDocData(readers[0].pReader)==pStart+nStart ){
  87249. nStart += dlrDocDataBytes(readers[0].pReader);
  87250. }else{
  87251. if( pStart!=0 ){
  87252. dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  87253. }
  87254. pStart = dlrDocData(readers[0].pReader);
  87255. nStart = dlrDocDataBytes(readers[0].pReader);
  87256. iFirstDocid = iDocid;
  87257. }
  87258. iLastDocid = iDocid;
  87259. dlrStep(readers[0].pReader);
  87260. /* Drop all of the older elements with the same docid. */
  87261. for(i=1; i<nReaders &&
  87262. !dlrAtEnd(readers[i].pReader) &&
  87263. dlrDocid(readers[i].pReader)==iDocid; i++){
  87264. dlrStep(readers[i].pReader);
  87265. }
  87266. /* Get the readers back into order. */
  87267. while( i-->0 ){
  87268. orderedDLReaderReorder(readers+i, nReaders-i);
  87269. }
  87270. }
  87271. /* Copy over any remaining elements. */
  87272. if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  87273. dlwDestroy(&writer);
  87274. }
  87275. /* Helper function for posListUnion(). Compares the current position
  87276. ** between left and right, returning as standard C idiom of <0 if
  87277. ** left<right, >0 if left>right, and 0 if left==right. "End" always
  87278. ** compares greater.
  87279. */
  87280. static int posListCmp(PLReader *pLeft, PLReader *pRight){
  87281. assert( pLeft->iType==pRight->iType );
  87282. if( pLeft->iType==DL_DOCIDS ) return 0;
  87283. if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
  87284. if( plrAtEnd(pRight) ) return -1;
  87285. if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
  87286. if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
  87287. if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
  87288. if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
  87289. if( pLeft->iType==DL_POSITIONS ) return 0;
  87290. if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
  87291. if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
  87292. if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
  87293. if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
  87294. return 0;
  87295. }
  87296. /* Write the union of position lists in pLeft and pRight to pOut.
  87297. ** "Union" in this case meaning "All unique position tuples". Should
  87298. ** work with any doclist type, though both inputs and the output
  87299. ** should be the same type.
  87300. */
  87301. static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
  87302. PLReader left, right;
  87303. PLWriter writer;
  87304. assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  87305. assert( pLeft->iType==pRight->iType );
  87306. assert( pLeft->iType==pOut->iType );
  87307. plrInit(&left, pLeft);
  87308. plrInit(&right, pRight);
  87309. plwInit(&writer, pOut, dlrDocid(pLeft));
  87310. while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
  87311. int c = posListCmp(&left, &right);
  87312. if( c<0 ){
  87313. plwCopy(&writer, &left);
  87314. plrStep(&left);
  87315. }else if( c>0 ){
  87316. plwCopy(&writer, &right);
  87317. plrStep(&right);
  87318. }else{
  87319. plwCopy(&writer, &left);
  87320. plrStep(&left);
  87321. plrStep(&right);
  87322. }
  87323. }
  87324. plwTerminate(&writer);
  87325. plwDestroy(&writer);
  87326. plrDestroy(&left);
  87327. plrDestroy(&right);
  87328. }
  87329. /* Write the union of doclists in pLeft and pRight to pOut. For
  87330. ** docids in common between the inputs, the union of the position
  87331. ** lists is written. Inputs and outputs are always type DL_DEFAULT.
  87332. */
  87333. static void docListUnion(
  87334. const char *pLeft, int nLeft,
  87335. const char *pRight, int nRight,
  87336. DataBuffer *pOut /* Write the combined doclist here */
  87337. ){
  87338. DLReader left, right;
  87339. DLWriter writer;
  87340. if( nLeft==0 ){
  87341. if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
  87342. return;
  87343. }
  87344. if( nRight==0 ){
  87345. dataBufferAppend(pOut, pLeft, nLeft);
  87346. return;
  87347. }
  87348. dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
  87349. dlrInit(&right, DL_DEFAULT, pRight, nRight);
  87350. dlwInit(&writer, DL_DEFAULT, pOut);
  87351. while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
  87352. if( dlrAtEnd(&right) ){
  87353. dlwCopy(&writer, &left);
  87354. dlrStep(&left);
  87355. }else if( dlrAtEnd(&left) ){
  87356. dlwCopy(&writer, &right);
  87357. dlrStep(&right);
  87358. }else if( dlrDocid(&left)<dlrDocid(&right) ){
  87359. dlwCopy(&writer, &left);
  87360. dlrStep(&left);
  87361. }else if( dlrDocid(&left)>dlrDocid(&right) ){
  87362. dlwCopy(&writer, &right);
  87363. dlrStep(&right);
  87364. }else{
  87365. posListUnion(&left, &right, &writer);
  87366. dlrStep(&left);
  87367. dlrStep(&right);
  87368. }
  87369. }
  87370. dlrDestroy(&left);
  87371. dlrDestroy(&right);
  87372. dlwDestroy(&writer);
  87373. }
  87374. /*
  87375. ** This function is used as part of the implementation of phrase and
  87376. ** NEAR matching.
  87377. **
  87378. ** pLeft and pRight are DLReaders positioned to the same docid in
  87379. ** lists of type DL_POSITION. This function writes an entry to the
  87380. ** DLWriter pOut for each position in pRight that is less than
  87381. ** (nNear+1) greater (but not equal to or smaller) than a position
  87382. ** in pLeft. For example, if nNear is 0, and the positions contained
  87383. ** by pLeft and pRight are:
  87384. **
  87385. ** pLeft: 5 10 15 20
  87386. ** pRight: 6 9 17 21
  87387. **
  87388. ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
  87389. ** then a positionids "6" and "21" are also added to pOut.
  87390. **
  87391. ** If boolean argument isSaveLeft is true, then positionids are copied
  87392. ** from pLeft instead of pRight. In the example above, the positions "5"
  87393. ** and "20" would be added instead of "6" and "21".
  87394. */
  87395. static void posListPhraseMerge(
  87396. DLReader *pLeft,
  87397. DLReader *pRight,
  87398. int nNear,
  87399. int isSaveLeft,
  87400. DLWriter *pOut
  87401. ){
  87402. PLReader left, right;
  87403. PLWriter writer;
  87404. int match = 0;
  87405. assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  87406. assert( pOut->iType!=DL_POSITIONS_OFFSETS );
  87407. plrInit(&left, pLeft);
  87408. plrInit(&right, pRight);
  87409. while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
  87410. if( plrColumn(&left)<plrColumn(&right) ){
  87411. plrStep(&left);
  87412. }else if( plrColumn(&left)>plrColumn(&right) ){
  87413. plrStep(&right);
  87414. }else if( plrPosition(&left)>=plrPosition(&right) ){
  87415. plrStep(&right);
  87416. }else{
  87417. if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
  87418. if( !match ){
  87419. plwInit(&writer, pOut, dlrDocid(pLeft));
  87420. match = 1;
  87421. }
  87422. if( !isSaveLeft ){
  87423. plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
  87424. }else{
  87425. plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
  87426. }
  87427. plrStep(&right);
  87428. }else{
  87429. plrStep(&left);
  87430. }
  87431. }
  87432. }
  87433. if( match ){
  87434. plwTerminate(&writer);
  87435. plwDestroy(&writer);
  87436. }
  87437. plrDestroy(&left);
  87438. plrDestroy(&right);
  87439. }
  87440. /*
  87441. ** Compare the values pointed to by the PLReaders passed as arguments.
  87442. ** Return -1 if the value pointed to by pLeft is considered less than
  87443. ** the value pointed to by pRight, +1 if it is considered greater
  87444. ** than it, or 0 if it is equal. i.e.
  87445. **
  87446. ** (*pLeft - *pRight)
  87447. **
  87448. ** A PLReader that is in the EOF condition is considered greater than
  87449. ** any other. If neither argument is in EOF state, the return value of
  87450. ** plrColumn() is used. If the plrColumn() values are equal, the
  87451. ** comparison is on the basis of plrPosition().
  87452. */
  87453. static int plrCompare(PLReader *pLeft, PLReader *pRight){
  87454. assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
  87455. if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
  87456. return (plrAtEnd(pRight) ? -1 : 1);
  87457. }
  87458. if( plrColumn(pLeft)!=plrColumn(pRight) ){
  87459. return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
  87460. }
  87461. if( plrPosition(pLeft)!=plrPosition(pRight) ){
  87462. return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
  87463. }
  87464. return 0;
  87465. }
  87466. /* We have two doclists with positions: pLeft and pRight. Depending
  87467. ** on the value of the nNear parameter, perform either a phrase
  87468. ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
  87469. ** and write the results into pOut.
  87470. **
  87471. ** A phrase intersection means that two documents only match
  87472. ** if pLeft.iPos+1==pRight.iPos.
  87473. **
  87474. ** A NEAR intersection means that two documents only match if
  87475. ** (abs(pLeft.iPos-pRight.iPos)<nNear).
  87476. **
  87477. ** If a NEAR intersection is requested, then the nPhrase argument should
  87478. ** be passed the number of tokens in the two operands to the NEAR operator
  87479. ** combined. For example:
  87480. **
  87481. ** Query syntax nPhrase
  87482. ** ------------------------------------
  87483. ** "A B C" NEAR "D E" 5
  87484. ** A NEAR B 2
  87485. **
  87486. ** iType controls the type of data written to pOut. If iType is
  87487. ** DL_POSITIONS, the positions are those from pRight.
  87488. */
  87489. static void docListPhraseMerge(
  87490. const char *pLeft, int nLeft,
  87491. const char *pRight, int nRight,
  87492. int nNear, /* 0 for a phrase merge, non-zero for a NEAR merge */
  87493. int nPhrase, /* Number of tokens in left+right operands to NEAR */
  87494. DocListType iType, /* Type of doclist to write to pOut */
  87495. DataBuffer *pOut /* Write the combined doclist here */
  87496. ){
  87497. DLReader left, right;
  87498. DLWriter writer;
  87499. if( nLeft==0 || nRight==0 ) return;
  87500. assert( iType!=DL_POSITIONS_OFFSETS );
  87501. dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
  87502. dlrInit(&right, DL_POSITIONS, pRight, nRight);
  87503. dlwInit(&writer, iType, pOut);
  87504. while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
  87505. if( dlrDocid(&left)<dlrDocid(&right) ){
  87506. dlrStep(&left);
  87507. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  87508. dlrStep(&right);
  87509. }else{
  87510. if( nNear==0 ){
  87511. posListPhraseMerge(&left, &right, 0, 0, &writer);
  87512. }else{
  87513. /* This case occurs when two terms (simple terms or phrases) are
  87514. * connected by a NEAR operator, span (nNear+1). i.e.
  87515. *
  87516. * '"terrible company" NEAR widget'
  87517. */
  87518. DataBuffer one = {0, 0, 0};
  87519. DataBuffer two = {0, 0, 0};
  87520. DLWriter dlwriter2;
  87521. DLReader dr1 = {0, 0, 0, 0, 0};
  87522. DLReader dr2 = {0, 0, 0, 0, 0};
  87523. dlwInit(&dlwriter2, iType, &one);
  87524. posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
  87525. dlwInit(&dlwriter2, iType, &two);
  87526. posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
  87527. if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
  87528. if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
  87529. if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
  87530. PLReader pr1 = {0};
  87531. PLReader pr2 = {0};
  87532. PLWriter plwriter;
  87533. plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
  87534. if( one.nData ) plrInit(&pr1, &dr1);
  87535. if( two.nData ) plrInit(&pr2, &dr2);
  87536. while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
  87537. int iCompare = plrCompare(&pr1, &pr2);
  87538. switch( iCompare ){
  87539. case -1:
  87540. plwCopy(&plwriter, &pr1);
  87541. plrStep(&pr1);
  87542. break;
  87543. case 1:
  87544. plwCopy(&plwriter, &pr2);
  87545. plrStep(&pr2);
  87546. break;
  87547. case 0:
  87548. plwCopy(&plwriter, &pr1);
  87549. plrStep(&pr1);
  87550. plrStep(&pr2);
  87551. break;
  87552. }
  87553. }
  87554. plwTerminate(&plwriter);
  87555. }
  87556. dataBufferDestroy(&one);
  87557. dataBufferDestroy(&two);
  87558. }
  87559. dlrStep(&left);
  87560. dlrStep(&right);
  87561. }
  87562. }
  87563. dlrDestroy(&left);
  87564. dlrDestroy(&right);
  87565. dlwDestroy(&writer);
  87566. }
  87567. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  87568. ** Write the intersection of these two doclists into pOut as a
  87569. ** DL_DOCIDS doclist.
  87570. */
  87571. static void docListAndMerge(
  87572. const char *pLeft, int nLeft,
  87573. const char *pRight, int nRight,
  87574. DataBuffer *pOut /* Write the combined doclist here */
  87575. ){
  87576. DLReader left, right;
  87577. DLWriter writer;
  87578. if( nLeft==0 || nRight==0 ) return;
  87579. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  87580. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  87581. dlwInit(&writer, DL_DOCIDS, pOut);
  87582. while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
  87583. if( dlrDocid(&left)<dlrDocid(&right) ){
  87584. dlrStep(&left);
  87585. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  87586. dlrStep(&right);
  87587. }else{
  87588. dlwAdd(&writer, dlrDocid(&left));
  87589. dlrStep(&left);
  87590. dlrStep(&right);
  87591. }
  87592. }
  87593. dlrDestroy(&left);
  87594. dlrDestroy(&right);
  87595. dlwDestroy(&writer);
  87596. }
  87597. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  87598. ** Write the union of these two doclists into pOut as a
  87599. ** DL_DOCIDS doclist.
  87600. */
  87601. static void docListOrMerge(
  87602. const char *pLeft, int nLeft,
  87603. const char *pRight, int nRight,
  87604. DataBuffer *pOut /* Write the combined doclist here */
  87605. ){
  87606. DLReader left, right;
  87607. DLWriter writer;
  87608. if( nLeft==0 ){
  87609. if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
  87610. return;
  87611. }
  87612. if( nRight==0 ){
  87613. dataBufferAppend(pOut, pLeft, nLeft);
  87614. return;
  87615. }
  87616. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  87617. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  87618. dlwInit(&writer, DL_DOCIDS, pOut);
  87619. while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
  87620. if( dlrAtEnd(&right) ){
  87621. dlwAdd(&writer, dlrDocid(&left));
  87622. dlrStep(&left);
  87623. }else if( dlrAtEnd(&left) ){
  87624. dlwAdd(&writer, dlrDocid(&right));
  87625. dlrStep(&right);
  87626. }else if( dlrDocid(&left)<dlrDocid(&right) ){
  87627. dlwAdd(&writer, dlrDocid(&left));
  87628. dlrStep(&left);
  87629. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  87630. dlwAdd(&writer, dlrDocid(&right));
  87631. dlrStep(&right);
  87632. }else{
  87633. dlwAdd(&writer, dlrDocid(&left));
  87634. dlrStep(&left);
  87635. dlrStep(&right);
  87636. }
  87637. }
  87638. dlrDestroy(&left);
  87639. dlrDestroy(&right);
  87640. dlwDestroy(&writer);
  87641. }
  87642. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  87643. ** Write into pOut as DL_DOCIDS doclist containing all documents that
  87644. ** occur in pLeft but not in pRight.
  87645. */
  87646. static void docListExceptMerge(
  87647. const char *pLeft, int nLeft,
  87648. const char *pRight, int nRight,
  87649. DataBuffer *pOut /* Write the combined doclist here */
  87650. ){
  87651. DLReader left, right;
  87652. DLWriter writer;
  87653. if( nLeft==0 ) return;
  87654. if( nRight==0 ){
  87655. dataBufferAppend(pOut, pLeft, nLeft);
  87656. return;
  87657. }
  87658. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  87659. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  87660. dlwInit(&writer, DL_DOCIDS, pOut);
  87661. while( !dlrAtEnd(&left) ){
  87662. while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
  87663. dlrStep(&right);
  87664. }
  87665. if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
  87666. dlwAdd(&writer, dlrDocid(&left));
  87667. }
  87668. dlrStep(&left);
  87669. }
  87670. dlrDestroy(&left);
  87671. dlrDestroy(&right);
  87672. dlwDestroy(&writer);
  87673. }
  87674. static char *string_dup_n(const char *s, int n){
  87675. char *str = sqlite3_malloc(n + 1);
  87676. memcpy(str, s, n);
  87677. str[n] = '\0';
  87678. return str;
  87679. }
  87680. /* Duplicate a string; the caller must free() the returned string.
  87681. * (We don't use strdup() since it is not part of the standard C library and
  87682. * may not be available everywhere.) */
  87683. static char *string_dup(const char *s){
  87684. return string_dup_n(s, strlen(s));
  87685. }
  87686. /* Format a string, replacing each occurrence of the % character with
  87687. * zDb.zName. This may be more convenient than sqlite_mprintf()
  87688. * when one string is used repeatedly in a format string.
  87689. * The caller must free() the returned string. */
  87690. static char *string_format(const char *zFormat,
  87691. const char *zDb, const char *zName){
  87692. const char *p;
  87693. size_t len = 0;
  87694. size_t nDb = strlen(zDb);
  87695. size_t nName = strlen(zName);
  87696. size_t nFullTableName = nDb+1+nName;
  87697. char *result;
  87698. char *r;
  87699. /* first compute length needed */
  87700. for(p = zFormat ; *p ; ++p){
  87701. len += (*p=='%' ? nFullTableName : 1);
  87702. }
  87703. len += 1; /* for null terminator */
  87704. r = result = sqlite3_malloc(len);
  87705. for(p = zFormat; *p; ++p){
  87706. if( *p=='%' ){
  87707. memcpy(r, zDb, nDb);
  87708. r += nDb;
  87709. *r++ = '.';
  87710. memcpy(r, zName, nName);
  87711. r += nName;
  87712. } else {
  87713. *r++ = *p;
  87714. }
  87715. }
  87716. *r++ = '\0';
  87717. assert( r == result + len );
  87718. return result;
  87719. }
  87720. static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
  87721. const char *zFormat){
  87722. char *zCommand = string_format(zFormat, zDb, zName);
  87723. int rc;
  87724. FTSTRACE(("FTS3 sql: %s\n", zCommand));
  87725. rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  87726. sqlite3_free(zCommand);
  87727. return rc;
  87728. }
  87729. static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
  87730. sqlite3_stmt **ppStmt, const char *zFormat){
  87731. char *zCommand = string_format(zFormat, zDb, zName);
  87732. int rc;
  87733. FTSTRACE(("FTS3 prepare: %s\n", zCommand));
  87734. rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
  87735. sqlite3_free(zCommand);
  87736. return rc;
  87737. }
  87738. /* end utility functions */
  87739. /* Forward reference */
  87740. typedef struct fulltext_vtab fulltext_vtab;
  87741. /*
  87742. ** An instance of the following structure keeps track of generated
  87743. ** matching-word offset information and snippets.
  87744. */
  87745. typedef struct Snippet {
  87746. int nMatch; /* Total number of matches */
  87747. int nAlloc; /* Space allocated for aMatch[] */
  87748. struct snippetMatch { /* One entry for each matching term */
  87749. char snStatus; /* Status flag for use while constructing snippets */
  87750. short int iCol; /* The column that contains the match */
  87751. short int iTerm; /* The index in Query.pTerms[] of the matching term */
  87752. int iToken; /* The index of the matching document token */
  87753. short int nByte; /* Number of bytes in the term */
  87754. int iStart; /* The offset to the first character of the term */
  87755. } *aMatch; /* Points to space obtained from malloc */
  87756. char *zOffset; /* Text rendering of aMatch[] */
  87757. int nOffset; /* strlen(zOffset) */
  87758. char *zSnippet; /* Snippet text */
  87759. int nSnippet; /* strlen(zSnippet) */
  87760. } Snippet;
  87761. typedef enum QueryType {
  87762. QUERY_GENERIC, /* table scan */
  87763. QUERY_DOCID, /* lookup by docid */
  87764. QUERY_FULLTEXT /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
  87765. } QueryType;
  87766. typedef enum fulltext_statement {
  87767. CONTENT_INSERT_STMT,
  87768. CONTENT_SELECT_STMT,
  87769. CONTENT_UPDATE_STMT,
  87770. CONTENT_DELETE_STMT,
  87771. CONTENT_EXISTS_STMT,
  87772. BLOCK_INSERT_STMT,
  87773. BLOCK_SELECT_STMT,
  87774. BLOCK_DELETE_STMT,
  87775. BLOCK_DELETE_ALL_STMT,
  87776. SEGDIR_MAX_INDEX_STMT,
  87777. SEGDIR_SET_STMT,
  87778. SEGDIR_SELECT_LEVEL_STMT,
  87779. SEGDIR_SPAN_STMT,
  87780. SEGDIR_DELETE_STMT,
  87781. SEGDIR_SELECT_SEGMENT_STMT,
  87782. SEGDIR_SELECT_ALL_STMT,
  87783. SEGDIR_DELETE_ALL_STMT,
  87784. SEGDIR_COUNT_STMT,
  87785. MAX_STMT /* Always at end! */
  87786. } fulltext_statement;
  87787. /* These must exactly match the enum above. */
  87788. /* TODO(shess): Is there some risk that a statement will be used in two
  87789. ** cursors at once, e.g. if a query joins a virtual table to itself?
  87790. ** If so perhaps we should move some of these to the cursor object.
  87791. */
  87792. static const char *const fulltext_zStatement[MAX_STMT] = {
  87793. /* CONTENT_INSERT */ NULL, /* generated in contentInsertStatement() */
  87794. /* CONTENT_SELECT */ NULL, /* generated in contentSelectStatement() */
  87795. /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */
  87796. /* CONTENT_DELETE */ "delete from %_content where docid = ?",
  87797. /* CONTENT_EXISTS */ "select docid from %_content limit 1",
  87798. /* BLOCK_INSERT */
  87799. "insert into %_segments (blockid, block) values (null, ?)",
  87800. /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
  87801. /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
  87802. /* BLOCK_DELETE_ALL */ "delete from %_segments",
  87803. /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
  87804. /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
  87805. /* SEGDIR_SELECT_LEVEL */
  87806. "select start_block, leaves_end_block, root from %_segdir "
  87807. " where level = ? order by idx",
  87808. /* SEGDIR_SPAN */
  87809. "select min(start_block), max(end_block) from %_segdir "
  87810. " where level = ? and start_block <> 0",
  87811. /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
  87812. /* NOTE(shess): The first three results of the following two
  87813. ** statements must match.
  87814. */
  87815. /* SEGDIR_SELECT_SEGMENT */
  87816. "select start_block, leaves_end_block, root from %_segdir "
  87817. " where level = ? and idx = ?",
  87818. /* SEGDIR_SELECT_ALL */
  87819. "select start_block, leaves_end_block, root from %_segdir "
  87820. " order by level desc, idx asc",
  87821. /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
  87822. /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
  87823. };
  87824. /*
  87825. ** A connection to a fulltext index is an instance of the following
  87826. ** structure. The xCreate and xConnect methods create an instance
  87827. ** of this structure and xDestroy and xDisconnect free that instance.
  87828. ** All other methods receive a pointer to the structure as one of their
  87829. ** arguments.
  87830. */
  87831. struct fulltext_vtab {
  87832. sqlite3_vtab base; /* Base class used by SQLite core */
  87833. sqlite3 *db; /* The database connection */
  87834. const char *zDb; /* logical database name */
  87835. const char *zName; /* virtual table name */
  87836. int nColumn; /* number of columns in virtual table */
  87837. char **azColumn; /* column names. malloced */
  87838. char **azContentColumn; /* column names in content table; malloced */
  87839. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  87840. /* Precompiled statements which we keep as long as the table is
  87841. ** open.
  87842. */
  87843. sqlite3_stmt *pFulltextStatements[MAX_STMT];
  87844. /* Precompiled statements used for segment merges. We run a
  87845. ** separate select across the leaf level of each tree being merged.
  87846. */
  87847. sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
  87848. /* The statement used to prepare pLeafSelectStmts. */
  87849. #define LEAF_SELECT \
  87850. "select block from %_segments where blockid between ? and ? order by blockid"
  87851. /* These buffer pending index updates during transactions.
  87852. ** nPendingData estimates the memory size of the pending data. It
  87853. ** doesn't include the hash-bucket overhead, nor any malloc
  87854. ** overhead. When nPendingData exceeds kPendingThreshold, the
  87855. ** buffer is flushed even before the transaction closes.
  87856. ** pendingTerms stores the data, and is only valid when nPendingData
  87857. ** is >=0 (nPendingData<0 means pendingTerms has not been
  87858. ** initialized). iPrevDocid is the last docid written, used to make
  87859. ** certain we're inserting in sorted order.
  87860. */
  87861. int nPendingData;
  87862. #define kPendingThreshold (1*1024*1024)
  87863. sqlite_int64 iPrevDocid;
  87864. fts3Hash pendingTerms;
  87865. };
  87866. /*
  87867. ** When the core wants to do a query, it create a cursor using a
  87868. ** call to xOpen. This structure is an instance of a cursor. It
  87869. ** is destroyed by xClose.
  87870. */
  87871. typedef struct fulltext_cursor {
  87872. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  87873. QueryType iCursorType; /* Copy of sqlite3_index_info.idxNum */
  87874. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  87875. int eof; /* True if at End Of Results */
  87876. Fts3Expr *pExpr; /* Parsed MATCH query string */
  87877. Snippet snippet; /* Cached snippet for the current row */
  87878. int iColumn; /* Column being searched */
  87879. DataBuffer result; /* Doclist results from fulltextQuery */
  87880. DLReader reader; /* Result reader if result not empty */
  87881. } fulltext_cursor;
  87882. static fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  87883. return (fulltext_vtab *) c->base.pVtab;
  87884. }
  87885. static const sqlite3_module fts3Module; /* forward declaration */
  87886. /* Return a dynamically generated statement of the form
  87887. * insert into %_content (docid, ...) values (?, ...)
  87888. */
  87889. static const char *contentInsertStatement(fulltext_vtab *v){
  87890. StringBuffer sb;
  87891. int i;
  87892. initStringBuffer(&sb);
  87893. append(&sb, "insert into %_content (docid, ");
  87894. appendList(&sb, v->nColumn, v->azContentColumn);
  87895. append(&sb, ") values (?");
  87896. for(i=0; i<v->nColumn; ++i)
  87897. append(&sb, ", ?");
  87898. append(&sb, ")");
  87899. return stringBufferData(&sb);
  87900. }
  87901. /* Return a dynamically generated statement of the form
  87902. * select <content columns> from %_content where docid = ?
  87903. */
  87904. static const char *contentSelectStatement(fulltext_vtab *v){
  87905. StringBuffer sb;
  87906. initStringBuffer(&sb);
  87907. append(&sb, "SELECT ");
  87908. appendList(&sb, v->nColumn, v->azContentColumn);
  87909. append(&sb, " FROM %_content WHERE docid = ?");
  87910. return stringBufferData(&sb);
  87911. }
  87912. /* Return a dynamically generated statement of the form
  87913. * update %_content set [col_0] = ?, [col_1] = ?, ...
  87914. * where docid = ?
  87915. */
  87916. static const char *contentUpdateStatement(fulltext_vtab *v){
  87917. StringBuffer sb;
  87918. int i;
  87919. initStringBuffer(&sb);
  87920. append(&sb, "update %_content set ");
  87921. for(i=0; i<v->nColumn; ++i) {
  87922. if( i>0 ){
  87923. append(&sb, ", ");
  87924. }
  87925. append(&sb, v->azContentColumn[i]);
  87926. append(&sb, " = ?");
  87927. }
  87928. append(&sb, " where docid = ?");
  87929. return stringBufferData(&sb);
  87930. }
  87931. /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
  87932. ** If the indicated statement has never been prepared, it is prepared
  87933. ** and cached, otherwise the cached version is reset.
  87934. */
  87935. static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
  87936. sqlite3_stmt **ppStmt){
  87937. assert( iStmt<MAX_STMT );
  87938. if( v->pFulltextStatements[iStmt]==NULL ){
  87939. const char *zStmt;
  87940. int rc;
  87941. switch( iStmt ){
  87942. case CONTENT_INSERT_STMT:
  87943. zStmt = contentInsertStatement(v); break;
  87944. case CONTENT_SELECT_STMT:
  87945. zStmt = contentSelectStatement(v); break;
  87946. case CONTENT_UPDATE_STMT:
  87947. zStmt = contentUpdateStatement(v); break;
  87948. default:
  87949. zStmt = fulltext_zStatement[iStmt];
  87950. }
  87951. rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
  87952. zStmt);
  87953. if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
  87954. if( rc!=SQLITE_OK ) return rc;
  87955. } else {
  87956. int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
  87957. if( rc!=SQLITE_OK ) return rc;
  87958. }
  87959. *ppStmt = v->pFulltextStatements[iStmt];
  87960. return SQLITE_OK;
  87961. }
  87962. /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
  87963. ** SQLITE_ROW to SQLITE_ERROR. Useful for statements like UPDATE,
  87964. ** where we expect no results.
  87965. */
  87966. static int sql_single_step(sqlite3_stmt *s){
  87967. int rc = sqlite3_step(s);
  87968. return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
  87969. }
  87970. /* Like sql_get_statement(), but for special replicated LEAF_SELECT
  87971. ** statements. idx -1 is a special case for an uncached version of
  87972. ** the statement (used in the optimize implementation).
  87973. */
  87974. /* TODO(shess) Write version for generic statements and then share
  87975. ** that between the cached-statement functions.
  87976. */
  87977. static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
  87978. sqlite3_stmt **ppStmt){
  87979. assert( idx>=-1 && idx<MERGE_COUNT );
  87980. if( idx==-1 ){
  87981. return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
  87982. }else if( v->pLeafSelectStmts[idx]==NULL ){
  87983. int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
  87984. LEAF_SELECT);
  87985. if( rc!=SQLITE_OK ) return rc;
  87986. }else{
  87987. int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
  87988. if( rc!=SQLITE_OK ) return rc;
  87989. }
  87990. *ppStmt = v->pLeafSelectStmts[idx];
  87991. return SQLITE_OK;
  87992. }
  87993. /* insert into %_content (docid, ...) values ([docid], [pValues])
  87994. ** If the docid contains SQL NULL, then a unique docid will be
  87995. ** generated.
  87996. */
  87997. static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
  87998. sqlite3_value **pValues){
  87999. sqlite3_stmt *s;
  88000. int i;
  88001. int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  88002. if( rc!=SQLITE_OK ) return rc;
  88003. rc = sqlite3_bind_value(s, 1, docid);
  88004. if( rc!=SQLITE_OK ) return rc;
  88005. for(i=0; i<v->nColumn; ++i){
  88006. rc = sqlite3_bind_value(s, 2+i, pValues[i]);
  88007. if( rc!=SQLITE_OK ) return rc;
  88008. }
  88009. return sql_single_step(s);
  88010. }
  88011. /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
  88012. * where docid = [iDocid] */
  88013. static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
  88014. sqlite_int64 iDocid){
  88015. sqlite3_stmt *s;
  88016. int i;
  88017. int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
  88018. if( rc!=SQLITE_OK ) return rc;
  88019. for(i=0; i<v->nColumn; ++i){
  88020. rc = sqlite3_bind_value(s, 1+i, pValues[i]);
  88021. if( rc!=SQLITE_OK ) return rc;
  88022. }
  88023. rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
  88024. if( rc!=SQLITE_OK ) return rc;
  88025. return sql_single_step(s);
  88026. }
  88027. static void freeStringArray(int nString, const char **pString){
  88028. int i;
  88029. for (i=0 ; i < nString ; ++i) {
  88030. if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
  88031. }
  88032. sqlite3_free((void *) pString);
  88033. }
  88034. /* select * from %_content where docid = [iDocid]
  88035. * The caller must delete the returned array and all strings in it.
  88036. * null fields will be NULL in the returned array.
  88037. *
  88038. * TODO: Perhaps we should return pointer/length strings here for consistency
  88039. * with other code which uses pointer/length. */
  88040. static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
  88041. const char ***pValues){
  88042. sqlite3_stmt *s;
  88043. const char **values;
  88044. int i;
  88045. int rc;
  88046. *pValues = NULL;
  88047. rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  88048. if( rc!=SQLITE_OK ) return rc;
  88049. rc = sqlite3_bind_int64(s, 1, iDocid);
  88050. if( rc!=SQLITE_OK ) return rc;
  88051. rc = sqlite3_step(s);
  88052. if( rc!=SQLITE_ROW ) return rc;
  88053. values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
  88054. for(i=0; i<v->nColumn; ++i){
  88055. if( sqlite3_column_type(s, i)==SQLITE_NULL ){
  88056. values[i] = NULL;
  88057. }else{
  88058. values[i] = string_dup((char*)sqlite3_column_text(s, i));
  88059. }
  88060. }
  88061. /* We expect only one row. We must execute another sqlite3_step()
  88062. * to complete the iteration; otherwise the table will remain locked. */
  88063. rc = sqlite3_step(s);
  88064. if( rc==SQLITE_DONE ){
  88065. *pValues = values;
  88066. return SQLITE_OK;
  88067. }
  88068. freeStringArray(v->nColumn, values);
  88069. return rc;
  88070. }
  88071. /* delete from %_content where docid = [iDocid ] */
  88072. static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
  88073. sqlite3_stmt *s;
  88074. int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  88075. if( rc!=SQLITE_OK ) return rc;
  88076. rc = sqlite3_bind_int64(s, 1, iDocid);
  88077. if( rc!=SQLITE_OK ) return rc;
  88078. return sql_single_step(s);
  88079. }
  88080. /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
  88081. ** no rows exist, and any error in case of failure.
  88082. */
  88083. static int content_exists(fulltext_vtab *v){
  88084. sqlite3_stmt *s;
  88085. int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
  88086. if( rc!=SQLITE_OK ) return rc;
  88087. rc = sqlite3_step(s);
  88088. if( rc!=SQLITE_ROW ) return rc;
  88089. /* We expect only one row. We must execute another sqlite3_step()
  88090. * to complete the iteration; otherwise the table will remain locked. */
  88091. rc = sqlite3_step(s);
  88092. if( rc==SQLITE_DONE ) return SQLITE_ROW;
  88093. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  88094. return rc;
  88095. }
  88096. /* insert into %_segments values ([pData])
  88097. ** returns assigned blockid in *piBlockid
  88098. */
  88099. static int block_insert(fulltext_vtab *v, const char *pData, int nData,
  88100. sqlite_int64 *piBlockid){
  88101. sqlite3_stmt *s;
  88102. int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
  88103. if( rc!=SQLITE_OK ) return rc;
  88104. rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
  88105. if( rc!=SQLITE_OK ) return rc;
  88106. rc = sqlite3_step(s);
  88107. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  88108. if( rc!=SQLITE_DONE ) return rc;
  88109. /* blockid column is an alias for rowid. */
  88110. *piBlockid = sqlite3_last_insert_rowid(v->db);
  88111. return SQLITE_OK;
  88112. }
  88113. /* delete from %_segments
  88114. ** where blockid between [iStartBlockid] and [iEndBlockid]
  88115. **
  88116. ** Deletes the range of blocks, inclusive, used to delete the blocks
  88117. ** which form a segment.
  88118. */
  88119. static int block_delete(fulltext_vtab *v,
  88120. sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
  88121. sqlite3_stmt *s;
  88122. int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
  88123. if( rc!=SQLITE_OK ) return rc;
  88124. rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  88125. if( rc!=SQLITE_OK ) return rc;
  88126. rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  88127. if( rc!=SQLITE_OK ) return rc;
  88128. return sql_single_step(s);
  88129. }
  88130. /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
  88131. ** at iLevel. Returns SQLITE_DONE if there are no segments at
  88132. ** iLevel. Otherwise returns an error.
  88133. */
  88134. static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
  88135. sqlite3_stmt *s;
  88136. int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
  88137. if( rc!=SQLITE_OK ) return rc;
  88138. rc = sqlite3_bind_int(s, 1, iLevel);
  88139. if( rc!=SQLITE_OK ) return rc;
  88140. rc = sqlite3_step(s);
  88141. /* Should always get at least one row due to how max() works. */
  88142. if( rc==SQLITE_DONE ) return SQLITE_DONE;
  88143. if( rc!=SQLITE_ROW ) return rc;
  88144. /* NULL means that there were no inputs to max(). */
  88145. if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
  88146. rc = sqlite3_step(s);
  88147. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  88148. return rc;
  88149. }
  88150. *pidx = sqlite3_column_int(s, 0);
  88151. /* We expect only one row. We must execute another sqlite3_step()
  88152. * to complete the iteration; otherwise the table will remain locked. */
  88153. rc = sqlite3_step(s);
  88154. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  88155. if( rc!=SQLITE_DONE ) return rc;
  88156. return SQLITE_ROW;
  88157. }
  88158. /* insert into %_segdir values (
  88159. ** [iLevel], [idx],
  88160. ** [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
  88161. ** [pRootData]
  88162. ** )
  88163. */
  88164. static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
  88165. sqlite_int64 iStartBlockid,
  88166. sqlite_int64 iLeavesEndBlockid,
  88167. sqlite_int64 iEndBlockid,
  88168. const char *pRootData, int nRootData){
  88169. sqlite3_stmt *s;
  88170. int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
  88171. if( rc!=SQLITE_OK ) return rc;
  88172. rc = sqlite3_bind_int(s, 1, iLevel);
  88173. if( rc!=SQLITE_OK ) return rc;
  88174. rc = sqlite3_bind_int(s, 2, idx);
  88175. if( rc!=SQLITE_OK ) return rc;
  88176. rc = sqlite3_bind_int64(s, 3, iStartBlockid);
  88177. if( rc!=SQLITE_OK ) return rc;
  88178. rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
  88179. if( rc!=SQLITE_OK ) return rc;
  88180. rc = sqlite3_bind_int64(s, 5, iEndBlockid);
  88181. if( rc!=SQLITE_OK ) return rc;
  88182. rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
  88183. if( rc!=SQLITE_OK ) return rc;
  88184. return sql_single_step(s);
  88185. }
  88186. /* Queries %_segdir for the block span of the segments in level
  88187. ** iLevel. Returns SQLITE_DONE if there are no blocks for iLevel,
  88188. ** SQLITE_ROW if there are blocks, else an error.
  88189. */
  88190. static int segdir_span(fulltext_vtab *v, int iLevel,
  88191. sqlite_int64 *piStartBlockid,
  88192. sqlite_int64 *piEndBlockid){
  88193. sqlite3_stmt *s;
  88194. int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
  88195. if( rc!=SQLITE_OK ) return rc;
  88196. rc = sqlite3_bind_int(s, 1, iLevel);
  88197. if( rc!=SQLITE_OK ) return rc;
  88198. rc = sqlite3_step(s);
  88199. if( rc==SQLITE_DONE ) return SQLITE_DONE; /* Should never happen */
  88200. if( rc!=SQLITE_ROW ) return rc;
  88201. /* This happens if all segments at this level are entirely inline. */
  88202. if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
  88203. /* We expect only one row. We must execute another sqlite3_step()
  88204. * to complete the iteration; otherwise the table will remain locked. */
  88205. int rc2 = sqlite3_step(s);
  88206. if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
  88207. return rc2;
  88208. }
  88209. *piStartBlockid = sqlite3_column_int64(s, 0);
  88210. *piEndBlockid = sqlite3_column_int64(s, 1);
  88211. /* We expect only one row. We must execute another sqlite3_step()
  88212. * to complete the iteration; otherwise the table will remain locked. */
  88213. rc = sqlite3_step(s);
  88214. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  88215. if( rc!=SQLITE_DONE ) return rc;
  88216. return SQLITE_ROW;
  88217. }
  88218. /* Delete the segment blocks and segment directory records for all
  88219. ** segments at iLevel.
  88220. */
  88221. static int segdir_delete(fulltext_vtab *v, int iLevel){
  88222. sqlite3_stmt *s;
  88223. sqlite_int64 iStartBlockid, iEndBlockid;
  88224. int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
  88225. if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
  88226. if( rc==SQLITE_ROW ){
  88227. rc = block_delete(v, iStartBlockid, iEndBlockid);
  88228. if( rc!=SQLITE_OK ) return rc;
  88229. }
  88230. /* Delete the segment directory itself. */
  88231. rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
  88232. if( rc!=SQLITE_OK ) return rc;
  88233. rc = sqlite3_bind_int64(s, 1, iLevel);
  88234. if( rc!=SQLITE_OK ) return rc;
  88235. return sql_single_step(s);
  88236. }
  88237. /* Delete entire fts index, SQLITE_OK on success, relevant error on
  88238. ** failure.
  88239. */
  88240. static int segdir_delete_all(fulltext_vtab *v){
  88241. sqlite3_stmt *s;
  88242. int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
  88243. if( rc!=SQLITE_OK ) return rc;
  88244. rc = sql_single_step(s);
  88245. if( rc!=SQLITE_OK ) return rc;
  88246. rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
  88247. if( rc!=SQLITE_OK ) return rc;
  88248. return sql_single_step(s);
  88249. }
  88250. /* Returns SQLITE_OK with *pnSegments set to the number of entries in
  88251. ** %_segdir and *piMaxLevel set to the highest level which has a
  88252. ** segment. Otherwise returns the SQLite error which caused failure.
  88253. */
  88254. static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
  88255. sqlite3_stmt *s;
  88256. int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
  88257. if( rc!=SQLITE_OK ) return rc;
  88258. rc = sqlite3_step(s);
  88259. /* TODO(shess): This case should not be possible? Should stronger
  88260. ** measures be taken if it happens?
  88261. */
  88262. if( rc==SQLITE_DONE ){
  88263. *pnSegments = 0;
  88264. *piMaxLevel = 0;
  88265. return SQLITE_OK;
  88266. }
  88267. if( rc!=SQLITE_ROW ) return rc;
  88268. *pnSegments = sqlite3_column_int(s, 0);
  88269. *piMaxLevel = sqlite3_column_int(s, 1);
  88270. /* We expect only one row. We must execute another sqlite3_step()
  88271. * to complete the iteration; otherwise the table will remain locked. */
  88272. rc = sqlite3_step(s);
  88273. if( rc==SQLITE_DONE ) return SQLITE_OK;
  88274. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  88275. return rc;
  88276. }
  88277. /* TODO(shess) clearPendingTerms() is far down the file because
  88278. ** writeZeroSegment() is far down the file because LeafWriter is far
  88279. ** down the file. Consider refactoring the code to move the non-vtab
  88280. ** code above the vtab code so that we don't need this forward
  88281. ** reference.
  88282. */
  88283. static int clearPendingTerms(fulltext_vtab *v);
  88284. /*
  88285. ** Free the memory used to contain a fulltext_vtab structure.
  88286. */
  88287. static void fulltext_vtab_destroy(fulltext_vtab *v){
  88288. int iStmt, i;
  88289. FTSTRACE(("FTS3 Destroy %p\n", v));
  88290. for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
  88291. if( v->pFulltextStatements[iStmt]!=NULL ){
  88292. sqlite3_finalize(v->pFulltextStatements[iStmt]);
  88293. v->pFulltextStatements[iStmt] = NULL;
  88294. }
  88295. }
  88296. for( i=0; i<MERGE_COUNT; i++ ){
  88297. if( v->pLeafSelectStmts[i]!=NULL ){
  88298. sqlite3_finalize(v->pLeafSelectStmts[i]);
  88299. v->pLeafSelectStmts[i] = NULL;
  88300. }
  88301. }
  88302. if( v->pTokenizer!=NULL ){
  88303. v->pTokenizer->pModule->xDestroy(v->pTokenizer);
  88304. v->pTokenizer = NULL;
  88305. }
  88306. clearPendingTerms(v);
  88307. sqlite3_free(v->azColumn);
  88308. for(i = 0; i < v->nColumn; ++i) {
  88309. sqlite3_free(v->azContentColumn[i]);
  88310. }
  88311. sqlite3_free(v->azContentColumn);
  88312. sqlite3_free(v);
  88313. }
  88314. /*
  88315. ** Token types for parsing the arguments to xConnect or xCreate.
  88316. */
  88317. #define TOKEN_EOF 0 /* End of file */
  88318. #define TOKEN_SPACE 1 /* Any kind of whitespace */
  88319. #define TOKEN_ID 2 /* An identifier */
  88320. #define TOKEN_STRING 3 /* A string literal */
  88321. #define TOKEN_PUNCT 4 /* A single punctuation character */
  88322. /*
  88323. ** If X is a character that can be used in an identifier then
  88324. ** ftsIdChar(X) will be true. Otherwise it is false.
  88325. **
  88326. ** For ASCII, any character with the high-order bit set is
  88327. ** allowed in an identifier. For 7-bit characters,
  88328. ** isFtsIdChar[X] must be 1.
  88329. **
  88330. ** Ticket #1066. the SQL standard does not allow '$' in the
  88331. ** middle of identfiers. But many SQL implementations do.
  88332. ** SQLite will allow '$' in identifiers for compatibility.
  88333. ** But the feature is undocumented.
  88334. */
  88335. static const char isFtsIdChar[] = {
  88336. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  88337. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  88338. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  88339. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  88340. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  88341. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  88342. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  88343. };
  88344. #define ftsIdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
  88345. /*
  88346. ** Return the length of the token that begins at z[0].
  88347. ** Store the token type in *tokenType before returning.
  88348. */
  88349. static int ftsGetToken(const char *z, int *tokenType){
  88350. int i, c;
  88351. switch( *z ){
  88352. case 0: {
  88353. *tokenType = TOKEN_EOF;
  88354. return 0;
  88355. }
  88356. case ' ': case '\t': case '\n': case '\f': case '\r': {
  88357. for(i=1; safe_isspace(z[i]); i++){}
  88358. *tokenType = TOKEN_SPACE;
  88359. return i;
  88360. }
  88361. case '`':
  88362. case '\'':
  88363. case '"': {
  88364. int delim = z[0];
  88365. for(i=1; (c=z[i])!=0; i++){
  88366. if( c==delim ){
  88367. if( z[i+1]==delim ){
  88368. i++;
  88369. }else{
  88370. break;
  88371. }
  88372. }
  88373. }
  88374. *tokenType = TOKEN_STRING;
  88375. return i + (c!=0);
  88376. }
  88377. case '[': {
  88378. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  88379. *tokenType = TOKEN_ID;
  88380. return i;
  88381. }
  88382. default: {
  88383. if( !ftsIdChar(*z) ){
  88384. break;
  88385. }
  88386. for(i=1; ftsIdChar(z[i]); i++){}
  88387. *tokenType = TOKEN_ID;
  88388. return i;
  88389. }
  88390. }
  88391. *tokenType = TOKEN_PUNCT;
  88392. return 1;
  88393. }
  88394. /*
  88395. ** A token extracted from a string is an instance of the following
  88396. ** structure.
  88397. */
  88398. typedef struct FtsToken {
  88399. const char *z; /* Pointer to token text. Not '\000' terminated */
  88400. short int n; /* Length of the token text in bytes. */
  88401. } FtsToken;
  88402. /*
  88403. ** Given a input string (which is really one of the argv[] parameters
  88404. ** passed into xConnect or xCreate) split the string up into tokens.
  88405. ** Return an array of pointers to '\000' terminated strings, one string
  88406. ** for each non-whitespace token.
  88407. **
  88408. ** The returned array is terminated by a single NULL pointer.
  88409. **
  88410. ** Space to hold the returned array is obtained from a single
  88411. ** malloc and should be freed by passing the return value to free().
  88412. ** The individual strings within the token list are all a part of
  88413. ** the single memory allocation and will all be freed at once.
  88414. */
  88415. static char **tokenizeString(const char *z, int *pnToken){
  88416. int nToken = 0;
  88417. FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
  88418. int n = 1;
  88419. int e, i;
  88420. int totalSize = 0;
  88421. char **azToken;
  88422. char *zCopy;
  88423. while( n>0 ){
  88424. n = ftsGetToken(z, &e);
  88425. if( e!=TOKEN_SPACE ){
  88426. aToken[nToken].z = z;
  88427. aToken[nToken].n = n;
  88428. nToken++;
  88429. totalSize += n+1;
  88430. }
  88431. z += n;
  88432. }
  88433. azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
  88434. zCopy = (char*)&azToken[nToken];
  88435. nToken--;
  88436. for(i=0; i<nToken; i++){
  88437. azToken[i] = zCopy;
  88438. n = aToken[i].n;
  88439. memcpy(zCopy, aToken[i].z, n);
  88440. zCopy[n] = 0;
  88441. zCopy += n+1;
  88442. }
  88443. azToken[nToken] = 0;
  88444. sqlite3_free(aToken);
  88445. *pnToken = nToken;
  88446. return azToken;
  88447. }
  88448. /*
  88449. ** Convert an SQL-style quoted string into a normal string by removing
  88450. ** the quote characters. The conversion is done in-place. If the
  88451. ** input does not begin with a quote character, then this routine
  88452. ** is a no-op.
  88453. **
  88454. ** Examples:
  88455. **
  88456. ** "abc" becomes abc
  88457. ** 'xyz' becomes xyz
  88458. ** [pqr] becomes pqr
  88459. ** `mno` becomes mno
  88460. */
  88461. static void dequoteString(char *z){
  88462. int quote;
  88463. int i, j;
  88464. if( z==0 ) return;
  88465. quote = z[0];
  88466. switch( quote ){
  88467. case '\'': break;
  88468. case '"': break;
  88469. case '`': break; /* For MySQL compatibility */
  88470. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  88471. default: return;
  88472. }
  88473. for(i=1, j=0; z[i]; i++){
  88474. if( z[i]==quote ){
  88475. if( z[i+1]==quote ){
  88476. z[j++] = quote;
  88477. i++;
  88478. }else{
  88479. z[j++] = 0;
  88480. break;
  88481. }
  88482. }else{
  88483. z[j++] = z[i];
  88484. }
  88485. }
  88486. }
  88487. /*
  88488. ** The input azIn is a NULL-terminated list of tokens. Remove the first
  88489. ** token and all punctuation tokens. Remove the quotes from
  88490. ** around string literal tokens.
  88491. **
  88492. ** Example:
  88493. **
  88494. ** input: tokenize chinese ( 'simplifed' , 'mixed' )
  88495. ** output: chinese simplifed mixed
  88496. **
  88497. ** Another example:
  88498. **
  88499. ** input: delimiters ( '[' , ']' , '...' )
  88500. ** output: [ ] ...
  88501. */
  88502. static void tokenListToIdList(char **azIn){
  88503. int i, j;
  88504. if( azIn ){
  88505. for(i=0, j=-1; azIn[i]; i++){
  88506. if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
  88507. dequoteString(azIn[i]);
  88508. if( j>=0 ){
  88509. azIn[j] = azIn[i];
  88510. }
  88511. j++;
  88512. }
  88513. }
  88514. azIn[j] = 0;
  88515. }
  88516. }
  88517. /*
  88518. ** Find the first alphanumeric token in the string zIn. Null-terminate
  88519. ** this token. Remove any quotation marks. And return a pointer to
  88520. ** the result.
  88521. */
  88522. static char *firstToken(char *zIn, char **pzTail){
  88523. int n, ttype;
  88524. while(1){
  88525. n = ftsGetToken(zIn, &ttype);
  88526. if( ttype==TOKEN_SPACE ){
  88527. zIn += n;
  88528. }else if( ttype==TOKEN_EOF ){
  88529. *pzTail = zIn;
  88530. return 0;
  88531. }else{
  88532. zIn[n] = 0;
  88533. *pzTail = &zIn[1];
  88534. dequoteString(zIn);
  88535. return zIn;
  88536. }
  88537. }
  88538. /*NOTREACHED*/
  88539. }
  88540. /* Return true if...
  88541. **
  88542. ** * s begins with the string t, ignoring case
  88543. ** * s is longer than t
  88544. ** * The first character of s beyond t is not a alphanumeric
  88545. **
  88546. ** Ignore leading space in *s.
  88547. **
  88548. ** To put it another way, return true if the first token of
  88549. ** s[] is t[].
  88550. */
  88551. static int startsWith(const char *s, const char *t){
  88552. while( safe_isspace(*s) ){ s++; }
  88553. while( *t ){
  88554. if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
  88555. }
  88556. return *s!='_' && !safe_isalnum(*s);
  88557. }
  88558. /*
  88559. ** An instance of this structure defines the "spec" of a
  88560. ** full text index. This structure is populated by parseSpec
  88561. ** and use by fulltextConnect and fulltextCreate.
  88562. */
  88563. typedef struct TableSpec {
  88564. const char *zDb; /* Logical database name */
  88565. const char *zName; /* Name of the full-text index */
  88566. int nColumn; /* Number of columns to be indexed */
  88567. char **azColumn; /* Original names of columns to be indexed */
  88568. char **azContentColumn; /* Column names for %_content */
  88569. char **azTokenizer; /* Name of tokenizer and its arguments */
  88570. } TableSpec;
  88571. /*
  88572. ** Reclaim all of the memory used by a TableSpec
  88573. */
  88574. static void clearTableSpec(TableSpec *p) {
  88575. sqlite3_free(p->azColumn);
  88576. sqlite3_free(p->azContentColumn);
  88577. sqlite3_free(p->azTokenizer);
  88578. }
  88579. /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
  88580. *
  88581. * CREATE VIRTUAL TABLE email
  88582. * USING fts3(subject, body, tokenize mytokenizer(myarg))
  88583. *
  88584. * We return parsed information in a TableSpec structure.
  88585. *
  88586. */
  88587. static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
  88588. char**pzErr){
  88589. int i, n;
  88590. char *z, *zDummy;
  88591. char **azArg;
  88592. const char *zTokenizer = 0; /* argv[] entry describing the tokenizer */
  88593. assert( argc>=3 );
  88594. /* Current interface:
  88595. ** argv[0] - module name
  88596. ** argv[1] - database name
  88597. ** argv[2] - table name
  88598. ** argv[3..] - columns, optionally followed by tokenizer specification
  88599. ** and snippet delimiters specification.
  88600. */
  88601. /* Make a copy of the complete argv[][] array in a single allocation.
  88602. ** The argv[][] array is read-only and transient. We can write to the
  88603. ** copy in order to modify things and the copy is persistent.
  88604. */
  88605. CLEAR(pSpec);
  88606. for(i=n=0; i<argc; i++){
  88607. n += strlen(argv[i]) + 1;
  88608. }
  88609. azArg = sqlite3_malloc( sizeof(char*)*argc + n );
  88610. if( azArg==0 ){
  88611. return SQLITE_NOMEM;
  88612. }
  88613. z = (char*)&azArg[argc];
  88614. for(i=0; i<argc; i++){
  88615. azArg[i] = z;
  88616. strcpy(z, argv[i]);
  88617. z += strlen(z)+1;
  88618. }
  88619. /* Identify the column names and the tokenizer and delimiter arguments
  88620. ** in the argv[][] array.
  88621. */
  88622. pSpec->zDb = azArg[1];
  88623. pSpec->zName = azArg[2];
  88624. pSpec->nColumn = 0;
  88625. pSpec->azColumn = azArg;
  88626. zTokenizer = "tokenize simple";
  88627. for(i=3; i<argc; ++i){
  88628. if( startsWith(azArg[i],"tokenize") ){
  88629. zTokenizer = azArg[i];
  88630. }else{
  88631. z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
  88632. pSpec->nColumn++;
  88633. }
  88634. }
  88635. if( pSpec->nColumn==0 ){
  88636. azArg[0] = "content";
  88637. pSpec->nColumn = 1;
  88638. }
  88639. /*
  88640. ** Construct the list of content column names.
  88641. **
  88642. ** Each content column name will be of the form cNNAAAA
  88643. ** where NN is the column number and AAAA is the sanitized
  88644. ** column name. "sanitized" means that special characters are
  88645. ** converted to "_". The cNN prefix guarantees that all column
  88646. ** names are unique.
  88647. **
  88648. ** The AAAA suffix is not strictly necessary. It is included
  88649. ** for the convenience of people who might examine the generated
  88650. ** %_content table and wonder what the columns are used for.
  88651. */
  88652. pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
  88653. if( pSpec->azContentColumn==0 ){
  88654. clearTableSpec(pSpec);
  88655. return SQLITE_NOMEM;
  88656. }
  88657. for(i=0; i<pSpec->nColumn; i++){
  88658. char *p;
  88659. pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
  88660. for (p = pSpec->azContentColumn[i]; *p ; ++p) {
  88661. if( !safe_isalnum(*p) ) *p = '_';
  88662. }
  88663. }
  88664. /*
  88665. ** Parse the tokenizer specification string.
  88666. */
  88667. pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
  88668. tokenListToIdList(pSpec->azTokenizer);
  88669. return SQLITE_OK;
  88670. }
  88671. /*
  88672. ** Generate a CREATE TABLE statement that describes the schema of
  88673. ** the virtual table. Return a pointer to this schema string.
  88674. **
  88675. ** Space is obtained from sqlite3_mprintf() and should be freed
  88676. ** using sqlite3_free().
  88677. */
  88678. static char *fulltextSchema(
  88679. int nColumn, /* Number of columns */
  88680. const char *const* azColumn, /* List of columns */
  88681. const char *zTableName /* Name of the table */
  88682. ){
  88683. int i;
  88684. char *zSchema, *zNext;
  88685. const char *zSep = "(";
  88686. zSchema = sqlite3_mprintf("CREATE TABLE x");
  88687. for(i=0; i<nColumn; i++){
  88688. zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
  88689. sqlite3_free(zSchema);
  88690. zSchema = zNext;
  88691. zSep = ",";
  88692. }
  88693. zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
  88694. sqlite3_free(zSchema);
  88695. zSchema = zNext;
  88696. zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
  88697. sqlite3_free(zSchema);
  88698. return zNext;
  88699. }
  88700. /*
  88701. ** Build a new sqlite3_vtab structure that will describe the
  88702. ** fulltext index defined by spec.
  88703. */
  88704. static int constructVtab(
  88705. sqlite3 *db, /* The SQLite database connection */
  88706. fts3Hash *pHash, /* Hash table containing tokenizers */
  88707. TableSpec *spec, /* Parsed spec information from parseSpec() */
  88708. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  88709. char **pzErr /* Write any error message here */
  88710. ){
  88711. int rc;
  88712. int n;
  88713. fulltext_vtab *v = 0;
  88714. const sqlite3_tokenizer_module *m = NULL;
  88715. char *schema;
  88716. char const *zTok; /* Name of tokenizer to use for this fts table */
  88717. int nTok; /* Length of zTok, including nul terminator */
  88718. v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
  88719. if( v==0 ) return SQLITE_NOMEM;
  88720. CLEAR(v);
  88721. /* sqlite will initialize v->base */
  88722. v->db = db;
  88723. v->zDb = spec->zDb; /* Freed when azColumn is freed */
  88724. v->zName = spec->zName; /* Freed when azColumn is freed */
  88725. v->nColumn = spec->nColumn;
  88726. v->azContentColumn = spec->azContentColumn;
  88727. spec->azContentColumn = 0;
  88728. v->azColumn = spec->azColumn;
  88729. spec->azColumn = 0;
  88730. if( spec->azTokenizer==0 ){
  88731. return SQLITE_NOMEM;
  88732. }
  88733. zTok = spec->azTokenizer[0];
  88734. if( !zTok ){
  88735. zTok = "simple";
  88736. }
  88737. nTok = strlen(zTok)+1;
  88738. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
  88739. if( !m ){
  88740. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
  88741. rc = SQLITE_ERROR;
  88742. goto err;
  88743. }
  88744. for(n=0; spec->azTokenizer[n]; n++){}
  88745. if( n ){
  88746. rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
  88747. &v->pTokenizer);
  88748. }else{
  88749. rc = m->xCreate(0, 0, &v->pTokenizer);
  88750. }
  88751. if( rc!=SQLITE_OK ) goto err;
  88752. v->pTokenizer->pModule = m;
  88753. /* TODO: verify the existence of backing tables foo_content, foo_term */
  88754. schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
  88755. spec->zName);
  88756. rc = sqlite3_declare_vtab(db, schema);
  88757. sqlite3_free(schema);
  88758. if( rc!=SQLITE_OK ) goto err;
  88759. memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
  88760. /* Indicate that the buffer is not live. */
  88761. v->nPendingData = -1;
  88762. *ppVTab = &v->base;
  88763. FTSTRACE(("FTS3 Connect %p\n", v));
  88764. return rc;
  88765. err:
  88766. fulltext_vtab_destroy(v);
  88767. return rc;
  88768. }
  88769. static int fulltextConnect(
  88770. sqlite3 *db,
  88771. void *pAux,
  88772. int argc, const char *const*argv,
  88773. sqlite3_vtab **ppVTab,
  88774. char **pzErr
  88775. ){
  88776. TableSpec spec;
  88777. int rc = parseSpec(&spec, argc, argv, pzErr);
  88778. if( rc!=SQLITE_OK ) return rc;
  88779. rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
  88780. clearTableSpec(&spec);
  88781. return rc;
  88782. }
  88783. /* The %_content table holds the text of each document, with
  88784. ** the docid column exposed as the SQLite rowid for the table.
  88785. */
  88786. /* TODO(shess) This comment needs elaboration to match the updated
  88787. ** code. Work it into the top-of-file comment at that time.
  88788. */
  88789. static int fulltextCreate(sqlite3 *db, void *pAux,
  88790. int argc, const char * const *argv,
  88791. sqlite3_vtab **ppVTab, char **pzErr){
  88792. int rc;
  88793. TableSpec spec;
  88794. StringBuffer schema;
  88795. FTSTRACE(("FTS3 Create\n"));
  88796. rc = parseSpec(&spec, argc, argv, pzErr);
  88797. if( rc!=SQLITE_OK ) return rc;
  88798. initStringBuffer(&schema);
  88799. append(&schema, "CREATE TABLE %_content(");
  88800. append(&schema, " docid INTEGER PRIMARY KEY,");
  88801. appendList(&schema, spec.nColumn, spec.azContentColumn);
  88802. append(&schema, ")");
  88803. rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
  88804. stringBufferDestroy(&schema);
  88805. if( rc!=SQLITE_OK ) goto out;
  88806. rc = sql_exec(db, spec.zDb, spec.zName,
  88807. "create table %_segments("
  88808. " blockid INTEGER PRIMARY KEY,"
  88809. " block blob"
  88810. ");"
  88811. );
  88812. if( rc!=SQLITE_OK ) goto out;
  88813. rc = sql_exec(db, spec.zDb, spec.zName,
  88814. "create table %_segdir("
  88815. " level integer,"
  88816. " idx integer,"
  88817. " start_block integer,"
  88818. " leaves_end_block integer,"
  88819. " end_block integer,"
  88820. " root blob,"
  88821. " primary key(level, idx)"
  88822. ");");
  88823. if( rc!=SQLITE_OK ) goto out;
  88824. rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
  88825. out:
  88826. clearTableSpec(&spec);
  88827. return rc;
  88828. }
  88829. /* Decide how to handle an SQL query. */
  88830. static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  88831. fulltext_vtab *v = (fulltext_vtab *)pVTab;
  88832. int i;
  88833. FTSTRACE(("FTS3 BestIndex\n"));
  88834. for(i=0; i<pInfo->nConstraint; ++i){
  88835. const struct sqlite3_index_constraint *pConstraint;
  88836. pConstraint = &pInfo->aConstraint[i];
  88837. if( pConstraint->usable ) {
  88838. if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
  88839. pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  88840. pInfo->idxNum = QUERY_DOCID; /* lookup by docid */
  88841. FTSTRACE(("FTS3 QUERY_DOCID\n"));
  88842. } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
  88843. pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  88844. /* full-text search */
  88845. pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
  88846. FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
  88847. } else continue;
  88848. pInfo->aConstraintUsage[i].argvIndex = 1;
  88849. pInfo->aConstraintUsage[i].omit = 1;
  88850. /* An arbitrary value for now.
  88851. * TODO: Perhaps docid matches should be considered cheaper than
  88852. * full-text searches. */
  88853. pInfo->estimatedCost = 1.0;
  88854. return SQLITE_OK;
  88855. }
  88856. }
  88857. pInfo->idxNum = QUERY_GENERIC;
  88858. return SQLITE_OK;
  88859. }
  88860. static int fulltextDisconnect(sqlite3_vtab *pVTab){
  88861. FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
  88862. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  88863. return SQLITE_OK;
  88864. }
  88865. static int fulltextDestroy(sqlite3_vtab *pVTab){
  88866. fulltext_vtab *v = (fulltext_vtab *)pVTab;
  88867. int rc;
  88868. FTSTRACE(("FTS3 Destroy %p\n", pVTab));
  88869. rc = sql_exec(v->db, v->zDb, v->zName,
  88870. "drop table if exists %_content;"
  88871. "drop table if exists %_segments;"
  88872. "drop table if exists %_segdir;"
  88873. );
  88874. if( rc!=SQLITE_OK ) return rc;
  88875. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  88876. return SQLITE_OK;
  88877. }
  88878. static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  88879. fulltext_cursor *c;
  88880. c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
  88881. if( c ){
  88882. memset(c, 0, sizeof(fulltext_cursor));
  88883. /* sqlite will initialize c->base */
  88884. *ppCursor = &c->base;
  88885. FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
  88886. return SQLITE_OK;
  88887. }else{
  88888. return SQLITE_NOMEM;
  88889. }
  88890. }
  88891. /* Free all of the dynamically allocated memory held by the
  88892. ** Snippet
  88893. */
  88894. static void snippetClear(Snippet *p){
  88895. sqlite3_free(p->aMatch);
  88896. sqlite3_free(p->zOffset);
  88897. sqlite3_free(p->zSnippet);
  88898. CLEAR(p);
  88899. }
  88900. /*
  88901. ** Append a single entry to the p->aMatch[] log.
  88902. */
  88903. static void snippetAppendMatch(
  88904. Snippet *p, /* Append the entry to this snippet */
  88905. int iCol, int iTerm, /* The column and query term */
  88906. int iToken, /* Matching token in document */
  88907. int iStart, int nByte /* Offset and size of the match */
  88908. ){
  88909. int i;
  88910. struct snippetMatch *pMatch;
  88911. if( p->nMatch+1>=p->nAlloc ){
  88912. p->nAlloc = p->nAlloc*2 + 10;
  88913. p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
  88914. if( p->aMatch==0 ){
  88915. p->nMatch = 0;
  88916. p->nAlloc = 0;
  88917. return;
  88918. }
  88919. }
  88920. i = p->nMatch++;
  88921. pMatch = &p->aMatch[i];
  88922. pMatch->iCol = iCol;
  88923. pMatch->iTerm = iTerm;
  88924. pMatch->iToken = iToken;
  88925. pMatch->iStart = iStart;
  88926. pMatch->nByte = nByte;
  88927. }
  88928. /*
  88929. ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
  88930. */
  88931. #define FTS3_ROTOR_SZ (32)
  88932. #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
  88933. /*
  88934. ** Function to iterate through the tokens of a compiled expression.
  88935. **
  88936. ** Except, skip all tokens on the right-hand side of a NOT operator.
  88937. ** This function is used to find tokens as part of snippet and offset
  88938. ** generation and we do nt want snippets and offsets to report matches
  88939. ** for tokens on the RHS of a NOT.
  88940. */
  88941. static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
  88942. Fts3Expr *p = *ppExpr;
  88943. int iToken = *piToken;
  88944. if( iToken<0 ){
  88945. /* In this case the expression p is the root of an expression tree.
  88946. ** Move to the first token in the expression tree.
  88947. */
  88948. while( p->pLeft ){
  88949. p = p->pLeft;
  88950. }
  88951. iToken = 0;
  88952. }else{
  88953. assert(p && p->eType==FTSQUERY_PHRASE );
  88954. if( iToken<(p->pPhrase->nToken-1) ){
  88955. iToken++;
  88956. }else{
  88957. iToken = 0;
  88958. while( p->pParent && p->pParent->pLeft!=p ){
  88959. assert( p->pParent->pRight==p );
  88960. p = p->pParent;
  88961. }
  88962. p = p->pParent;
  88963. if( p ){
  88964. assert( p->pRight!=0 );
  88965. p = p->pRight;
  88966. while( p->pLeft ){
  88967. p = p->pLeft;
  88968. }
  88969. }
  88970. }
  88971. }
  88972. *ppExpr = p;
  88973. *piToken = iToken;
  88974. return p?1:0;
  88975. }
  88976. /*
  88977. ** Return TRUE if the expression node pExpr is located beneath the
  88978. ** RHS of a NOT operator.
  88979. */
  88980. static int fts3ExprBeneathNot(Fts3Expr *p){
  88981. Fts3Expr *pParent;
  88982. while( p ){
  88983. pParent = p->pParent;
  88984. if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
  88985. return 1;
  88986. }
  88987. p = pParent;
  88988. }
  88989. return 0;
  88990. }
  88991. /*
  88992. ** Add entries to pSnippet->aMatch[] for every match that occurs against
  88993. ** document zDoc[0..nDoc-1] which is stored in column iColumn.
  88994. */
  88995. static void snippetOffsetsOfColumn(
  88996. fulltext_cursor *pCur, /* The fulltest search cursor */
  88997. Snippet *pSnippet, /* The Snippet object to be filled in */
  88998. int iColumn, /* Index of fulltext table column */
  88999. const char *zDoc, /* Text of the fulltext table column */
  89000. int nDoc /* Length of zDoc in bytes */
  89001. ){
  89002. const sqlite3_tokenizer_module *pTModule; /* The tokenizer module */
  89003. sqlite3_tokenizer *pTokenizer; /* The specific tokenizer */
  89004. sqlite3_tokenizer_cursor *pTCursor; /* Tokenizer cursor */
  89005. fulltext_vtab *pVtab; /* The full text index */
  89006. int nColumn; /* Number of columns in the index */
  89007. int i, j; /* Loop counters */
  89008. int rc; /* Return code */
  89009. unsigned int match, prevMatch; /* Phrase search bitmasks */
  89010. const char *zToken; /* Next token from the tokenizer */
  89011. int nToken; /* Size of zToken */
  89012. int iBegin, iEnd, iPos; /* Offsets of beginning and end */
  89013. /* The following variables keep a circular buffer of the last
  89014. ** few tokens */
  89015. unsigned int iRotor = 0; /* Index of current token */
  89016. int iRotorBegin[FTS3_ROTOR_SZ]; /* Beginning offset of token */
  89017. int iRotorLen[FTS3_ROTOR_SZ]; /* Length of token */
  89018. pVtab = cursor_vtab(pCur);
  89019. nColumn = pVtab->nColumn;
  89020. pTokenizer = pVtab->pTokenizer;
  89021. pTModule = pTokenizer->pModule;
  89022. rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
  89023. if( rc ) return;
  89024. pTCursor->pTokenizer = pTokenizer;
  89025. prevMatch = 0;
  89026. while( !pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos) ){
  89027. Fts3Expr *pIter = pCur->pExpr;
  89028. int iIter = -1;
  89029. iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
  89030. iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
  89031. match = 0;
  89032. for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
  89033. int nPhrase; /* Number of tokens in current phrase */
  89034. struct PhraseToken *pToken; /* Current token */
  89035. int iCol; /* Column index */
  89036. if( fts3ExprBeneathNot(pIter) ) continue;
  89037. nPhrase = pIter->pPhrase->nToken;
  89038. pToken = &pIter->pPhrase->aToken[iIter];
  89039. iCol = pIter->pPhrase->iColumn;
  89040. if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
  89041. if( pToken->n>nToken ) continue;
  89042. if( !pToken->isPrefix && pToken->n<nToken ) continue;
  89043. assert( pToken->n<=nToken );
  89044. if( memcmp(pToken->z, zToken, pToken->n) ) continue;
  89045. if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
  89046. match |= 1<<i;
  89047. if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
  89048. for(j=nPhrase-1; j>=0; j--){
  89049. int k = (iRotor-j) & FTS3_ROTOR_MASK;
  89050. snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
  89051. iRotorBegin[k], iRotorLen[k]);
  89052. }
  89053. }
  89054. }
  89055. prevMatch = match<<1;
  89056. iRotor++;
  89057. }
  89058. pTModule->xClose(pTCursor);
  89059. }
  89060. /*
  89061. ** Remove entries from the pSnippet structure to account for the NEAR
  89062. ** operator. When this is called, pSnippet contains the list of token
  89063. ** offsets produced by treating all NEAR operators as AND operators.
  89064. ** This function removes any entries that should not be present after
  89065. ** accounting for the NEAR restriction. For example, if the queried
  89066. ** document is:
  89067. **
  89068. ** "A B C D E A"
  89069. **
  89070. ** and the query is:
  89071. **
  89072. ** A NEAR/0 E
  89073. **
  89074. ** then when this function is called the Snippet contains token offsets
  89075. ** 0, 4 and 5. This function removes the "0" entry (because the first A
  89076. ** is not near enough to an E).
  89077. **
  89078. ** When this function is called, the value pointed to by parameter piLeft is
  89079. ** the integer id of the left-most token in the expression tree headed by
  89080. ** pExpr. This function increments *piLeft by the total number of tokens
  89081. ** in the expression tree headed by pExpr.
  89082. **
  89083. ** Return 1 if any trimming occurs. Return 0 if no trimming is required.
  89084. */
  89085. static int trimSnippetOffsets(
  89086. Fts3Expr *pExpr, /* The search expression */
  89087. Snippet *pSnippet, /* The set of snippet offsets to be trimmed */
  89088. int *piLeft /* Index of left-most token in pExpr */
  89089. ){
  89090. if( pExpr ){
  89091. if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
  89092. return 1;
  89093. }
  89094. switch( pExpr->eType ){
  89095. case FTSQUERY_PHRASE:
  89096. *piLeft += pExpr->pPhrase->nToken;
  89097. break;
  89098. case FTSQUERY_NEAR: {
  89099. /* The right-hand-side of a NEAR operator is always a phrase. The
  89100. ** left-hand-side is either a phrase or an expression tree that is
  89101. ** itself headed by a NEAR operator. The following initializations
  89102. ** set local variable iLeft to the token number of the left-most
  89103. ** token in the right-hand phrase, and iRight to the right most
  89104. ** token in the same phrase. For example, if we had:
  89105. **
  89106. ** <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
  89107. **
  89108. ** then iLeft will be set to 2 (token number of ghi) and nToken will
  89109. ** be set to 4.
  89110. */
  89111. Fts3Expr *pLeft = pExpr->pLeft;
  89112. Fts3Expr *pRight = pExpr->pRight;
  89113. int iLeft = *piLeft;
  89114. int nNear = pExpr->nNear;
  89115. int nToken = pRight->pPhrase->nToken;
  89116. int jj, ii;
  89117. if( pLeft->eType==FTSQUERY_NEAR ){
  89118. pLeft = pLeft->pRight;
  89119. }
  89120. assert( pRight->eType==FTSQUERY_PHRASE );
  89121. assert( pLeft->eType==FTSQUERY_PHRASE );
  89122. nToken += pLeft->pPhrase->nToken;
  89123. for(ii=0; ii<pSnippet->nMatch; ii++){
  89124. struct snippetMatch *p = &pSnippet->aMatch[ii];
  89125. if( p->iTerm==iLeft ){
  89126. int isOk = 0;
  89127. /* Snippet ii is an occurence of query term iLeft in the document.
  89128. ** It occurs at position (p->iToken) of the document. We now
  89129. ** search for an instance of token (iLeft-1) somewhere in the
  89130. ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
  89131. ** the set of snippetMatch structures. If one is found, proceed.
  89132. ** If one cannot be found, then remove snippets ii..(ii+N-1)
  89133. ** from the matching snippets, where N is the number of tokens
  89134. ** in phrase pRight->pPhrase.
  89135. */
  89136. for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
  89137. struct snippetMatch *p2 = &pSnippet->aMatch[jj];
  89138. if( p2->iTerm==(iLeft-1) ){
  89139. if( p2->iToken>=(p->iToken-nNear-1)
  89140. && p2->iToken<(p->iToken+nNear+nToken)
  89141. ){
  89142. isOk = 1;
  89143. }
  89144. }
  89145. }
  89146. if( !isOk ){
  89147. int kk;
  89148. for(kk=0; kk<pRight->pPhrase->nToken; kk++){
  89149. pSnippet->aMatch[kk+ii].iTerm = -2;
  89150. }
  89151. return 1;
  89152. }
  89153. }
  89154. if( p->iTerm==(iLeft-1) ){
  89155. int isOk = 0;
  89156. for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
  89157. struct snippetMatch *p2 = &pSnippet->aMatch[jj];
  89158. if( p2->iTerm==iLeft ){
  89159. if( p2->iToken<=(p->iToken+nNear+1)
  89160. && p2->iToken>(p->iToken-nNear-nToken)
  89161. ){
  89162. isOk = 1;
  89163. }
  89164. }
  89165. }
  89166. if( !isOk ){
  89167. int kk;
  89168. for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
  89169. pSnippet->aMatch[ii-kk].iTerm = -2;
  89170. }
  89171. return 1;
  89172. }
  89173. }
  89174. }
  89175. break;
  89176. }
  89177. }
  89178. if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
  89179. return 1;
  89180. }
  89181. }
  89182. return 0;
  89183. }
  89184. /*
  89185. ** Compute all offsets for the current row of the query.
  89186. ** If the offsets have already been computed, this routine is a no-op.
  89187. */
  89188. static void snippetAllOffsets(fulltext_cursor *p){
  89189. int nColumn;
  89190. int iColumn, i;
  89191. int iFirst, iLast;
  89192. int iTerm = 0;
  89193. fulltext_vtab *pFts = cursor_vtab(p);
  89194. if( p->snippet.nMatch || p->pExpr==0 ){
  89195. return;
  89196. }
  89197. nColumn = pFts->nColumn;
  89198. iColumn = (p->iCursorType - QUERY_FULLTEXT);
  89199. if( iColumn<0 || iColumn>=nColumn ){
  89200. /* Look for matches over all columns of the full-text index */
  89201. iFirst = 0;
  89202. iLast = nColumn-1;
  89203. }else{
  89204. /* Look for matches in the iColumn-th column of the index only */
  89205. iFirst = iColumn;
  89206. iLast = iColumn;
  89207. }
  89208. for(i=iFirst; i<=iLast; i++){
  89209. const char *zDoc;
  89210. int nDoc;
  89211. zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
  89212. nDoc = sqlite3_column_bytes(p->pStmt, i+1);
  89213. snippetOffsetsOfColumn(p, &p->snippet, i, zDoc, nDoc);
  89214. }
  89215. while( trimSnippetOffsets(p->pExpr, &p->snippet, &iTerm) ){
  89216. iTerm = 0;
  89217. }
  89218. }
  89219. /*
  89220. ** Convert the information in the aMatch[] array of the snippet
  89221. ** into the string zOffset[0..nOffset-1]. This string is used as
  89222. ** the return of the SQL offsets() function.
  89223. */
  89224. static void snippetOffsetText(Snippet *p){
  89225. int i;
  89226. int cnt = 0;
  89227. StringBuffer sb;
  89228. char zBuf[200];
  89229. if( p->zOffset ) return;
  89230. initStringBuffer(&sb);
  89231. for(i=0; i<p->nMatch; i++){
  89232. struct snippetMatch *pMatch = &p->aMatch[i];
  89233. if( pMatch->iTerm>=0 ){
  89234. /* If snippetMatch.iTerm is less than 0, then the match was
  89235. ** discarded as part of processing the NEAR operator (see the
  89236. ** trimSnippetOffsetsForNear() function for details). Ignore
  89237. ** it in this case
  89238. */
  89239. zBuf[0] = ' ';
  89240. sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
  89241. pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
  89242. append(&sb, zBuf);
  89243. cnt++;
  89244. }
  89245. }
  89246. p->zOffset = stringBufferData(&sb);
  89247. p->nOffset = stringBufferLength(&sb);
  89248. }
  89249. /*
  89250. ** zDoc[0..nDoc-1] is phrase of text. aMatch[0..nMatch-1] are a set
  89251. ** of matching words some of which might be in zDoc. zDoc is column
  89252. ** number iCol.
  89253. **
  89254. ** iBreak is suggested spot in zDoc where we could begin or end an
  89255. ** excerpt. Return a value similar to iBreak but possibly adjusted
  89256. ** to be a little left or right so that the break point is better.
  89257. */
  89258. static int wordBoundary(
  89259. int iBreak, /* The suggested break point */
  89260. const char *zDoc, /* Document text */
  89261. int nDoc, /* Number of bytes in zDoc[] */
  89262. struct snippetMatch *aMatch, /* Matching words */
  89263. int nMatch, /* Number of entries in aMatch[] */
  89264. int iCol /* The column number for zDoc[] */
  89265. ){
  89266. int i;
  89267. if( iBreak<=10 ){
  89268. return 0;
  89269. }
  89270. if( iBreak>=nDoc-10 ){
  89271. return nDoc;
  89272. }
  89273. for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
  89274. while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
  89275. if( i<nMatch ){
  89276. if( aMatch[i].iStart<iBreak+10 ){
  89277. return aMatch[i].iStart;
  89278. }
  89279. if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
  89280. return aMatch[i-1].iStart;
  89281. }
  89282. }
  89283. for(i=1; i<=10; i++){
  89284. if( safe_isspace(zDoc[iBreak-i]) ){
  89285. return iBreak - i + 1;
  89286. }
  89287. if( safe_isspace(zDoc[iBreak+i]) ){
  89288. return iBreak + i + 1;
  89289. }
  89290. }
  89291. return iBreak;
  89292. }
  89293. /*
  89294. ** Allowed values for Snippet.aMatch[].snStatus
  89295. */
  89296. #define SNIPPET_IGNORE 0 /* It is ok to omit this match from the snippet */
  89297. #define SNIPPET_DESIRED 1 /* We want to include this match in the snippet */
  89298. /*
  89299. ** Generate the text of a snippet.
  89300. */
  89301. static void snippetText(
  89302. fulltext_cursor *pCursor, /* The cursor we need the snippet for */
  89303. const char *zStartMark, /* Markup to appear before each match */
  89304. const char *zEndMark, /* Markup to appear after each match */
  89305. const char *zEllipsis /* Ellipsis mark */
  89306. ){
  89307. int i, j;
  89308. struct snippetMatch *aMatch;
  89309. int nMatch;
  89310. int nDesired;
  89311. StringBuffer sb;
  89312. int tailCol;
  89313. int tailOffset;
  89314. int iCol;
  89315. int nDoc;
  89316. const char *zDoc;
  89317. int iStart, iEnd;
  89318. int tailEllipsis = 0;
  89319. int iMatch;
  89320. sqlite3_free(pCursor->snippet.zSnippet);
  89321. pCursor->snippet.zSnippet = 0;
  89322. aMatch = pCursor->snippet.aMatch;
  89323. nMatch = pCursor->snippet.nMatch;
  89324. initStringBuffer(&sb);
  89325. for(i=0; i<nMatch; i++){
  89326. aMatch[i].snStatus = SNIPPET_IGNORE;
  89327. }
  89328. nDesired = 0;
  89329. for(i=0; i<FTS3_ROTOR_SZ; i++){
  89330. for(j=0; j<nMatch; j++){
  89331. if( aMatch[j].iTerm==i ){
  89332. aMatch[j].snStatus = SNIPPET_DESIRED;
  89333. nDesired++;
  89334. break;
  89335. }
  89336. }
  89337. }
  89338. iMatch = 0;
  89339. tailCol = -1;
  89340. tailOffset = 0;
  89341. for(i=0; i<nMatch && nDesired>0; i++){
  89342. if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
  89343. nDesired--;
  89344. iCol = aMatch[i].iCol;
  89345. zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
  89346. nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
  89347. iStart = aMatch[i].iStart - 40;
  89348. iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
  89349. if( iStart<=10 ){
  89350. iStart = 0;
  89351. }
  89352. if( iCol==tailCol && iStart<=tailOffset+20 ){
  89353. iStart = tailOffset;
  89354. }
  89355. if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
  89356. trimWhiteSpace(&sb);
  89357. appendWhiteSpace(&sb);
  89358. append(&sb, zEllipsis);
  89359. appendWhiteSpace(&sb);
  89360. }
  89361. iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
  89362. iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
  89363. if( iEnd>=nDoc-10 ){
  89364. iEnd = nDoc;
  89365. tailEllipsis = 0;
  89366. }else{
  89367. tailEllipsis = 1;
  89368. }
  89369. while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
  89370. while( iStart<iEnd ){
  89371. while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
  89372. && aMatch[iMatch].iCol<=iCol ){
  89373. iMatch++;
  89374. }
  89375. if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
  89376. && aMatch[iMatch].iCol==iCol ){
  89377. nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
  89378. iStart = aMatch[iMatch].iStart;
  89379. append(&sb, zStartMark);
  89380. nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
  89381. append(&sb, zEndMark);
  89382. iStart += aMatch[iMatch].nByte;
  89383. for(j=iMatch+1; j<nMatch; j++){
  89384. if( aMatch[j].iTerm==aMatch[iMatch].iTerm
  89385. && aMatch[j].snStatus==SNIPPET_DESIRED ){
  89386. nDesired--;
  89387. aMatch[j].snStatus = SNIPPET_IGNORE;
  89388. }
  89389. }
  89390. }else{
  89391. nappend(&sb, &zDoc[iStart], iEnd - iStart);
  89392. iStart = iEnd;
  89393. }
  89394. }
  89395. tailCol = iCol;
  89396. tailOffset = iEnd;
  89397. }
  89398. trimWhiteSpace(&sb);
  89399. if( tailEllipsis ){
  89400. appendWhiteSpace(&sb);
  89401. append(&sb, zEllipsis);
  89402. }
  89403. pCursor->snippet.zSnippet = stringBufferData(&sb);
  89404. pCursor->snippet.nSnippet = stringBufferLength(&sb);
  89405. }
  89406. /*
  89407. ** Close the cursor. For additional information see the documentation
  89408. ** on the xClose method of the virtual table interface.
  89409. */
  89410. static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  89411. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  89412. FTSTRACE(("FTS3 Close %p\n", c));
  89413. sqlite3_finalize(c->pStmt);
  89414. sqlite3Fts3ExprFree(c->pExpr);
  89415. snippetClear(&c->snippet);
  89416. if( c->result.nData!=0 ){
  89417. dlrDestroy(&c->reader);
  89418. }
  89419. dataBufferDestroy(&c->result);
  89420. sqlite3_free(c);
  89421. return SQLITE_OK;
  89422. }
  89423. static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  89424. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  89425. int rc;
  89426. FTSTRACE(("FTS3 Next %p\n", pCursor));
  89427. snippetClear(&c->snippet);
  89428. if( c->iCursorType < QUERY_FULLTEXT ){
  89429. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  89430. rc = sqlite3_step(c->pStmt);
  89431. switch( rc ){
  89432. case SQLITE_ROW:
  89433. c->eof = 0;
  89434. return SQLITE_OK;
  89435. case SQLITE_DONE:
  89436. c->eof = 1;
  89437. return SQLITE_OK;
  89438. default:
  89439. c->eof = 1;
  89440. return rc;
  89441. }
  89442. } else { /* full-text query */
  89443. rc = sqlite3_reset(c->pStmt);
  89444. if( rc!=SQLITE_OK ) return rc;
  89445. if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
  89446. c->eof = 1;
  89447. return SQLITE_OK;
  89448. }
  89449. rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
  89450. dlrStep(&c->reader);
  89451. if( rc!=SQLITE_OK ) return rc;
  89452. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  89453. rc = sqlite3_step(c->pStmt);
  89454. if( rc==SQLITE_ROW ){ /* the case we expect */
  89455. c->eof = 0;
  89456. return SQLITE_OK;
  89457. }
  89458. /* an error occurred; abort */
  89459. return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  89460. }
  89461. }
  89462. /* TODO(shess) If we pushed LeafReader to the top of the file, or to
  89463. ** another file, term_select() could be pushed above
  89464. ** docListOfTerm().
  89465. */
  89466. static int termSelect(fulltext_vtab *v, int iColumn,
  89467. const char *pTerm, int nTerm, int isPrefix,
  89468. DocListType iType, DataBuffer *out);
  89469. /*
  89470. ** Return a DocList corresponding to the phrase *pPhrase.
  89471. **
  89472. ** The resulting DL_DOCIDS doclist is stored in pResult, which is
  89473. ** overwritten.
  89474. */
  89475. static int docListOfPhrase(
  89476. fulltext_vtab *pTab, /* The full text index */
  89477. Fts3Phrase *pPhrase, /* Phrase to return a doclist corresponding to */
  89478. DocListType eListType, /* Either DL_DOCIDS or DL_POSITIONS */
  89479. DataBuffer *pResult /* Write the result here */
  89480. ){
  89481. int ii;
  89482. int rc = SQLITE_OK;
  89483. int iCol = pPhrase->iColumn;
  89484. DocListType eType = eListType;
  89485. assert( eType==DL_POSITIONS || eType==DL_DOCIDS );
  89486. if( pPhrase->nToken>1 ){
  89487. eType = DL_POSITIONS;
  89488. }
  89489. /* This code should never be called with buffered updates. */
  89490. assert( pTab->nPendingData<0 );
  89491. for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
  89492. DataBuffer tmp;
  89493. struct PhraseToken *p = &pPhrase->aToken[ii];
  89494. rc = termSelect(pTab, iCol, p->z, p->n, p->isPrefix, eType, &tmp);
  89495. if( rc==SQLITE_OK ){
  89496. if( ii==0 ){
  89497. *pResult = tmp;
  89498. }else{
  89499. DataBuffer res = *pResult;
  89500. dataBufferInit(pResult, 0);
  89501. if( ii==(pPhrase->nToken-1) ){
  89502. eType = eListType;
  89503. }
  89504. docListPhraseMerge(
  89505. res.pData, res.nData, tmp.pData, tmp.nData, 0, 0, eType, pResult
  89506. );
  89507. dataBufferDestroy(&res);
  89508. dataBufferDestroy(&tmp);
  89509. }
  89510. }
  89511. }
  89512. return rc;
  89513. }
  89514. /*
  89515. ** Evaluate the full-text expression pExpr against fts3 table pTab. Write
  89516. ** the results into pRes.
  89517. */
  89518. static int evalFts3Expr(
  89519. fulltext_vtab *pTab, /* Fts3 Virtual table object */
  89520. Fts3Expr *pExpr, /* Parsed fts3 expression */
  89521. DataBuffer *pRes /* OUT: Write results of the expression here */
  89522. ){
  89523. int rc = SQLITE_OK;
  89524. /* Initialize the output buffer. If this is an empty query (pExpr==0),
  89525. ** this is all that needs to be done. Empty queries produce empty
  89526. ** result sets.
  89527. */
  89528. dataBufferInit(pRes, 0);
  89529. if( pExpr ){
  89530. if( pExpr->eType==FTSQUERY_PHRASE ){
  89531. DocListType eType = DL_DOCIDS;
  89532. if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
  89533. eType = DL_POSITIONS;
  89534. }
  89535. rc = docListOfPhrase(pTab, pExpr->pPhrase, eType, pRes);
  89536. }else{
  89537. DataBuffer lhs;
  89538. DataBuffer rhs;
  89539. dataBufferInit(&rhs, 0);
  89540. if( SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pLeft, &lhs))
  89541. && SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pRight, &rhs))
  89542. ){
  89543. switch( pExpr->eType ){
  89544. case FTSQUERY_NEAR: {
  89545. int nToken;
  89546. Fts3Expr *pLeft;
  89547. DocListType eType = DL_DOCIDS;
  89548. if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
  89549. eType = DL_POSITIONS;
  89550. }
  89551. pLeft = pExpr->pLeft;
  89552. while( pLeft->eType==FTSQUERY_NEAR ){
  89553. pLeft=pLeft->pRight;
  89554. }
  89555. assert( pExpr->pRight->eType==FTSQUERY_PHRASE );
  89556. assert( pLeft->eType==FTSQUERY_PHRASE );
  89557. nToken = pLeft->pPhrase->nToken + pExpr->pRight->pPhrase->nToken;
  89558. docListPhraseMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData,
  89559. pExpr->nNear+1, nToken, eType, pRes
  89560. );
  89561. break;
  89562. }
  89563. case FTSQUERY_NOT: {
  89564. docListExceptMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData,pRes);
  89565. break;
  89566. }
  89567. case FTSQUERY_AND: {
  89568. docListAndMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
  89569. break;
  89570. }
  89571. case FTSQUERY_OR: {
  89572. docListOrMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
  89573. break;
  89574. }
  89575. }
  89576. }
  89577. dataBufferDestroy(&lhs);
  89578. dataBufferDestroy(&rhs);
  89579. }
  89580. }
  89581. return rc;
  89582. }
  89583. /* TODO(shess) Refactor the code to remove this forward decl. */
  89584. static int flushPendingTerms(fulltext_vtab *v);
  89585. /* Perform a full-text query using the search expression in
  89586. ** zInput[0..nInput-1]. Return a list of matching documents
  89587. ** in pResult.
  89588. **
  89589. ** Queries must match column iColumn. Or if iColumn>=nColumn
  89590. ** they are allowed to match against any column.
  89591. */
  89592. static int fulltextQuery(
  89593. fulltext_vtab *v, /* The full text index */
  89594. int iColumn, /* Match against this column by default */
  89595. const char *zInput, /* The query string */
  89596. int nInput, /* Number of bytes in zInput[] */
  89597. DataBuffer *pResult, /* Write the result doclist here */
  89598. Fts3Expr **ppExpr /* Put parsed query string here */
  89599. ){
  89600. int rc;
  89601. /* TODO(shess) Instead of flushing pendingTerms, we could query for
  89602. ** the relevant term and merge the doclist into what we receive from
  89603. ** the database. Wait and see if this is a common issue, first.
  89604. **
  89605. ** A good reason not to flush is to not generate update-related
  89606. ** error codes from here.
  89607. */
  89608. /* Flush any buffered updates before executing the query. */
  89609. rc = flushPendingTerms(v);
  89610. if( rc!=SQLITE_OK ){
  89611. return rc;
  89612. }
  89613. /* Parse the query passed to the MATCH operator. */
  89614. rc = sqlite3Fts3ExprParse(v->pTokenizer,
  89615. v->azColumn, v->nColumn, iColumn, zInput, nInput, ppExpr
  89616. );
  89617. if( rc!=SQLITE_OK ){
  89618. assert( 0==(*ppExpr) );
  89619. return rc;
  89620. }
  89621. return evalFts3Expr(v, *ppExpr, pResult);
  89622. }
  89623. /*
  89624. ** This is the xFilter interface for the virtual table. See
  89625. ** the virtual table xFilter method documentation for additional
  89626. ** information.
  89627. **
  89628. ** If idxNum==QUERY_GENERIC then do a full table scan against
  89629. ** the %_content table.
  89630. **
  89631. ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
  89632. ** in the %_content table.
  89633. **
  89634. ** If idxNum>=QUERY_FULLTEXT then use the full text index. The
  89635. ** column on the left-hand side of the MATCH operator is column
  89636. ** number idxNum-QUERY_FULLTEXT, 0 indexed. argv[0] is the right-hand
  89637. ** side of the MATCH operator.
  89638. */
  89639. /* TODO(shess) Upgrade the cursor initialization and destruction to
  89640. ** account for fulltextFilter() being called multiple times on the
  89641. ** same cursor. The current solution is very fragile. Apply fix to
  89642. ** fts3 as appropriate.
  89643. */
  89644. static int fulltextFilter(
  89645. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  89646. int idxNum, const char *idxStr, /* Which indexing scheme to use */
  89647. int argc, sqlite3_value **argv /* Arguments for the indexing scheme */
  89648. ){
  89649. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  89650. fulltext_vtab *v = cursor_vtab(c);
  89651. int rc;
  89652. FTSTRACE(("FTS3 Filter %p\n",pCursor));
  89653. /* If the cursor has a statement that was not prepared according to
  89654. ** idxNum, clear it. I believe all calls to fulltextFilter with a
  89655. ** given cursor will have the same idxNum , but in this case it's
  89656. ** easy to be safe.
  89657. */
  89658. if( c->pStmt && c->iCursorType!=idxNum ){
  89659. sqlite3_finalize(c->pStmt);
  89660. c->pStmt = NULL;
  89661. }
  89662. /* Get a fresh statement appropriate to idxNum. */
  89663. /* TODO(shess): Add a prepared-statement cache in the vt structure.
  89664. ** The cache must handle multiple open cursors. Easier to cache the
  89665. ** statement variants at the vt to reduce malloc/realloc/free here.
  89666. ** Or we could have a StringBuffer variant which allowed stack
  89667. ** construction for small values.
  89668. */
  89669. if( !c->pStmt ){
  89670. StringBuffer sb;
  89671. initStringBuffer(&sb);
  89672. append(&sb, "SELECT docid, ");
  89673. appendList(&sb, v->nColumn, v->azContentColumn);
  89674. append(&sb, " FROM %_content");
  89675. if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
  89676. rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
  89677. stringBufferData(&sb));
  89678. stringBufferDestroy(&sb);
  89679. if( rc!=SQLITE_OK ) return rc;
  89680. c->iCursorType = idxNum;
  89681. }else{
  89682. sqlite3_reset(c->pStmt);
  89683. assert( c->iCursorType==idxNum );
  89684. }
  89685. switch( idxNum ){
  89686. case QUERY_GENERIC:
  89687. break;
  89688. case QUERY_DOCID:
  89689. rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
  89690. if( rc!=SQLITE_OK ) return rc;
  89691. break;
  89692. default: /* full-text search */
  89693. {
  89694. int iCol = idxNum-QUERY_FULLTEXT;
  89695. const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
  89696. assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
  89697. assert( argc==1 );
  89698. if( c->result.nData!=0 ){
  89699. /* This case happens if the same cursor is used repeatedly. */
  89700. dlrDestroy(&c->reader);
  89701. dataBufferReset(&c->result);
  89702. }else{
  89703. dataBufferInit(&c->result, 0);
  89704. }
  89705. rc = fulltextQuery(v, iCol, zQuery, -1, &c->result, &c->pExpr);
  89706. if( rc!=SQLITE_OK ) return rc;
  89707. if( c->result.nData!=0 ){
  89708. dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
  89709. }
  89710. break;
  89711. }
  89712. }
  89713. return fulltextNext(pCursor);
  89714. }
  89715. /* This is the xEof method of the virtual table. The SQLite core
  89716. ** calls this routine to find out if it has reached the end of
  89717. ** a query's results set.
  89718. */
  89719. static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  89720. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  89721. return c->eof;
  89722. }
  89723. /* This is the xColumn method of the virtual table. The SQLite
  89724. ** core calls this method during a query when it needs the value
  89725. ** of a column from the virtual table. This method needs to use
  89726. ** one of the sqlite3_result_*() routines to store the requested
  89727. ** value back in the pContext.
  89728. */
  89729. static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
  89730. sqlite3_context *pContext, int idxCol){
  89731. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  89732. fulltext_vtab *v = cursor_vtab(c);
  89733. if( idxCol<v->nColumn ){
  89734. sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
  89735. sqlite3_result_value(pContext, pVal);
  89736. }else if( idxCol==v->nColumn ){
  89737. /* The extra column whose name is the same as the table.
  89738. ** Return a blob which is a pointer to the cursor
  89739. */
  89740. sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
  89741. }else if( idxCol==v->nColumn+1 ){
  89742. /* The docid column, which is an alias for rowid. */
  89743. sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
  89744. sqlite3_result_value(pContext, pVal);
  89745. }
  89746. return SQLITE_OK;
  89747. }
  89748. /* This is the xRowid method. The SQLite core calls this routine to
  89749. ** retrieve the rowid for the current row of the result set. fts3
  89750. ** exposes %_content.docid as the rowid for the virtual table. The
  89751. ** rowid should be written to *pRowid.
  89752. */
  89753. static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  89754. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  89755. *pRowid = sqlite3_column_int64(c->pStmt, 0);
  89756. return SQLITE_OK;
  89757. }
  89758. /* Add all terms in [zText] to pendingTerms table. If [iColumn] > 0,
  89759. ** we also store positions and offsets in the hash table using that
  89760. ** column number.
  89761. */
  89762. static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
  89763. const char *zText, int iColumn){
  89764. sqlite3_tokenizer *pTokenizer = v->pTokenizer;
  89765. sqlite3_tokenizer_cursor *pCursor;
  89766. const char *pToken;
  89767. int nTokenBytes;
  89768. int iStartOffset, iEndOffset, iPosition;
  89769. int rc;
  89770. rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  89771. if( rc!=SQLITE_OK ) return rc;
  89772. pCursor->pTokenizer = pTokenizer;
  89773. while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
  89774. &pToken, &nTokenBytes,
  89775. &iStartOffset, &iEndOffset,
  89776. &iPosition)) ){
  89777. DLCollector *p;
  89778. int nData; /* Size of doclist before our update. */
  89779. /* Positions can't be negative; we use -1 as a terminator
  89780. * internally. Token can't be NULL or empty. */
  89781. if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
  89782. rc = SQLITE_ERROR;
  89783. break;
  89784. }
  89785. p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
  89786. if( p==NULL ){
  89787. nData = 0;
  89788. p = dlcNew(iDocid, DL_DEFAULT);
  89789. fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
  89790. /* Overhead for our hash table entry, the key, and the value. */
  89791. v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
  89792. }else{
  89793. nData = p->b.nData;
  89794. if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
  89795. }
  89796. if( iColumn>=0 ){
  89797. dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
  89798. }
  89799. /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
  89800. v->nPendingData += p->b.nData-nData;
  89801. }
  89802. /* TODO(shess) Check return? Should this be able to cause errors at
  89803. ** this point? Actually, same question about sqlite3_finalize(),
  89804. ** though one could argue that failure there means that the data is
  89805. ** not durable. *ponder*
  89806. */
  89807. pTokenizer->pModule->xClose(pCursor);
  89808. if( SQLITE_DONE == rc ) return SQLITE_OK;
  89809. return rc;
  89810. }
  89811. /* Add doclists for all terms in [pValues] to pendingTerms table. */
  89812. static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
  89813. sqlite3_value **pValues){
  89814. int i;
  89815. for(i = 0; i < v->nColumn ; ++i){
  89816. char *zText = (char*)sqlite3_value_text(pValues[i]);
  89817. int rc = buildTerms(v, iDocid, zText, i);
  89818. if( rc!=SQLITE_OK ) return rc;
  89819. }
  89820. return SQLITE_OK;
  89821. }
  89822. /* Add empty doclists for all terms in the given row's content to
  89823. ** pendingTerms.
  89824. */
  89825. static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  89826. const char **pValues;
  89827. int i, rc;
  89828. /* TODO(shess) Should we allow such tables at all? */
  89829. if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
  89830. rc = content_select(v, iDocid, &pValues);
  89831. if( rc!=SQLITE_OK ) return rc;
  89832. for(i = 0 ; i < v->nColumn; ++i) {
  89833. rc = buildTerms(v, iDocid, pValues[i], -1);
  89834. if( rc!=SQLITE_OK ) break;
  89835. }
  89836. freeStringArray(v->nColumn, pValues);
  89837. return SQLITE_OK;
  89838. }
  89839. /* TODO(shess) Refactor the code to remove this forward decl. */
  89840. static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
  89841. /* Insert a row into the %_content table; set *piDocid to be the ID of the
  89842. ** new row. Add doclists for terms to pendingTerms.
  89843. */
  89844. static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
  89845. sqlite3_value **pValues, sqlite_int64 *piDocid){
  89846. int rc;
  89847. rc = content_insert(v, pRequestDocid, pValues); /* execute an SQL INSERT */
  89848. if( rc!=SQLITE_OK ) return rc;
  89849. /* docid column is an alias for rowid. */
  89850. *piDocid = sqlite3_last_insert_rowid(v->db);
  89851. rc = initPendingTerms(v, *piDocid);
  89852. if( rc!=SQLITE_OK ) return rc;
  89853. return insertTerms(v, *piDocid, pValues);
  89854. }
  89855. /* Delete a row from the %_content table; add empty doclists for terms
  89856. ** to pendingTerms.
  89857. */
  89858. static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  89859. int rc = initPendingTerms(v, iRow);
  89860. if( rc!=SQLITE_OK ) return rc;
  89861. rc = deleteTerms(v, iRow);
  89862. if( rc!=SQLITE_OK ) return rc;
  89863. return content_delete(v, iRow); /* execute an SQL DELETE */
  89864. }
  89865. /* Update a row in the %_content table; add delete doclists to
  89866. ** pendingTerms for old terms not in the new data, add insert doclists
  89867. ** to pendingTerms for terms in the new data.
  89868. */
  89869. static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
  89870. sqlite3_value **pValues){
  89871. int rc = initPendingTerms(v, iRow);
  89872. if( rc!=SQLITE_OK ) return rc;
  89873. /* Generate an empty doclist for each term that previously appeared in this
  89874. * row. */
  89875. rc = deleteTerms(v, iRow);
  89876. if( rc!=SQLITE_OK ) return rc;
  89877. rc = content_update(v, pValues, iRow); /* execute an SQL UPDATE */
  89878. if( rc!=SQLITE_OK ) return rc;
  89879. /* Now add positions for terms which appear in the updated row. */
  89880. return insertTerms(v, iRow, pValues);
  89881. }
  89882. /*******************************************************************/
  89883. /* InteriorWriter is used to collect terms and block references into
  89884. ** interior nodes in %_segments. See commentary at top of file for
  89885. ** format.
  89886. */
  89887. /* How large interior nodes can grow. */
  89888. #define INTERIOR_MAX 2048
  89889. /* Minimum number of terms per interior node (except the root). This
  89890. ** prevents large terms from making the tree too skinny - must be >0
  89891. ** so that the tree always makes progress. Note that the min tree
  89892. ** fanout will be INTERIOR_MIN_TERMS+1.
  89893. */
  89894. #define INTERIOR_MIN_TERMS 7
  89895. #if INTERIOR_MIN_TERMS<1
  89896. # error INTERIOR_MIN_TERMS must be greater than 0.
  89897. #endif
  89898. /* ROOT_MAX controls how much data is stored inline in the segment
  89899. ** directory.
  89900. */
  89901. /* TODO(shess) Push ROOT_MAX down to whoever is writing things. It's
  89902. ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
  89903. ** can both see it, but if the caller passed it in, we wouldn't even
  89904. ** need a define.
  89905. */
  89906. #define ROOT_MAX 1024
  89907. #if ROOT_MAX<VARINT_MAX*2
  89908. # error ROOT_MAX must have enough space for a header.
  89909. #endif
  89910. /* InteriorBlock stores a linked-list of interior blocks while a lower
  89911. ** layer is being constructed.
  89912. */
  89913. typedef struct InteriorBlock {
  89914. DataBuffer term; /* Leftmost term in block's subtree. */
  89915. DataBuffer data; /* Accumulated data for the block. */
  89916. struct InteriorBlock *next;
  89917. } InteriorBlock;
  89918. static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
  89919. const char *pTerm, int nTerm){
  89920. InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
  89921. char c[VARINT_MAX+VARINT_MAX];
  89922. int n;
  89923. if( block ){
  89924. memset(block, 0, sizeof(*block));
  89925. dataBufferInit(&block->term, 0);
  89926. dataBufferReplace(&block->term, pTerm, nTerm);
  89927. n = fts3PutVarint(c, iHeight);
  89928. n += fts3PutVarint(c+n, iChildBlock);
  89929. dataBufferInit(&block->data, INTERIOR_MAX);
  89930. dataBufferReplace(&block->data, c, n);
  89931. }
  89932. return block;
  89933. }
  89934. #ifndef NDEBUG
  89935. /* Verify that the data is readable as an interior node. */
  89936. static void interiorBlockValidate(InteriorBlock *pBlock){
  89937. const char *pData = pBlock->data.pData;
  89938. int nData = pBlock->data.nData;
  89939. int n, iDummy;
  89940. sqlite_int64 iBlockid;
  89941. assert( nData>0 );
  89942. assert( pData!=0 );
  89943. assert( pData+nData>pData );
  89944. /* Must lead with height of node as a varint(n), n>0 */
  89945. n = fts3GetVarint32(pData, &iDummy);
  89946. assert( n>0 );
  89947. assert( iDummy>0 );
  89948. assert( n<nData );
  89949. pData += n;
  89950. nData -= n;
  89951. /* Must contain iBlockid. */
  89952. n = fts3GetVarint(pData, &iBlockid);
  89953. assert( n>0 );
  89954. assert( n<=nData );
  89955. pData += n;
  89956. nData -= n;
  89957. /* Zero or more terms of positive length */
  89958. if( nData!=0 ){
  89959. /* First term is not delta-encoded. */
  89960. n = fts3GetVarint32(pData, &iDummy);
  89961. assert( n>0 );
  89962. assert( iDummy>0 );
  89963. assert( n+iDummy>0);
  89964. assert( n+iDummy<=nData );
  89965. pData += n+iDummy;
  89966. nData -= n+iDummy;
  89967. /* Following terms delta-encoded. */
  89968. while( nData!=0 ){
  89969. /* Length of shared prefix. */
  89970. n = fts3GetVarint32(pData, &iDummy);
  89971. assert( n>0 );
  89972. assert( iDummy>=0 );
  89973. assert( n<nData );
  89974. pData += n;
  89975. nData -= n;
  89976. /* Length and data of distinct suffix. */
  89977. n = fts3GetVarint32(pData, &iDummy);
  89978. assert( n>0 );
  89979. assert( iDummy>0 );
  89980. assert( n+iDummy>0);
  89981. assert( n+iDummy<=nData );
  89982. pData += n+iDummy;
  89983. nData -= n+iDummy;
  89984. }
  89985. }
  89986. }
  89987. #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
  89988. #else
  89989. #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
  89990. #endif
  89991. typedef struct InteriorWriter {
  89992. int iHeight; /* from 0 at leaves. */
  89993. InteriorBlock *first, *last;
  89994. struct InteriorWriter *parentWriter;
  89995. DataBuffer term; /* Last term written to block "last". */
  89996. sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
  89997. #ifndef NDEBUG
  89998. sqlite_int64 iLastChildBlock; /* for consistency checks. */
  89999. #endif
  90000. } InteriorWriter;
  90001. /* Initialize an interior node where pTerm[nTerm] marks the leftmost
  90002. ** term in the tree. iChildBlock is the leftmost child block at the
  90003. ** next level down the tree.
  90004. */
  90005. static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
  90006. sqlite_int64 iChildBlock,
  90007. InteriorWriter *pWriter){
  90008. InteriorBlock *block;
  90009. assert( iHeight>0 );
  90010. CLEAR(pWriter);
  90011. pWriter->iHeight = iHeight;
  90012. pWriter->iOpeningChildBlock = iChildBlock;
  90013. #ifndef NDEBUG
  90014. pWriter->iLastChildBlock = iChildBlock;
  90015. #endif
  90016. block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
  90017. pWriter->last = pWriter->first = block;
  90018. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  90019. dataBufferInit(&pWriter->term, 0);
  90020. }
  90021. /* Append the child node rooted at iChildBlock to the interior node,
  90022. ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
  90023. */
  90024. static void interiorWriterAppend(InteriorWriter *pWriter,
  90025. const char *pTerm, int nTerm,
  90026. sqlite_int64 iChildBlock){
  90027. char c[VARINT_MAX+VARINT_MAX];
  90028. int n, nPrefix = 0;
  90029. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  90030. /* The first term written into an interior node is actually
  90031. ** associated with the second child added (the first child was added
  90032. ** in interiorWriterInit, or in the if clause at the bottom of this
  90033. ** function). That term gets encoded straight up, with nPrefix left
  90034. ** at 0.
  90035. */
  90036. if( pWriter->term.nData==0 ){
  90037. n = fts3PutVarint(c, nTerm);
  90038. }else{
  90039. while( nPrefix<pWriter->term.nData &&
  90040. pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
  90041. nPrefix++;
  90042. }
  90043. n = fts3PutVarint(c, nPrefix);
  90044. n += fts3PutVarint(c+n, nTerm-nPrefix);
  90045. }
  90046. #ifndef NDEBUG
  90047. pWriter->iLastChildBlock++;
  90048. #endif
  90049. assert( pWriter->iLastChildBlock==iChildBlock );
  90050. /* Overflow to a new block if the new term makes the current block
  90051. ** too big, and the current block already has enough terms.
  90052. */
  90053. if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
  90054. iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
  90055. pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
  90056. pTerm, nTerm);
  90057. pWriter->last = pWriter->last->next;
  90058. pWriter->iOpeningChildBlock = iChildBlock;
  90059. dataBufferReset(&pWriter->term);
  90060. }else{
  90061. dataBufferAppend2(&pWriter->last->data, c, n,
  90062. pTerm+nPrefix, nTerm-nPrefix);
  90063. dataBufferReplace(&pWriter->term, pTerm, nTerm);
  90064. }
  90065. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  90066. }
  90067. /* Free the space used by pWriter, including the linked-list of
  90068. ** InteriorBlocks, and parentWriter, if present.
  90069. */
  90070. static int interiorWriterDestroy(InteriorWriter *pWriter){
  90071. InteriorBlock *block = pWriter->first;
  90072. while( block!=NULL ){
  90073. InteriorBlock *b = block;
  90074. block = block->next;
  90075. dataBufferDestroy(&b->term);
  90076. dataBufferDestroy(&b->data);
  90077. sqlite3_free(b);
  90078. }
  90079. if( pWriter->parentWriter!=NULL ){
  90080. interiorWriterDestroy(pWriter->parentWriter);
  90081. sqlite3_free(pWriter->parentWriter);
  90082. }
  90083. dataBufferDestroy(&pWriter->term);
  90084. SCRAMBLE(pWriter);
  90085. return SQLITE_OK;
  90086. }
  90087. /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
  90088. ** directly, leaving *piEndBlockid unchanged. Otherwise, flush
  90089. ** pWriter to %_segments, building a new layer of interior nodes, and
  90090. ** recursively ask for their root into.
  90091. */
  90092. static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
  90093. char **ppRootInfo, int *pnRootInfo,
  90094. sqlite_int64 *piEndBlockid){
  90095. InteriorBlock *block = pWriter->first;
  90096. sqlite_int64 iBlockid = 0;
  90097. int rc;
  90098. /* If we can fit the segment inline */
  90099. if( block==pWriter->last && block->data.nData<ROOT_MAX ){
  90100. *ppRootInfo = block->data.pData;
  90101. *pnRootInfo = block->data.nData;
  90102. return SQLITE_OK;
  90103. }
  90104. /* Flush the first block to %_segments, and create a new level of
  90105. ** interior node.
  90106. */
  90107. ASSERT_VALID_INTERIOR_BLOCK(block);
  90108. rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  90109. if( rc!=SQLITE_OK ) return rc;
  90110. *piEndBlockid = iBlockid;
  90111. pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
  90112. interiorWriterInit(pWriter->iHeight+1,
  90113. block->term.pData, block->term.nData,
  90114. iBlockid, pWriter->parentWriter);
  90115. /* Flush additional blocks and append to the higher interior
  90116. ** node.
  90117. */
  90118. for(block=block->next; block!=NULL; block=block->next){
  90119. ASSERT_VALID_INTERIOR_BLOCK(block);
  90120. rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  90121. if( rc!=SQLITE_OK ) return rc;
  90122. *piEndBlockid = iBlockid;
  90123. interiorWriterAppend(pWriter->parentWriter,
  90124. block->term.pData, block->term.nData, iBlockid);
  90125. }
  90126. /* Parent node gets the chance to be the root. */
  90127. return interiorWriterRootInfo(v, pWriter->parentWriter,
  90128. ppRootInfo, pnRootInfo, piEndBlockid);
  90129. }
  90130. /****************************************************************/
  90131. /* InteriorReader is used to read off the data from an interior node
  90132. ** (see comment at top of file for the format).
  90133. */
  90134. typedef struct InteriorReader {
  90135. const char *pData;
  90136. int nData;
  90137. DataBuffer term; /* previous term, for decoding term delta. */
  90138. sqlite_int64 iBlockid;
  90139. } InteriorReader;
  90140. static void interiorReaderDestroy(InteriorReader *pReader){
  90141. dataBufferDestroy(&pReader->term);
  90142. SCRAMBLE(pReader);
  90143. }
  90144. /* TODO(shess) The assertions are great, but what if we're in NDEBUG
  90145. ** and the blob is empty or otherwise contains suspect data?
  90146. */
  90147. static void interiorReaderInit(const char *pData, int nData,
  90148. InteriorReader *pReader){
  90149. int n, nTerm;
  90150. /* Require at least the leading flag byte */
  90151. assert( nData>0 );
  90152. assert( pData[0]!='\0' );
  90153. CLEAR(pReader);
  90154. /* Decode the base blockid, and set the cursor to the first term. */
  90155. n = fts3GetVarint(pData+1, &pReader->iBlockid);
  90156. assert( 1+n<=nData );
  90157. pReader->pData = pData+1+n;
  90158. pReader->nData = nData-(1+n);
  90159. /* A single-child interior node (such as when a leaf node was too
  90160. ** large for the segment directory) won't have any terms.
  90161. ** Otherwise, decode the first term.
  90162. */
  90163. if( pReader->nData==0 ){
  90164. dataBufferInit(&pReader->term, 0);
  90165. }else{
  90166. n = fts3GetVarint32(pReader->pData, &nTerm);
  90167. dataBufferInit(&pReader->term, nTerm);
  90168. dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
  90169. assert( n+nTerm<=pReader->nData );
  90170. pReader->pData += n+nTerm;
  90171. pReader->nData -= n+nTerm;
  90172. }
  90173. }
  90174. static int interiorReaderAtEnd(InteriorReader *pReader){
  90175. return pReader->term.nData==0;
  90176. }
  90177. static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
  90178. return pReader->iBlockid;
  90179. }
  90180. static int interiorReaderTermBytes(InteriorReader *pReader){
  90181. assert( !interiorReaderAtEnd(pReader) );
  90182. return pReader->term.nData;
  90183. }
  90184. static const char *interiorReaderTerm(InteriorReader *pReader){
  90185. assert( !interiorReaderAtEnd(pReader) );
  90186. return pReader->term.pData;
  90187. }
  90188. /* Step forward to the next term in the node. */
  90189. static void interiorReaderStep(InteriorReader *pReader){
  90190. assert( !interiorReaderAtEnd(pReader) );
  90191. /* If the last term has been read, signal eof, else construct the
  90192. ** next term.
  90193. */
  90194. if( pReader->nData==0 ){
  90195. dataBufferReset(&pReader->term);
  90196. }else{
  90197. int n, nPrefix, nSuffix;
  90198. n = fts3GetVarint32(pReader->pData, &nPrefix);
  90199. n += fts3GetVarint32(pReader->pData+n, &nSuffix);
  90200. /* Truncate the current term and append suffix data. */
  90201. pReader->term.nData = nPrefix;
  90202. dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
  90203. assert( n+nSuffix<=pReader->nData );
  90204. pReader->pData += n+nSuffix;
  90205. pReader->nData -= n+nSuffix;
  90206. }
  90207. pReader->iBlockid++;
  90208. }
  90209. /* Compare the current term to pTerm[nTerm], returning strcmp-style
  90210. ** results. If isPrefix, equality means equal through nTerm bytes.
  90211. */
  90212. static int interiorReaderTermCmp(InteriorReader *pReader,
  90213. const char *pTerm, int nTerm, int isPrefix){
  90214. const char *pReaderTerm = interiorReaderTerm(pReader);
  90215. int nReaderTerm = interiorReaderTermBytes(pReader);
  90216. int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
  90217. if( n==0 ){
  90218. if( nReaderTerm>0 ) return -1;
  90219. if( nTerm>0 ) return 1;
  90220. return 0;
  90221. }
  90222. c = memcmp(pReaderTerm, pTerm, n);
  90223. if( c!=0 ) return c;
  90224. if( isPrefix && n==nTerm ) return 0;
  90225. return nReaderTerm - nTerm;
  90226. }
  90227. /****************************************************************/
  90228. /* LeafWriter is used to collect terms and associated doclist data
  90229. ** into leaf blocks in %_segments (see top of file for format info).
  90230. ** Expected usage is:
  90231. **
  90232. ** LeafWriter writer;
  90233. ** leafWriterInit(0, 0, &writer);
  90234. ** while( sorted_terms_left_to_process ){
  90235. ** // data is doclist data for that term.
  90236. ** rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
  90237. ** if( rc!=SQLITE_OK ) goto err;
  90238. ** }
  90239. ** rc = leafWriterFinalize(v, &writer);
  90240. **err:
  90241. ** leafWriterDestroy(&writer);
  90242. ** return rc;
  90243. **
  90244. ** leafWriterStep() may write a collected leaf out to %_segments.
  90245. ** leafWriterFinalize() finishes writing any buffered data and stores
  90246. ** a root node in %_segdir. leafWriterDestroy() frees all buffers and
  90247. ** InteriorWriters allocated as part of writing this segment.
  90248. **
  90249. ** TODO(shess) Document leafWriterStepMerge().
  90250. */
  90251. /* Put terms with data this big in their own block. */
  90252. #define STANDALONE_MIN 1024
  90253. /* Keep leaf blocks below this size. */
  90254. #define LEAF_MAX 2048
  90255. typedef struct LeafWriter {
  90256. int iLevel;
  90257. int idx;
  90258. sqlite_int64 iStartBlockid; /* needed to create the root info */
  90259. sqlite_int64 iEndBlockid; /* when we're done writing. */
  90260. DataBuffer term; /* previous encoded term */
  90261. DataBuffer data; /* encoding buffer */
  90262. /* bytes of first term in the current node which distinguishes that
  90263. ** term from the last term of the previous node.
  90264. */
  90265. int nTermDistinct;
  90266. InteriorWriter parentWriter; /* if we overflow */
  90267. int has_parent;
  90268. } LeafWriter;
  90269. static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
  90270. CLEAR(pWriter);
  90271. pWriter->iLevel = iLevel;
  90272. pWriter->idx = idx;
  90273. dataBufferInit(&pWriter->term, 32);
  90274. /* Start out with a reasonably sized block, though it can grow. */
  90275. dataBufferInit(&pWriter->data, LEAF_MAX);
  90276. }
  90277. #ifndef NDEBUG
  90278. /* Verify that the data is readable as a leaf node. */
  90279. static void leafNodeValidate(const char *pData, int nData){
  90280. int n, iDummy;
  90281. if( nData==0 ) return;
  90282. assert( nData>0 );
  90283. assert( pData!=0 );
  90284. assert( pData+nData>pData );
  90285. /* Must lead with a varint(0) */
  90286. n = fts3GetVarint32(pData, &iDummy);
  90287. assert( iDummy==0 );
  90288. assert( n>0 );
  90289. assert( n<nData );
  90290. pData += n;
  90291. nData -= n;
  90292. /* Leading term length and data must fit in buffer. */
  90293. n = fts3GetVarint32(pData, &iDummy);
  90294. assert( n>0 );
  90295. assert( iDummy>0 );
  90296. assert( n+iDummy>0 );
  90297. assert( n+iDummy<nData );
  90298. pData += n+iDummy;
  90299. nData -= n+iDummy;
  90300. /* Leading term's doclist length and data must fit. */
  90301. n = fts3GetVarint32(pData, &iDummy);
  90302. assert( n>0 );
  90303. assert( iDummy>0 );
  90304. assert( n+iDummy>0 );
  90305. assert( n+iDummy<=nData );
  90306. ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  90307. pData += n+iDummy;
  90308. nData -= n+iDummy;
  90309. /* Verify that trailing terms and doclists also are readable. */
  90310. while( nData!=0 ){
  90311. n = fts3GetVarint32(pData, &iDummy);
  90312. assert( n>0 );
  90313. assert( iDummy>=0 );
  90314. assert( n<nData );
  90315. pData += n;
  90316. nData -= n;
  90317. n = fts3GetVarint32(pData, &iDummy);
  90318. assert( n>0 );
  90319. assert( iDummy>0 );
  90320. assert( n+iDummy>0 );
  90321. assert( n+iDummy<nData );
  90322. pData += n+iDummy;
  90323. nData -= n+iDummy;
  90324. n = fts3GetVarint32(pData, &iDummy);
  90325. assert( n>0 );
  90326. assert( iDummy>0 );
  90327. assert( n+iDummy>0 );
  90328. assert( n+iDummy<=nData );
  90329. ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  90330. pData += n+iDummy;
  90331. nData -= n+iDummy;
  90332. }
  90333. }
  90334. #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
  90335. #else
  90336. #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
  90337. #endif
  90338. /* Flush the current leaf node to %_segments, and adding the resulting
  90339. ** blockid and the starting term to the interior node which will
  90340. ** contain it.
  90341. */
  90342. static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
  90343. int iData, int nData){
  90344. sqlite_int64 iBlockid = 0;
  90345. const char *pStartingTerm;
  90346. int nStartingTerm, rc, n;
  90347. /* Must have the leading varint(0) flag, plus at least some
  90348. ** valid-looking data.
  90349. */
  90350. assert( nData>2 );
  90351. assert( iData>=0 );
  90352. assert( iData+nData<=pWriter->data.nData );
  90353. ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
  90354. rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
  90355. if( rc!=SQLITE_OK ) return rc;
  90356. assert( iBlockid!=0 );
  90357. /* Reconstruct the first term in the leaf for purposes of building
  90358. ** the interior node.
  90359. */
  90360. n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
  90361. pStartingTerm = pWriter->data.pData+iData+1+n;
  90362. assert( pWriter->data.nData>iData+1+n+nStartingTerm );
  90363. assert( pWriter->nTermDistinct>0 );
  90364. assert( pWriter->nTermDistinct<=nStartingTerm );
  90365. nStartingTerm = pWriter->nTermDistinct;
  90366. if( pWriter->has_parent ){
  90367. interiorWriterAppend(&pWriter->parentWriter,
  90368. pStartingTerm, nStartingTerm, iBlockid);
  90369. }else{
  90370. interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
  90371. &pWriter->parentWriter);
  90372. pWriter->has_parent = 1;
  90373. }
  90374. /* Track the span of this segment's leaf nodes. */
  90375. if( pWriter->iEndBlockid==0 ){
  90376. pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
  90377. }else{
  90378. pWriter->iEndBlockid++;
  90379. assert( iBlockid==pWriter->iEndBlockid );
  90380. }
  90381. return SQLITE_OK;
  90382. }
  90383. static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
  90384. int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
  90385. if( rc!=SQLITE_OK ) return rc;
  90386. /* Re-initialize the output buffer. */
  90387. dataBufferReset(&pWriter->data);
  90388. return SQLITE_OK;
  90389. }
  90390. /* Fetch the root info for the segment. If the entire leaf fits
  90391. ** within ROOT_MAX, then it will be returned directly, otherwise it
  90392. ** will be flushed and the root info will be returned from the
  90393. ** interior node. *piEndBlockid is set to the blockid of the last
  90394. ** interior or leaf node written to disk (0 if none are written at
  90395. ** all).
  90396. */
  90397. static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
  90398. char **ppRootInfo, int *pnRootInfo,
  90399. sqlite_int64 *piEndBlockid){
  90400. /* we can fit the segment entirely inline */
  90401. if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
  90402. *ppRootInfo = pWriter->data.pData;
  90403. *pnRootInfo = pWriter->data.nData;
  90404. *piEndBlockid = 0;
  90405. return SQLITE_OK;
  90406. }
  90407. /* Flush remaining leaf data. */
  90408. if( pWriter->data.nData>0 ){
  90409. int rc = leafWriterFlush(v, pWriter);
  90410. if( rc!=SQLITE_OK ) return rc;
  90411. }
  90412. /* We must have flushed a leaf at some point. */
  90413. assert( pWriter->has_parent );
  90414. /* Tenatively set the end leaf blockid as the end blockid. If the
  90415. ** interior node can be returned inline, this will be the final
  90416. ** blockid, otherwise it will be overwritten by
  90417. ** interiorWriterRootInfo().
  90418. */
  90419. *piEndBlockid = pWriter->iEndBlockid;
  90420. return interiorWriterRootInfo(v, &pWriter->parentWriter,
  90421. ppRootInfo, pnRootInfo, piEndBlockid);
  90422. }
  90423. /* Collect the rootInfo data and store it into the segment directory.
  90424. ** This has the effect of flushing the segment's leaf data to
  90425. ** %_segments, and also flushing any interior nodes to %_segments.
  90426. */
  90427. static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
  90428. sqlite_int64 iEndBlockid;
  90429. char *pRootInfo;
  90430. int rc, nRootInfo;
  90431. rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
  90432. if( rc!=SQLITE_OK ) return rc;
  90433. /* Don't bother storing an entirely empty segment. */
  90434. if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
  90435. return segdir_set(v, pWriter->iLevel, pWriter->idx,
  90436. pWriter->iStartBlockid, pWriter->iEndBlockid,
  90437. iEndBlockid, pRootInfo, nRootInfo);
  90438. }
  90439. static void leafWriterDestroy(LeafWriter *pWriter){
  90440. if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
  90441. dataBufferDestroy(&pWriter->term);
  90442. dataBufferDestroy(&pWriter->data);
  90443. }
  90444. /* Encode a term into the leafWriter, delta-encoding as appropriate.
  90445. ** Returns the length of the new term which distinguishes it from the
  90446. ** previous term, which can be used to set nTermDistinct when a node
  90447. ** boundary is crossed.
  90448. */
  90449. static int leafWriterEncodeTerm(LeafWriter *pWriter,
  90450. const char *pTerm, int nTerm){
  90451. char c[VARINT_MAX+VARINT_MAX];
  90452. int n, nPrefix = 0;
  90453. assert( nTerm>0 );
  90454. while( nPrefix<pWriter->term.nData &&
  90455. pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
  90456. nPrefix++;
  90457. /* Failing this implies that the terms weren't in order. */
  90458. assert( nPrefix<nTerm );
  90459. }
  90460. if( pWriter->data.nData==0 ){
  90461. /* Encode the node header and leading term as:
  90462. ** varint(0)
  90463. ** varint(nTerm)
  90464. ** char pTerm[nTerm]
  90465. */
  90466. n = fts3PutVarint(c, '\0');
  90467. n += fts3PutVarint(c+n, nTerm);
  90468. dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
  90469. }else{
  90470. /* Delta-encode the term as:
  90471. ** varint(nPrefix)
  90472. ** varint(nSuffix)
  90473. ** char pTermSuffix[nSuffix]
  90474. */
  90475. n = fts3PutVarint(c, nPrefix);
  90476. n += fts3PutVarint(c+n, nTerm-nPrefix);
  90477. dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
  90478. }
  90479. dataBufferReplace(&pWriter->term, pTerm, nTerm);
  90480. return nPrefix+1;
  90481. }
  90482. /* Used to avoid a memmove when a large amount of doclist data is in
  90483. ** the buffer. This constructs a node and term header before
  90484. ** iDoclistData and flushes the resulting complete node using
  90485. ** leafWriterInternalFlush().
  90486. */
  90487. static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
  90488. const char *pTerm, int nTerm,
  90489. int iDoclistData){
  90490. char c[VARINT_MAX+VARINT_MAX];
  90491. int iData, n = fts3PutVarint(c, 0);
  90492. n += fts3PutVarint(c+n, nTerm);
  90493. /* There should always be room for the header. Even if pTerm shared
  90494. ** a substantial prefix with the previous term, the entire prefix
  90495. ** could be constructed from earlier data in the doclist, so there
  90496. ** should be room.
  90497. */
  90498. assert( iDoclistData>=n+nTerm );
  90499. iData = iDoclistData-(n+nTerm);
  90500. memcpy(pWriter->data.pData+iData, c, n);
  90501. memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
  90502. return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
  90503. }
  90504. /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
  90505. ** %_segments.
  90506. */
  90507. static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
  90508. const char *pTerm, int nTerm,
  90509. DLReader *pReaders, int nReaders){
  90510. char c[VARINT_MAX+VARINT_MAX];
  90511. int iTermData = pWriter->data.nData, iDoclistData;
  90512. int i, nData, n, nActualData, nActual, rc, nTermDistinct;
  90513. ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  90514. nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
  90515. /* Remember nTermDistinct if opening a new node. */
  90516. if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
  90517. iDoclistData = pWriter->data.nData;
  90518. /* Estimate the length of the merged doclist so we can leave space
  90519. ** to encode it.
  90520. */
  90521. for(i=0, nData=0; i<nReaders; i++){
  90522. nData += dlrAllDataBytes(&pReaders[i]);
  90523. }
  90524. n = fts3PutVarint(c, nData);
  90525. dataBufferAppend(&pWriter->data, c, n);
  90526. docListMerge(&pWriter->data, pReaders, nReaders);
  90527. ASSERT_VALID_DOCLIST(DL_DEFAULT,
  90528. pWriter->data.pData+iDoclistData+n,
  90529. pWriter->data.nData-iDoclistData-n, NULL);
  90530. /* The actual amount of doclist data at this point could be smaller
  90531. ** than the length we encoded. Additionally, the space required to
  90532. ** encode this length could be smaller. For small doclists, this is
  90533. ** not a big deal, we can just use memmove() to adjust things.
  90534. */
  90535. nActualData = pWriter->data.nData-(iDoclistData+n);
  90536. nActual = fts3PutVarint(c, nActualData);
  90537. assert( nActualData<=nData );
  90538. assert( nActual<=n );
  90539. /* If the new doclist is big enough for force a standalone leaf
  90540. ** node, we can immediately flush it inline without doing the
  90541. ** memmove().
  90542. */
  90543. /* TODO(shess) This test matches leafWriterStep(), which does this
  90544. ** test before it knows the cost to varint-encode the term and
  90545. ** doclist lengths. At some point, change to
  90546. ** pWriter->data.nData-iTermData>STANDALONE_MIN.
  90547. */
  90548. if( nTerm+nActualData>STANDALONE_MIN ){
  90549. /* Push leaf node from before this term. */
  90550. if( iTermData>0 ){
  90551. rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
  90552. if( rc!=SQLITE_OK ) return rc;
  90553. pWriter->nTermDistinct = nTermDistinct;
  90554. }
  90555. /* Fix the encoded doclist length. */
  90556. iDoclistData += n - nActual;
  90557. memcpy(pWriter->data.pData+iDoclistData, c, nActual);
  90558. /* Push the standalone leaf node. */
  90559. rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
  90560. if( rc!=SQLITE_OK ) return rc;
  90561. /* Leave the node empty. */
  90562. dataBufferReset(&pWriter->data);
  90563. return rc;
  90564. }
  90565. /* At this point, we know that the doclist was small, so do the
  90566. ** memmove if indicated.
  90567. */
  90568. if( nActual<n ){
  90569. memmove(pWriter->data.pData+iDoclistData+nActual,
  90570. pWriter->data.pData+iDoclistData+n,
  90571. pWriter->data.nData-(iDoclistData+n));
  90572. pWriter->data.nData -= n-nActual;
  90573. }
  90574. /* Replace written length with actual length. */
  90575. memcpy(pWriter->data.pData+iDoclistData, c, nActual);
  90576. /* If the node is too large, break things up. */
  90577. /* TODO(shess) This test matches leafWriterStep(), which does this
  90578. ** test before it knows the cost to varint-encode the term and
  90579. ** doclist lengths. At some point, change to
  90580. ** pWriter->data.nData>LEAF_MAX.
  90581. */
  90582. if( iTermData+nTerm+nActualData>LEAF_MAX ){
  90583. /* Flush out the leading data as a node */
  90584. rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
  90585. if( rc!=SQLITE_OK ) return rc;
  90586. pWriter->nTermDistinct = nTermDistinct;
  90587. /* Rebuild header using the current term */
  90588. n = fts3PutVarint(pWriter->data.pData, 0);
  90589. n += fts3PutVarint(pWriter->data.pData+n, nTerm);
  90590. memcpy(pWriter->data.pData+n, pTerm, nTerm);
  90591. n += nTerm;
  90592. /* There should always be room, because the previous encoding
  90593. ** included all data necessary to construct the term.
  90594. */
  90595. assert( n<iDoclistData );
  90596. /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
  90597. ** following memcpy() is safe (as opposed to needing a memmove).
  90598. */
  90599. assert( 2*STANDALONE_MIN<=LEAF_MAX );
  90600. assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
  90601. memcpy(pWriter->data.pData+n,
  90602. pWriter->data.pData+iDoclistData,
  90603. pWriter->data.nData-iDoclistData);
  90604. pWriter->data.nData -= iDoclistData-n;
  90605. }
  90606. ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  90607. return SQLITE_OK;
  90608. }
  90609. /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
  90610. ** %_segments.
  90611. */
  90612. /* TODO(shess) Revise writeZeroSegment() so that doclists are
  90613. ** constructed directly in pWriter->data.
  90614. */
  90615. static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
  90616. const char *pTerm, int nTerm,
  90617. const char *pData, int nData){
  90618. int rc;
  90619. DLReader reader;
  90620. dlrInit(&reader, DL_DEFAULT, pData, nData);
  90621. rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
  90622. dlrDestroy(&reader);
  90623. return rc;
  90624. }
  90625. /****************************************************************/
  90626. /* LeafReader is used to iterate over an individual leaf node. */
  90627. typedef struct LeafReader {
  90628. DataBuffer term; /* copy of current term. */
  90629. const char *pData; /* data for current term. */
  90630. int nData;
  90631. } LeafReader;
  90632. static void leafReaderDestroy(LeafReader *pReader){
  90633. dataBufferDestroy(&pReader->term);
  90634. SCRAMBLE(pReader);
  90635. }
  90636. static int leafReaderAtEnd(LeafReader *pReader){
  90637. return pReader->nData<=0;
  90638. }
  90639. /* Access the current term. */
  90640. static int leafReaderTermBytes(LeafReader *pReader){
  90641. return pReader->term.nData;
  90642. }
  90643. static const char *leafReaderTerm(LeafReader *pReader){
  90644. assert( pReader->term.nData>0 );
  90645. return pReader->term.pData;
  90646. }
  90647. /* Access the doclist data for the current term. */
  90648. static int leafReaderDataBytes(LeafReader *pReader){
  90649. int nData;
  90650. assert( pReader->term.nData>0 );
  90651. fts3GetVarint32(pReader->pData, &nData);
  90652. return nData;
  90653. }
  90654. static const char *leafReaderData(LeafReader *pReader){
  90655. int n, nData;
  90656. assert( pReader->term.nData>0 );
  90657. n = fts3GetVarint32(pReader->pData, &nData);
  90658. return pReader->pData+n;
  90659. }
  90660. static void leafReaderInit(const char *pData, int nData,
  90661. LeafReader *pReader){
  90662. int nTerm, n;
  90663. assert( nData>0 );
  90664. assert( pData[0]=='\0' );
  90665. CLEAR(pReader);
  90666. /* Read the first term, skipping the header byte. */
  90667. n = fts3GetVarint32(pData+1, &nTerm);
  90668. dataBufferInit(&pReader->term, nTerm);
  90669. dataBufferReplace(&pReader->term, pData+1+n, nTerm);
  90670. /* Position after the first term. */
  90671. assert( 1+n+nTerm<nData );
  90672. pReader->pData = pData+1+n+nTerm;
  90673. pReader->nData = nData-1-n-nTerm;
  90674. }
  90675. /* Step the reader forward to the next term. */
  90676. static void leafReaderStep(LeafReader *pReader){
  90677. int n, nData, nPrefix, nSuffix;
  90678. assert( !leafReaderAtEnd(pReader) );
  90679. /* Skip previous entry's data block. */
  90680. n = fts3GetVarint32(pReader->pData, &nData);
  90681. assert( n+nData<=pReader->nData );
  90682. pReader->pData += n+nData;
  90683. pReader->nData -= n+nData;
  90684. if( !leafReaderAtEnd(pReader) ){
  90685. /* Construct the new term using a prefix from the old term plus a
  90686. ** suffix from the leaf data.
  90687. */
  90688. n = fts3GetVarint32(pReader->pData, &nPrefix);
  90689. n += fts3GetVarint32(pReader->pData+n, &nSuffix);
  90690. assert( n+nSuffix<pReader->nData );
  90691. pReader->term.nData = nPrefix;
  90692. dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
  90693. pReader->pData += n+nSuffix;
  90694. pReader->nData -= n+nSuffix;
  90695. }
  90696. }
  90697. /* strcmp-style comparison of pReader's current term against pTerm.
  90698. ** If isPrefix, equality means equal through nTerm bytes.
  90699. */
  90700. static int leafReaderTermCmp(LeafReader *pReader,
  90701. const char *pTerm, int nTerm, int isPrefix){
  90702. int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
  90703. if( n==0 ){
  90704. if( pReader->term.nData>0 ) return -1;
  90705. if(nTerm>0 ) return 1;
  90706. return 0;
  90707. }
  90708. c = memcmp(pReader->term.pData, pTerm, n);
  90709. if( c!=0 ) return c;
  90710. if( isPrefix && n==nTerm ) return 0;
  90711. return pReader->term.nData - nTerm;
  90712. }
  90713. /****************************************************************/
  90714. /* LeavesReader wraps LeafReader to allow iterating over the entire
  90715. ** leaf layer of the tree.
  90716. */
  90717. typedef struct LeavesReader {
  90718. int idx; /* Index within the segment. */
  90719. sqlite3_stmt *pStmt; /* Statement we're streaming leaves from. */
  90720. int eof; /* we've seen SQLITE_DONE from pStmt. */
  90721. LeafReader leafReader; /* reader for the current leaf. */
  90722. DataBuffer rootData; /* root data for inline. */
  90723. } LeavesReader;
  90724. /* Access the current term. */
  90725. static int leavesReaderTermBytes(LeavesReader *pReader){
  90726. assert( !pReader->eof );
  90727. return leafReaderTermBytes(&pReader->leafReader);
  90728. }
  90729. static const char *leavesReaderTerm(LeavesReader *pReader){
  90730. assert( !pReader->eof );
  90731. return leafReaderTerm(&pReader->leafReader);
  90732. }
  90733. /* Access the doclist data for the current term. */
  90734. static int leavesReaderDataBytes(LeavesReader *pReader){
  90735. assert( !pReader->eof );
  90736. return leafReaderDataBytes(&pReader->leafReader);
  90737. }
  90738. static const char *leavesReaderData(LeavesReader *pReader){
  90739. assert( !pReader->eof );
  90740. return leafReaderData(&pReader->leafReader);
  90741. }
  90742. static int leavesReaderAtEnd(LeavesReader *pReader){
  90743. return pReader->eof;
  90744. }
  90745. /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
  90746. ** leaving the statement handle open, which locks the table.
  90747. */
  90748. /* TODO(shess) This "solution" is not satisfactory. Really, there
  90749. ** should be check-in function for all statement handles which
  90750. ** arranges to call sqlite3_reset(). This most likely will require
  90751. ** modification to control flow all over the place, though, so for now
  90752. ** just punt.
  90753. **
  90754. ** Note the the current system assumes that segment merges will run to
  90755. ** completion, which is why this particular probably hasn't arisen in
  90756. ** this case. Probably a brittle assumption.
  90757. */
  90758. static int leavesReaderReset(LeavesReader *pReader){
  90759. return sqlite3_reset(pReader->pStmt);
  90760. }
  90761. static void leavesReaderDestroy(LeavesReader *pReader){
  90762. /* If idx is -1, that means we're using a non-cached statement
  90763. ** handle in the optimize() case, so we need to release it.
  90764. */
  90765. if( pReader->pStmt!=NULL && pReader->idx==-1 ){
  90766. sqlite3_finalize(pReader->pStmt);
  90767. }
  90768. leafReaderDestroy(&pReader->leafReader);
  90769. dataBufferDestroy(&pReader->rootData);
  90770. SCRAMBLE(pReader);
  90771. }
  90772. /* Initialize pReader with the given root data (if iStartBlockid==0
  90773. ** the leaf data was entirely contained in the root), or from the
  90774. ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
  90775. */
  90776. static int leavesReaderInit(fulltext_vtab *v,
  90777. int idx,
  90778. sqlite_int64 iStartBlockid,
  90779. sqlite_int64 iEndBlockid,
  90780. const char *pRootData, int nRootData,
  90781. LeavesReader *pReader){
  90782. CLEAR(pReader);
  90783. pReader->idx = idx;
  90784. dataBufferInit(&pReader->rootData, 0);
  90785. if( iStartBlockid==0 ){
  90786. /* Entire leaf level fit in root data. */
  90787. dataBufferReplace(&pReader->rootData, pRootData, nRootData);
  90788. leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
  90789. &pReader->leafReader);
  90790. }else{
  90791. sqlite3_stmt *s;
  90792. int rc = sql_get_leaf_statement(v, idx, &s);
  90793. if( rc!=SQLITE_OK ) return rc;
  90794. rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  90795. if( rc!=SQLITE_OK ) return rc;
  90796. rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  90797. if( rc!=SQLITE_OK ) return rc;
  90798. rc = sqlite3_step(s);
  90799. if( rc==SQLITE_DONE ){
  90800. pReader->eof = 1;
  90801. return SQLITE_OK;
  90802. }
  90803. if( rc!=SQLITE_ROW ) return rc;
  90804. pReader->pStmt = s;
  90805. leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
  90806. sqlite3_column_bytes(pReader->pStmt, 0),
  90807. &pReader->leafReader);
  90808. }
  90809. return SQLITE_OK;
  90810. }
  90811. /* Step the current leaf forward to the next term. If we reach the
  90812. ** end of the current leaf, step forward to the next leaf block.
  90813. */
  90814. static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
  90815. assert( !leavesReaderAtEnd(pReader) );
  90816. leafReaderStep(&pReader->leafReader);
  90817. if( leafReaderAtEnd(&pReader->leafReader) ){
  90818. int rc;
  90819. if( pReader->rootData.pData ){
  90820. pReader->eof = 1;
  90821. return SQLITE_OK;
  90822. }
  90823. rc = sqlite3_step(pReader->pStmt);
  90824. if( rc!=SQLITE_ROW ){
  90825. pReader->eof = 1;
  90826. return rc==SQLITE_DONE ? SQLITE_OK : rc;
  90827. }
  90828. leafReaderDestroy(&pReader->leafReader);
  90829. leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
  90830. sqlite3_column_bytes(pReader->pStmt, 0),
  90831. &pReader->leafReader);
  90832. }
  90833. return SQLITE_OK;
  90834. }
  90835. /* Order LeavesReaders by their term, ignoring idx. Readers at eof
  90836. ** always sort to the end.
  90837. */
  90838. static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
  90839. if( leavesReaderAtEnd(lr1) ){
  90840. if( leavesReaderAtEnd(lr2) ) return 0;
  90841. return 1;
  90842. }
  90843. if( leavesReaderAtEnd(lr2) ) return -1;
  90844. return leafReaderTermCmp(&lr1->leafReader,
  90845. leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
  90846. 0);
  90847. }
  90848. /* Similar to leavesReaderTermCmp(), with additional ordering by idx
  90849. ** so that older segments sort before newer segments.
  90850. */
  90851. static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
  90852. int c = leavesReaderTermCmp(lr1, lr2);
  90853. if( c!=0 ) return c;
  90854. return lr1->idx-lr2->idx;
  90855. }
  90856. /* Assume that pLr[1]..pLr[nLr] are sorted. Bubble pLr[0] into its
  90857. ** sorted position.
  90858. */
  90859. static void leavesReaderReorder(LeavesReader *pLr, int nLr){
  90860. while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
  90861. LeavesReader tmp = pLr[0];
  90862. pLr[0] = pLr[1];
  90863. pLr[1] = tmp;
  90864. nLr--;
  90865. pLr++;
  90866. }
  90867. }
  90868. /* Initializes pReaders with the segments from level iLevel, returning
  90869. ** the number of segments in *piReaders. Leaves pReaders in sorted
  90870. ** order.
  90871. */
  90872. static int leavesReadersInit(fulltext_vtab *v, int iLevel,
  90873. LeavesReader *pReaders, int *piReaders){
  90874. sqlite3_stmt *s;
  90875. int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
  90876. if( rc!=SQLITE_OK ) return rc;
  90877. rc = sqlite3_bind_int(s, 1, iLevel);
  90878. if( rc!=SQLITE_OK ) return rc;
  90879. i = 0;
  90880. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  90881. sqlite_int64 iStart = sqlite3_column_int64(s, 0);
  90882. sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
  90883. const char *pRootData = sqlite3_column_blob(s, 2);
  90884. int nRootData = sqlite3_column_bytes(s, 2);
  90885. assert( i<MERGE_COUNT );
  90886. rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
  90887. &pReaders[i]);
  90888. if( rc!=SQLITE_OK ) break;
  90889. i++;
  90890. }
  90891. if( rc!=SQLITE_DONE ){
  90892. while( i-->0 ){
  90893. leavesReaderDestroy(&pReaders[i]);
  90894. }
  90895. return rc;
  90896. }
  90897. *piReaders = i;
  90898. /* Leave our results sorted by term, then age. */
  90899. while( i-- ){
  90900. leavesReaderReorder(pReaders+i, *piReaders-i);
  90901. }
  90902. return SQLITE_OK;
  90903. }
  90904. /* Merge doclists from pReaders[nReaders] into a single doclist, which
  90905. ** is written to pWriter. Assumes pReaders is ordered oldest to
  90906. ** newest.
  90907. */
  90908. /* TODO(shess) Consider putting this inline in segmentMerge(). */
  90909. static int leavesReadersMerge(fulltext_vtab *v,
  90910. LeavesReader *pReaders, int nReaders,
  90911. LeafWriter *pWriter){
  90912. DLReader dlReaders[MERGE_COUNT];
  90913. const char *pTerm = leavesReaderTerm(pReaders);
  90914. int i, nTerm = leavesReaderTermBytes(pReaders);
  90915. assert( nReaders<=MERGE_COUNT );
  90916. for(i=0; i<nReaders; i++){
  90917. dlrInit(&dlReaders[i], DL_DEFAULT,
  90918. leavesReaderData(pReaders+i),
  90919. leavesReaderDataBytes(pReaders+i));
  90920. }
  90921. return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
  90922. }
  90923. /* Forward ref due to mutual recursion with segdirNextIndex(). */
  90924. static int segmentMerge(fulltext_vtab *v, int iLevel);
  90925. /* Put the next available index at iLevel into *pidx. If iLevel
  90926. ** already has MERGE_COUNT segments, they are merged to a higher
  90927. ** level to make room.
  90928. */
  90929. static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
  90930. int rc = segdir_max_index(v, iLevel, pidx);
  90931. if( rc==SQLITE_DONE ){ /* No segments at iLevel. */
  90932. *pidx = 0;
  90933. }else if( rc==SQLITE_ROW ){
  90934. if( *pidx==(MERGE_COUNT-1) ){
  90935. rc = segmentMerge(v, iLevel);
  90936. if( rc!=SQLITE_OK ) return rc;
  90937. *pidx = 0;
  90938. }else{
  90939. (*pidx)++;
  90940. }
  90941. }else{
  90942. return rc;
  90943. }
  90944. return SQLITE_OK;
  90945. }
  90946. /* Merge MERGE_COUNT segments at iLevel into a new segment at
  90947. ** iLevel+1. If iLevel+1 is already full of segments, those will be
  90948. ** merged to make room.
  90949. */
  90950. static int segmentMerge(fulltext_vtab *v, int iLevel){
  90951. LeafWriter writer;
  90952. LeavesReader lrs[MERGE_COUNT];
  90953. int i, rc, idx = 0;
  90954. /* Determine the next available segment index at the next level,
  90955. ** merging as necessary.
  90956. */
  90957. rc = segdirNextIndex(v, iLevel+1, &idx);
  90958. if( rc!=SQLITE_OK ) return rc;
  90959. /* TODO(shess) This assumes that we'll always see exactly
  90960. ** MERGE_COUNT segments to merge at a given level. That will be
  90961. ** broken if we allow the developer to request preemptive or
  90962. ** deferred merging.
  90963. */
  90964. memset(&lrs, '\0', sizeof(lrs));
  90965. rc = leavesReadersInit(v, iLevel, lrs, &i);
  90966. if( rc!=SQLITE_OK ) return rc;
  90967. assert( i==MERGE_COUNT );
  90968. leafWriterInit(iLevel+1, idx, &writer);
  90969. /* Since leavesReaderReorder() pushes readers at eof to the end,
  90970. ** when the first reader is empty, all will be empty.
  90971. */
  90972. while( !leavesReaderAtEnd(lrs) ){
  90973. /* Figure out how many readers share their next term. */
  90974. for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
  90975. if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
  90976. }
  90977. rc = leavesReadersMerge(v, lrs, i, &writer);
  90978. if( rc!=SQLITE_OK ) goto err;
  90979. /* Step forward those that were merged. */
  90980. while( i-->0 ){
  90981. rc = leavesReaderStep(v, lrs+i);
  90982. if( rc!=SQLITE_OK ) goto err;
  90983. /* Reorder by term, then by age. */
  90984. leavesReaderReorder(lrs+i, MERGE_COUNT-i);
  90985. }
  90986. }
  90987. for(i=0; i<MERGE_COUNT; i++){
  90988. leavesReaderDestroy(&lrs[i]);
  90989. }
  90990. rc = leafWriterFinalize(v, &writer);
  90991. leafWriterDestroy(&writer);
  90992. if( rc!=SQLITE_OK ) return rc;
  90993. /* Delete the merged segment data. */
  90994. return segdir_delete(v, iLevel);
  90995. err:
  90996. for(i=0; i<MERGE_COUNT; i++){
  90997. leavesReaderDestroy(&lrs[i]);
  90998. }
  90999. leafWriterDestroy(&writer);
  91000. return rc;
  91001. }
  91002. /* Accumulate the union of *acc and *pData into *acc. */
  91003. static void docListAccumulateUnion(DataBuffer *acc,
  91004. const char *pData, int nData) {
  91005. DataBuffer tmp = *acc;
  91006. dataBufferInit(acc, tmp.nData+nData);
  91007. docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
  91008. dataBufferDestroy(&tmp);
  91009. }
  91010. /* TODO(shess) It might be interesting to explore different merge
  91011. ** strategies, here. For instance, since this is a sorted merge, we
  91012. ** could easily merge many doclists in parallel. With some
  91013. ** comprehension of the storage format, we could merge all of the
  91014. ** doclists within a leaf node directly from the leaf node's storage.
  91015. ** It may be worthwhile to merge smaller doclists before larger
  91016. ** doclists, since they can be traversed more quickly - but the
  91017. ** results may have less overlap, making them more expensive in a
  91018. ** different way.
  91019. */
  91020. /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
  91021. ** *out (any doclists with duplicate docids overwrite those in *out).
  91022. ** Internal function for loadSegmentLeaf().
  91023. */
  91024. static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
  91025. const char *pTerm, int nTerm, int isPrefix,
  91026. DataBuffer *out){
  91027. /* doclist data is accumulated into pBuffers similar to how one does
  91028. ** increment in binary arithmetic. If index 0 is empty, the data is
  91029. ** stored there. If there is data there, it is merged and the
  91030. ** results carried into position 1, with further merge-and-carry
  91031. ** until an empty position is found.
  91032. */
  91033. DataBuffer *pBuffers = NULL;
  91034. int nBuffers = 0, nMaxBuffers = 0, rc;
  91035. assert( nTerm>0 );
  91036. for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
  91037. rc=leavesReaderStep(v, pReader)){
  91038. /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
  91039. ** already taken to compare the terms of two LeavesReaders. Think
  91040. ** on a better name. [Meanwhile, break encapsulation rather than
  91041. ** use a confusing name.]
  91042. */
  91043. int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
  91044. if( c>0 ) break; /* Past any possible matches. */
  91045. if( c==0 ){
  91046. const char *pData = leavesReaderData(pReader);
  91047. int iBuffer, nData = leavesReaderDataBytes(pReader);
  91048. /* Find the first empty buffer. */
  91049. for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
  91050. if( 0==pBuffers[iBuffer].nData ) break;
  91051. }
  91052. /* Out of buffers, add an empty one. */
  91053. if( iBuffer==nBuffers ){
  91054. if( nBuffers==nMaxBuffers ){
  91055. DataBuffer *p;
  91056. nMaxBuffers += 20;
  91057. /* Manual realloc so we can handle NULL appropriately. */
  91058. p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
  91059. if( p==NULL ){
  91060. rc = SQLITE_NOMEM;
  91061. break;
  91062. }
  91063. if( nBuffers>0 ){
  91064. assert(pBuffers!=NULL);
  91065. memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
  91066. sqlite3_free(pBuffers);
  91067. }
  91068. pBuffers = p;
  91069. }
  91070. dataBufferInit(&(pBuffers[nBuffers]), 0);
  91071. nBuffers++;
  91072. }
  91073. /* At this point, must have an empty at iBuffer. */
  91074. assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
  91075. /* If empty was first buffer, no need for merge logic. */
  91076. if( iBuffer==0 ){
  91077. dataBufferReplace(&(pBuffers[0]), pData, nData);
  91078. }else{
  91079. /* pAcc is the empty buffer the merged data will end up in. */
  91080. DataBuffer *pAcc = &(pBuffers[iBuffer]);
  91081. DataBuffer *p = &(pBuffers[0]);
  91082. /* Handle position 0 specially to avoid need to prime pAcc
  91083. ** with pData/nData.
  91084. */
  91085. dataBufferSwap(p, pAcc);
  91086. docListAccumulateUnion(pAcc, pData, nData);
  91087. /* Accumulate remaining doclists into pAcc. */
  91088. for(++p; p<pAcc; ++p){
  91089. docListAccumulateUnion(pAcc, p->pData, p->nData);
  91090. /* dataBufferReset() could allow a large doclist to blow up
  91091. ** our memory requirements.
  91092. */
  91093. if( p->nCapacity<1024 ){
  91094. dataBufferReset(p);
  91095. }else{
  91096. dataBufferDestroy(p);
  91097. dataBufferInit(p, 0);
  91098. }
  91099. }
  91100. }
  91101. }
  91102. }
  91103. /* Union all the doclists together into *out. */
  91104. /* TODO(shess) What if *out is big? Sigh. */
  91105. if( rc==SQLITE_OK && nBuffers>0 ){
  91106. int iBuffer;
  91107. for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
  91108. if( pBuffers[iBuffer].nData>0 ){
  91109. if( out->nData==0 ){
  91110. dataBufferSwap(out, &(pBuffers[iBuffer]));
  91111. }else{
  91112. docListAccumulateUnion(out, pBuffers[iBuffer].pData,
  91113. pBuffers[iBuffer].nData);
  91114. }
  91115. }
  91116. }
  91117. }
  91118. while( nBuffers-- ){
  91119. dataBufferDestroy(&(pBuffers[nBuffers]));
  91120. }
  91121. if( pBuffers!=NULL ) sqlite3_free(pBuffers);
  91122. return rc;
  91123. }
  91124. /* Call loadSegmentLeavesInt() with pData/nData as input. */
  91125. static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
  91126. const char *pTerm, int nTerm, int isPrefix,
  91127. DataBuffer *out){
  91128. LeavesReader reader;
  91129. int rc;
  91130. assert( nData>1 );
  91131. assert( *pData=='\0' );
  91132. rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
  91133. if( rc!=SQLITE_OK ) return rc;
  91134. rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  91135. leavesReaderReset(&reader);
  91136. leavesReaderDestroy(&reader);
  91137. return rc;
  91138. }
  91139. /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
  91140. ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
  91141. ** out.
  91142. */
  91143. static int loadSegmentLeaves(fulltext_vtab *v,
  91144. sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
  91145. const char *pTerm, int nTerm, int isPrefix,
  91146. DataBuffer *out){
  91147. int rc;
  91148. LeavesReader reader;
  91149. assert( iStartLeaf<=iEndLeaf );
  91150. rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
  91151. if( rc!=SQLITE_OK ) return rc;
  91152. rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  91153. leavesReaderReset(&reader);
  91154. leavesReaderDestroy(&reader);
  91155. return rc;
  91156. }
  91157. /* Taking pData/nData as an interior node, find the sequence of child
  91158. ** nodes which could include pTerm/nTerm/isPrefix. Note that the
  91159. ** interior node terms logically come between the blocks, so there is
  91160. ** one more blockid than there are terms (that block contains terms >=
  91161. ** the last interior-node term).
  91162. */
  91163. /* TODO(shess) The calling code may already know that the end child is
  91164. ** not worth calculating, because the end may be in a later sibling
  91165. ** node. Consider whether breaking symmetry is worthwhile. I suspect
  91166. ** it is not worthwhile.
  91167. */
  91168. static void getChildrenContaining(const char *pData, int nData,
  91169. const char *pTerm, int nTerm, int isPrefix,
  91170. sqlite_int64 *piStartChild,
  91171. sqlite_int64 *piEndChild){
  91172. InteriorReader reader;
  91173. assert( nData>1 );
  91174. assert( *pData!='\0' );
  91175. interiorReaderInit(pData, nData, &reader);
  91176. /* Scan for the first child which could contain pTerm/nTerm. */
  91177. while( !interiorReaderAtEnd(&reader) ){
  91178. if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
  91179. interiorReaderStep(&reader);
  91180. }
  91181. *piStartChild = interiorReaderCurrentBlockid(&reader);
  91182. /* Keep scanning to find a term greater than our term, using prefix
  91183. ** comparison if indicated. If isPrefix is false, this will be the
  91184. ** same blockid as the starting block.
  91185. */
  91186. while( !interiorReaderAtEnd(&reader) ){
  91187. if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
  91188. interiorReaderStep(&reader);
  91189. }
  91190. *piEndChild = interiorReaderCurrentBlockid(&reader);
  91191. interiorReaderDestroy(&reader);
  91192. /* Children must ascend, and if !prefix, both must be the same. */
  91193. assert( *piEndChild>=*piStartChild );
  91194. assert( isPrefix || *piStartChild==*piEndChild );
  91195. }
  91196. /* Read block at iBlockid and pass it with other params to
  91197. ** getChildrenContaining().
  91198. */
  91199. static int loadAndGetChildrenContaining(
  91200. fulltext_vtab *v,
  91201. sqlite_int64 iBlockid,
  91202. const char *pTerm, int nTerm, int isPrefix,
  91203. sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
  91204. ){
  91205. sqlite3_stmt *s = NULL;
  91206. int rc;
  91207. assert( iBlockid!=0 );
  91208. assert( pTerm!=NULL );
  91209. assert( nTerm!=0 ); /* TODO(shess) Why not allow this? */
  91210. assert( piStartChild!=NULL );
  91211. assert( piEndChild!=NULL );
  91212. rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
  91213. if( rc!=SQLITE_OK ) return rc;
  91214. rc = sqlite3_bind_int64(s, 1, iBlockid);
  91215. if( rc!=SQLITE_OK ) return rc;
  91216. rc = sqlite3_step(s);
  91217. if( rc==SQLITE_DONE ) return SQLITE_ERROR;
  91218. if( rc!=SQLITE_ROW ) return rc;
  91219. getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
  91220. pTerm, nTerm, isPrefix, piStartChild, piEndChild);
  91221. /* We expect only one row. We must execute another sqlite3_step()
  91222. * to complete the iteration; otherwise the table will remain
  91223. * locked. */
  91224. rc = sqlite3_step(s);
  91225. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  91226. if( rc!=SQLITE_DONE ) return rc;
  91227. return SQLITE_OK;
  91228. }
  91229. /* Traverse the tree represented by pData[nData] looking for
  91230. ** pTerm[nTerm], placing its doclist into *out. This is internal to
  91231. ** loadSegment() to make error-handling cleaner.
  91232. */
  91233. static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
  91234. sqlite_int64 iLeavesEnd,
  91235. const char *pTerm, int nTerm, int isPrefix,
  91236. DataBuffer *out){
  91237. /* Special case where root is a leaf. */
  91238. if( *pData=='\0' ){
  91239. return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
  91240. }else{
  91241. int rc;
  91242. sqlite_int64 iStartChild, iEndChild;
  91243. /* Process pData as an interior node, then loop down the tree
  91244. ** until we find the set of leaf nodes to scan for the term.
  91245. */
  91246. getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
  91247. &iStartChild, &iEndChild);
  91248. while( iStartChild>iLeavesEnd ){
  91249. sqlite_int64 iNextStart, iNextEnd;
  91250. rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
  91251. &iNextStart, &iNextEnd);
  91252. if( rc!=SQLITE_OK ) return rc;
  91253. /* If we've branched, follow the end branch, too. */
  91254. if( iStartChild!=iEndChild ){
  91255. sqlite_int64 iDummy;
  91256. rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
  91257. &iDummy, &iNextEnd);
  91258. if( rc!=SQLITE_OK ) return rc;
  91259. }
  91260. assert( iNextStart<=iNextEnd );
  91261. iStartChild = iNextStart;
  91262. iEndChild = iNextEnd;
  91263. }
  91264. assert( iStartChild<=iLeavesEnd );
  91265. assert( iEndChild<=iLeavesEnd );
  91266. /* Scan through the leaf segments for doclists. */
  91267. return loadSegmentLeaves(v, iStartChild, iEndChild,
  91268. pTerm, nTerm, isPrefix, out);
  91269. }
  91270. }
  91271. /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
  91272. ** merge its doclist over *out (any duplicate doclists read from the
  91273. ** segment rooted at pData will overwrite those in *out).
  91274. */
  91275. /* TODO(shess) Consider changing this to determine the depth of the
  91276. ** leaves using either the first characters of interior nodes (when
  91277. ** ==1, we're one level above the leaves), or the first character of
  91278. ** the root (which will describe the height of the tree directly).
  91279. ** Either feels somewhat tricky to me.
  91280. */
  91281. /* TODO(shess) The current merge is likely to be slow for large
  91282. ** doclists (though it should process from newest/smallest to
  91283. ** oldest/largest, so it may not be that bad). It might be useful to
  91284. ** modify things to allow for N-way merging. This could either be
  91285. ** within a segment, with pairwise merges across segments, or across
  91286. ** all segments at once.
  91287. */
  91288. static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
  91289. sqlite_int64 iLeavesEnd,
  91290. const char *pTerm, int nTerm, int isPrefix,
  91291. DataBuffer *out){
  91292. DataBuffer result;
  91293. int rc;
  91294. assert( nData>1 );
  91295. /* This code should never be called with buffered updates. */
  91296. assert( v->nPendingData<0 );
  91297. dataBufferInit(&result, 0);
  91298. rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
  91299. pTerm, nTerm, isPrefix, &result);
  91300. if( rc==SQLITE_OK && result.nData>0 ){
  91301. if( out->nData==0 ){
  91302. DataBuffer tmp = *out;
  91303. *out = result;
  91304. result = tmp;
  91305. }else{
  91306. DataBuffer merged;
  91307. DLReader readers[2];
  91308. dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
  91309. dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
  91310. dataBufferInit(&merged, out->nData+result.nData);
  91311. docListMerge(&merged, readers, 2);
  91312. dataBufferDestroy(out);
  91313. *out = merged;
  91314. dlrDestroy(&readers[0]);
  91315. dlrDestroy(&readers[1]);
  91316. }
  91317. }
  91318. dataBufferDestroy(&result);
  91319. return rc;
  91320. }
  91321. /* Scan the database and merge together the posting lists for the term
  91322. ** into *out.
  91323. */
  91324. static int termSelect(
  91325. fulltext_vtab *v,
  91326. int iColumn,
  91327. const char *pTerm, int nTerm, /* Term to query for */
  91328. int isPrefix, /* True for a prefix search */
  91329. DocListType iType,
  91330. DataBuffer *out /* Write results here */
  91331. ){
  91332. DataBuffer doclist;
  91333. sqlite3_stmt *s;
  91334. int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  91335. if( rc!=SQLITE_OK ) return rc;
  91336. /* This code should never be called with buffered updates. */
  91337. assert( v->nPendingData<0 );
  91338. dataBufferInit(&doclist, 0);
  91339. dataBufferInit(out, 0);
  91340. /* Traverse the segments from oldest to newest so that newer doclist
  91341. ** elements for given docids overwrite older elements.
  91342. */
  91343. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  91344. const char *pData = sqlite3_column_blob(s, 2);
  91345. const int nData = sqlite3_column_bytes(s, 2);
  91346. const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
  91347. rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
  91348. &doclist);
  91349. if( rc!=SQLITE_OK ) goto err;
  91350. }
  91351. if( rc==SQLITE_DONE ){
  91352. if( doclist.nData!=0 ){
  91353. /* TODO(shess) The old term_select_all() code applied the column
  91354. ** restrict as we merged segments, leading to smaller buffers.
  91355. ** This is probably worthwhile to bring back, once the new storage
  91356. ** system is checked in.
  91357. */
  91358. if( iColumn==v->nColumn) iColumn = -1;
  91359. docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
  91360. iColumn, iType, out);
  91361. }
  91362. rc = SQLITE_OK;
  91363. }
  91364. err:
  91365. dataBufferDestroy(&doclist);
  91366. return rc;
  91367. }
  91368. /****************************************************************/
  91369. /* Used to hold hashtable data for sorting. */
  91370. typedef struct TermData {
  91371. const char *pTerm;
  91372. int nTerm;
  91373. DLCollector *pCollector;
  91374. } TermData;
  91375. /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
  91376. ** for equal, >0 for greater-than).
  91377. */
  91378. static int termDataCmp(const void *av, const void *bv){
  91379. const TermData *a = (const TermData *)av;
  91380. const TermData *b = (const TermData *)bv;
  91381. int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
  91382. int c = memcmp(a->pTerm, b->pTerm, n);
  91383. if( c!=0 ) return c;
  91384. return a->nTerm-b->nTerm;
  91385. }
  91386. /* Order pTerms data by term, then write a new level 0 segment using
  91387. ** LeafWriter.
  91388. */
  91389. static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
  91390. fts3HashElem *e;
  91391. int idx, rc, i, n;
  91392. TermData *pData;
  91393. LeafWriter writer;
  91394. DataBuffer dl;
  91395. /* Determine the next index at level 0, merging as necessary. */
  91396. rc = segdirNextIndex(v, 0, &idx);
  91397. if( rc!=SQLITE_OK ) return rc;
  91398. n = fts3HashCount(pTerms);
  91399. pData = sqlite3_malloc(n*sizeof(TermData));
  91400. for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
  91401. assert( i<n );
  91402. pData[i].pTerm = fts3HashKey(e);
  91403. pData[i].nTerm = fts3HashKeysize(e);
  91404. pData[i].pCollector = fts3HashData(e);
  91405. }
  91406. assert( i==n );
  91407. /* TODO(shess) Should we allow user-defined collation sequences,
  91408. ** here? I think we only need that once we support prefix searches.
  91409. */
  91410. if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
  91411. /* TODO(shess) Refactor so that we can write directly to the segment
  91412. ** DataBuffer, as happens for segment merges.
  91413. */
  91414. leafWriterInit(0, idx, &writer);
  91415. dataBufferInit(&dl, 0);
  91416. for(i=0; i<n; i++){
  91417. dataBufferReset(&dl);
  91418. dlcAddDoclist(pData[i].pCollector, &dl);
  91419. rc = leafWriterStep(v, &writer,
  91420. pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
  91421. if( rc!=SQLITE_OK ) goto err;
  91422. }
  91423. rc = leafWriterFinalize(v, &writer);
  91424. err:
  91425. dataBufferDestroy(&dl);
  91426. sqlite3_free(pData);
  91427. leafWriterDestroy(&writer);
  91428. return rc;
  91429. }
  91430. /* If pendingTerms has data, free it. */
  91431. static int clearPendingTerms(fulltext_vtab *v){
  91432. if( v->nPendingData>=0 ){
  91433. fts3HashElem *e;
  91434. for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
  91435. dlcDelete(fts3HashData(e));
  91436. }
  91437. fts3HashClear(&v->pendingTerms);
  91438. v->nPendingData = -1;
  91439. }
  91440. return SQLITE_OK;
  91441. }
  91442. /* If pendingTerms has data, flush it to a level-zero segment, and
  91443. ** free it.
  91444. */
  91445. static int flushPendingTerms(fulltext_vtab *v){
  91446. if( v->nPendingData>=0 ){
  91447. int rc = writeZeroSegment(v, &v->pendingTerms);
  91448. if( rc==SQLITE_OK ) clearPendingTerms(v);
  91449. return rc;
  91450. }
  91451. return SQLITE_OK;
  91452. }
  91453. /* If pendingTerms is "too big", or docid is out of order, flush it.
  91454. ** Regardless, be certain that pendingTerms is initialized for use.
  91455. */
  91456. static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  91457. /* TODO(shess) Explore whether partially flushing the buffer on
  91458. ** forced-flush would provide better performance. I suspect that if
  91459. ** we ordered the doclists by size and flushed the largest until the
  91460. ** buffer was half empty, that would let the less frequent terms
  91461. ** generate longer doclists.
  91462. */
  91463. if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
  91464. int rc = flushPendingTerms(v);
  91465. if( rc!=SQLITE_OK ) return rc;
  91466. }
  91467. if( v->nPendingData<0 ){
  91468. fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
  91469. v->nPendingData = 0;
  91470. }
  91471. v->iPrevDocid = iDocid;
  91472. return SQLITE_OK;
  91473. }
  91474. /* This function implements the xUpdate callback; it is the top-level entry
  91475. * point for inserting, deleting or updating a row in a full-text table. */
  91476. static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
  91477. sqlite_int64 *pRowid){
  91478. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  91479. int rc;
  91480. FTSTRACE(("FTS3 Update %p\n", pVtab));
  91481. if( nArg<2 ){
  91482. rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
  91483. if( rc==SQLITE_OK ){
  91484. /* If we just deleted the last row in the table, clear out the
  91485. ** index data.
  91486. */
  91487. rc = content_exists(v);
  91488. if( rc==SQLITE_ROW ){
  91489. rc = SQLITE_OK;
  91490. }else if( rc==SQLITE_DONE ){
  91491. /* Clear the pending terms so we don't flush a useless level-0
  91492. ** segment when the transaction closes.
  91493. */
  91494. rc = clearPendingTerms(v);
  91495. if( rc==SQLITE_OK ){
  91496. rc = segdir_delete_all(v);
  91497. }
  91498. }
  91499. }
  91500. } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
  91501. /* An update:
  91502. * ppArg[0] = old rowid
  91503. * ppArg[1] = new rowid
  91504. * ppArg[2..2+v->nColumn-1] = values
  91505. * ppArg[2+v->nColumn] = value for magic column (we ignore this)
  91506. * ppArg[2+v->nColumn+1] = value for docid
  91507. */
  91508. sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
  91509. if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
  91510. sqlite3_value_int64(ppArg[1]) != rowid ){
  91511. rc = SQLITE_ERROR; /* we don't allow changing the rowid */
  91512. }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
  91513. sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
  91514. rc = SQLITE_ERROR; /* we don't allow changing the docid */
  91515. }else{
  91516. assert( nArg==2+v->nColumn+2);
  91517. rc = index_update(v, rowid, &ppArg[2]);
  91518. }
  91519. } else {
  91520. /* An insert:
  91521. * ppArg[1] = requested rowid
  91522. * ppArg[2..2+v->nColumn-1] = values
  91523. * ppArg[2+v->nColumn] = value for magic column (we ignore this)
  91524. * ppArg[2+v->nColumn+1] = value for docid
  91525. */
  91526. sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
  91527. assert( nArg==2+v->nColumn+2);
  91528. if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
  91529. SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
  91530. /* TODO(shess) Consider allowing this to work if the values are
  91531. ** identical. I'm inclined to discourage that usage, though,
  91532. ** given that both rowid and docid are special columns. Better
  91533. ** would be to define one or the other as the default winner,
  91534. ** but should it be fts3-centric (docid) or SQLite-centric
  91535. ** (rowid)?
  91536. */
  91537. rc = SQLITE_ERROR;
  91538. }else{
  91539. if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
  91540. pRequestDocid = ppArg[1];
  91541. }
  91542. rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
  91543. }
  91544. }
  91545. return rc;
  91546. }
  91547. static int fulltextSync(sqlite3_vtab *pVtab){
  91548. FTSTRACE(("FTS3 xSync()\n"));
  91549. return flushPendingTerms((fulltext_vtab *)pVtab);
  91550. }
  91551. static int fulltextBegin(sqlite3_vtab *pVtab){
  91552. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  91553. FTSTRACE(("FTS3 xBegin()\n"));
  91554. /* Any buffered updates should have been cleared by the previous
  91555. ** transaction.
  91556. */
  91557. assert( v->nPendingData<0 );
  91558. return clearPendingTerms(v);
  91559. }
  91560. static int fulltextCommit(sqlite3_vtab *pVtab){
  91561. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  91562. FTSTRACE(("FTS3 xCommit()\n"));
  91563. /* Buffered updates should have been cleared by fulltextSync(). */
  91564. assert( v->nPendingData<0 );
  91565. return clearPendingTerms(v);
  91566. }
  91567. static int fulltextRollback(sqlite3_vtab *pVtab){
  91568. FTSTRACE(("FTS3 xRollback()\n"));
  91569. return clearPendingTerms((fulltext_vtab *)pVtab);
  91570. }
  91571. /*
  91572. ** Implementation of the snippet() function for FTS3
  91573. */
  91574. static void snippetFunc(
  91575. sqlite3_context *pContext,
  91576. int argc,
  91577. sqlite3_value **argv
  91578. ){
  91579. fulltext_cursor *pCursor;
  91580. if( argc<1 ) return;
  91581. if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  91582. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  91583. sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
  91584. }else{
  91585. const char *zStart = "<b>";
  91586. const char *zEnd = "</b>";
  91587. const char *zEllipsis = "<b>...</b>";
  91588. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  91589. if( argc>=2 ){
  91590. zStart = (const char*)sqlite3_value_text(argv[1]);
  91591. if( argc>=3 ){
  91592. zEnd = (const char*)sqlite3_value_text(argv[2]);
  91593. if( argc>=4 ){
  91594. zEllipsis = (const char*)sqlite3_value_text(argv[3]);
  91595. }
  91596. }
  91597. }
  91598. snippetAllOffsets(pCursor);
  91599. snippetText(pCursor, zStart, zEnd, zEllipsis);
  91600. sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
  91601. pCursor->snippet.nSnippet, SQLITE_STATIC);
  91602. }
  91603. }
  91604. /*
  91605. ** Implementation of the offsets() function for FTS3
  91606. */
  91607. static void snippetOffsetsFunc(
  91608. sqlite3_context *pContext,
  91609. int argc,
  91610. sqlite3_value **argv
  91611. ){
  91612. fulltext_cursor *pCursor;
  91613. if( argc<1 ) return;
  91614. if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  91615. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  91616. sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
  91617. }else{
  91618. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  91619. snippetAllOffsets(pCursor);
  91620. snippetOffsetText(&pCursor->snippet);
  91621. sqlite3_result_text(pContext,
  91622. pCursor->snippet.zOffset, pCursor->snippet.nOffset,
  91623. SQLITE_STATIC);
  91624. }
  91625. }
  91626. /* OptLeavesReader is nearly identical to LeavesReader, except that
  91627. ** where LeavesReader is geared towards the merging of complete
  91628. ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
  91629. ** is geared towards implementation of the optimize() function, and
  91630. ** can merge all segments simultaneously. This version may be
  91631. ** somewhat less efficient than LeavesReader because it merges into an
  91632. ** accumulator rather than doing an N-way merge, but since segment
  91633. ** size grows exponentially (so segment count logrithmically) this is
  91634. ** probably not an immediate problem.
  91635. */
  91636. /* TODO(shess): Prove that assertion, or extend the merge code to
  91637. ** merge tree fashion (like the prefix-searching code does).
  91638. */
  91639. /* TODO(shess): OptLeavesReader and LeavesReader could probably be
  91640. ** merged with little or no loss of performance for LeavesReader. The
  91641. ** merged code would need to handle >MERGE_COUNT segments, and would
  91642. ** also need to be able to optionally optimize away deletes.
  91643. */
  91644. typedef struct OptLeavesReader {
  91645. /* Segment number, to order readers by age. */
  91646. int segment;
  91647. LeavesReader reader;
  91648. } OptLeavesReader;
  91649. static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
  91650. return leavesReaderAtEnd(&pReader->reader);
  91651. }
  91652. static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
  91653. return leavesReaderTermBytes(&pReader->reader);
  91654. }
  91655. static const char *optLeavesReaderData(OptLeavesReader *pReader){
  91656. return leavesReaderData(&pReader->reader);
  91657. }
  91658. static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
  91659. return leavesReaderDataBytes(&pReader->reader);
  91660. }
  91661. static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
  91662. return leavesReaderTerm(&pReader->reader);
  91663. }
  91664. static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
  91665. return leavesReaderStep(v, &pReader->reader);
  91666. }
  91667. static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  91668. return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
  91669. }
  91670. /* Order by term ascending, segment ascending (oldest to newest), with
  91671. ** exhausted readers to the end.
  91672. */
  91673. static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  91674. int c = optLeavesReaderTermCmp(lr1, lr2);
  91675. if( c!=0 ) return c;
  91676. return lr1->segment-lr2->segment;
  91677. }
  91678. /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1]. Assumes that
  91679. ** pLr[1..nLr-1] is already sorted.
  91680. */
  91681. static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
  91682. while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
  91683. OptLeavesReader tmp = pLr[0];
  91684. pLr[0] = pLr[1];
  91685. pLr[1] = tmp;
  91686. nLr--;
  91687. pLr++;
  91688. }
  91689. }
  91690. /* optimize() helper function. Put the readers in order and iterate
  91691. ** through them, merging doclists for matching terms into pWriter.
  91692. ** Returns SQLITE_OK on success, or the SQLite error code which
  91693. ** prevented success.
  91694. */
  91695. static int optimizeInternal(fulltext_vtab *v,
  91696. OptLeavesReader *readers, int nReaders,
  91697. LeafWriter *pWriter){
  91698. int i, rc = SQLITE_OK;
  91699. DataBuffer doclist, merged, tmp;
  91700. /* Order the readers. */
  91701. i = nReaders;
  91702. while( i-- > 0 ){
  91703. optLeavesReaderReorder(&readers[i], nReaders-i);
  91704. }
  91705. dataBufferInit(&doclist, LEAF_MAX);
  91706. dataBufferInit(&merged, LEAF_MAX);
  91707. /* Exhausted readers bubble to the end, so when the first reader is
  91708. ** at eof, all are at eof.
  91709. */
  91710. while( !optLeavesReaderAtEnd(&readers[0]) ){
  91711. /* Figure out how many readers share the next term. */
  91712. for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
  91713. if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
  91714. }
  91715. /* Special-case for no merge. */
  91716. if( i==1 ){
  91717. /* Trim deletions from the doclist. */
  91718. dataBufferReset(&merged);
  91719. docListTrim(DL_DEFAULT,
  91720. optLeavesReaderData(&readers[0]),
  91721. optLeavesReaderDataBytes(&readers[0]),
  91722. -1, DL_DEFAULT, &merged);
  91723. }else{
  91724. DLReader dlReaders[MERGE_COUNT];
  91725. int iReader, nReaders;
  91726. /* Prime the pipeline with the first reader's doclist. After
  91727. ** one pass index 0 will reference the accumulated doclist.
  91728. */
  91729. dlrInit(&dlReaders[0], DL_DEFAULT,
  91730. optLeavesReaderData(&readers[0]),
  91731. optLeavesReaderDataBytes(&readers[0]));
  91732. iReader = 1;
  91733. assert( iReader<i ); /* Must execute the loop at least once. */
  91734. while( iReader<i ){
  91735. /* Merge 16 inputs per pass. */
  91736. for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
  91737. iReader++, nReaders++ ){
  91738. dlrInit(&dlReaders[nReaders], DL_DEFAULT,
  91739. optLeavesReaderData(&readers[iReader]),
  91740. optLeavesReaderDataBytes(&readers[iReader]));
  91741. }
  91742. /* Merge doclists and swap result into accumulator. */
  91743. dataBufferReset(&merged);
  91744. docListMerge(&merged, dlReaders, nReaders);
  91745. tmp = merged;
  91746. merged = doclist;
  91747. doclist = tmp;
  91748. while( nReaders-- > 0 ){
  91749. dlrDestroy(&dlReaders[nReaders]);
  91750. }
  91751. /* Accumulated doclist to reader 0 for next pass. */
  91752. dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
  91753. }
  91754. /* Destroy reader that was left in the pipeline. */
  91755. dlrDestroy(&dlReaders[0]);
  91756. /* Trim deletions from the doclist. */
  91757. dataBufferReset(&merged);
  91758. docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
  91759. -1, DL_DEFAULT, &merged);
  91760. }
  91761. /* Only pass doclists with hits (skip if all hits deleted). */
  91762. if( merged.nData>0 ){
  91763. rc = leafWriterStep(v, pWriter,
  91764. optLeavesReaderTerm(&readers[0]),
  91765. optLeavesReaderTermBytes(&readers[0]),
  91766. merged.pData, merged.nData);
  91767. if( rc!=SQLITE_OK ) goto err;
  91768. }
  91769. /* Step merged readers to next term and reorder. */
  91770. while( i-- > 0 ){
  91771. rc = optLeavesReaderStep(v, &readers[i]);
  91772. if( rc!=SQLITE_OK ) goto err;
  91773. optLeavesReaderReorder(&readers[i], nReaders-i);
  91774. }
  91775. }
  91776. err:
  91777. dataBufferDestroy(&doclist);
  91778. dataBufferDestroy(&merged);
  91779. return rc;
  91780. }
  91781. /* Implement optimize() function for FTS3. optimize(t) merges all
  91782. ** segments in the fts index into a single segment. 't' is the magic
  91783. ** table-named column.
  91784. */
  91785. static void optimizeFunc(sqlite3_context *pContext,
  91786. int argc, sqlite3_value **argv){
  91787. fulltext_cursor *pCursor;
  91788. if( argc>1 ){
  91789. sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
  91790. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  91791. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  91792. sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
  91793. }else{
  91794. fulltext_vtab *v;
  91795. int i, rc, iMaxLevel;
  91796. OptLeavesReader *readers;
  91797. int nReaders;
  91798. LeafWriter writer;
  91799. sqlite3_stmt *s;
  91800. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  91801. v = cursor_vtab(pCursor);
  91802. /* Flush any buffered updates before optimizing. */
  91803. rc = flushPendingTerms(v);
  91804. if( rc!=SQLITE_OK ) goto err;
  91805. rc = segdir_count(v, &nReaders, &iMaxLevel);
  91806. if( rc!=SQLITE_OK ) goto err;
  91807. if( nReaders==0 || nReaders==1 ){
  91808. sqlite3_result_text(pContext, "Index already optimal", -1,
  91809. SQLITE_STATIC);
  91810. return;
  91811. }
  91812. rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  91813. if( rc!=SQLITE_OK ) goto err;
  91814. readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
  91815. if( readers==NULL ) goto err;
  91816. /* Note that there will already be a segment at this position
  91817. ** until we call segdir_delete() on iMaxLevel.
  91818. */
  91819. leafWriterInit(iMaxLevel, 0, &writer);
  91820. i = 0;
  91821. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  91822. sqlite_int64 iStart = sqlite3_column_int64(s, 0);
  91823. sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
  91824. const char *pRootData = sqlite3_column_blob(s, 2);
  91825. int nRootData = sqlite3_column_bytes(s, 2);
  91826. assert( i<nReaders );
  91827. rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
  91828. &readers[i].reader);
  91829. if( rc!=SQLITE_OK ) break;
  91830. readers[i].segment = i;
  91831. i++;
  91832. }
  91833. /* If we managed to successfully read them all, optimize them. */
  91834. if( rc==SQLITE_DONE ){
  91835. assert( i==nReaders );
  91836. rc = optimizeInternal(v, readers, nReaders, &writer);
  91837. }
  91838. while( i-- > 0 ){
  91839. leavesReaderDestroy(&readers[i].reader);
  91840. }
  91841. sqlite3_free(readers);
  91842. /* If we've successfully gotten to here, delete the old segments
  91843. ** and flush the interior structure of the new segment.
  91844. */
  91845. if( rc==SQLITE_OK ){
  91846. for( i=0; i<=iMaxLevel; i++ ){
  91847. rc = segdir_delete(v, i);
  91848. if( rc!=SQLITE_OK ) break;
  91849. }
  91850. if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
  91851. }
  91852. leafWriterDestroy(&writer);
  91853. if( rc!=SQLITE_OK ) goto err;
  91854. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  91855. return;
  91856. /* TODO(shess): Error-handling needs to be improved along the
  91857. ** lines of the dump_ functions.
  91858. */
  91859. err:
  91860. {
  91861. char buf[512];
  91862. sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
  91863. sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
  91864. sqlite3_result_error(pContext, buf, -1);
  91865. }
  91866. }
  91867. }
  91868. #ifdef SQLITE_TEST
  91869. /* Generate an error of the form "<prefix>: <msg>". If msg is NULL,
  91870. ** pull the error from the context's db handle.
  91871. */
  91872. static void generateError(sqlite3_context *pContext,
  91873. const char *prefix, const char *msg){
  91874. char buf[512];
  91875. if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
  91876. sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
  91877. sqlite3_result_error(pContext, buf, -1);
  91878. }
  91879. /* Helper function to collect the set of terms in the segment into
  91880. ** pTerms. The segment is defined by the leaf nodes between
  91881. ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
  91882. ** pRootData if iStartBlockid is 0 (in which case the entire segment
  91883. ** fit in a leaf).
  91884. */
  91885. static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
  91886. fts3Hash *pTerms){
  91887. const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
  91888. const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
  91889. const char *pRootData = sqlite3_column_blob(s, 2);
  91890. const int nRootData = sqlite3_column_bytes(s, 2);
  91891. LeavesReader reader;
  91892. int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
  91893. pRootData, nRootData, &reader);
  91894. if( rc!=SQLITE_OK ) return rc;
  91895. while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
  91896. const char *pTerm = leavesReaderTerm(&reader);
  91897. const int nTerm = leavesReaderTermBytes(&reader);
  91898. void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
  91899. void *newValue = (void *)((char *)oldValue+1);
  91900. /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
  91901. ** the data value passed is returned in case of malloc failure.
  91902. */
  91903. if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
  91904. rc = SQLITE_NOMEM;
  91905. }else{
  91906. rc = leavesReaderStep(v, &reader);
  91907. }
  91908. }
  91909. leavesReaderDestroy(&reader);
  91910. return rc;
  91911. }
  91912. /* Helper function to build the result string for dump_terms(). */
  91913. static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
  91914. int iTerm, nTerms, nResultBytes, iByte;
  91915. char *result;
  91916. TermData *pData;
  91917. fts3HashElem *e;
  91918. /* Iterate pTerms to generate an array of terms in pData for
  91919. ** sorting.
  91920. */
  91921. nTerms = fts3HashCount(pTerms);
  91922. assert( nTerms>0 );
  91923. pData = sqlite3_malloc(nTerms*sizeof(TermData));
  91924. if( pData==NULL ) return SQLITE_NOMEM;
  91925. nResultBytes = 0;
  91926. for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
  91927. nResultBytes += fts3HashKeysize(e)+1; /* Term plus trailing space */
  91928. assert( iTerm<nTerms );
  91929. pData[iTerm].pTerm = fts3HashKey(e);
  91930. pData[iTerm].nTerm = fts3HashKeysize(e);
  91931. pData[iTerm].pCollector = fts3HashData(e); /* unused */
  91932. }
  91933. assert( iTerm==nTerms );
  91934. assert( nResultBytes>0 ); /* nTerms>0, nResultsBytes must be, too. */
  91935. result = sqlite3_malloc(nResultBytes);
  91936. if( result==NULL ){
  91937. sqlite3_free(pData);
  91938. return SQLITE_NOMEM;
  91939. }
  91940. if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
  91941. /* Read the terms in order to build the result. */
  91942. iByte = 0;
  91943. for(iTerm=0; iTerm<nTerms; ++iTerm){
  91944. memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
  91945. iByte += pData[iTerm].nTerm;
  91946. result[iByte++] = ' ';
  91947. }
  91948. assert( iByte==nResultBytes );
  91949. assert( result[nResultBytes-1]==' ' );
  91950. result[nResultBytes-1] = '\0';
  91951. /* Passes away ownership of result. */
  91952. sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
  91953. sqlite3_free(pData);
  91954. return SQLITE_OK;
  91955. }
  91956. /* Implements dump_terms() for use in inspecting the fts3 index from
  91957. ** tests. TEXT result containing the ordered list of terms joined by
  91958. ** spaces. dump_terms(t, level, idx) dumps the terms for the segment
  91959. ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
  91960. ** all terms in the index. In both cases t is the fts table's magic
  91961. ** table-named column.
  91962. */
  91963. static void dumpTermsFunc(
  91964. sqlite3_context *pContext,
  91965. int argc, sqlite3_value **argv
  91966. ){
  91967. fulltext_cursor *pCursor;
  91968. if( argc!=3 && argc!=1 ){
  91969. generateError(pContext, "dump_terms", "incorrect arguments");
  91970. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  91971. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  91972. generateError(pContext, "dump_terms", "illegal first argument");
  91973. }else{
  91974. fulltext_vtab *v;
  91975. fts3Hash terms;
  91976. sqlite3_stmt *s = NULL;
  91977. int rc;
  91978. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  91979. v = cursor_vtab(pCursor);
  91980. /* If passed only the cursor column, get all segments. Otherwise
  91981. ** get the segment described by the following two arguments.
  91982. */
  91983. if( argc==1 ){
  91984. rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  91985. }else{
  91986. rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
  91987. if( rc==SQLITE_OK ){
  91988. rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
  91989. if( rc==SQLITE_OK ){
  91990. rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
  91991. }
  91992. }
  91993. }
  91994. if( rc!=SQLITE_OK ){
  91995. generateError(pContext, "dump_terms", NULL);
  91996. return;
  91997. }
  91998. /* Collect the terms for each segment. */
  91999. sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
  92000. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  92001. rc = collectSegmentTerms(v, s, &terms);
  92002. if( rc!=SQLITE_OK ) break;
  92003. }
  92004. if( rc!=SQLITE_DONE ){
  92005. sqlite3_reset(s);
  92006. generateError(pContext, "dump_terms", NULL);
  92007. }else{
  92008. const int nTerms = fts3HashCount(&terms);
  92009. if( nTerms>0 ){
  92010. rc = generateTermsResult(pContext, &terms);
  92011. if( rc==SQLITE_NOMEM ){
  92012. generateError(pContext, "dump_terms", "out of memory");
  92013. }else{
  92014. assert( rc==SQLITE_OK );
  92015. }
  92016. }else if( argc==3 ){
  92017. /* The specific segment asked for could not be found. */
  92018. generateError(pContext, "dump_terms", "segment not found");
  92019. }else{
  92020. /* No segments found. */
  92021. /* TODO(shess): It should be impossible to reach this. This
  92022. ** case can only happen for an empty table, in which case
  92023. ** SQLite has no rows to call this function on.
  92024. */
  92025. sqlite3_result_null(pContext);
  92026. }
  92027. }
  92028. sqlite3Fts3HashClear(&terms);
  92029. }
  92030. }
  92031. /* Expand the DL_DEFAULT doclist in pData into a text result in
  92032. ** pContext.
  92033. */
  92034. static void createDoclistResult(sqlite3_context *pContext,
  92035. const char *pData, int nData){
  92036. DataBuffer dump;
  92037. DLReader dlReader;
  92038. assert( pData!=NULL && nData>0 );
  92039. dataBufferInit(&dump, 0);
  92040. dlrInit(&dlReader, DL_DEFAULT, pData, nData);
  92041. for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
  92042. char buf[256];
  92043. PLReader plReader;
  92044. plrInit(&plReader, &dlReader);
  92045. if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
  92046. sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
  92047. dataBufferAppend(&dump, buf, strlen(buf));
  92048. }else{
  92049. int iColumn = plrColumn(&plReader);
  92050. sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
  92051. dlrDocid(&dlReader), iColumn);
  92052. dataBufferAppend(&dump, buf, strlen(buf));
  92053. for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
  92054. if( plrColumn(&plReader)!=iColumn ){
  92055. iColumn = plrColumn(&plReader);
  92056. sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
  92057. assert( dump.nData>0 );
  92058. dump.nData--; /* Overwrite trailing space. */
  92059. assert( dump.pData[dump.nData]==' ');
  92060. dataBufferAppend(&dump, buf, strlen(buf));
  92061. }
  92062. if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
  92063. sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
  92064. plrPosition(&plReader),
  92065. plrStartOffset(&plReader), plrEndOffset(&plReader));
  92066. }else if( DL_DEFAULT==DL_POSITIONS ){
  92067. sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
  92068. }else{
  92069. assert( NULL=="Unhandled DL_DEFAULT value");
  92070. }
  92071. dataBufferAppend(&dump, buf, strlen(buf));
  92072. }
  92073. plrDestroy(&plReader);
  92074. assert( dump.nData>0 );
  92075. dump.nData--; /* Overwrite trailing space. */
  92076. assert( dump.pData[dump.nData]==' ');
  92077. dataBufferAppend(&dump, "]] ", 3);
  92078. }
  92079. }
  92080. dlrDestroy(&dlReader);
  92081. assert( dump.nData>0 );
  92082. dump.nData--; /* Overwrite trailing space. */
  92083. assert( dump.pData[dump.nData]==' ');
  92084. dump.pData[dump.nData] = '\0';
  92085. assert( dump.nData>0 );
  92086. /* Passes ownership of dump's buffer to pContext. */
  92087. sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
  92088. dump.pData = NULL;
  92089. dump.nData = dump.nCapacity = 0;
  92090. }
  92091. /* Implements dump_doclist() for use in inspecting the fts3 index from
  92092. ** tests. TEXT result containing a string representation of the
  92093. ** doclist for the indicated term. dump_doclist(t, term, level, idx)
  92094. ** dumps the doclist for term from the segment specified by level, idx
  92095. ** (in %_segdir), while dump_doclist(t, term) dumps the logical
  92096. ** doclist for the term across all segments. The per-segment doclist
  92097. ** can contain deletions, while the full-index doclist will not
  92098. ** (deletions are omitted).
  92099. **
  92100. ** Result formats differ with the setting of DL_DEFAULTS. Examples:
  92101. **
  92102. ** DL_DOCIDS: [1] [3] [7]
  92103. ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
  92104. ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
  92105. **
  92106. ** In each case the number after the outer '[' is the docid. In the
  92107. ** latter two cases, the number before the inner '[' is the column
  92108. ** associated with the values within. For DL_POSITIONS the numbers
  92109. ** within are the positions, for DL_POSITIONS_OFFSETS they are the
  92110. ** position, the start offset, and the end offset.
  92111. */
  92112. static void dumpDoclistFunc(
  92113. sqlite3_context *pContext,
  92114. int argc, sqlite3_value **argv
  92115. ){
  92116. fulltext_cursor *pCursor;
  92117. if( argc!=2 && argc!=4 ){
  92118. generateError(pContext, "dump_doclist", "incorrect arguments");
  92119. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  92120. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  92121. generateError(pContext, "dump_doclist", "illegal first argument");
  92122. }else if( sqlite3_value_text(argv[1])==NULL ||
  92123. sqlite3_value_text(argv[1])[0]=='\0' ){
  92124. generateError(pContext, "dump_doclist", "empty second argument");
  92125. }else{
  92126. const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
  92127. const int nTerm = strlen(pTerm);
  92128. fulltext_vtab *v;
  92129. int rc;
  92130. DataBuffer doclist;
  92131. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  92132. v = cursor_vtab(pCursor);
  92133. dataBufferInit(&doclist, 0);
  92134. /* termSelect() yields the same logical doclist that queries are
  92135. ** run against.
  92136. */
  92137. if( argc==2 ){
  92138. rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
  92139. }else{
  92140. sqlite3_stmt *s = NULL;
  92141. /* Get our specific segment's information. */
  92142. rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
  92143. if( rc==SQLITE_OK ){
  92144. rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
  92145. if( rc==SQLITE_OK ){
  92146. rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
  92147. }
  92148. }
  92149. if( rc==SQLITE_OK ){
  92150. rc = sqlite3_step(s);
  92151. if( rc==SQLITE_DONE ){
  92152. dataBufferDestroy(&doclist);
  92153. generateError(pContext, "dump_doclist", "segment not found");
  92154. return;
  92155. }
  92156. /* Found a segment, load it into doclist. */
  92157. if( rc==SQLITE_ROW ){
  92158. const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
  92159. const char *pData = sqlite3_column_blob(s, 2);
  92160. const int nData = sqlite3_column_bytes(s, 2);
  92161. /* loadSegment() is used by termSelect() to load each
  92162. ** segment's data.
  92163. */
  92164. rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
  92165. &doclist);
  92166. if( rc==SQLITE_OK ){
  92167. rc = sqlite3_step(s);
  92168. /* Should not have more than one matching segment. */
  92169. if( rc!=SQLITE_DONE ){
  92170. sqlite3_reset(s);
  92171. dataBufferDestroy(&doclist);
  92172. generateError(pContext, "dump_doclist", "invalid segdir");
  92173. return;
  92174. }
  92175. rc = SQLITE_OK;
  92176. }
  92177. }
  92178. }
  92179. sqlite3_reset(s);
  92180. }
  92181. if( rc==SQLITE_OK ){
  92182. if( doclist.nData>0 ){
  92183. createDoclistResult(pContext, doclist.pData, doclist.nData);
  92184. }else{
  92185. /* TODO(shess): This can happen if the term is not present, or
  92186. ** if all instances of the term have been deleted and this is
  92187. ** an all-index dump. It may be interesting to distinguish
  92188. ** these cases.
  92189. */
  92190. sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
  92191. }
  92192. }else if( rc==SQLITE_NOMEM ){
  92193. /* Handle out-of-memory cases specially because if they are
  92194. ** generated in fts3 code they may not be reflected in the db
  92195. ** handle.
  92196. */
  92197. /* TODO(shess): Handle this more comprehensively.
  92198. ** sqlite3ErrStr() has what I need, but is internal.
  92199. */
  92200. generateError(pContext, "dump_doclist", "out of memory");
  92201. }else{
  92202. generateError(pContext, "dump_doclist", NULL);
  92203. }
  92204. dataBufferDestroy(&doclist);
  92205. }
  92206. }
  92207. #endif
  92208. /*
  92209. ** This routine implements the xFindFunction method for the FTS3
  92210. ** virtual table.
  92211. */
  92212. static int fulltextFindFunction(
  92213. sqlite3_vtab *pVtab,
  92214. int nArg,
  92215. const char *zName,
  92216. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  92217. void **ppArg
  92218. ){
  92219. if( strcmp(zName,"snippet")==0 ){
  92220. *pxFunc = snippetFunc;
  92221. return 1;
  92222. }else if( strcmp(zName,"offsets")==0 ){
  92223. *pxFunc = snippetOffsetsFunc;
  92224. return 1;
  92225. }else if( strcmp(zName,"optimize")==0 ){
  92226. *pxFunc = optimizeFunc;
  92227. return 1;
  92228. #ifdef SQLITE_TEST
  92229. /* NOTE(shess): These functions are present only for testing
  92230. ** purposes. No particular effort is made to optimize their
  92231. ** execution or how they build their results.
  92232. */
  92233. }else if( strcmp(zName,"dump_terms")==0 ){
  92234. /* fprintf(stderr, "Found dump_terms\n"); */
  92235. *pxFunc = dumpTermsFunc;
  92236. return 1;
  92237. }else if( strcmp(zName,"dump_doclist")==0 ){
  92238. /* fprintf(stderr, "Found dump_doclist\n"); */
  92239. *pxFunc = dumpDoclistFunc;
  92240. return 1;
  92241. #endif
  92242. }
  92243. return 0;
  92244. }
  92245. /*
  92246. ** Rename an fts3 table.
  92247. */
  92248. static int fulltextRename(
  92249. sqlite3_vtab *pVtab,
  92250. const char *zName
  92251. ){
  92252. fulltext_vtab *p = (fulltext_vtab *)pVtab;
  92253. int rc = SQLITE_NOMEM;
  92254. char *zSql = sqlite3_mprintf(
  92255. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';"
  92256. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
  92257. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';"
  92258. , p->zDb, p->zName, zName
  92259. , p->zDb, p->zName, zName
  92260. , p->zDb, p->zName, zName
  92261. );
  92262. if( zSql ){
  92263. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  92264. sqlite3_free(zSql);
  92265. }
  92266. return rc;
  92267. }
  92268. static const sqlite3_module fts3Module = {
  92269. /* iVersion */ 0,
  92270. /* xCreate */ fulltextCreate,
  92271. /* xConnect */ fulltextConnect,
  92272. /* xBestIndex */ fulltextBestIndex,
  92273. /* xDisconnect */ fulltextDisconnect,
  92274. /* xDestroy */ fulltextDestroy,
  92275. /* xOpen */ fulltextOpen,
  92276. /* xClose */ fulltextClose,
  92277. /* xFilter */ fulltextFilter,
  92278. /* xNext */ fulltextNext,
  92279. /* xEof */ fulltextEof,
  92280. /* xColumn */ fulltextColumn,
  92281. /* xRowid */ fulltextRowid,
  92282. /* xUpdate */ fulltextUpdate,
  92283. /* xBegin */ fulltextBegin,
  92284. /* xSync */ fulltextSync,
  92285. /* xCommit */ fulltextCommit,
  92286. /* xRollback */ fulltextRollback,
  92287. /* xFindFunction */ fulltextFindFunction,
  92288. /* xRename */ fulltextRename,
  92289. };
  92290. static void hashDestroy(void *p){
  92291. fts3Hash *pHash = (fts3Hash *)p;
  92292. sqlite3Fts3HashClear(pHash);
  92293. sqlite3_free(pHash);
  92294. }
  92295. /*
  92296. ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
  92297. ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
  92298. ** two forward declarations are for functions declared in these files
  92299. ** used to retrieve the respective implementations.
  92300. **
  92301. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  92302. ** to by the argument to point a the "simple" tokenizer implementation.
  92303. ** Function ...PorterTokenizerModule() sets *pModule to point to the
  92304. ** porter tokenizer/stemmer implementation.
  92305. */
  92306. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  92307. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  92308. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  92309. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
  92310. /*
  92311. ** Initialise the fts3 extension. If this extension is built as part
  92312. ** of the sqlite library, then this function is called directly by
  92313. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  92314. ** function is called by the sqlite3_extension_init() entry point.
  92315. */
  92316. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  92317. int rc = SQLITE_OK;
  92318. fts3Hash *pHash = 0;
  92319. const sqlite3_tokenizer_module *pSimple = 0;
  92320. const sqlite3_tokenizer_module *pPorter = 0;
  92321. const sqlite3_tokenizer_module *pIcu = 0;
  92322. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  92323. sqlite3Fts3PorterTokenizerModule(&pPorter);
  92324. #ifdef SQLITE_ENABLE_ICU
  92325. sqlite3Fts3IcuTokenizerModule(&pIcu);
  92326. #endif
  92327. /* Allocate and initialise the hash-table used to store tokenizers. */
  92328. pHash = sqlite3_malloc(sizeof(fts3Hash));
  92329. if( !pHash ){
  92330. rc = SQLITE_NOMEM;
  92331. }else{
  92332. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  92333. }
  92334. /* Load the built-in tokenizers into the hash table */
  92335. if( rc==SQLITE_OK ){
  92336. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  92337. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  92338. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  92339. ){
  92340. rc = SQLITE_NOMEM;
  92341. }
  92342. }
  92343. #ifdef SQLITE_TEST
  92344. sqlite3Fts3ExprInitTestInterface(db);
  92345. #endif
  92346. /* Create the virtual table wrapper around the hash-table and overload
  92347. ** the two scalar functions. If this is successful, register the
  92348. ** module with sqlite.
  92349. */
  92350. if( SQLITE_OK==rc
  92351. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  92352. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  92353. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
  92354. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
  92355. #ifdef SQLITE_TEST
  92356. && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
  92357. && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
  92358. #endif
  92359. ){
  92360. return sqlite3_create_module_v2(
  92361. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  92362. );
  92363. }
  92364. /* An error has occurred. Delete the hash table and return the error code. */
  92365. assert( rc!=SQLITE_OK );
  92366. if( pHash ){
  92367. sqlite3Fts3HashClear(pHash);
  92368. sqlite3_free(pHash);
  92369. }
  92370. return rc;
  92371. }
  92372. #if !SQLITE_CORE
  92373. SQLITE_API int sqlite3_extension_init(
  92374. sqlite3 *db,
  92375. char **pzErrMsg,
  92376. const sqlite3_api_routines *pApi
  92377. ){
  92378. SQLITE_EXTENSION_INIT2(pApi)
  92379. return sqlite3Fts3Init(db);
  92380. }
  92381. #endif
  92382. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  92383. /************** End of fts3.c ************************************************/
  92384. /************** Begin file fts3_expr.c ***************************************/
  92385. /*
  92386. ** 2008 Nov 28
  92387. **
  92388. ** The author disclaims copyright to this source code. In place of
  92389. ** a legal notice, here is a blessing:
  92390. **
  92391. ** May you do good and not evil.
  92392. ** May you find forgiveness for yourself and forgive others.
  92393. ** May you share freely, never taking more than you give.
  92394. **
  92395. ******************************************************************************
  92396. **
  92397. ** This module contains code that implements a parser for fts3 query strings
  92398. ** (the right-hand argument to the MATCH operator). Because the supported
  92399. ** syntax is relatively simple, the whole tokenizer/parser system is
  92400. ** hand-coded. The public interface to this module is declared in source
  92401. ** code file "fts3_expr.h".
  92402. */
  92403. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  92404. /*
  92405. ** By default, this module parses the legacy syntax that has been
  92406. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  92407. ** is defined, then it uses the new syntax. The differences between
  92408. ** the new and the old syntaxes are:
  92409. **
  92410. ** a) The new syntax supports parenthesis. The old does not.
  92411. **
  92412. ** b) The new syntax supports the AND and NOT operators. The old does not.
  92413. **
  92414. ** c) The old syntax supports the "-" token qualifier. This is not
  92415. ** supported by the new syntax (it is replaced by the NOT operator).
  92416. **
  92417. ** d) When using the old syntax, the OR operator has a greater precedence
  92418. ** than an implicit AND. When using the new, both implicity and explicit
  92419. ** AND operators have a higher precedence than OR.
  92420. **
  92421. ** If compiled with SQLITE_TEST defined, then this module exports the
  92422. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  92423. ** to zero causes the module to use the old syntax. If it is set to
  92424. ** non-zero the new syntax is activated. This is so both syntaxes can
  92425. ** be tested using a single build of testfixture.
  92426. */
  92427. #ifdef SQLITE_TEST
  92428. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  92429. #else
  92430. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  92431. # define sqlite3_fts3_enable_parentheses 1
  92432. # else
  92433. # define sqlite3_fts3_enable_parentheses 0
  92434. # endif
  92435. #endif
  92436. /*
  92437. ** Default span for NEAR operators.
  92438. */
  92439. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  92440. typedef struct ParseContext ParseContext;
  92441. struct ParseContext {
  92442. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  92443. const char **azCol; /* Array of column names for fts3 table */
  92444. int nCol; /* Number of entries in azCol[] */
  92445. int iDefaultCol; /* Default column to query */
  92446. sqlite3_context *pCtx; /* Write error message here */
  92447. int nNest; /* Number of nested brackets */
  92448. };
  92449. /*
  92450. ** This function is equivalent to the standard isspace() function.
  92451. **
  92452. ** The standard isspace() can be awkward to use safely, because although it
  92453. ** is defined to accept an argument of type int, its behaviour when passed
  92454. ** an integer that falls outside of the range of the unsigned char type
  92455. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  92456. ** is defined to accept an argument of type char, and always returns 0 for
  92457. ** any values that fall outside of the range of the unsigned char type (i.e.
  92458. ** negative values).
  92459. */
  92460. static int fts3isspace(char c){
  92461. return (c&0x80)==0 ? isspace(c) : 0;
  92462. }
  92463. /*
  92464. ** Extract the next token from buffer z (length n) using the tokenizer
  92465. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  92466. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  92467. ** single token and set *ppExpr to point to it. If the end of the buffer is
  92468. ** reached before a token is found, set *ppExpr to zero. It is the
  92469. ** responsibility of the caller to eventually deallocate the allocated
  92470. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  92471. **
  92472. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  92473. ** fails.
  92474. */
  92475. static int getNextToken(
  92476. ParseContext *pParse, /* fts3 query parse context */
  92477. int iCol, /* Value for Fts3Phrase.iColumn */
  92478. const char *z, int n, /* Input string */
  92479. Fts3Expr **ppExpr, /* OUT: expression */
  92480. int *pnConsumed /* OUT: Number of bytes consumed */
  92481. ){
  92482. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  92483. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  92484. int rc;
  92485. sqlite3_tokenizer_cursor *pCursor;
  92486. Fts3Expr *pRet = 0;
  92487. int nConsumed = 0;
  92488. rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
  92489. if( rc==SQLITE_OK ){
  92490. const char *zToken;
  92491. int nToken, iStart, iEnd, iPosition;
  92492. int nByte; /* total space to allocate */
  92493. pCursor->pTokenizer = pTokenizer;
  92494. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  92495. if( rc==SQLITE_OK ){
  92496. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  92497. pRet = (Fts3Expr *)sqlite3_malloc(nByte);
  92498. if( !pRet ){
  92499. rc = SQLITE_NOMEM;
  92500. }else{
  92501. memset(pRet, 0, nByte);
  92502. pRet->eType = FTSQUERY_PHRASE;
  92503. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  92504. pRet->pPhrase->nToken = 1;
  92505. pRet->pPhrase->iColumn = iCol;
  92506. pRet->pPhrase->aToken[0].n = nToken;
  92507. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  92508. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  92509. if( iEnd<n && z[iEnd]=='*' ){
  92510. pRet->pPhrase->aToken[0].isPrefix = 1;
  92511. iEnd++;
  92512. }
  92513. if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
  92514. pRet->pPhrase->isNot = 1;
  92515. }
  92516. }
  92517. nConsumed = iEnd;
  92518. }
  92519. pModule->xClose(pCursor);
  92520. }
  92521. *pnConsumed = nConsumed;
  92522. *ppExpr = pRet;
  92523. return rc;
  92524. }
  92525. /*
  92526. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  92527. ** then free the old allocation.
  92528. */
  92529. void *fts3ReallocOrFree(void *pOrig, int nNew){
  92530. void *pRet = sqlite3_realloc(pOrig, nNew);
  92531. if( !pRet ){
  92532. sqlite3_free(pOrig);
  92533. }
  92534. return pRet;
  92535. }
  92536. /*
  92537. ** Buffer zInput, length nInput, contains the contents of a quoted string
  92538. ** that appeared as part of an fts3 query expression. Neither quote character
  92539. ** is included in the buffer. This function attempts to tokenize the entire
  92540. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  92541. ** containing the results.
  92542. **
  92543. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  92544. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  92545. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  92546. ** to 0.
  92547. */
  92548. static int getNextString(
  92549. ParseContext *pParse, /* fts3 query parse context */
  92550. const char *zInput, int nInput, /* Input string */
  92551. Fts3Expr **ppExpr /* OUT: expression */
  92552. ){
  92553. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  92554. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  92555. int rc;
  92556. Fts3Expr *p = 0;
  92557. sqlite3_tokenizer_cursor *pCursor = 0;
  92558. char *zTemp = 0;
  92559. int nTemp = 0;
  92560. rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
  92561. if( rc==SQLITE_OK ){
  92562. int ii;
  92563. pCursor->pTokenizer = pTokenizer;
  92564. for(ii=0; rc==SQLITE_OK; ii++){
  92565. const char *zToken;
  92566. int nToken, iBegin, iEnd, iPos;
  92567. rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
  92568. if( rc==SQLITE_OK ){
  92569. int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  92570. p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
  92571. zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
  92572. if( !p || !zTemp ){
  92573. goto no_mem;
  92574. }
  92575. if( ii==0 ){
  92576. memset(p, 0, nByte);
  92577. p->pPhrase = (Fts3Phrase *)&p[1];
  92578. }
  92579. p->pPhrase = (Fts3Phrase *)&p[1];
  92580. p->pPhrase->nToken = ii+1;
  92581. p->pPhrase->aToken[ii].n = nToken;
  92582. memcpy(&zTemp[nTemp], zToken, nToken);
  92583. nTemp += nToken;
  92584. if( iEnd<nInput && zInput[iEnd]=='*' ){
  92585. p->pPhrase->aToken[ii].isPrefix = 1;
  92586. }else{
  92587. p->pPhrase->aToken[ii].isPrefix = 0;
  92588. }
  92589. }
  92590. }
  92591. pModule->xClose(pCursor);
  92592. pCursor = 0;
  92593. }
  92594. if( rc==SQLITE_DONE ){
  92595. int jj;
  92596. char *zNew;
  92597. int nNew = 0;
  92598. int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  92599. nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
  92600. p = fts3ReallocOrFree(p, nByte + nTemp);
  92601. if( !p ){
  92602. goto no_mem;
  92603. }
  92604. if( zTemp ){
  92605. zNew = &(((char *)p)[nByte]);
  92606. memcpy(zNew, zTemp, nTemp);
  92607. }else{
  92608. memset(p, 0, nByte+nTemp);
  92609. }
  92610. p->pPhrase = (Fts3Phrase *)&p[1];
  92611. for(jj=0; jj<p->pPhrase->nToken; jj++){
  92612. p->pPhrase->aToken[jj].z = &zNew[nNew];
  92613. nNew += p->pPhrase->aToken[jj].n;
  92614. }
  92615. sqlite3_free(zTemp);
  92616. p->eType = FTSQUERY_PHRASE;
  92617. p->pPhrase->iColumn = pParse->iDefaultCol;
  92618. rc = SQLITE_OK;
  92619. }
  92620. *ppExpr = p;
  92621. return rc;
  92622. no_mem:
  92623. if( pCursor ){
  92624. pModule->xClose(pCursor);
  92625. }
  92626. sqlite3_free(zTemp);
  92627. sqlite3_free(p);
  92628. *ppExpr = 0;
  92629. return SQLITE_NOMEM;
  92630. }
  92631. /*
  92632. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  92633. ** call fts3ExprParse(). So this forward declaration is required.
  92634. */
  92635. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  92636. /*
  92637. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  92638. ** structure, or set to 0 if the end of the input buffer is reached.
  92639. **
  92640. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  92641. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  92642. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  92643. */
  92644. static int getNextNode(
  92645. ParseContext *pParse, /* fts3 query parse context */
  92646. const char *z, int n, /* Input string */
  92647. Fts3Expr **ppExpr, /* OUT: expression */
  92648. int *pnConsumed /* OUT: Number of bytes consumed */
  92649. ){
  92650. static const struct Fts3Keyword {
  92651. char z[4]; /* Keyword text */
  92652. unsigned char n; /* Length of the keyword */
  92653. unsigned char parenOnly; /* Only valid in paren mode */
  92654. unsigned char eType; /* Keyword code */
  92655. } aKeyword[] = {
  92656. { "OR" , 2, 0, FTSQUERY_OR },
  92657. { "AND", 3, 1, FTSQUERY_AND },
  92658. { "NOT", 3, 1, FTSQUERY_NOT },
  92659. { "NEAR", 4, 0, FTSQUERY_NEAR }
  92660. };
  92661. int ii;
  92662. int iCol;
  92663. int iColLen;
  92664. int rc;
  92665. Fts3Expr *pRet = 0;
  92666. const char *zInput = z;
  92667. int nInput = n;
  92668. /* Skip over any whitespace before checking for a keyword, an open or
  92669. ** close bracket, or a quoted string.
  92670. */
  92671. while( nInput>0 && fts3isspace(*zInput) ){
  92672. nInput--;
  92673. zInput++;
  92674. }
  92675. if( nInput==0 ){
  92676. return SQLITE_DONE;
  92677. }
  92678. /* See if we are dealing with a keyword. */
  92679. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  92680. const struct Fts3Keyword *pKey = &aKeyword[ii];
  92681. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  92682. continue;
  92683. }
  92684. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  92685. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  92686. int nKey = pKey->n;
  92687. char cNext;
  92688. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  92689. if( pKey->eType==FTSQUERY_NEAR ){
  92690. assert( nKey==4 );
  92691. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  92692. nNear = 0;
  92693. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  92694. nNear = nNear * 10 + (zInput[nKey] - '0');
  92695. }
  92696. }
  92697. }
  92698. /* At this point this is probably a keyword. But for that to be true,
  92699. ** the next byte must contain either whitespace, an open or close
  92700. ** parenthesis, a quote character, or EOF.
  92701. */
  92702. cNext = zInput[nKey];
  92703. if( fts3isspace(cNext)
  92704. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  92705. ){
  92706. pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
  92707. memset(pRet, 0, sizeof(Fts3Expr));
  92708. pRet->eType = pKey->eType;
  92709. pRet->nNear = nNear;
  92710. *ppExpr = pRet;
  92711. *pnConsumed = (zInput - z) + nKey;
  92712. return SQLITE_OK;
  92713. }
  92714. /* Turns out that wasn't a keyword after all. This happens if the
  92715. ** user has supplied a token such as "ORacle". Continue.
  92716. */
  92717. }
  92718. }
  92719. /* Check for an open bracket. */
  92720. if( sqlite3_fts3_enable_parentheses ){
  92721. if( *zInput=='(' ){
  92722. int nConsumed;
  92723. int rc;
  92724. pParse->nNest++;
  92725. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  92726. if( rc==SQLITE_OK && !*ppExpr ){
  92727. rc = SQLITE_DONE;
  92728. }
  92729. *pnConsumed = (zInput - z) + 1 + nConsumed;
  92730. return rc;
  92731. }
  92732. /* Check for a close bracket. */
  92733. if( *zInput==')' ){
  92734. pParse->nNest--;
  92735. *pnConsumed = (zInput - z) + 1;
  92736. return SQLITE_DONE;
  92737. }
  92738. }
  92739. /* See if we are dealing with a quoted phrase. If this is the case, then
  92740. ** search for the closing quote and pass the whole string to getNextString()
  92741. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  92742. ** a quote character embedded in a string.
  92743. */
  92744. if( *zInput=='"' ){
  92745. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  92746. *pnConsumed = (zInput - z) + ii + 1;
  92747. if( ii==nInput ){
  92748. return SQLITE_ERROR;
  92749. }
  92750. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  92751. }
  92752. /* If control flows to this point, this must be a regular token, or
  92753. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  92754. ** interface. Before doing so, figure out if there is an explicit
  92755. ** column specifier for the token.
  92756. **
  92757. ** TODO: Strangely, it is not possible to associate a column specifier
  92758. ** with a quoted phrase, only with a single token. Not sure if this was
  92759. ** an implementation artifact or an intentional decision when fts3 was
  92760. ** first implemented. Whichever it was, this module duplicates the
  92761. ** limitation.
  92762. */
  92763. iCol = pParse->iDefaultCol;
  92764. iColLen = 0;
  92765. for(ii=0; ii<pParse->nCol; ii++){
  92766. const char *zStr = pParse->azCol[ii];
  92767. int nStr = strlen(zStr);
  92768. if( nInput>nStr && zInput[nStr]==':' && memcmp(zStr, zInput, nStr)==0 ){
  92769. iCol = ii;
  92770. iColLen = ((zInput - z) + nStr + 1);
  92771. break;
  92772. }
  92773. }
  92774. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  92775. *pnConsumed += iColLen;
  92776. return rc;
  92777. }
  92778. /*
  92779. ** The argument is an Fts3Expr structure for a binary operator (any type
  92780. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  92781. ** precedence of the operator. Lower values have a higher precedence (i.e.
  92782. ** group more tightly). For example, in the C language, the == operator
  92783. ** groups more tightly than ||, and would therefore have a higher precedence.
  92784. **
  92785. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  92786. ** is defined), the order of the operators in precedence from highest to
  92787. ** lowest is:
  92788. **
  92789. ** NEAR
  92790. ** NOT
  92791. ** AND (including implicit ANDs)
  92792. ** OR
  92793. **
  92794. ** Note that when using the old query syntax, the OR operator has a higher
  92795. ** precedence than the AND operator.
  92796. */
  92797. static int opPrecedence(Fts3Expr *p){
  92798. assert( p->eType!=FTSQUERY_PHRASE );
  92799. if( sqlite3_fts3_enable_parentheses ){
  92800. return p->eType;
  92801. }else if( p->eType==FTSQUERY_NEAR ){
  92802. return 1;
  92803. }else if( p->eType==FTSQUERY_OR ){
  92804. return 2;
  92805. }
  92806. assert( p->eType==FTSQUERY_AND );
  92807. return 3;
  92808. }
  92809. /*
  92810. ** Argument ppHead contains a pointer to the current head of a query
  92811. ** expression tree being parsed. pPrev is the expression node most recently
  92812. ** inserted into the tree. This function adds pNew, which is always a binary
  92813. ** operator node, into the expression tree based on the relative precedence
  92814. ** of pNew and the existing nodes of the tree. This may result in the head
  92815. ** of the tree changing, in which case *ppHead is set to the new root node.
  92816. */
  92817. static void insertBinaryOperator(
  92818. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  92819. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  92820. Fts3Expr *pNew /* New binary node to insert into expression tree */
  92821. ){
  92822. Fts3Expr *pSplit = pPrev;
  92823. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  92824. pSplit = pSplit->pParent;
  92825. }
  92826. if( pSplit->pParent ){
  92827. assert( pSplit->pParent->pRight==pSplit );
  92828. pSplit->pParent->pRight = pNew;
  92829. pNew->pParent = pSplit->pParent;
  92830. }else{
  92831. *ppHead = pNew;
  92832. }
  92833. pNew->pLeft = pSplit;
  92834. pSplit->pParent = pNew;
  92835. }
  92836. /*
  92837. ** Parse the fts3 query expression found in buffer z, length n. This function
  92838. ** returns either when the end of the buffer is reached or an unmatched
  92839. ** closing bracket - ')' - is encountered.
  92840. **
  92841. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  92842. ** parsed form of the expression and *pnConsumed is set to the number of
  92843. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  92844. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  92845. */
  92846. static int fts3ExprParse(
  92847. ParseContext *pParse, /* fts3 query parse context */
  92848. const char *z, int n, /* Text of MATCH query */
  92849. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  92850. int *pnConsumed /* OUT: Number of bytes consumed */
  92851. ){
  92852. Fts3Expr *pRet = 0;
  92853. Fts3Expr *pPrev = 0;
  92854. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  92855. int nIn = n;
  92856. const char *zIn = z;
  92857. int rc = SQLITE_OK;
  92858. int isRequirePhrase = 1;
  92859. while( rc==SQLITE_OK ){
  92860. Fts3Expr *p = 0;
  92861. int nByte = 0;
  92862. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  92863. if( rc==SQLITE_OK ){
  92864. int isPhrase;
  92865. if( !sqlite3_fts3_enable_parentheses
  92866. && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
  92867. ){
  92868. /* Create an implicit NOT operator. */
  92869. Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
  92870. if( !pNot ){
  92871. sqlite3Fts3ExprFree(p);
  92872. rc = SQLITE_NOMEM;
  92873. goto exprparse_out;
  92874. }
  92875. memset(pNot, 0, sizeof(Fts3Expr));
  92876. pNot->eType = FTSQUERY_NOT;
  92877. pNot->pRight = p;
  92878. if( pNotBranch ){
  92879. pNotBranch->pLeft = p;
  92880. pNot->pRight = pNotBranch;
  92881. }
  92882. pNotBranch = pNot;
  92883. }else{
  92884. int eType = p->eType;
  92885. assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
  92886. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  92887. /* The isRequirePhrase variable is set to true if a phrase or
  92888. ** an expression contained in parenthesis is required. If a
  92889. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  92890. ** isRequirePhrase is set, this is a syntax error.
  92891. */
  92892. if( !isPhrase && isRequirePhrase ){
  92893. sqlite3Fts3ExprFree(p);
  92894. rc = SQLITE_ERROR;
  92895. goto exprparse_out;
  92896. }
  92897. if( isPhrase && !isRequirePhrase ){
  92898. /* Insert an implicit AND operator. */
  92899. Fts3Expr *pAnd;
  92900. assert( pRet && pPrev );
  92901. pAnd = sqlite3_malloc(sizeof(Fts3Expr));
  92902. if( !pAnd ){
  92903. sqlite3Fts3ExprFree(p);
  92904. rc = SQLITE_NOMEM;
  92905. goto exprparse_out;
  92906. }
  92907. memset(pAnd, 0, sizeof(Fts3Expr));
  92908. pAnd->eType = FTSQUERY_AND;
  92909. insertBinaryOperator(&pRet, pPrev, pAnd);
  92910. pPrev = pAnd;
  92911. }
  92912. /* This test catches attempts to make either operand of a NEAR
  92913. ** operator something other than a phrase. For example, either of
  92914. ** the following:
  92915. **
  92916. ** (bracketed expression) NEAR phrase
  92917. ** phrase NEAR (bracketed expression)
  92918. **
  92919. ** Return an error in either case.
  92920. */
  92921. if( pPrev && (
  92922. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  92923. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  92924. )){
  92925. sqlite3Fts3ExprFree(p);
  92926. rc = SQLITE_ERROR;
  92927. goto exprparse_out;
  92928. }
  92929. if( isPhrase ){
  92930. if( pRet ){
  92931. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  92932. pPrev->pRight = p;
  92933. p->pParent = pPrev;
  92934. }else{
  92935. pRet = p;
  92936. }
  92937. }else{
  92938. insertBinaryOperator(&pRet, pPrev, p);
  92939. }
  92940. isRequirePhrase = !isPhrase;
  92941. }
  92942. assert( nByte>0 );
  92943. }
  92944. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  92945. nIn -= nByte;
  92946. zIn += nByte;
  92947. pPrev = p;
  92948. }
  92949. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  92950. rc = SQLITE_ERROR;
  92951. }
  92952. if( rc==SQLITE_DONE ){
  92953. rc = SQLITE_OK;
  92954. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  92955. if( !pRet ){
  92956. rc = SQLITE_ERROR;
  92957. }else{
  92958. pNotBranch->pLeft = pRet;
  92959. pRet = pNotBranch;
  92960. }
  92961. }
  92962. }
  92963. *pnConsumed = n - nIn;
  92964. exprparse_out:
  92965. if( rc!=SQLITE_OK ){
  92966. sqlite3Fts3ExprFree(pRet);
  92967. sqlite3Fts3ExprFree(pNotBranch);
  92968. pRet = 0;
  92969. }
  92970. *ppExpr = pRet;
  92971. return rc;
  92972. }
  92973. /*
  92974. ** Parameters z and n contain a pointer to and length of a buffer containing
  92975. ** an fts3 query expression, respectively. This function attempts to parse the
  92976. ** query expression and create a tree of Fts3Expr structures representing the
  92977. ** parsed expression. If successful, *ppExpr is set to point to the head
  92978. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  92979. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  92980. ** error) is returned and *ppExpr is set to 0.
  92981. **
  92982. ** If parameter n is a negative number, then z is assumed to point to a
  92983. ** nul-terminated string and the length is determined using strlen().
  92984. **
  92985. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  92986. ** use to normalize query tokens while parsing the expression. The azCol[]
  92987. ** array, which is assumed to contain nCol entries, should contain the names
  92988. ** of each column in the target fts3 table, in order from left to right.
  92989. ** Column names must be nul-terminated strings.
  92990. **
  92991. ** The iDefaultCol parameter should be passed the index of the table column
  92992. ** that appears on the left-hand-side of the MATCH operator (the default
  92993. ** column to match against for tokens for which a column name is not explicitly
  92994. ** specified as part of the query string), or -1 if tokens may by default
  92995. ** match any table column.
  92996. */
  92997. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  92998. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  92999. char **azCol, /* Array of column names for fts3 table */
  93000. int nCol, /* Number of entries in azCol[] */
  93001. int iDefaultCol, /* Default column to query */
  93002. const char *z, int n, /* Text of MATCH query */
  93003. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  93004. ){
  93005. int nParsed;
  93006. int rc;
  93007. ParseContext sParse;
  93008. sParse.pTokenizer = pTokenizer;
  93009. sParse.azCol = (const char **)azCol;
  93010. sParse.nCol = nCol;
  93011. sParse.iDefaultCol = iDefaultCol;
  93012. sParse.nNest = 0;
  93013. if( z==0 ){
  93014. *ppExpr = 0;
  93015. return SQLITE_OK;
  93016. }
  93017. if( n<0 ){
  93018. n = strlen(z);
  93019. }
  93020. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  93021. /* Check for mismatched parenthesis */
  93022. if( rc==SQLITE_OK && sParse.nNest ){
  93023. rc = SQLITE_ERROR;
  93024. sqlite3Fts3ExprFree(*ppExpr);
  93025. *ppExpr = 0;
  93026. }
  93027. return rc;
  93028. }
  93029. /*
  93030. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  93031. */
  93032. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
  93033. if( p ){
  93034. sqlite3Fts3ExprFree(p->pLeft);
  93035. sqlite3Fts3ExprFree(p->pRight);
  93036. sqlite3_free(p);
  93037. }
  93038. }
  93039. /****************************************************************************
  93040. *****************************************************************************
  93041. ** Everything after this point is just test code.
  93042. */
  93043. #ifdef SQLITE_TEST
  93044. /*
  93045. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  93046. */
  93047. static int queryTestTokenizer(
  93048. sqlite3 *db,
  93049. const char *zName,
  93050. const sqlite3_tokenizer_module **pp
  93051. ){
  93052. int rc;
  93053. sqlite3_stmt *pStmt;
  93054. const char zSql[] = "SELECT fts3_tokenizer(?)";
  93055. *pp = 0;
  93056. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  93057. if( rc!=SQLITE_OK ){
  93058. return rc;
  93059. }
  93060. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  93061. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  93062. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  93063. memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  93064. }
  93065. }
  93066. return sqlite3_finalize(pStmt);
  93067. }
  93068. /*
  93069. ** This function is part of the test interface for the query parser. It
  93070. ** writes a text representation of the query expression pExpr into the
  93071. ** buffer pointed to by argument zBuf. It is assumed that zBuf is large
  93072. ** enough to store the required text representation.
  93073. */
  93074. static void exprToString(Fts3Expr *pExpr, char *zBuf){
  93075. switch( pExpr->eType ){
  93076. case FTSQUERY_PHRASE: {
  93077. Fts3Phrase *pPhrase = pExpr->pPhrase;
  93078. int i;
  93079. zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
  93080. for(i=0; i<pPhrase->nToken; i++){
  93081. zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
  93082. zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
  93083. }
  93084. return;
  93085. }
  93086. case FTSQUERY_NEAR:
  93087. zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
  93088. break;
  93089. case FTSQUERY_NOT:
  93090. zBuf += sprintf(zBuf, "NOT ");
  93091. break;
  93092. case FTSQUERY_AND:
  93093. zBuf += sprintf(zBuf, "AND ");
  93094. break;
  93095. case FTSQUERY_OR:
  93096. zBuf += sprintf(zBuf, "OR ");
  93097. break;
  93098. }
  93099. zBuf += sprintf(zBuf, "{");
  93100. exprToString(pExpr->pLeft, zBuf);
  93101. zBuf += strlen(zBuf);
  93102. zBuf += sprintf(zBuf, "} ");
  93103. zBuf += sprintf(zBuf, "{");
  93104. exprToString(pExpr->pRight, zBuf);
  93105. zBuf += strlen(zBuf);
  93106. zBuf += sprintf(zBuf, "}");
  93107. }
  93108. /*
  93109. ** This is the implementation of a scalar SQL function used to test the
  93110. ** expression parser. It should be called as follows:
  93111. **
  93112. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  93113. **
  93114. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  93115. ** to parse the query expression (see README.tokenizers). The second argument
  93116. ** is the query expression to parse. Each subsequent argument is the name
  93117. ** of a column of the fts3 table that the query expression may refer to.
  93118. ** For example:
  93119. **
  93120. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  93121. */
  93122. static void fts3ExprTest(
  93123. sqlite3_context *context,
  93124. int argc,
  93125. sqlite3_value **argv
  93126. ){
  93127. sqlite3_tokenizer_module const *pModule = 0;
  93128. sqlite3_tokenizer *pTokenizer = 0;
  93129. int rc;
  93130. char **azCol = 0;
  93131. const char *zExpr;
  93132. int nExpr;
  93133. int nCol;
  93134. int ii;
  93135. Fts3Expr *pExpr;
  93136. sqlite3 *db = sqlite3_context_db_handle(context);
  93137. if( argc<3 ){
  93138. sqlite3_result_error(context,
  93139. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  93140. );
  93141. return;
  93142. }
  93143. rc = queryTestTokenizer(db,
  93144. (const char *)sqlite3_value_text(argv[0]), &pModule);
  93145. if( rc==SQLITE_NOMEM ){
  93146. sqlite3_result_error_nomem(context);
  93147. goto exprtest_out;
  93148. }else if( !pModule ){
  93149. sqlite3_result_error(context, "No such tokenizer module", -1);
  93150. goto exprtest_out;
  93151. }
  93152. rc = pModule->xCreate(0, 0, &pTokenizer);
  93153. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  93154. if( rc==SQLITE_NOMEM ){
  93155. sqlite3_result_error_nomem(context);
  93156. goto exprtest_out;
  93157. }
  93158. pTokenizer->pModule = pModule;
  93159. zExpr = (const char *)sqlite3_value_text(argv[1]);
  93160. nExpr = sqlite3_value_bytes(argv[1]);
  93161. nCol = argc-2;
  93162. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  93163. if( !azCol ){
  93164. sqlite3_result_error_nomem(context);
  93165. goto exprtest_out;
  93166. }
  93167. for(ii=0; ii<nCol; ii++){
  93168. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  93169. }
  93170. rc = sqlite3Fts3ExprParse(
  93171. pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
  93172. );
  93173. if( rc==SQLITE_NOMEM ){
  93174. sqlite3_result_error_nomem(context);
  93175. goto exprtest_out;
  93176. }else if( rc==SQLITE_OK ){
  93177. char zBuf[4096];
  93178. exprToString(pExpr, zBuf);
  93179. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  93180. sqlite3Fts3ExprFree(pExpr);
  93181. }else{
  93182. sqlite3_result_error(context, "Error parsing expression", -1);
  93183. }
  93184. exprtest_out:
  93185. if( pModule && pTokenizer ){
  93186. rc = pModule->xDestroy(pTokenizer);
  93187. }
  93188. sqlite3_free(azCol);
  93189. }
  93190. /*
  93191. ** Register the query expression parser test function fts3_exprtest()
  93192. ** with database connection db.
  93193. */
  93194. SQLITE_PRIVATE void sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  93195. sqlite3_create_function(
  93196. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  93197. );
  93198. }
  93199. #endif
  93200. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  93201. /************** End of fts3_expr.c *******************************************/
  93202. /************** Begin file fts3_hash.c ***************************************/
  93203. /*
  93204. ** 2001 September 22
  93205. **
  93206. ** The author disclaims copyright to this source code. In place of
  93207. ** a legal notice, here is a blessing:
  93208. **
  93209. ** May you do good and not evil.
  93210. ** May you find forgiveness for yourself and forgive others.
  93211. ** May you share freely, never taking more than you give.
  93212. **
  93213. *************************************************************************
  93214. ** This is the implementation of generic hash-tables used in SQLite.
  93215. ** We've modified it slightly to serve as a standalone hash table
  93216. ** implementation for the full-text indexing module.
  93217. */
  93218. /*
  93219. ** The code in this file is only compiled if:
  93220. **
  93221. ** * The FTS3 module is being built as an extension
  93222. ** (in which case SQLITE_CORE is not defined), or
  93223. **
  93224. ** * The FTS3 module is being built into the core of
  93225. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  93226. */
  93227. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  93228. /*
  93229. ** Malloc and Free functions
  93230. */
  93231. static void *fts3HashMalloc(int n){
  93232. void *p = sqlite3_malloc(n);
  93233. if( p ){
  93234. memset(p, 0, n);
  93235. }
  93236. return p;
  93237. }
  93238. static void fts3HashFree(void *p){
  93239. sqlite3_free(p);
  93240. }
  93241. /* Turn bulk memory into a hash table object by initializing the
  93242. ** fields of the Hash structure.
  93243. **
  93244. ** "pNew" is a pointer to the hash table that is to be initialized.
  93245. ** keyClass is one of the constants
  93246. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  93247. ** determines what kind of key the hash table will use. "copyKey" is
  93248. ** true if the hash table should make its own private copy of keys and
  93249. ** false if it should just use the supplied pointer.
  93250. */
  93251. SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
  93252. assert( pNew!=0 );
  93253. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  93254. pNew->keyClass = keyClass;
  93255. pNew->copyKey = copyKey;
  93256. pNew->first = 0;
  93257. pNew->count = 0;
  93258. pNew->htsize = 0;
  93259. pNew->ht = 0;
  93260. }
  93261. /* Remove all entries from a hash table. Reclaim all memory.
  93262. ** Call this routine to delete a hash table or to reset a hash table
  93263. ** to the empty state.
  93264. */
  93265. SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
  93266. fts3HashElem *elem; /* For looping over all elements of the table */
  93267. assert( pH!=0 );
  93268. elem = pH->first;
  93269. pH->first = 0;
  93270. fts3HashFree(pH->ht);
  93271. pH->ht = 0;
  93272. pH->htsize = 0;
  93273. while( elem ){
  93274. fts3HashElem *next_elem = elem->next;
  93275. if( pH->copyKey && elem->pKey ){
  93276. fts3HashFree(elem->pKey);
  93277. }
  93278. fts3HashFree(elem);
  93279. elem = next_elem;
  93280. }
  93281. pH->count = 0;
  93282. }
  93283. /*
  93284. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  93285. */
  93286. static int fts3StrHash(const void *pKey, int nKey){
  93287. const char *z = (const char *)pKey;
  93288. int h = 0;
  93289. if( nKey<=0 ) nKey = (int) strlen(z);
  93290. while( nKey > 0 ){
  93291. h = (h<<3) ^ h ^ *z++;
  93292. nKey--;
  93293. }
  93294. return h & 0x7fffffff;
  93295. }
  93296. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  93297. if( n1!=n2 ) return 1;
  93298. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  93299. }
  93300. /*
  93301. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  93302. */
  93303. static int fts3BinHash(const void *pKey, int nKey){
  93304. int h = 0;
  93305. const char *z = (const char *)pKey;
  93306. while( nKey-- > 0 ){
  93307. h = (h<<3) ^ h ^ *(z++);
  93308. }
  93309. return h & 0x7fffffff;
  93310. }
  93311. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  93312. if( n1!=n2 ) return 1;
  93313. return memcmp(pKey1,pKey2,n1);
  93314. }
  93315. /*
  93316. ** Return a pointer to the appropriate hash function given the key class.
  93317. **
  93318. ** The C syntax in this function definition may be unfamilar to some
  93319. ** programmers, so we provide the following additional explanation:
  93320. **
  93321. ** The name of the function is "ftsHashFunction". The function takes a
  93322. ** single parameter "keyClass". The return value of ftsHashFunction()
  93323. ** is a pointer to another function. Specifically, the return value
  93324. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  93325. ** with types "const void*" and "int" and returns an "int".
  93326. */
  93327. static int (*ftsHashFunction(int keyClass))(const void*,int){
  93328. if( keyClass==FTS3_HASH_STRING ){
  93329. return &fts3StrHash;
  93330. }else{
  93331. assert( keyClass==FTS3_HASH_BINARY );
  93332. return &fts3BinHash;
  93333. }
  93334. }
  93335. /*
  93336. ** Return a pointer to the appropriate hash function given the key class.
  93337. **
  93338. ** For help in interpreted the obscure C code in the function definition,
  93339. ** see the header comment on the previous function.
  93340. */
  93341. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  93342. if( keyClass==FTS3_HASH_STRING ){
  93343. return &fts3StrCompare;
  93344. }else{
  93345. assert( keyClass==FTS3_HASH_BINARY );
  93346. return &fts3BinCompare;
  93347. }
  93348. }
  93349. /* Link an element into the hash table
  93350. */
  93351. static void fts3HashInsertElement(
  93352. fts3Hash *pH, /* The complete hash table */
  93353. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  93354. fts3HashElem *pNew /* The element to be inserted */
  93355. ){
  93356. fts3HashElem *pHead; /* First element already in pEntry */
  93357. pHead = pEntry->chain;
  93358. if( pHead ){
  93359. pNew->next = pHead;
  93360. pNew->prev = pHead->prev;
  93361. if( pHead->prev ){ pHead->prev->next = pNew; }
  93362. else { pH->first = pNew; }
  93363. pHead->prev = pNew;
  93364. }else{
  93365. pNew->next = pH->first;
  93366. if( pH->first ){ pH->first->prev = pNew; }
  93367. pNew->prev = 0;
  93368. pH->first = pNew;
  93369. }
  93370. pEntry->count++;
  93371. pEntry->chain = pNew;
  93372. }
  93373. /* Resize the hash table so that it cantains "new_size" buckets.
  93374. ** "new_size" must be a power of 2. The hash table might fail
  93375. ** to resize if sqliteMalloc() fails.
  93376. */
  93377. static void fts3Rehash(fts3Hash *pH, int new_size){
  93378. struct _fts3ht *new_ht; /* The new hash table */
  93379. fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  93380. int (*xHash)(const void*,int); /* The hash function */
  93381. assert( (new_size & (new_size-1))==0 );
  93382. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  93383. if( new_ht==0 ) return;
  93384. fts3HashFree(pH->ht);
  93385. pH->ht = new_ht;
  93386. pH->htsize = new_size;
  93387. xHash = ftsHashFunction(pH->keyClass);
  93388. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  93389. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  93390. next_elem = elem->next;
  93391. fts3HashInsertElement(pH, &new_ht[h], elem);
  93392. }
  93393. }
  93394. /* This function (for internal use only) locates an element in an
  93395. ** hash table that matches the given key. The hash for this key has
  93396. ** already been computed and is passed as the 4th parameter.
  93397. */
  93398. static fts3HashElem *fts3FindElementByHash(
  93399. const fts3Hash *pH, /* The pH to be searched */
  93400. const void *pKey, /* The key we are searching for */
  93401. int nKey,
  93402. int h /* The hash for this key. */
  93403. ){
  93404. fts3HashElem *elem; /* Used to loop thru the element list */
  93405. int count; /* Number of elements left to test */
  93406. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  93407. if( pH->ht ){
  93408. struct _fts3ht *pEntry = &pH->ht[h];
  93409. elem = pEntry->chain;
  93410. count = pEntry->count;
  93411. xCompare = ftsCompareFunction(pH->keyClass);
  93412. while( count-- && elem ){
  93413. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  93414. return elem;
  93415. }
  93416. elem = elem->next;
  93417. }
  93418. }
  93419. return 0;
  93420. }
  93421. /* Remove a single entry from the hash table given a pointer to that
  93422. ** element and a hash on the element's key.
  93423. */
  93424. static void fts3RemoveElementByHash(
  93425. fts3Hash *pH, /* The pH containing "elem" */
  93426. fts3HashElem* elem, /* The element to be removed from the pH */
  93427. int h /* Hash value for the element */
  93428. ){
  93429. struct _fts3ht *pEntry;
  93430. if( elem->prev ){
  93431. elem->prev->next = elem->next;
  93432. }else{
  93433. pH->first = elem->next;
  93434. }
  93435. if( elem->next ){
  93436. elem->next->prev = elem->prev;
  93437. }
  93438. pEntry = &pH->ht[h];
  93439. if( pEntry->chain==elem ){
  93440. pEntry->chain = elem->next;
  93441. }
  93442. pEntry->count--;
  93443. if( pEntry->count<=0 ){
  93444. pEntry->chain = 0;
  93445. }
  93446. if( pH->copyKey && elem->pKey ){
  93447. fts3HashFree(elem->pKey);
  93448. }
  93449. fts3HashFree( elem );
  93450. pH->count--;
  93451. if( pH->count<=0 ){
  93452. assert( pH->first==0 );
  93453. assert( pH->count==0 );
  93454. fts3HashClear(pH);
  93455. }
  93456. }
  93457. /* Attempt to locate an element of the hash table pH with a key
  93458. ** that matches pKey,nKey. Return the data for this element if it is
  93459. ** found, or NULL if there is no match.
  93460. */
  93461. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
  93462. int h; /* A hash on key */
  93463. fts3HashElem *elem; /* The element that matches key */
  93464. int (*xHash)(const void*,int); /* The hash function */
  93465. if( pH==0 || pH->ht==0 ) return 0;
  93466. xHash = ftsHashFunction(pH->keyClass);
  93467. assert( xHash!=0 );
  93468. h = (*xHash)(pKey,nKey);
  93469. assert( (pH->htsize & (pH->htsize-1))==0 );
  93470. elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  93471. return elem ? elem->data : 0;
  93472. }
  93473. /* Insert an element into the hash table pH. The key is pKey,nKey
  93474. ** and the data is "data".
  93475. **
  93476. ** If no element exists with a matching key, then a new
  93477. ** element is created. A copy of the key is made if the copyKey
  93478. ** flag is set. NULL is returned.
  93479. **
  93480. ** If another element already exists with the same key, then the
  93481. ** new data replaces the old data and the old data is returned.
  93482. ** The key is not copied in this instance. If a malloc fails, then
  93483. ** the new data is returned and the hash table is unchanged.
  93484. **
  93485. ** If the "data" parameter to this function is NULL, then the
  93486. ** element corresponding to "key" is removed from the hash table.
  93487. */
  93488. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  93489. fts3Hash *pH, /* The hash table to insert into */
  93490. const void *pKey, /* The key */
  93491. int nKey, /* Number of bytes in the key */
  93492. void *data /* The data */
  93493. ){
  93494. int hraw; /* Raw hash value of the key */
  93495. int h; /* the hash of the key modulo hash table size */
  93496. fts3HashElem *elem; /* Used to loop thru the element list */
  93497. fts3HashElem *new_elem; /* New element added to the pH */
  93498. int (*xHash)(const void*,int); /* The hash function */
  93499. assert( pH!=0 );
  93500. xHash = ftsHashFunction(pH->keyClass);
  93501. assert( xHash!=0 );
  93502. hraw = (*xHash)(pKey, nKey);
  93503. assert( (pH->htsize & (pH->htsize-1))==0 );
  93504. h = hraw & (pH->htsize-1);
  93505. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  93506. if( elem ){
  93507. void *old_data = elem->data;
  93508. if( data==0 ){
  93509. fts3RemoveElementByHash(pH,elem,h);
  93510. }else{
  93511. elem->data = data;
  93512. }
  93513. return old_data;
  93514. }
  93515. if( data==0 ) return 0;
  93516. if( pH->htsize==0 ){
  93517. fts3Rehash(pH,8);
  93518. if( pH->htsize==0 ){
  93519. pH->count = 0;
  93520. return data;
  93521. }
  93522. }
  93523. new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
  93524. if( new_elem==0 ) return data;
  93525. if( pH->copyKey && pKey!=0 ){
  93526. new_elem->pKey = fts3HashMalloc( nKey );
  93527. if( new_elem->pKey==0 ){
  93528. fts3HashFree(new_elem);
  93529. return data;
  93530. }
  93531. memcpy((void*)new_elem->pKey, pKey, nKey);
  93532. }else{
  93533. new_elem->pKey = (void*)pKey;
  93534. }
  93535. new_elem->nKey = nKey;
  93536. pH->count++;
  93537. if( pH->count > pH->htsize ){
  93538. fts3Rehash(pH,pH->htsize*2);
  93539. }
  93540. assert( pH->htsize>0 );
  93541. assert( (pH->htsize & (pH->htsize-1))==0 );
  93542. h = hraw & (pH->htsize-1);
  93543. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  93544. new_elem->data = data;
  93545. return 0;
  93546. }
  93547. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  93548. /************** End of fts3_hash.c *******************************************/
  93549. /************** Begin file fts3_porter.c *************************************/
  93550. /*
  93551. ** 2006 September 30
  93552. **
  93553. ** The author disclaims copyright to this source code. In place of
  93554. ** a legal notice, here is a blessing:
  93555. **
  93556. ** May you do good and not evil.
  93557. ** May you find forgiveness for yourself and forgive others.
  93558. ** May you share freely, never taking more than you give.
  93559. **
  93560. *************************************************************************
  93561. ** Implementation of the full-text-search tokenizer that implements
  93562. ** a Porter stemmer.
  93563. */
  93564. /*
  93565. ** The code in this file is only compiled if:
  93566. **
  93567. ** * The FTS3 module is being built as an extension
  93568. ** (in which case SQLITE_CORE is not defined), or
  93569. **
  93570. ** * The FTS3 module is being built into the core of
  93571. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  93572. */
  93573. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  93574. /*
  93575. ** Class derived from sqlite3_tokenizer
  93576. */
  93577. typedef struct porter_tokenizer {
  93578. sqlite3_tokenizer base; /* Base class */
  93579. } porter_tokenizer;
  93580. /*
  93581. ** Class derived from sqlit3_tokenizer_cursor
  93582. */
  93583. typedef struct porter_tokenizer_cursor {
  93584. sqlite3_tokenizer_cursor base;
  93585. const char *zInput; /* input we are tokenizing */
  93586. int nInput; /* size of the input */
  93587. int iOffset; /* current position in zInput */
  93588. int iToken; /* index of next token to be returned */
  93589. char *zToken; /* storage for current token */
  93590. int nAllocated; /* space allocated to zToken buffer */
  93591. } porter_tokenizer_cursor;
  93592. /* Forward declaration */
  93593. static const sqlite3_tokenizer_module porterTokenizerModule;
  93594. /*
  93595. ** Create a new tokenizer instance.
  93596. */
  93597. static int porterCreate(
  93598. int argc, const char * const *argv,
  93599. sqlite3_tokenizer **ppTokenizer
  93600. ){
  93601. porter_tokenizer *t;
  93602. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  93603. if( t==NULL ) return SQLITE_NOMEM;
  93604. memset(t, 0, sizeof(*t));
  93605. *ppTokenizer = &t->base;
  93606. return SQLITE_OK;
  93607. }
  93608. /*
  93609. ** Destroy a tokenizer
  93610. */
  93611. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  93612. sqlite3_free(pTokenizer);
  93613. return SQLITE_OK;
  93614. }
  93615. /*
  93616. ** Prepare to begin tokenizing a particular string. The input
  93617. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  93618. ** used to incrementally tokenize this string is returned in
  93619. ** *ppCursor.
  93620. */
  93621. static int porterOpen(
  93622. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  93623. const char *zInput, int nInput, /* String to be tokenized */
  93624. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  93625. ){
  93626. porter_tokenizer_cursor *c;
  93627. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  93628. if( c==NULL ) return SQLITE_NOMEM;
  93629. c->zInput = zInput;
  93630. if( zInput==0 ){
  93631. c->nInput = 0;
  93632. }else if( nInput<0 ){
  93633. c->nInput = (int)strlen(zInput);
  93634. }else{
  93635. c->nInput = nInput;
  93636. }
  93637. c->iOffset = 0; /* start tokenizing at the beginning */
  93638. c->iToken = 0;
  93639. c->zToken = NULL; /* no space allocated, yet. */
  93640. c->nAllocated = 0;
  93641. *ppCursor = &c->base;
  93642. return SQLITE_OK;
  93643. }
  93644. /*
  93645. ** Close a tokenization cursor previously opened by a call to
  93646. ** porterOpen() above.
  93647. */
  93648. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  93649. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  93650. sqlite3_free(c->zToken);
  93651. sqlite3_free(c);
  93652. return SQLITE_OK;
  93653. }
  93654. /*
  93655. ** Vowel or consonant
  93656. */
  93657. static const char cType[] = {
  93658. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  93659. 1, 1, 1, 2, 1
  93660. };
  93661. /*
  93662. ** isConsonant() and isVowel() determine if their first character in
  93663. ** the string they point to is a consonant or a vowel, according
  93664. ** to Porter ruls.
  93665. **
  93666. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  93667. ** 'Y' is a consonant unless it follows another consonant,
  93668. ** in which case it is a vowel.
  93669. **
  93670. ** In these routine, the letters are in reverse order. So the 'y' rule
  93671. ** is that 'y' is a consonant unless it is followed by another
  93672. ** consonent.
  93673. */
  93674. static int isVowel(const char*);
  93675. static int isConsonant(const char *z){
  93676. int j;
  93677. char x = *z;
  93678. if( x==0 ) return 0;
  93679. assert( x>='a' && x<='z' );
  93680. j = cType[x-'a'];
  93681. if( j<2 ) return j;
  93682. return z[1]==0 || isVowel(z + 1);
  93683. }
  93684. static int isVowel(const char *z){
  93685. int j;
  93686. char x = *z;
  93687. if( x==0 ) return 0;
  93688. assert( x>='a' && x<='z' );
  93689. j = cType[x-'a'];
  93690. if( j<2 ) return 1-j;
  93691. return isConsonant(z + 1);
  93692. }
  93693. /*
  93694. ** Let any sequence of one or more vowels be represented by V and let
  93695. ** C be sequence of one or more consonants. Then every word can be
  93696. ** represented as:
  93697. **
  93698. ** [C] (VC){m} [V]
  93699. **
  93700. ** In prose: A word is an optional consonant followed by zero or
  93701. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  93702. ** number of vowel consonant pairs. This routine computes the value
  93703. ** of m for the first i bytes of a word.
  93704. **
  93705. ** Return true if the m-value for z is 1 or more. In other words,
  93706. ** return true if z contains at least one vowel that is followed
  93707. ** by a consonant.
  93708. **
  93709. ** In this routine z[] is in reverse order. So we are really looking
  93710. ** for an instance of of a consonant followed by a vowel.
  93711. */
  93712. static int m_gt_0(const char *z){
  93713. while( isVowel(z) ){ z++; }
  93714. if( *z==0 ) return 0;
  93715. while( isConsonant(z) ){ z++; }
  93716. return *z!=0;
  93717. }
  93718. /* Like mgt0 above except we are looking for a value of m which is
  93719. ** exactly 1
  93720. */
  93721. static int m_eq_1(const char *z){
  93722. while( isVowel(z) ){ z++; }
  93723. if( *z==0 ) return 0;
  93724. while( isConsonant(z) ){ z++; }
  93725. if( *z==0 ) return 0;
  93726. while( isVowel(z) ){ z++; }
  93727. if( *z==0 ) return 1;
  93728. while( isConsonant(z) ){ z++; }
  93729. return *z==0;
  93730. }
  93731. /* Like mgt0 above except we are looking for a value of m>1 instead
  93732. ** or m>0
  93733. */
  93734. static int m_gt_1(const char *z){
  93735. while( isVowel(z) ){ z++; }
  93736. if( *z==0 ) return 0;
  93737. while( isConsonant(z) ){ z++; }
  93738. if( *z==0 ) return 0;
  93739. while( isVowel(z) ){ z++; }
  93740. if( *z==0 ) return 0;
  93741. while( isConsonant(z) ){ z++; }
  93742. return *z!=0;
  93743. }
  93744. /*
  93745. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  93746. */
  93747. static int hasVowel(const char *z){
  93748. while( isConsonant(z) ){ z++; }
  93749. return *z!=0;
  93750. }
  93751. /*
  93752. ** Return TRUE if the word ends in a double consonant.
  93753. **
  93754. ** The text is reversed here. So we are really looking at
  93755. ** the first two characters of z[].
  93756. */
  93757. static int doubleConsonant(const char *z){
  93758. return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
  93759. }
  93760. /*
  93761. ** Return TRUE if the word ends with three letters which
  93762. ** are consonant-vowel-consonent and where the final consonant
  93763. ** is not 'w', 'x', or 'y'.
  93764. **
  93765. ** The word is reversed here. So we are really checking the
  93766. ** first three letters and the first one cannot be in [wxy].
  93767. */
  93768. static int star_oh(const char *z){
  93769. return
  93770. z[0]!=0 && isConsonant(z) &&
  93771. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  93772. z[1]!=0 && isVowel(z+1) &&
  93773. z[2]!=0 && isConsonant(z+2);
  93774. }
  93775. /*
  93776. ** If the word ends with zFrom and xCond() is true for the stem
  93777. ** of the word that preceeds the zFrom ending, then change the
  93778. ** ending to zTo.
  93779. **
  93780. ** The input word *pz and zFrom are both in reverse order. zTo
  93781. ** is in normal order.
  93782. **
  93783. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  93784. ** match. Not that TRUE is returned even if xCond() fails and
  93785. ** no substitution occurs.
  93786. */
  93787. static int stem(
  93788. char **pz, /* The word being stemmed (Reversed) */
  93789. const char *zFrom, /* If the ending matches this... (Reversed) */
  93790. const char *zTo, /* ... change the ending to this (not reversed) */
  93791. int (*xCond)(const char*) /* Condition that must be true */
  93792. ){
  93793. char *z = *pz;
  93794. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  93795. if( *zFrom!=0 ) return 0;
  93796. if( xCond && !xCond(z) ) return 1;
  93797. while( *zTo ){
  93798. *(--z) = *(zTo++);
  93799. }
  93800. *pz = z;
  93801. return 1;
  93802. }
  93803. /*
  93804. ** This is the fallback stemmer used when the porter stemmer is
  93805. ** inappropriate. The input word is copied into the output with
  93806. ** US-ASCII case folding. If the input word is too long (more
  93807. ** than 20 bytes if it contains no digits or more than 6 bytes if
  93808. ** it contains digits) then word is truncated to 20 or 6 bytes
  93809. ** by taking 10 or 3 bytes from the beginning and end.
  93810. */
  93811. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  93812. int i, mx, j;
  93813. int hasDigit = 0;
  93814. for(i=0; i<nIn; i++){
  93815. int c = zIn[i];
  93816. if( c>='A' && c<='Z' ){
  93817. zOut[i] = c - 'A' + 'a';
  93818. }else{
  93819. if( c>='0' && c<='9' ) hasDigit = 1;
  93820. zOut[i] = c;
  93821. }
  93822. }
  93823. mx = hasDigit ? 3 : 10;
  93824. if( nIn>mx*2 ){
  93825. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  93826. zOut[j] = zOut[i];
  93827. }
  93828. i = j;
  93829. }
  93830. zOut[i] = 0;
  93831. *pnOut = i;
  93832. }
  93833. /*
  93834. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  93835. ** zOut is at least big enough to hold nIn bytes. Write the actual
  93836. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  93837. **
  93838. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  93839. ** are converted to lower case. Upper-case UTF characters are
  93840. ** unchanged.
  93841. **
  93842. ** Words that are longer than about 20 bytes are stemmed by retaining
  93843. ** a few bytes from the beginning and the end of the word. If the
  93844. ** word contains digits, 3 bytes are taken from the beginning and
  93845. ** 3 bytes from the end. For long words without digits, 10 bytes
  93846. ** are taken from each end. US-ASCII case folding still applies.
  93847. **
  93848. ** If the input word contains not digits but does characters not
  93849. ** in [a-zA-Z] then no stemming is attempted and this routine just
  93850. ** copies the input into the input into the output with US-ASCII
  93851. ** case folding.
  93852. **
  93853. ** Stemming never increases the length of the word. So there is
  93854. ** no chance of overflowing the zOut buffer.
  93855. */
  93856. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  93857. int i, j, c;
  93858. char zReverse[28];
  93859. char *z, *z2;
  93860. if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
  93861. /* The word is too big or too small for the porter stemmer.
  93862. ** Fallback to the copy stemmer */
  93863. copy_stemmer(zIn, nIn, zOut, pnOut);
  93864. return;
  93865. }
  93866. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  93867. c = zIn[i];
  93868. if( c>='A' && c<='Z' ){
  93869. zReverse[j] = c + 'a' - 'A';
  93870. }else if( c>='a' && c<='z' ){
  93871. zReverse[j] = c;
  93872. }else{
  93873. /* The use of a character not in [a-zA-Z] means that we fallback
  93874. ** to the copy stemmer */
  93875. copy_stemmer(zIn, nIn, zOut, pnOut);
  93876. return;
  93877. }
  93878. }
  93879. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  93880. z = &zReverse[j+1];
  93881. /* Step 1a */
  93882. if( z[0]=='s' ){
  93883. if(
  93884. !stem(&z, "sess", "ss", 0) &&
  93885. !stem(&z, "sei", "i", 0) &&
  93886. !stem(&z, "ss", "ss", 0)
  93887. ){
  93888. z++;
  93889. }
  93890. }
  93891. /* Step 1b */
  93892. z2 = z;
  93893. if( stem(&z, "dee", "ee", m_gt_0) ){
  93894. /* Do nothing. The work was all in the test */
  93895. }else if(
  93896. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  93897. && z!=z2
  93898. ){
  93899. if( stem(&z, "ta", "ate", 0) ||
  93900. stem(&z, "lb", "ble", 0) ||
  93901. stem(&z, "zi", "ize", 0) ){
  93902. /* Do nothing. The work was all in the test */
  93903. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  93904. z++;
  93905. }else if( m_eq_1(z) && star_oh(z) ){
  93906. *(--z) = 'e';
  93907. }
  93908. }
  93909. /* Step 1c */
  93910. if( z[0]=='y' && hasVowel(z+1) ){
  93911. z[0] = 'i';
  93912. }
  93913. /* Step 2 */
  93914. switch( z[1] ){
  93915. case 'a':
  93916. stem(&z, "lanoita", "ate", m_gt_0) ||
  93917. stem(&z, "lanoit", "tion", m_gt_0);
  93918. break;
  93919. case 'c':
  93920. stem(&z, "icne", "ence", m_gt_0) ||
  93921. stem(&z, "icna", "ance", m_gt_0);
  93922. break;
  93923. case 'e':
  93924. stem(&z, "rezi", "ize", m_gt_0);
  93925. break;
  93926. case 'g':
  93927. stem(&z, "igol", "log", m_gt_0);
  93928. break;
  93929. case 'l':
  93930. stem(&z, "ilb", "ble", m_gt_0) ||
  93931. stem(&z, "illa", "al", m_gt_0) ||
  93932. stem(&z, "iltne", "ent", m_gt_0) ||
  93933. stem(&z, "ile", "e", m_gt_0) ||
  93934. stem(&z, "ilsuo", "ous", m_gt_0);
  93935. break;
  93936. case 'o':
  93937. stem(&z, "noitazi", "ize", m_gt_0) ||
  93938. stem(&z, "noita", "ate", m_gt_0) ||
  93939. stem(&z, "rota", "ate", m_gt_0);
  93940. break;
  93941. case 's':
  93942. stem(&z, "msila", "al", m_gt_0) ||
  93943. stem(&z, "ssenevi", "ive", m_gt_0) ||
  93944. stem(&z, "ssenluf", "ful", m_gt_0) ||
  93945. stem(&z, "ssensuo", "ous", m_gt_0);
  93946. break;
  93947. case 't':
  93948. stem(&z, "itila", "al", m_gt_0) ||
  93949. stem(&z, "itivi", "ive", m_gt_0) ||
  93950. stem(&z, "itilib", "ble", m_gt_0);
  93951. break;
  93952. }
  93953. /* Step 3 */
  93954. switch( z[0] ){
  93955. case 'e':
  93956. stem(&z, "etaci", "ic", m_gt_0) ||
  93957. stem(&z, "evita", "", m_gt_0) ||
  93958. stem(&z, "ezila", "al", m_gt_0);
  93959. break;
  93960. case 'i':
  93961. stem(&z, "itici", "ic", m_gt_0);
  93962. break;
  93963. case 'l':
  93964. stem(&z, "laci", "ic", m_gt_0) ||
  93965. stem(&z, "luf", "", m_gt_0);
  93966. break;
  93967. case 's':
  93968. stem(&z, "ssen", "", m_gt_0);
  93969. break;
  93970. }
  93971. /* Step 4 */
  93972. switch( z[1] ){
  93973. case 'a':
  93974. if( z[0]=='l' && m_gt_1(z+2) ){
  93975. z += 2;
  93976. }
  93977. break;
  93978. case 'c':
  93979. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  93980. z += 4;
  93981. }
  93982. break;
  93983. case 'e':
  93984. if( z[0]=='r' && m_gt_1(z+2) ){
  93985. z += 2;
  93986. }
  93987. break;
  93988. case 'i':
  93989. if( z[0]=='c' && m_gt_1(z+2) ){
  93990. z += 2;
  93991. }
  93992. break;
  93993. case 'l':
  93994. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  93995. z += 4;
  93996. }
  93997. break;
  93998. case 'n':
  93999. if( z[0]=='t' ){
  94000. if( z[2]=='a' ){
  94001. if( m_gt_1(z+3) ){
  94002. z += 3;
  94003. }
  94004. }else if( z[2]=='e' ){
  94005. stem(&z, "tneme", "", m_gt_1) ||
  94006. stem(&z, "tnem", "", m_gt_1) ||
  94007. stem(&z, "tne", "", m_gt_1);
  94008. }
  94009. }
  94010. break;
  94011. case 'o':
  94012. if( z[0]=='u' ){
  94013. if( m_gt_1(z+2) ){
  94014. z += 2;
  94015. }
  94016. }else if( z[3]=='s' || z[3]=='t' ){
  94017. stem(&z, "noi", "", m_gt_1);
  94018. }
  94019. break;
  94020. case 's':
  94021. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  94022. z += 3;
  94023. }
  94024. break;
  94025. case 't':
  94026. stem(&z, "eta", "", m_gt_1) ||
  94027. stem(&z, "iti", "", m_gt_1);
  94028. break;
  94029. case 'u':
  94030. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  94031. z += 3;
  94032. }
  94033. break;
  94034. case 'v':
  94035. case 'z':
  94036. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  94037. z += 3;
  94038. }
  94039. break;
  94040. }
  94041. /* Step 5a */
  94042. if( z[0]=='e' ){
  94043. if( m_gt_1(z+1) ){
  94044. z++;
  94045. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  94046. z++;
  94047. }
  94048. }
  94049. /* Step 5b */
  94050. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  94051. z++;
  94052. }
  94053. /* z[] is now the stemmed word in reverse order. Flip it back
  94054. ** around into forward order and return.
  94055. */
  94056. *pnOut = i = strlen(z);
  94057. zOut[i] = 0;
  94058. while( *z ){
  94059. zOut[--i] = *(z++);
  94060. }
  94061. }
  94062. /*
  94063. ** Characters that can be part of a token. We assume any character
  94064. ** whose value is greater than 0x80 (any UTF character) can be
  94065. ** part of a token. In other words, delimiters all must have
  94066. ** values of 0x7f or lower.
  94067. */
  94068. static const char porterIdChar[] = {
  94069. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  94070. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  94071. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  94072. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  94073. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  94074. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  94075. };
  94076. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  94077. /*
  94078. ** Extract the next token from a tokenization cursor. The cursor must
  94079. ** have been opened by a prior call to porterOpen().
  94080. */
  94081. static int porterNext(
  94082. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  94083. const char **pzToken, /* OUT: *pzToken is the token text */
  94084. int *pnBytes, /* OUT: Number of bytes in token */
  94085. int *piStartOffset, /* OUT: Starting offset of token */
  94086. int *piEndOffset, /* OUT: Ending offset of token */
  94087. int *piPosition /* OUT: Position integer of token */
  94088. ){
  94089. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  94090. const char *z = c->zInput;
  94091. while( c->iOffset<c->nInput ){
  94092. int iStartOffset, ch;
  94093. /* Scan past delimiter characters */
  94094. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  94095. c->iOffset++;
  94096. }
  94097. /* Count non-delimiter characters. */
  94098. iStartOffset = c->iOffset;
  94099. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  94100. c->iOffset++;
  94101. }
  94102. if( c->iOffset>iStartOffset ){
  94103. int n = c->iOffset-iStartOffset;
  94104. if( n>c->nAllocated ){
  94105. c->nAllocated = n+20;
  94106. c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
  94107. if( c->zToken==NULL ) return SQLITE_NOMEM;
  94108. }
  94109. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  94110. *pzToken = c->zToken;
  94111. *piStartOffset = iStartOffset;
  94112. *piEndOffset = c->iOffset;
  94113. *piPosition = c->iToken++;
  94114. return SQLITE_OK;
  94115. }
  94116. }
  94117. return SQLITE_DONE;
  94118. }
  94119. /*
  94120. ** The set of routines that implement the porter-stemmer tokenizer
  94121. */
  94122. static const sqlite3_tokenizer_module porterTokenizerModule = {
  94123. 0,
  94124. porterCreate,
  94125. porterDestroy,
  94126. porterOpen,
  94127. porterClose,
  94128. porterNext,
  94129. };
  94130. /*
  94131. ** Allocate a new porter tokenizer. Return a pointer to the new
  94132. ** tokenizer in *ppModule
  94133. */
  94134. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  94135. sqlite3_tokenizer_module const**ppModule
  94136. ){
  94137. *ppModule = &porterTokenizerModule;
  94138. }
  94139. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  94140. /************** End of fts3_porter.c *****************************************/
  94141. /************** Begin file fts3_tokenizer.c **********************************/
  94142. /*
  94143. ** 2007 June 22
  94144. **
  94145. ** The author disclaims copyright to this source code. In place of
  94146. ** a legal notice, here is a blessing:
  94147. **
  94148. ** May you do good and not evil.
  94149. ** May you find forgiveness for yourself and forgive others.
  94150. ** May you share freely, never taking more than you give.
  94151. **
  94152. ******************************************************************************
  94153. **
  94154. ** This is part of an SQLite module implementing full-text search.
  94155. ** This particular file implements the generic tokenizer interface.
  94156. */
  94157. /*
  94158. ** The code in this file is only compiled if:
  94159. **
  94160. ** * The FTS3 module is being built as an extension
  94161. ** (in which case SQLITE_CORE is not defined), or
  94162. **
  94163. ** * The FTS3 module is being built into the core of
  94164. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  94165. */
  94166. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  94167. #ifndef SQLITE_CORE
  94168. SQLITE_EXTENSION_INIT1
  94169. #endif
  94170. /*
  94171. ** Implementation of the SQL scalar function for accessing the underlying
  94172. ** hash table. This function may be called as follows:
  94173. **
  94174. ** SELECT <function-name>(<key-name>);
  94175. ** SELECT <function-name>(<key-name>, <pointer>);
  94176. **
  94177. ** where <function-name> is the name passed as the second argument
  94178. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  94179. **
  94180. ** If the <pointer> argument is specified, it must be a blob value
  94181. ** containing a pointer to be stored as the hash data corresponding
  94182. ** to the string <key-name>. If <pointer> is not specified, then
  94183. ** the string <key-name> must already exist in the has table. Otherwise,
  94184. ** an error is returned.
  94185. **
  94186. ** Whether or not the <pointer> argument is specified, the value returned
  94187. ** is a blob containing the pointer stored as the hash data corresponding
  94188. ** to string <key-name> (after the hash-table is updated, if applicable).
  94189. */
  94190. static void scalarFunc(
  94191. sqlite3_context *context,
  94192. int argc,
  94193. sqlite3_value **argv
  94194. ){
  94195. fts3Hash *pHash;
  94196. void *pPtr = 0;
  94197. const unsigned char *zName;
  94198. int nName;
  94199. assert( argc==1 || argc==2 );
  94200. pHash = (fts3Hash *)sqlite3_user_data(context);
  94201. zName = sqlite3_value_text(argv[0]);
  94202. nName = sqlite3_value_bytes(argv[0])+1;
  94203. if( argc==2 ){
  94204. void *pOld;
  94205. int n = sqlite3_value_bytes(argv[1]);
  94206. if( n!=sizeof(pPtr) ){
  94207. sqlite3_result_error(context, "argument type mismatch", -1);
  94208. return;
  94209. }
  94210. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  94211. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  94212. if( pOld==pPtr ){
  94213. sqlite3_result_error(context, "out of memory", -1);
  94214. return;
  94215. }
  94216. }else{
  94217. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  94218. if( !pPtr ){
  94219. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  94220. sqlite3_result_error(context, zErr, -1);
  94221. sqlite3_free(zErr);
  94222. return;
  94223. }
  94224. }
  94225. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  94226. }
  94227. #ifdef SQLITE_TEST
  94228. /*
  94229. ** Implementation of a special SQL scalar function for testing tokenizers
  94230. ** designed to be used in concert with the Tcl testing framework. This
  94231. ** function must be called with two arguments:
  94232. **
  94233. ** SELECT <function-name>(<key-name>, <input-string>);
  94234. ** SELECT <function-name>(<key-name>, <pointer>);
  94235. **
  94236. ** where <function-name> is the name passed as the second argument
  94237. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  94238. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  94239. **
  94240. ** The return value is a string that may be interpreted as a Tcl
  94241. ** list. For each token in the <input-string>, three elements are
  94242. ** added to the returned list. The first is the token position, the
  94243. ** second is the token text (folded, stemmed, etc.) and the third is the
  94244. ** substring of <input-string> associated with the token. For example,
  94245. ** using the built-in "simple" tokenizer:
  94246. **
  94247. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  94248. **
  94249. ** will return the string:
  94250. **
  94251. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  94252. **
  94253. */
  94254. static void testFunc(
  94255. sqlite3_context *context,
  94256. int argc,
  94257. sqlite3_value **argv
  94258. ){
  94259. fts3Hash *pHash;
  94260. sqlite3_tokenizer_module *p;
  94261. sqlite3_tokenizer *pTokenizer = 0;
  94262. sqlite3_tokenizer_cursor *pCsr = 0;
  94263. const char *zErr = 0;
  94264. const char *zName;
  94265. int nName;
  94266. const char *zInput;
  94267. int nInput;
  94268. const char *zArg = 0;
  94269. const char *zToken;
  94270. int nToken;
  94271. int iStart;
  94272. int iEnd;
  94273. int iPos;
  94274. Tcl_Obj *pRet;
  94275. assert( argc==2 || argc==3 );
  94276. nName = sqlite3_value_bytes(argv[0]);
  94277. zName = (const char *)sqlite3_value_text(argv[0]);
  94278. nInput = sqlite3_value_bytes(argv[argc-1]);
  94279. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  94280. if( argc==3 ){
  94281. zArg = (const char *)sqlite3_value_text(argv[1]);
  94282. }
  94283. pHash = (fts3Hash *)sqlite3_user_data(context);
  94284. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  94285. if( !p ){
  94286. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  94287. sqlite3_result_error(context, zErr, -1);
  94288. sqlite3_free(zErr);
  94289. return;
  94290. }
  94291. pRet = Tcl_NewObj();
  94292. Tcl_IncrRefCount(pRet);
  94293. if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
  94294. zErr = "error in xCreate()";
  94295. goto finish;
  94296. }
  94297. pTokenizer->pModule = p;
  94298. if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
  94299. zErr = "error in xOpen()";
  94300. goto finish;
  94301. }
  94302. pCsr->pTokenizer = pTokenizer;
  94303. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  94304. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  94305. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  94306. zToken = &zInput[iStart];
  94307. nToken = iEnd-iStart;
  94308. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  94309. }
  94310. if( SQLITE_OK!=p->xClose(pCsr) ){
  94311. zErr = "error in xClose()";
  94312. goto finish;
  94313. }
  94314. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  94315. zErr = "error in xDestroy()";
  94316. goto finish;
  94317. }
  94318. finish:
  94319. if( zErr ){
  94320. sqlite3_result_error(context, zErr, -1);
  94321. }else{
  94322. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  94323. }
  94324. Tcl_DecrRefCount(pRet);
  94325. }
  94326. static
  94327. int registerTokenizer(
  94328. sqlite3 *db,
  94329. char *zName,
  94330. const sqlite3_tokenizer_module *p
  94331. ){
  94332. int rc;
  94333. sqlite3_stmt *pStmt;
  94334. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  94335. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  94336. if( rc!=SQLITE_OK ){
  94337. return rc;
  94338. }
  94339. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  94340. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  94341. sqlite3_step(pStmt);
  94342. return sqlite3_finalize(pStmt);
  94343. }
  94344. static
  94345. int queryTokenizer(
  94346. sqlite3 *db,
  94347. char *zName,
  94348. const sqlite3_tokenizer_module **pp
  94349. ){
  94350. int rc;
  94351. sqlite3_stmt *pStmt;
  94352. const char zSql[] = "SELECT fts3_tokenizer(?)";
  94353. *pp = 0;
  94354. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  94355. if( rc!=SQLITE_OK ){
  94356. return rc;
  94357. }
  94358. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  94359. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  94360. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  94361. memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  94362. }
  94363. }
  94364. return sqlite3_finalize(pStmt);
  94365. }
  94366. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  94367. /*
  94368. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  94369. ** This function is used for testing only, it is not included in the
  94370. ** build unless SQLITE_TEST is defined.
  94371. **
  94372. ** The purpose of this is to test that the fts3_tokenizer() function
  94373. ** can be used as designed by the C-code in the queryTokenizer and
  94374. ** registerTokenizer() functions above. These two functions are repeated
  94375. ** in the README.tokenizer file as an example, so it is important to
  94376. ** test them.
  94377. **
  94378. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  94379. ** function with no arguments. An assert() will fail if a problem is
  94380. ** detected. i.e.:
  94381. **
  94382. ** SELECT fts3_tokenizer_internal_test();
  94383. **
  94384. */
  94385. static void intTestFunc(
  94386. sqlite3_context *context,
  94387. int argc,
  94388. sqlite3_value **argv
  94389. ){
  94390. int rc;
  94391. const sqlite3_tokenizer_module *p1;
  94392. const sqlite3_tokenizer_module *p2;
  94393. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  94394. /* Test the query function */
  94395. sqlite3Fts3SimpleTokenizerModule(&p1);
  94396. rc = queryTokenizer(db, "simple", &p2);
  94397. assert( rc==SQLITE_OK );
  94398. assert( p1==p2 );
  94399. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  94400. assert( rc==SQLITE_ERROR );
  94401. assert( p2==0 );
  94402. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  94403. /* Test the storage function */
  94404. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  94405. assert( rc==SQLITE_OK );
  94406. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  94407. assert( rc==SQLITE_OK );
  94408. assert( p2==p1 );
  94409. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  94410. }
  94411. #endif
  94412. /*
  94413. ** Set up SQL objects in database db used to access the contents of
  94414. ** the hash table pointed to by argument pHash. The hash table must
  94415. ** been initialised to use string keys, and to take a private copy
  94416. ** of the key when a value is inserted. i.e. by a call similar to:
  94417. **
  94418. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  94419. **
  94420. ** This function adds a scalar function (see header comment above
  94421. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  94422. ** defined at compilation time, a temporary virtual table (see header
  94423. ** comment above struct HashTableVtab) to the database schema. Both
  94424. ** provide read/write access to the contents of *pHash.
  94425. **
  94426. ** The third argument to this function, zName, is used as the name
  94427. ** of both the scalar and, if created, the virtual table.
  94428. */
  94429. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  94430. sqlite3 *db,
  94431. fts3Hash *pHash,
  94432. const char *zName
  94433. ){
  94434. int rc = SQLITE_OK;
  94435. void *p = (void *)pHash;
  94436. const int any = SQLITE_ANY;
  94437. char *zTest = 0;
  94438. char *zTest2 = 0;
  94439. #ifdef SQLITE_TEST
  94440. void *pdb = (void *)db;
  94441. zTest = sqlite3_mprintf("%s_test", zName);
  94442. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  94443. if( !zTest || !zTest2 ){
  94444. rc = SQLITE_NOMEM;
  94445. }
  94446. #endif
  94447. if( rc!=SQLITE_OK
  94448. || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
  94449. || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
  94450. #ifdef SQLITE_TEST
  94451. || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
  94452. || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
  94453. || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
  94454. #endif
  94455. );
  94456. sqlite3_free(zTest);
  94457. sqlite3_free(zTest2);
  94458. return rc;
  94459. }
  94460. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  94461. /************** End of fts3_tokenizer.c **************************************/
  94462. /************** Begin file fts3_tokenizer1.c *********************************/
  94463. /*
  94464. ** 2006 Oct 10
  94465. **
  94466. ** The author disclaims copyright to this source code. In place of
  94467. ** a legal notice, here is a blessing:
  94468. **
  94469. ** May you do good and not evil.
  94470. ** May you find forgiveness for yourself and forgive others.
  94471. ** May you share freely, never taking more than you give.
  94472. **
  94473. ******************************************************************************
  94474. **
  94475. ** Implementation of the "simple" full-text-search tokenizer.
  94476. */
  94477. /*
  94478. ** The code in this file is only compiled if:
  94479. **
  94480. ** * The FTS3 module is being built as an extension
  94481. ** (in which case SQLITE_CORE is not defined), or
  94482. **
  94483. ** * The FTS3 module is being built into the core of
  94484. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  94485. */
  94486. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  94487. typedef struct simple_tokenizer {
  94488. sqlite3_tokenizer base;
  94489. char delim[128]; /* flag ASCII delimiters */
  94490. } simple_tokenizer;
  94491. typedef struct simple_tokenizer_cursor {
  94492. sqlite3_tokenizer_cursor base;
  94493. const char *pInput; /* input we are tokenizing */
  94494. int nBytes; /* size of the input */
  94495. int iOffset; /* current position in pInput */
  94496. int iToken; /* index of next token to be returned */
  94497. char *pToken; /* storage for current token */
  94498. int nTokenAllocated; /* space allocated to zToken buffer */
  94499. } simple_tokenizer_cursor;
  94500. /* Forward declaration */
  94501. static const sqlite3_tokenizer_module simpleTokenizerModule;
  94502. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  94503. return c<0x80 && t->delim[c];
  94504. }
  94505. /*
  94506. ** Create a new tokenizer instance.
  94507. */
  94508. static int simpleCreate(
  94509. int argc, const char * const *argv,
  94510. sqlite3_tokenizer **ppTokenizer
  94511. ){
  94512. simple_tokenizer *t;
  94513. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  94514. if( t==NULL ) return SQLITE_NOMEM;
  94515. memset(t, 0, sizeof(*t));
  94516. /* TODO(shess) Delimiters need to remain the same from run to run,
  94517. ** else we need to reindex. One solution would be a meta-table to
  94518. ** track such information in the database, then we'd only want this
  94519. ** information on the initial create.
  94520. */
  94521. if( argc>1 ){
  94522. int i, n = strlen(argv[1]);
  94523. for(i=0; i<n; i++){
  94524. unsigned char ch = argv[1][i];
  94525. /* We explicitly don't support UTF-8 delimiters for now. */
  94526. if( ch>=0x80 ){
  94527. sqlite3_free(t);
  94528. return SQLITE_ERROR;
  94529. }
  94530. t->delim[ch] = 1;
  94531. }
  94532. } else {
  94533. /* Mark non-alphanumeric ASCII characters as delimiters */
  94534. int i;
  94535. for(i=1; i<0x80; i++){
  94536. t->delim[i] = !isalnum(i);
  94537. }
  94538. }
  94539. *ppTokenizer = &t->base;
  94540. return SQLITE_OK;
  94541. }
  94542. /*
  94543. ** Destroy a tokenizer
  94544. */
  94545. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  94546. sqlite3_free(pTokenizer);
  94547. return SQLITE_OK;
  94548. }
  94549. /*
  94550. ** Prepare to begin tokenizing a particular string. The input
  94551. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  94552. ** used to incrementally tokenize this string is returned in
  94553. ** *ppCursor.
  94554. */
  94555. static int simpleOpen(
  94556. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  94557. const char *pInput, int nBytes, /* String to be tokenized */
  94558. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  94559. ){
  94560. simple_tokenizer_cursor *c;
  94561. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  94562. if( c==NULL ) return SQLITE_NOMEM;
  94563. c->pInput = pInput;
  94564. if( pInput==0 ){
  94565. c->nBytes = 0;
  94566. }else if( nBytes<0 ){
  94567. c->nBytes = (int)strlen(pInput);
  94568. }else{
  94569. c->nBytes = nBytes;
  94570. }
  94571. c->iOffset = 0; /* start tokenizing at the beginning */
  94572. c->iToken = 0;
  94573. c->pToken = NULL; /* no space allocated, yet. */
  94574. c->nTokenAllocated = 0;
  94575. *ppCursor = &c->base;
  94576. return SQLITE_OK;
  94577. }
  94578. /*
  94579. ** Close a tokenization cursor previously opened by a call to
  94580. ** simpleOpen() above.
  94581. */
  94582. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  94583. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  94584. sqlite3_free(c->pToken);
  94585. sqlite3_free(c);
  94586. return SQLITE_OK;
  94587. }
  94588. /*
  94589. ** Extract the next token from a tokenization cursor. The cursor must
  94590. ** have been opened by a prior call to simpleOpen().
  94591. */
  94592. static int simpleNext(
  94593. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  94594. const char **ppToken, /* OUT: *ppToken is the token text */
  94595. int *pnBytes, /* OUT: Number of bytes in token */
  94596. int *piStartOffset, /* OUT: Starting offset of token */
  94597. int *piEndOffset, /* OUT: Ending offset of token */
  94598. int *piPosition /* OUT: Position integer of token */
  94599. ){
  94600. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  94601. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  94602. unsigned char *p = (unsigned char *)c->pInput;
  94603. while( c->iOffset<c->nBytes ){
  94604. int iStartOffset;
  94605. /* Scan past delimiter characters */
  94606. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  94607. c->iOffset++;
  94608. }
  94609. /* Count non-delimiter characters. */
  94610. iStartOffset = c->iOffset;
  94611. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  94612. c->iOffset++;
  94613. }
  94614. if( c->iOffset>iStartOffset ){
  94615. int i, n = c->iOffset-iStartOffset;
  94616. if( n>c->nTokenAllocated ){
  94617. c->nTokenAllocated = n+20;
  94618. c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  94619. if( c->pToken==NULL ) return SQLITE_NOMEM;
  94620. }
  94621. for(i=0; i<n; i++){
  94622. /* TODO(shess) This needs expansion to handle UTF-8
  94623. ** case-insensitivity.
  94624. */
  94625. unsigned char ch = p[iStartOffset+i];
  94626. c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
  94627. }
  94628. *ppToken = c->pToken;
  94629. *pnBytes = n;
  94630. *piStartOffset = iStartOffset;
  94631. *piEndOffset = c->iOffset;
  94632. *piPosition = c->iToken++;
  94633. return SQLITE_OK;
  94634. }
  94635. }
  94636. return SQLITE_DONE;
  94637. }
  94638. /*
  94639. ** The set of routines that implement the simple tokenizer
  94640. */
  94641. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  94642. 0,
  94643. simpleCreate,
  94644. simpleDestroy,
  94645. simpleOpen,
  94646. simpleClose,
  94647. simpleNext,
  94648. };
  94649. /*
  94650. ** Allocate a new simple tokenizer. Return a pointer to the new
  94651. ** tokenizer in *ppModule
  94652. */
  94653. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  94654. sqlite3_tokenizer_module const**ppModule
  94655. ){
  94656. *ppModule = &simpleTokenizerModule;
  94657. }
  94658. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  94659. /************** End of fts3_tokenizer1.c *************************************/
  94660. /************** Begin file rtree.c *******************************************/
  94661. /*
  94662. ** 2001 September 15
  94663. **
  94664. ** The author disclaims copyright to this source code. In place of
  94665. ** a legal notice, here is a blessing:
  94666. **
  94667. ** May you do good and not evil.
  94668. ** May you find forgiveness for yourself and forgive others.
  94669. ** May you share freely, never taking more than you give.
  94670. **
  94671. *************************************************************************
  94672. ** This file contains code for implementations of the r-tree and r*-tree
  94673. ** algorithms packaged as an SQLite virtual table module.
  94674. **
  94675. ** $Id: rtree.c,v 1.12 2008/12/22 15:04:32 danielk1977 Exp $
  94676. */
  94677. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  94678. /*
  94679. ** This file contains an implementation of a couple of different variants
  94680. ** of the r-tree algorithm. See the README file for further details. The
  94681. ** same data-structure is used for all, but the algorithms for insert and
  94682. ** delete operations vary. The variants used are selected at compile time
  94683. ** by defining the following symbols:
  94684. */
  94685. /* Either, both or none of the following may be set to activate
  94686. ** r*tree variant algorithms.
  94687. */
  94688. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  94689. #define VARIANT_RSTARTREE_REINSERT 1
  94690. /*
  94691. ** Exactly one of the following must be set to 1.
  94692. */
  94693. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  94694. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  94695. #define VARIANT_RSTARTREE_SPLIT 1
  94696. #define VARIANT_GUTTMAN_SPLIT \
  94697. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  94698. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  94699. #define PickNext QuadraticPickNext
  94700. #define PickSeeds QuadraticPickSeeds
  94701. #define AssignCells splitNodeGuttman
  94702. #endif
  94703. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  94704. #define PickNext LinearPickNext
  94705. #define PickSeeds LinearPickSeeds
  94706. #define AssignCells splitNodeGuttman
  94707. #endif
  94708. #if VARIANT_RSTARTREE_SPLIT
  94709. #define AssignCells splitNodeStartree
  94710. #endif
  94711. #ifndef SQLITE_CORE
  94712. SQLITE_EXTENSION_INIT1
  94713. #else
  94714. #endif
  94715. #ifndef SQLITE_AMALGAMATION
  94716. typedef sqlite3_int64 i64;
  94717. typedef unsigned char u8;
  94718. typedef unsigned int u32;
  94719. #endif
  94720. typedef struct Rtree Rtree;
  94721. typedef struct RtreeCursor RtreeCursor;
  94722. typedef struct RtreeNode RtreeNode;
  94723. typedef struct RtreeCell RtreeCell;
  94724. typedef struct RtreeConstraint RtreeConstraint;
  94725. typedef union RtreeCoord RtreeCoord;
  94726. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  94727. #define RTREE_MAX_DIMENSIONS 5
  94728. /* Size of hash table Rtree.aHash. This hash table is not expected to
  94729. ** ever contain very many entries, so a fixed number of buckets is
  94730. ** used.
  94731. */
  94732. #define HASHSIZE 128
  94733. /*
  94734. ** An rtree virtual-table object.
  94735. */
  94736. struct Rtree {
  94737. sqlite3_vtab base;
  94738. sqlite3 *db; /* Host database connection */
  94739. int iNodeSize; /* Size in bytes of each node in the node table */
  94740. int nDim; /* Number of dimensions */
  94741. int nBytesPerCell; /* Bytes consumed per cell */
  94742. int iDepth; /* Current depth of the r-tree structure */
  94743. char *zDb; /* Name of database containing r-tree table */
  94744. char *zName; /* Name of r-tree table */
  94745. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  94746. int nBusy; /* Current number of users of this structure */
  94747. /* List of nodes removed during a CondenseTree operation. List is
  94748. ** linked together via the pointer normally used for hash chains -
  94749. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  94750. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  94751. */
  94752. RtreeNode *pDeleted;
  94753. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  94754. /* Statements to read/write/delete a record from xxx_node */
  94755. sqlite3_stmt *pReadNode;
  94756. sqlite3_stmt *pWriteNode;
  94757. sqlite3_stmt *pDeleteNode;
  94758. /* Statements to read/write/delete a record from xxx_rowid */
  94759. sqlite3_stmt *pReadRowid;
  94760. sqlite3_stmt *pWriteRowid;
  94761. sqlite3_stmt *pDeleteRowid;
  94762. /* Statements to read/write/delete a record from xxx_parent */
  94763. sqlite3_stmt *pReadParent;
  94764. sqlite3_stmt *pWriteParent;
  94765. sqlite3_stmt *pDeleteParent;
  94766. int eCoordType;
  94767. };
  94768. /* Possible values for eCoordType: */
  94769. #define RTREE_COORD_REAL32 0
  94770. #define RTREE_COORD_INT32 1
  94771. /*
  94772. ** The minimum number of cells allowed for a node is a third of the
  94773. ** maximum. In Gutman's notation:
  94774. **
  94775. ** m = M/3
  94776. **
  94777. ** If an R*-tree "Reinsert" operation is required, the same number of
  94778. ** cells are removed from the overfull node and reinserted into the tree.
  94779. */
  94780. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  94781. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  94782. #define RTREE_MAXCELLS 51
  94783. /*
  94784. ** An rtree cursor object.
  94785. */
  94786. struct RtreeCursor {
  94787. sqlite3_vtab_cursor base;
  94788. RtreeNode *pNode; /* Node cursor is currently pointing at */
  94789. int iCell; /* Index of current cell in pNode */
  94790. int iStrategy; /* Copy of idxNum search parameter */
  94791. int nConstraint; /* Number of entries in aConstraint */
  94792. RtreeConstraint *aConstraint; /* Search constraints. */
  94793. };
  94794. union RtreeCoord {
  94795. float f;
  94796. int i;
  94797. };
  94798. /*
  94799. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  94800. ** formatted as a double. This macro assumes that local variable pRtree points
  94801. ** to the Rtree structure associated with the RtreeCoord.
  94802. */
  94803. #define DCOORD(coord) ( \
  94804. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  94805. ((double)coord.f) : \
  94806. ((double)coord.i) \
  94807. )
  94808. /*
  94809. ** A search constraint.
  94810. */
  94811. struct RtreeConstraint {
  94812. int iCoord; /* Index of constrained coordinate */
  94813. int op; /* Constraining operation */
  94814. double rValue; /* Constraint value. */
  94815. };
  94816. /* Possible values for RtreeConstraint.op */
  94817. #define RTREE_EQ 0x41
  94818. #define RTREE_LE 0x42
  94819. #define RTREE_LT 0x43
  94820. #define RTREE_GE 0x44
  94821. #define RTREE_GT 0x45
  94822. /*
  94823. ** An rtree structure node.
  94824. **
  94825. ** Data format (RtreeNode.zData):
  94826. **
  94827. ** 1. If the node is the root node (node 1), then the first 2 bytes
  94828. ** of the node contain the tree depth as a big-endian integer.
  94829. ** For non-root nodes, the first 2 bytes are left unused.
  94830. **
  94831. ** 2. The next 2 bytes contain the number of entries currently
  94832. ** stored in the node.
  94833. **
  94834. ** 3. The remainder of the node contains the node entries. Each entry
  94835. ** consists of a single 8-byte integer followed by an even number
  94836. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  94837. ** of a record. For internal nodes it is the node number of a
  94838. ** child page.
  94839. */
  94840. struct RtreeNode {
  94841. RtreeNode *pParent; /* Parent node */
  94842. i64 iNode;
  94843. int nRef;
  94844. int isDirty;
  94845. u8 *zData;
  94846. RtreeNode *pNext; /* Next node in this hash chain */
  94847. };
  94848. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  94849. /*
  94850. ** Structure to store a deserialized rtree record.
  94851. */
  94852. struct RtreeCell {
  94853. i64 iRowid;
  94854. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  94855. };
  94856. #ifndef MAX
  94857. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  94858. #endif
  94859. #ifndef MIN
  94860. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  94861. #endif
  94862. /*
  94863. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  94864. ** 64 bit integer. The deserialized value is returned.
  94865. */
  94866. static int readInt16(u8 *p){
  94867. return (p[0]<<8) + p[1];
  94868. }
  94869. static void readCoord(u8 *p, RtreeCoord *pCoord){
  94870. u32 i = (
  94871. (((u32)p[0]) << 24) +
  94872. (((u32)p[1]) << 16) +
  94873. (((u32)p[2]) << 8) +
  94874. (((u32)p[3]) << 0)
  94875. );
  94876. *(u32 *)pCoord = i;
  94877. }
  94878. static i64 readInt64(u8 *p){
  94879. return (
  94880. (((i64)p[0]) << 56) +
  94881. (((i64)p[1]) << 48) +
  94882. (((i64)p[2]) << 40) +
  94883. (((i64)p[3]) << 32) +
  94884. (((i64)p[4]) << 24) +
  94885. (((i64)p[5]) << 16) +
  94886. (((i64)p[6]) << 8) +
  94887. (((i64)p[7]) << 0)
  94888. );
  94889. }
  94890. /*
  94891. ** Functions to serialize a 16 bit integer, 32 bit real number and
  94892. ** 64 bit integer. The value returned is the number of bytes written
  94893. ** to the argument buffer (always 2, 4 and 8 respectively).
  94894. */
  94895. static int writeInt16(u8 *p, int i){
  94896. p[0] = (i>> 8)&0xFF;
  94897. p[1] = (i>> 0)&0xFF;
  94898. return 2;
  94899. }
  94900. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  94901. u32 i;
  94902. assert( sizeof(RtreeCoord)==4 );
  94903. assert( sizeof(u32)==4 );
  94904. i = *(u32 *)pCoord;
  94905. p[0] = (i>>24)&0xFF;
  94906. p[1] = (i>>16)&0xFF;
  94907. p[2] = (i>> 8)&0xFF;
  94908. p[3] = (i>> 0)&0xFF;
  94909. return 4;
  94910. }
  94911. static int writeInt64(u8 *p, i64 i){
  94912. p[0] = (i>>56)&0xFF;
  94913. p[1] = (i>>48)&0xFF;
  94914. p[2] = (i>>40)&0xFF;
  94915. p[3] = (i>>32)&0xFF;
  94916. p[4] = (i>>24)&0xFF;
  94917. p[5] = (i>>16)&0xFF;
  94918. p[6] = (i>> 8)&0xFF;
  94919. p[7] = (i>> 0)&0xFF;
  94920. return 8;
  94921. }
  94922. /*
  94923. ** Increment the reference count of node p.
  94924. */
  94925. static void nodeReference(RtreeNode *p){
  94926. if( p ){
  94927. p->nRef++;
  94928. }
  94929. }
  94930. /*
  94931. ** Clear the content of node p (set all bytes to 0x00).
  94932. */
  94933. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  94934. if( p ){
  94935. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  94936. p->isDirty = 1;
  94937. }
  94938. }
  94939. /*
  94940. ** Given a node number iNode, return the corresponding key to use
  94941. ** in the Rtree.aHash table.
  94942. */
  94943. static int nodeHash(i64 iNode){
  94944. return (
  94945. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  94946. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  94947. ) % HASHSIZE;
  94948. }
  94949. /*
  94950. ** Search the node hash table for node iNode. If found, return a pointer
  94951. ** to it. Otherwise, return 0.
  94952. */
  94953. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  94954. RtreeNode *p;
  94955. assert( iNode!=0 );
  94956. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  94957. return p;
  94958. }
  94959. /*
  94960. ** Add node pNode to the node hash table.
  94961. */
  94962. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  94963. if( pNode ){
  94964. int iHash;
  94965. assert( pNode->pNext==0 );
  94966. iHash = nodeHash(pNode->iNode);
  94967. pNode->pNext = pRtree->aHash[iHash];
  94968. pRtree->aHash[iHash] = pNode;
  94969. }
  94970. }
  94971. /*
  94972. ** Remove node pNode from the node hash table.
  94973. */
  94974. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  94975. RtreeNode **pp;
  94976. if( pNode->iNode!=0 ){
  94977. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  94978. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  94979. *pp = pNode->pNext;
  94980. pNode->pNext = 0;
  94981. }
  94982. }
  94983. /*
  94984. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  94985. ** indicating that node has not yet been assigned a node number. It is
  94986. ** assigned a node number when nodeWrite() is called to write the
  94987. ** node contents out to the database.
  94988. */
  94989. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
  94990. RtreeNode *pNode;
  94991. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  94992. if( pNode ){
  94993. memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
  94994. pNode->zData = (u8 *)&pNode[1];
  94995. pNode->nRef = 1;
  94996. pNode->pParent = pParent;
  94997. pNode->isDirty = 1;
  94998. nodeReference(pParent);
  94999. }
  95000. return pNode;
  95001. }
  95002. /*
  95003. ** Obtain a reference to an r-tree node.
  95004. */
  95005. static int
  95006. nodeAcquire(
  95007. Rtree *pRtree, /* R-tree structure */
  95008. i64 iNode, /* Node number to load */
  95009. RtreeNode *pParent, /* Either the parent node or NULL */
  95010. RtreeNode **ppNode /* OUT: Acquired node */
  95011. ){
  95012. int rc;
  95013. RtreeNode *pNode;
  95014. /* Check if the requested node is already in the hash table. If so,
  95015. ** increase its reference count and return it.
  95016. */
  95017. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  95018. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  95019. if( pParent && !pNode->pParent ){
  95020. nodeReference(pParent);
  95021. pNode->pParent = pParent;
  95022. }
  95023. pNode->nRef++;
  95024. *ppNode = pNode;
  95025. return SQLITE_OK;
  95026. }
  95027. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  95028. if( !pNode ){
  95029. *ppNode = 0;
  95030. return SQLITE_NOMEM;
  95031. }
  95032. pNode->pParent = pParent;
  95033. pNode->zData = (u8 *)&pNode[1];
  95034. pNode->nRef = 1;
  95035. pNode->iNode = iNode;
  95036. pNode->isDirty = 0;
  95037. pNode->pNext = 0;
  95038. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  95039. rc = sqlite3_step(pRtree->pReadNode);
  95040. if( rc==SQLITE_ROW ){
  95041. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  95042. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  95043. nodeReference(pParent);
  95044. }else{
  95045. sqlite3_free(pNode);
  95046. pNode = 0;
  95047. }
  95048. *ppNode = pNode;
  95049. rc = sqlite3_reset(pRtree->pReadNode);
  95050. if( rc==SQLITE_OK && iNode==1 ){
  95051. pRtree->iDepth = readInt16(pNode->zData);
  95052. }
  95053. assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
  95054. nodeHashInsert(pRtree, pNode);
  95055. return rc;
  95056. }
  95057. /*
  95058. ** Overwrite cell iCell of node pNode with the contents of pCell.
  95059. */
  95060. static void nodeOverwriteCell(
  95061. Rtree *pRtree,
  95062. RtreeNode *pNode,
  95063. RtreeCell *pCell,
  95064. int iCell
  95065. ){
  95066. int ii;
  95067. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  95068. p += writeInt64(p, pCell->iRowid);
  95069. for(ii=0; ii<(pRtree->nDim*2); ii++){
  95070. p += writeCoord(p, &pCell->aCoord[ii]);
  95071. }
  95072. pNode->isDirty = 1;
  95073. }
  95074. /*
  95075. ** Remove cell the cell with index iCell from node pNode.
  95076. */
  95077. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  95078. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  95079. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  95080. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  95081. memmove(pDst, pSrc, nByte);
  95082. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  95083. pNode->isDirty = 1;
  95084. }
  95085. /*
  95086. ** Insert the contents of cell pCell into node pNode. If the insert
  95087. ** is successful, return SQLITE_OK.
  95088. **
  95089. ** If there is not enough free space in pNode, return SQLITE_FULL.
  95090. */
  95091. static int
  95092. nodeInsertCell(
  95093. Rtree *pRtree,
  95094. RtreeNode *pNode,
  95095. RtreeCell *pCell
  95096. ){
  95097. int nCell; /* Current number of cells in pNode */
  95098. int nMaxCell; /* Maximum number of cells for pNode */
  95099. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  95100. nCell = NCELL(pNode);
  95101. assert(nCell<=nMaxCell);
  95102. if( nCell<nMaxCell ){
  95103. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  95104. writeInt16(&pNode->zData[2], nCell+1);
  95105. pNode->isDirty = 1;
  95106. }
  95107. return (nCell==nMaxCell);
  95108. }
  95109. /*
  95110. ** If the node is dirty, write it out to the database.
  95111. */
  95112. static int
  95113. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  95114. int rc = SQLITE_OK;
  95115. if( pNode->isDirty ){
  95116. sqlite3_stmt *p = pRtree->pWriteNode;
  95117. if( pNode->iNode ){
  95118. sqlite3_bind_int64(p, 1, pNode->iNode);
  95119. }else{
  95120. sqlite3_bind_null(p, 1);
  95121. }
  95122. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  95123. sqlite3_step(p);
  95124. pNode->isDirty = 0;
  95125. rc = sqlite3_reset(p);
  95126. if( pNode->iNode==0 && rc==SQLITE_OK ){
  95127. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  95128. nodeHashInsert(pRtree, pNode);
  95129. }
  95130. }
  95131. return rc;
  95132. }
  95133. /*
  95134. ** Release a reference to a node. If the node is dirty and the reference
  95135. ** count drops to zero, the node data is written to the database.
  95136. */
  95137. static int
  95138. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  95139. int rc = SQLITE_OK;
  95140. if( pNode ){
  95141. assert( pNode->nRef>0 );
  95142. pNode->nRef--;
  95143. if( pNode->nRef==0 ){
  95144. if( pNode->iNode==1 ){
  95145. pRtree->iDepth = -1;
  95146. }
  95147. if( pNode->pParent ){
  95148. rc = nodeRelease(pRtree, pNode->pParent);
  95149. }
  95150. if( rc==SQLITE_OK ){
  95151. rc = nodeWrite(pRtree, pNode);
  95152. }
  95153. nodeHashDelete(pRtree, pNode);
  95154. sqlite3_free(pNode);
  95155. }
  95156. }
  95157. return rc;
  95158. }
  95159. /*
  95160. ** Return the 64-bit integer value associated with cell iCell of
  95161. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  95162. ** an internal node, then the 64-bit integer is a child page number.
  95163. */
  95164. static i64 nodeGetRowid(
  95165. Rtree *pRtree,
  95166. RtreeNode *pNode,
  95167. int iCell
  95168. ){
  95169. assert( iCell<NCELL(pNode) );
  95170. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  95171. }
  95172. /*
  95173. ** Return coordinate iCoord from cell iCell in node pNode.
  95174. */
  95175. static void nodeGetCoord(
  95176. Rtree *pRtree,
  95177. RtreeNode *pNode,
  95178. int iCell,
  95179. int iCoord,
  95180. RtreeCoord *pCoord /* Space to write result to */
  95181. ){
  95182. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  95183. }
  95184. /*
  95185. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  95186. ** to by pCell with the results.
  95187. */
  95188. static void nodeGetCell(
  95189. Rtree *pRtree,
  95190. RtreeNode *pNode,
  95191. int iCell,
  95192. RtreeCell *pCell
  95193. ){
  95194. int ii;
  95195. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  95196. for(ii=0; ii<pRtree->nDim*2; ii++){
  95197. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  95198. }
  95199. }
  95200. /* Forward declaration for the function that does the work of
  95201. ** the virtual table module xCreate() and xConnect() methods.
  95202. */
  95203. static int rtreeInit(
  95204. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  95205. );
  95206. /*
  95207. ** Rtree virtual table module xCreate method.
  95208. */
  95209. static int rtreeCreate(
  95210. sqlite3 *db,
  95211. void *pAux,
  95212. int argc, const char *const*argv,
  95213. sqlite3_vtab **ppVtab,
  95214. char **pzErr
  95215. ){
  95216. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  95217. }
  95218. /*
  95219. ** Rtree virtual table module xConnect method.
  95220. */
  95221. static int rtreeConnect(
  95222. sqlite3 *db,
  95223. void *pAux,
  95224. int argc, const char *const*argv,
  95225. sqlite3_vtab **ppVtab,
  95226. char **pzErr
  95227. ){
  95228. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  95229. }
  95230. /*
  95231. ** Increment the r-tree reference count.
  95232. */
  95233. static void rtreeReference(Rtree *pRtree){
  95234. pRtree->nBusy++;
  95235. }
  95236. /*
  95237. ** Decrement the r-tree reference count. When the reference count reaches
  95238. ** zero the structure is deleted.
  95239. */
  95240. static void rtreeRelease(Rtree *pRtree){
  95241. pRtree->nBusy--;
  95242. if( pRtree->nBusy==0 ){
  95243. sqlite3_finalize(pRtree->pReadNode);
  95244. sqlite3_finalize(pRtree->pWriteNode);
  95245. sqlite3_finalize(pRtree->pDeleteNode);
  95246. sqlite3_finalize(pRtree->pReadRowid);
  95247. sqlite3_finalize(pRtree->pWriteRowid);
  95248. sqlite3_finalize(pRtree->pDeleteRowid);
  95249. sqlite3_finalize(pRtree->pReadParent);
  95250. sqlite3_finalize(pRtree->pWriteParent);
  95251. sqlite3_finalize(pRtree->pDeleteParent);
  95252. sqlite3_free(pRtree);
  95253. }
  95254. }
  95255. /*
  95256. ** Rtree virtual table module xDisconnect method.
  95257. */
  95258. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  95259. rtreeRelease((Rtree *)pVtab);
  95260. return SQLITE_OK;
  95261. }
  95262. /*
  95263. ** Rtree virtual table module xDestroy method.
  95264. */
  95265. static int rtreeDestroy(sqlite3_vtab *pVtab){
  95266. Rtree *pRtree = (Rtree *)pVtab;
  95267. int rc;
  95268. char *zCreate = sqlite3_mprintf(
  95269. "DROP TABLE '%q'.'%q_node';"
  95270. "DROP TABLE '%q'.'%q_rowid';"
  95271. "DROP TABLE '%q'.'%q_parent';",
  95272. pRtree->zDb, pRtree->zName,
  95273. pRtree->zDb, pRtree->zName,
  95274. pRtree->zDb, pRtree->zName
  95275. );
  95276. if( !zCreate ){
  95277. rc = SQLITE_NOMEM;
  95278. }else{
  95279. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  95280. sqlite3_free(zCreate);
  95281. }
  95282. if( rc==SQLITE_OK ){
  95283. rtreeRelease(pRtree);
  95284. }
  95285. return rc;
  95286. }
  95287. /*
  95288. ** Rtree virtual table module xOpen method.
  95289. */
  95290. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  95291. int rc = SQLITE_NOMEM;
  95292. RtreeCursor *pCsr;
  95293. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  95294. if( pCsr ){
  95295. memset(pCsr, 0, sizeof(RtreeCursor));
  95296. pCsr->base.pVtab = pVTab;
  95297. rc = SQLITE_OK;
  95298. }
  95299. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  95300. return rc;
  95301. }
  95302. /*
  95303. ** Rtree virtual table module xClose method.
  95304. */
  95305. static int rtreeClose(sqlite3_vtab_cursor *cur){
  95306. Rtree *pRtree = (Rtree *)(cur->pVtab);
  95307. int rc;
  95308. RtreeCursor *pCsr = (RtreeCursor *)cur;
  95309. sqlite3_free(pCsr->aConstraint);
  95310. rc = nodeRelease(pRtree, pCsr->pNode);
  95311. sqlite3_free(pCsr);
  95312. return rc;
  95313. }
  95314. /*
  95315. ** Rtree virtual table module xEof method.
  95316. **
  95317. ** Return non-zero if the cursor does not currently point to a valid
  95318. ** record (i.e if the scan has finished), or zero otherwise.
  95319. */
  95320. static int rtreeEof(sqlite3_vtab_cursor *cur){
  95321. RtreeCursor *pCsr = (RtreeCursor *)cur;
  95322. return (pCsr->pNode==0);
  95323. }
  95324. /*
  95325. ** Cursor pCursor currently points to a cell in a non-leaf page.
  95326. ** Return true if the sub-tree headed by the cell is filtered
  95327. ** (excluded) by the constraints in the pCursor->aConstraint[]
  95328. ** array, or false otherwise.
  95329. */
  95330. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
  95331. RtreeCell cell;
  95332. int ii;
  95333. int bRes = 0;
  95334. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  95335. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  95336. RtreeConstraint *p = &pCursor->aConstraint[ii];
  95337. double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  95338. double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  95339. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  95340. || p->op==RTREE_GT || p->op==RTREE_EQ
  95341. );
  95342. switch( p->op ){
  95343. case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
  95344. case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
  95345. case RTREE_EQ:
  95346. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  95347. break;
  95348. }
  95349. }
  95350. return bRes;
  95351. }
  95352. /*
  95353. ** Return true if the cell that cursor pCursor currently points to
  95354. ** would be filtered (excluded) by the constraints in the
  95355. ** pCursor->aConstraint[] array, or false otherwise.
  95356. **
  95357. ** This function assumes that the cell is part of a leaf node.
  95358. */
  95359. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
  95360. RtreeCell cell;
  95361. int ii;
  95362. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  95363. for(ii=0; ii<pCursor->nConstraint; ii++){
  95364. RtreeConstraint *p = &pCursor->aConstraint[ii];
  95365. double coord = DCOORD(cell.aCoord[p->iCoord]);
  95366. int res;
  95367. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  95368. || p->op==RTREE_GT || p->op==RTREE_EQ
  95369. );
  95370. switch( p->op ){
  95371. case RTREE_LE: res = (coord<=p->rValue); break;
  95372. case RTREE_LT: res = (coord<p->rValue); break;
  95373. case RTREE_GE: res = (coord>=p->rValue); break;
  95374. case RTREE_GT: res = (coord>p->rValue); break;
  95375. case RTREE_EQ: res = (coord==p->rValue); break;
  95376. }
  95377. if( !res ) return 1;
  95378. }
  95379. return 0;
  95380. }
  95381. /*
  95382. ** Cursor pCursor currently points at a node that heads a sub-tree of
  95383. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  95384. ** to point to the left-most cell of the sub-tree that matches the
  95385. ** configured constraints.
  95386. */
  95387. static int descendToCell(
  95388. Rtree *pRtree,
  95389. RtreeCursor *pCursor,
  95390. int iHeight,
  95391. int *pEof /* OUT: Set to true if cannot descend */
  95392. ){
  95393. int isEof;
  95394. int rc;
  95395. int ii;
  95396. RtreeNode *pChild;
  95397. sqlite3_int64 iRowid;
  95398. RtreeNode *pSavedNode = pCursor->pNode;
  95399. int iSavedCell = pCursor->iCell;
  95400. assert( iHeight>=0 );
  95401. if( iHeight==0 ){
  95402. isEof = testRtreeEntry(pRtree, pCursor);
  95403. }else{
  95404. isEof = testRtreeCell(pRtree, pCursor);
  95405. }
  95406. if( isEof || iHeight==0 ){
  95407. *pEof = isEof;
  95408. return SQLITE_OK;
  95409. }
  95410. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  95411. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  95412. if( rc!=SQLITE_OK ){
  95413. return rc;
  95414. }
  95415. nodeRelease(pRtree, pCursor->pNode);
  95416. pCursor->pNode = pChild;
  95417. isEof = 1;
  95418. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  95419. pCursor->iCell = ii;
  95420. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  95421. if( rc!=SQLITE_OK ){
  95422. return rc;
  95423. }
  95424. }
  95425. if( isEof ){
  95426. assert( pCursor->pNode==pChild );
  95427. nodeReference(pSavedNode);
  95428. nodeRelease(pRtree, pChild);
  95429. pCursor->pNode = pSavedNode;
  95430. pCursor->iCell = iSavedCell;
  95431. }
  95432. *pEof = isEof;
  95433. return SQLITE_OK;
  95434. }
  95435. /*
  95436. ** One of the cells in node pNode is guaranteed to have a 64-bit
  95437. ** integer value equal to iRowid. Return the index of this cell.
  95438. */
  95439. static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
  95440. int ii;
  95441. for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
  95442. assert( ii<(NCELL(pNode)-1) );
  95443. }
  95444. return ii;
  95445. }
  95446. /*
  95447. ** Return the index of the cell containing a pointer to node pNode
  95448. ** in its parent. If pNode is the root node, return -1.
  95449. */
  95450. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
  95451. RtreeNode *pParent = pNode->pParent;
  95452. if( pParent ){
  95453. return nodeRowidIndex(pRtree, pParent, pNode->iNode);
  95454. }
  95455. return -1;
  95456. }
  95457. /*
  95458. ** Rtree virtual table module xNext method.
  95459. */
  95460. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  95461. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  95462. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  95463. int rc = SQLITE_OK;
  95464. if( pCsr->iStrategy==1 ){
  95465. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  95466. nodeRelease(pRtree, pCsr->pNode);
  95467. pCsr->pNode = 0;
  95468. }
  95469. else if( pCsr->pNode ){
  95470. /* Move to the next entry that matches the configured constraints. */
  95471. int iHeight = 0;
  95472. while( pCsr->pNode ){
  95473. RtreeNode *pNode = pCsr->pNode;
  95474. int nCell = NCELL(pNode);
  95475. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  95476. int isEof;
  95477. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  95478. if( rc!=SQLITE_OK || !isEof ){
  95479. return rc;
  95480. }
  95481. }
  95482. pCsr->pNode = pNode->pParent;
  95483. pCsr->iCell = nodeParentIndex(pRtree, pNode);
  95484. nodeReference(pCsr->pNode);
  95485. nodeRelease(pRtree, pNode);
  95486. iHeight++;
  95487. }
  95488. }
  95489. return rc;
  95490. }
  95491. /*
  95492. ** Rtree virtual table module xRowid method.
  95493. */
  95494. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  95495. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  95496. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  95497. assert(pCsr->pNode);
  95498. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  95499. return SQLITE_OK;
  95500. }
  95501. /*
  95502. ** Rtree virtual table module xColumn method.
  95503. */
  95504. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  95505. Rtree *pRtree = (Rtree *)cur->pVtab;
  95506. RtreeCursor *pCsr = (RtreeCursor *)cur;
  95507. if( i==0 ){
  95508. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  95509. sqlite3_result_int64(ctx, iRowid);
  95510. }else{
  95511. RtreeCoord c;
  95512. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  95513. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  95514. sqlite3_result_double(ctx, c.f);
  95515. }else{
  95516. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  95517. sqlite3_result_int(ctx, c.i);
  95518. }
  95519. }
  95520. return SQLITE_OK;
  95521. }
  95522. /*
  95523. ** Use nodeAcquire() to obtain the leaf node containing the record with
  95524. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  95525. ** return SQLITE_OK. If there is no such record in the table, set
  95526. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  95527. ** to zero and return an SQLite error code.
  95528. */
  95529. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  95530. int rc;
  95531. *ppLeaf = 0;
  95532. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  95533. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  95534. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  95535. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  95536. sqlite3_reset(pRtree->pReadRowid);
  95537. }else{
  95538. rc = sqlite3_reset(pRtree->pReadRowid);
  95539. }
  95540. return rc;
  95541. }
  95542. /*
  95543. ** Rtree virtual table module xFilter method.
  95544. */
  95545. static int rtreeFilter(
  95546. sqlite3_vtab_cursor *pVtabCursor,
  95547. int idxNum, const char *idxStr,
  95548. int argc, sqlite3_value **argv
  95549. ){
  95550. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  95551. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  95552. RtreeNode *pRoot = 0;
  95553. int ii;
  95554. int rc = SQLITE_OK;
  95555. rtreeReference(pRtree);
  95556. sqlite3_free(pCsr->aConstraint);
  95557. pCsr->aConstraint = 0;
  95558. pCsr->iStrategy = idxNum;
  95559. if( idxNum==1 ){
  95560. /* Special case - lookup by rowid. */
  95561. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  95562. i64 iRowid = sqlite3_value_int64(argv[0]);
  95563. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  95564. pCsr->pNode = pLeaf;
  95565. if( pLeaf && rc==SQLITE_OK ){
  95566. pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
  95567. }
  95568. }else{
  95569. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  95570. ** with the configured constraints.
  95571. */
  95572. if( argc>0 ){
  95573. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  95574. pCsr->nConstraint = argc;
  95575. if( !pCsr->aConstraint ){
  95576. rc = SQLITE_NOMEM;
  95577. }else{
  95578. assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
  95579. for(ii=0; ii<argc; ii++){
  95580. RtreeConstraint *p = &pCsr->aConstraint[ii];
  95581. p->op = idxStr[ii*2];
  95582. p->iCoord = idxStr[ii*2+1]-'a';
  95583. p->rValue = sqlite3_value_double(argv[ii]);
  95584. }
  95585. }
  95586. }
  95587. if( rc==SQLITE_OK ){
  95588. pCsr->pNode = 0;
  95589. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  95590. }
  95591. if( rc==SQLITE_OK ){
  95592. int isEof = 1;
  95593. int nCell = NCELL(pRoot);
  95594. pCsr->pNode = pRoot;
  95595. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  95596. assert( pCsr->pNode==pRoot );
  95597. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  95598. if( !isEof ){
  95599. break;
  95600. }
  95601. }
  95602. if( rc==SQLITE_OK && isEof ){
  95603. assert( pCsr->pNode==pRoot );
  95604. nodeRelease(pRtree, pRoot);
  95605. pCsr->pNode = 0;
  95606. }
  95607. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  95608. }
  95609. }
  95610. rtreeRelease(pRtree);
  95611. return rc;
  95612. }
  95613. /*
  95614. ** Rtree virtual table module xBestIndex method. There are three
  95615. ** table scan strategies to choose from (in order from most to
  95616. ** least desirable):
  95617. **
  95618. ** idxNum idxStr Strategy
  95619. ** ------------------------------------------------
  95620. ** 1 Unused Direct lookup by rowid.
  95621. ** 2 See below R-tree query.
  95622. ** 3 Unused Full table scan.
  95623. ** ------------------------------------------------
  95624. **
  95625. ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
  95626. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  95627. ** constraint used. The first two bytes of idxStr correspond to
  95628. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  95629. ** (argvIndex==1) etc.
  95630. **
  95631. ** The first of each pair of bytes in idxStr identifies the constraint
  95632. ** operator as follows:
  95633. **
  95634. ** Operator Byte Value
  95635. ** ----------------------
  95636. ** = 0x41 ('A')
  95637. ** <= 0x42 ('B')
  95638. ** < 0x43 ('C')
  95639. ** >= 0x44 ('D')
  95640. ** > 0x45 ('E')
  95641. ** ----------------------
  95642. **
  95643. ** The second of each pair of bytes identifies the coordinate column
  95644. ** to which the constraint applies. The leftmost coordinate column
  95645. ** is 'a', the second from the left 'b' etc.
  95646. */
  95647. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  95648. int rc = SQLITE_OK;
  95649. int ii, cCol;
  95650. int iIdx = 0;
  95651. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  95652. memset(zIdxStr, 0, sizeof(zIdxStr));
  95653. assert( pIdxInfo->idxStr==0 );
  95654. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  95655. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  95656. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  95657. /* We have an equality constraint on the rowid. Use strategy 1. */
  95658. int jj;
  95659. for(jj=0; jj<ii; jj++){
  95660. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  95661. pIdxInfo->aConstraintUsage[jj].omit = 0;
  95662. }
  95663. pIdxInfo->idxNum = 1;
  95664. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  95665. pIdxInfo->aConstraintUsage[jj].omit = 1;
  95666. /* This strategy involves a two rowid lookups on an B-Tree structures
  95667. ** and then a linear search of an R-Tree node. This should be
  95668. ** considered almost as quick as a direct rowid lookup (for which
  95669. ** sqlite uses an internal cost of 0.0).
  95670. */
  95671. pIdxInfo->estimatedCost = 10.0;
  95672. return SQLITE_OK;
  95673. }
  95674. if( p->usable && p->iColumn>0 ){
  95675. u8 op = 0;
  95676. switch( p->op ){
  95677. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  95678. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  95679. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  95680. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  95681. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  95682. }
  95683. if( op ){
  95684. /* Make sure this particular constraint has not been used before.
  95685. ** If it has been used before, ignore it.
  95686. **
  95687. ** A <= or < can be used if there is a prior >= or >.
  95688. ** A >= or > can be used if there is a prior < or <=.
  95689. ** A <= or < is disqualified if there is a prior <=, <, or ==.
  95690. ** A >= or > is disqualified if there is a prior >=, >, or ==.
  95691. ** A == is disqualifed if there is any prior constraint.
  95692. */
  95693. int j, opmsk;
  95694. static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
  95695. assert( compatible[RTREE_EQ & 7]==0 );
  95696. assert( compatible[RTREE_LT & 7]==1 );
  95697. assert( compatible[RTREE_LE & 7]==1 );
  95698. assert( compatible[RTREE_GT & 7]==2 );
  95699. assert( compatible[RTREE_GE & 7]==2 );
  95700. cCol = p->iColumn - 1 + 'a';
  95701. opmsk = compatible[op & 7];
  95702. for(j=0; j<iIdx; j+=2){
  95703. if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
  95704. op = 0;
  95705. break;
  95706. }
  95707. }
  95708. }
  95709. if( op ){
  95710. assert( iIdx<sizeof(zIdxStr)-1 );
  95711. zIdxStr[iIdx++] = op;
  95712. zIdxStr[iIdx++] = cCol;
  95713. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  95714. pIdxInfo->aConstraintUsage[ii].omit = 1;
  95715. }
  95716. }
  95717. }
  95718. pIdxInfo->idxNum = 2;
  95719. pIdxInfo->needToFreeIdxStr = 1;
  95720. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  95721. return SQLITE_NOMEM;
  95722. }
  95723. assert( iIdx>=0 );
  95724. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  95725. return rc;
  95726. }
  95727. /*
  95728. ** Return the N-dimensional volumn of the cell stored in *p.
  95729. */
  95730. static float cellArea(Rtree *pRtree, RtreeCell *p){
  95731. float area = 1.0;
  95732. int ii;
  95733. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95734. area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  95735. }
  95736. return area;
  95737. }
  95738. /*
  95739. ** Return the margin length of cell p. The margin length is the sum
  95740. ** of the objects size in each dimension.
  95741. */
  95742. static float cellMargin(Rtree *pRtree, RtreeCell *p){
  95743. float margin = 0.0;
  95744. int ii;
  95745. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95746. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  95747. }
  95748. return margin;
  95749. }
  95750. /*
  95751. ** Store the union of cells p1 and p2 in p1.
  95752. */
  95753. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  95754. int ii;
  95755. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  95756. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95757. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  95758. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  95759. }
  95760. }else{
  95761. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95762. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  95763. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  95764. }
  95765. }
  95766. }
  95767. /*
  95768. ** Return true if the area covered by p2 is a subset of the area covered
  95769. ** by p1. False otherwise.
  95770. */
  95771. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  95772. int ii;
  95773. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  95774. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  95775. RtreeCoord *a1 = &p1->aCoord[ii];
  95776. RtreeCoord *a2 = &p2->aCoord[ii];
  95777. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  95778. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  95779. ){
  95780. return 0;
  95781. }
  95782. }
  95783. return 1;
  95784. }
  95785. /*
  95786. ** Return the amount cell p would grow by if it were unioned with pCell.
  95787. */
  95788. static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  95789. float area;
  95790. RtreeCell cell;
  95791. memcpy(&cell, p, sizeof(RtreeCell));
  95792. area = cellArea(pRtree, &cell);
  95793. cellUnion(pRtree, &cell, pCell);
  95794. return (cellArea(pRtree, &cell)-area);
  95795. }
  95796. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  95797. static float cellOverlap(
  95798. Rtree *pRtree,
  95799. RtreeCell *p,
  95800. RtreeCell *aCell,
  95801. int nCell,
  95802. int iExclude
  95803. ){
  95804. int ii;
  95805. float overlap = 0.0;
  95806. for(ii=0; ii<nCell; ii++){
  95807. if( ii!=iExclude ){
  95808. int jj;
  95809. float o = 1.0;
  95810. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  95811. double x1;
  95812. double x2;
  95813. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  95814. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  95815. if( x2<x1 ){
  95816. o = 0.0;
  95817. break;
  95818. }else{
  95819. o = o * (x2-x1);
  95820. }
  95821. }
  95822. overlap += o;
  95823. }
  95824. }
  95825. return overlap;
  95826. }
  95827. #endif
  95828. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  95829. static float cellOverlapEnlargement(
  95830. Rtree *pRtree,
  95831. RtreeCell *p,
  95832. RtreeCell *pInsert,
  95833. RtreeCell *aCell,
  95834. int nCell,
  95835. int iExclude
  95836. ){
  95837. float before;
  95838. float after;
  95839. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  95840. cellUnion(pRtree, p, pInsert);
  95841. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  95842. return after-before;
  95843. }
  95844. #endif
  95845. /*
  95846. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  95847. ** ChooseSubTree in r*tree terminology.
  95848. */
  95849. static int ChooseLeaf(
  95850. Rtree *pRtree, /* Rtree table */
  95851. RtreeCell *pCell, /* Cell to insert into rtree */
  95852. int iHeight, /* Height of sub-tree rooted at pCell */
  95853. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  95854. ){
  95855. int rc;
  95856. int ii;
  95857. RtreeNode *pNode;
  95858. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  95859. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  95860. int iCell;
  95861. sqlite3_int64 iBest;
  95862. float fMinGrowth;
  95863. float fMinArea;
  95864. float fMinOverlap;
  95865. int nCell = NCELL(pNode);
  95866. RtreeCell cell;
  95867. RtreeNode *pChild;
  95868. RtreeCell *aCell = 0;
  95869. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  95870. if( ii==(pRtree->iDepth-1) ){
  95871. int jj;
  95872. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  95873. if( !aCell ){
  95874. rc = SQLITE_NOMEM;
  95875. nodeRelease(pRtree, pNode);
  95876. pNode = 0;
  95877. continue;
  95878. }
  95879. for(jj=0; jj<nCell; jj++){
  95880. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  95881. }
  95882. }
  95883. #endif
  95884. /* Select the child node which will be enlarged the least if pCell
  95885. ** is inserted into it. Resolve ties by choosing the entry with
  95886. ** the smallest area.
  95887. */
  95888. for(iCell=0; iCell<nCell; iCell++){
  95889. float growth;
  95890. float area;
  95891. float overlap = 0.0;
  95892. nodeGetCell(pRtree, pNode, iCell, &cell);
  95893. growth = cellGrowth(pRtree, &cell, pCell);
  95894. area = cellArea(pRtree, &cell);
  95895. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  95896. if( ii==(pRtree->iDepth-1) ){
  95897. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  95898. }
  95899. #endif
  95900. if( (iCell==0)
  95901. || (overlap<fMinOverlap)
  95902. || (overlap==fMinOverlap && growth<fMinGrowth)
  95903. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  95904. ){
  95905. fMinOverlap = overlap;
  95906. fMinGrowth = growth;
  95907. fMinArea = area;
  95908. iBest = cell.iRowid;
  95909. }
  95910. }
  95911. sqlite3_free(aCell);
  95912. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  95913. nodeRelease(pRtree, pNode);
  95914. pNode = pChild;
  95915. }
  95916. *ppLeaf = pNode;
  95917. return rc;
  95918. }
  95919. /*
  95920. ** A cell with the same content as pCell has just been inserted into
  95921. ** the node pNode. This function updates the bounding box cells in
  95922. ** all ancestor elements.
  95923. */
  95924. static void AdjustTree(
  95925. Rtree *pRtree, /* Rtree table */
  95926. RtreeNode *pNode, /* Adjust ancestry of this node. */
  95927. RtreeCell *pCell /* This cell was just inserted */
  95928. ){
  95929. RtreeNode *p = pNode;
  95930. while( p->pParent ){
  95931. RtreeCell cell;
  95932. RtreeNode *pParent = p->pParent;
  95933. int iCell = nodeParentIndex(pRtree, p);
  95934. nodeGetCell(pRtree, pParent, iCell, &cell);
  95935. if( !cellContains(pRtree, &cell, pCell) ){
  95936. cellUnion(pRtree, &cell, pCell);
  95937. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  95938. }
  95939. p = pParent;
  95940. }
  95941. }
  95942. /*
  95943. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  95944. */
  95945. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  95946. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  95947. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  95948. sqlite3_step(pRtree->pWriteRowid);
  95949. return sqlite3_reset(pRtree->pWriteRowid);
  95950. }
  95951. /*
  95952. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  95953. */
  95954. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  95955. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  95956. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  95957. sqlite3_step(pRtree->pWriteParent);
  95958. return sqlite3_reset(pRtree->pWriteParent);
  95959. }
  95960. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  95961. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  95962. /*
  95963. ** Implementation of the linear variant of the PickNext() function from
  95964. ** Guttman[84].
  95965. */
  95966. static RtreeCell *LinearPickNext(
  95967. Rtree *pRtree,
  95968. RtreeCell *aCell,
  95969. int nCell,
  95970. RtreeCell *pLeftBox,
  95971. RtreeCell *pRightBox,
  95972. int *aiUsed
  95973. ){
  95974. int ii;
  95975. for(ii=0; aiUsed[ii]; ii++);
  95976. aiUsed[ii] = 1;
  95977. return &aCell[ii];
  95978. }
  95979. /*
  95980. ** Implementation of the linear variant of the PickSeeds() function from
  95981. ** Guttman[84].
  95982. */
  95983. static void LinearPickSeeds(
  95984. Rtree *pRtree,
  95985. RtreeCell *aCell,
  95986. int nCell,
  95987. int *piLeftSeed,
  95988. int *piRightSeed
  95989. ){
  95990. int i;
  95991. int iLeftSeed = 0;
  95992. int iRightSeed = 1;
  95993. float maxNormalInnerWidth = 0.0;
  95994. /* Pick two "seed" cells from the array of cells. The algorithm used
  95995. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  95996. ** indices of the two seed cells in the array are stored in local
  95997. ** variables iLeftSeek and iRightSeed.
  95998. */
  95999. for(i=0; i<pRtree->nDim; i++){
  96000. float x1 = aCell[0].aCoord[i*2];
  96001. float x2 = aCell[0].aCoord[i*2+1];
  96002. float x3 = x1;
  96003. float x4 = x2;
  96004. int jj;
  96005. int iCellLeft = 0;
  96006. int iCellRight = 0;
  96007. for(jj=1; jj<nCell; jj++){
  96008. float left = aCell[jj].aCoord[i*2];
  96009. float right = aCell[jj].aCoord[i*2+1];
  96010. if( left<x1 ) x1 = left;
  96011. if( right>x4 ) x4 = right;
  96012. if( left>x3 ){
  96013. x3 = left;
  96014. iCellRight = jj;
  96015. }
  96016. if( right<x2 ){
  96017. x2 = right;
  96018. iCellLeft = jj;
  96019. }
  96020. }
  96021. if( x4!=x1 ){
  96022. float normalwidth = (x3 - x2) / (x4 - x1);
  96023. if( normalwidth>maxNormalInnerWidth ){
  96024. iLeftSeed = iCellLeft;
  96025. iRightSeed = iCellRight;
  96026. }
  96027. }
  96028. }
  96029. *piLeftSeed = iLeftSeed;
  96030. *piRightSeed = iRightSeed;
  96031. }
  96032. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  96033. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  96034. /*
  96035. ** Implementation of the quadratic variant of the PickNext() function from
  96036. ** Guttman[84].
  96037. */
  96038. static RtreeCell *QuadraticPickNext(
  96039. Rtree *pRtree,
  96040. RtreeCell *aCell,
  96041. int nCell,
  96042. RtreeCell *pLeftBox,
  96043. RtreeCell *pRightBox,
  96044. int *aiUsed
  96045. ){
  96046. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  96047. int iSelect = -1;
  96048. float fDiff;
  96049. int ii;
  96050. for(ii=0; ii<nCell; ii++){
  96051. if( aiUsed[ii]==0 ){
  96052. float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  96053. float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  96054. float diff = FABS(right-left);
  96055. if( iSelect<0 || diff>fDiff ){
  96056. fDiff = diff;
  96057. iSelect = ii;
  96058. }
  96059. }
  96060. }
  96061. aiUsed[iSelect] = 1;
  96062. return &aCell[iSelect];
  96063. }
  96064. /*
  96065. ** Implementation of the quadratic variant of the PickSeeds() function from
  96066. ** Guttman[84].
  96067. */
  96068. static void QuadraticPickSeeds(
  96069. Rtree *pRtree,
  96070. RtreeCell *aCell,
  96071. int nCell,
  96072. int *piLeftSeed,
  96073. int *piRightSeed
  96074. ){
  96075. int ii;
  96076. int jj;
  96077. int iLeftSeed = 0;
  96078. int iRightSeed = 1;
  96079. float fWaste = 0.0;
  96080. for(ii=0; ii<nCell; ii++){
  96081. for(jj=ii+1; jj<nCell; jj++){
  96082. float right = cellArea(pRtree, &aCell[jj]);
  96083. float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  96084. float waste = growth - right;
  96085. if( waste>fWaste ){
  96086. iLeftSeed = ii;
  96087. iRightSeed = jj;
  96088. fWaste = waste;
  96089. }
  96090. }
  96091. }
  96092. *piLeftSeed = iLeftSeed;
  96093. *piRightSeed = iRightSeed;
  96094. }
  96095. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  96096. /*
  96097. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  96098. ** nIdx. The aIdx array contains the set of integers from 0 to
  96099. ** (nIdx-1) in no particular order. This function sorts the values
  96100. ** in aIdx according to the indexed values in aDistance. For
  96101. ** example, assuming the inputs:
  96102. **
  96103. ** aIdx = { 0, 1, 2, 3 }
  96104. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  96105. **
  96106. ** this function sets the aIdx array to contain:
  96107. **
  96108. ** aIdx = { 0, 1, 2, 3 }
  96109. **
  96110. ** The aSpare array is used as temporary working space by the
  96111. ** sorting algorithm.
  96112. */
  96113. static void SortByDistance(
  96114. int *aIdx,
  96115. int nIdx,
  96116. float *aDistance,
  96117. int *aSpare
  96118. ){
  96119. if( nIdx>1 ){
  96120. int iLeft = 0;
  96121. int iRight = 0;
  96122. int nLeft = nIdx/2;
  96123. int nRight = nIdx-nLeft;
  96124. int *aLeft = aIdx;
  96125. int *aRight = &aIdx[nLeft];
  96126. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  96127. SortByDistance(aRight, nRight, aDistance, aSpare);
  96128. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  96129. aLeft = aSpare;
  96130. while( iLeft<nLeft || iRight<nRight ){
  96131. if( iLeft==nLeft ){
  96132. aIdx[iLeft+iRight] = aRight[iRight];
  96133. iRight++;
  96134. }else if( iRight==nRight ){
  96135. aIdx[iLeft+iRight] = aLeft[iLeft];
  96136. iLeft++;
  96137. }else{
  96138. float fLeft = aDistance[aLeft[iLeft]];
  96139. float fRight = aDistance[aRight[iRight]];
  96140. if( fLeft<fRight ){
  96141. aIdx[iLeft+iRight] = aLeft[iLeft];
  96142. iLeft++;
  96143. }else{
  96144. aIdx[iLeft+iRight] = aRight[iRight];
  96145. iRight++;
  96146. }
  96147. }
  96148. }
  96149. #if 0
  96150. /* Check that the sort worked */
  96151. {
  96152. int jj;
  96153. for(jj=1; jj<nIdx; jj++){
  96154. float left = aDistance[aIdx[jj-1]];
  96155. float right = aDistance[aIdx[jj]];
  96156. assert( left<=right );
  96157. }
  96158. }
  96159. #endif
  96160. }
  96161. }
  96162. /*
  96163. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  96164. ** nIdx. The aIdx array contains the set of integers from 0 to
  96165. ** (nIdx-1) in no particular order. This function sorts the values
  96166. ** in aIdx according to dimension iDim of the cells in aCell. The
  96167. ** minimum value of dimension iDim is considered first, the
  96168. ** maximum used to break ties.
  96169. **
  96170. ** The aSpare array is used as temporary working space by the
  96171. ** sorting algorithm.
  96172. */
  96173. static void SortByDimension(
  96174. Rtree *pRtree,
  96175. int *aIdx,
  96176. int nIdx,
  96177. int iDim,
  96178. RtreeCell *aCell,
  96179. int *aSpare
  96180. ){
  96181. if( nIdx>1 ){
  96182. int iLeft = 0;
  96183. int iRight = 0;
  96184. int nLeft = nIdx/2;
  96185. int nRight = nIdx-nLeft;
  96186. int *aLeft = aIdx;
  96187. int *aRight = &aIdx[nLeft];
  96188. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  96189. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  96190. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  96191. aLeft = aSpare;
  96192. while( iLeft<nLeft || iRight<nRight ){
  96193. double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  96194. double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  96195. double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  96196. double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  96197. if( (iLeft!=nLeft) && ((iRight==nRight)
  96198. || (xleft1<xright1)
  96199. || (xleft1==xright1 && xleft2<xright2)
  96200. )){
  96201. aIdx[iLeft+iRight] = aLeft[iLeft];
  96202. iLeft++;
  96203. }else{
  96204. aIdx[iLeft+iRight] = aRight[iRight];
  96205. iRight++;
  96206. }
  96207. }
  96208. #if 0
  96209. /* Check that the sort worked */
  96210. {
  96211. int jj;
  96212. for(jj=1; jj<nIdx; jj++){
  96213. float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  96214. float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  96215. float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  96216. float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  96217. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  96218. }
  96219. }
  96220. #endif
  96221. }
  96222. }
  96223. #if VARIANT_RSTARTREE_SPLIT
  96224. /*
  96225. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  96226. */
  96227. static int splitNodeStartree(
  96228. Rtree *pRtree,
  96229. RtreeCell *aCell,
  96230. int nCell,
  96231. RtreeNode *pLeft,
  96232. RtreeNode *pRight,
  96233. RtreeCell *pBboxLeft,
  96234. RtreeCell *pBboxRight
  96235. ){
  96236. int **aaSorted;
  96237. int *aSpare;
  96238. int ii;
  96239. int iBestDim;
  96240. int iBestSplit;
  96241. float fBestMargin;
  96242. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  96243. aaSorted = (int **)sqlite3_malloc(nByte);
  96244. if( !aaSorted ){
  96245. return SQLITE_NOMEM;
  96246. }
  96247. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  96248. memset(aaSorted, 0, nByte);
  96249. for(ii=0; ii<pRtree->nDim; ii++){
  96250. int jj;
  96251. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  96252. for(jj=0; jj<nCell; jj++){
  96253. aaSorted[ii][jj] = jj;
  96254. }
  96255. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  96256. }
  96257. for(ii=0; ii<pRtree->nDim; ii++){
  96258. float margin = 0.0;
  96259. float fBestOverlap;
  96260. float fBestArea;
  96261. int iBestLeft;
  96262. int nLeft;
  96263. for(
  96264. nLeft=RTREE_MINCELLS(pRtree);
  96265. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  96266. nLeft++
  96267. ){
  96268. RtreeCell left;
  96269. RtreeCell right;
  96270. int kk;
  96271. float overlap;
  96272. float area;
  96273. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  96274. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  96275. for(kk=1; kk<(nCell-1); kk++){
  96276. if( kk<nLeft ){
  96277. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  96278. }else{
  96279. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  96280. }
  96281. }
  96282. margin += cellMargin(pRtree, &left);
  96283. margin += cellMargin(pRtree, &right);
  96284. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  96285. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  96286. if( (nLeft==RTREE_MINCELLS(pRtree))
  96287. || (overlap<fBestOverlap)
  96288. || (overlap==fBestOverlap && area<fBestArea)
  96289. ){
  96290. iBestLeft = nLeft;
  96291. fBestOverlap = overlap;
  96292. fBestArea = area;
  96293. }
  96294. }
  96295. if( ii==0 || margin<fBestMargin ){
  96296. iBestDim = ii;
  96297. fBestMargin = margin;
  96298. iBestSplit = iBestLeft;
  96299. }
  96300. }
  96301. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  96302. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  96303. for(ii=0; ii<nCell; ii++){
  96304. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  96305. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  96306. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  96307. nodeInsertCell(pRtree, pTarget, pCell);
  96308. cellUnion(pRtree, pBbox, pCell);
  96309. }
  96310. sqlite3_free(aaSorted);
  96311. return SQLITE_OK;
  96312. }
  96313. #endif
  96314. #if VARIANT_GUTTMAN_SPLIT
  96315. /*
  96316. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  96317. */
  96318. static int splitNodeGuttman(
  96319. Rtree *pRtree,
  96320. RtreeCell *aCell,
  96321. int nCell,
  96322. RtreeNode *pLeft,
  96323. RtreeNode *pRight,
  96324. RtreeCell *pBboxLeft,
  96325. RtreeCell *pBboxRight
  96326. ){
  96327. int iLeftSeed = 0;
  96328. int iRightSeed = 1;
  96329. int *aiUsed;
  96330. int i;
  96331. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  96332. memset(aiUsed, 0, sizeof(int)*nCell);
  96333. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  96334. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  96335. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  96336. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  96337. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  96338. aiUsed[iLeftSeed] = 1;
  96339. aiUsed[iRightSeed] = 1;
  96340. for(i=nCell-2; i>0; i--){
  96341. RtreeCell *pNext;
  96342. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  96343. float diff =
  96344. cellGrowth(pRtree, pBboxLeft, pNext) -
  96345. cellGrowth(pRtree, pBboxRight, pNext)
  96346. ;
  96347. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  96348. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  96349. ){
  96350. nodeInsertCell(pRtree, pRight, pNext);
  96351. cellUnion(pRtree, pBboxRight, pNext);
  96352. }else{
  96353. nodeInsertCell(pRtree, pLeft, pNext);
  96354. cellUnion(pRtree, pBboxLeft, pNext);
  96355. }
  96356. }
  96357. sqlite3_free(aiUsed);
  96358. return SQLITE_OK;
  96359. }
  96360. #endif
  96361. static int updateMapping(
  96362. Rtree *pRtree,
  96363. i64 iRowid,
  96364. RtreeNode *pNode,
  96365. int iHeight
  96366. ){
  96367. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  96368. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  96369. if( iHeight>0 ){
  96370. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  96371. if( pChild ){
  96372. nodeRelease(pRtree, pChild->pParent);
  96373. nodeReference(pNode);
  96374. pChild->pParent = pNode;
  96375. }
  96376. }
  96377. return xSetMapping(pRtree, iRowid, pNode->iNode);
  96378. }
  96379. static int SplitNode(
  96380. Rtree *pRtree,
  96381. RtreeNode *pNode,
  96382. RtreeCell *pCell,
  96383. int iHeight
  96384. ){
  96385. int i;
  96386. int newCellIsRight = 0;
  96387. int rc = SQLITE_OK;
  96388. int nCell = NCELL(pNode);
  96389. RtreeCell *aCell;
  96390. int *aiUsed;
  96391. RtreeNode *pLeft = 0;
  96392. RtreeNode *pRight = 0;
  96393. RtreeCell leftbbox;
  96394. RtreeCell rightbbox;
  96395. /* Allocate an array and populate it with a copy of pCell and
  96396. ** all cells from node pLeft. Then zero the original node.
  96397. */
  96398. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  96399. if( !aCell ){
  96400. rc = SQLITE_NOMEM;
  96401. goto splitnode_out;
  96402. }
  96403. aiUsed = (int *)&aCell[nCell+1];
  96404. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  96405. for(i=0; i<nCell; i++){
  96406. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  96407. }
  96408. nodeZero(pRtree, pNode);
  96409. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  96410. nCell++;
  96411. if( pNode->iNode==1 ){
  96412. pRight = nodeNew(pRtree, pNode, 1);
  96413. pLeft = nodeNew(pRtree, pNode, 1);
  96414. pRtree->iDepth++;
  96415. pNode->isDirty = 1;
  96416. writeInt16(pNode->zData, pRtree->iDepth);
  96417. }else{
  96418. pLeft = pNode;
  96419. pRight = nodeNew(pRtree, pLeft->pParent, 1);
  96420. nodeReference(pLeft);
  96421. }
  96422. if( !pLeft || !pRight ){
  96423. rc = SQLITE_NOMEM;
  96424. goto splitnode_out;
  96425. }
  96426. memset(pLeft->zData, 0, pRtree->iNodeSize);
  96427. memset(pRight->zData, 0, pRtree->iNodeSize);
  96428. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  96429. if( rc!=SQLITE_OK ){
  96430. goto splitnode_out;
  96431. }
  96432. /* Ensure both child nodes have node numbers assigned to them. */
  96433. if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
  96434. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  96435. ){
  96436. goto splitnode_out;
  96437. }
  96438. rightbbox.iRowid = pRight->iNode;
  96439. leftbbox.iRowid = pLeft->iNode;
  96440. if( pNode->iNode==1 ){
  96441. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  96442. if( rc!=SQLITE_OK ){
  96443. goto splitnode_out;
  96444. }
  96445. }else{
  96446. RtreeNode *pParent = pLeft->pParent;
  96447. int iCell = nodeParentIndex(pRtree, pLeft);
  96448. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  96449. AdjustTree(pRtree, pParent, &leftbbox);
  96450. }
  96451. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  96452. goto splitnode_out;
  96453. }
  96454. for(i=0; i<NCELL(pRight); i++){
  96455. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  96456. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  96457. if( iRowid==pCell->iRowid ){
  96458. newCellIsRight = 1;
  96459. }
  96460. if( rc!=SQLITE_OK ){
  96461. goto splitnode_out;
  96462. }
  96463. }
  96464. if( pNode->iNode==1 ){
  96465. for(i=0; i<NCELL(pLeft); i++){
  96466. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  96467. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  96468. if( rc!=SQLITE_OK ){
  96469. goto splitnode_out;
  96470. }
  96471. }
  96472. }else if( newCellIsRight==0 ){
  96473. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  96474. }
  96475. if( rc==SQLITE_OK ){
  96476. rc = nodeRelease(pRtree, pRight);
  96477. pRight = 0;
  96478. }
  96479. if( rc==SQLITE_OK ){
  96480. rc = nodeRelease(pRtree, pLeft);
  96481. pLeft = 0;
  96482. }
  96483. splitnode_out:
  96484. nodeRelease(pRtree, pRight);
  96485. nodeRelease(pRtree, pLeft);
  96486. sqlite3_free(aCell);
  96487. return rc;
  96488. }
  96489. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  96490. int rc = SQLITE_OK;
  96491. if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
  96492. sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
  96493. if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
  96494. i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  96495. rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
  96496. }else{
  96497. rc = SQLITE_ERROR;
  96498. }
  96499. sqlite3_reset(pRtree->pReadParent);
  96500. if( rc==SQLITE_OK ){
  96501. rc = fixLeafParent(pRtree, pLeaf->pParent);
  96502. }
  96503. }
  96504. return rc;
  96505. }
  96506. static int deleteCell(Rtree *, RtreeNode *, int, int);
  96507. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  96508. int rc;
  96509. RtreeNode *pParent;
  96510. int iCell;
  96511. assert( pNode->nRef==1 );
  96512. /* Remove the entry in the parent cell. */
  96513. iCell = nodeParentIndex(pRtree, pNode);
  96514. pParent = pNode->pParent;
  96515. pNode->pParent = 0;
  96516. if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
  96517. || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
  96518. ){
  96519. return rc;
  96520. }
  96521. /* Remove the xxx_node entry. */
  96522. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  96523. sqlite3_step(pRtree->pDeleteNode);
  96524. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  96525. return rc;
  96526. }
  96527. /* Remove the xxx_parent entry. */
  96528. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  96529. sqlite3_step(pRtree->pDeleteParent);
  96530. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  96531. return rc;
  96532. }
  96533. /* Remove the node from the in-memory hash table and link it into
  96534. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  96535. */
  96536. nodeHashDelete(pRtree, pNode);
  96537. pNode->iNode = iHeight;
  96538. pNode->pNext = pRtree->pDeleted;
  96539. pNode->nRef++;
  96540. pRtree->pDeleted = pNode;
  96541. return SQLITE_OK;
  96542. }
  96543. static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  96544. RtreeNode *pParent = pNode->pParent;
  96545. if( pParent ){
  96546. int ii;
  96547. int nCell = NCELL(pNode);
  96548. RtreeCell box; /* Bounding box for pNode */
  96549. nodeGetCell(pRtree, pNode, 0, &box);
  96550. for(ii=1; ii<nCell; ii++){
  96551. RtreeCell cell;
  96552. nodeGetCell(pRtree, pNode, ii, &cell);
  96553. cellUnion(pRtree, &box, &cell);
  96554. }
  96555. box.iRowid = pNode->iNode;
  96556. ii = nodeParentIndex(pRtree, pNode);
  96557. nodeOverwriteCell(pRtree, pParent, &box, ii);
  96558. fixBoundingBox(pRtree, pParent);
  96559. }
  96560. }
  96561. /*
  96562. ** Delete the cell at index iCell of node pNode. After removing the
  96563. ** cell, adjust the r-tree data structure if required.
  96564. */
  96565. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  96566. int rc;
  96567. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  96568. return rc;
  96569. }
  96570. /* Remove the cell from the node. This call just moves bytes around
  96571. ** the in-memory node image, so it cannot fail.
  96572. */
  96573. nodeDeleteCell(pRtree, pNode, iCell);
  96574. /* If the node is not the tree root and now has less than the minimum
  96575. ** number of cells, remove it from the tree. Otherwise, update the
  96576. ** cell in the parent node so that it tightly contains the updated
  96577. ** node.
  96578. */
  96579. if( pNode->iNode!=1 ){
  96580. RtreeNode *pParent = pNode->pParent;
  96581. if( (pParent->iNode!=1 || NCELL(pParent)!=1)
  96582. && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
  96583. ){
  96584. rc = removeNode(pRtree, pNode, iHeight);
  96585. }else{
  96586. fixBoundingBox(pRtree, pNode);
  96587. }
  96588. }
  96589. return rc;
  96590. }
  96591. static int Reinsert(
  96592. Rtree *pRtree,
  96593. RtreeNode *pNode,
  96594. RtreeCell *pCell,
  96595. int iHeight
  96596. ){
  96597. int *aOrder;
  96598. int *aSpare;
  96599. RtreeCell *aCell;
  96600. float *aDistance;
  96601. int nCell;
  96602. float aCenterCoord[RTREE_MAX_DIMENSIONS];
  96603. int iDim;
  96604. int ii;
  96605. int rc = SQLITE_OK;
  96606. memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
  96607. nCell = NCELL(pNode)+1;
  96608. /* Allocate the buffers used by this operation. The allocation is
  96609. ** relinquished before this function returns.
  96610. */
  96611. aCell = (RtreeCell *)sqlite3_malloc(nCell * (
  96612. sizeof(RtreeCell) + /* aCell array */
  96613. sizeof(int) + /* aOrder array */
  96614. sizeof(int) + /* aSpare array */
  96615. sizeof(float) /* aDistance array */
  96616. ));
  96617. if( !aCell ){
  96618. return SQLITE_NOMEM;
  96619. }
  96620. aOrder = (int *)&aCell[nCell];
  96621. aSpare = (int *)&aOrder[nCell];
  96622. aDistance = (float *)&aSpare[nCell];
  96623. for(ii=0; ii<nCell; ii++){
  96624. if( ii==(nCell-1) ){
  96625. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  96626. }else{
  96627. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  96628. }
  96629. aOrder[ii] = ii;
  96630. for(iDim=0; iDim<pRtree->nDim; iDim++){
  96631. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  96632. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  96633. }
  96634. }
  96635. for(iDim=0; iDim<pRtree->nDim; iDim++){
  96636. aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
  96637. }
  96638. for(ii=0; ii<nCell; ii++){
  96639. aDistance[ii] = 0.0;
  96640. for(iDim=0; iDim<pRtree->nDim; iDim++){
  96641. float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  96642. DCOORD(aCell[ii].aCoord[iDim*2]);
  96643. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  96644. }
  96645. }
  96646. SortByDistance(aOrder, nCell, aDistance, aSpare);
  96647. nodeZero(pRtree, pNode);
  96648. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  96649. RtreeCell *p = &aCell[aOrder[ii]];
  96650. nodeInsertCell(pRtree, pNode, p);
  96651. if( p->iRowid==pCell->iRowid ){
  96652. if( iHeight==0 ){
  96653. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  96654. }else{
  96655. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  96656. }
  96657. }
  96658. }
  96659. if( rc==SQLITE_OK ){
  96660. fixBoundingBox(pRtree, pNode);
  96661. }
  96662. for(; rc==SQLITE_OK && ii<nCell; ii++){
  96663. /* Find a node to store this cell in. pNode->iNode currently contains
  96664. ** the height of the sub-tree headed by the cell.
  96665. */
  96666. RtreeNode *pInsert;
  96667. RtreeCell *p = &aCell[aOrder[ii]];
  96668. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  96669. if( rc==SQLITE_OK ){
  96670. int rc2;
  96671. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  96672. rc2 = nodeRelease(pRtree, pInsert);
  96673. if( rc==SQLITE_OK ){
  96674. rc = rc2;
  96675. }
  96676. }
  96677. }
  96678. sqlite3_free(aCell);
  96679. return rc;
  96680. }
  96681. /*
  96682. ** Insert cell pCell into node pNode. Node pNode is the head of a
  96683. ** subtree iHeight high (leaf nodes have iHeight==0).
  96684. */
  96685. static int rtreeInsertCell(
  96686. Rtree *pRtree,
  96687. RtreeNode *pNode,
  96688. RtreeCell *pCell,
  96689. int iHeight
  96690. ){
  96691. int rc = SQLITE_OK;
  96692. if( iHeight>0 ){
  96693. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  96694. if( pChild ){
  96695. nodeRelease(pRtree, pChild->pParent);
  96696. nodeReference(pNode);
  96697. pChild->pParent = pNode;
  96698. }
  96699. }
  96700. if( nodeInsertCell(pRtree, pNode, pCell) ){
  96701. #if VARIANT_RSTARTREE_REINSERT
  96702. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  96703. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  96704. }else{
  96705. pRtree->iReinsertHeight = iHeight;
  96706. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  96707. }
  96708. #else
  96709. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  96710. #endif
  96711. }else{
  96712. AdjustTree(pRtree, pNode, pCell);
  96713. if( iHeight==0 ){
  96714. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  96715. }else{
  96716. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  96717. }
  96718. }
  96719. return rc;
  96720. }
  96721. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  96722. int ii;
  96723. int rc = SQLITE_OK;
  96724. int nCell = NCELL(pNode);
  96725. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  96726. RtreeNode *pInsert;
  96727. RtreeCell cell;
  96728. nodeGetCell(pRtree, pNode, ii, &cell);
  96729. /* Find a node to store this cell in. pNode->iNode currently contains
  96730. ** the height of the sub-tree headed by the cell.
  96731. */
  96732. rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
  96733. if( rc==SQLITE_OK ){
  96734. int rc2;
  96735. rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
  96736. rc2 = nodeRelease(pRtree, pInsert);
  96737. if( rc==SQLITE_OK ){
  96738. rc = rc2;
  96739. }
  96740. }
  96741. }
  96742. return rc;
  96743. }
  96744. /*
  96745. ** Select a currently unused rowid for a new r-tree record.
  96746. */
  96747. static int newRowid(Rtree *pRtree, i64 *piRowid){
  96748. int rc;
  96749. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  96750. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  96751. sqlite3_step(pRtree->pWriteRowid);
  96752. rc = sqlite3_reset(pRtree->pWriteRowid);
  96753. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  96754. return rc;
  96755. }
  96756. #ifndef NDEBUG
  96757. static int hashIsEmpty(Rtree *pRtree){
  96758. int ii;
  96759. for(ii=0; ii<HASHSIZE; ii++){
  96760. assert( !pRtree->aHash[ii] );
  96761. }
  96762. return 1;
  96763. }
  96764. #endif
  96765. /*
  96766. ** The xUpdate method for rtree module virtual tables.
  96767. */
  96768. int rtreeUpdate(
  96769. sqlite3_vtab *pVtab,
  96770. int nData,
  96771. sqlite3_value **azData,
  96772. sqlite_int64 *pRowid
  96773. ){
  96774. Rtree *pRtree = (Rtree *)pVtab;
  96775. int rc = SQLITE_OK;
  96776. rtreeReference(pRtree);
  96777. assert(nData>=1);
  96778. assert(hashIsEmpty(pRtree));
  96779. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  96780. ** record to delete from the r-tree table. The following block does
  96781. ** just that.
  96782. */
  96783. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  96784. i64 iDelete; /* The rowid to delete */
  96785. RtreeNode *pLeaf; /* Leaf node containing record iDelete */
  96786. int iCell; /* Index of iDelete cell in pLeaf */
  96787. RtreeNode *pRoot;
  96788. /* Obtain a reference to the root node to initialise Rtree.iDepth */
  96789. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  96790. /* Obtain a reference to the leaf node that contains the entry
  96791. ** about to be deleted.
  96792. */
  96793. if( rc==SQLITE_OK ){
  96794. iDelete = sqlite3_value_int64(azData[0]);
  96795. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  96796. }
  96797. /* Delete the cell in question from the leaf node. */
  96798. if( rc==SQLITE_OK ){
  96799. int rc2;
  96800. iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
  96801. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  96802. rc2 = nodeRelease(pRtree, pLeaf);
  96803. if( rc==SQLITE_OK ){
  96804. rc = rc2;
  96805. }
  96806. }
  96807. /* Delete the corresponding entry in the <rtree>_rowid table. */
  96808. if( rc==SQLITE_OK ){
  96809. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  96810. sqlite3_step(pRtree->pDeleteRowid);
  96811. rc = sqlite3_reset(pRtree->pDeleteRowid);
  96812. }
  96813. /* Check if the root node now has exactly one child. If so, remove
  96814. ** it, schedule the contents of the child for reinsertion and
  96815. ** reduce the tree height by one.
  96816. **
  96817. ** This is equivalent to copying the contents of the child into
  96818. ** the root node (the operation that Gutman's paper says to perform
  96819. ** in this scenario).
  96820. */
  96821. if( rc==SQLITE_OK && pRtree->iDepth>0 ){
  96822. if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
  96823. RtreeNode *pChild;
  96824. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  96825. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  96826. if( rc==SQLITE_OK ){
  96827. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  96828. }
  96829. if( rc==SQLITE_OK ){
  96830. pRtree->iDepth--;
  96831. writeInt16(pRoot->zData, pRtree->iDepth);
  96832. pRoot->isDirty = 1;
  96833. }
  96834. }
  96835. }
  96836. /* Re-insert the contents of any underfull nodes removed from the tree. */
  96837. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  96838. if( rc==SQLITE_OK ){
  96839. rc = reinsertNodeContent(pRtree, pLeaf);
  96840. }
  96841. pRtree->pDeleted = pLeaf->pNext;
  96842. sqlite3_free(pLeaf);
  96843. }
  96844. /* Release the reference to the root node. */
  96845. if( rc==SQLITE_OK ){
  96846. rc = nodeRelease(pRtree, pRoot);
  96847. }else{
  96848. nodeRelease(pRtree, pRoot);
  96849. }
  96850. }
  96851. /* If the azData[] array contains more than one element, elements
  96852. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  96853. ** the r-tree structure.
  96854. */
  96855. if( rc==SQLITE_OK && nData>1 ){
  96856. /* Insert a new record into the r-tree */
  96857. RtreeCell cell;
  96858. int ii;
  96859. RtreeNode *pLeaf;
  96860. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  96861. assert( nData==(pRtree->nDim*2 + 3) );
  96862. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  96863. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  96864. cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
  96865. cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
  96866. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  96867. rc = SQLITE_CONSTRAINT;
  96868. goto constraint;
  96869. }
  96870. }
  96871. }else{
  96872. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  96873. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  96874. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  96875. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  96876. rc = SQLITE_CONSTRAINT;
  96877. goto constraint;
  96878. }
  96879. }
  96880. }
  96881. /* Figure out the rowid of the new row. */
  96882. if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
  96883. rc = newRowid(pRtree, &cell.iRowid);
  96884. }else{
  96885. cell.iRowid = sqlite3_value_int64(azData[2]);
  96886. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  96887. if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
  96888. sqlite3_reset(pRtree->pReadRowid);
  96889. rc = SQLITE_CONSTRAINT;
  96890. goto constraint;
  96891. }
  96892. rc = sqlite3_reset(pRtree->pReadRowid);
  96893. }
  96894. if( rc==SQLITE_OK ){
  96895. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  96896. }
  96897. if( rc==SQLITE_OK ){
  96898. int rc2;
  96899. pRtree->iReinsertHeight = -1;
  96900. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  96901. rc2 = nodeRelease(pRtree, pLeaf);
  96902. if( rc==SQLITE_OK ){
  96903. rc = rc2;
  96904. }
  96905. }
  96906. }
  96907. constraint:
  96908. rtreeRelease(pRtree);
  96909. return rc;
  96910. }
  96911. /*
  96912. ** The xRename method for rtree module virtual tables.
  96913. */
  96914. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  96915. Rtree *pRtree = (Rtree *)pVtab;
  96916. int rc = SQLITE_NOMEM;
  96917. char *zSql = sqlite3_mprintf(
  96918. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  96919. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  96920. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  96921. , pRtree->zDb, pRtree->zName, zNewName
  96922. , pRtree->zDb, pRtree->zName, zNewName
  96923. , pRtree->zDb, pRtree->zName, zNewName
  96924. );
  96925. if( zSql ){
  96926. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  96927. sqlite3_free(zSql);
  96928. }
  96929. return rc;
  96930. }
  96931. static sqlite3_module rtreeModule = {
  96932. 0, /* iVersion */
  96933. rtreeCreate, /* xCreate - create a table */
  96934. rtreeConnect, /* xConnect - connect to an existing table */
  96935. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  96936. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  96937. rtreeDestroy, /* xDestroy - Drop a table */
  96938. rtreeOpen, /* xOpen - open a cursor */
  96939. rtreeClose, /* xClose - close a cursor */
  96940. rtreeFilter, /* xFilter - configure scan constraints */
  96941. rtreeNext, /* xNext - advance a cursor */
  96942. rtreeEof, /* xEof */
  96943. rtreeColumn, /* xColumn - read data */
  96944. rtreeRowid, /* xRowid - read data */
  96945. rtreeUpdate, /* xUpdate - write data */
  96946. 0, /* xBegin - begin transaction */
  96947. 0, /* xSync - sync transaction */
  96948. 0, /* xCommit - commit transaction */
  96949. 0, /* xRollback - rollback transaction */
  96950. 0, /* xFindFunction - function overloading */
  96951. rtreeRename /* xRename - rename the table */
  96952. };
  96953. static int rtreeSqlInit(
  96954. Rtree *pRtree,
  96955. sqlite3 *db,
  96956. const char *zDb,
  96957. const char *zPrefix,
  96958. int isCreate
  96959. ){
  96960. int rc = SQLITE_OK;
  96961. #define N_STATEMENT 9
  96962. static const char *azSql[N_STATEMENT] = {
  96963. /* Read and write the xxx_node table */
  96964. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  96965. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  96966. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  96967. /* Read and write the xxx_rowid table */
  96968. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  96969. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  96970. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  96971. /* Read and write the xxx_parent table */
  96972. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  96973. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  96974. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  96975. };
  96976. sqlite3_stmt **appStmt[N_STATEMENT];
  96977. int i;
  96978. pRtree->db = db;
  96979. if( isCreate ){
  96980. char *zCreate = sqlite3_mprintf(
  96981. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  96982. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  96983. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  96984. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  96985. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  96986. );
  96987. if( !zCreate ){
  96988. return SQLITE_NOMEM;
  96989. }
  96990. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  96991. sqlite3_free(zCreate);
  96992. if( rc!=SQLITE_OK ){
  96993. return rc;
  96994. }
  96995. }
  96996. appStmt[0] = &pRtree->pReadNode;
  96997. appStmt[1] = &pRtree->pWriteNode;
  96998. appStmt[2] = &pRtree->pDeleteNode;
  96999. appStmt[3] = &pRtree->pReadRowid;
  97000. appStmt[4] = &pRtree->pWriteRowid;
  97001. appStmt[5] = &pRtree->pDeleteRowid;
  97002. appStmt[6] = &pRtree->pReadParent;
  97003. appStmt[7] = &pRtree->pWriteParent;
  97004. appStmt[8] = &pRtree->pDeleteParent;
  97005. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  97006. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  97007. if( zSql ){
  97008. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  97009. }else{
  97010. rc = SQLITE_NOMEM;
  97011. }
  97012. sqlite3_free(zSql);
  97013. }
  97014. return rc;
  97015. }
  97016. /*
  97017. ** This routine queries database handle db for the page-size used by
  97018. ** database zDb. If successful, the page-size in bytes is written to
  97019. ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
  97020. ** code is returned.
  97021. */
  97022. static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
  97023. int rc = SQLITE_NOMEM;
  97024. char *zSql;
  97025. sqlite3_stmt *pStmt = 0;
  97026. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
  97027. if( !zSql ){
  97028. return SQLITE_NOMEM;
  97029. }
  97030. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  97031. sqlite3_free(zSql);
  97032. if( rc!=SQLITE_OK ){
  97033. return rc;
  97034. }
  97035. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  97036. *piPageSize = sqlite3_column_int(pStmt, 0);
  97037. }
  97038. return sqlite3_finalize(pStmt);
  97039. }
  97040. /*
  97041. ** This function is the implementation of both the xConnect and xCreate
  97042. ** methods of the r-tree virtual table.
  97043. **
  97044. ** argv[0] -> module name
  97045. ** argv[1] -> database name
  97046. ** argv[2] -> table name
  97047. ** argv[...] -> column names...
  97048. */
  97049. static int rtreeInit(
  97050. sqlite3 *db, /* Database connection */
  97051. void *pAux, /* One of the RTREE_COORD_* constants */
  97052. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  97053. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  97054. char **pzErr, /* OUT: Error message, if any */
  97055. int isCreate /* True for xCreate, false for xConnect */
  97056. ){
  97057. int rc = SQLITE_OK;
  97058. int iPageSize = 0;
  97059. Rtree *pRtree;
  97060. int nDb; /* Length of string argv[1] */
  97061. int nName; /* Length of string argv[2] */
  97062. int eCoordType = (int)pAux;
  97063. const char *aErrMsg[] = {
  97064. 0, /* 0 */
  97065. "Wrong number of columns for an rtree table", /* 1 */
  97066. "Too few columns for an rtree table", /* 2 */
  97067. "Too many columns for an rtree table" /* 3 */
  97068. };
  97069. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  97070. if( aErrMsg[iErr] ){
  97071. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  97072. return SQLITE_ERROR;
  97073. }
  97074. rc = getPageSize(db, argv[1], &iPageSize);
  97075. if( rc!=SQLITE_OK ){
  97076. return rc;
  97077. }
  97078. /* Allocate the sqlite3_vtab structure */
  97079. nDb = strlen(argv[1]);
  97080. nName = strlen(argv[2]);
  97081. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  97082. if( !pRtree ){
  97083. return SQLITE_NOMEM;
  97084. }
  97085. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  97086. pRtree->nBusy = 1;
  97087. pRtree->base.pModule = &rtreeModule;
  97088. pRtree->zDb = (char *)&pRtree[1];
  97089. pRtree->zName = &pRtree->zDb[nDb+1];
  97090. pRtree->nDim = (argc-4)/2;
  97091. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  97092. pRtree->eCoordType = eCoordType;
  97093. memcpy(pRtree->zDb, argv[1], nDb);
  97094. memcpy(pRtree->zName, argv[2], nName);
  97095. /* Figure out the node size to use. By default, use 64 bytes less than
  97096. ** the database page-size. This ensures that each node is stored on
  97097. ** a single database page.
  97098. **
  97099. ** If the databasd page-size is so large that more than RTREE_MAXCELLS
  97100. ** entries would fit in a single node, use a smaller node-size.
  97101. */
  97102. pRtree->iNodeSize = iPageSize-64;
  97103. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  97104. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  97105. }
  97106. /* Create/Connect to the underlying relational database schema. If
  97107. ** that is successful, call sqlite3_declare_vtab() to configure
  97108. ** the r-tree table schema.
  97109. */
  97110. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  97111. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  97112. }else{
  97113. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  97114. char *zTmp;
  97115. int ii;
  97116. for(ii=4; zSql && ii<argc; ii++){
  97117. zTmp = zSql;
  97118. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  97119. sqlite3_free(zTmp);
  97120. }
  97121. if( zSql ){
  97122. zTmp = zSql;
  97123. zSql = sqlite3_mprintf("%s);", zTmp);
  97124. sqlite3_free(zTmp);
  97125. }
  97126. if( !zSql || sqlite3_declare_vtab(db, zSql) ){
  97127. rc = SQLITE_NOMEM;
  97128. }
  97129. sqlite3_free(zSql);
  97130. }
  97131. if( rc==SQLITE_OK ){
  97132. *ppVtab = (sqlite3_vtab *)pRtree;
  97133. }else{
  97134. rtreeRelease(pRtree);
  97135. }
  97136. return rc;
  97137. }
  97138. /*
  97139. ** Implementation of a scalar function that decodes r-tree nodes to
  97140. ** human readable strings. This can be used for debugging and analysis.
  97141. **
  97142. ** The scalar function takes two arguments, a blob of data containing
  97143. ** an r-tree node, and the number of dimensions the r-tree indexes.
  97144. ** For a two-dimensional r-tree structure called "rt", to deserialize
  97145. ** all nodes, a statement like:
  97146. **
  97147. ** SELECT rtreenode(2, data) FROM rt_node;
  97148. **
  97149. ** The human readable string takes the form of a Tcl list with one
  97150. ** entry for each cell in the r-tree node. Each entry is itself a
  97151. ** list, containing the 8-byte rowid/pageno followed by the
  97152. ** <num-dimension>*2 coordinates.
  97153. */
  97154. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  97155. char *zText = 0;
  97156. RtreeNode node;
  97157. Rtree tree;
  97158. int ii;
  97159. memset(&node, 0, sizeof(RtreeNode));
  97160. memset(&tree, 0, sizeof(Rtree));
  97161. tree.nDim = sqlite3_value_int(apArg[0]);
  97162. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  97163. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  97164. for(ii=0; ii<NCELL(&node); ii++){
  97165. char zCell[512];
  97166. int nCell = 0;
  97167. RtreeCell cell;
  97168. int jj;
  97169. nodeGetCell(&tree, &node, ii, &cell);
  97170. sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
  97171. nCell = strlen(zCell);
  97172. for(jj=0; jj<tree.nDim*2; jj++){
  97173. sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
  97174. nCell = strlen(zCell);
  97175. }
  97176. if( zText ){
  97177. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  97178. sqlite3_free(zText);
  97179. zText = zTextNew;
  97180. }else{
  97181. zText = sqlite3_mprintf("{%s}", zCell);
  97182. }
  97183. }
  97184. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  97185. }
  97186. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  97187. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  97188. || sqlite3_value_bytes(apArg[0])<2
  97189. ){
  97190. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  97191. }else{
  97192. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  97193. sqlite3_result_int(ctx, readInt16(zBlob));
  97194. }
  97195. }
  97196. /*
  97197. ** Register the r-tree module with database handle db. This creates the
  97198. ** virtual table module "rtree" and the debugging/analysis scalar
  97199. ** function "rtreenode".
  97200. */
  97201. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  97202. int rc = SQLITE_OK;
  97203. if( rc==SQLITE_OK ){
  97204. int utf8 = SQLITE_UTF8;
  97205. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  97206. }
  97207. if( rc==SQLITE_OK ){
  97208. int utf8 = SQLITE_UTF8;
  97209. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  97210. }
  97211. if( rc==SQLITE_OK ){
  97212. void *c = (void *)RTREE_COORD_REAL32;
  97213. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  97214. }
  97215. if( rc==SQLITE_OK ){
  97216. void *c = (void *)RTREE_COORD_INT32;
  97217. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  97218. }
  97219. return rc;
  97220. }
  97221. #if !SQLITE_CORE
  97222. SQLITE_API int sqlite3_extension_init(
  97223. sqlite3 *db,
  97224. char **pzErrMsg,
  97225. const sqlite3_api_routines *pApi
  97226. ){
  97227. SQLITE_EXTENSION_INIT2(pApi)
  97228. return sqlite3RtreeInit(db);
  97229. }
  97230. #endif
  97231. #endif
  97232. /************** End of rtree.c ***********************************************/
  97233. /************** Begin file icu.c *********************************************/
  97234. /*
  97235. ** 2007 May 6
  97236. **
  97237. ** The author disclaims copyright to this source code. In place of
  97238. ** a legal notice, here is a blessing:
  97239. **
  97240. ** May you do good and not evil.
  97241. ** May you find forgiveness for yourself and forgive others.
  97242. ** May you share freely, never taking more than you give.
  97243. **
  97244. *************************************************************************
  97245. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  97246. **
  97247. ** This file implements an integration between the ICU library
  97248. ** ("International Components for Unicode", an open-source library
  97249. ** for handling unicode data) and SQLite. The integration uses
  97250. ** ICU to provide the following to SQLite:
  97251. **
  97252. ** * An implementation of the SQL regexp() function (and hence REGEXP
  97253. ** operator) using the ICU uregex_XX() APIs.
  97254. **
  97255. ** * Implementations of the SQL scalar upper() and lower() functions
  97256. ** for case mapping.
  97257. **
  97258. ** * Integration of ICU and SQLite collation seqences.
  97259. **
  97260. ** * An implementation of the LIKE operator that uses ICU to
  97261. ** provide case-independent matching.
  97262. */
  97263. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  97264. /* Include ICU headers */
  97265. #include <unicode/utypes.h>
  97266. #include <unicode/uregex.h>
  97267. #include <unicode/ustring.h>
  97268. #include <unicode/ucol.h>
  97269. #ifndef SQLITE_CORE
  97270. SQLITE_EXTENSION_INIT1
  97271. #else
  97272. #endif
  97273. /*
  97274. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  97275. ** operator.
  97276. */
  97277. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  97278. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  97279. #endif
  97280. /*
  97281. ** Version of sqlite3_free() that is always a function, never a macro.
  97282. */
  97283. static void xFree(void *p){
  97284. sqlite3_free(p);
  97285. }
  97286. /*
  97287. ** Compare two UTF-8 strings for equality where the first string is
  97288. ** a "LIKE" expression. Return true (1) if they are the same and
  97289. ** false (0) if they are different.
  97290. */
  97291. static int icuLikeCompare(
  97292. const uint8_t *zPattern, /* LIKE pattern */
  97293. const uint8_t *zString, /* The UTF-8 string to compare against */
  97294. const UChar32 uEsc /* The escape character */
  97295. ){
  97296. static const int MATCH_ONE = (UChar32)'_';
  97297. static const int MATCH_ALL = (UChar32)'%';
  97298. int iPattern = 0; /* Current byte index in zPattern */
  97299. int iString = 0; /* Current byte index in zString */
  97300. int prevEscape = 0; /* True if the previous character was uEsc */
  97301. while( zPattern[iPattern]!=0 ){
  97302. /* Read (and consume) the next character from the input pattern. */
  97303. UChar32 uPattern;
  97304. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  97305. assert(uPattern!=0);
  97306. /* There are now 4 possibilities:
  97307. **
  97308. ** 1. uPattern is an unescaped match-all character "%",
  97309. ** 2. uPattern is an unescaped match-one character "_",
  97310. ** 3. uPattern is an unescaped escape character, or
  97311. ** 4. uPattern is to be handled as an ordinary character
  97312. */
  97313. if( !prevEscape && uPattern==MATCH_ALL ){
  97314. /* Case 1. */
  97315. uint8_t c;
  97316. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  97317. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  97318. ** test string.
  97319. */
  97320. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  97321. if( c==MATCH_ONE ){
  97322. if( zString[iString]==0 ) return 0;
  97323. U8_FWD_1_UNSAFE(zString, iString);
  97324. }
  97325. iPattern++;
  97326. }
  97327. if( zPattern[iPattern]==0 ) return 1;
  97328. while( zString[iString] ){
  97329. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  97330. return 1;
  97331. }
  97332. U8_FWD_1_UNSAFE(zString, iString);
  97333. }
  97334. return 0;
  97335. }else if( !prevEscape && uPattern==MATCH_ONE ){
  97336. /* Case 2. */
  97337. if( zString[iString]==0 ) return 0;
  97338. U8_FWD_1_UNSAFE(zString, iString);
  97339. }else if( !prevEscape && uPattern==uEsc){
  97340. /* Case 3. */
  97341. prevEscape = 1;
  97342. }else{
  97343. /* Case 4. */
  97344. UChar32 uString;
  97345. U8_NEXT_UNSAFE(zString, iString, uString);
  97346. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  97347. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  97348. if( uString!=uPattern ){
  97349. return 0;
  97350. }
  97351. prevEscape = 0;
  97352. }
  97353. }
  97354. return zString[iString]==0;
  97355. }
  97356. /*
  97357. ** Implementation of the like() SQL function. This function implements
  97358. ** the build-in LIKE operator. The first argument to the function is the
  97359. ** pattern and the second argument is the string. So, the SQL statements:
  97360. **
  97361. ** A LIKE B
  97362. **
  97363. ** is implemented as like(B, A). If there is an escape character E,
  97364. **
  97365. ** A LIKE B ESCAPE E
  97366. **
  97367. ** is mapped to like(B, A, E).
  97368. */
  97369. static void icuLikeFunc(
  97370. sqlite3_context *context,
  97371. int argc,
  97372. sqlite3_value **argv
  97373. ){
  97374. const unsigned char *zA = sqlite3_value_text(argv[0]);
  97375. const unsigned char *zB = sqlite3_value_text(argv[1]);
  97376. UChar32 uEsc = 0;
  97377. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  97378. ** of deep recursion and N*N behavior in patternCompare().
  97379. */
  97380. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  97381. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  97382. return;
  97383. }
  97384. if( argc==3 ){
  97385. /* The escape character string must consist of a single UTF-8 character.
  97386. ** Otherwise, return an error.
  97387. */
  97388. int nE= sqlite3_value_bytes(argv[2]);
  97389. const unsigned char *zE = sqlite3_value_text(argv[2]);
  97390. int i = 0;
  97391. if( zE==0 ) return;
  97392. U8_NEXT(zE, i, nE, uEsc);
  97393. if( i!=nE){
  97394. sqlite3_result_error(context,
  97395. "ESCAPE expression must be a single character", -1);
  97396. return;
  97397. }
  97398. }
  97399. if( zA && zB ){
  97400. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  97401. }
  97402. }
  97403. /*
  97404. ** This function is called when an ICU function called from within
  97405. ** the implementation of an SQL scalar function returns an error.
  97406. **
  97407. ** The scalar function context passed as the first argument is
  97408. ** loaded with an error message based on the following two args.
  97409. */
  97410. static void icuFunctionError(
  97411. sqlite3_context *pCtx, /* SQLite scalar function context */
  97412. const char *zName, /* Name of ICU function that failed */
  97413. UErrorCode e /* Error code returned by ICU function */
  97414. ){
  97415. char zBuf[128];
  97416. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  97417. zBuf[127] = '\0';
  97418. sqlite3_result_error(pCtx, zBuf, -1);
  97419. }
  97420. /*
  97421. ** Function to delete compiled regexp objects. Registered as
  97422. ** a destructor function with sqlite3_set_auxdata().
  97423. */
  97424. static void icuRegexpDelete(void *p){
  97425. URegularExpression *pExpr = (URegularExpression *)p;
  97426. uregex_close(pExpr);
  97427. }
  97428. /*
  97429. ** Implementation of SQLite REGEXP operator. This scalar function takes
  97430. ** two arguments. The first is a regular expression pattern to compile
  97431. ** the second is a string to match against that pattern. If either
  97432. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  97433. ** is 1 if the string matches the pattern, or 0 otherwise.
  97434. **
  97435. ** SQLite maps the regexp() function to the regexp() operator such
  97436. ** that the following two are equivalent:
  97437. **
  97438. ** zString REGEXP zPattern
  97439. ** regexp(zPattern, zString)
  97440. **
  97441. ** Uses the following ICU regexp APIs:
  97442. **
  97443. ** uregex_open()
  97444. ** uregex_matches()
  97445. ** uregex_close()
  97446. */
  97447. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  97448. UErrorCode status = U_ZERO_ERROR;
  97449. URegularExpression *pExpr;
  97450. UBool res;
  97451. const UChar *zString = sqlite3_value_text16(apArg[1]);
  97452. /* If the left hand side of the regexp operator is NULL,
  97453. ** then the result is also NULL.
  97454. */
  97455. if( !zString ){
  97456. return;
  97457. }
  97458. pExpr = sqlite3_get_auxdata(p, 0);
  97459. if( !pExpr ){
  97460. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  97461. if( !zPattern ){
  97462. return;
  97463. }
  97464. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  97465. if( U_SUCCESS(status) ){
  97466. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  97467. }else{
  97468. assert(!pExpr);
  97469. icuFunctionError(p, "uregex_open", status);
  97470. return;
  97471. }
  97472. }
  97473. /* Configure the text that the regular expression operates on. */
  97474. uregex_setText(pExpr, zString, -1, &status);
  97475. if( !U_SUCCESS(status) ){
  97476. icuFunctionError(p, "uregex_setText", status);
  97477. return;
  97478. }
  97479. /* Attempt the match */
  97480. res = uregex_matches(pExpr, 0, &status);
  97481. if( !U_SUCCESS(status) ){
  97482. icuFunctionError(p, "uregex_matches", status);
  97483. return;
  97484. }
  97485. /* Set the text that the regular expression operates on to a NULL
  97486. ** pointer. This is not really necessary, but it is tidier than
  97487. ** leaving the regular expression object configured with an invalid
  97488. ** pointer after this function returns.
  97489. */
  97490. uregex_setText(pExpr, 0, 0, &status);
  97491. /* Return 1 or 0. */
  97492. sqlite3_result_int(p, res ? 1 : 0);
  97493. }
  97494. /*
  97495. ** Implementations of scalar functions for case mapping - upper() and
  97496. ** lower(). Function upper() converts its input to upper-case (ABC).
  97497. ** Function lower() converts to lower-case (abc).
  97498. **
  97499. ** ICU provides two types of case mapping, "general" case mapping and
  97500. ** "language specific". Refer to ICU documentation for the differences
  97501. ** between the two.
  97502. **
  97503. ** To utilise "general" case mapping, the upper() or lower() scalar
  97504. ** functions are invoked with one argument:
  97505. **
  97506. ** upper('ABC') -> 'abc'
  97507. ** lower('abc') -> 'ABC'
  97508. **
  97509. ** To access ICU "language specific" case mapping, upper() or lower()
  97510. ** should be invoked with two arguments. The second argument is the name
  97511. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  97512. ** as the second argument is the same as invoking the 1 argument version
  97513. ** of upper() or lower().
  97514. **
  97515. ** lower('I', 'en_us') -> 'i'
  97516. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  97517. **
  97518. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  97519. */
  97520. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  97521. const UChar *zInput;
  97522. UChar *zOutput;
  97523. int nInput;
  97524. int nOutput;
  97525. UErrorCode status = U_ZERO_ERROR;
  97526. const char *zLocale = 0;
  97527. assert(nArg==1 || nArg==2);
  97528. if( nArg==2 ){
  97529. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  97530. }
  97531. zInput = sqlite3_value_text16(apArg[0]);
  97532. if( !zInput ){
  97533. return;
  97534. }
  97535. nInput = sqlite3_value_bytes16(apArg[0]);
  97536. nOutput = nInput * 2 + 2;
  97537. zOutput = sqlite3_malloc(nOutput);
  97538. if( !zOutput ){
  97539. return;
  97540. }
  97541. if( sqlite3_user_data(p) ){
  97542. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  97543. }else{
  97544. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  97545. }
  97546. if( !U_SUCCESS(status) ){
  97547. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  97548. return;
  97549. }
  97550. sqlite3_result_text16(p, zOutput, -1, xFree);
  97551. }
  97552. /*
  97553. ** Collation sequence destructor function. The pCtx argument points to
  97554. ** a UCollator structure previously allocated using ucol_open().
  97555. */
  97556. static void icuCollationDel(void *pCtx){
  97557. UCollator *p = (UCollator *)pCtx;
  97558. ucol_close(p);
  97559. }
  97560. /*
  97561. ** Collation sequence comparison function. The pCtx argument points to
  97562. ** a UCollator structure previously allocated using ucol_open().
  97563. */
  97564. static int icuCollationColl(
  97565. void *pCtx,
  97566. int nLeft,
  97567. const void *zLeft,
  97568. int nRight,
  97569. const void *zRight
  97570. ){
  97571. UCollationResult res;
  97572. UCollator *p = (UCollator *)pCtx;
  97573. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  97574. switch( res ){
  97575. case UCOL_LESS: return -1;
  97576. case UCOL_GREATER: return +1;
  97577. case UCOL_EQUAL: return 0;
  97578. }
  97579. assert(!"Unexpected return value from ucol_strcoll()");
  97580. return 0;
  97581. }
  97582. /*
  97583. ** Implementation of the scalar function icu_load_collation().
  97584. **
  97585. ** This scalar function is used to add ICU collation based collation
  97586. ** types to an SQLite database connection. It is intended to be called
  97587. ** as follows:
  97588. **
  97589. ** SELECT icu_load_collation(<locale>, <collation-name>);
  97590. **
  97591. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  97592. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  97593. ** collation sequence to create.
  97594. */
  97595. static void icuLoadCollation(
  97596. sqlite3_context *p,
  97597. int nArg,
  97598. sqlite3_value **apArg
  97599. ){
  97600. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  97601. UErrorCode status = U_ZERO_ERROR;
  97602. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  97603. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  97604. UCollator *pUCollator; /* ICU library collation object */
  97605. int rc; /* Return code from sqlite3_create_collation_x() */
  97606. assert(nArg==2);
  97607. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  97608. zName = (const char *)sqlite3_value_text(apArg[1]);
  97609. if( !zLocale || !zName ){
  97610. return;
  97611. }
  97612. pUCollator = ucol_open(zLocale, &status);
  97613. if( !U_SUCCESS(status) ){
  97614. icuFunctionError(p, "ucol_open", status);
  97615. return;
  97616. }
  97617. assert(p);
  97618. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  97619. icuCollationColl, icuCollationDel
  97620. );
  97621. if( rc!=SQLITE_OK ){
  97622. ucol_close(pUCollator);
  97623. sqlite3_result_error(p, "Error registering collation function", -1);
  97624. }
  97625. }
  97626. /*
  97627. ** Register the ICU extension functions with database db.
  97628. */
  97629. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  97630. struct IcuScalar {
  97631. const char *zName; /* Function name */
  97632. int nArg; /* Number of arguments */
  97633. int enc; /* Optimal text encoding */
  97634. void *pContext; /* sqlite3_user_data() context */
  97635. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  97636. } scalars[] = {
  97637. {"regexp",-1, SQLITE_ANY, 0, icuRegexpFunc},
  97638. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  97639. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  97640. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  97641. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  97642. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  97643. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  97644. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  97645. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  97646. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  97647. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  97648. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  97649. };
  97650. int rc = SQLITE_OK;
  97651. int i;
  97652. for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
  97653. struct IcuScalar *p = &scalars[i];
  97654. rc = sqlite3_create_function(
  97655. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  97656. );
  97657. }
  97658. return rc;
  97659. }
  97660. #if !SQLITE_CORE
  97661. SQLITE_API int sqlite3_extension_init(
  97662. sqlite3 *db,
  97663. char **pzErrMsg,
  97664. const sqlite3_api_routines *pApi
  97665. ){
  97666. SQLITE_EXTENSION_INIT2(pApi)
  97667. return sqlite3IcuInit(db);
  97668. }
  97669. #endif
  97670. #endif
  97671. /************** End of icu.c *************************************************/
  97672. /************** Begin file fts3_icu.c ****************************************/
  97673. /*
  97674. ** 2007 June 22
  97675. **
  97676. ** The author disclaims copyright to this source code. In place of
  97677. ** a legal notice, here is a blessing:
  97678. **
  97679. ** May you do good and not evil.
  97680. ** May you find forgiveness for yourself and forgive others.
  97681. ** May you share freely, never taking more than you give.
  97682. **
  97683. *************************************************************************
  97684. ** This file implements a tokenizer for fts3 based on the ICU library.
  97685. **
  97686. ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
  97687. */
  97688. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  97689. #ifdef SQLITE_ENABLE_ICU
  97690. #include <unicode/ubrk.h>
  97691. #include <unicode/utf16.h>
  97692. typedef struct IcuTokenizer IcuTokenizer;
  97693. typedef struct IcuCursor IcuCursor;
  97694. struct IcuTokenizer {
  97695. sqlite3_tokenizer base;
  97696. char *zLocale;
  97697. };
  97698. struct IcuCursor {
  97699. sqlite3_tokenizer_cursor base;
  97700. UBreakIterator *pIter; /* ICU break-iterator object */
  97701. int nChar; /* Number of UChar elements in pInput */
  97702. UChar *aChar; /* Copy of input using utf-16 encoding */
  97703. int *aOffset; /* Offsets of each character in utf-8 input */
  97704. int nBuffer;
  97705. char *zBuffer;
  97706. int iToken;
  97707. };
  97708. /*
  97709. ** Create a new tokenizer instance.
  97710. */
  97711. static int icuCreate(
  97712. int argc, /* Number of entries in argv[] */
  97713. const char * const *argv, /* Tokenizer creation arguments */
  97714. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  97715. ){
  97716. IcuTokenizer *p;
  97717. int n = 0;
  97718. if( argc>0 ){
  97719. n = strlen(argv[0])+1;
  97720. }
  97721. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  97722. if( !p ){
  97723. return SQLITE_NOMEM;
  97724. }
  97725. memset(p, 0, sizeof(IcuTokenizer));
  97726. if( n ){
  97727. p->zLocale = (char *)&p[1];
  97728. memcpy(p->zLocale, argv[0], n);
  97729. }
  97730. *ppTokenizer = (sqlite3_tokenizer *)p;
  97731. return SQLITE_OK;
  97732. }
  97733. /*
  97734. ** Destroy a tokenizer
  97735. */
  97736. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  97737. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  97738. sqlite3_free(p);
  97739. return SQLITE_OK;
  97740. }
  97741. /*
  97742. ** Prepare to begin tokenizing a particular string. The input
  97743. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  97744. ** used to incrementally tokenize this string is returned in
  97745. ** *ppCursor.
  97746. */
  97747. static int icuOpen(
  97748. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  97749. const char *zInput, /* Input string */
  97750. int nInput, /* Length of zInput in bytes */
  97751. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  97752. ){
  97753. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  97754. IcuCursor *pCsr;
  97755. const int32_t opt = U_FOLD_CASE_DEFAULT;
  97756. UErrorCode status = U_ZERO_ERROR;
  97757. int nChar;
  97758. UChar32 c;
  97759. int iInput = 0;
  97760. int iOut = 0;
  97761. *ppCursor = 0;
  97762. if( nInput<0 ){
  97763. nInput = strlen(zInput);
  97764. }
  97765. nChar = nInput+1;
  97766. pCsr = (IcuCursor *)sqlite3_malloc(
  97767. sizeof(IcuCursor) + /* IcuCursor */
  97768. nChar * sizeof(UChar) + /* IcuCursor.aChar[] */
  97769. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  97770. );
  97771. if( !pCsr ){
  97772. return SQLITE_NOMEM;
  97773. }
  97774. memset(pCsr, 0, sizeof(IcuCursor));
  97775. pCsr->aChar = (UChar *)&pCsr[1];
  97776. pCsr->aOffset = (int *)&pCsr->aChar[nChar];
  97777. pCsr->aOffset[iOut] = iInput;
  97778. U8_NEXT(zInput, iInput, nInput, c);
  97779. while( c>0 ){
  97780. int isError = 0;
  97781. c = u_foldCase(c, opt);
  97782. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  97783. if( isError ){
  97784. sqlite3_free(pCsr);
  97785. return SQLITE_ERROR;
  97786. }
  97787. pCsr->aOffset[iOut] = iInput;
  97788. if( iInput<nInput ){
  97789. U8_NEXT(zInput, iInput, nInput, c);
  97790. }else{
  97791. c = 0;
  97792. }
  97793. }
  97794. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  97795. if( !U_SUCCESS(status) ){
  97796. sqlite3_free(pCsr);
  97797. return SQLITE_ERROR;
  97798. }
  97799. pCsr->nChar = iOut;
  97800. ubrk_first(pCsr->pIter);
  97801. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  97802. return SQLITE_OK;
  97803. }
  97804. /*
  97805. ** Close a tokenization cursor previously opened by a call to icuOpen().
  97806. */
  97807. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  97808. IcuCursor *pCsr = (IcuCursor *)pCursor;
  97809. ubrk_close(pCsr->pIter);
  97810. sqlite3_free(pCsr->zBuffer);
  97811. sqlite3_free(pCsr);
  97812. return SQLITE_OK;
  97813. }
  97814. /*
  97815. ** Extract the next token from a tokenization cursor.
  97816. */
  97817. static int icuNext(
  97818. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  97819. const char **ppToken, /* OUT: *ppToken is the token text */
  97820. int *pnBytes, /* OUT: Number of bytes in token */
  97821. int *piStartOffset, /* OUT: Starting offset of token */
  97822. int *piEndOffset, /* OUT: Ending offset of token */
  97823. int *piPosition /* OUT: Position integer of token */
  97824. ){
  97825. IcuCursor *pCsr = (IcuCursor *)pCursor;
  97826. int iStart = 0;
  97827. int iEnd = 0;
  97828. int nByte = 0;
  97829. while( iStart==iEnd ){
  97830. UChar32 c;
  97831. iStart = ubrk_current(pCsr->pIter);
  97832. iEnd = ubrk_next(pCsr->pIter);
  97833. if( iEnd==UBRK_DONE ){
  97834. return SQLITE_DONE;
  97835. }
  97836. while( iStart<iEnd ){
  97837. int iWhite = iStart;
  97838. U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  97839. if( u_isspace(c) ){
  97840. iStart = iWhite;
  97841. }else{
  97842. break;
  97843. }
  97844. }
  97845. assert(iStart<=iEnd);
  97846. }
  97847. do {
  97848. UErrorCode status = U_ZERO_ERROR;
  97849. if( nByte ){
  97850. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  97851. if( !zNew ){
  97852. return SQLITE_NOMEM;
  97853. }
  97854. pCsr->zBuffer = zNew;
  97855. pCsr->nBuffer = nByte;
  97856. }
  97857. u_strToUTF8(
  97858. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  97859. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  97860. &status /* Output success/failure */
  97861. );
  97862. } while( nByte>pCsr->nBuffer );
  97863. *ppToken = pCsr->zBuffer;
  97864. *pnBytes = nByte;
  97865. *piStartOffset = pCsr->aOffset[iStart];
  97866. *piEndOffset = pCsr->aOffset[iEnd];
  97867. *piPosition = pCsr->iToken++;
  97868. return SQLITE_OK;
  97869. }
  97870. /*
  97871. ** The set of routines that implement the simple tokenizer
  97872. */
  97873. static const sqlite3_tokenizer_module icuTokenizerModule = {
  97874. 0, /* iVersion */
  97875. icuCreate, /* xCreate */
  97876. icuDestroy, /* xCreate */
  97877. icuOpen, /* xOpen */
  97878. icuClose, /* xClose */
  97879. icuNext, /* xNext */
  97880. };
  97881. /*
  97882. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  97883. */
  97884. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  97885. sqlite3_tokenizer_module const**ppModule
  97886. ){
  97887. *ppModule = &icuTokenizerModule;
  97888. }
  97889. #endif /* defined(SQLITE_ENABLE_ICU) */
  97890. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  97891. /************** End of fts3_icu.c ********************************************/
粤ICP备19079148号