sqlite3rbu.c 171 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448
  1. /*
  2. ** 2014 August 30
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. **
  13. **
  14. ** OVERVIEW
  15. **
  16. ** The RBU extension requires that the RBU update be packaged as an
  17. ** SQLite database. The tables it expects to find are described in
  18. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  19. ** that the user wishes to write to, a corresponding data_xyz table is
  20. ** created in the RBU database and populated with one row for each row to
  21. ** update, insert or delete from the target table.
  22. **
  23. ** The update proceeds in three stages:
  24. **
  25. ** 1) The database is updated. The modified database pages are written
  26. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  27. ** that it is named "<database>-oal" instead of "<database>-wal".
  28. ** Because regular SQLite clients do not look for file named
  29. ** "<database>-oal", they go on using the original database in
  30. ** rollback mode while the *-oal file is being generated.
  31. **
  32. ** During this stage RBU does not update the database by writing
  33. ** directly to the target tables. Instead it creates "imposter"
  34. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  35. ** to update each b-tree individually. All updates required by each
  36. ** b-tree are completed before moving on to the next, and all
  37. ** updates are done in sorted key order.
  38. **
  39. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  40. ** location using a call to rename(2). Before doing this the RBU
  41. ** module takes an EXCLUSIVE lock on the database file, ensuring
  42. ** that there are no other active readers.
  43. **
  44. ** Once the EXCLUSIVE lock is released, any other database readers
  45. ** detect the new *-wal file and read the database in wal mode. At
  46. ** this point they see the new version of the database - including
  47. ** the updates made as part of the RBU update.
  48. **
  49. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  50. ** as a regular database checkpoint, except that a single frame is
  51. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  52. ** handle is closed before the entire *-wal file is checkpointed,
  53. ** the checkpoint progress is saved in the RBU database and the
  54. ** checkpoint can be resumed by another RBU client at some point in
  55. ** the future.
  56. **
  57. ** POTENTIAL PROBLEMS
  58. **
  59. ** The rename() call might not be portable. And RBU is not currently
  60. ** syncing the directory after renaming the file.
  61. **
  62. ** When state is saved, any commit to the *-oal file and the commit to
  63. ** the RBU update database are not atomic. So if the power fails at the
  64. ** wrong moment they might get out of sync. As the main database will be
  65. ** committed before the RBU update database this will likely either just
  66. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  67. ** constraint violations).
  68. **
  69. ** If some client does modify the target database mid RBU update, or some
  70. ** other error occurs, the RBU extension will keep throwing errors. It's
  71. ** not really clear how to get out of this state. The system could just
  72. ** by delete the RBU update database and *-oal file and have the device
  73. ** download the update again and start over.
  74. **
  75. ** At present, for an UPDATE, both the new.* and old.* records are
  76. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  77. ** fields are collected. This means we're probably writing a lot more
  78. ** data to disk when saving the state of an ongoing update to the RBU
  79. ** update database than is strictly necessary.
  80. **
  81. */
  82. #include <assert.h>
  83. #include <string.h>
  84. #include <stdio.h>
  85. #include "sqlite3.h"
  86. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  87. #include "sqlite3rbu.h"
  88. #if defined(_WIN32_WCE)
  89. #include "windows.h"
  90. #endif
  91. /* Maximum number of prepared UPDATE statements held by this module */
  92. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  93. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  94. ** to enable checksum verification.
  95. */
  96. #ifndef RBU_ENABLE_DELTA_CKSUM
  97. # define RBU_ENABLE_DELTA_CKSUM 0
  98. #endif
  99. /*
  100. ** Swap two objects of type TYPE.
  101. */
  102. #if !defined(SQLITE_AMALGAMATION)
  103. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  104. #endif
  105. /*
  106. ** Name of the URI option that causes RBU to take an exclusive lock as
  107. ** part of the incremental checkpoint operation.
  108. */
  109. #define RBU_EXCLUSIVE_CHECKPOINT "rbu_exclusive_checkpoint"
  110. /*
  111. ** The rbu_state table is used to save the state of a partially applied
  112. ** update so that it can be resumed later. The table consists of integer
  113. ** keys mapped to values as follows:
  114. **
  115. ** RBU_STATE_STAGE:
  116. ** May be set to integer values 1, 2, 4 or 5. As follows:
  117. ** 1: the *-rbu file is currently under construction.
  118. ** 2: the *-rbu file has been constructed, but not yet moved
  119. ** to the *-wal path.
  120. ** 4: the checkpoint is underway.
  121. ** 5: the rbu update has been checkpointed.
  122. **
  123. ** RBU_STATE_TBL:
  124. ** Only valid if STAGE==1. The target database name of the table
  125. ** currently being written.
  126. **
  127. ** RBU_STATE_IDX:
  128. ** Only valid if STAGE==1. The target database name of the index
  129. ** currently being written, or NULL if the main table is currently being
  130. ** updated.
  131. **
  132. ** RBU_STATE_ROW:
  133. ** Only valid if STAGE==1. Number of rows already processed for the current
  134. ** table/index.
  135. **
  136. ** RBU_STATE_PROGRESS:
  137. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  138. ** rbu update.
  139. **
  140. ** RBU_STATE_CKPT:
  141. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  142. ** header created by recovering the *-wal file. This is used to detect
  143. ** cases when another client appends frames to the *-wal file in the
  144. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  145. ** be continued if this happens).
  146. **
  147. ** RBU_STATE_COOKIE:
  148. ** Valid if STAGE==1. The current change-counter cookie value in the
  149. ** target db file.
  150. **
  151. ** RBU_STATE_OALSZ:
  152. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  153. **
  154. ** RBU_STATE_DATATBL:
  155. ** Only valid if STAGE==1. The RBU database name of the table
  156. ** currently being read.
  157. */
  158. #define RBU_STATE_STAGE 1
  159. #define RBU_STATE_TBL 2
  160. #define RBU_STATE_IDX 3
  161. #define RBU_STATE_ROW 4
  162. #define RBU_STATE_PROGRESS 5
  163. #define RBU_STATE_CKPT 6
  164. #define RBU_STATE_COOKIE 7
  165. #define RBU_STATE_OALSZ 8
  166. #define RBU_STATE_PHASEONESTEP 9
  167. #define RBU_STATE_DATATBL 10
  168. #define RBU_STAGE_OAL 1
  169. #define RBU_STAGE_MOVE 2
  170. #define RBU_STAGE_CAPTURE 3
  171. #define RBU_STAGE_CKPT 4
  172. #define RBU_STAGE_DONE 5
  173. #define RBU_CREATE_STATE \
  174. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  175. typedef struct RbuFrame RbuFrame;
  176. typedef struct RbuObjIter RbuObjIter;
  177. typedef struct RbuState RbuState;
  178. typedef struct RbuSpan RbuSpan;
  179. typedef struct rbu_vfs rbu_vfs;
  180. typedef struct rbu_file rbu_file;
  181. typedef struct RbuUpdateStmt RbuUpdateStmt;
  182. #if !defined(SQLITE_AMALGAMATION)
  183. typedef unsigned int u32;
  184. typedef unsigned short u16;
  185. typedef unsigned char u8;
  186. typedef sqlite3_int64 i64;
  187. typedef sqlite3_uint64 u64;
  188. #endif
  189. /*
  190. ** These values must match the values defined in wal.c for the equivalent
  191. ** locks. These are not magic numbers as they are part of the SQLite file
  192. ** format.
  193. */
  194. #define WAL_LOCK_WRITE 0
  195. #define WAL_LOCK_CKPT 1
  196. #define WAL_LOCK_READ0 3
  197. #define SQLITE_FCNTL_RBUCNT 5149216
  198. /*
  199. ** A structure to store values read from the rbu_state table in memory.
  200. */
  201. struct RbuState {
  202. int eStage;
  203. char *zTbl;
  204. char *zDataTbl;
  205. char *zIdx;
  206. i64 iWalCksum;
  207. int nRow;
  208. i64 nProgress;
  209. u32 iCookie;
  210. i64 iOalSz;
  211. i64 nPhaseOneStep;
  212. };
  213. struct RbuUpdateStmt {
  214. char *zMask; /* Copy of update mask used with pUpdate */
  215. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  216. RbuUpdateStmt *pNext;
  217. };
  218. struct RbuSpan {
  219. const char *zSpan;
  220. int nSpan;
  221. };
  222. /*
  223. ** An iterator of this type is used to iterate through all objects in
  224. ** the target database that require updating. For each such table, the
  225. ** iterator visits, in order:
  226. **
  227. ** * the table itself,
  228. ** * each index of the table (zero or more points to visit), and
  229. ** * a special "cleanup table" state.
  230. **
  231. ** abIndexed:
  232. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  233. ** it points to an array of flags nTblCol elements in size. The flag is
  234. ** set for each column that is either a part of the PK or a part of an
  235. ** index. Or clear otherwise.
  236. **
  237. ** If there are one or more partial indexes on the table, all fields of
  238. ** this array set set to 1. This is because in that case, the module has
  239. ** no way to tell which fields will be required to add and remove entries
  240. ** from the partial indexes.
  241. **
  242. */
  243. struct RbuObjIter {
  244. sqlite3_stmt *pTblIter; /* Iterate through tables */
  245. sqlite3_stmt *pIdxIter; /* Index iterator */
  246. int nTblCol; /* Size of azTblCol[] array */
  247. char **azTblCol; /* Array of unquoted target column names */
  248. char **azTblType; /* Array of target column types */
  249. int *aiSrcOrder; /* src table col -> target table col */
  250. u8 *abTblPk; /* Array of flags, set on target PK columns */
  251. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  252. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  253. int eType; /* Table type - an RBU_PK_XXX value */
  254. /* Output variables. zTbl==0 implies EOF. */
  255. int bCleanup; /* True in "cleanup" state */
  256. const char *zTbl; /* Name of target db table */
  257. const char *zDataTbl; /* Name of rbu db table (or null) */
  258. const char *zIdx; /* Name of target db index (or null) */
  259. int iTnum; /* Root page of current object */
  260. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  261. int bUnique; /* Current index is unique */
  262. int nIndex; /* Number of aux. indexes on table zTbl */
  263. /* Statements created by rbuObjIterPrepareAll() */
  264. int nCol; /* Number of columns in current object */
  265. sqlite3_stmt *pSelect; /* Source data */
  266. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  267. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  268. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  269. int nIdxCol;
  270. RbuSpan *aIdxCol;
  271. char *zIdxSql;
  272. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  273. RbuUpdateStmt *pRbuUpdate;
  274. };
  275. /*
  276. ** Values for RbuObjIter.eType
  277. **
  278. ** 0: Table does not exist (error)
  279. ** 1: Table has an implicit rowid.
  280. ** 2: Table has an explicit IPK column.
  281. ** 3: Table has an external PK index.
  282. ** 4: Table is WITHOUT ROWID.
  283. ** 5: Table is a virtual table.
  284. */
  285. #define RBU_PK_NOTABLE 0
  286. #define RBU_PK_NONE 1
  287. #define RBU_PK_IPK 2
  288. #define RBU_PK_EXTERNAL 3
  289. #define RBU_PK_WITHOUT_ROWID 4
  290. #define RBU_PK_VTAB 5
  291. /*
  292. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  293. ** one of the following operations.
  294. */
  295. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  296. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  297. #define RBU_REPLACE 3 /* Delete and then insert a row */
  298. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  299. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  300. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  301. /*
  302. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  303. ** file should be copied to page iDbPage of the database file.
  304. */
  305. struct RbuFrame {
  306. u32 iDbPage;
  307. u32 iWalFrame;
  308. };
  309. #ifndef UNUSED_PARAMETER
  310. /*
  311. ** The following macros are used to suppress compiler warnings and to
  312. ** make it clear to human readers when a function parameter is deliberately
  313. ** left unused within the body of a function. This usually happens when
  314. ** a function is called via a function pointer. For example the
  315. ** implementation of an SQL aggregate step callback may not use the
  316. ** parameter indicating the number of arguments passed to the aggregate,
  317. ** if it knows that this is enforced elsewhere.
  318. **
  319. ** When a function parameter is not used at all within the body of a function,
  320. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  321. ** However, these macros may also be used to suppress warnings related to
  322. ** parameters that may or may not be used depending on compilation options.
  323. ** For example those parameters only used in assert() statements. In these
  324. ** cases the parameters are named as per the usual conventions.
  325. */
  326. #define UNUSED_PARAMETER(x) (void)(x)
  327. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  328. #endif
  329. /*
  330. ** RBU handle.
  331. **
  332. ** nPhaseOneStep:
  333. ** If the RBU database contains an rbu_count table, this value is set to
  334. ** a running estimate of the number of b-tree operations required to
  335. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  336. ** API to calculate the permyriadage progress of populating the *-oal file
  337. ** using the formula:
  338. **
  339. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  340. **
  341. ** nPhaseOneStep is initialized to the sum of:
  342. **
  343. ** nRow * (nIndex + 1)
  344. **
  345. ** for all source tables in the RBU database, where nRow is the number
  346. ** of rows in the source table and nIndex the number of indexes on the
  347. ** corresponding target database table.
  348. **
  349. ** This estimate is accurate if the RBU update consists entirely of
  350. ** INSERT operations. However, it is inaccurate if:
  351. **
  352. ** * the RBU update contains any UPDATE operations. If the PK specified
  353. ** for an UPDATE operation does not exist in the target table, then
  354. ** no b-tree operations are required on index b-trees. Or if the
  355. ** specified PK does exist, then (nIndex*2) such operations are
  356. ** required (one delete and one insert on each index b-tree).
  357. **
  358. ** * the RBU update contains any DELETE operations for which the specified
  359. ** PK does not exist. In this case no operations are required on index
  360. ** b-trees.
  361. **
  362. ** * the RBU update contains REPLACE operations. These are similar to
  363. ** UPDATE operations.
  364. **
  365. ** nPhaseOneStep is updated to account for the conditions above during the
  366. ** first pass of each source table. The updated nPhaseOneStep value is
  367. ** stored in the rbu_state table if the RBU update is suspended.
  368. */
  369. struct sqlite3rbu {
  370. int eStage; /* Value of RBU_STATE_STAGE field */
  371. sqlite3 *dbMain; /* target database handle */
  372. sqlite3 *dbRbu; /* rbu database handle */
  373. char *zTarget; /* Path to target db */
  374. char *zRbu; /* Path to rbu db */
  375. char *zState; /* Path to state db (or NULL if zRbu) */
  376. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  377. int rc; /* Value returned by last rbu_step() call */
  378. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  379. int nStep; /* Rows processed for current object */
  380. sqlite3_int64 nProgress; /* Rows processed for all objects */
  381. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  382. const char *zVfsName; /* Name of automatically created rbu vfs */
  383. rbu_file *pTargetFd; /* File handle open on target db */
  384. int nPagePerSector; /* Pages per sector for pTargetFd */
  385. i64 iOalSz;
  386. i64 nPhaseOneStep;
  387. void *pRenameArg;
  388. int (*xRename)(void*, const char*, const char*);
  389. /* The following state variables are used as part of the incremental
  390. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  391. ** function rbuSetupCheckpoint() for details. */
  392. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  393. u32 mLock;
  394. int nFrame; /* Entries in aFrame[] array */
  395. int nFrameAlloc; /* Allocated size of aFrame[] array */
  396. RbuFrame *aFrame;
  397. int pgsz;
  398. u8 *aBuf;
  399. i64 iWalCksum;
  400. i64 szTemp; /* Current size of all temp files in use */
  401. i64 szTempLimit; /* Total size limit for temp files */
  402. /* Used in RBU vacuum mode only */
  403. int nRbu; /* Number of RBU VFS in the stack */
  404. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  405. };
  406. /*
  407. ** An rbu VFS is implemented using an instance of this structure.
  408. **
  409. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  410. ** It is NULL for RBU VFS objects created explicitly using
  411. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  412. ** space used by the RBU handle.
  413. */
  414. struct rbu_vfs {
  415. sqlite3_vfs base; /* rbu VFS shim methods */
  416. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  417. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  418. sqlite3rbu *pRbu; /* Owner RBU object */
  419. rbu_file *pMain; /* List of main db files */
  420. rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */
  421. };
  422. /*
  423. ** Each file opened by an rbu VFS is represented by an instance of
  424. ** the following structure.
  425. **
  426. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  427. ** "sz" is set to the current size of the database file.
  428. */
  429. struct rbu_file {
  430. sqlite3_file base; /* sqlite3_file methods */
  431. sqlite3_file *pReal; /* Underlying file handle */
  432. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  433. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  434. i64 sz; /* Size of file in bytes (temp only) */
  435. int openFlags; /* Flags this file was opened with */
  436. u32 iCookie; /* Cookie value for main db files */
  437. u8 iWriteVer; /* "write-version" value for main db files */
  438. u8 bNolock; /* True to fail EXCLUSIVE locks */
  439. int nShm; /* Number of entries in apShm[] array */
  440. char **apShm; /* Array of mmap'd *-shm regions */
  441. char *zDel; /* Delete this when closing file */
  442. const char *zWal; /* Wal filename for this main db file */
  443. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  444. rbu_file *pMainNext; /* Next MAIN_DB file */
  445. rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */
  446. };
  447. /*
  448. ** True for an RBU vacuum handle, or false otherwise.
  449. */
  450. #define rbuIsVacuum(p) ((p)->zTarget==0)
  451. /*************************************************************************
  452. ** The following three functions, found below:
  453. **
  454. ** rbuDeltaGetInt()
  455. ** rbuDeltaChecksum()
  456. ** rbuDeltaApply()
  457. **
  458. ** are lifted from the fossil source code (http://fossil-scm.org). They
  459. ** are used to implement the scalar SQL function rbu_fossil_delta().
  460. */
  461. /*
  462. ** Read bytes from *pz and convert them into a positive integer. When
  463. ** finished, leave *pz pointing to the first character past the end of
  464. ** the integer. The *pLen parameter holds the length of the string
  465. ** in *pz and is decremented once for each character in the integer.
  466. */
  467. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  468. static const signed char zValue[] = {
  469. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  470. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  471. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  472. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  473. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  474. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  475. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  476. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  477. };
  478. unsigned int v = 0;
  479. int c;
  480. unsigned char *z = (unsigned char*)*pz;
  481. unsigned char *zStart = z;
  482. while( (c = zValue[0x7f&*(z++)])>=0 ){
  483. v = (v<<6) + c;
  484. }
  485. z--;
  486. *pLen -= (int)(z - zStart);
  487. *pz = (char*)z;
  488. return v;
  489. }
  490. #if RBU_ENABLE_DELTA_CKSUM
  491. /*
  492. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  493. */
  494. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  495. const unsigned char *z = (const unsigned char *)zIn;
  496. unsigned sum0 = 0;
  497. unsigned sum1 = 0;
  498. unsigned sum2 = 0;
  499. unsigned sum3 = 0;
  500. while(N >= 16){
  501. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  502. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  503. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  504. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  505. z += 16;
  506. N -= 16;
  507. }
  508. while(N >= 4){
  509. sum0 += z[0];
  510. sum1 += z[1];
  511. sum2 += z[2];
  512. sum3 += z[3];
  513. z += 4;
  514. N -= 4;
  515. }
  516. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  517. switch(N){
  518. case 3: sum3 += (z[2] << 8);
  519. case 2: sum3 += (z[1] << 16);
  520. case 1: sum3 += (z[0] << 24);
  521. default: ;
  522. }
  523. return sum3;
  524. }
  525. #endif
  526. /*
  527. ** Apply a delta.
  528. **
  529. ** The output buffer should be big enough to hold the whole output
  530. ** file and a NUL terminator at the end. The delta_output_size()
  531. ** routine will determine this size for you.
  532. **
  533. ** The delta string should be null-terminated. But the delta string
  534. ** may contain embedded NUL characters (if the input and output are
  535. ** binary files) so we also have to pass in the length of the delta in
  536. ** the lenDelta parameter.
  537. **
  538. ** This function returns the size of the output file in bytes (excluding
  539. ** the final NUL terminator character). Except, if the delta string is
  540. ** malformed or intended for use with a source file other than zSrc,
  541. ** then this routine returns -1.
  542. **
  543. ** Refer to the delta_create() documentation above for a description
  544. ** of the delta file format.
  545. */
  546. static int rbuDeltaApply(
  547. const char *zSrc, /* The source or pattern file */
  548. int lenSrc, /* Length of the source file */
  549. const char *zDelta, /* Delta to apply to the pattern */
  550. int lenDelta, /* Length of the delta */
  551. char *zOut /* Write the output into this preallocated buffer */
  552. ){
  553. unsigned int limit;
  554. unsigned int total = 0;
  555. #if RBU_ENABLE_DELTA_CKSUM
  556. char *zOrigOut = zOut;
  557. #endif
  558. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  559. if( *zDelta!='\n' ){
  560. /* ERROR: size integer not terminated by "\n" */
  561. return -1;
  562. }
  563. zDelta++; lenDelta--;
  564. while( *zDelta && lenDelta>0 ){
  565. unsigned int cnt, ofst;
  566. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  567. switch( zDelta[0] ){
  568. case '@': {
  569. zDelta++; lenDelta--;
  570. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  571. if( lenDelta>0 && zDelta[0]!=',' ){
  572. /* ERROR: copy command not terminated by ',' */
  573. return -1;
  574. }
  575. zDelta++; lenDelta--;
  576. total += cnt;
  577. if( total>limit ){
  578. /* ERROR: copy exceeds output file size */
  579. return -1;
  580. }
  581. if( (int)(ofst+cnt) > lenSrc ){
  582. /* ERROR: copy extends past end of input */
  583. return -1;
  584. }
  585. memcpy(zOut, &zSrc[ofst], cnt);
  586. zOut += cnt;
  587. break;
  588. }
  589. case ':': {
  590. zDelta++; lenDelta--;
  591. total += cnt;
  592. if( total>limit ){
  593. /* ERROR: insert command gives an output larger than predicted */
  594. return -1;
  595. }
  596. if( (int)cnt>lenDelta ){
  597. /* ERROR: insert count exceeds size of delta */
  598. return -1;
  599. }
  600. memcpy(zOut, zDelta, cnt);
  601. zOut += cnt;
  602. zDelta += cnt;
  603. lenDelta -= cnt;
  604. break;
  605. }
  606. case ';': {
  607. zDelta++; lenDelta--;
  608. zOut[0] = 0;
  609. #if RBU_ENABLE_DELTA_CKSUM
  610. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  611. /* ERROR: bad checksum */
  612. return -1;
  613. }
  614. #endif
  615. if( total!=limit ){
  616. /* ERROR: generated size does not match predicted size */
  617. return -1;
  618. }
  619. return total;
  620. }
  621. default: {
  622. /* ERROR: unknown delta operator */
  623. return -1;
  624. }
  625. }
  626. }
  627. /* ERROR: unterminated delta */
  628. return -1;
  629. }
  630. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  631. int size;
  632. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  633. if( *zDelta!='\n' ){
  634. /* ERROR: size integer not terminated by "\n" */
  635. return -1;
  636. }
  637. return size;
  638. }
  639. /*
  640. ** End of code taken from fossil.
  641. *************************************************************************/
  642. /*
  643. ** Implementation of SQL scalar function rbu_fossil_delta().
  644. **
  645. ** This function applies a fossil delta patch to a blob. Exactly two
  646. ** arguments must be passed to this function. The first is the blob to
  647. ** patch and the second the patch to apply. If no error occurs, this
  648. ** function returns the patched blob.
  649. */
  650. static void rbuFossilDeltaFunc(
  651. sqlite3_context *context,
  652. int argc,
  653. sqlite3_value **argv
  654. ){
  655. const char *aDelta;
  656. int nDelta;
  657. const char *aOrig;
  658. int nOrig;
  659. int nOut;
  660. int nOut2;
  661. char *aOut;
  662. assert( argc==2 );
  663. UNUSED_PARAMETER(argc);
  664. nOrig = sqlite3_value_bytes(argv[0]);
  665. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  666. nDelta = sqlite3_value_bytes(argv[1]);
  667. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  668. /* Figure out the size of the output */
  669. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  670. if( nOut<0 ){
  671. sqlite3_result_error(context, "corrupt fossil delta", -1);
  672. return;
  673. }
  674. aOut = sqlite3_malloc(nOut+1);
  675. if( aOut==0 ){
  676. sqlite3_result_error_nomem(context);
  677. }else{
  678. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  679. if( nOut2!=nOut ){
  680. sqlite3_free(aOut);
  681. sqlite3_result_error(context, "corrupt fossil delta", -1);
  682. }else{
  683. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  684. }
  685. }
  686. }
  687. /*
  688. ** Prepare the SQL statement in buffer zSql against database handle db.
  689. ** If successful, set *ppStmt to point to the new statement and return
  690. ** SQLITE_OK.
  691. **
  692. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  693. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  694. ** point to a buffer containing an error message. It is the responsibility
  695. ** of the caller to (eventually) free this buffer using sqlite3_free().
  696. */
  697. static int prepareAndCollectError(
  698. sqlite3 *db,
  699. sqlite3_stmt **ppStmt,
  700. char **pzErrmsg,
  701. const char *zSql
  702. ){
  703. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  704. if( rc!=SQLITE_OK ){
  705. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  706. *ppStmt = 0;
  707. }
  708. return rc;
  709. }
  710. /*
  711. ** Reset the SQL statement passed as the first argument. Return a copy
  712. ** of the value returned by sqlite3_reset().
  713. **
  714. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  715. ** containing an error message. It is the responsibility of the caller
  716. ** to eventually free this buffer using sqlite3_free().
  717. */
  718. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  719. int rc = sqlite3_reset(pStmt);
  720. if( rc!=SQLITE_OK ){
  721. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  722. }
  723. return rc;
  724. }
  725. /*
  726. ** Unless it is NULL, argument zSql points to a buffer allocated using
  727. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  728. ** statement against database db and frees the buffer. If statement
  729. ** compilation is successful, *ppStmt is set to point to the new statement
  730. ** handle and SQLITE_OK is returned.
  731. **
  732. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  733. ** returned. In this case, *pzErrmsg may also be set to point to an error
  734. ** message. It is the responsibility of the caller to free this error message
  735. ** buffer using sqlite3_free().
  736. **
  737. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  738. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  739. */
  740. static int prepareFreeAndCollectError(
  741. sqlite3 *db,
  742. sqlite3_stmt **ppStmt,
  743. char **pzErrmsg,
  744. char *zSql
  745. ){
  746. int rc;
  747. assert( *pzErrmsg==0 );
  748. if( zSql==0 ){
  749. rc = SQLITE_NOMEM;
  750. *ppStmt = 0;
  751. }else{
  752. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  753. sqlite3_free(zSql);
  754. }
  755. return rc;
  756. }
  757. /*
  758. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  759. ** by an earlier call to rbuObjIterCacheTableInfo().
  760. */
  761. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  762. int i;
  763. for(i=0; i<pIter->nTblCol; i++){
  764. sqlite3_free(pIter->azTblCol[i]);
  765. sqlite3_free(pIter->azTblType[i]);
  766. }
  767. sqlite3_free(pIter->azTblCol);
  768. pIter->azTblCol = 0;
  769. pIter->azTblType = 0;
  770. pIter->aiSrcOrder = 0;
  771. pIter->abTblPk = 0;
  772. pIter->abNotNull = 0;
  773. pIter->nTblCol = 0;
  774. pIter->eType = 0; /* Invalid value */
  775. }
  776. /*
  777. ** Finalize all statements and free all allocations that are specific to
  778. ** the current object (table/index pair).
  779. */
  780. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  781. RbuUpdateStmt *pUp;
  782. sqlite3_finalize(pIter->pSelect);
  783. sqlite3_finalize(pIter->pInsert);
  784. sqlite3_finalize(pIter->pDelete);
  785. sqlite3_finalize(pIter->pTmpInsert);
  786. pUp = pIter->pRbuUpdate;
  787. while( pUp ){
  788. RbuUpdateStmt *pTmp = pUp->pNext;
  789. sqlite3_finalize(pUp->pUpdate);
  790. sqlite3_free(pUp);
  791. pUp = pTmp;
  792. }
  793. sqlite3_free(pIter->aIdxCol);
  794. sqlite3_free(pIter->zIdxSql);
  795. pIter->pSelect = 0;
  796. pIter->pInsert = 0;
  797. pIter->pDelete = 0;
  798. pIter->pRbuUpdate = 0;
  799. pIter->pTmpInsert = 0;
  800. pIter->nCol = 0;
  801. pIter->nIdxCol = 0;
  802. pIter->aIdxCol = 0;
  803. pIter->zIdxSql = 0;
  804. }
  805. /*
  806. ** Clean up any resources allocated as part of the iterator object passed
  807. ** as the only argument.
  808. */
  809. static void rbuObjIterFinalize(RbuObjIter *pIter){
  810. rbuObjIterClearStatements(pIter);
  811. sqlite3_finalize(pIter->pTblIter);
  812. sqlite3_finalize(pIter->pIdxIter);
  813. rbuObjIterFreeCols(pIter);
  814. memset(pIter, 0, sizeof(RbuObjIter));
  815. }
  816. /*
  817. ** Advance the iterator to the next position.
  818. **
  819. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  820. ** pointing to the next entry. Otherwise, an error code and message is
  821. ** left in the RBU handle passed as the first argument. A copy of the
  822. ** error code is returned.
  823. */
  824. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  825. int rc = p->rc;
  826. if( rc==SQLITE_OK ){
  827. /* Free any SQLite statements used while processing the previous object */
  828. rbuObjIterClearStatements(pIter);
  829. if( pIter->zIdx==0 ){
  830. rc = sqlite3_exec(p->dbMain,
  831. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  832. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  833. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  834. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  835. , 0, 0, &p->zErrmsg
  836. );
  837. }
  838. if( rc==SQLITE_OK ){
  839. if( pIter->bCleanup ){
  840. rbuObjIterFreeCols(pIter);
  841. pIter->bCleanup = 0;
  842. rc = sqlite3_step(pIter->pTblIter);
  843. if( rc!=SQLITE_ROW ){
  844. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  845. pIter->zTbl = 0;
  846. pIter->zDataTbl = 0;
  847. }else{
  848. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  849. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  850. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  851. }
  852. }else{
  853. if( pIter->zIdx==0 ){
  854. sqlite3_stmt *pIdx = pIter->pIdxIter;
  855. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  856. }
  857. if( rc==SQLITE_OK ){
  858. rc = sqlite3_step(pIter->pIdxIter);
  859. if( rc!=SQLITE_ROW ){
  860. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  861. pIter->bCleanup = 1;
  862. pIter->zIdx = 0;
  863. }else{
  864. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  865. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  866. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  867. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  868. }
  869. }
  870. }
  871. }
  872. }
  873. if( rc!=SQLITE_OK ){
  874. rbuObjIterFinalize(pIter);
  875. p->rc = rc;
  876. }
  877. return rc;
  878. }
  879. /*
  880. ** The implementation of the rbu_target_name() SQL function. This function
  881. ** accepts one or two arguments. The first argument is the name of a table -
  882. ** the name of a table in the RBU database. The second, if it is present, is 1
  883. ** for a view or 0 for a table.
  884. **
  885. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  886. **
  887. ** data[0-9]_<name>
  888. **
  889. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  890. ** Otherwise, if the only argument does not match the above pattern, an SQL
  891. ** NULL is returned.
  892. **
  893. ** "data_t1" -> "t1"
  894. ** "data0123_t2" -> "t2"
  895. ** "dataAB_t3" -> NULL
  896. **
  897. ** For an rbu vacuum handle, a copy of the first argument is returned if
  898. ** the second argument is either missing or 0 (not a view).
  899. */
  900. static void rbuTargetNameFunc(
  901. sqlite3_context *pCtx,
  902. int argc,
  903. sqlite3_value **argv
  904. ){
  905. sqlite3rbu *p = sqlite3_user_data(pCtx);
  906. const char *zIn;
  907. assert( argc==1 || argc==2 );
  908. zIn = (const char*)sqlite3_value_text(argv[0]);
  909. if( zIn ){
  910. if( rbuIsVacuum(p) ){
  911. assert( argc==2 || argc==1 );
  912. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  913. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  914. }
  915. }else{
  916. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  917. int i;
  918. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  919. if( zIn[i]=='_' && zIn[i+1] ){
  920. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  921. }
  922. }
  923. }
  924. }
  925. }
  926. /*
  927. ** Initialize the iterator structure passed as the second argument.
  928. **
  929. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  930. ** pointing to the first entry. Otherwise, an error code and message is
  931. ** left in the RBU handle passed as the first argument. A copy of the
  932. ** error code is returned.
  933. */
  934. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  935. int rc;
  936. memset(pIter, 0, sizeof(RbuObjIter));
  937. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  938. sqlite3_mprintf(
  939. "SELECT rbu_target_name(name, type='view') AS target, name "
  940. "FROM sqlite_schema "
  941. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  942. " %s "
  943. "ORDER BY name"
  944. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  945. if( rc==SQLITE_OK ){
  946. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  947. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  948. " FROM main.sqlite_schema "
  949. " WHERE type='index' AND tbl_name = ?"
  950. );
  951. }
  952. pIter->bCleanup = 1;
  953. p->rc = rc;
  954. return rbuObjIterNext(p, pIter);
  955. }
  956. /*
  957. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  958. ** an error code is stored in the RBU handle passed as the first argument.
  959. **
  960. ** If an error has already occurred (p->rc is already set to something other
  961. ** than SQLITE_OK), then this function returns NULL without modifying the
  962. ** stored error code. In this case it still calls sqlite3_free() on any
  963. ** printf() parameters associated with %z conversions.
  964. */
  965. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  966. char *zSql = 0;
  967. va_list ap;
  968. va_start(ap, zFmt);
  969. zSql = sqlite3_vmprintf(zFmt, ap);
  970. if( p->rc==SQLITE_OK ){
  971. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  972. }else{
  973. sqlite3_free(zSql);
  974. zSql = 0;
  975. }
  976. va_end(ap);
  977. return zSql;
  978. }
  979. /*
  980. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  981. ** arguments are the usual subsitution values. This function performs
  982. ** the printf() style substitutions and executes the result as an SQL
  983. ** statement on the RBU handles database.
  984. **
  985. ** If an error occurs, an error code and error message is stored in the
  986. ** RBU handle. If an error has already occurred when this function is
  987. ** called, it is a no-op.
  988. */
  989. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  990. va_list ap;
  991. char *zSql;
  992. va_start(ap, zFmt);
  993. zSql = sqlite3_vmprintf(zFmt, ap);
  994. if( p->rc==SQLITE_OK ){
  995. if( zSql==0 ){
  996. p->rc = SQLITE_NOMEM;
  997. }else{
  998. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  999. }
  1000. }
  1001. sqlite3_free(zSql);
  1002. va_end(ap);
  1003. return p->rc;
  1004. }
  1005. /*
  1006. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  1007. ** bytes.
  1008. **
  1009. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  1010. ** error code in the rbu handle passed as the first argument. Or, if an
  1011. ** error has already occurred when this function is called, return NULL
  1012. ** immediately without attempting the allocation or modifying the stored
  1013. ** error code.
  1014. */
  1015. static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
  1016. void *pRet = 0;
  1017. if( p->rc==SQLITE_OK ){
  1018. assert( nByte>0 );
  1019. pRet = sqlite3_malloc64(nByte);
  1020. if( pRet==0 ){
  1021. p->rc = SQLITE_NOMEM;
  1022. }else{
  1023. memset(pRet, 0, nByte);
  1024. }
  1025. }
  1026. return pRet;
  1027. }
  1028. /*
  1029. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  1030. ** there is room for at least nCol elements. If an OOM occurs, store an
  1031. ** error code in the RBU handle passed as the first argument.
  1032. */
  1033. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  1034. sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  1035. char **azNew;
  1036. azNew = (char**)rbuMalloc(p, nByte);
  1037. if( azNew ){
  1038. pIter->azTblCol = azNew;
  1039. pIter->azTblType = &azNew[nCol];
  1040. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  1041. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  1042. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  1043. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  1044. }
  1045. }
  1046. /*
  1047. ** The first argument must be a nul-terminated string. This function
  1048. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  1049. ** It is the responsibility of the caller to eventually free this memory
  1050. ** using sqlite3_free().
  1051. **
  1052. ** If an OOM condition is encountered when attempting to allocate memory,
  1053. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  1054. ** if the allocation succeeds, (*pRc) is left unchanged.
  1055. */
  1056. static char *rbuStrndup(const char *zStr, int *pRc){
  1057. char *zRet = 0;
  1058. if( *pRc==SQLITE_OK ){
  1059. if( zStr ){
  1060. size_t nCopy = strlen(zStr) + 1;
  1061. zRet = (char*)sqlite3_malloc64(nCopy);
  1062. if( zRet ){
  1063. memcpy(zRet, zStr, nCopy);
  1064. }else{
  1065. *pRc = SQLITE_NOMEM;
  1066. }
  1067. }
  1068. }
  1069. return zRet;
  1070. }
  1071. /*
  1072. ** Finalize the statement passed as the second argument.
  1073. **
  1074. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  1075. ** rbu handle error code is not already set, set the error code and error
  1076. ** message accordingly.
  1077. */
  1078. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  1079. sqlite3 *db = sqlite3_db_handle(pStmt);
  1080. int rc = sqlite3_finalize(pStmt);
  1081. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  1082. p->rc = rc;
  1083. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  1084. }
  1085. }
  1086. /* Determine the type of a table.
  1087. **
  1088. ** peType is of type (int*), a pointer to an output parameter of type
  1089. ** (int). This call sets the output parameter as follows, depending
  1090. ** on the type of the table specified by parameters dbName and zTbl.
  1091. **
  1092. ** RBU_PK_NOTABLE: No such table.
  1093. ** RBU_PK_NONE: Table has an implicit rowid.
  1094. ** RBU_PK_IPK: Table has an explicit IPK column.
  1095. ** RBU_PK_EXTERNAL: Table has an external PK index.
  1096. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  1097. ** RBU_PK_VTAB: Table is a virtual table.
  1098. **
  1099. ** Argument *piPk is also of type (int*), and also points to an output
  1100. ** parameter. Unless the table has an external primary key index
  1101. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  1102. ** if the table does have an external primary key index, then *piPk
  1103. ** is set to the root page number of the primary key index before
  1104. ** returning.
  1105. **
  1106. ** ALGORITHM:
  1107. **
  1108. ** if( no entry exists in sqlite_schema ){
  1109. ** return RBU_PK_NOTABLE
  1110. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  1111. ** return RBU_PK_VTAB
  1112. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  1113. ** if( the index that is the pk exists in sqlite_schema ){
  1114. ** *piPK = rootpage of that index.
  1115. ** return RBU_PK_EXTERNAL
  1116. ** }else{
  1117. ** return RBU_PK_WITHOUT_ROWID
  1118. ** }
  1119. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  1120. ** return RBU_PK_IPK
  1121. ** }else{
  1122. ** return RBU_PK_NONE
  1123. ** }
  1124. */
  1125. static void rbuTableType(
  1126. sqlite3rbu *p,
  1127. const char *zTab,
  1128. int *peType,
  1129. int *piTnum,
  1130. int *piPk
  1131. ){
  1132. /*
  1133. ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q)
  1134. ** 1) PRAGMA index_list = ?
  1135. ** 2) SELECT count(*) FROM sqlite_schema where name=%Q
  1136. ** 3) PRAGMA table_info = ?
  1137. */
  1138. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  1139. *peType = RBU_PK_NOTABLE;
  1140. *piPk = 0;
  1141. assert( p->rc==SQLITE_OK );
  1142. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  1143. sqlite3_mprintf(
  1144. "SELECT "
  1145. " (sql COLLATE nocase BETWEEN 'CREATE VIRTUAL' AND 'CREATE VIRTUAM'),"
  1146. " rootpage"
  1147. " FROM sqlite_schema"
  1148. " WHERE name=%Q", zTab
  1149. ));
  1150. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  1151. /* Either an error, or no such table. */
  1152. goto rbuTableType_end;
  1153. }
  1154. if( sqlite3_column_int(aStmt[0], 0) ){
  1155. *peType = RBU_PK_VTAB; /* virtual table */
  1156. goto rbuTableType_end;
  1157. }
  1158. *piTnum = sqlite3_column_int(aStmt[0], 1);
  1159. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  1160. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  1161. );
  1162. if( p->rc ) goto rbuTableType_end;
  1163. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  1164. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  1165. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  1166. if( zOrig && zIdx && zOrig[0]=='p' ){
  1167. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  1168. sqlite3_mprintf(
  1169. "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx
  1170. ));
  1171. if( p->rc==SQLITE_OK ){
  1172. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  1173. *piPk = sqlite3_column_int(aStmt[2], 0);
  1174. *peType = RBU_PK_EXTERNAL;
  1175. }else{
  1176. *peType = RBU_PK_WITHOUT_ROWID;
  1177. }
  1178. }
  1179. goto rbuTableType_end;
  1180. }
  1181. }
  1182. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  1183. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  1184. );
  1185. if( p->rc==SQLITE_OK ){
  1186. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  1187. if( sqlite3_column_int(aStmt[3],5)>0 ){
  1188. *peType = RBU_PK_IPK; /* explicit IPK column */
  1189. goto rbuTableType_end;
  1190. }
  1191. }
  1192. *peType = RBU_PK_NONE;
  1193. }
  1194. rbuTableType_end: {
  1195. unsigned int i;
  1196. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  1197. rbuFinalize(p, aStmt[i]);
  1198. }
  1199. }
  1200. }
  1201. /*
  1202. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  1203. ** the pIter->abIndexed[] array.
  1204. */
  1205. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  1206. sqlite3_stmt *pList = 0;
  1207. int bIndex = 0;
  1208. if( p->rc==SQLITE_OK ){
  1209. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  1210. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  1211. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  1212. );
  1213. }
  1214. pIter->nIndex = 0;
  1215. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  1216. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  1217. int bPartial = sqlite3_column_int(pList, 4);
  1218. sqlite3_stmt *pXInfo = 0;
  1219. if( zIdx==0 ) break;
  1220. if( bPartial ){
  1221. memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
  1222. }
  1223. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  1224. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  1225. );
  1226. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  1227. int iCid = sqlite3_column_int(pXInfo, 1);
  1228. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  1229. if( iCid==-2 ){
  1230. memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
  1231. }
  1232. }
  1233. rbuFinalize(p, pXInfo);
  1234. bIndex = 1;
  1235. pIter->nIndex++;
  1236. }
  1237. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  1238. /* "PRAGMA index_list" includes the main PK b-tree */
  1239. pIter->nIndex--;
  1240. }
  1241. rbuFinalize(p, pList);
  1242. if( bIndex==0 ) pIter->abIndexed = 0;
  1243. }
  1244. /*
  1245. ** If they are not already populated, populate the pIter->azTblCol[],
  1246. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  1247. ** the table (not index) that the iterator currently points to.
  1248. **
  1249. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  1250. ** an error does occur, an error code and error message are also left in
  1251. ** the RBU handle.
  1252. */
  1253. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  1254. if( pIter->azTblCol==0 ){
  1255. sqlite3_stmt *pStmt = 0;
  1256. int nCol = 0;
  1257. int i; /* for() loop iterator variable */
  1258. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  1259. int iOrder = 0;
  1260. int iTnum = 0;
  1261. /* Figure out the type of table this step will deal with. */
  1262. assert( pIter->eType==0 );
  1263. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  1264. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  1265. p->rc = SQLITE_ERROR;
  1266. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  1267. }
  1268. if( p->rc ) return p->rc;
  1269. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  1270. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  1271. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  1272. || pIter->eType==RBU_PK_VTAB
  1273. );
  1274. /* Populate the azTblCol[] and nTblCol variables based on the columns
  1275. ** of the input table. Ignore any input table columns that begin with
  1276. ** "rbu_". */
  1277. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  1278. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  1279. );
  1280. if( p->rc==SQLITE_OK ){
  1281. nCol = sqlite3_column_count(pStmt);
  1282. rbuAllocateIterArrays(p, pIter, nCol);
  1283. }
  1284. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  1285. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  1286. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  1287. char *zCopy = rbuStrndup(zName, &p->rc);
  1288. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  1289. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  1290. }
  1291. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  1292. bRbuRowid = 1;
  1293. }
  1294. }
  1295. sqlite3_finalize(pStmt);
  1296. pStmt = 0;
  1297. if( p->rc==SQLITE_OK
  1298. && rbuIsVacuum(p)==0
  1299. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  1300. ){
  1301. p->rc = SQLITE_ERROR;
  1302. p->zErrmsg = sqlite3_mprintf(
  1303. "table %q %s rbu_rowid column", pIter->zDataTbl,
  1304. (bRbuRowid ? "may not have" : "requires")
  1305. );
  1306. }
  1307. /* Check that all non-HIDDEN columns in the destination table are also
  1308. ** present in the input table. Populate the abTblPk[], azTblType[] and
  1309. ** aiTblOrder[] arrays at the same time. */
  1310. if( p->rc==SQLITE_OK ){
  1311. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  1312. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  1313. );
  1314. }
  1315. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  1316. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  1317. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  1318. for(i=iOrder; i<pIter->nTblCol; i++){
  1319. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  1320. }
  1321. if( i==pIter->nTblCol ){
  1322. p->rc = SQLITE_ERROR;
  1323. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  1324. pIter->zDataTbl, zName
  1325. );
  1326. }else{
  1327. int iPk = sqlite3_column_int(pStmt, 5);
  1328. int bNotNull = sqlite3_column_int(pStmt, 3);
  1329. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  1330. if( i!=iOrder ){
  1331. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  1332. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  1333. }
  1334. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  1335. assert( iPk>=0 );
  1336. pIter->abTblPk[iOrder] = (u8)iPk;
  1337. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  1338. iOrder++;
  1339. }
  1340. }
  1341. rbuFinalize(p, pStmt);
  1342. rbuObjIterCacheIndexedCols(p, pIter);
  1343. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  1344. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  1345. }
  1346. return p->rc;
  1347. }
  1348. /*
  1349. ** This function constructs and returns a pointer to a nul-terminated
  1350. ** string containing some SQL clause or list based on one or more of the
  1351. ** column names currently stored in the pIter->azTblCol[] array.
  1352. */
  1353. static char *rbuObjIterGetCollist(
  1354. sqlite3rbu *p, /* RBU object */
  1355. RbuObjIter *pIter /* Object iterator for column names */
  1356. ){
  1357. char *zList = 0;
  1358. const char *zSep = "";
  1359. int i;
  1360. for(i=0; i<pIter->nTblCol; i++){
  1361. const char *z = pIter->azTblCol[i];
  1362. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  1363. zSep = ", ";
  1364. }
  1365. return zList;
  1366. }
  1367. /*
  1368. ** Return a comma separated list of the quoted PRIMARY KEY column names,
  1369. ** in order, for the current table. Before each column name, add the text
  1370. ** zPre. After each column name, add the zPost text. Use zSeparator as
  1371. ** the separator text (usually ", ").
  1372. */
  1373. static char *rbuObjIterGetPkList(
  1374. sqlite3rbu *p, /* RBU object */
  1375. RbuObjIter *pIter, /* Object iterator for column names */
  1376. const char *zPre, /* Before each quoted column name */
  1377. const char *zSeparator, /* Separator to use between columns */
  1378. const char *zPost /* After each quoted column name */
  1379. ){
  1380. int iPk = 1;
  1381. char *zRet = 0;
  1382. const char *zSep = "";
  1383. while( 1 ){
  1384. int i;
  1385. for(i=0; i<pIter->nTblCol; i++){
  1386. if( (int)pIter->abTblPk[i]==iPk ){
  1387. const char *zCol = pIter->azTblCol[i];
  1388. zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost);
  1389. zSep = zSeparator;
  1390. break;
  1391. }
  1392. }
  1393. if( i==pIter->nTblCol ) break;
  1394. iPk++;
  1395. }
  1396. return zRet;
  1397. }
  1398. /*
  1399. ** This function is called as part of restarting an RBU vacuum within
  1400. ** stage 1 of the process (while the *-oal file is being built) while
  1401. ** updating a table (not an index). The table may be a rowid table or
  1402. ** a WITHOUT ROWID table. It queries the target database to find the
  1403. ** largest key that has already been written to the target table and
  1404. ** constructs a WHERE clause that can be used to extract the remaining
  1405. ** rows from the source table. For a rowid table, the WHERE clause
  1406. ** is of the form:
  1407. **
  1408. ** "WHERE _rowid_ > ?"
  1409. **
  1410. ** and for WITHOUT ROWID tables:
  1411. **
  1412. ** "WHERE (key1, key2) > (?, ?)"
  1413. **
  1414. ** Instead of "?" placeholders, the actual WHERE clauses created by
  1415. ** this function contain literal SQL values.
  1416. */
  1417. static char *rbuVacuumTableStart(
  1418. sqlite3rbu *p, /* RBU handle */
  1419. RbuObjIter *pIter, /* RBU iterator object */
  1420. int bRowid, /* True for a rowid table */
  1421. const char *zWrite /* Target table name prefix */
  1422. ){
  1423. sqlite3_stmt *pMax = 0;
  1424. char *zRet = 0;
  1425. if( bRowid ){
  1426. p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
  1427. sqlite3_mprintf(
  1428. "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
  1429. )
  1430. );
  1431. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  1432. sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);
  1433. zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax);
  1434. }
  1435. rbuFinalize(p, pMax);
  1436. }else{
  1437. char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC");
  1438. char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")");
  1439. char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
  1440. if( p->rc==SQLITE_OK ){
  1441. p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
  1442. sqlite3_mprintf(
  1443. "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
  1444. zSelect, zWrite, pIter->zTbl, zOrder
  1445. )
  1446. );
  1447. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  1448. const char *zVal = (const char*)sqlite3_column_text(pMax, 0);
  1449. zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal);
  1450. }
  1451. rbuFinalize(p, pMax);
  1452. }
  1453. sqlite3_free(zOrder);
  1454. sqlite3_free(zSelect);
  1455. sqlite3_free(zList);
  1456. }
  1457. return zRet;
  1458. }
  1459. /*
  1460. ** This function is called as part of restating an RBU vacuum when the
  1461. ** current operation is writing content to an index. If possible, it
  1462. ** queries the target index b-tree for the largest key already written to
  1463. ** it, then composes and returns an expression that can be used in a WHERE
  1464. ** clause to select the remaining required rows from the source table.
  1465. ** It is only possible to return such an expression if:
  1466. **
  1467. ** * The index contains no DESC columns, and
  1468. ** * The last key written to the index before the operation was
  1469. ** suspended does not contain any NULL values.
  1470. **
  1471. ** The expression is of the form:
  1472. **
  1473. ** (index-field1, index-field2, ...) > (?, ?, ...)
  1474. **
  1475. ** except that the "?" placeholders are replaced with literal values.
  1476. **
  1477. ** If the expression cannot be created, NULL is returned. In this case,
  1478. ** the caller has to use an OFFSET clause to extract only the required
  1479. ** rows from the sourct table, just as it does for an RBU update operation.
  1480. */
  1481. static char *rbuVacuumIndexStart(
  1482. sqlite3rbu *p, /* RBU handle */
  1483. RbuObjIter *pIter /* RBU iterator object */
  1484. ){
  1485. char *zOrder = 0;
  1486. char *zLhs = 0;
  1487. char *zSelect = 0;
  1488. char *zVector = 0;
  1489. char *zRet = 0;
  1490. int bFailed = 0;
  1491. const char *zSep = "";
  1492. int iCol = 0;
  1493. sqlite3_stmt *pXInfo = 0;
  1494. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  1495. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  1496. );
  1497. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  1498. int iCid = sqlite3_column_int(pXInfo, 1);
  1499. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  1500. const char *zCol;
  1501. if( sqlite3_column_int(pXInfo, 3) ){
  1502. bFailed = 1;
  1503. break;
  1504. }
  1505. if( iCid<0 ){
  1506. if( pIter->eType==RBU_PK_IPK ){
  1507. int i;
  1508. for(i=0; pIter->abTblPk[i]==0; i++);
  1509. assert( i<pIter->nTblCol );
  1510. zCol = pIter->azTblCol[i];
  1511. }else{
  1512. zCol = "_rowid_";
  1513. }
  1514. }else{
  1515. zCol = pIter->azTblCol[iCid];
  1516. }
  1517. zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q",
  1518. zLhs, zSep, zCol, zCollate
  1519. );
  1520. zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
  1521. zOrder, zSep, iCol, zCol, zCollate
  1522. );
  1523. zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")",
  1524. zSelect, zSep, iCol, zCol
  1525. );
  1526. zSep = ", ";
  1527. iCol++;
  1528. }
  1529. rbuFinalize(p, pXInfo);
  1530. if( bFailed ) goto index_start_out;
  1531. if( p->rc==SQLITE_OK ){
  1532. sqlite3_stmt *pSel = 0;
  1533. p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,
  1534. sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
  1535. zSelect, pIter->zTbl, zOrder
  1536. )
  1537. );
  1538. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){
  1539. zSep = "";
  1540. for(iCol=0; iCol<pIter->nCol; iCol++){
  1541. const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
  1542. if( zQuoted==0 ){
  1543. p->rc = SQLITE_NOMEM;
  1544. }else if( zQuoted[0]=='N' ){
  1545. bFailed = 1;
  1546. break;
  1547. }
  1548. zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted);
  1549. zSep = ", ";
  1550. }
  1551. if( !bFailed ){
  1552. zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector);
  1553. }
  1554. }
  1555. rbuFinalize(p, pSel);
  1556. }
  1557. index_start_out:
  1558. sqlite3_free(zOrder);
  1559. sqlite3_free(zSelect);
  1560. sqlite3_free(zVector);
  1561. sqlite3_free(zLhs);
  1562. return zRet;
  1563. }
  1564. /*
  1565. ** This function is used to create a SELECT list (the list of SQL
  1566. ** expressions that follows a SELECT keyword) for a SELECT statement
  1567. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  1568. ** index object currently indicated by the iterator object passed as the
  1569. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  1570. ** to obtain the required information.
  1571. **
  1572. ** If the index is of the following form:
  1573. **
  1574. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  1575. **
  1576. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  1577. ** "ipk", the returned string is:
  1578. **
  1579. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  1580. **
  1581. ** As well as the returned string, three other malloc'd strings are
  1582. ** returned via output parameters. As follows:
  1583. **
  1584. ** pzImposterCols: ...
  1585. ** pzImposterPk: ...
  1586. ** pzWhere: ...
  1587. */
  1588. static char *rbuObjIterGetIndexCols(
  1589. sqlite3rbu *p, /* RBU object */
  1590. RbuObjIter *pIter, /* Object iterator for column names */
  1591. char **pzImposterCols, /* OUT: Columns for imposter table */
  1592. char **pzImposterPk, /* OUT: Imposter PK clause */
  1593. char **pzWhere, /* OUT: WHERE clause */
  1594. int *pnBind /* OUT: Trbul number of columns */
  1595. ){
  1596. int rc = p->rc; /* Error code */
  1597. int rc2; /* sqlite3_finalize() return code */
  1598. char *zRet = 0; /* String to return */
  1599. char *zImpCols = 0; /* String to return via *pzImposterCols */
  1600. char *zImpPK = 0; /* String to return via *pzImposterPK */
  1601. char *zWhere = 0; /* String to return via *pzWhere */
  1602. int nBind = 0; /* Value to return via *pnBind */
  1603. const char *zCom = ""; /* Set to ", " later on */
  1604. const char *zAnd = ""; /* Set to " AND " later on */
  1605. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  1606. if( rc==SQLITE_OK ){
  1607. assert( p->zErrmsg==0 );
  1608. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  1609. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  1610. );
  1611. }
  1612. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  1613. int iCid = sqlite3_column_int(pXInfo, 1);
  1614. int bDesc = sqlite3_column_int(pXInfo, 3);
  1615. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  1616. const char *zCol = 0;
  1617. const char *zType;
  1618. if( iCid==-2 ){
  1619. int iSeq = sqlite3_column_int(pXInfo, 0);
  1620. zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom,
  1621. pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate
  1622. );
  1623. zType = "";
  1624. }else {
  1625. if( iCid<0 ){
  1626. /* An integer primary key. If the table has an explicit IPK, use
  1627. ** its name. Otherwise, use "rbu_rowid". */
  1628. if( pIter->eType==RBU_PK_IPK ){
  1629. int i;
  1630. for(i=0; pIter->abTblPk[i]==0; i++);
  1631. assert( i<pIter->nTblCol );
  1632. zCol = pIter->azTblCol[i];
  1633. }else if( rbuIsVacuum(p) ){
  1634. zCol = "_rowid_";
  1635. }else{
  1636. zCol = "rbu_rowid";
  1637. }
  1638. zType = "INTEGER";
  1639. }else{
  1640. zCol = pIter->azTblCol[iCid];
  1641. zType = pIter->azTblType[iCid];
  1642. }
  1643. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate);
  1644. }
  1645. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  1646. const char *zOrder = (bDesc ? " DESC" : "");
  1647. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  1648. zImpPK, zCom, nBind, zCol, zOrder
  1649. );
  1650. }
  1651. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  1652. zImpCols, zCom, nBind, zCol, zType, zCollate
  1653. );
  1654. zWhere = sqlite3_mprintf(
  1655. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  1656. );
  1657. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  1658. zCom = ", ";
  1659. zAnd = " AND ";
  1660. nBind++;
  1661. }
  1662. rc2 = sqlite3_finalize(pXInfo);
  1663. if( rc==SQLITE_OK ) rc = rc2;
  1664. if( rc!=SQLITE_OK ){
  1665. sqlite3_free(zRet);
  1666. sqlite3_free(zImpCols);
  1667. sqlite3_free(zImpPK);
  1668. sqlite3_free(zWhere);
  1669. zRet = 0;
  1670. zImpCols = 0;
  1671. zImpPK = 0;
  1672. zWhere = 0;
  1673. p->rc = rc;
  1674. }
  1675. *pzImposterCols = zImpCols;
  1676. *pzImposterPk = zImpPK;
  1677. *pzWhere = zWhere;
  1678. *pnBind = nBind;
  1679. return zRet;
  1680. }
  1681. /*
  1682. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  1683. ** paramter is passed "old", return a string of the form:
  1684. **
  1685. ** "old.a, old.b, old.b"
  1686. **
  1687. ** With the column names escaped.
  1688. **
  1689. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  1690. ** the text ", old._rowid_" to the returned value.
  1691. */
  1692. static char *rbuObjIterGetOldlist(
  1693. sqlite3rbu *p,
  1694. RbuObjIter *pIter,
  1695. const char *zObj
  1696. ){
  1697. char *zList = 0;
  1698. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  1699. const char *zS = "";
  1700. int i;
  1701. for(i=0; i<pIter->nTblCol; i++){
  1702. if( pIter->abIndexed[i] ){
  1703. const char *zCol = pIter->azTblCol[i];
  1704. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  1705. }else{
  1706. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  1707. }
  1708. zS = ", ";
  1709. if( zList==0 ){
  1710. p->rc = SQLITE_NOMEM;
  1711. break;
  1712. }
  1713. }
  1714. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  1715. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  1716. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  1717. }
  1718. }
  1719. return zList;
  1720. }
  1721. /*
  1722. ** Return an expression that can be used in a WHERE clause to match the
  1723. ** primary key of the current table. For example, if the table is:
  1724. **
  1725. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  1726. **
  1727. ** Return the string:
  1728. **
  1729. ** "b = ?1 AND c = ?2"
  1730. */
  1731. static char *rbuObjIterGetWhere(
  1732. sqlite3rbu *p,
  1733. RbuObjIter *pIter
  1734. ){
  1735. char *zList = 0;
  1736. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  1737. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  1738. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  1739. const char *zSep = "";
  1740. int i;
  1741. for(i=0; i<pIter->nTblCol; i++){
  1742. if( pIter->abTblPk[i] ){
  1743. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  1744. zSep = " AND ";
  1745. }
  1746. }
  1747. zList = rbuMPrintf(p,
  1748. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  1749. );
  1750. }else{
  1751. const char *zSep = "";
  1752. int i;
  1753. for(i=0; i<pIter->nTblCol; i++){
  1754. if( pIter->abTblPk[i] ){
  1755. const char *zCol = pIter->azTblCol[i];
  1756. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  1757. zSep = " AND ";
  1758. }
  1759. }
  1760. }
  1761. return zList;
  1762. }
  1763. /*
  1764. ** The SELECT statement iterating through the keys for the current object
  1765. ** (p->objiter.pSelect) currently points to a valid row. However, there
  1766. ** is something wrong with the rbu_control value in the rbu_control value
  1767. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  1768. ** of the RBU handle to something reflecting this.
  1769. */
  1770. static void rbuBadControlError(sqlite3rbu *p){
  1771. p->rc = SQLITE_ERROR;
  1772. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  1773. }
  1774. /*
  1775. ** Return a nul-terminated string containing the comma separated list of
  1776. ** assignments that should be included following the "SET" keyword of
  1777. ** an UPDATE statement used to update the table object that the iterator
  1778. ** passed as the second argument currently points to if the rbu_control
  1779. ** column of the data_xxx table entry is set to zMask.
  1780. **
  1781. ** The memory for the returned string is obtained from sqlite3_malloc().
  1782. ** It is the responsibility of the caller to eventually free it using
  1783. ** sqlite3_free().
  1784. **
  1785. ** If an OOM error is encountered when allocating space for the new
  1786. ** string, an error code is left in the rbu handle passed as the first
  1787. ** argument and NULL is returned. Or, if an error has already occurred
  1788. ** when this function is called, NULL is returned immediately, without
  1789. ** attempting the allocation or modifying the stored error code.
  1790. */
  1791. static char *rbuObjIterGetSetlist(
  1792. sqlite3rbu *p,
  1793. RbuObjIter *pIter,
  1794. const char *zMask
  1795. ){
  1796. char *zList = 0;
  1797. if( p->rc==SQLITE_OK ){
  1798. int i;
  1799. if( (int)strlen(zMask)!=pIter->nTblCol ){
  1800. rbuBadControlError(p);
  1801. }else{
  1802. const char *zSep = "";
  1803. for(i=0; i<pIter->nTblCol; i++){
  1804. char c = zMask[pIter->aiSrcOrder[i]];
  1805. if( c=='x' ){
  1806. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  1807. zList, zSep, pIter->azTblCol[i], i+1
  1808. );
  1809. zSep = ", ";
  1810. }
  1811. else if( c=='d' ){
  1812. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  1813. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  1814. );
  1815. zSep = ", ";
  1816. }
  1817. else if( c=='f' ){
  1818. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  1819. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  1820. );
  1821. zSep = ", ";
  1822. }
  1823. }
  1824. }
  1825. }
  1826. return zList;
  1827. }
  1828. /*
  1829. ** Return a nul-terminated string consisting of nByte comma separated
  1830. ** "?" expressions. For example, if nByte is 3, return a pointer to
  1831. ** a buffer containing the string "?,?,?".
  1832. **
  1833. ** The memory for the returned string is obtained from sqlite3_malloc().
  1834. ** It is the responsibility of the caller to eventually free it using
  1835. ** sqlite3_free().
  1836. **
  1837. ** If an OOM error is encountered when allocating space for the new
  1838. ** string, an error code is left in the rbu handle passed as the first
  1839. ** argument and NULL is returned. Or, if an error has already occurred
  1840. ** when this function is called, NULL is returned immediately, without
  1841. ** attempting the allocation or modifying the stored error code.
  1842. */
  1843. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  1844. char *zRet = 0;
  1845. sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
  1846. zRet = (char*)rbuMalloc(p, nByte);
  1847. if( zRet ){
  1848. int i;
  1849. for(i=0; i<nBind; i++){
  1850. zRet[i*2] = '?';
  1851. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  1852. }
  1853. }
  1854. return zRet;
  1855. }
  1856. /*
  1857. ** The iterator currently points to a table (not index) of type
  1858. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  1859. ** declaration for the corresponding imposter table. For example,
  1860. ** if the iterator points to a table created as:
  1861. **
  1862. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  1863. **
  1864. ** this function returns:
  1865. **
  1866. ** PRIMARY KEY("b", "a" DESC)
  1867. */
  1868. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  1869. char *z = 0;
  1870. assert( pIter->zIdx==0 );
  1871. if( p->rc==SQLITE_OK ){
  1872. const char *zSep = "PRIMARY KEY(";
  1873. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  1874. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  1875. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  1876. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  1877. );
  1878. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  1879. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  1880. if( zOrig && strcmp(zOrig, "pk")==0 ){
  1881. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  1882. if( zIdx ){
  1883. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  1884. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  1885. );
  1886. }
  1887. break;
  1888. }
  1889. }
  1890. rbuFinalize(p, pXList);
  1891. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  1892. if( sqlite3_column_int(pXInfo, 5) ){
  1893. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  1894. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  1895. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  1896. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  1897. zSep = ", ";
  1898. }
  1899. }
  1900. z = rbuMPrintf(p, "%z)", z);
  1901. rbuFinalize(p, pXInfo);
  1902. }
  1903. return z;
  1904. }
  1905. /*
  1906. ** This function creates the second imposter table used when writing to
  1907. ** a table b-tree where the table has an external primary key. If the
  1908. ** iterator passed as the second argument does not currently point to
  1909. ** a table (not index) with an external primary key, this function is a
  1910. ** no-op.
  1911. **
  1912. ** Assuming the iterator does point to a table with an external PK, this
  1913. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  1914. ** used to access that PK index. For example, if the target table is
  1915. ** declared as follows:
  1916. **
  1917. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  1918. **
  1919. ** then the imposter table schema is:
  1920. **
  1921. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  1922. **
  1923. */
  1924. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  1925. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  1926. int tnum = pIter->iPkTnum; /* Root page of PK index */
  1927. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  1928. const char *zIdx = 0; /* Name of PK index */
  1929. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  1930. const char *zComma = "";
  1931. char *zCols = 0; /* Used to build up list of table cols */
  1932. char *zPk = 0; /* Used to build up table PK declaration */
  1933. /* Figure out the name of the primary key index for the current table.
  1934. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  1935. ** zIdx to point to a nul-terminated string containing this name. */
  1936. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  1937. "SELECT name FROM sqlite_schema WHERE rootpage = ?"
  1938. );
  1939. if( p->rc==SQLITE_OK ){
  1940. sqlite3_bind_int(pQuery, 1, tnum);
  1941. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  1942. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  1943. }
  1944. }
  1945. if( zIdx ){
  1946. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  1947. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  1948. );
  1949. }
  1950. rbuFinalize(p, pQuery);
  1951. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  1952. int bKey = sqlite3_column_int(pXInfo, 5);
  1953. if( bKey ){
  1954. int iCid = sqlite3_column_int(pXInfo, 1);
  1955. int bDesc = sqlite3_column_int(pXInfo, 3);
  1956. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  1957. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  1958. iCid, pIter->azTblType[iCid], zCollate
  1959. );
  1960. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  1961. zComma = ", ";
  1962. }
  1963. }
  1964. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  1965. rbuFinalize(p, pXInfo);
  1966. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  1967. rbuMPrintfExec(p, p->dbMain,
  1968. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  1969. zCols, zPk
  1970. );
  1971. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  1972. }
  1973. }
  1974. /*
  1975. ** If an error has already occurred when this function is called, it
  1976. ** immediately returns zero (without doing any work). Or, if an error
  1977. ** occurs during the execution of this function, it sets the error code
  1978. ** in the sqlite3rbu object indicated by the first argument and returns
  1979. ** zero.
  1980. **
  1981. ** The iterator passed as the second argument is guaranteed to point to
  1982. ** a table (not an index) when this function is called. This function
  1983. ** attempts to create any imposter table required to write to the main
  1984. ** table b-tree of the table before returning. Non-zero is returned if
  1985. ** an imposter table are created, or zero otherwise.
  1986. **
  1987. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  1988. ** virtual tables are written to directly. The imposter table has the
  1989. ** same schema as the actual target table (less any UNIQUE constraints).
  1990. ** More precisely, the "same schema" means the same columns, types,
  1991. ** collation sequences. For tables that do not have an external PRIMARY
  1992. ** KEY, it also means the same PRIMARY KEY declaration.
  1993. */
  1994. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  1995. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  1996. int tnum = pIter->iTnum;
  1997. const char *zComma = "";
  1998. char *zSql = 0;
  1999. int iCol;
  2000. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  2001. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  2002. const char *zPk = "";
  2003. const char *zCol = pIter->azTblCol[iCol];
  2004. const char *zColl = 0;
  2005. p->rc = sqlite3_table_column_metadata(
  2006. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  2007. );
  2008. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  2009. /* If the target table column is an "INTEGER PRIMARY KEY", add
  2010. ** "PRIMARY KEY" to the imposter table column declaration. */
  2011. zPk = "PRIMARY KEY ";
  2012. }
  2013. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  2014. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  2015. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  2016. );
  2017. zComma = ", ";
  2018. }
  2019. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  2020. char *zPk = rbuWithoutRowidPK(p, pIter);
  2021. if( zPk ){
  2022. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  2023. }
  2024. }
  2025. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  2026. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  2027. pIter->zTbl, zSql,
  2028. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  2029. );
  2030. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  2031. }
  2032. }
  2033. /*
  2034. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  2035. ** Specifically a statement of the form:
  2036. **
  2037. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  2038. **
  2039. ** The number of bound variables is equal to the number of columns in
  2040. ** the target table, plus one (for the rbu_control column), plus one more
  2041. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  2042. ** virtual table.
  2043. */
  2044. static void rbuObjIterPrepareTmpInsert(
  2045. sqlite3rbu *p,
  2046. RbuObjIter *pIter,
  2047. const char *zCollist,
  2048. const char *zRbuRowid
  2049. ){
  2050. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  2051. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  2052. if( zBind ){
  2053. assert( pIter->pTmpInsert==0 );
  2054. p->rc = prepareFreeAndCollectError(
  2055. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  2056. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  2057. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  2058. ));
  2059. }
  2060. }
  2061. static void rbuTmpInsertFunc(
  2062. sqlite3_context *pCtx,
  2063. int nVal,
  2064. sqlite3_value **apVal
  2065. ){
  2066. sqlite3rbu *p = sqlite3_user_data(pCtx);
  2067. int rc = SQLITE_OK;
  2068. int i;
  2069. assert( sqlite3_value_int(apVal[0])!=0
  2070. || p->objiter.eType==RBU_PK_EXTERNAL
  2071. || p->objiter.eType==RBU_PK_NONE
  2072. );
  2073. if( sqlite3_value_int(apVal[0])!=0 ){
  2074. p->nPhaseOneStep += p->objiter.nIndex;
  2075. }
  2076. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  2077. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  2078. }
  2079. if( rc==SQLITE_OK ){
  2080. sqlite3_step(p->objiter.pTmpInsert);
  2081. rc = sqlite3_reset(p->objiter.pTmpInsert);
  2082. }
  2083. if( rc!=SQLITE_OK ){
  2084. sqlite3_result_error_code(pCtx, rc);
  2085. }
  2086. }
  2087. static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
  2088. sqlite3_stmt *pStmt = 0;
  2089. int rc = p->rc;
  2090. char *zRet = 0;
  2091. assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 );
  2092. if( rc==SQLITE_OK ){
  2093. rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  2094. "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?"
  2095. );
  2096. }
  2097. if( rc==SQLITE_OK ){
  2098. int rc2;
  2099. rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
  2100. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  2101. char *zSql = (char*)sqlite3_column_text(pStmt, 0);
  2102. if( zSql ){
  2103. pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc);
  2104. }
  2105. if( zSql ){
  2106. int nParen = 0; /* Number of open parenthesis */
  2107. int i;
  2108. int iIdxCol = 0;
  2109. int nIdxAlloc = 0;
  2110. for(i=0; zSql[i]; i++){
  2111. char c = zSql[i];
  2112. /* If necessary, grow the pIter->aIdxCol[] array */
  2113. if( iIdxCol==nIdxAlloc ){
  2114. RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc(
  2115. pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan)
  2116. );
  2117. if( aIdxCol==0 ){
  2118. rc = SQLITE_NOMEM;
  2119. break;
  2120. }
  2121. pIter->aIdxCol = aIdxCol;
  2122. nIdxAlloc += 16;
  2123. }
  2124. if( c=='(' ){
  2125. if( nParen==0 ){
  2126. assert( iIdxCol==0 );
  2127. pIter->aIdxCol[0].zSpan = &zSql[i+1];
  2128. }
  2129. nParen++;
  2130. }
  2131. else if( c==')' ){
  2132. nParen--;
  2133. if( nParen==0 ){
  2134. int nSpan = (int)(&zSql[i] - pIter->aIdxCol[iIdxCol].zSpan);
  2135. pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
  2136. i++;
  2137. break;
  2138. }
  2139. }else if( c==',' && nParen==1 ){
  2140. int nSpan = (int)(&zSql[i] - pIter->aIdxCol[iIdxCol].zSpan);
  2141. pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
  2142. pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1];
  2143. }else if( c=='"' || c=='\'' || c=='`' ){
  2144. for(i++; 1; i++){
  2145. if( zSql[i]==c ){
  2146. if( zSql[i+1]!=c ) break;
  2147. i++;
  2148. }
  2149. }
  2150. }else if( c=='[' ){
  2151. for(i++; 1; i++){
  2152. if( zSql[i]==']' ) break;
  2153. }
  2154. }else if( c=='-' && zSql[i+1]=='-' ){
  2155. for(i=i+2; zSql[i] && zSql[i]!='\n'; i++);
  2156. if( zSql[i]=='\0' ) break;
  2157. }else if( c=='/' && zSql[i+1]=='*' ){
  2158. for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++);
  2159. if( zSql[i]=='\0' ) break;
  2160. i++;
  2161. }
  2162. }
  2163. if( zSql[i] ){
  2164. zRet = rbuStrndup(&zSql[i], &rc);
  2165. }
  2166. pIter->nIdxCol = iIdxCol;
  2167. }
  2168. }
  2169. rc2 = sqlite3_finalize(pStmt);
  2170. if( rc==SQLITE_OK ) rc = rc2;
  2171. }
  2172. p->rc = rc;
  2173. return zRet;
  2174. }
  2175. /*
  2176. ** Ensure that the SQLite statement handles required to update the
  2177. ** target database object currently indicated by the iterator passed
  2178. ** as the second argument are available.
  2179. */
  2180. static int rbuObjIterPrepareAll(
  2181. sqlite3rbu *p,
  2182. RbuObjIter *pIter,
  2183. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  2184. ){
  2185. assert( pIter->bCleanup==0 );
  2186. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  2187. const int tnum = pIter->iTnum;
  2188. char *zCollist = 0; /* List of indexed columns */
  2189. char **pz = &p->zErrmsg;
  2190. const char *zIdx = pIter->zIdx;
  2191. char *zLimit = 0;
  2192. if( nOffset ){
  2193. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  2194. if( !zLimit ) p->rc = SQLITE_NOMEM;
  2195. }
  2196. if( zIdx ){
  2197. const char *zTbl = pIter->zTbl;
  2198. char *zImposterCols = 0; /* Columns for imposter table */
  2199. char *zImposterPK = 0; /* Primary key declaration for imposter */
  2200. char *zWhere = 0; /* WHERE clause on PK columns */
  2201. char *zBind = 0;
  2202. char *zPart = 0;
  2203. int nBind = 0;
  2204. assert( pIter->eType!=RBU_PK_VTAB );
  2205. zPart = rbuObjIterGetIndexWhere(p, pIter);
  2206. zCollist = rbuObjIterGetIndexCols(
  2207. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  2208. );
  2209. zBind = rbuObjIterGetBindlist(p, nBind);
  2210. /* Create the imposter table used to write to this index. */
  2211. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  2212. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  2213. rbuMPrintfExec(p, p->dbMain,
  2214. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  2215. zTbl, zImposterCols, zImposterPK
  2216. );
  2217. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  2218. /* Create the statement to insert index entries */
  2219. pIter->nCol = nBind;
  2220. if( p->rc==SQLITE_OK ){
  2221. p->rc = prepareFreeAndCollectError(
  2222. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  2223. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  2224. );
  2225. }
  2226. /* And to delete index entries */
  2227. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  2228. p->rc = prepareFreeAndCollectError(
  2229. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  2230. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  2231. );
  2232. }
  2233. /* Create the SELECT statement to read keys in sorted order */
  2234. if( p->rc==SQLITE_OK ){
  2235. char *zSql;
  2236. if( rbuIsVacuum(p) ){
  2237. char *zStart = 0;
  2238. if( nOffset ){
  2239. zStart = rbuVacuumIndexStart(p, pIter);
  2240. if( zStart ){
  2241. sqlite3_free(zLimit);
  2242. zLimit = 0;
  2243. }
  2244. }
  2245. zSql = sqlite3_mprintf(
  2246. "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
  2247. zCollist,
  2248. pIter->zDataTbl,
  2249. zPart,
  2250. (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
  2251. zCollist, zLimit
  2252. );
  2253. sqlite3_free(zStart);
  2254. }else
  2255. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  2256. zSql = sqlite3_mprintf(
  2257. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
  2258. zCollist, p->zStateDb, pIter->zDataTbl,
  2259. zPart, zCollist, zLimit
  2260. );
  2261. }else{
  2262. zSql = sqlite3_mprintf(
  2263. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
  2264. "UNION ALL "
  2265. "SELECT %s, rbu_control FROM '%q' "
  2266. "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
  2267. "ORDER BY %s%s",
  2268. zCollist, p->zStateDb, pIter->zDataTbl, zPart,
  2269. zCollist, pIter->zDataTbl,
  2270. zPart,
  2271. (zPart ? "AND" : "WHERE"),
  2272. zCollist, zLimit
  2273. );
  2274. }
  2275. if( p->rc==SQLITE_OK ){
  2276. p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);
  2277. }else{
  2278. sqlite3_free(zSql);
  2279. }
  2280. }
  2281. sqlite3_free(zImposterCols);
  2282. sqlite3_free(zImposterPK);
  2283. sqlite3_free(zWhere);
  2284. sqlite3_free(zBind);
  2285. sqlite3_free(zPart);
  2286. }else{
  2287. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  2288. ||(pIter->eType==RBU_PK_NONE)
  2289. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  2290. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  2291. const char *zWrite; /* Imposter table name */
  2292. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  2293. char *zWhere = rbuObjIterGetWhere(p, pIter);
  2294. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  2295. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  2296. zCollist = rbuObjIterGetCollist(p, pIter);
  2297. pIter->nCol = pIter->nTblCol;
  2298. /* Create the imposter table or tables (if required). */
  2299. rbuCreateImposterTable(p, pIter);
  2300. rbuCreateImposterTable2(p, pIter);
  2301. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  2302. /* Create the INSERT statement to write to the target PK b-tree */
  2303. if( p->rc==SQLITE_OK ){
  2304. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  2305. sqlite3_mprintf(
  2306. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  2307. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  2308. )
  2309. );
  2310. }
  2311. /* Create the DELETE statement to write to the target PK b-tree.
  2312. ** Because it only performs INSERT operations, this is not required for
  2313. ** an rbu vacuum handle. */
  2314. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  2315. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  2316. sqlite3_mprintf(
  2317. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  2318. )
  2319. );
  2320. }
  2321. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  2322. const char *zRbuRowid = "";
  2323. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  2324. zRbuRowid = ", rbu_rowid";
  2325. }
  2326. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  2327. rbuMPrintfExec(p, p->dbRbu,
  2328. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  2329. "SELECT *%s FROM '%q' WHERE 0;"
  2330. , p->zStateDb, pIter->zDataTbl
  2331. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  2332. , pIter->zDataTbl
  2333. );
  2334. rbuMPrintfExec(p, p->dbMain,
  2335. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  2336. "BEGIN "
  2337. " SELECT rbu_tmp_insert(3, %s);"
  2338. "END;"
  2339. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  2340. "BEGIN "
  2341. " SELECT rbu_tmp_insert(3, %s);"
  2342. "END;"
  2343. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  2344. "BEGIN "
  2345. " SELECT rbu_tmp_insert(4, %s);"
  2346. "END;",
  2347. zWrite, zTbl, zOldlist,
  2348. zWrite, zTbl, zOldlist,
  2349. zWrite, zTbl, zNewlist
  2350. );
  2351. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  2352. rbuMPrintfExec(p, p->dbMain,
  2353. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  2354. "BEGIN "
  2355. " SELECT rbu_tmp_insert(0, %s);"
  2356. "END;",
  2357. zWrite, zTbl, zNewlist
  2358. );
  2359. }
  2360. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  2361. }
  2362. /* Create the SELECT statement to read keys from data_xxx */
  2363. if( p->rc==SQLITE_OK ){
  2364. const char *zRbuRowid = "";
  2365. char *zStart = 0;
  2366. char *zOrder = 0;
  2367. if( bRbuRowid ){
  2368. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  2369. }
  2370. if( rbuIsVacuum(p) ){
  2371. if( nOffset ){
  2372. zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);
  2373. if( zStart ){
  2374. sqlite3_free(zLimit);
  2375. zLimit = 0;
  2376. }
  2377. }
  2378. if( bRbuRowid ){
  2379. zOrder = rbuMPrintf(p, "_rowid_");
  2380. }else{
  2381. zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", "");
  2382. }
  2383. }
  2384. if( p->rc==SQLITE_OK ){
  2385. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  2386. sqlite3_mprintf(
  2387. "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
  2388. zCollist,
  2389. (rbuIsVacuum(p) ? "0 AS " : ""),
  2390. zRbuRowid,
  2391. pIter->zDataTbl, (zStart ? zStart : ""),
  2392. (zOrder ? "ORDER BY" : ""), zOrder,
  2393. zLimit
  2394. )
  2395. );
  2396. }
  2397. sqlite3_free(zStart);
  2398. sqlite3_free(zOrder);
  2399. }
  2400. sqlite3_free(zWhere);
  2401. sqlite3_free(zOldlist);
  2402. sqlite3_free(zNewlist);
  2403. sqlite3_free(zBindings);
  2404. }
  2405. sqlite3_free(zCollist);
  2406. sqlite3_free(zLimit);
  2407. }
  2408. return p->rc;
  2409. }
  2410. /*
  2411. ** Set output variable *ppStmt to point to an UPDATE statement that may
  2412. ** be used to update the imposter table for the main table b-tree of the
  2413. ** table object that pIter currently points to, assuming that the
  2414. ** rbu_control column of the data_xyz table contains zMask.
  2415. **
  2416. ** If the zMask string does not specify any columns to update, then this
  2417. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  2418. */
  2419. static int rbuGetUpdateStmt(
  2420. sqlite3rbu *p, /* RBU handle */
  2421. RbuObjIter *pIter, /* Object iterator */
  2422. const char *zMask, /* rbu_control value ('x.x.') */
  2423. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  2424. ){
  2425. RbuUpdateStmt **pp;
  2426. RbuUpdateStmt *pUp = 0;
  2427. int nUp = 0;
  2428. /* In case an error occurs */
  2429. *ppStmt = 0;
  2430. /* Search for an existing statement. If one is found, shift it to the front
  2431. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  2432. ** to the number of statements currently in the cache and pUp to the
  2433. ** last object in the list. */
  2434. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  2435. pUp = *pp;
  2436. if( strcmp(pUp->zMask, zMask)==0 ){
  2437. *pp = pUp->pNext;
  2438. pUp->pNext = pIter->pRbuUpdate;
  2439. pIter->pRbuUpdate = pUp;
  2440. *ppStmt = pUp->pUpdate;
  2441. return SQLITE_OK;
  2442. }
  2443. nUp++;
  2444. }
  2445. assert( pUp==0 || pUp->pNext==0 );
  2446. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  2447. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  2448. *pp = 0;
  2449. sqlite3_finalize(pUp->pUpdate);
  2450. pUp->pUpdate = 0;
  2451. }else{
  2452. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  2453. }
  2454. if( pUp ){
  2455. char *zWhere = rbuObjIterGetWhere(p, pIter);
  2456. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  2457. char *zUpdate = 0;
  2458. pUp->zMask = (char*)&pUp[1];
  2459. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  2460. pUp->pNext = pIter->pRbuUpdate;
  2461. pIter->pRbuUpdate = pUp;
  2462. if( zSet ){
  2463. const char *zPrefix = "";
  2464. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  2465. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  2466. zPrefix, pIter->zTbl, zSet, zWhere
  2467. );
  2468. p->rc = prepareFreeAndCollectError(
  2469. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  2470. );
  2471. *ppStmt = pUp->pUpdate;
  2472. }
  2473. sqlite3_free(zWhere);
  2474. sqlite3_free(zSet);
  2475. }
  2476. return p->rc;
  2477. }
  2478. static sqlite3 *rbuOpenDbhandle(
  2479. sqlite3rbu *p,
  2480. const char *zName,
  2481. int bUseVfs
  2482. ){
  2483. sqlite3 *db = 0;
  2484. if( p->rc==SQLITE_OK ){
  2485. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  2486. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  2487. if( p->rc ){
  2488. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  2489. sqlite3_close(db);
  2490. db = 0;
  2491. }
  2492. }
  2493. return db;
  2494. }
  2495. /*
  2496. ** Free an RbuState object allocated by rbuLoadState().
  2497. */
  2498. static void rbuFreeState(RbuState *p){
  2499. if( p ){
  2500. sqlite3_free(p->zTbl);
  2501. sqlite3_free(p->zDataTbl);
  2502. sqlite3_free(p->zIdx);
  2503. sqlite3_free(p);
  2504. }
  2505. }
  2506. /*
  2507. ** Allocate an RbuState object and load the contents of the rbu_state
  2508. ** table into it. Return a pointer to the new object. It is the
  2509. ** responsibility of the caller to eventually free the object using
  2510. ** sqlite3_free().
  2511. **
  2512. ** If an error occurs, leave an error code and message in the rbu handle
  2513. ** and return NULL.
  2514. */
  2515. static RbuState *rbuLoadState(sqlite3rbu *p){
  2516. RbuState *pRet = 0;
  2517. sqlite3_stmt *pStmt = 0;
  2518. int rc;
  2519. int rc2;
  2520. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  2521. if( pRet==0 ) return 0;
  2522. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  2523. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  2524. );
  2525. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  2526. switch( sqlite3_column_int(pStmt, 0) ){
  2527. case RBU_STATE_STAGE:
  2528. pRet->eStage = sqlite3_column_int(pStmt, 1);
  2529. if( pRet->eStage!=RBU_STAGE_OAL
  2530. && pRet->eStage!=RBU_STAGE_MOVE
  2531. && pRet->eStage!=RBU_STAGE_CKPT
  2532. ){
  2533. p->rc = SQLITE_CORRUPT;
  2534. }
  2535. break;
  2536. case RBU_STATE_TBL:
  2537. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  2538. break;
  2539. case RBU_STATE_IDX:
  2540. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  2541. break;
  2542. case RBU_STATE_ROW:
  2543. pRet->nRow = sqlite3_column_int(pStmt, 1);
  2544. break;
  2545. case RBU_STATE_PROGRESS:
  2546. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  2547. break;
  2548. case RBU_STATE_CKPT:
  2549. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  2550. break;
  2551. case RBU_STATE_COOKIE:
  2552. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  2553. break;
  2554. case RBU_STATE_OALSZ:
  2555. pRet->iOalSz = sqlite3_column_int64(pStmt, 1);
  2556. break;
  2557. case RBU_STATE_PHASEONESTEP:
  2558. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  2559. break;
  2560. case RBU_STATE_DATATBL:
  2561. pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  2562. break;
  2563. default:
  2564. rc = SQLITE_CORRUPT;
  2565. break;
  2566. }
  2567. }
  2568. rc2 = sqlite3_finalize(pStmt);
  2569. if( rc==SQLITE_OK ) rc = rc2;
  2570. p->rc = rc;
  2571. return pRet;
  2572. }
  2573. /*
  2574. ** Open the database handle and attach the RBU database as "rbu". If an
  2575. ** error occurs, leave an error code and message in the RBU handle.
  2576. **
  2577. ** If argument dbMain is not NULL, then it is a database handle already
  2578. ** open on the target database. Use this handle instead of opening a new
  2579. ** one.
  2580. */
  2581. static void rbuOpenDatabase(sqlite3rbu *p, sqlite3 *dbMain, int *pbRetry){
  2582. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  2583. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  2584. assert( dbMain==0 || rbuIsVacuum(p)==0 );
  2585. /* Open the RBU database */
  2586. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  2587. p->dbMain = dbMain;
  2588. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  2589. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  2590. if( p->zState==0 ){
  2591. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  2592. p->zState = rbuMPrintf(p, "file:///%s-vacuum?modeof=%s", zFile, zFile);
  2593. }
  2594. }
  2595. /* If using separate RBU and state databases, attach the state database to
  2596. ** the RBU db handle now. */
  2597. if( p->zState ){
  2598. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  2599. memcpy(p->zStateDb, "stat", 4);
  2600. }else{
  2601. memcpy(p->zStateDb, "main", 4);
  2602. }
  2603. #if 0
  2604. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  2605. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  2606. }
  2607. #endif
  2608. /* If it has not already been created, create the rbu_state table */
  2609. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  2610. #if 0
  2611. if( rbuIsVacuum(p) ){
  2612. if( p->rc==SQLITE_OK ){
  2613. int rc2;
  2614. int bOk = 0;
  2615. sqlite3_stmt *pCnt = 0;
  2616. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  2617. "SELECT count(*) FROM stat.sqlite_schema"
  2618. );
  2619. if( p->rc==SQLITE_OK
  2620. && sqlite3_step(pCnt)==SQLITE_ROW
  2621. && 1==sqlite3_column_int(pCnt, 0)
  2622. ){
  2623. bOk = 1;
  2624. }
  2625. rc2 = sqlite3_finalize(pCnt);
  2626. if( p->rc==SQLITE_OK ) p->rc = rc2;
  2627. if( p->rc==SQLITE_OK && bOk==0 ){
  2628. p->rc = SQLITE_ERROR;
  2629. p->zErrmsg = sqlite3_mprintf("invalid state database");
  2630. }
  2631. if( p->rc==SQLITE_OK ){
  2632. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  2633. }
  2634. }
  2635. }
  2636. #endif
  2637. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  2638. int bOpen = 0;
  2639. int rc;
  2640. p->nRbu = 0;
  2641. p->pRbuFd = 0;
  2642. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  2643. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  2644. if( p->eStage>=RBU_STAGE_MOVE ){
  2645. bOpen = 1;
  2646. }else{
  2647. RbuState *pState = rbuLoadState(p);
  2648. if( pState ){
  2649. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  2650. rbuFreeState(pState);
  2651. }
  2652. }
  2653. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  2654. }
  2655. p->eStage = 0;
  2656. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  2657. if( !rbuIsVacuum(p) ){
  2658. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  2659. }else if( p->pRbuFd->pWalFd ){
  2660. if( pbRetry ){
  2661. p->pRbuFd->bNolock = 0;
  2662. sqlite3_close(p->dbRbu);
  2663. sqlite3_close(p->dbMain);
  2664. p->dbMain = 0;
  2665. p->dbRbu = 0;
  2666. *pbRetry = 1;
  2667. return;
  2668. }
  2669. p->rc = SQLITE_ERROR;
  2670. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  2671. }else{
  2672. char *zTarget;
  2673. char *zExtra = 0;
  2674. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  2675. zExtra = &p->zRbu[5];
  2676. while( *zExtra ){
  2677. if( *zExtra++=='?' ) break;
  2678. }
  2679. if( *zExtra=='\0' ) zExtra = 0;
  2680. }
  2681. zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
  2682. sqlite3_db_filename(p->dbRbu, "main"),
  2683. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  2684. );
  2685. if( zTarget==0 ){
  2686. p->rc = SQLITE_NOMEM;
  2687. return;
  2688. }
  2689. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  2690. sqlite3_free(zTarget);
  2691. }
  2692. }
  2693. if( p->rc==SQLITE_OK ){
  2694. p->rc = sqlite3_create_function(p->dbMain,
  2695. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  2696. );
  2697. }
  2698. if( p->rc==SQLITE_OK ){
  2699. p->rc = sqlite3_create_function(p->dbMain,
  2700. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  2701. );
  2702. }
  2703. if( p->rc==SQLITE_OK ){
  2704. p->rc = sqlite3_create_function(p->dbRbu,
  2705. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  2706. );
  2707. }
  2708. if( p->rc==SQLITE_OK ){
  2709. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  2710. }
  2711. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
  2712. /* Mark the database file just opened as an RBU target database. If
  2713. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  2714. ** This is an error. */
  2715. if( p->rc==SQLITE_OK ){
  2716. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  2717. }
  2718. if( p->rc==SQLITE_NOTFOUND ){
  2719. p->rc = SQLITE_ERROR;
  2720. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  2721. }
  2722. }
  2723. /*
  2724. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  2725. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  2726. **
  2727. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  2728. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  2729. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  2730. ** three characters, then shorten the suffix on z[] to be the last three
  2731. ** characters of the original suffix.
  2732. **
  2733. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  2734. ** do the suffix shortening regardless of URI parameter.
  2735. **
  2736. ** Examples:
  2737. **
  2738. ** test.db-journal => test.nal
  2739. ** test.db-wal => test.wal
  2740. ** test.db-shm => test.shm
  2741. ** test.db-mj7f3319fa => test.9fa
  2742. */
  2743. static void rbuFileSuffix3(const char *zBase, char *z){
  2744. #ifdef SQLITE_ENABLE_8_3_NAMES
  2745. #if SQLITE_ENABLE_8_3_NAMES<2
  2746. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  2747. #endif
  2748. {
  2749. int i, sz;
  2750. sz = (int)strlen(z)&0xffffff;
  2751. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  2752. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  2753. }
  2754. #else
  2755. UNUSED_PARAMETER2(zBase,z);
  2756. #endif
  2757. }
  2758. /*
  2759. ** Return the current wal-index header checksum for the target database
  2760. ** as a 64-bit integer.
  2761. **
  2762. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  2763. ** blob starting at byte offset 40.
  2764. */
  2765. static i64 rbuShmChecksum(sqlite3rbu *p){
  2766. i64 iRet = 0;
  2767. if( p->rc==SQLITE_OK ){
  2768. sqlite3_file *pDb = p->pTargetFd->pReal;
  2769. u32 volatile *ptr;
  2770. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  2771. if( p->rc==SQLITE_OK ){
  2772. iRet = (i64)(((u64)ptr[10] << 32) + ptr[11]);
  2773. }
  2774. }
  2775. return iRet;
  2776. }
  2777. /*
  2778. ** This function is called as part of initializing or reinitializing an
  2779. ** incremental checkpoint.
  2780. **
  2781. ** It populates the sqlite3rbu.aFrame[] array with the set of
  2782. ** (wal frame -> db page) copy operations required to checkpoint the
  2783. ** current wal file, and obtains the set of shm locks required to safely
  2784. ** perform the copy operations directly on the file-system.
  2785. **
  2786. ** If argument pState is not NULL, then the incremental checkpoint is
  2787. ** being resumed. In this case, if the checksum of the wal-index-header
  2788. ** following recovery is not the same as the checksum saved in the RbuState
  2789. ** object, then the rbu handle is set to DONE state. This occurs if some
  2790. ** other client appends a transaction to the wal file in the middle of
  2791. ** an incremental checkpoint.
  2792. */
  2793. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  2794. /* If pState is NULL, then the wal file may not have been opened and
  2795. ** recovered. Running a read-statement here to ensure that doing so
  2796. ** does not interfere with the "capture" process below. */
  2797. if( pState==0 ){
  2798. p->eStage = 0;
  2799. if( p->rc==SQLITE_OK ){
  2800. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0);
  2801. }
  2802. }
  2803. /* Assuming no error has occurred, run a "restart" checkpoint with the
  2804. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  2805. ** special behaviour in the rbu VFS:
  2806. **
  2807. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  2808. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  2809. ** proceed with running a passive checkpoint instead of failing).
  2810. **
  2811. ** * Attempts to read from the *-wal file or write to the database file
  2812. ** do not perform any IO. Instead, the frame/page combinations that
  2813. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  2814. ** array.
  2815. **
  2816. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  2817. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  2818. ** no-ops. These locks will not be released until the connection
  2819. ** is closed.
  2820. **
  2821. ** * Attempting to xSync() the database file causes an SQLITE_NOTICE
  2822. ** error.
  2823. **
  2824. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  2825. ** checkpoint below fails with SQLITE_NOTICE, and leaves the aFrame[]
  2826. ** array populated with a set of (frame -> page) mappings. Because the
  2827. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  2828. ** data from the wal file into the database file according to the
  2829. ** contents of aFrame[].
  2830. */
  2831. if( p->rc==SQLITE_OK ){
  2832. int rc2;
  2833. p->eStage = RBU_STAGE_CAPTURE;
  2834. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  2835. if( rc2!=SQLITE_NOTICE ) p->rc = rc2;
  2836. }
  2837. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  2838. p->eStage = RBU_STAGE_CKPT;
  2839. p->nStep = (pState ? pState->nRow : 0);
  2840. p->aBuf = rbuMalloc(p, p->pgsz);
  2841. p->iWalCksum = rbuShmChecksum(p);
  2842. }
  2843. if( p->rc==SQLITE_OK ){
  2844. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  2845. p->rc = SQLITE_DONE;
  2846. p->eStage = RBU_STAGE_DONE;
  2847. }else{
  2848. int nSectorSize;
  2849. sqlite3_file *pDb = p->pTargetFd->pReal;
  2850. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  2851. assert( p->nPagePerSector==0 );
  2852. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  2853. if( nSectorSize>p->pgsz ){
  2854. p->nPagePerSector = nSectorSize / p->pgsz;
  2855. }else{
  2856. p->nPagePerSector = 1;
  2857. }
  2858. /* Call xSync() on the wal file. This causes SQLite to sync the
  2859. ** directory in which the target database and the wal file reside, in
  2860. ** case it has not been synced since the rename() call in
  2861. ** rbuMoveOalFile(). */
  2862. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  2863. }
  2864. }
  2865. }
  2866. /*
  2867. ** Called when iAmt bytes are read from offset iOff of the wal file while
  2868. ** the rbu object is in capture mode. Record the frame number of the frame
  2869. ** being read in the aFrame[] array.
  2870. */
  2871. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  2872. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  2873. u32 iFrame;
  2874. if( pRbu->mLock!=mReq ){
  2875. pRbu->rc = SQLITE_BUSY;
  2876. return SQLITE_NOTICE_RBU;
  2877. }
  2878. pRbu->pgsz = iAmt;
  2879. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  2880. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  2881. RbuFrame *aNew;
  2882. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  2883. if( aNew==0 ) return SQLITE_NOMEM;
  2884. pRbu->aFrame = aNew;
  2885. pRbu->nFrameAlloc = nNew;
  2886. }
  2887. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  2888. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  2889. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  2890. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  2891. pRbu->nFrame++;
  2892. return SQLITE_OK;
  2893. }
  2894. /*
  2895. ** Called when a page of data is written to offset iOff of the database
  2896. ** file while the rbu handle is in capture mode. Record the page number
  2897. ** of the page being written in the aFrame[] array.
  2898. */
  2899. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  2900. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  2901. return SQLITE_OK;
  2902. }
  2903. /*
  2904. ** This is called as part of an incremental checkpoint operation. Copy
  2905. ** a single frame of data from the wal file into the database file, as
  2906. ** indicated by the RbuFrame object.
  2907. */
  2908. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  2909. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  2910. sqlite3_file *pDb = p->pTargetFd->pReal;
  2911. i64 iOff;
  2912. assert( p->rc==SQLITE_OK );
  2913. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  2914. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  2915. if( p->rc ) return;
  2916. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  2917. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  2918. }
  2919. /*
  2920. ** This value is copied from the definition of ZIPVFS_CTRL_FILE_POINTER
  2921. ** in zipvfs.h.
  2922. */
  2923. #define RBU_ZIPVFS_CTRL_FILE_POINTER 230439
  2924. /*
  2925. ** Take an EXCLUSIVE lock on the database file. Return SQLITE_OK if
  2926. ** successful, or an SQLite error code otherwise.
  2927. */
  2928. static int rbuLockDatabase(sqlite3 *db){
  2929. int rc = SQLITE_OK;
  2930. sqlite3_file *fd = 0;
  2931. sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
  2932. if( fd ){
  2933. sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
  2934. rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
  2935. if( rc==SQLITE_OK ){
  2936. rc = fd->pMethods->xUnlock(fd, SQLITE_LOCK_NONE);
  2937. }
  2938. sqlite3_file_control(db, "main", RBU_ZIPVFS_CTRL_FILE_POINTER, &fd);
  2939. }else{
  2940. sqlite3_file_control(db, "main", SQLITE_FCNTL_FILE_POINTER, &fd);
  2941. }
  2942. if( rc==SQLITE_OK && fd->pMethods ){
  2943. rc = fd->pMethods->xLock(fd, SQLITE_LOCK_SHARED);
  2944. if( rc==SQLITE_OK ){
  2945. rc = fd->pMethods->xLock(fd, SQLITE_LOCK_EXCLUSIVE);
  2946. }
  2947. }
  2948. return rc;
  2949. }
  2950. /*
  2951. ** Return true if the database handle passed as the only argument
  2952. ** was opened with the rbu_exclusive_checkpoint=1 URI parameter
  2953. ** specified. Or false otherwise.
  2954. */
  2955. static int rbuExclusiveCheckpoint(sqlite3 *db){
  2956. const char *zUri = sqlite3_db_filename(db, 0);
  2957. return sqlite3_uri_boolean(zUri, RBU_EXCLUSIVE_CHECKPOINT, 0);
  2958. }
  2959. #if defined(_WIN32_WCE)
  2960. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  2961. int nChar;
  2962. LPWSTR zWideFilename;
  2963. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  2964. if( nChar==0 ){
  2965. return 0;
  2966. }
  2967. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  2968. if( zWideFilename==0 ){
  2969. return 0;
  2970. }
  2971. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  2972. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  2973. nChar);
  2974. if( nChar==0 ){
  2975. sqlite3_free(zWideFilename);
  2976. zWideFilename = 0;
  2977. }
  2978. return zWideFilename;
  2979. }
  2980. #endif
  2981. /*
  2982. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  2983. ** on the database file. This proc moves the *-oal file to the *-wal path,
  2984. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  2985. ** If an error occurs, leave an error code and error message in the rbu
  2986. ** handle.
  2987. */
  2988. static void rbuMoveOalFile(sqlite3rbu *p){
  2989. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  2990. const char *zMove = zBase;
  2991. char *zOal;
  2992. char *zWal;
  2993. if( rbuIsVacuum(p) ){
  2994. zMove = sqlite3_db_filename(p->dbRbu, "main");
  2995. }
  2996. zOal = sqlite3_mprintf("%s-oal", zMove);
  2997. zWal = sqlite3_mprintf("%s-wal", zMove);
  2998. assert( p->eStage==RBU_STAGE_MOVE );
  2999. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  3000. if( zWal==0 || zOal==0 ){
  3001. p->rc = SQLITE_NOMEM;
  3002. }else{
  3003. /* Move the *-oal file to *-wal. At this point connection p->db is
  3004. ** holding a SHARED lock on the target database file (because it is
  3005. ** in WAL mode). So no other connection may be writing the db.
  3006. **
  3007. ** In order to ensure that there are no database readers, an EXCLUSIVE
  3008. ** lock is obtained here before the *-oal is moved to *-wal.
  3009. */
  3010. sqlite3 *dbMain = 0;
  3011. rbuFileSuffix3(zBase, zWal);
  3012. rbuFileSuffix3(zBase, zOal);
  3013. /* Re-open the databases. */
  3014. rbuObjIterFinalize(&p->objiter);
  3015. sqlite3_close(p->dbRbu);
  3016. sqlite3_close(p->dbMain);
  3017. p->dbMain = 0;
  3018. p->dbRbu = 0;
  3019. dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  3020. if( dbMain ){
  3021. assert( p->rc==SQLITE_OK );
  3022. p->rc = rbuLockDatabase(dbMain);
  3023. }
  3024. if( p->rc==SQLITE_OK ){
  3025. p->rc = p->xRename(p->pRenameArg, zOal, zWal);
  3026. }
  3027. if( p->rc!=SQLITE_OK
  3028. || rbuIsVacuum(p)
  3029. || rbuExclusiveCheckpoint(dbMain)==0
  3030. ){
  3031. sqlite3_close(dbMain);
  3032. dbMain = 0;
  3033. }
  3034. if( p->rc==SQLITE_OK ){
  3035. rbuOpenDatabase(p, dbMain, 0);
  3036. rbuSetupCheckpoint(p, 0);
  3037. }
  3038. }
  3039. sqlite3_free(zWal);
  3040. sqlite3_free(zOal);
  3041. }
  3042. /*
  3043. ** The SELECT statement iterating through the keys for the current object
  3044. ** (p->objiter.pSelect) currently points to a valid row. This function
  3045. ** determines the type of operation requested by this row and returns
  3046. ** one of the following values to indicate the result:
  3047. **
  3048. ** * RBU_INSERT
  3049. ** * RBU_DELETE
  3050. ** * RBU_IDX_DELETE
  3051. ** * RBU_UPDATE
  3052. **
  3053. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  3054. ** point to the text value indicating the columns to update.
  3055. **
  3056. ** If the rbu_control field contains an invalid value, an error code and
  3057. ** message are left in the RBU handle and zero returned.
  3058. */
  3059. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  3060. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  3061. int res = 0; /* Return value */
  3062. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  3063. case SQLITE_INTEGER: {
  3064. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  3065. switch( iVal ){
  3066. case 0: res = RBU_INSERT; break;
  3067. case 1: res = RBU_DELETE; break;
  3068. case 2: res = RBU_REPLACE; break;
  3069. case 3: res = RBU_IDX_DELETE; break;
  3070. case 4: res = RBU_IDX_INSERT; break;
  3071. }
  3072. break;
  3073. }
  3074. case SQLITE_TEXT: {
  3075. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  3076. if( z==0 ){
  3077. p->rc = SQLITE_NOMEM;
  3078. }else{
  3079. *pzMask = (const char*)z;
  3080. }
  3081. res = RBU_UPDATE;
  3082. break;
  3083. }
  3084. default:
  3085. break;
  3086. }
  3087. if( res==0 ){
  3088. rbuBadControlError(p);
  3089. }
  3090. return res;
  3091. }
  3092. #ifdef SQLITE_DEBUG
  3093. /*
  3094. ** Assert that column iCol of statement pStmt is named zName.
  3095. */
  3096. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  3097. const char *zCol = sqlite3_column_name(pStmt, iCol);
  3098. assert( 0==sqlite3_stricmp(zName, zCol) );
  3099. }
  3100. #else
  3101. # define assertColumnName(x,y,z)
  3102. #endif
  3103. /*
  3104. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  3105. ** RBU_IDX_DELETE. This function performs the work of a single
  3106. ** sqlite3rbu_step() call for the type of operation specified by eType.
  3107. */
  3108. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  3109. RbuObjIter *pIter = &p->objiter;
  3110. sqlite3_value *pVal;
  3111. sqlite3_stmt *pWriter;
  3112. int i;
  3113. assert( p->rc==SQLITE_OK );
  3114. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  3115. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  3116. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  3117. );
  3118. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  3119. ** statement below does actually delete a row, nPhaseOneStep will be
  3120. ** incremented by the same amount when SQL function rbu_tmp_insert()
  3121. ** is invoked by the trigger. */
  3122. if( eType==RBU_DELETE ){
  3123. p->nPhaseOneStep -= p->objiter.nIndex;
  3124. }
  3125. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  3126. pWriter = pIter->pDelete;
  3127. }else{
  3128. pWriter = pIter->pInsert;
  3129. }
  3130. for(i=0; i<pIter->nCol; i++){
  3131. /* If this is an INSERT into a table b-tree and the table has an
  3132. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  3133. ** to write a NULL into the IPK column. That is not permitted. */
  3134. if( eType==RBU_INSERT
  3135. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  3136. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  3137. ){
  3138. p->rc = SQLITE_MISMATCH;
  3139. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  3140. return;
  3141. }
  3142. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  3143. continue;
  3144. }
  3145. pVal = sqlite3_column_value(pIter->pSelect, i);
  3146. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  3147. if( p->rc ) return;
  3148. }
  3149. if( pIter->zIdx==0 ){
  3150. if( pIter->eType==RBU_PK_VTAB
  3151. || pIter->eType==RBU_PK_NONE
  3152. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  3153. ){
  3154. /* For a virtual table, or a table with no primary key, the
  3155. ** SELECT statement is:
  3156. **
  3157. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  3158. **
  3159. ** Hence column_value(pIter->nCol+1).
  3160. */
  3161. assertColumnName(pIter->pSelect, pIter->nCol+1,
  3162. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  3163. );
  3164. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  3165. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  3166. }
  3167. }
  3168. if( p->rc==SQLITE_OK ){
  3169. sqlite3_step(pWriter);
  3170. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  3171. }
  3172. }
  3173. /*
  3174. ** This function does the work for an sqlite3rbu_step() call.
  3175. **
  3176. ** The object-iterator (p->objiter) currently points to a valid object,
  3177. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  3178. ** input row. Perform whatever processing is required and return.
  3179. **
  3180. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  3181. ** and message is left in the RBU handle and a copy of the error code
  3182. ** returned.
  3183. */
  3184. static int rbuStep(sqlite3rbu *p){
  3185. RbuObjIter *pIter = &p->objiter;
  3186. const char *zMask = 0;
  3187. int eType = rbuStepType(p, &zMask);
  3188. if( eType ){
  3189. assert( eType==RBU_INSERT || eType==RBU_DELETE
  3190. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  3191. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  3192. );
  3193. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  3194. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  3195. rbuBadControlError(p);
  3196. }
  3197. else if( eType==RBU_REPLACE ){
  3198. if( pIter->zIdx==0 ){
  3199. p->nPhaseOneStep += p->objiter.nIndex;
  3200. rbuStepOneOp(p, RBU_DELETE);
  3201. }
  3202. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  3203. }
  3204. else if( eType!=RBU_UPDATE ){
  3205. rbuStepOneOp(p, eType);
  3206. }
  3207. else{
  3208. sqlite3_value *pVal;
  3209. sqlite3_stmt *pUpdate = 0;
  3210. assert( eType==RBU_UPDATE );
  3211. p->nPhaseOneStep -= p->objiter.nIndex;
  3212. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  3213. if( pUpdate ){
  3214. int i;
  3215. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  3216. char c = zMask[pIter->aiSrcOrder[i]];
  3217. pVal = sqlite3_column_value(pIter->pSelect, i);
  3218. if( pIter->abTblPk[i] || c!='.' ){
  3219. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  3220. }
  3221. }
  3222. if( p->rc==SQLITE_OK
  3223. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  3224. ){
  3225. /* Bind the rbu_rowid value to column _rowid_ */
  3226. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  3227. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  3228. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  3229. }
  3230. if( p->rc==SQLITE_OK ){
  3231. sqlite3_step(pUpdate);
  3232. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  3233. }
  3234. }
  3235. }
  3236. }
  3237. return p->rc;
  3238. }
  3239. /*
  3240. ** Increment the schema cookie of the main database opened by p->dbMain.
  3241. **
  3242. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  3243. ** opened by p->dbMain to one more than the schema cookie of the main
  3244. ** db opened by p->dbRbu.
  3245. */
  3246. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  3247. if( p->rc==SQLITE_OK ){
  3248. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  3249. int iCookie = 1000000;
  3250. sqlite3_stmt *pStmt;
  3251. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  3252. "PRAGMA schema_version"
  3253. );
  3254. if( p->rc==SQLITE_OK ){
  3255. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  3256. ** is already a transaction open, so the prepared statement cannot
  3257. ** throw an SQLITE_SCHEMA exception. The only database page the
  3258. ** statement reads is page 1, which is guaranteed to be in the cache.
  3259. ** And no memory allocations are required. */
  3260. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  3261. iCookie = sqlite3_column_int(pStmt, 0);
  3262. }
  3263. rbuFinalize(p, pStmt);
  3264. }
  3265. if( p->rc==SQLITE_OK ){
  3266. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  3267. }
  3268. }
  3269. }
  3270. /*
  3271. ** Update the contents of the rbu_state table within the rbu database. The
  3272. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  3273. ** are determined by inspecting the rbu handle passed as the first argument.
  3274. */
  3275. static void rbuSaveState(sqlite3rbu *p, int eStage){
  3276. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  3277. sqlite3_stmt *pInsert = 0;
  3278. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  3279. int rc;
  3280. assert( p->zErrmsg==0 );
  3281. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  3282. sqlite3_mprintf(
  3283. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  3284. "(%d, %d), "
  3285. "(%d, %Q), "
  3286. "(%d, %Q), "
  3287. "(%d, %d), "
  3288. "(%d, %lld), "
  3289. "(%d, %lld), "
  3290. "(%d, %lld), "
  3291. "(%d, %lld), "
  3292. "(%d, %lld), "
  3293. "(%d, %Q) ",
  3294. p->zStateDb,
  3295. RBU_STATE_STAGE, eStage,
  3296. RBU_STATE_TBL, p->objiter.zTbl,
  3297. RBU_STATE_IDX, p->objiter.zIdx,
  3298. RBU_STATE_ROW, p->nStep,
  3299. RBU_STATE_PROGRESS, p->nProgress,
  3300. RBU_STATE_CKPT, p->iWalCksum,
  3301. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  3302. RBU_STATE_OALSZ, p->iOalSz,
  3303. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
  3304. RBU_STATE_DATATBL, p->objiter.zDataTbl
  3305. )
  3306. );
  3307. assert( pInsert==0 || rc==SQLITE_OK );
  3308. if( rc==SQLITE_OK ){
  3309. sqlite3_step(pInsert);
  3310. rc = sqlite3_finalize(pInsert);
  3311. }
  3312. if( rc!=SQLITE_OK ) p->rc = rc;
  3313. }
  3314. }
  3315. /*
  3316. ** The second argument passed to this function is the name of a PRAGMA
  3317. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  3318. ** This function executes the following on sqlite3rbu.dbRbu:
  3319. **
  3320. ** "PRAGMA main.$zPragma"
  3321. **
  3322. ** where $zPragma is the string passed as the second argument, then
  3323. ** on sqlite3rbu.dbMain:
  3324. **
  3325. ** "PRAGMA main.$zPragma = $val"
  3326. **
  3327. ** where $val is the value returned by the first PRAGMA invocation.
  3328. **
  3329. ** In short, it copies the value of the specified PRAGMA setting from
  3330. ** dbRbu to dbMain.
  3331. */
  3332. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  3333. if( p->rc==SQLITE_OK ){
  3334. sqlite3_stmt *pPragma = 0;
  3335. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  3336. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  3337. );
  3338. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  3339. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  3340. zPragma, sqlite3_column_int(pPragma, 0)
  3341. );
  3342. }
  3343. rbuFinalize(p, pPragma);
  3344. }
  3345. }
  3346. /*
  3347. ** The RBU handle passed as the only argument has just been opened and
  3348. ** the state database is empty. If this RBU handle was opened for an
  3349. ** RBU vacuum operation, create the schema in the target db.
  3350. */
  3351. static void rbuCreateTargetSchema(sqlite3rbu *p){
  3352. sqlite3_stmt *pSql = 0;
  3353. sqlite3_stmt *pInsert = 0;
  3354. assert( rbuIsVacuum(p) );
  3355. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  3356. if( p->rc==SQLITE_OK ){
  3357. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  3358. "SELECT sql FROM sqlite_schema WHERE sql!='' AND rootpage!=0"
  3359. " AND name!='sqlite_sequence' "
  3360. " ORDER BY type DESC"
  3361. );
  3362. }
  3363. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  3364. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  3365. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  3366. }
  3367. rbuFinalize(p, pSql);
  3368. if( p->rc!=SQLITE_OK ) return;
  3369. if( p->rc==SQLITE_OK ){
  3370. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  3371. "SELECT * FROM sqlite_schema WHERE rootpage=0 OR rootpage IS NULL"
  3372. );
  3373. }
  3374. if( p->rc==SQLITE_OK ){
  3375. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  3376. "INSERT INTO sqlite_schema VALUES(?,?,?,?,?)"
  3377. );
  3378. }
  3379. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  3380. int i;
  3381. for(i=0; i<5; i++){
  3382. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  3383. }
  3384. sqlite3_step(pInsert);
  3385. p->rc = sqlite3_reset(pInsert);
  3386. }
  3387. if( p->rc==SQLITE_OK ){
  3388. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  3389. }
  3390. rbuFinalize(p, pSql);
  3391. rbuFinalize(p, pInsert);
  3392. }
  3393. /*
  3394. ** Step the RBU object.
  3395. */
  3396. int sqlite3rbu_step(sqlite3rbu *p){
  3397. if( p ){
  3398. switch( p->eStage ){
  3399. case RBU_STAGE_OAL: {
  3400. RbuObjIter *pIter = &p->objiter;
  3401. /* If this is an RBU vacuum operation and the state table was empty
  3402. ** when this handle was opened, create the target database schema. */
  3403. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  3404. rbuCreateTargetSchema(p);
  3405. rbuCopyPragma(p, "user_version");
  3406. rbuCopyPragma(p, "application_id");
  3407. }
  3408. while( p->rc==SQLITE_OK && pIter->zTbl ){
  3409. if( pIter->bCleanup ){
  3410. /* Clean up the rbu_tmp_xxx table for the previous table. It
  3411. ** cannot be dropped as there are currently active SQL statements.
  3412. ** But the contents can be deleted. */
  3413. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  3414. rbuMPrintfExec(p, p->dbRbu,
  3415. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  3416. );
  3417. }
  3418. }else{
  3419. rbuObjIterPrepareAll(p, pIter, 0);
  3420. /* Advance to the next row to process. */
  3421. if( p->rc==SQLITE_OK ){
  3422. int rc = sqlite3_step(pIter->pSelect);
  3423. if( rc==SQLITE_ROW ){
  3424. p->nProgress++;
  3425. p->nStep++;
  3426. return rbuStep(p);
  3427. }
  3428. p->rc = sqlite3_reset(pIter->pSelect);
  3429. p->nStep = 0;
  3430. }
  3431. }
  3432. rbuObjIterNext(p, pIter);
  3433. }
  3434. if( p->rc==SQLITE_OK ){
  3435. assert( pIter->zTbl==0 );
  3436. rbuSaveState(p, RBU_STAGE_MOVE);
  3437. rbuIncrSchemaCookie(p);
  3438. if( p->rc==SQLITE_OK ){
  3439. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  3440. }
  3441. if( p->rc==SQLITE_OK ){
  3442. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  3443. }
  3444. p->eStage = RBU_STAGE_MOVE;
  3445. }
  3446. break;
  3447. }
  3448. case RBU_STAGE_MOVE: {
  3449. if( p->rc==SQLITE_OK ){
  3450. rbuMoveOalFile(p);
  3451. p->nProgress++;
  3452. }
  3453. break;
  3454. }
  3455. case RBU_STAGE_CKPT: {
  3456. if( p->rc==SQLITE_OK ){
  3457. if( p->nStep>=p->nFrame ){
  3458. sqlite3_file *pDb = p->pTargetFd->pReal;
  3459. /* Sync the db file */
  3460. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  3461. /* Update nBackfill */
  3462. if( p->rc==SQLITE_OK ){
  3463. void volatile *ptr;
  3464. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  3465. if( p->rc==SQLITE_OK ){
  3466. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  3467. }
  3468. }
  3469. if( p->rc==SQLITE_OK ){
  3470. p->eStage = RBU_STAGE_DONE;
  3471. p->rc = SQLITE_DONE;
  3472. }
  3473. }else{
  3474. /* At one point the following block copied a single frame from the
  3475. ** wal file to the database file. So that one call to sqlite3rbu_step()
  3476. ** checkpointed a single frame.
  3477. **
  3478. ** However, if the sector-size is larger than the page-size, and the
  3479. ** application calls sqlite3rbu_savestate() or close() immediately
  3480. ** after this step, then rbu_step() again, then a power failure occurs,
  3481. ** then the database page written here may be damaged. Work around
  3482. ** this by checkpointing frames until the next page in the aFrame[]
  3483. ** lies on a different disk sector to the current one. */
  3484. u32 iSector;
  3485. do{
  3486. RbuFrame *pFrame = &p->aFrame[p->nStep];
  3487. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  3488. rbuCheckpointFrame(p, pFrame);
  3489. p->nStep++;
  3490. }while( p->nStep<p->nFrame
  3491. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  3492. && p->rc==SQLITE_OK
  3493. );
  3494. }
  3495. p->nProgress++;
  3496. }
  3497. break;
  3498. }
  3499. default:
  3500. break;
  3501. }
  3502. return p->rc;
  3503. }else{
  3504. return SQLITE_NOMEM;
  3505. }
  3506. }
  3507. /*
  3508. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  3509. ** otherwise. Either or both argument may be NULL. Two NULL values are
  3510. ** considered equal, and NULL is considered distinct from all other values.
  3511. */
  3512. static int rbuStrCompare(const char *z1, const char *z2){
  3513. if( z1==0 && z2==0 ) return 0;
  3514. if( z1==0 || z2==0 ) return 1;
  3515. return (sqlite3_stricmp(z1, z2)!=0);
  3516. }
  3517. /*
  3518. ** This function is called as part of sqlite3rbu_open() when initializing
  3519. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  3520. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  3521. ** things so that the next call to sqlite3rbu_step() continues on from
  3522. ** where the previous rbu handle left off.
  3523. **
  3524. ** If an error occurs, an error code and error message are left in the
  3525. ** rbu handle passed as the first argument.
  3526. */
  3527. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  3528. assert( p->rc==SQLITE_OK );
  3529. if( pState->zTbl ){
  3530. RbuObjIter *pIter = &p->objiter;
  3531. int rc = SQLITE_OK;
  3532. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  3533. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  3534. || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
  3535. || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
  3536. )){
  3537. rc = rbuObjIterNext(p, pIter);
  3538. }
  3539. if( rc==SQLITE_OK && !pIter->zTbl ){
  3540. rc = SQLITE_ERROR;
  3541. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  3542. }
  3543. if( rc==SQLITE_OK ){
  3544. p->nStep = pState->nRow;
  3545. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  3546. }
  3547. p->rc = rc;
  3548. }
  3549. }
  3550. /*
  3551. ** If there is a "*-oal" file in the file-system corresponding to the
  3552. ** target database in the file-system, delete it. If an error occurs,
  3553. ** leave an error code and error message in the rbu handle.
  3554. */
  3555. static void rbuDeleteOalFile(sqlite3rbu *p){
  3556. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  3557. if( zOal ){
  3558. sqlite3_vfs *pVfs = 0;
  3559. sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_VFS_POINTER, &pVfs);
  3560. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  3561. pVfs->xDelete(pVfs, zOal, 0);
  3562. sqlite3_free(zOal);
  3563. }
  3564. }
  3565. /*
  3566. ** Allocate a private rbu VFS for the rbu handle passed as the only
  3567. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  3568. ** specified a URI with a vfs=? option in place of a target database
  3569. ** file name.
  3570. */
  3571. static void rbuCreateVfs(sqlite3rbu *p){
  3572. int rnd;
  3573. char zRnd[64];
  3574. assert( p->rc==SQLITE_OK );
  3575. sqlite3_randomness(sizeof(int), (void*)&rnd);
  3576. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  3577. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  3578. if( p->rc==SQLITE_OK ){
  3579. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  3580. assert( pVfs );
  3581. p->zVfsName = pVfs->zName;
  3582. ((rbu_vfs*)pVfs)->pRbu = p;
  3583. }
  3584. }
  3585. /*
  3586. ** Destroy the private VFS created for the rbu handle passed as the only
  3587. ** argument by an earlier call to rbuCreateVfs().
  3588. */
  3589. static void rbuDeleteVfs(sqlite3rbu *p){
  3590. if( p->zVfsName ){
  3591. sqlite3rbu_destroy_vfs(p->zVfsName);
  3592. p->zVfsName = 0;
  3593. }
  3594. }
  3595. /*
  3596. ** This user-defined SQL function is invoked with a single argument - the
  3597. ** name of a table expected to appear in the target database. It returns
  3598. ** the number of auxilliary indexes on the table.
  3599. */
  3600. static void rbuIndexCntFunc(
  3601. sqlite3_context *pCtx,
  3602. int nVal,
  3603. sqlite3_value **apVal
  3604. ){
  3605. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  3606. sqlite3_stmt *pStmt = 0;
  3607. char *zErrmsg = 0;
  3608. int rc;
  3609. sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  3610. assert( nVal==1 );
  3611. UNUSED_PARAMETER(nVal);
  3612. rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg,
  3613. sqlite3_mprintf("SELECT count(*) FROM sqlite_schema "
  3614. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  3615. );
  3616. if( rc!=SQLITE_OK ){
  3617. sqlite3_result_error(pCtx, zErrmsg, -1);
  3618. }else{
  3619. int nIndex = 0;
  3620. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  3621. nIndex = sqlite3_column_int(pStmt, 0);
  3622. }
  3623. rc = sqlite3_finalize(pStmt);
  3624. if( rc==SQLITE_OK ){
  3625. sqlite3_result_int(pCtx, nIndex);
  3626. }else{
  3627. sqlite3_result_error(pCtx, sqlite3_errmsg(db), -1);
  3628. }
  3629. }
  3630. sqlite3_free(zErrmsg);
  3631. }
  3632. /*
  3633. ** If the RBU database contains the rbu_count table, use it to initialize
  3634. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  3635. ** is assumed to contain the same columns as:
  3636. **
  3637. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  3638. **
  3639. ** There should be one row in the table for each data_xxx table in the
  3640. ** database. The 'tbl' column should contain the name of a data_xxx table,
  3641. ** and the cnt column the number of rows it contains.
  3642. **
  3643. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  3644. ** for all rows in the rbu_count table, where nIndex is the number of
  3645. ** indexes on the corresponding target database table.
  3646. */
  3647. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  3648. if( p->rc==SQLITE_OK ){
  3649. sqlite3_stmt *pStmt = 0;
  3650. int bExists = 0; /* True if rbu_count exists */
  3651. p->nPhaseOneStep = -1;
  3652. p->rc = sqlite3_create_function(p->dbRbu,
  3653. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  3654. );
  3655. /* Check for the rbu_count table. If it does not exist, or if an error
  3656. ** occurs, nPhaseOneStep will be left set to -1. */
  3657. if( p->rc==SQLITE_OK ){
  3658. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  3659. "SELECT 1 FROM sqlite_schema WHERE tbl_name = 'rbu_count'"
  3660. );
  3661. }
  3662. if( p->rc==SQLITE_OK ){
  3663. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  3664. bExists = 1;
  3665. }
  3666. p->rc = sqlite3_finalize(pStmt);
  3667. }
  3668. if( p->rc==SQLITE_OK && bExists ){
  3669. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  3670. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  3671. "FROM rbu_count"
  3672. );
  3673. if( p->rc==SQLITE_OK ){
  3674. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  3675. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  3676. }
  3677. p->rc = sqlite3_finalize(pStmt);
  3678. }
  3679. }
  3680. }
  3681. }
  3682. static sqlite3rbu *openRbuHandle(
  3683. const char *zTarget,
  3684. const char *zRbu,
  3685. const char *zState
  3686. ){
  3687. sqlite3rbu *p;
  3688. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  3689. size_t nRbu = strlen(zRbu);
  3690. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  3691. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  3692. if( p ){
  3693. RbuState *pState = 0;
  3694. /* Create the custom VFS. */
  3695. memset(p, 0, sizeof(sqlite3rbu));
  3696. sqlite3rbu_rename_handler(p, 0, 0);
  3697. rbuCreateVfs(p);
  3698. /* Open the target, RBU and state databases */
  3699. if( p->rc==SQLITE_OK ){
  3700. char *pCsr = (char*)&p[1];
  3701. int bRetry = 0;
  3702. if( zTarget ){
  3703. p->zTarget = pCsr;
  3704. memcpy(p->zTarget, zTarget, nTarget+1);
  3705. pCsr += nTarget+1;
  3706. }
  3707. p->zRbu = pCsr;
  3708. memcpy(p->zRbu, zRbu, nRbu+1);
  3709. pCsr += nRbu+1;
  3710. if( zState ){
  3711. p->zState = rbuMPrintf(p, "%s", zState);
  3712. }
  3713. /* If the first attempt to open the database file fails and the bRetry
  3714. ** flag it set, this means that the db was not opened because it seemed
  3715. ** to be a wal-mode db. But, this may have happened due to an earlier
  3716. ** RBU vacuum operation leaving an old wal file in the directory.
  3717. ** If this is the case, it will have been checkpointed and deleted
  3718. ** when the handle was closed and a second attempt to open the
  3719. ** database may succeed. */
  3720. rbuOpenDatabase(p, 0, &bRetry);
  3721. if( bRetry ){
  3722. rbuOpenDatabase(p, 0, 0);
  3723. }
  3724. }
  3725. if( p->rc==SQLITE_OK ){
  3726. pState = rbuLoadState(p);
  3727. assert( pState || p->rc!=SQLITE_OK );
  3728. if( p->rc==SQLITE_OK ){
  3729. if( pState->eStage==0 ){
  3730. rbuDeleteOalFile(p);
  3731. rbuInitPhaseOneSteps(p);
  3732. p->eStage = RBU_STAGE_OAL;
  3733. }else{
  3734. p->eStage = pState->eStage;
  3735. p->nPhaseOneStep = pState->nPhaseOneStep;
  3736. }
  3737. p->nProgress = pState->nProgress;
  3738. p->iOalSz = pState->iOalSz;
  3739. }
  3740. }
  3741. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  3742. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  3743. if( p->eStage==RBU_STAGE_OAL ){
  3744. p->rc = SQLITE_ERROR;
  3745. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  3746. }else if( p->eStage==RBU_STAGE_MOVE ){
  3747. p->eStage = RBU_STAGE_CKPT;
  3748. p->nStep = 0;
  3749. }
  3750. }
  3751. if( p->rc==SQLITE_OK
  3752. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  3753. && pState->eStage!=0
  3754. ){
  3755. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  3756. if( pFd->iCookie!=pState->iCookie ){
  3757. /* At this point (pTargetFd->iCookie) contains the value of the
  3758. ** change-counter cookie (the thing that gets incremented when a
  3759. ** transaction is committed in rollback mode) currently stored on
  3760. ** page 1 of the database file. */
  3761. p->rc = SQLITE_BUSY;
  3762. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  3763. (rbuIsVacuum(p) ? "vacuum" : "update")
  3764. );
  3765. }
  3766. }
  3767. if( p->rc==SQLITE_OK ){
  3768. if( p->eStage==RBU_STAGE_OAL ){
  3769. sqlite3 *db = p->dbMain;
  3770. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  3771. /* Point the object iterator at the first object */
  3772. if( p->rc==SQLITE_OK ){
  3773. p->rc = rbuObjIterFirst(p, &p->objiter);
  3774. }
  3775. /* If the RBU database contains no data_xxx tables, declare the RBU
  3776. ** update finished. */
  3777. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  3778. p->rc = SQLITE_DONE;
  3779. p->eStage = RBU_STAGE_DONE;
  3780. }else{
  3781. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  3782. rbuCopyPragma(p, "page_size");
  3783. rbuCopyPragma(p, "auto_vacuum");
  3784. }
  3785. /* Open transactions both databases. The *-oal file is opened or
  3786. ** created at this point. */
  3787. if( p->rc==SQLITE_OK ){
  3788. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  3789. }
  3790. /* Check if the main database is a zipvfs db. If it is, set the upper
  3791. ** level pager to use "journal_mode=off". This prevents it from
  3792. ** generating a large journal using a temp file. */
  3793. if( p->rc==SQLITE_OK ){
  3794. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  3795. if( frc==SQLITE_OK ){
  3796. p->rc = sqlite3_exec(
  3797. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  3798. }
  3799. }
  3800. if( p->rc==SQLITE_OK ){
  3801. rbuSetupOal(p, pState);
  3802. }
  3803. }
  3804. }else if( p->eStage==RBU_STAGE_MOVE ){
  3805. /* no-op */
  3806. }else if( p->eStage==RBU_STAGE_CKPT ){
  3807. if( !rbuIsVacuum(p) && rbuExclusiveCheckpoint(p->dbMain) ){
  3808. /* If the rbu_exclusive_checkpoint=1 URI parameter was specified
  3809. ** and an incremental checkpoint is being resumed, attempt an
  3810. ** exclusive lock on the db file. If this fails, so be it. */
  3811. p->eStage = RBU_STAGE_DONE;
  3812. rbuLockDatabase(p->dbMain);
  3813. p->eStage = RBU_STAGE_CKPT;
  3814. }
  3815. rbuSetupCheckpoint(p, pState);
  3816. }else if( p->eStage==RBU_STAGE_DONE ){
  3817. p->rc = SQLITE_DONE;
  3818. }else{
  3819. p->rc = SQLITE_CORRUPT;
  3820. }
  3821. }
  3822. rbuFreeState(pState);
  3823. }
  3824. return p;
  3825. }
  3826. /*
  3827. ** Allocate and return an RBU handle with all fields zeroed except for the
  3828. ** error code, which is set to SQLITE_MISUSE.
  3829. */
  3830. static sqlite3rbu *rbuMisuseError(void){
  3831. sqlite3rbu *pRet;
  3832. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  3833. if( pRet ){
  3834. memset(pRet, 0, sizeof(sqlite3rbu));
  3835. pRet->rc = SQLITE_MISUSE;
  3836. }
  3837. return pRet;
  3838. }
  3839. /*
  3840. ** Open and return a new RBU handle.
  3841. */
  3842. sqlite3rbu *sqlite3rbu_open(
  3843. const char *zTarget,
  3844. const char *zRbu,
  3845. const char *zState
  3846. ){
  3847. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  3848. return openRbuHandle(zTarget, zRbu, zState);
  3849. }
  3850. /*
  3851. ** Open a handle to begin or resume an RBU VACUUM operation.
  3852. */
  3853. sqlite3rbu *sqlite3rbu_vacuum(
  3854. const char *zTarget,
  3855. const char *zState
  3856. ){
  3857. if( zTarget==0 ){ return rbuMisuseError(); }
  3858. if( zState ){
  3859. size_t n = strlen(zState);
  3860. if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
  3861. return rbuMisuseError();
  3862. }
  3863. }
  3864. /* TODO: Check that both arguments are non-NULL */
  3865. return openRbuHandle(0, zTarget, zState);
  3866. }
  3867. /*
  3868. ** Return the database handle used by pRbu.
  3869. */
  3870. sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  3871. sqlite3 *db = 0;
  3872. if( pRbu ){
  3873. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  3874. }
  3875. return db;
  3876. }
  3877. /*
  3878. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  3879. ** then edit any error message string so as to remove all occurrences of
  3880. ** the pattern "rbu_imp_[0-9]*".
  3881. */
  3882. static void rbuEditErrmsg(sqlite3rbu *p){
  3883. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  3884. unsigned int i;
  3885. size_t nErrmsg = strlen(p->zErrmsg);
  3886. for(i=0; i<(nErrmsg-8); i++){
  3887. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  3888. int nDel = 8;
  3889. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  3890. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  3891. nErrmsg -= nDel;
  3892. }
  3893. }
  3894. }
  3895. }
  3896. /*
  3897. ** Close the RBU handle.
  3898. */
  3899. int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  3900. int rc;
  3901. if( p ){
  3902. /* Commit the transaction to the *-oal file. */
  3903. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  3904. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  3905. }
  3906. /* Sync the db file if currently doing an incremental checkpoint */
  3907. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  3908. sqlite3_file *pDb = p->pTargetFd->pReal;
  3909. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  3910. }
  3911. rbuSaveState(p, p->eStage);
  3912. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  3913. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  3914. }
  3915. /* Close any open statement handles. */
  3916. rbuObjIterFinalize(&p->objiter);
  3917. /* If this is an RBU vacuum handle and the vacuum has either finished
  3918. ** successfully or encountered an error, delete the contents of the
  3919. ** state table. This causes the next call to sqlite3rbu_vacuum()
  3920. ** specifying the current target and state databases to start a new
  3921. ** vacuum from scratch. */
  3922. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  3923. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  3924. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  3925. }
  3926. /* Close the open database handle and VFS object. */
  3927. sqlite3_close(p->dbRbu);
  3928. sqlite3_close(p->dbMain);
  3929. assert( p->szTemp==0 );
  3930. rbuDeleteVfs(p);
  3931. sqlite3_free(p->aBuf);
  3932. sqlite3_free(p->aFrame);
  3933. rbuEditErrmsg(p);
  3934. rc = p->rc;
  3935. if( pzErrmsg ){
  3936. *pzErrmsg = p->zErrmsg;
  3937. }else{
  3938. sqlite3_free(p->zErrmsg);
  3939. }
  3940. sqlite3_free(p->zState);
  3941. sqlite3_free(p);
  3942. }else{
  3943. rc = SQLITE_NOMEM;
  3944. *pzErrmsg = 0;
  3945. }
  3946. return rc;
  3947. }
  3948. /*
  3949. ** Return the total number of key-value operations (inserts, deletes or
  3950. ** updates) that have been performed on the target database since the
  3951. ** current RBU update was started.
  3952. */
  3953. sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  3954. return pRbu->nProgress;
  3955. }
  3956. /*
  3957. ** Return permyriadage progress indications for the two main stages of
  3958. ** an RBU update.
  3959. */
  3960. void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  3961. const int MAX_PROGRESS = 10000;
  3962. switch( p->eStage ){
  3963. case RBU_STAGE_OAL:
  3964. if( p->nPhaseOneStep>0 ){
  3965. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  3966. }else{
  3967. *pnOne = -1;
  3968. }
  3969. *pnTwo = 0;
  3970. break;
  3971. case RBU_STAGE_MOVE:
  3972. *pnOne = MAX_PROGRESS;
  3973. *pnTwo = 0;
  3974. break;
  3975. case RBU_STAGE_CKPT:
  3976. *pnOne = MAX_PROGRESS;
  3977. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  3978. break;
  3979. case RBU_STAGE_DONE:
  3980. *pnOne = MAX_PROGRESS;
  3981. *pnTwo = MAX_PROGRESS;
  3982. break;
  3983. default:
  3984. assert( 0 );
  3985. }
  3986. }
  3987. /*
  3988. ** Return the current state of the RBU vacuum or update operation.
  3989. */
  3990. int sqlite3rbu_state(sqlite3rbu *p){
  3991. int aRes[] = {
  3992. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  3993. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  3994. };
  3995. assert( RBU_STAGE_OAL==1 );
  3996. assert( RBU_STAGE_MOVE==2 );
  3997. assert( RBU_STAGE_CKPT==4 );
  3998. assert( RBU_STAGE_DONE==5 );
  3999. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  4000. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  4001. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  4002. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  4003. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  4004. return SQLITE_RBU_STATE_ERROR;
  4005. }else{
  4006. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  4007. assert( p->eStage==RBU_STAGE_OAL
  4008. || p->eStage==RBU_STAGE_MOVE
  4009. || p->eStage==RBU_STAGE_CKPT
  4010. || p->eStage==RBU_STAGE_DONE
  4011. );
  4012. return aRes[p->eStage];
  4013. }
  4014. }
  4015. int sqlite3rbu_savestate(sqlite3rbu *p){
  4016. int rc = p->rc;
  4017. if( rc==SQLITE_DONE ) return SQLITE_OK;
  4018. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  4019. if( p->eStage==RBU_STAGE_OAL ){
  4020. assert( rc!=SQLITE_DONE );
  4021. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  4022. }
  4023. /* Sync the db file */
  4024. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  4025. sqlite3_file *pDb = p->pTargetFd->pReal;
  4026. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  4027. }
  4028. p->rc = rc;
  4029. rbuSaveState(p, p->eStage);
  4030. rc = p->rc;
  4031. if( p->eStage==RBU_STAGE_OAL ){
  4032. assert( rc!=SQLITE_DONE );
  4033. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  4034. if( rc==SQLITE_OK ){
  4035. const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
  4036. rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
  4037. }
  4038. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  4039. }
  4040. p->rc = rc;
  4041. return rc;
  4042. }
  4043. /*
  4044. ** Default xRename callback for RBU.
  4045. */
  4046. static int xDefaultRename(void *pArg, const char *zOld, const char *zNew){
  4047. int rc = SQLITE_OK;
  4048. UNUSED_PARAMETER(pArg);
  4049. #if defined(_WIN32_WCE)
  4050. {
  4051. LPWSTR zWideOld;
  4052. LPWSTR zWideNew;
  4053. zWideOld = rbuWinUtf8ToUnicode(zOld);
  4054. if( zWideOld ){
  4055. zWideNew = rbuWinUtf8ToUnicode(zNew);
  4056. if( zWideNew ){
  4057. if( MoveFileW(zWideOld, zWideNew) ){
  4058. rc = SQLITE_OK;
  4059. }else{
  4060. rc = SQLITE_IOERR;
  4061. }
  4062. sqlite3_free(zWideNew);
  4063. }else{
  4064. rc = SQLITE_IOERR_NOMEM;
  4065. }
  4066. sqlite3_free(zWideOld);
  4067. }else{
  4068. rc = SQLITE_IOERR_NOMEM;
  4069. }
  4070. }
  4071. #else
  4072. rc = rename(zOld, zNew) ? SQLITE_IOERR : SQLITE_OK;
  4073. #endif
  4074. return rc;
  4075. }
  4076. void sqlite3rbu_rename_handler(
  4077. sqlite3rbu *pRbu,
  4078. void *pArg,
  4079. int (*xRename)(void *pArg, const char *zOld, const char *zNew)
  4080. ){
  4081. if( xRename ){
  4082. pRbu->xRename = xRename;
  4083. pRbu->pRenameArg = pArg;
  4084. }else{
  4085. pRbu->xRename = xDefaultRename;
  4086. pRbu->pRenameArg = 0;
  4087. }
  4088. }
  4089. /**************************************************************************
  4090. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  4091. ** of a standard VFS in the following ways:
  4092. **
  4093. ** 1. Whenever the first page of a main database file is read or
  4094. ** written, the value of the change-counter cookie is stored in
  4095. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  4096. ** database header field is stored in rbu_file.iWriteVer. This ensures
  4097. ** that the values are always trustworthy within an open transaction.
  4098. **
  4099. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  4100. ** member variable of the associated database file descriptor is set
  4101. ** to point to the new file. A mutex protected linked list of all main
  4102. ** db fds opened using a particular RBU VFS is maintained at
  4103. ** rbu_vfs.pMain to facilitate this.
  4104. **
  4105. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  4106. ** object can be marked as the target database of an RBU update. This
  4107. ** turns on the following extra special behaviour:
  4108. **
  4109. ** 3a. If xAccess() is called to check if there exists a *-wal file
  4110. ** associated with an RBU target database currently in RBU_STAGE_OAL
  4111. ** stage (preparing the *-oal file), the following special handling
  4112. ** applies:
  4113. **
  4114. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  4115. ** target database may not be in wal mode already.
  4116. **
  4117. ** * if the *-wal file does not exist, set the output parameter to
  4118. ** non-zero (to tell SQLite that it does exist) anyway.
  4119. **
  4120. ** Then, when xOpen() is called to open the *-wal file associated with
  4121. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  4122. ** file, the rbu vfs opens the corresponding *-oal file instead.
  4123. **
  4124. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  4125. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  4126. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  4127. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  4128. ** because assert() statements in some VFS implementations fail if
  4129. ** xShmLock() is called before xShmMap().
  4130. **
  4131. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  4132. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  4133. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  4134. ** from automatically checkpointing a *-wal (or *-oal) file from within
  4135. ** sqlite3_close().
  4136. **
  4137. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  4138. ** all xWrite() calls on the target database file perform no IO.
  4139. ** Instead the frame and page numbers that would be read and written
  4140. ** are recorded. Additionally, successful attempts to obtain exclusive
  4141. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  4142. ** database file are recorded. xShmLock() calls to unlock the same
  4143. ** locks are no-ops (so that once obtained, these locks are never
  4144. ** relinquished). Finally, calls to xSync() on the target database
  4145. ** file fail with SQLITE_NOTICE errors.
  4146. */
  4147. static void rbuUnlockShm(rbu_file *p){
  4148. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  4149. if( p->pRbu ){
  4150. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  4151. int i;
  4152. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  4153. if( (1<<i) & p->pRbu->mLock ){
  4154. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  4155. }
  4156. }
  4157. p->pRbu->mLock = 0;
  4158. }
  4159. }
  4160. /*
  4161. */
  4162. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  4163. sqlite3rbu *pRbu = pFd->pRbu;
  4164. i64 nDiff = nNew - pFd->sz;
  4165. pRbu->szTemp += nDiff;
  4166. pFd->sz = nNew;
  4167. assert( pRbu->szTemp>=0 );
  4168. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  4169. return SQLITE_OK;
  4170. }
  4171. /*
  4172. ** Add an item to the main-db lists, if it is not already present.
  4173. **
  4174. ** There are two main-db lists. One for all file descriptors, and one
  4175. ** for all file descriptors with rbu_file.pDb!=0. If the argument has
  4176. ** rbu_file.pDb!=0, then it is assumed to already be present on the
  4177. ** main list and is only added to the pDb!=0 list.
  4178. */
  4179. static void rbuMainlistAdd(rbu_file *p){
  4180. rbu_vfs *pRbuVfs = p->pRbuVfs;
  4181. rbu_file *pIter;
  4182. assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
  4183. sqlite3_mutex_enter(pRbuVfs->mutex);
  4184. if( p->pRbu==0 ){
  4185. for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
  4186. p->pMainNext = pRbuVfs->pMain;
  4187. pRbuVfs->pMain = p;
  4188. }else{
  4189. for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
  4190. if( pIter==0 ){
  4191. p->pMainRbuNext = pRbuVfs->pMainRbu;
  4192. pRbuVfs->pMainRbu = p;
  4193. }
  4194. }
  4195. sqlite3_mutex_leave(pRbuVfs->mutex);
  4196. }
  4197. /*
  4198. ** Remove an item from the main-db lists.
  4199. */
  4200. static void rbuMainlistRemove(rbu_file *p){
  4201. rbu_file **pp;
  4202. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  4203. for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
  4204. if( *pp ) *pp = p->pMainNext;
  4205. p->pMainNext = 0;
  4206. for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
  4207. if( *pp ) *pp = p->pMainRbuNext;
  4208. p->pMainRbuNext = 0;
  4209. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  4210. }
  4211. /*
  4212. ** Given that zWal points to a buffer containing a wal file name passed to
  4213. ** either the xOpen() or xAccess() VFS method, search the main-db list for
  4214. ** a file-handle opened by the same database connection on the corresponding
  4215. ** database file.
  4216. **
  4217. ** If parameter bRbu is true, only search for file-descriptors with
  4218. ** rbu_file.pDb!=0.
  4219. */
  4220. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
  4221. rbu_file *pDb;
  4222. sqlite3_mutex_enter(pRbuVfs->mutex);
  4223. if( bRbu ){
  4224. for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
  4225. }else{
  4226. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  4227. }
  4228. sqlite3_mutex_leave(pRbuVfs->mutex);
  4229. return pDb;
  4230. }
  4231. /*
  4232. ** Close an rbu file.
  4233. */
  4234. static int rbuVfsClose(sqlite3_file *pFile){
  4235. rbu_file *p = (rbu_file*)pFile;
  4236. int rc;
  4237. int i;
  4238. /* Free the contents of the apShm[] array. And the array itself. */
  4239. for(i=0; i<p->nShm; i++){
  4240. sqlite3_free(p->apShm[i]);
  4241. }
  4242. sqlite3_free(p->apShm);
  4243. p->apShm = 0;
  4244. sqlite3_free(p->zDel);
  4245. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  4246. const sqlite3_io_methods *pMeth = p->pReal->pMethods;
  4247. rbuMainlistRemove(p);
  4248. rbuUnlockShm(p);
  4249. if( pMeth->iVersion>1 && pMeth->xShmUnmap ){
  4250. pMeth->xShmUnmap(p->pReal, 0);
  4251. }
  4252. }
  4253. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  4254. rbuUpdateTempSize(p, 0);
  4255. }
  4256. assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
  4257. /* Close the underlying file handle */
  4258. rc = p->pReal->pMethods->xClose(p->pReal);
  4259. return rc;
  4260. }
  4261. /*
  4262. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  4263. ** passed as the only argument.
  4264. */
  4265. static u32 rbuGetU32(u8 *aBuf){
  4266. return ((u32)aBuf[0] << 24)
  4267. + ((u32)aBuf[1] << 16)
  4268. + ((u32)aBuf[2] << 8)
  4269. + ((u32)aBuf[3]);
  4270. }
  4271. /*
  4272. ** Write an unsigned 32-bit value in big-endian format to the supplied
  4273. ** buffer.
  4274. */
  4275. static void rbuPutU32(u8 *aBuf, u32 iVal){
  4276. aBuf[0] = (iVal >> 24) & 0xFF;
  4277. aBuf[1] = (iVal >> 16) & 0xFF;
  4278. aBuf[2] = (iVal >> 8) & 0xFF;
  4279. aBuf[3] = (iVal >> 0) & 0xFF;
  4280. }
  4281. static void rbuPutU16(u8 *aBuf, u16 iVal){
  4282. aBuf[0] = (iVal >> 8) & 0xFF;
  4283. aBuf[1] = (iVal >> 0) & 0xFF;
  4284. }
  4285. /*
  4286. ** Read data from an rbuVfs-file.
  4287. */
  4288. static int rbuVfsRead(
  4289. sqlite3_file *pFile,
  4290. void *zBuf,
  4291. int iAmt,
  4292. sqlite_int64 iOfst
  4293. ){
  4294. rbu_file *p = (rbu_file*)pFile;
  4295. sqlite3rbu *pRbu = p->pRbu;
  4296. int rc;
  4297. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  4298. assert( p->openFlags & SQLITE_OPEN_WAL );
  4299. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  4300. }else{
  4301. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  4302. && (p->openFlags & SQLITE_OPEN_WAL)
  4303. && iOfst>=pRbu->iOalSz
  4304. ){
  4305. rc = SQLITE_OK;
  4306. memset(zBuf, 0, iAmt);
  4307. }else{
  4308. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  4309. #if 1
  4310. /* If this is being called to read the first page of the target
  4311. ** database as part of an rbu vacuum operation, synthesize the
  4312. ** contents of the first page if it does not yet exist. Otherwise,
  4313. ** SQLite will not check for a *-wal file. */
  4314. if( pRbu && rbuIsVacuum(pRbu)
  4315. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  4316. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  4317. && pRbu->rc==SQLITE_OK
  4318. ){
  4319. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  4320. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  4321. if( rc==SQLITE_OK ){
  4322. u8 *aBuf = (u8*)zBuf;
  4323. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  4324. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  4325. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  4326. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  4327. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  4328. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  4329. if( iAmt>100 ){
  4330. memset(&aBuf[100], 0, iAmt-100);
  4331. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  4332. aBuf[100] = 0x0D;
  4333. }
  4334. }
  4335. }
  4336. #endif
  4337. }
  4338. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  4339. /* These look like magic numbers. But they are stable, as they are part
  4340. ** of the definition of the SQLite file format, which may not change. */
  4341. u8 *pBuf = (u8*)zBuf;
  4342. p->iCookie = rbuGetU32(&pBuf[24]);
  4343. p->iWriteVer = pBuf[19];
  4344. }
  4345. }
  4346. return rc;
  4347. }
  4348. /*
  4349. ** Write data to an rbuVfs-file.
  4350. */
  4351. static int rbuVfsWrite(
  4352. sqlite3_file *pFile,
  4353. const void *zBuf,
  4354. int iAmt,
  4355. sqlite_int64 iOfst
  4356. ){
  4357. rbu_file *p = (rbu_file*)pFile;
  4358. sqlite3rbu *pRbu = p->pRbu;
  4359. int rc;
  4360. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  4361. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  4362. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  4363. }else{
  4364. if( pRbu ){
  4365. if( pRbu->eStage==RBU_STAGE_OAL
  4366. && (p->openFlags & SQLITE_OPEN_WAL)
  4367. && iOfst>=pRbu->iOalSz
  4368. ){
  4369. pRbu->iOalSz = iAmt + iOfst;
  4370. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  4371. i64 szNew = iAmt+iOfst;
  4372. if( szNew>p->sz ){
  4373. rc = rbuUpdateTempSize(p, szNew);
  4374. if( rc!=SQLITE_OK ) return rc;
  4375. }
  4376. }
  4377. }
  4378. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  4379. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  4380. /* These look like magic numbers. But they are stable, as they are part
  4381. ** of the definition of the SQLite file format, which may not change. */
  4382. u8 *pBuf = (u8*)zBuf;
  4383. p->iCookie = rbuGetU32(&pBuf[24]);
  4384. p->iWriteVer = pBuf[19];
  4385. }
  4386. }
  4387. return rc;
  4388. }
  4389. /*
  4390. ** Truncate an rbuVfs-file.
  4391. */
  4392. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  4393. rbu_file *p = (rbu_file*)pFile;
  4394. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  4395. int rc = rbuUpdateTempSize(p, size);
  4396. if( rc!=SQLITE_OK ) return rc;
  4397. }
  4398. return p->pReal->pMethods->xTruncate(p->pReal, size);
  4399. }
  4400. /*
  4401. ** Sync an rbuVfs-file.
  4402. */
  4403. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  4404. rbu_file *p = (rbu_file *)pFile;
  4405. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  4406. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  4407. return SQLITE_NOTICE_RBU;
  4408. }
  4409. return SQLITE_OK;
  4410. }
  4411. return p->pReal->pMethods->xSync(p->pReal, flags);
  4412. }
  4413. /*
  4414. ** Return the current file-size of an rbuVfs-file.
  4415. */
  4416. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  4417. rbu_file *p = (rbu_file *)pFile;
  4418. int rc;
  4419. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  4420. /* If this is an RBU vacuum operation and this is the target database,
  4421. ** pretend that it has at least one page. Otherwise, SQLite will not
  4422. ** check for the existance of a *-wal file. rbuVfsRead() contains
  4423. ** similar logic. */
  4424. if( rc==SQLITE_OK && *pSize==0
  4425. && p->pRbu && rbuIsVacuum(p->pRbu)
  4426. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  4427. ){
  4428. *pSize = 1024;
  4429. }
  4430. return rc;
  4431. }
  4432. /*
  4433. ** Lock an rbuVfs-file.
  4434. */
  4435. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  4436. rbu_file *p = (rbu_file*)pFile;
  4437. sqlite3rbu *pRbu = p->pRbu;
  4438. int rc = SQLITE_OK;
  4439. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  4440. if( eLock==SQLITE_LOCK_EXCLUSIVE
  4441. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  4442. ){
  4443. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  4444. ** prevents it from checkpointing the database from sqlite3_close(). */
  4445. rc = SQLITE_BUSY;
  4446. }else{
  4447. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  4448. }
  4449. return rc;
  4450. }
  4451. /*
  4452. ** Unlock an rbuVfs-file.
  4453. */
  4454. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  4455. rbu_file *p = (rbu_file *)pFile;
  4456. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  4457. }
  4458. /*
  4459. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  4460. */
  4461. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  4462. rbu_file *p = (rbu_file *)pFile;
  4463. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  4464. }
  4465. /*
  4466. ** File control method. For custom operations on an rbuVfs-file.
  4467. */
  4468. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  4469. rbu_file *p = (rbu_file *)pFile;
  4470. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  4471. int rc;
  4472. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  4473. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  4474. );
  4475. if( op==SQLITE_FCNTL_RBU ){
  4476. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  4477. /* First try to find another RBU vfs lower down in the vfs stack. If
  4478. ** one is found, this vfs will operate in pass-through mode. The lower
  4479. ** level vfs will do the special RBU handling. */
  4480. rc = xControl(p->pReal, op, pArg);
  4481. if( rc==SQLITE_NOTFOUND ){
  4482. /* Now search for a zipvfs instance lower down in the VFS stack. If
  4483. ** one is found, this is an error. */
  4484. void *dummy = 0;
  4485. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  4486. if( rc==SQLITE_OK ){
  4487. rc = SQLITE_ERROR;
  4488. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  4489. }else if( rc==SQLITE_NOTFOUND ){
  4490. pRbu->pTargetFd = p;
  4491. p->pRbu = pRbu;
  4492. rbuMainlistAdd(p);
  4493. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  4494. rc = SQLITE_OK;
  4495. }
  4496. }
  4497. return rc;
  4498. }
  4499. else if( op==SQLITE_FCNTL_RBUCNT ){
  4500. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  4501. pRbu->nRbu++;
  4502. pRbu->pRbuFd = p;
  4503. p->bNolock = 1;
  4504. }
  4505. rc = xControl(p->pReal, op, pArg);
  4506. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  4507. rbu_vfs *pRbuVfs = p->pRbuVfs;
  4508. char *zIn = *(char**)pArg;
  4509. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  4510. *(char**)pArg = zOut;
  4511. if( zOut==0 ) rc = SQLITE_NOMEM;
  4512. }
  4513. return rc;
  4514. }
  4515. /*
  4516. ** Return the sector-size in bytes for an rbuVfs-file.
  4517. */
  4518. static int rbuVfsSectorSize(sqlite3_file *pFile){
  4519. rbu_file *p = (rbu_file *)pFile;
  4520. return p->pReal->pMethods->xSectorSize(p->pReal);
  4521. }
  4522. /*
  4523. ** Return the device characteristic flags supported by an rbuVfs-file.
  4524. */
  4525. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  4526. rbu_file *p = (rbu_file *)pFile;
  4527. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  4528. }
  4529. /*
  4530. ** Take or release a shared-memory lock.
  4531. */
  4532. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  4533. rbu_file *p = (rbu_file*)pFile;
  4534. sqlite3rbu *pRbu = p->pRbu;
  4535. int rc = SQLITE_OK;
  4536. #ifdef SQLITE_AMALGAMATION
  4537. assert( WAL_CKPT_LOCK==1 );
  4538. #endif
  4539. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  4540. if( pRbu && (
  4541. pRbu->eStage==RBU_STAGE_OAL
  4542. || pRbu->eStage==RBU_STAGE_MOVE
  4543. || pRbu->eStage==RBU_STAGE_DONE
  4544. )){
  4545. /* Prevent SQLite from taking a shm-lock on the target file when it
  4546. ** is supplying heap memory to the upper layer in place of *-shm
  4547. ** segments. */
  4548. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  4549. }else{
  4550. int bCapture = 0;
  4551. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  4552. bCapture = 1;
  4553. }
  4554. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  4555. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  4556. if( bCapture && rc==SQLITE_OK ){
  4557. pRbu->mLock |= ((1<<n) - 1) << ofst;
  4558. }
  4559. }
  4560. }
  4561. return rc;
  4562. }
  4563. /*
  4564. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  4565. */
  4566. static int rbuVfsShmMap(
  4567. sqlite3_file *pFile,
  4568. int iRegion,
  4569. int szRegion,
  4570. int isWrite,
  4571. void volatile **pp
  4572. ){
  4573. rbu_file *p = (rbu_file*)pFile;
  4574. int rc = SQLITE_OK;
  4575. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  4576. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  4577. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  4578. ** instead of a file on disk. */
  4579. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  4580. if( eStage==RBU_STAGE_OAL ){
  4581. sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
  4582. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  4583. /* This is an RBU connection that uses its own heap memory for the
  4584. ** pages of the *-shm file. Since no other process can have run
  4585. ** recovery, the connection must request *-shm pages in order
  4586. ** from start to finish. */
  4587. assert( iRegion==p->nShm );
  4588. if( apNew==0 ){
  4589. rc = SQLITE_NOMEM;
  4590. }else{
  4591. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  4592. p->apShm = apNew;
  4593. p->nShm = iRegion+1;
  4594. }
  4595. if( rc==SQLITE_OK ){
  4596. char *pNew = (char*)sqlite3_malloc64(szRegion);
  4597. if( pNew==0 ){
  4598. rc = SQLITE_NOMEM;
  4599. }else{
  4600. memset(pNew, 0, szRegion);
  4601. p->apShm[iRegion] = pNew;
  4602. }
  4603. }
  4604. if( rc==SQLITE_OK ){
  4605. *pp = p->apShm[iRegion];
  4606. }else{
  4607. *pp = 0;
  4608. }
  4609. }else{
  4610. assert( p->apShm==0 );
  4611. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  4612. }
  4613. return rc;
  4614. }
  4615. /*
  4616. ** Memory barrier.
  4617. */
  4618. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  4619. rbu_file *p = (rbu_file *)pFile;
  4620. p->pReal->pMethods->xShmBarrier(p->pReal);
  4621. }
  4622. /*
  4623. ** The xShmUnmap method.
  4624. */
  4625. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  4626. rbu_file *p = (rbu_file*)pFile;
  4627. int rc = SQLITE_OK;
  4628. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  4629. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  4630. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  4631. /* no-op */
  4632. }else{
  4633. /* Release the checkpointer and writer locks */
  4634. rbuUnlockShm(p);
  4635. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  4636. }
  4637. return rc;
  4638. }
  4639. /*
  4640. ** Open an rbu file handle.
  4641. */
  4642. static int rbuVfsOpen(
  4643. sqlite3_vfs *pVfs,
  4644. const char *zName,
  4645. sqlite3_file *pFile,
  4646. int flags,
  4647. int *pOutFlags
  4648. ){
  4649. static sqlite3_io_methods rbuvfs_io_methods = {
  4650. 2, /* iVersion */
  4651. rbuVfsClose, /* xClose */
  4652. rbuVfsRead, /* xRead */
  4653. rbuVfsWrite, /* xWrite */
  4654. rbuVfsTruncate, /* xTruncate */
  4655. rbuVfsSync, /* xSync */
  4656. rbuVfsFileSize, /* xFileSize */
  4657. rbuVfsLock, /* xLock */
  4658. rbuVfsUnlock, /* xUnlock */
  4659. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  4660. rbuVfsFileControl, /* xFileControl */
  4661. rbuVfsSectorSize, /* xSectorSize */
  4662. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  4663. rbuVfsShmMap, /* xShmMap */
  4664. rbuVfsShmLock, /* xShmLock */
  4665. rbuVfsShmBarrier, /* xShmBarrier */
  4666. rbuVfsShmUnmap, /* xShmUnmap */
  4667. 0, 0 /* xFetch, xUnfetch */
  4668. };
  4669. static sqlite3_io_methods rbuvfs_io_methods1 = {
  4670. 1, /* iVersion */
  4671. rbuVfsClose, /* xClose */
  4672. rbuVfsRead, /* xRead */
  4673. rbuVfsWrite, /* xWrite */
  4674. rbuVfsTruncate, /* xTruncate */
  4675. rbuVfsSync, /* xSync */
  4676. rbuVfsFileSize, /* xFileSize */
  4677. rbuVfsLock, /* xLock */
  4678. rbuVfsUnlock, /* xUnlock */
  4679. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  4680. rbuVfsFileControl, /* xFileControl */
  4681. rbuVfsSectorSize, /* xSectorSize */
  4682. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  4683. 0, 0, 0, 0, 0, 0
  4684. };
  4685. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  4686. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  4687. rbu_file *pFd = (rbu_file *)pFile;
  4688. int rc = SQLITE_OK;
  4689. const char *zOpen = zName;
  4690. int oflags = flags;
  4691. memset(pFd, 0, sizeof(rbu_file));
  4692. pFd->pReal = (sqlite3_file*)&pFd[1];
  4693. pFd->pRbuVfs = pRbuVfs;
  4694. pFd->openFlags = flags;
  4695. if( zName ){
  4696. if( flags & SQLITE_OPEN_MAIN_DB ){
  4697. /* A main database has just been opened. The following block sets
  4698. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  4699. ** the name of the *-wal file this db connection will use. SQLite
  4700. ** happens to pass a pointer to this buffer when using xAccess()
  4701. ** or xOpen() to operate on the *-wal file. */
  4702. pFd->zWal = sqlite3_filename_wal(zName);
  4703. }
  4704. else if( flags & SQLITE_OPEN_WAL ){
  4705. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
  4706. if( pDb ){
  4707. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  4708. /* This call is to open a *-wal file. Intead, open the *-oal. */
  4709. size_t nOpen;
  4710. if( rbuIsVacuum(pDb->pRbu) ){
  4711. zOpen = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  4712. zOpen = sqlite3_filename_wal(zOpen);
  4713. }
  4714. nOpen = strlen(zOpen);
  4715. ((char*)zOpen)[nOpen-3] = 'o';
  4716. pFd->pRbu = pDb->pRbu;
  4717. }
  4718. pDb->pWalFd = pFd;
  4719. }
  4720. }
  4721. }else{
  4722. pFd->pRbu = pRbuVfs->pRbu;
  4723. }
  4724. if( oflags & SQLITE_OPEN_MAIN_DB
  4725. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  4726. ){
  4727. assert( oflags & SQLITE_OPEN_MAIN_DB );
  4728. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  4729. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  4730. zOpen = 0;
  4731. }
  4732. if( rc==SQLITE_OK ){
  4733. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  4734. }
  4735. if( pFd->pReal->pMethods ){
  4736. const sqlite3_io_methods *pMeth = pFd->pReal->pMethods;
  4737. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  4738. ** pointer and, if the file is a main database file, link it into the
  4739. ** mutex protected linked list of all such files. */
  4740. if( pMeth->iVersion<2 || pMeth->xShmLock==0 ){
  4741. pFile->pMethods = &rbuvfs_io_methods1;
  4742. }else{
  4743. pFile->pMethods = &rbuvfs_io_methods;
  4744. }
  4745. if( flags & SQLITE_OPEN_MAIN_DB ){
  4746. rbuMainlistAdd(pFd);
  4747. }
  4748. }else{
  4749. sqlite3_free(pFd->zDel);
  4750. }
  4751. return rc;
  4752. }
  4753. /*
  4754. ** Delete the file located at zPath.
  4755. */
  4756. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  4757. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4758. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  4759. }
  4760. /*
  4761. ** Test for access permissions. Return true if the requested permission
  4762. ** is available, or false otherwise.
  4763. */
  4764. static int rbuVfsAccess(
  4765. sqlite3_vfs *pVfs,
  4766. const char *zPath,
  4767. int flags,
  4768. int *pResOut
  4769. ){
  4770. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  4771. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  4772. int rc;
  4773. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  4774. /* If this call is to check if a *-wal file associated with an RBU target
  4775. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  4776. ** the following special handling is activated:
  4777. **
  4778. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  4779. ** ensures that the RBU extension never tries to update a database
  4780. ** in wal mode, even if the first page of the database file has
  4781. ** been damaged.
  4782. **
  4783. ** b) if the *-wal file does not exist, claim that it does anyway,
  4784. ** causing SQLite to call xOpen() to open it. This call will also
  4785. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  4786. ** file opened instead.
  4787. */
  4788. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  4789. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
  4790. if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  4791. assert( pDb->pRbu );
  4792. if( *pResOut ){
  4793. rc = SQLITE_CANTOPEN;
  4794. }else{
  4795. sqlite3_int64 sz = 0;
  4796. rc = rbuVfsFileSize(&pDb->base, &sz);
  4797. *pResOut = (sz>0);
  4798. }
  4799. }
  4800. }
  4801. return rc;
  4802. }
  4803. /*
  4804. ** Populate buffer zOut with the full canonical pathname corresponding
  4805. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  4806. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  4807. */
  4808. static int rbuVfsFullPathname(
  4809. sqlite3_vfs *pVfs,
  4810. const char *zPath,
  4811. int nOut,
  4812. char *zOut
  4813. ){
  4814. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4815. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  4816. }
  4817. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  4818. /*
  4819. ** Open the dynamic library located at zPath and return a handle.
  4820. */
  4821. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  4822. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4823. return pRealVfs->xDlOpen(pRealVfs, zPath);
  4824. }
  4825. /*
  4826. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  4827. ** utf-8 string describing the most recent error encountered associated
  4828. ** with dynamic libraries.
  4829. */
  4830. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  4831. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4832. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  4833. }
  4834. /*
  4835. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  4836. */
  4837. static void (*rbuVfsDlSym(
  4838. sqlite3_vfs *pVfs,
  4839. void *pArg,
  4840. const char *zSym
  4841. ))(void){
  4842. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4843. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  4844. }
  4845. /*
  4846. ** Close the dynamic library handle pHandle.
  4847. */
  4848. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  4849. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4850. pRealVfs->xDlClose(pRealVfs, pHandle);
  4851. }
  4852. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  4853. /*
  4854. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  4855. ** random data.
  4856. */
  4857. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  4858. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4859. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  4860. }
  4861. /*
  4862. ** Sleep for nMicro microseconds. Return the number of microseconds
  4863. ** actually slept.
  4864. */
  4865. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  4866. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4867. return pRealVfs->xSleep(pRealVfs, nMicro);
  4868. }
  4869. /*
  4870. ** Return the current time as a Julian Day number in *pTimeOut.
  4871. */
  4872. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  4873. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  4874. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  4875. }
  4876. /*
  4877. ** No-op.
  4878. */
  4879. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  4880. UNUSED_PARAMETER(pVfs);
  4881. UNUSED_PARAMETER(a);
  4882. UNUSED_PARAMETER(b);
  4883. return 0;
  4884. }
  4885. /*
  4886. ** Deregister and destroy an RBU vfs created by an earlier call to
  4887. ** sqlite3rbu_create_vfs().
  4888. */
  4889. void sqlite3rbu_destroy_vfs(const char *zName){
  4890. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  4891. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  4892. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  4893. sqlite3_vfs_unregister(pVfs);
  4894. sqlite3_free(pVfs);
  4895. }
  4896. }
  4897. /*
  4898. ** Create an RBU VFS named zName that accesses the underlying file-system
  4899. ** via existing VFS zParent. The new object is registered as a non-default
  4900. ** VFS with SQLite before returning.
  4901. */
  4902. int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  4903. /* Template for VFS */
  4904. static sqlite3_vfs vfs_template = {
  4905. 1, /* iVersion */
  4906. 0, /* szOsFile */
  4907. 0, /* mxPathname */
  4908. 0, /* pNext */
  4909. 0, /* zName */
  4910. 0, /* pAppData */
  4911. rbuVfsOpen, /* xOpen */
  4912. rbuVfsDelete, /* xDelete */
  4913. rbuVfsAccess, /* xAccess */
  4914. rbuVfsFullPathname, /* xFullPathname */
  4915. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  4916. rbuVfsDlOpen, /* xDlOpen */
  4917. rbuVfsDlError, /* xDlError */
  4918. rbuVfsDlSym, /* xDlSym */
  4919. rbuVfsDlClose, /* xDlClose */
  4920. #else
  4921. 0, 0, 0, 0,
  4922. #endif
  4923. rbuVfsRandomness, /* xRandomness */
  4924. rbuVfsSleep, /* xSleep */
  4925. rbuVfsCurrentTime, /* xCurrentTime */
  4926. rbuVfsGetLastError, /* xGetLastError */
  4927. 0, /* xCurrentTimeInt64 (version 2) */
  4928. 0, 0, 0 /* Unimplemented version 3 methods */
  4929. };
  4930. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  4931. int rc = SQLITE_OK;
  4932. size_t nName;
  4933. size_t nByte;
  4934. nName = strlen(zName);
  4935. nByte = sizeof(rbu_vfs) + nName + 1;
  4936. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  4937. if( pNew==0 ){
  4938. rc = SQLITE_NOMEM;
  4939. }else{
  4940. sqlite3_vfs *pParent; /* Parent VFS */
  4941. memset(pNew, 0, nByte);
  4942. pParent = sqlite3_vfs_find(zParent);
  4943. if( pParent==0 ){
  4944. rc = SQLITE_NOTFOUND;
  4945. }else{
  4946. char *zSpace;
  4947. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  4948. pNew->base.mxPathname = pParent->mxPathname;
  4949. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  4950. pNew->pRealVfs = pParent;
  4951. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  4952. memcpy(zSpace, zName, nName);
  4953. /* Allocate the mutex and register the new VFS (not as the default) */
  4954. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  4955. if( pNew->mutex==0 ){
  4956. rc = SQLITE_NOMEM;
  4957. }else{
  4958. rc = sqlite3_vfs_register(&pNew->base, 0);
  4959. }
  4960. }
  4961. if( rc!=SQLITE_OK ){
  4962. sqlite3_mutex_free(pNew->mutex);
  4963. sqlite3_free(pNew);
  4964. }
  4965. }
  4966. return rc;
  4967. }
  4968. /*
  4969. ** Configure the aggregate temp file size limit for this RBU handle.
  4970. */
  4971. sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  4972. if( n>=0 ){
  4973. pRbu->szTempLimit = n;
  4974. }
  4975. return pRbu->szTempLimit;
  4976. }
  4977. sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  4978. return pRbu->szTemp;
  4979. }
  4980. /**************************************************************************/
  4981. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */