123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034 |
- //
- // Copyright (c) 2009-2024 Krueger Systems, Inc.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- #if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
- #define USE_CSHARP_SQLITE
- #endif
- using System;
- using System.Collections;
- using System.Diagnostics;
- #if !USE_SQLITEPCL_RAW
- using System.Runtime.InteropServices;
- #endif
- using System.Collections.Generic;
- using System.Reflection;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Text;
- using System.Threading;
- #if USE_CSHARP_SQLITE
- using Sqlite3 = Community.CsharpSqlite.Sqlite3;
- using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
- using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
- #elif USE_WP8_NATIVE_SQLITE
- using Sqlite3 = Sqlite.Sqlite3;
- using Sqlite3DatabaseHandle = Sqlite.Database;
- using Sqlite3Statement = Sqlite.Statement;
- #elif USE_SQLITEPCL_RAW
- using Sqlite3DatabaseHandle = SQLitePCL.sqlite3;
- using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup;
- using Sqlite3Statement = SQLitePCL.sqlite3_stmt;
- using Sqlite3 = SQLitePCL.raw;
- #else
- using Sqlite3DatabaseHandle = System.IntPtr;
- using Sqlite3BackupHandle = System.IntPtr;
- using Sqlite3Statement = System.IntPtr;
- #endif
- #pragma warning disable 1591 // XML Doc Comments
- namespace SQLite
- {
- public class SQLiteException : Exception
- {
- public SQLite3.Result Result { get; private set; }
- protected SQLiteException (SQLite3.Result r, string message) : base (message)
- {
- Result = r;
- }
- public static SQLiteException New (SQLite3.Result r, string message)
- {
- return new SQLiteException (r, message);
- }
- }
- public class NotNullConstraintViolationException : SQLiteException
- {
- public IEnumerable<TableMapping.Column> Columns { get; protected set; }
- protected NotNullConstraintViolationException (SQLite3.Result r, string message)
- : this (r, message, null, null)
- {
- }
- protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
- : base (r, message)
- {
- if (mapping != null && obj != null) {
- this.Columns = from c in mapping.Columns
- where c.IsNullable == false && c.GetValue (obj) == null
- select c;
- }
- }
- public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
- {
- return new NotNullConstraintViolationException (r, message);
- }
- public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
- {
- return new NotNullConstraintViolationException (r, message, mapping, obj);
- }
- public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
- {
- return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
- }
- }
- [Flags]
- public enum SQLiteOpenFlags
- {
- ReadOnly = 1, ReadWrite = 2, Create = 4,
- Uri = 0x40, Memory = 0x80,
- NoMutex = 0x8000, FullMutex = 0x10000,
- SharedCache = 0x20000, PrivateCache = 0x40000,
- ProtectionComplete = 0x00100000,
- ProtectionCompleteUnlessOpen = 0x00200000,
- ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
- ProtectionNone = 0x00400000
- }
- [Flags]
- public enum CreateFlags
- {
- /// <summary>
- /// Use the default creation options
- /// </summary>
- None = 0x000,
- /// <summary>
- /// Create a primary key index for a property called 'Id' (case-insensitive).
- /// This avoids the need for the [PrimaryKey] attribute.
- /// </summary>
- ImplicitPK = 0x001,
- /// <summary>
- /// Create indices for properties ending in 'Id' (case-insensitive).
- /// </summary>
- ImplicitIndex = 0x002,
- /// <summary>
- /// Create a primary key for a property called 'Id' and
- /// create an indices for properties ending in 'Id' (case-insensitive).
- /// </summary>
- AllImplicit = 0x003,
- /// <summary>
- /// Force the primary key property to be auto incrementing.
- /// This avoids the need for the [AutoIncrement] attribute.
- /// The primary key property on the class should have type int or long.
- /// </summary>
- AutoIncPK = 0x004,
- /// <summary>
- /// Create virtual table using FTS3
- /// </summary>
- FullTextSearch3 = 0x100,
- /// <summary>
- /// Create virtual table using FTS4
- /// </summary>
- FullTextSearch4 = 0x200
- }
- public interface ISQLiteConnection : IDisposable
- {
- Sqlite3DatabaseHandle Handle { get; }
- string DatabasePath { get; }
- int LibVersionNumber { get; }
- bool TimeExecution { get; set; }
- bool Trace { get; set; }
- Action<string> Tracer { get; set; }
- bool StoreDateTimeAsTicks { get; }
- bool StoreTimeSpanAsTicks { get; }
- string DateTimeStringFormat { get; }
- TimeSpan BusyTimeout { get; set; }
- IEnumerable<TableMapping> TableMappings { get; }
- bool IsInTransaction { get; }
- event EventHandler<NotifyTableChangedEventArgs> TableChanged;
- void Backup (string destinationDatabasePath, string databaseName = "main");
- void BeginTransaction ();
- void Close ();
- void Commit ();
- SQLiteCommand CreateCommand (string cmdText, params object[] ps);
- SQLiteCommand CreateCommand (string cmdText, Dictionary<string, object> args);
- int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false);
- int CreateIndex (string indexName, string tableName, string columnName, bool unique = false);
- int CreateIndex (string tableName, string columnName, bool unique = false);
- int CreateIndex (string tableName, string[] columnNames, bool unique = false);
- int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false);
- CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None,string tableName = "");
- CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None,string tableName = "");
- CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new();
- CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- where T3 : new();
- CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- where T3 : new()
- where T4 : new();
- CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- where T3 : new()
- where T4 : new()
- where T5 : new();
- CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types);
- IEnumerable<T> DeferredQuery<T> (string query, params object[] args) where T : new();
- IEnumerable<object> DeferredQuery (TableMapping map, string query, params object[] args);
- int Delete (object objectToDelete,string tableName = "");
- int Delete<T> (object primaryKey,string tableName = "");
- int Delete (object primaryKey, TableMapping map);
- int DeleteAll<T> (string tableName = "");
- int DeleteAll (TableMapping map);
- int DropTable<T> (string tableName = "");
- int DropTable (TableMapping map);
- void EnableLoadExtension (bool enabled);
- void EnableWriteAheadLogging ();
- int Execute (string query, params object[] args);
- T ExecuteScalar<T> (string query, params object[] args);
- T Find<T> (object pk,string tableName = "") where T : new();
- object Find (object pk, TableMapping map);
- T Find<T> (Expression<Func<T, bool>> predicate,string tableName = "") where T : new();
- T FindWithQuery<T> (string query, params object[] args) where T : new();
- object FindWithQuery (TableMapping map, string query, params object[] args);
- T Get<T> (object pk,string tableName = "") where T : new();
- object Get (object pk, TableMapping map);
- T Get<T> (Expression<Func<T, bool>> predicate,string tableName = "") where T : new();
- TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None,string tableName = "");
- TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None,string tableName = "");
- List<SQLiteConnection.ColumnInfo> GetTableInfo (string tableName);
- int Insert (object obj,string tableName = "");
- int Insert (object obj, Type objType,string tableName = "");
- int Insert (object obj, string extra,string tableName = "");
- int Insert (object obj, string extra, Type objType,string tableName = "");
- int InsertAll (IEnumerable objects, bool runInTransaction = true,string tableName = "");
- int InsertAll (IEnumerable objects, string extra, bool runInTransaction = true,string tableName = "");
- int InsertAll (IEnumerable objects, Type objType, bool runInTransaction = true,string tableName = "");
- int InsertOrReplace (object obj,string tableName = "");
- int InsertOrReplace (object obj, Type objType,string tableName = "");
- List<T> Query<T> (string query, params object[] args) where T : new();
- List<object> Query (TableMapping map, string query, params object[] args);
- List<T> QueryScalars<T> (string query, params object[] args);
- void ReKey (string key);
- void ReKey (byte[] key);
- void Release (string savepoint);
- void Rollback ();
- void RollbackTo (string savepoint);
- void RunInTransaction (Action action);
- string SaveTransactionPoint ();
- TableQuery<T> Table<T> (string tableName = "") where T : new();
- int Update (object obj,string tableName = "");
- int Update (object obj, Type objType,string tableName = "");
- int UpdateAll (IEnumerable objects, bool runInTransaction = true,string tableName = "");
- }
- /// <summary>
- /// An open connection to a SQLite database.
- /// </summary>
- [Preserve (AllMembers = true)]
- public partial class SQLiteConnection : ISQLiteConnection
- {
- private bool _open;
- private TimeSpan _busyTimeout;
- readonly static Dictionary<string, TableMapping> _mappings = new Dictionary<string, TableMapping> ();
- private System.Diagnostics.Stopwatch _sw;
- private long _elapsedMilliseconds = 0;
- private int _transactionDepth = 0;
- private Random _rand = new Random ();
- public Sqlite3DatabaseHandle Handle { get; private set; }
- static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle);
- static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle);
- /// <summary>
- /// Gets the database path used by this connection.
- /// </summary>
- public string DatabasePath { get; private set; }
- /// <summary>
- /// Gets the SQLite library version number. 3007014 would be v3.7.14
- /// </summary>
- public int LibVersionNumber { get; private set; }
- /// <summary>
- /// Whether Trace lines should be written that show the execution time of queries.
- /// </summary>
- public bool TimeExecution { get; set; }
- /// <summary>
- /// Whether to write queries to <see cref="Tracer"/> during execution.
- /// </summary>
- public bool Trace { get; set; }
- /// <summary>
- /// The delegate responsible for writing trace lines.
- /// </summary>
- /// <value>The tracer.</value>
- public Action<string> Tracer { get; set; }
- /// <summary>
- /// Whether to store DateTime properties as ticks (true) or strings (false).
- /// </summary>
- public bool StoreDateTimeAsTicks { get; private set; }
- /// <summary>
- /// Whether to store TimeSpan properties as ticks (true) or strings (false).
- /// </summary>
- public bool StoreTimeSpanAsTicks { get; private set; }
- /// <summary>
- /// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true.
- /// </summary>
- /// <value>The date time string format.</value>
- public string DateTimeStringFormat { get; private set; }
- /// <summary>
- /// The DateTimeStyles value to use when parsing a DateTime property string.
- /// </summary>
- /// <value>The date time style.</value>
- internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; }
- #if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES
- static SQLiteConnection ()
- {
- SQLitePCL.Batteries_V2.Init ();
- }
- #endif
- /// <summary>
- /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
- /// </summary>
- /// <param name="databasePath">
- /// Specifies the path to the database file.
- /// </param>
- /// <param name="storeDateTimeAsTicks">
- /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
- /// absolutely do want to store them as Ticks in all new projects. The value of false is
- /// only here for backwards compatibility. There is a *significant* speed advantage, with no
- /// down sides, when setting storeDateTimeAsTicks = true.
- /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
- /// the storeDateTimeAsTicks parameter.
- /// </param>
- public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true)
- : this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks))
- {
- }
- /// <summary>
- /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
- /// </summary>
- /// <param name="databasePath">
- /// Specifies the path to the database file.
- /// </param>
- /// <param name="openFlags">
- /// Flags controlling how the connection should be opened.
- /// </param>
- /// <param name="storeDateTimeAsTicks">
- /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
- /// absolutely do want to store them as Ticks in all new projects. The value of false is
- /// only here for backwards compatibility. There is a *significant* speed advantage, with no
- /// down sides, when setting storeDateTimeAsTicks = true.
- /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
- /// the storeDateTimeAsTicks parameter.
- /// </param>
- public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
- : this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks))
- {
- }
- /// <summary>
- /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
- /// </summary>
- /// <param name="connectionString">
- /// Details on how to find and open the database.
- /// </param>
- public SQLiteConnection (SQLiteConnectionString connectionString)
- {
- if (connectionString == null)
- throw new ArgumentNullException (nameof (connectionString));
- if (connectionString.DatabasePath == null)
- throw new InvalidOperationException ("DatabasePath must be specified");
- DatabasePath = connectionString.DatabasePath;
- LibVersionNumber = SQLite3.LibVersionNumber ();
- #if NETFX_CORE
- SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
- #endif
- Sqlite3DatabaseHandle handle;
- #if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW
- var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
- #else
- // open using the byte[]
- // in the case where the path may include Unicode
- // force open to using UTF-8 using sqlite3_open_v2
- var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath);
- var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
- #endif
- Handle = handle;
- if (r != SQLite3.Result.OK) {
- throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
- }
- _open = true;
- StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks;
- StoreTimeSpanAsTicks = connectionString.StoreTimeSpanAsTicks;
- DateTimeStringFormat = connectionString.DateTimeStringFormat;
- DateTimeStyle = connectionString.DateTimeStyle;
- BusyTimeout = TimeSpan.FromSeconds (1.0);
- Tracer = line => Debug.WriteLine (line);
- connectionString.PreKeyAction?.Invoke (this);
- if (connectionString.Key is string stringKey) {
- SetKey (stringKey);
- }
- else if (connectionString.Key is byte[] bytesKey) {
- SetKey (bytesKey);
- }
- else if (connectionString.Key != null) {
- throw new InvalidOperationException ("Encryption keys must be strings or byte arrays");
- }
- connectionString.PostKeyAction?.Invoke (this);
- }
- /// <summary>
- /// Enables the write ahead logging. WAL is significantly faster in most scenarios
- /// by providing better concurrency and better disk IO performance than the normal
- /// journal mode. You only need to call this function once in the lifetime of the database.
- /// </summary>
- public void EnableWriteAheadLogging ()
- {
- ExecuteScalar<string> ("PRAGMA journal_mode=WAL");
- }
- /// <summary>
- /// Convert an input string to a quoted SQL string that can be safely used in queries.
- /// </summary>
- /// <returns>The quoted string.</returns>
- /// <param name="unsafeString">The unsafe string to quote.</param>
- static string Quote (string unsafeString)
- {
- // TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153
- if (unsafeString == null)
- return "NULL";
- var safe = unsafeString.Replace ("'", "''");
- return "'" + safe + "'";
- }
- /// <summary>
- /// Sets the key used to encrypt/decrypt the database with "pragma key = ...".
- /// This must be the first thing you call before doing anything else with this connection
- /// if your database is encrypted.
- /// This only has an effect if you are using the SQLCipher nuget package.
- /// </summary>
- /// <param name="key">Encryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
- void SetKey (string key)
- {
- if (key == null)
- throw new ArgumentNullException (nameof (key));
- var q = Quote (key);
- ExecuteScalar<string> ("pragma key = " + q);
- }
- /// <summary>
- /// Sets the key used to encrypt/decrypt the database.
- /// This must be the first thing you call before doing anything else with this connection
- /// if your database is encrypted.
- /// This only has an effect if you are using the SQLCipher nuget package.
- /// </summary>
- /// <param name="key">256-bit (32 byte) encryption key data</param>
- void SetKey (byte[] key)
- {
- if (key == null)
- throw new ArgumentNullException (nameof (key));
- if (key.Length != 32 && key.Length != 48)
- throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
- var s = String.Join ("", key.Select (x => x.ToString ("X2")));
- ExecuteScalar<string> ("pragma key = \"x'" + s + "'\"");
- }
- /// <summary>
- /// Change the encryption key for a SQLCipher database with "pragma rekey = ...".
- /// </summary>
- /// <param name="key">Encryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
- public void ReKey (string key)
- {
- if (key == null)
- throw new ArgumentNullException(nameof(key));
- var q = Quote(key);
- ExecuteScalar<string>("pragma rekey = " + q);
- }
- /// <summary>
- /// Change the encryption key for a SQLCipher database.
- /// </summary>
- /// <param name="key">256-bit (32 byte) or 384-bit (48 bytes) encryption key data</param>
- public void ReKey (byte[] key)
- {
- if (key == null)
- throw new ArgumentNullException(nameof(key));
- if (key.Length != 32 && key.Length != 48)
- throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
- var s = String.Join("", key.Select(x => x.ToString("X2")));
- ExecuteScalar<string>("pragma rekey = \"x'" + s + "'\"");
- }
- /// <summary>
- /// Enable or disable extension loading.
- /// </summary>
- public void EnableLoadExtension (bool enabled)
- {
- SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0);
- if (r != SQLite3.Result.OK) {
- string msg = SQLite3.GetErrmsg (Handle);
- throw SQLiteException.New (r, msg);
- }
- }
- #if !USE_SQLITEPCL_RAW
- static byte[] GetNullTerminatedUtf8 (string s)
- {
- var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
- var bytes = new byte [utf8Length + 1];
- utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
- return bytes;
- }
- #endif
- /// <summary>
- /// Sets a busy handler to sleep the specified amount of time when a table is locked.
- /// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated.
- /// </summary>
- public TimeSpan BusyTimeout {
- get { return _busyTimeout; }
- set {
- _busyTimeout = value;
- if (Handle != NullHandle) {
- SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
- }
- }
- }
- /// <summary>
- /// Returns the mappings from types to tables that the connection
- /// currently understands.
- /// </summary>
- public IEnumerable<TableMapping> TableMappings {
- get {
- lock (_mappings) {
- return new List<TableMapping> (_mappings.Values);
- }
- }
- }
- /// <summary>
- /// Retrieves the mapping that is automatically generated for the given type.
- /// </summary>
- /// <param name="type">
- /// The type whose mapping to the database is returned.
- /// </param>
- /// <param name="createFlags">
- /// Optional flags allowing implicit PK and indexes based on naming conventions
- /// </param>
- /// <returns>
- /// The mapping represents the schema of the columns of the database and contains
- /// methods to set and get properties of objects.
- /// </returns>
- public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None,string tableName = "")
- {
- TableMapping map;
- var key = type.FullName;
- if (!string.IsNullOrEmpty(tableName)) key = tableName;
- lock (_mappings) {
- if (_mappings.TryGetValue (key, out map)) {
- if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) {
- map = new TableMapping (type, createFlags,tableName);
- _mappings[key] = map;
- }
- }
- else {
- map = new TableMapping (type, createFlags,tableName);
- _mappings.Add (key, map);
- }
- }
- return map;
- }
- /// <summary>
- /// Retrieves the mapping that is automatically generated for the given type.
- /// </summary>
- /// <param name="createFlags">
- /// Optional flags allowing implicit PK and indexes based on naming conventions
- /// </param>
- /// <returns>
- /// The mapping represents the schema of the columns of the database and contains
- /// methods to set and get properties of objects.
- /// </returns>
- public TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None,string tableName = "")
- {
- return GetMapping (typeof (T), createFlags,tableName);
- }
- private struct IndexedColumn
- {
- public int Order;
- public string ColumnName;
- }
- private struct IndexInfo
- {
- public string IndexName;
- public string TableName;
- public bool Unique;
- public List<IndexedColumn> Columns;
- }
- /// <summary>
- /// Executes a "drop table" on the database. This is non-recoverable.
- /// </summary>
- public int DropTable<T> (string tableName = "")
- {
- return DropTable (GetMapping (typeof (T),tableName:tableName));
- }
- /// <summary>
- /// Executes a "drop table" on the database. This is non-recoverable.
- /// </summary>
- /// <param name="map">
- /// The TableMapping used to identify the table.
- /// </param>
- public int DropTable (TableMapping map)
- {
- var query = string.Format ("drop table if exists \"{0}\"", map.TableName);
- return Execute (query);
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <returns>
- /// Whether the table was created or migrated.
- /// </returns>
- public CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None,string tableName = "")
- {
- return CreateTable (typeof (T), createFlags,tableName);
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <param name="ty">Type to reflect to a database table.</param>
- /// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
- /// <returns>
- /// Whether the table was created or migrated.
- /// </returns>
- public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None,string tableName="")
- {
- var map = GetMapping (ty, createFlags,tableName);
- // Present a nice error if no columns specified
- if (map.Columns.Length == 0) {
- throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName));
- }
- // Check if the table exists
- var result = CreateTableResult.Created;
- var existingCols = GetTableInfo (map.TableName);
- // Create or migrate it
- if (existingCols.Count == 0) {
- // Facilitate virtual tables a.k.a. full-text search.
- bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
- bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
- bool fts = fts3 || fts4;
- var @virtual = fts ? "virtual " : string.Empty;
- var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty;
- // Build query.
- var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n";
- var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks));
- var decl = string.Join (",\n", decls.ToArray ());
- query += decl;
- query += ")";
- if (map.WithoutRowId) {
- query += " without rowid";
- }
- Execute (query);
- }
- else {
- result = CreateTableResult.Migrated;
- MigrateTable (map, existingCols);
- }
- var indexes = new Dictionary<string, IndexInfo> ();
- foreach (var c in map.Columns) {
- foreach (var i in c.Indices) {
- var iname = i.Name ?? map.TableName + "_" + c.Name;
- IndexInfo iinfo;
- if (!indexes.TryGetValue (iname, out iinfo)) {
- iinfo = new IndexInfo {
- IndexName = iname,
- TableName = map.TableName,
- Unique = i.Unique,
- Columns = new List<IndexedColumn> ()
- };
- indexes.Add (iname, iinfo);
- }
- if (i.Unique != iinfo.Unique)
- throw new Exception ("All the columns in an index must have the same value for their Unique property");
- iinfo.Columns.Add (new IndexedColumn {
- Order = i.Order,
- ColumnName = c.Name
- });
- }
- }
- foreach (var indexName in indexes.Keys) {
- var index = indexes[indexName];
- var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray ();
- CreateIndex (indexName, index.TableName, columns, index.Unique);
- }
- return result;
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database for each type. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <returns>
- /// Whether the table was created or migrated for each type.
- /// </returns>
- public CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- {
- return CreateTables (createFlags, typeof (T), typeof (T2));
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database for each type. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <returns>
- /// Whether the table was created or migrated for each type.
- /// </returns>
- public CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- where T3 : new()
- {
- return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3));
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database for each type. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <returns>
- /// Whether the table was created or migrated for each type.
- /// </returns>
- public CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- where T3 : new()
- where T4 : new()
- {
- return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4));
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database for each type. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <returns>
- /// Whether the table was created or migrated for each type.
- /// </returns>
- public CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
- where T : new()
- where T2 : new()
- where T3 : new()
- where T4 : new()
- where T5 : new()
- {
- return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
- }
- /// <summary>
- /// Executes a "create table if not exists" on the database for each type. It also
- /// creates any specified indexes on the columns of the table. It uses
- /// a schema automatically generated from the specified type. You can
- /// later access this schema by calling GetMapping.
- /// </summary>
- /// <returns>
- /// Whether the table was created or migrated for each type.
- /// </returns>
- public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types)
- {
- var result = new CreateTablesResult ();
- foreach (Type type in types) {
- var aResult = CreateTable (type, createFlags);
- result.Results[type] = aResult;
- }
- return result;
- }
- /// <summary>
- /// Creates an index for the specified table and columns.
- /// </summary>
- /// <param name="indexName">Name of the index to create</param>
- /// <param name="tableName">Name of the database table</param>
- /// <param name="columnNames">An array of column names to index</param>
- /// <param name="unique">Whether the index should be unique</param>
- /// <returns>Zero on success.</returns>
- public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false)
- {
- const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
- var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
- return Execute (sql);
- }
- /// <summary>
- /// Creates an index for the specified table and column.
- /// </summary>
- /// <param name="indexName">Name of the index to create</param>
- /// <param name="tableName">Name of the database table</param>
- /// <param name="columnName">Name of the column to index</param>
- /// <param name="unique">Whether the index should be unique</param>
- /// <returns>Zero on success.</returns>
- public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false)
- {
- return CreateIndex (indexName, tableName, new string[] { columnName }, unique);
- }
- /// <summary>
- /// Creates an index for the specified table and column.
- /// </summary>
- /// <param name="tableName">Name of the database table</param>
- /// <param name="columnName">Name of the column to index</param>
- /// <param name="unique">Whether the index should be unique</param>
- /// <returns>Zero on success.</returns>
- public int CreateIndex (string tableName, string columnName, bool unique = false)
- {
- return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique);
- }
- /// <summary>
- /// Creates an index for the specified table and columns.
- /// </summary>
- /// <param name="tableName">Name of the database table</param>
- /// <param name="columnNames">An array of column names to index</param>
- /// <param name="unique">Whether the index should be unique</param>
- /// <returns>Zero on success.</returns>
- public int CreateIndex (string tableName, string[] columnNames, bool unique = false)
- {
- return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
- }
- /// <summary>
- /// Creates an index for the specified object property.
- /// e.g. CreateIndex<Client>(c => c.Name);
- /// </summary>
- /// <typeparam name="T">Type to reflect to a database table.</typeparam>
- /// <param name="property">Property to index</param>
- /// <param name="unique">Whether the index should be unique</param>
- /// <returns>Zero on success.</returns>
- public int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false)
- {
- MemberExpression mx;
- if (property.Body.NodeType == ExpressionType.Convert) {
- mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
- }
- else {
- mx = (property.Body as MemberExpression);
- }
- var propertyInfo = mx.Member as PropertyInfo;
- if (propertyInfo == null) {
- throw new ArgumentException ("The lambda expression 'property' should point to a valid Property");
- }
- var propName = propertyInfo.Name;
- var map = GetMapping<T> ();
- var colName = map.FindColumnWithPropertyName (propName).Name;
- return CreateIndex (map.TableName, colName, unique);
- }
- [Preserve (AllMembers = true)]
- public class ColumnInfo
- {
- // public int cid { get; set; }
- [Column ("name")]
- public string Name { get; set; }
- // [Column ("type")]
- // public string ColumnType { get; set; }
- public int notnull { get; set; }
- // public string dflt_value { get; set; }
- // public int pk { get; set; }
- public override string ToString ()
- {
- return Name;
- }
- }
- /// <summary>
- /// Query the built-in sqlite table_info table for a specific tables columns.
- /// </summary>
- /// <returns>The columns contains in the table.</returns>
- /// <param name="tableName">Table name.</param>
- public List<ColumnInfo> GetTableInfo (string tableName)
- {
- var query = "pragma table_info(\"" + tableName + "\")";
- return Query<ColumnInfo> (query);
- }
- void MigrateTable (TableMapping map, List<ColumnInfo> existingCols)
- {
- var toBeAdded = new List<TableMapping.Column> ();
- foreach (var p in map.Columns) {
- var found = false;
- foreach (var c in existingCols) {
- found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
- if (found)
- break;
- }
- if (!found) {
- toBeAdded.Add (p);
- }
- }
- foreach (var p in toBeAdded) {
- var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks);
- Execute (addCol);
- }
- }
- /// <summary>
- /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
- /// </summary>
- /// <seealso cref="SQLiteCommand.OnInstanceCreated"/>
- protected virtual SQLiteCommand NewCommand ()
- {
- return new SQLiteCommand (this);
- }
- /// <summary>
- /// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
- /// in the command text for each of the arguments.
- /// </summary>
- /// <param name="cmdText">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="ps">
- /// Arguments to substitute for the occurences of '?' in the command text.
- /// </param>
- /// <returns>
- /// A <see cref="SQLiteCommand"/>
- /// </returns>
- public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
- {
- if (!_open)
- throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
- var cmd = NewCommand ();
- cmd.CommandText = cmdText;
- foreach (var o in ps) {
- cmd.Bind (o);
- }
- return cmd;
- }
- /// <summary>
- /// Creates a new SQLiteCommand given the command text with named arguments. Place a "[@:$]VVV"
- /// in the command text for each of the arguments. VVV represents an alphanumeric identifier.
- /// For example, @name :name and $name can all be used in the query.
- /// </summary>
- /// <param name="cmdText">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of "[@:$]VVV" in the command text.
- /// </param>
- /// <returns>
- /// A <see cref="SQLiteCommand" />
- /// </returns>
- public SQLiteCommand CreateCommand (string cmdText, Dictionary<string, object> args)
- {
- if (!_open)
- throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
- SQLiteCommand cmd = NewCommand ();
- cmd.CommandText = cmdText;
- foreach (var kv in args) {
- cmd.Bind (kv.Key, kv.Value);
- }
- return cmd;
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// Use this method instead of Query when you don't expect rows back. Such cases include
- /// INSERTs, UPDATEs, and DELETEs.
- /// You can set the Trace or TimeExecution properties of the connection
- /// to profile execution.
- /// </summary>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// The number of rows modified in the database as a result of this execution.
- /// </returns>
- public int Execute (string query, params object[] args)
- {
- var cmd = CreateCommand (query, args);
- if (TimeExecution) {
- if (_sw == null) {
- _sw = new Stopwatch ();
- }
- _sw.Reset ();
- _sw.Start ();
- }
- var r = cmd.ExecuteNonQuery ();
- if (TimeExecution) {
- _sw.Stop ();
- _elapsedMilliseconds += _sw.ElapsedMilliseconds;
- Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
- }
- return r;
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// Use this method when return primitive values.
- /// You can set the Trace or TimeExecution properties of the connection
- /// to profile execution.
- /// </summary>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// The number of rows modified in the database as a result of this execution.
- /// </returns>
- public T ExecuteScalar<T> (string query, params object[] args)
- {
- var cmd = CreateCommand (query, args);
- if (TimeExecution) {
- if (_sw == null) {
- _sw = new Stopwatch ();
- }
- _sw.Reset ();
- _sw.Start ();
- }
- var r = cmd.ExecuteScalar<T> ();
- if (TimeExecution) {
- _sw.Stop ();
- _elapsedMilliseconds += _sw.ElapsedMilliseconds;
- Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
- }
- return r;
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// It returns each row of the result using the mapping automatically generated for
- /// the given type.
- /// </summary>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// An enumerable with one result for each row returned by the query.
- /// </returns>
- public List<T> Query<T> (string query, params object[] args) where T : new()
- {
- var cmd = CreateCommand (query, args);
- return cmd.ExecuteQuery<T> ();
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// It returns the first column of each row of the result.
- /// </summary>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// An enumerable with one result for the first column of each row returned by the query.
- /// </returns>
- public List<T> QueryScalars<T> (string query, params object[] args)
- {
- var cmd = CreateCommand (query, args);
- return cmd.ExecuteQueryScalars<T> ().ToList ();
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// It returns each row of the result using the mapping automatically generated for
- /// the given type.
- /// </summary>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// An enumerable with one result for each row returned by the query.
- /// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
- /// will call sqlite3_step on each call to MoveNext, so the database
- /// connection must remain open for the lifetime of the enumerator.
- /// </returns>
- public IEnumerable<T> DeferredQuery<T> (string query, params object[] args) where T : new()
- {
- var cmd = CreateCommand (query, args);
- return cmd.ExecuteDeferredQuery<T> ();
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// It returns each row of the result using the specified mapping. This function is
- /// only used by libraries in order to query the database via introspection. It is
- /// normally not used.
- /// </summary>
- /// <param name="map">
- /// A <see cref="TableMapping"/> to use to convert the resulting rows
- /// into objects.
- /// </param>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// An enumerable with one result for each row returned by the query.
- /// </returns>
- public List<object> Query (TableMapping map, string query, params object[] args)
- {
- var cmd = CreateCommand (query, args);
- return cmd.ExecuteQuery<object> (map);
- }
- /// <summary>
- /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
- /// in the command text for each of the arguments and then executes that command.
- /// It returns each row of the result using the specified mapping. This function is
- /// only used by libraries in order to query the database via introspection. It is
- /// normally not used.
- /// </summary>
- /// <param name="map">
- /// A <see cref="TableMapping"/> to use to convert the resulting rows
- /// into objects.
- /// </param>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// An enumerable with one result for each row returned by the query.
- /// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
- /// will call sqlite3_step on each call to MoveNext, so the database
- /// connection must remain open for the lifetime of the enumerator.
- /// </returns>
- public IEnumerable<object> DeferredQuery (TableMapping map, string query, params object[] args)
- {
- var cmd = CreateCommand (query, args);
- return cmd.ExecuteDeferredQuery<object> (map);
- }
- /// <summary>
- /// Returns a queryable interface to the table represented by the given type.
- /// </summary>
- /// <returns>
- /// A queryable object that is able to translate Where, OrderBy, and Take
- /// queries into native SQL.
- /// </returns>
- public TableQuery<T> Table<T> (string tableName = "") where T : new()
- {
- return new TableQuery<T> (this,tableName);
- }
- /// <summary>
- /// Attempts to retrieve an object with the given primary key from the table
- /// associated with the specified type. Use of this method requires that
- /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
- /// </summary>
- /// <param name="pk">
- /// The primary key.
- /// </param>
- /// <returns>
- /// The object with the given primary key. Throws a not found exception
- /// if the object is not found.
- /// </returns>
- public T Get<T> (object pk,string tableName = "") where T : new()
- {
- var map = GetMapping (typeof (T),tableName:tableName);
- return Query<T> (map.GetByPrimaryKeySql, pk).First ();
- }
- /// <summary>
- /// Attempts to retrieve an object with the given primary key from the table
- /// associated with the specified type. Use of this method requires that
- /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
- /// </summary>
- /// <param name="pk">
- /// The primary key.
- /// </param>
- /// <param name="map">
- /// The TableMapping used to identify the table.
- /// </param>
- /// <returns>
- /// The object with the given primary key. Throws a not found exception
- /// if the object is not found.
- /// </returns>
- public object Get (object pk, TableMapping map)
- {
- return Query (map, map.GetByPrimaryKeySql, pk).First ();
- }
- /// <summary>
- /// Attempts to retrieve the first object that matches the predicate from the table
- /// associated with the specified type.
- /// </summary>
- /// <param name="predicate">
- /// A predicate for which object to find.
- /// </param>
- /// <returns>
- /// The object that matches the given predicate. Throws a not found exception
- /// if the object is not found.
- /// </returns>
- public T Get<T> (Expression<Func<T, bool>> predicate,string tableName = "") where T : new()
- {
- return Table<T> (tableName).Where (predicate).First ();
- }
- /// <summary>
- /// Attempts to retrieve an object with the given primary key from the table
- /// associated with the specified type. Use of this method requires that
- /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
- /// </summary>
- /// <param name="pk">
- /// The primary key.
- /// </param>
- /// <returns>
- /// The object with the given primary key or null
- /// if the object is not found.
- /// </returns>
- public T Find<T> (object pk,string tableName = "") where T : new()
- {
- var map = GetMapping (typeof (T),tableName:tableName);
- return Query<T> (map.GetByPrimaryKeySql, pk).FirstOrDefault ();
- }
- /// <summary>
- /// Attempts to retrieve an object with the given primary key from the table
- /// associated with the specified type. Use of this method requires that
- /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
- /// </summary>
- /// <param name="pk">
- /// The primary key.
- /// </param>
- /// <param name="map">
- /// The TableMapping used to identify the table.
- /// </param>
- /// <returns>
- /// The object with the given primary key or null
- /// if the object is not found.
- /// </returns>
- public object Find (object pk, TableMapping map)
- {
- return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault ();
- }
- /// <summary>
- /// Attempts to retrieve the first object that matches the predicate from the table
- /// associated with the specified type.
- /// </summary>
- /// <param name="predicate">
- /// A predicate for which object to find.
- /// </param>
- /// <returns>
- /// The object that matches the given predicate or null
- /// if the object is not found.
- /// </returns>
- public T Find<T> (Expression<Func<T, bool>> predicate,string tableName = "") where T : new()
- {
- return Table<T> (tableName).Where (predicate).FirstOrDefault ();
- }
- /// <summary>
- /// Attempts to retrieve the first object that matches the query from the table
- /// associated with the specified type.
- /// </summary>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// The object that matches the given predicate or null
- /// if the object is not found.
- /// </returns>
- public T FindWithQuery<T> (string query, params object[] args) where T : new()
- {
- return Query<T> (query, args).FirstOrDefault ();
- }
- /// <summary>
- /// Attempts to retrieve the first object that matches the query from the table
- /// associated with the specified type.
- /// </summary>
- /// <param name="map">
- /// The TableMapping used to identify the table.
- /// </param>
- /// <param name="query">
- /// The fully escaped SQL.
- /// </param>
- /// <param name="args">
- /// Arguments to substitute for the occurences of '?' in the query.
- /// </param>
- /// <returns>
- /// The object that matches the given predicate or null
- /// if the object is not found.
- /// </returns>
- public object FindWithQuery (TableMapping map, string query, params object[] args)
- {
- return Query (map, query, args).FirstOrDefault ();
- }
- /// <summary>
- /// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>.
- /// </summary>
- public bool IsInTransaction {
- get { return _transactionDepth > 0; }
- }
- /// <summary>
- /// Begins a new transaction. Call <see cref="Commit"/> to end the transaction.
- /// </summary>
- /// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example>
- public void BeginTransaction ()
- {
- // The BEGIN command only works if the transaction stack is empty,
- // or in other words if there are no pending transactions.
- // If the transaction stack is not empty when the BEGIN command is invoked,
- // then the command fails with an error.
- // Rather than crash with an error, we will just ignore calls to BeginTransaction
- // that would result in an error.
- if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) {
- try {
- Execute ("begin transaction");
- }
- catch (Exception ex) {
- var sqlExp = ex as SQLiteException;
- if (sqlExp != null) {
- // It is recommended that applications respond to the errors listed below
- // by explicitly issuing a ROLLBACK command.
- // TODO: This rollback failsafe should be localized to all throw sites.
- switch (sqlExp.Result) {
- case SQLite3.Result.IOError:
- case SQLite3.Result.Full:
- case SQLite3.Result.Busy:
- case SQLite3.Result.NoMem:
- case SQLite3.Result.Interrupt:
- RollbackTo (null, true);
- break;
- }
- }
- else {
- // Call decrement and not VolatileWrite in case we've already
- // created a transaction point in SaveTransactionPoint since the catch.
- Interlocked.Decrement (ref _transactionDepth);
- }
- throw;
- }
- }
- else {
- // Calling BeginTransaction on an already open transaction is invalid
- throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction.");
- }
- }
- /// <summary>
- /// Creates a savepoint in the database at the current point in the transaction timeline.
- /// Begins a new transaction if one is not in progress.
- ///
- /// Call <see cref="RollbackTo(string)"/> to undo transactions since the returned savepoint.
- /// Call <see cref="Release"/> to commit transactions after the savepoint returned here.
- /// Call <see cref="Commit"/> to end the transaction, committing all changes.
- /// </summary>
- /// <returns>A string naming the savepoint.</returns>
- public string SaveTransactionPoint ()
- {
- int depth = Interlocked.Increment (ref _transactionDepth) - 1;
- string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth;
- try {
- Execute ("savepoint " + retVal);
- }
- catch (Exception ex) {
- var sqlExp = ex as SQLiteException;
- if (sqlExp != null) {
- // It is recommended that applications respond to the errors listed below
- // by explicitly issuing a ROLLBACK command.
- // TODO: This rollback failsafe should be localized to all throw sites.
- switch (sqlExp.Result) {
- case SQLite3.Result.IOError:
- case SQLite3.Result.Full:
- case SQLite3.Result.Busy:
- case SQLite3.Result.NoMem:
- case SQLite3.Result.Interrupt:
- RollbackTo (null, true);
- break;
- }
- }
- else {
- Interlocked.Decrement (ref _transactionDepth);
- }
- throw;
- }
- return retVal;
- }
- /// <summary>
- /// Rolls back the transaction that was begun by <see cref="BeginTransaction"/> or <see cref="SaveTransactionPoint"/>.
- /// </summary>
- public void Rollback ()
- {
- RollbackTo (null, false);
- }
- /// <summary>
- /// Rolls back the savepoint created by <see cref="BeginTransaction"/> or SaveTransactionPoint.
- /// </summary>
- /// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
- public void RollbackTo (string savepoint)
- {
- RollbackTo (savepoint, false);
- }
- /// <summary>
- /// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>.
- /// </summary>
- /// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
- /// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param>
- void RollbackTo (string savepoint, bool noThrow)
- {
- // Rolling back without a TO clause rolls backs all transactions
- // and leaves the transaction stack empty.
- try {
- if (String.IsNullOrEmpty (savepoint)) {
- if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) {
- Execute ("rollback");
- }
- }
- else {
- DoSavePointExecute (savepoint, "rollback to ");
- }
- }
- catch (SQLiteException) {
- if (!noThrow)
- throw;
- }
- // No need to rollback if there are no transactions open.
- }
- /// <summary>
- /// Releases a savepoint returned from <see cref="SaveTransactionPoint"/>. Releasing a savepoint
- /// makes changes since that savepoint permanent if the savepoint began the transaction,
- /// or otherwise the changes are permanent pending a call to <see cref="Commit"/>.
- ///
- /// The RELEASE command is like a COMMIT for a SAVEPOINT.
- /// </summary>
- /// <param name="savepoint">The name of the savepoint to release. The string should be the result of a call to <see cref="SaveTransactionPoint"/></param>
- public void Release (string savepoint)
- {
- try {
- DoSavePointExecute (savepoint, "release ");
- }
- catch (SQLiteException ex) {
- if (ex.Result == SQLite3.Result.Busy) {
- // Force a rollback since most people don't know this function can fail
- // Don't call Rollback() since the _transactionDepth is 0 and it won't try
- // Calling rollback makes our _transactionDepth variable correct.
- // Writes to the database only happen at depth=0, so this failure will only happen then.
- try {
- Execute ("rollback");
- }
- catch {
- // rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
- }
- }
- throw;
- }
- }
- void DoSavePointExecute (string savepoint, string cmd)
- {
- // Validate the savepoint
- int firstLen = savepoint.IndexOf ('D');
- if (firstLen >= 2 && savepoint.Length > firstLen + 1) {
- int depth;
- if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) {
- // TODO: Mild race here, but inescapable without locking almost everywhere.
- if (0 <= depth && depth < _transactionDepth) {
- #if NETFX_CORE || USE_SQLITEPCL_RAW || NETCORE
- Volatile.Write (ref _transactionDepth, depth);
- #elif SILVERLIGHT
- _transactionDepth = depth;
- #else
- Thread.VolatileWrite (ref _transactionDepth, depth);
- #endif
- Execute (cmd + savepoint);
- return;
- }
- }
- }
- throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint");
- }
- /// <summary>
- /// Commits the transaction that was begun by <see cref="BeginTransaction"/>.
- /// </summary>
- public void Commit ()
- {
- if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) {
- try {
- Execute ("commit");
- }
- catch {
- // Force a rollback since most people don't know this function can fail
- // Don't call Rollback() since the _transactionDepth is 0 and it won't try
- // Calling rollback makes our _transactionDepth variable correct.
- try {
- Execute ("rollback");
- }
- catch {
- // rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
- }
- throw;
- }
- }
- // Do nothing on a commit with no open transaction
- }
- /// <summary>
- /// Executes <paramref name="action"/> within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an
- /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception
- /// is rethrown.
- /// </summary>
- /// <param name="action">
- /// The <see cref="Action"/> to perform within a transaction. <paramref name="action"/> can contain any number
- /// of operations on the connection but should never call <see cref="BeginTransaction"/> or
- /// <see cref="Commit"/>.
- /// </param>
- public void RunInTransaction (Action action)
- {
- try {
- var savePoint = SaveTransactionPoint ();
- action ();
- Release (savePoint);
- }
- catch (Exception) {
- Rollback ();
- throw;
- }
- }
- /// <summary>
- /// Inserts all specified objects.
- /// </summary>
- /// <param name="objects">
- /// An <see cref="IEnumerable"/> of the objects to insert.
- /// <param name="runInTransaction"/>
- /// A boolean indicating if the inserts should be wrapped in a transaction.
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int InsertAll (System.Collections.IEnumerable objects, bool runInTransaction = true,string tableName = "")
- {
- var c = 0;
- if (runInTransaction) {
- RunInTransaction (() => {
- foreach (var r in objects) {
- c += Insert (r,tableName:tableName);
- }
- });
- }
- else {
- foreach (var r in objects) {
- c += Insert (r,tableName:tableName);
- }
- }
- return c;
- }
- /// <summary>
- /// Inserts all specified objects.
- /// </summary>
- /// <param name="objects">
- /// An <see cref="IEnumerable"/> of the objects to insert.
- /// </param>
- /// <param name="extra">
- /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
- /// </param>
- /// <param name="runInTransaction">
- /// A boolean indicating if the inserts should be wrapped in a transaction.
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int InsertAll (System.Collections.IEnumerable objects, string extra, bool runInTransaction = true,string tableName = "")
- {
- var c = 0;
- if (runInTransaction) {
- RunInTransaction (() => {
- foreach (var r in objects) {
- c += Insert (r, extra,tableName:tableName);
- }
- });
- }
- else {
- foreach (var r in objects) {
- c += Insert (r, extra,tableName:tableName);
- }
- }
- return c;
- }
- /// <summary>
- /// Inserts all specified objects.
- /// </summary>
- /// <param name="objects">
- /// An <see cref="IEnumerable"/> of the objects to insert.
- /// </param>
- /// <param name="objType">
- /// The type of object to insert.
- /// </param>
- /// <param name="runInTransaction">
- /// A boolean indicating if the inserts should be wrapped in a transaction.
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int InsertAll (System.Collections.IEnumerable objects, Type objType, bool runInTransaction = true,string tableName = "")
- {
- var c = 0;
- if (runInTransaction) {
- RunInTransaction (() => {
- foreach (var r in objects) {
- c += Insert (r, objType,tableName:tableName);
- }
- });
- }
- else {
- foreach (var r in objects) {
- c += Insert (r, objType,tableName:tableName);
- }
- }
- return c;
- }
- /// <summary>
- /// Inserts the given object (and updates its
- /// auto incremented primary key if it has one).
- /// The return value is the number of rows added to the table.
- /// </summary>
- /// <param name="obj">
- /// The object to insert.
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int Insert (object obj,string tableName = "")
- {
- if (obj == null) {
- return 0;
- }
- return Insert (obj, "", Orm.GetType (obj),tableName:tableName);
- }
- /// <summary>
- /// Inserts the given object (and updates its
- /// auto incremented primary key if it has one).
- /// The return value is the number of rows added to the table.
- /// If a UNIQUE constraint violation occurs with
- /// some pre-existing object, this function deletes
- /// the old object.
- /// </summary>
- /// <param name="obj">
- /// The object to insert.
- /// </param>
- /// <returns>
- /// The number of rows modified.
- /// </returns>
- public int InsertOrReplace (object obj,string tableName = "")
- {
- if (obj == null) {
- return 0;
- }
- return Insert (obj, "OR REPLACE", Orm.GetType (obj),tableName:tableName);
- }
- /// <summary>
- /// Inserts the given object (and updates its
- /// auto incremented primary key if it has one).
- /// The return value is the number of rows added to the table.
- /// </summary>
- /// <param name="obj">
- /// The object to insert.
- /// </param>
- /// <param name="objType">
- /// The type of object to insert.
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int Insert (object obj, Type objType,string tableName = "")
- {
- return Insert (obj, "", objType,tableName:tableName);
- }
- /// <summary>
- /// Inserts the given object (and updates its
- /// auto incremented primary key if it has one).
- /// The return value is the number of rows added to the table.
- /// If a UNIQUE constraint violation occurs with
- /// some pre-existing object, this function deletes
- /// the old object.
- /// </summary>
- /// <param name="obj">
- /// The object to insert.
- /// </param>
- /// <param name="objType">
- /// The type of object to insert.
- /// </param>
- /// <returns>
- /// The number of rows modified.
- /// </returns>
- public int InsertOrReplace (object obj, Type objType,string tableName = "")
- {
- return Insert (obj, "OR REPLACE", objType,tableName:tableName);
- }
- /// <summary>
- /// Inserts the given object (and updates its
- /// auto incremented primary key if it has one).
- /// The return value is the number of rows added to the table.
- /// </summary>
- /// <param name="obj">
- /// The object to insert.
- /// </param>
- /// <param name="extra">
- /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int Insert (object obj, string extra,string tableName = "")
- {
- if (obj == null) {
- return 0;
- }
- return Insert (obj, extra, Orm.GetType (obj),tableName:tableName);
- }
- /// <summary>
- /// Inserts the given object (and updates its
- /// auto incremented primary key if it has one).
- /// The return value is the number of rows added to the table.
- /// </summary>
- /// <param name="obj">
- /// The object to insert.
- /// </param>
- /// <param name="extra">
- /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
- /// </param>
- /// <param name="objType">
- /// The type of object to insert.
- /// </param>
- /// <returns>
- /// The number of rows added to the table.
- /// </returns>
- public int Insert (object obj, string extra, Type objType,string tableName = "")
- {
- if (obj == null || objType == null) {
- return 0;
- }
- var map = GetMapping (objType,tableName:tableName);
- if (map.PK != null && map.PK.IsAutoGuid) {
- if (map.PK.GetValue (obj).Equals (Guid.Empty)) {
- map.PK.SetValue (obj, Guid.NewGuid ());
- }
- }
- var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
- var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns;
- var vals = new object[cols.Length];
- for (var i = 0; i < vals.Length; i++) {
- vals[i] = cols[i].GetValue (obj);
- }
- var insertCmd = GetInsertCommand (map, extra);
- int count;
- lock (insertCmd) {
- // We lock here to protect the prepared statement returned via GetInsertCommand.
- // A SQLite prepared statement can be bound for only one operation at a time.
- try {
- count = insertCmd.ExecuteNonQuery (vals);
- }
- catch (SQLiteException ex) {
- if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
- throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj);
- }
- throw;
- }
- if (map.HasAutoIncPK) {
- var id = SQLite3.LastInsertRowid (Handle);
- map.SetAutoIncPK (obj, id);
- }
- }
- if (count > 0)
- OnTableChanged (map, NotifyTableChangedAction.Insert);
- return count;
- }
- readonly Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> _insertCommandMap = new Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> ();
- PreparedSqlLiteInsertCommand GetInsertCommand (TableMapping map, string extra)
- {
- PreparedSqlLiteInsertCommand prepCmd;
- var key = Tuple.Create (map.TableName, extra);
- lock (_insertCommandMap) {
- if (_insertCommandMap.TryGetValue (key, out prepCmd)) {
- return prepCmd;
- }
- }
- prepCmd = CreateInsertCommand (map, extra);
- lock (_insertCommandMap) {
- if (_insertCommandMap.TryGetValue (key, out var existing)) {
- prepCmd.Dispose ();
- return existing;
- }
- _insertCommandMap.Add (key, prepCmd);
- }
- return prepCmd;
- }
- PreparedSqlLiteInsertCommand CreateInsertCommand (TableMapping map, string extra)
- {
- var cols = map.InsertColumns;
- string insertSql;
- if (cols.Length == 0 && map.Columns.Length == 1 && map.Columns[0].IsAutoInc) {
- insertSql = string.Format ("insert {1} into \"{0}\" default values", map.TableName, extra);
- }
- else {
- var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
- if (replacing) {
- cols = map.InsertOrReplaceColumns;
- }
- insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", map.TableName,
- string.Join (",", (from c in cols
- select "\"" + c.Name + "\"").ToArray ()),
- string.Join (",", (from c in cols
- select "?").ToArray ()), extra);
- }
- var insertCommand = new PreparedSqlLiteInsertCommand (this, insertSql);
- return insertCommand;
- }
- /// <summary>
- /// Updates all of the columns of a table using the specified object
- /// except for its primary key.
- /// The object is required to have a primary key.
- /// </summary>
- /// <param name="obj">
- /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
- /// </param>
- /// <returns>
- /// The number of rows updated.
- /// </returns>
- public int Update (object obj,string tableName = "")
- {
- if (obj == null) {
- return 0;
- }
- return Update (obj, Orm.GetType (obj),tableName:tableName);
- }
- /// <summary>
- /// Updates all of the columns of a table using the specified object
- /// except for its primary key.
- /// The object is required to have a primary key.
- /// </summary>
- /// <param name="obj">
- /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
- /// </param>
- /// <param name="objType">
- /// The type of object to insert.
- /// </param>
- /// <returns>
- /// The number of rows updated.
- /// </returns>
- public int Update (object obj, Type objType,string tableName = "")
- {
- int rowsAffected = 0;
- if (obj == null || objType == null) {
- return 0;
- }
- var map = GetMapping (objType,tableName:tableName);
- var pk = map.PK;
- if (pk == null) {
- throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK");
- }
- var cols = from p in map.Columns
- where p != pk
- select p;
- var vals = from c in cols
- select c.GetValue (obj);
- var ps = new List<object> (vals);
- if (ps.Count == 0) {
- // There is a PK but no accompanying data,
- // so reset the PK to make the UPDATE work.
- cols = map.Columns;
- vals = from c in cols
- select c.GetValue (obj);
- ps = new List<object> (vals);
- }
- ps.Add (pk.GetValue (obj));
- var q = string.Format ("update \"{0}\" set {1} where \"{2}\" = ? ", map.TableName, string.Join (",", (from c in cols
- select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name);
- try {
- rowsAffected = Execute (q, ps.ToArray ());
- }
- catch (SQLiteException ex) {
- if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
- throw NotNullConstraintViolationException.New (ex, map, obj);
- }
- throw;
- }
- if (rowsAffected > 0)
- OnTableChanged (map, NotifyTableChangedAction.Update);
- return rowsAffected;
- }
- /// <summary>
- /// Updates all specified objects.
- /// </summary>
- /// <param name="objects">
- /// An <see cref="IEnumerable"/> of the objects to insert.
- /// </param>
- /// <param name="runInTransaction">
- /// A boolean indicating if the inserts should be wrapped in a transaction
- /// </param>
- /// <returns>
- /// The number of rows modified.
- /// </returns>
- public int UpdateAll (System.Collections.IEnumerable objects, bool runInTransaction = true,string tableName = "")
- {
- var c = 0;
- if (runInTransaction) {
- RunInTransaction (() => {
- foreach (var r in objects) {
- c += Update (r,tableName:tableName);
- }
- });
- }
- else {
- foreach (var r in objects) {
- c += Update (r,tableName:tableName);
- }
- }
- return c;
- }
- /// <summary>
- /// Deletes the given object from the database using its primary key.
- /// </summary>
- /// <param name="objectToDelete">
- /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute.
- /// </param>
- /// <returns>
- /// The number of rows deleted.
- /// </returns>
- public int Delete (object objectToDelete,string tableName = "")
- {
- var map = GetMapping (Orm.GetType (objectToDelete),tableName:tableName);
- var pk = map.PK;
- if (pk == null) {
- throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
- }
- var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
- var count = Execute (q, pk.GetValue (objectToDelete));
- if (count > 0)
- OnTableChanged (map, NotifyTableChangedAction.Delete);
- return count;
- }
- /// <summary>
- /// Deletes the object with the specified primary key.
- /// </summary>
- /// <param name="primaryKey">
- /// The primary key of the object to delete.
- /// </param>
- /// <returns>
- /// The number of objects deleted.
- /// </returns>
- /// <typeparam name='T'>
- /// The type of object.
- /// </typeparam>
- public int Delete<T> (object primaryKey,string tableName = "")
- {
- return Delete (primaryKey, GetMapping (typeof (T),tableName:tableName));
- }
- /// <summary>
- /// Deletes the object with the specified primary key.
- /// </summary>
- /// <param name="primaryKey">
- /// The primary key of the object to delete.
- /// </param>
- /// <param name="map">
- /// The TableMapping used to identify the table.
- /// </param>
- /// <returns>
- /// The number of objects deleted.
- /// </returns>
- public int Delete (object primaryKey, TableMapping map)
- {
- var pk = map.PK;
- if (pk == null) {
- throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
- }
- var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
- var count = Execute (q, primaryKey);
- if (count > 0)
- OnTableChanged (map, NotifyTableChangedAction.Delete);
- return count;
- }
- /// <summary>
- /// Deletes all the objects from the specified table.
- /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
- /// specified table. Do you really want to do that?
- /// </summary>
- /// <returns>
- /// The number of objects deleted.
- /// </returns>
- /// <typeparam name='T'>
- /// The type of objects to delete.
- /// </typeparam>
- public int DeleteAll<T> (string tableName = "")
- {
- var map = GetMapping(typeof(T), tableName: tableName);
- return DeleteAll (map);
- }
- /// <summary>
- /// Deletes all the objects from the specified table.
- /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
- /// specified table. Do you really want to do that?
- /// </summary>
- /// <param name="map">
- /// The TableMapping used to identify the table.
- /// </param>
- /// <returns>
- /// The number of objects deleted.
- /// </returns>
- public int DeleteAll (TableMapping map)
- {
- var query = string.Format ("delete from \"{0}\"", map.TableName);
- var count = Execute (query);
- if (count > 0)
- OnTableChanged (map, NotifyTableChangedAction.Delete);
- return count;
- }
- /// <summary>
- /// Backup the entire database to the specified path.
- /// </summary>
- /// <param name="destinationDatabasePath">Path to backup file.</param>
- /// <param name="databaseName">The name of the database to backup (usually "main").</param>
- public void Backup (string destinationDatabasePath, string databaseName = "main")
- {
- // Open the destination
- var r = SQLite3.Open (destinationDatabasePath, out var destHandle);
- if (r != SQLite3.Result.OK) {
- throw SQLiteException.New (r, "Failed to open destination database");
- }
- // Init the backup
- var backup = SQLite3.BackupInit (destHandle, databaseName, Handle, databaseName);
- if (backup == NullBackupHandle) {
- SQLite3.Close (destHandle);
- throw new Exception ("Failed to create backup");
- }
- // Perform it
- SQLite3.BackupStep (backup, -1);
- SQLite3.BackupFinish (backup);
- // Check for errors
- r = SQLite3.GetResult (destHandle);
- string msg = "";
- if (r != SQLite3.Result.OK) {
- msg = SQLite3.GetErrmsg (destHandle);
- }
- // Close everything and report errors
- SQLite3.Close (destHandle);
- if (r != SQLite3.Result.OK) {
- throw SQLiteException.New (r, msg);
- }
- }
- ~SQLiteConnection ()
- {
- Dispose (false);
- }
- public void Dispose ()
- {
- Dispose (true);
- GC.SuppressFinalize (this);
- }
- public void Close ()
- {
- Dispose (true);
- }
- protected virtual void Dispose (bool disposing)
- {
- var useClose2 = LibVersionNumber >= 3007014;
- if (_open && Handle != NullHandle) {
- try {
- if (disposing) {
- lock (_insertCommandMap) {
- foreach (var sqlInsertCommand in _insertCommandMap.Values) {
- sqlInsertCommand.Dispose ();
- }
- _insertCommandMap.Clear ();
- }
- var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
- if (r != SQLite3.Result.OK) {
- string msg = SQLite3.GetErrmsg (Handle);
- throw SQLiteException.New (r, msg);
- }
- }
- else {
- var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
- }
- }
- finally {
- Handle = NullHandle;
- _open = false;
- }
- }
- }
- void OnTableChanged (TableMapping table, NotifyTableChangedAction action)
- {
- var ev = TableChanged;
- if (ev != null)
- ev (this, new NotifyTableChangedEventArgs (table, action));
- }
- public event EventHandler<NotifyTableChangedEventArgs> TableChanged;
- }
- public class NotifyTableChangedEventArgs : EventArgs
- {
- public TableMapping Table { get; private set; }
- public NotifyTableChangedAction Action { get; private set; }
- public NotifyTableChangedEventArgs (TableMapping table, NotifyTableChangedAction action)
- {
- Table = table;
- Action = action;
- }
- }
- public enum NotifyTableChangedAction
- {
- Insert,
- Update,
- Delete,
- }
- /// <summary>
- /// Represents a parsed connection string.
- /// </summary>
- public class SQLiteConnectionString
- {
- const string DateTimeSqliteDefaultFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff";
- public string UniqueKey { get; }
- public string DatabasePath { get; }
- public bool StoreDateTimeAsTicks { get; }
- public bool StoreTimeSpanAsTicks { get; }
- public string DateTimeStringFormat { get; }
- public System.Globalization.DateTimeStyles DateTimeStyle { get; }
- public object Key { get; }
- public SQLiteOpenFlags OpenFlags { get; }
- public Action<SQLiteConnection> PreKeyAction { get; }
- public Action<SQLiteConnection> PostKeyAction { get; }
- public string VfsName { get; }
- #if NETFX_CORE
- static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
- public static readonly string[] InMemoryDbPaths = new[]
- {
- ":memory:",
- "file::memory:"
- };
- public static bool IsInMemoryPath(string databasePath)
- {
- return InMemoryDbPaths.Any(i => i.Equals(databasePath, StringComparison.OrdinalIgnoreCase));
- }
- #endif
- /// <summary>
- /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
- /// </summary>
- /// <param name="databasePath">
- /// Specifies the path to the database file.
- /// </param>
- /// <param name="storeDateTimeAsTicks">
- /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
- /// absolutely do want to store them as Ticks in all new projects. The value of false is
- /// only here for backwards compatibility. There is a *significant* speed advantage, with no
- /// down sides, when setting storeDateTimeAsTicks = true.
- /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
- /// the storeDateTimeAsTicks parameter.
- /// </param>
- public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks = true)
- : this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks)
- {
- }
- /// <summary>
- /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
- /// </summary>
- /// <param name="databasePath">
- /// Specifies the path to the database file.
- /// </param>
- /// <param name="storeDateTimeAsTicks">
- /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
- /// absolutely do want to store them as Ticks in all new projects. The value of false is
- /// only here for backwards compatibility. There is a *significant* speed advantage, with no
- /// down sides, when setting storeDateTimeAsTicks = true.
- /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
- /// the storeDateTimeAsTicks parameter.
- /// </param>
- /// <param name="key">
- /// Specifies the encryption key to use on the database. Should be a string or a byte[].
- /// </param>
- /// <param name="preKeyAction">
- /// Executes prior to setting key for SQLCipher databases
- /// </param>
- /// <param name="postKeyAction">
- /// Executes after setting key for SQLCipher databases
- /// </param>
- /// <param name="vfsName">
- /// Specifies the Virtual File System to use on the database.
- /// </param>
- public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null)
- : this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks, key, preKeyAction, postKeyAction, vfsName)
- {
- }
- /// <summary>
- /// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
- /// </summary>
- /// <param name="databasePath">
- /// Specifies the path to the database file.
- /// </param>
- /// <param name="openFlags">
- /// Flags controlling how the connection should be opened.
- /// </param>
- /// <param name="storeDateTimeAsTicks">
- /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
- /// absolutely do want to store them as Ticks in all new projects. The value of false is
- /// only here for backwards compatibility. There is a *significant* speed advantage, with no
- /// down sides, when setting storeDateTimeAsTicks = true.
- /// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
- /// the storeDateTimeAsTicks parameter.
- /// </param>
- /// <param name="key">
- /// Specifies the encryption key to use on the database. Should be a string or a byte[].
- /// </param>
- /// <param name="preKeyAction">
- /// Executes prior to setting key for SQLCipher databases
- /// </param>
- /// <param name="postKeyAction">
- /// Executes after setting key for SQLCipher databases
- /// </param>
- /// <param name="vfsName">
- /// Specifies the Virtual File System to use on the database.
- /// </param>
- /// <param name="dateTimeStringFormat">
- /// Specifies the format to use when storing DateTime properties as strings.
- /// </param>
- /// <param name="storeTimeSpanAsTicks">
- /// Specifies whether to store TimeSpan properties as ticks (true) or strings (false). You
- /// absolutely do want to store them as Ticks in all new projects. The value of false is
- /// only here for backwards compatibility. There is a *significant* speed advantage, with no
- /// down sides, when setting storeTimeSpanAsTicks = true.
- /// </param>
- public SQLiteConnectionString (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null, string dateTimeStringFormat = DateTimeSqliteDefaultFormat, bool storeTimeSpanAsTicks = true)
- {
- if (key != null && !((key is byte[]) || (key is string)))
- throw new ArgumentException ("Encryption keys must be strings or byte arrays", nameof (key));
- UniqueKey = string.Format ("{0}_{1:X8}", databasePath, (uint)openFlags);
- StoreDateTimeAsTicks = storeDateTimeAsTicks;
- StoreTimeSpanAsTicks = storeTimeSpanAsTicks;
- DateTimeStringFormat = dateTimeStringFormat;
- DateTimeStyle = "o".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) || "r".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) ? System.Globalization.DateTimeStyles.RoundtripKind : System.Globalization.DateTimeStyles.None;
- Key = key;
- PreKeyAction = preKeyAction;
- PostKeyAction = postKeyAction;
- OpenFlags = openFlags;
- VfsName = vfsName;
- #if NETFX_CORE
- DatabasePath = IsInMemoryPath(databasePath)
- ? databasePath
- : System.IO.Path.Combine(MetroStyleDataPath, databasePath);
- #else
- DatabasePath = databasePath;
- #endif
- }
- }
- [AttributeUsage (AttributeTargets.Class)]
- public class TableAttribute : Attribute
- {
- public string Name { get; set; }
- /// <summary>
- /// Flag whether to create the table without rowid (see https://sqlite.org/withoutrowid.html)
- ///
- /// The default is <c>false</c> so that sqlite adds an implicit <c>rowid</c> to every table created.
- /// </summary>
- public bool WithoutRowId { get; set; }
- public TableAttribute (string name)
- {
- Name = name;
- }
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class ColumnAttribute : Attribute
- {
- public string Name { get; set; }
- public ColumnAttribute (string name)
- {
- Name = name;
- }
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class PrimaryKeyAttribute : Attribute
- {
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class AutoIncrementAttribute : Attribute
- {
- }
- [AttributeUsage (AttributeTargets.Property, AllowMultiple = true)]
- public class IndexedAttribute : Attribute
- {
- public string Name { get; set; }
- public int Order { get; set; }
- public virtual bool Unique { get; set; }
- public IndexedAttribute ()
- {
- }
- public IndexedAttribute (string name, int order)
- {
- Name = name;
- Order = order;
- }
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class IgnoreAttribute : Attribute
- {
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class UniqueAttribute : IndexedAttribute
- {
- public override bool Unique {
- get { return true; }
- set { /* throw? */ }
- }
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class MaxLengthAttribute : Attribute
- {
- public int Value { get; private set; }
- public MaxLengthAttribute (int length)
- {
- Value = length;
- }
- }
- public sealed class PreserveAttribute : System.Attribute
- {
- public bool AllMembers;
- public bool Conditional;
- }
- /// <summary>
- /// Select the collating sequence to use on a column.
- /// "BINARY", "NOCASE", and "RTRIM" are supported.
- /// "BINARY" is the default.
- /// </summary>
- [AttributeUsage (AttributeTargets.Property)]
- public class CollationAttribute : Attribute
- {
- public string Value { get; private set; }
- public CollationAttribute (string collation)
- {
- Value = collation;
- }
- }
- [AttributeUsage (AttributeTargets.Property)]
- public class NotNullAttribute : Attribute
- {
- }
- [AttributeUsage (AttributeTargets.Enum)]
- public class StoreAsTextAttribute : Attribute
- {
- }
- public class TableMapping
- {
- public Type MappedType { get; private set; }
- public string TableName { get; private set; }
- public bool WithoutRowId { get; private set; }
- public Column[] Columns { get; private set; }
- public Column PK { get; private set; }
- public string GetByPrimaryKeySql { get; private set; }
- public CreateFlags CreateFlags { get; private set; }
- internal MapMethod Method { get; private set; } = MapMethod.ByName;
- readonly Column _autoPk;
- readonly Column[] _insertColumns;
- readonly Column[] _insertOrReplaceColumns;
- public TableMapping (Type type, CreateFlags createFlags = CreateFlags.None,string tableName = "")
- {
- MappedType = type;
- CreateFlags = createFlags;
- var typeInfo = type.GetTypeInfo ();
- #if ENABLE_IL2CPP
- var tableAttr = typeInfo.GetCustomAttribute<TableAttribute> ();
- #else
- var tableAttr =
- typeInfo.CustomAttributes
- .Where (x => x.AttributeType == typeof (TableAttribute))
- .Select (x => (TableAttribute)Orm.InflateAttribute (x))
- .FirstOrDefault ();
- #endif
- TableName = string.IsNullOrEmpty(tableName)? ((tableAttr != null && !string.IsNullOrEmpty (tableAttr.Name)) ? tableAttr.Name : MappedType.Name):tableName;
- WithoutRowId = tableAttr != null ? tableAttr.WithoutRowId : false;
- var members = GetPublicMembers(type);
- var cols = new List<Column>(members.Count);
- foreach(var m in members)
- {
- var ignore = m.IsDefined(typeof(IgnoreAttribute), true);
- if(!ignore)
- cols.Add(new Column(m, createFlags));
- }
- Columns = cols.ToArray ();
- foreach (var c in Columns) {
- if (c.IsAutoInc && c.IsPK) {
- _autoPk = c;
- }
- if (c.IsPK) {
- PK = c;
- }
- }
- HasAutoIncPK = _autoPk != null;
- if (PK != null) {
- GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
- }
- else {
- // People should not be calling Get/Find without a PK
- GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName);
- }
- _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray ();
- _insertOrReplaceColumns = Columns.ToArray ();
- }
- private readonly List<Type> SupportTypes = new List<Type>()
- {
- typeof(bool),
- typeof(byte),
- typeof(UInt16),
- typeof(UInt32),
- typeof(UInt64),
- typeof(sbyte),
- typeof(Int16),
- typeof(Int32),
- typeof(Int64),
- typeof(float),
- typeof(double),
- typeof(decimal),
- typeof(string),
- typeof(StringBuilder),
- typeof(Uri),
- typeof(UriBuilder),
- typeof(DateTime),
- typeof(DateTimeOffset),
- typeof(TimeSpan),
- typeof(Guid),
- typeof(byte[]),
- };
- private IReadOnlyCollection<MemberInfo> GetPublicMembers(Type type)
- {
- if(type.Name.StartsWith("ValueTuple`"))
- return GetFieldsFromValueTuple(type);
- var members = new List<MemberInfo>();
- var memberNames = new HashSet<string>();
- var newMembers = new List<MemberInfo>();
- do
- {
- var ti = type.GetTypeInfo();
- newMembers.Clear();
- newMembers.AddRange(
- from p in ti.DeclaredProperties
- where !memberNames.Contains(p.Name) &&
- p.CanRead && p.CanWrite &&
- p.GetMethod != null && p.SetMethod != null &&
- p.GetMethod.IsPublic && p.SetMethod.IsPublic &&
- !p.GetMethod.IsStatic && !p.SetMethod.IsStatic
- &&(p.PropertyType.IsEnum || (!p.PropertyType.IsEnum && SupportTypes.Contains(p.PropertyType)))
- select p);
- newMembers.AddRange(
- from p in ti.DeclaredFields
- where !memberNames.Contains(p.Name) &&
- !p.IsInitOnly && p.IsPublic && !p.IsStatic
- &&(p.FieldType.IsEnum || (!p.FieldType.IsEnum && SupportTypes.Contains(p.FieldType)))
- select p);
- members.AddRange(newMembers);
- foreach(var m in newMembers)
- memberNames.Add(m.Name);
- type = ti.BaseType;
- }
- while(type != typeof(object));
- return members;
- }
- private IReadOnlyCollection<MemberInfo> GetFieldsFromValueTuple(Type type)
- {
- Method = MapMethod.ByPosition;
- var fields = type.GetFields();
- // https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest
- if(fields.Length >= 8)
- throw new NotSupportedException("ValueTuple with more than 7 members not supported due to nesting; see https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest");
- return fields;
- }
- public bool HasAutoIncPK { get; private set; }
- public void SetAutoIncPK (object obj, long id)
- {
- if (_autoPk != null) {
- _autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null));
- }
- }
- public Column[] InsertColumns {
- get {
- return _insertColumns;
- }
- }
- public Column[] InsertOrReplaceColumns {
- get {
- return _insertOrReplaceColumns;
- }
- }
- public Column FindColumnWithPropertyName (string propertyName)
- {
- var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName);
- return exact;
- }
- public Column FindColumn (string columnName)
- {
- if(Method != MapMethod.ByName)
- throw new InvalidOperationException($"This {nameof(TableMapping)} is not mapped by name, but {Method}.");
- var exact = Columns.FirstOrDefault (c => c.Name.ToLower () == columnName.ToLower ());
- return exact;
- }
- public class Column
- {
- MemberInfo _member;
- public string Name { get; private set; }
- public PropertyInfo PropertyInfo => _member.MemberType == MemberTypes.Property ? _member as PropertyInfo :null;
- public FieldInfo FieldInfo => _member.MemberType == MemberTypes.Field ? _member as FieldInfo:null;
- public bool IsProperty => _member.MemberType == MemberTypes.Property;
- public string PropertyName { get { return _member.Name; } }
- public Type ColumnType { get; private set; }
- public string Collation { get; private set; }
- public bool IsAutoInc { get; private set; }
- public bool IsAutoGuid { get; private set; }
- public bool IsPK { get; private set; }
- public IEnumerable<IndexedAttribute> Indices { get; set; }
- public bool IsNullable { get; private set; }
- public int? MaxStringLength { get; private set; }
- public bool StoreAsText { get; private set; }
- public Column (MemberInfo member, CreateFlags createFlags = CreateFlags.None)
- {
- _member = member;
- var memberType = GetMemberType(member);
- var colAttr = member.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (ColumnAttribute));
- #if ENABLE_IL2CPP
- var ca = member.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
- Name = ca == null ? member.Name : ca.Name;
- #else
- Name = (colAttr != null && colAttr.ConstructorArguments.Count > 0) ?
- colAttr.ConstructorArguments[0].Value?.ToString () :
- member.Name;
- #endif
- //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
- ColumnType = Nullable.GetUnderlyingType (memberType) ?? memberType;
- Collation = Orm.Collation (member);
- IsPK = Orm.IsPK (member) ||
- (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
- string.Compare (member.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);
- var isAuto = Orm.IsAutoInc (member) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));
- IsAutoGuid = isAuto && ColumnType == typeof (Guid);
- IsAutoInc = isAuto && !IsAutoGuid;
- Indices = Orm.GetIndices (member);
- if (!Indices.Any ()
- && !IsPK
- && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex)
- && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
- ) {
- Indices = new IndexedAttribute[] { new IndexedAttribute () };
- }
- IsNullable = !(IsPK || Orm.IsMarkedNotNull (member));
- MaxStringLength = Orm.MaxStringLength (member);
- StoreAsText = memberType.GetTypeInfo ().CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
- }
- public Column (PropertyInfo member, CreateFlags createFlags = CreateFlags.None)
- : this((MemberInfo)member, createFlags)
- { }
- public void SetValue (object obj, object val)
- {
- if(_member is PropertyInfo propy)
- {
- if (val != null && ColumnType.GetTypeInfo ().IsEnum)
- propy.SetValue (obj, Enum.ToObject (ColumnType, val));
- else
- propy.SetValue (obj, val);
- }
- else if(_member is FieldInfo field)
- {
- if (val != null && ColumnType.GetTypeInfo ().IsEnum)
- field.SetValue (obj, Enum.ToObject (ColumnType, val));
- else
- field.SetValue (obj, val);
- }
- else
- throw new InvalidProgramException("unreachable condition");
- }
- public object GetValue (object obj)
- {
- if(_member is PropertyInfo propy)
- return propy.GetValue(obj);
- else if(_member is FieldInfo field)
- return field.GetValue(obj);
- else
- throw new InvalidProgramException("unreachable condition");
- }
- private static Type GetMemberType(MemberInfo m)
- {
- switch(m.MemberType)
- {
- case MemberTypes.Property: return ((PropertyInfo)m).PropertyType;
- case MemberTypes.Field: return ((FieldInfo)m).FieldType;
- default: throw new InvalidProgramException($"{nameof(TableMapping)} supports properties or fields only.");
- }
- }
- }
- internal enum MapMethod
- {
- ByName,
- ByPosition
- }
- }
- class EnumCacheInfo
- {
- public EnumCacheInfo (Type type)
- {
- var typeInfo = type.GetTypeInfo ();
- IsEnum = typeInfo.IsEnum;
- if (IsEnum) {
- StoreAsText = typeInfo.CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
- if (StoreAsText) {
- EnumValues = new Dictionary<int, string> ();
- foreach (object e in Enum.GetValues (type)) {
- EnumValues[Convert.ToInt32 (e)] = e.ToString ();
- }
- }
- }
- }
- public bool IsEnum { get; private set; }
- public bool StoreAsText { get; private set; }
- public Dictionary<int, string> EnumValues { get; private set; }
- }
- static class EnumCache
- {
- static readonly Dictionary<Type, EnumCacheInfo> Cache = new Dictionary<Type, EnumCacheInfo> ();
- public static EnumCacheInfo GetInfo<T> ()
- {
- return GetInfo (typeof (T));
- }
- public static EnumCacheInfo GetInfo (Type type)
- {
- lock (Cache) {
- EnumCacheInfo info = null;
- if (!Cache.TryGetValue (type, out info)) {
- info = new EnumCacheInfo (type);
- Cache[type] = info;
- }
- return info;
- }
- }
- }
- public static class Orm
- {
- public const int DefaultMaxStringLength = 140;
- public const string ImplicitPkName = "Id";
- public const string ImplicitIndexSuffix = "Id";
- public static Type GetType (object obj)
- {
- if (obj == null)
- return typeof (object);
- var rt = obj as IReflectableType;
- if (rt != null)
- return rt.GetTypeInfo ().AsType ();
- return obj.GetType ();
- }
- public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
- {
- string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks, storeTimeSpanAsTicks) + " ";
- if (p.IsPK) {
- decl += "primary key ";
- }
- if (p.IsAutoInc) {
- decl += "autoincrement ";
- }
- if (!p.IsNullable) {
- decl += "not null ";
- }
- if (!string.IsNullOrEmpty (p.Collation)) {
- decl += "collate " + p.Collation + " ";
- }
- return decl;
- }
- public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
- {
- var clrType = p.ColumnType;
- if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32) || clrType == typeof (UInt32) || clrType == typeof (Int64) || clrType == typeof (UInt64)) {
- return "integer";
- }
- else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) {
- return "float";
- }
- else if (clrType == typeof (String) || clrType == typeof (StringBuilder) || clrType == typeof (Uri) || clrType == typeof (UriBuilder)) {
- int? len = p.MaxStringLength;
- if (len.HasValue)
- return "varchar(" + len.Value + ")";
- return "varchar";
- }
- else if (clrType == typeof (TimeSpan)) {
- return storeTimeSpanAsTicks ? "bigint" : "time";
- }
- else if (clrType == typeof (DateTime)) {
- return storeDateTimeAsTicks ? "bigint" : "datetime";
- }
- else if (clrType == typeof (DateTimeOffset)) {
- return "bigint";
- }
- else if (clrType.GetTypeInfo ().IsEnum) {
- if (p.StoreAsText)
- return "varchar";
- else
- return "integer";
- }
- else if (clrType == typeof (byte[])) {
- return "blob";
- }
- else if (clrType == typeof (Guid)) {
- return "varchar(36)";
- }
- else {
- throw new NotSupportedException ("Don't know about " + clrType);
- }
- }
- public static bool IsPK (MemberInfo p)
- {
- return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute));
- }
- public static string Collation (MemberInfo p)
- {
- #if ENABLE_IL2CPP
- return (p.GetCustomAttribute<CollationAttribute> ()?.Value) ?? "";
- #else
- return
- (p.CustomAttributes
- .Where (x => typeof (CollationAttribute) == x.AttributeType)
- .Select (x => {
- var args = x.ConstructorArguments;
- return args.Count > 0 ? ((args[0].Value as string) ?? "") : "";
- })
- .FirstOrDefault ()) ?? "";
- #endif
- }
- public static bool IsAutoInc (MemberInfo p)
- {
- return p.CustomAttributes.Any (x => x.AttributeType == typeof (AutoIncrementAttribute));
- }
- public static FieldInfo GetField (TypeInfo t, string name)
- {
- var f = t.GetDeclaredField (name);
- if (f != null)
- return f;
- return GetField (t.BaseType.GetTypeInfo (), name);
- }
- public static PropertyInfo GetProperty (TypeInfo t, string name)
- {
- var f = t.GetDeclaredProperty (name);
- if (f != null)
- return f;
- return GetProperty (t.BaseType.GetTypeInfo (), name);
- }
- public static object InflateAttribute (CustomAttributeData x)
- {
- var atype = x.AttributeType;
- var typeInfo = atype.GetTypeInfo ();
- #if ENABLE_IL2CPP
- var r = Activator.CreateInstance (x.AttributeType);
- #else
- var args = x.ConstructorArguments.Select (a => a.Value).ToArray ();
- var r = Activator.CreateInstance (x.AttributeType, args);
- foreach (var arg in x.NamedArguments) {
- if (arg.IsField) {
- GetField (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
- }
- else {
- GetProperty (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
- }
- }
- #endif
- return r;
- }
- public static IEnumerable<IndexedAttribute> GetIndices (MemberInfo p)
- {
- #if ENABLE_IL2CPP
- return p.GetCustomAttributes<IndexedAttribute> ();
- #else
- var indexedInfo = typeof (IndexedAttribute).GetTypeInfo ();
- return
- p.CustomAttributes
- .Where (x => indexedInfo.IsAssignableFrom (x.AttributeType.GetTypeInfo ()))
- .Select (x => (IndexedAttribute)InflateAttribute (x));
- #endif
- }
- public static int? MaxStringLength (MemberInfo p)
- {
- #if ENABLE_IL2CPP
- return p.GetCustomAttribute<MaxLengthAttribute> ()?.Value;
- #else
- var attr = p.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (MaxLengthAttribute));
- if (attr != null) {
- var attrv = (MaxLengthAttribute)InflateAttribute (attr);
- return attrv.Value;
- }
- return null;
- #endif
- }
- public static int? MaxStringLength (PropertyInfo p) => MaxStringLength((MemberInfo)p);
- public static bool IsMarkedNotNull (MemberInfo p)
- {
- return p.CustomAttributes.Any (x => x.AttributeType == typeof (NotNullAttribute));
- }
- }
- public partial class SQLiteCommand
- {
- SQLiteConnection _conn;
- private List<Binding> _bindings;
- public string CommandText { get; set; }
- public SQLiteCommand (SQLiteConnection conn)
- {
- _conn = conn;
- _bindings = new List<Binding> ();
- CommandText = "";
- }
- public int ExecuteNonQuery ()
- {
- if (_conn.Trace) {
- _conn.Tracer?.Invoke ("Executing: " + this);
- }
- var r = SQLite3.Result.OK;
- var stmt = Prepare ();
- r = SQLite3.Step (stmt);
- Finalize (stmt);
- if (r == SQLite3.Result.Done) {
- int rowsAffected = SQLite3.Changes (_conn.Handle);
- return rowsAffected;
- }
- else if (r == SQLite3.Result.Error) {
- string msg = SQLite3.GetErrmsg (_conn.Handle);
- throw SQLiteException.New (r, msg);
- }
- else if (r == SQLite3.Result.Constraint) {
- if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
- throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle));
- }
- }
- throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
- }
- public IEnumerable<T> ExecuteDeferredQuery<T> (string tableName = "")
- {
- return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T),tableName:tableName));
- }
- public List<T> ExecuteQuery<T> (string tableName = "")
- {
- return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T),tableName:tableName)).ToList ();
- }
- public List<T> ExecuteQuery<T> (TableMapping map)
- {
- return ExecuteDeferredQuery<T> (map).ToList ();
- }
- /// <summary>
- /// Invoked every time an instance is loaded from the database.
- /// </summary>
- /// <param name='obj'>
- /// The newly created object.
- /// </param>
- /// <remarks>
- /// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand"/>
- /// method to hook into the life-cycle of objects.
- /// </remarks>
- protected virtual void OnInstanceCreated (object obj)
- {
- // Can be overridden.
- }
- public IEnumerable<T> ExecuteDeferredQuery<T> (TableMapping map)
- {
- if (_conn.Trace) {
- _conn.Tracer?.Invoke ("Executing Query: " + this);
- }
- var stmt = Prepare ();
- try {
- var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)];
- var fastColumnSetters = new Action<object, Sqlite3Statement, int>[SQLite3.ColumnCount (stmt)];
- if (map.Method == TableMapping.MapMethod.ByPosition)
- {
- Array.Copy(map.Columns, cols, Math.Min(cols.Length, map.Columns.Length));
- }
- else if (map.Method == TableMapping.MapMethod.ByName) {
- MethodInfo getSetter = null;
- if (typeof(T) != map.MappedType) {
- getSetter = typeof(FastColumnSetter)
- .GetMethod (nameof(FastColumnSetter.GetFastSetter),
- BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod (map.MappedType);
- }
- for (int i = 0; i < cols.Length; i++) {
- var name = SQLite3.ColumnName16 (stmt, i);
- cols[i] = map.FindColumn (name);
- if (cols[i] != null)
- if (getSetter != null) {
- fastColumnSetters[i] = (Action<object, Sqlite3Statement, int>)getSetter.Invoke(null, new object[]{ _conn, cols[i]});
- }
- else {
- fastColumnSetters[i] = FastColumnSetter.GetFastSetter<T>(_conn, cols[i]);
- }
- }
- }
- while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
- var obj = Activator.CreateInstance (map.MappedType);
- for (int i = 0; i < cols.Length; i++) {
- if (cols[i] == null)
- continue;
- if (fastColumnSetters[i] != null) {
- fastColumnSetters[i].Invoke (obj, stmt, i);
- }
- else {
- var colType = SQLite3.ColumnType (stmt, i);
- var val = ReadCol (stmt, i, colType, cols[i].ColumnType);
- cols[i].SetValue (obj, val);
- }
- }
- OnInstanceCreated (obj);
- yield return (T)obj;
- }
- }
- finally {
- SQLite3.Finalize (stmt);
- }
- }
- public T ExecuteScalar<T> ()
- {
- if (_conn.Trace) {
- _conn.Tracer?.Invoke ("Executing Query: " + this);
- }
- T val = default (T);
- var stmt = Prepare ();
- try {
- var r = SQLite3.Step (stmt);
- if (r == SQLite3.Result.Row) {
- var colType = SQLite3.ColumnType (stmt, 0);
- var colval = ReadCol (stmt, 0, colType, typeof (T));
- if (colval != null) {
- val = (T)colval;
- }
- }
- else if (r == SQLite3.Result.Done) {
- }
- else {
- throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
- }
- }
- finally {
- Finalize (stmt);
- }
- return val;
- }
- public IEnumerable<T> ExecuteQueryScalars<T> ()
- {
- if (_conn.Trace) {
- _conn.Tracer?.Invoke ("Executing Query: " + this);
- }
- var stmt = Prepare ();
- try {
- if (SQLite3.ColumnCount (stmt) < 1) {
- throw new InvalidOperationException ("QueryScalars should return at least one column");
- }
- while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
- var colType = SQLite3.ColumnType (stmt, 0);
- var val = ReadCol (stmt, 0, colType, typeof (T));
- if (val == null) {
- yield return default (T);
- }
- else {
- yield return (T)val;
- }
- }
- }
- finally {
- Finalize (stmt);
- }
- }
- public void Bind (string name, object val)
- {
- _bindings.Add (new Binding {
- Name = name,
- Value = val
- });
- }
- public void Bind (object val)
- {
- Bind (null, val);
- }
- public override string ToString ()
- {
- var parts = new string[1 + _bindings.Count];
- parts[0] = CommandText;
- var i = 1;
- foreach (var b in _bindings) {
- parts[i] = string.Format (" {0}: {1}", i - 1, b.Value);
- i++;
- }
- return string.Join (Environment.NewLine, parts);
- }
- Sqlite3Statement Prepare ()
- {
- var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText);
- BindAll (stmt);
- return stmt;
- }
- void Finalize (Sqlite3Statement stmt)
- {
- SQLite3.Finalize (stmt);
- }
- void BindAll (Sqlite3Statement stmt)
- {
- int nextIdx = 1;
- foreach (var b in _bindings) {
- if (b.Name != null) {
- b.Index = SQLite3.BindParameterIndex (stmt, b.Name);
- }
- else {
- b.Index = nextIdx++;
- }
- BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks, _conn.DateTimeStringFormat, _conn.StoreTimeSpanAsTicks);
- }
- }
- static IntPtr NegativePointer = new IntPtr (-1);
- internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks, string dateTimeStringFormat, bool storeTimeSpanAsTicks)
- {
- if (value == null) {
- SQLite3.BindNull (stmt, index);
- }
- else {
- if (value is Int32) {
- SQLite3.BindInt (stmt, index, (int)value);
- }
- else if (value is String) {
- SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer);
- }
- else if (value is Byte || value is UInt16 || value is SByte || value is Int16) {
- SQLite3.BindInt (stmt, index, Convert.ToInt32 (value));
- }
- else if (value is Boolean) {
- SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0);
- }
- else if (value is UInt32 || value is Int64 || value is UInt64) {
- SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value));
- }
- else if (value is Single || value is Double || value is Decimal) {
- SQLite3.BindDouble (stmt, index, Convert.ToDouble (value));
- }
- else if (value is TimeSpan) {
- if (storeTimeSpanAsTicks) {
- SQLite3.BindInt64 (stmt, index, ((TimeSpan)value).Ticks);
- }
- else {
- SQLite3.BindText (stmt, index, ((TimeSpan)value).ToString (), -1, NegativePointer);
- }
- }
- else if (value is DateTime) {
- if (storeDateTimeAsTicks) {
- SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks);
- }
- else {
- SQLite3.BindText (stmt, index, ((DateTime)value).ToString (dateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture), -1, NegativePointer);
- }
- }
- else if (value is DateTimeOffset) {
- SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks);
- }
- else if (value is byte[]) {
- SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer);
- }
- else if (value is Guid) {
- SQLite3.BindText (stmt, index, ((Guid)value).ToString (), 72, NegativePointer);
- }
- else if (value is Uri) {
- SQLite3.BindText (stmt, index, ((Uri)value).ToString (), -1, NegativePointer);
- }
- else if (value is StringBuilder) {
- SQLite3.BindText (stmt, index, ((StringBuilder)value).ToString (), -1, NegativePointer);
- }
- else if (value is UriBuilder) {
- SQLite3.BindText (stmt, index, ((UriBuilder)value).ToString (), -1, NegativePointer);
- }
- else {
- // Now we could possibly get an enum, retrieve cached info
- var valueType = value.GetType ();
- var enumInfo = EnumCache.GetInfo (valueType);
- if (enumInfo.IsEnum) {
- var enumIntValue = Convert.ToInt32 (value);
- if (enumInfo.StoreAsText)
- SQLite3.BindText (stmt, index, enumInfo.EnumValues[enumIntValue], -1, NegativePointer);
- else
- SQLite3.BindInt (stmt, index, enumIntValue);
- }
- else {
- throw new NotSupportedException ("Cannot store type: " + Orm.GetType (value));
- }
- }
- }
- }
- class Binding
- {
- public string Name { get; set; }
- public object Value { get; set; }
- public int Index { get; set; }
- }
- object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType)
- {
- if (type == SQLite3.ColType.Null) {
- return null;
- }
- else {
- var clrTypeInfo = clrType.GetTypeInfo ();
- if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
- clrType = clrTypeInfo.GenericTypeArguments[0];
- clrTypeInfo = clrType.GetTypeInfo ();
- }
- if (clrType == typeof (String)) {
- return SQLite3.ColumnString (stmt, index);
- }
- else if (clrType == typeof (Int32)) {
- return (int)SQLite3.ColumnInt (stmt, index);
- }
- else if (clrType == typeof (Boolean)) {
- return SQLite3.ColumnInt (stmt, index) == 1;
- }
- else if (clrType == typeof (double)) {
- return SQLite3.ColumnDouble (stmt, index);
- }
- else if (clrType == typeof (float)) {
- return (float)SQLite3.ColumnDouble (stmt, index);
- }
- else if (clrType == typeof (TimeSpan)) {
- if (_conn.StoreTimeSpanAsTicks) {
- return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
- }
- else {
- var text = SQLite3.ColumnString (stmt, index);
- TimeSpan resultTime;
- if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
- resultTime = TimeSpan.Parse (text);
- }
- return resultTime;
- }
- }
- else if (clrType == typeof (DateTime)) {
- if (_conn.StoreDateTimeAsTicks) {
- return new DateTime (SQLite3.ColumnInt64 (stmt, index));
- }
- else {
- var text = SQLite3.ColumnString (stmt, index);
- DateTime resultDate;
- if (!DateTime.TryParseExact (text, _conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, _conn.DateTimeStyle, out resultDate)) {
- resultDate = DateTime.Parse (text);
- }
- return resultDate;
- }
- }
- else if (clrType == typeof (DateTimeOffset)) {
- return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
- }
- else if (clrTypeInfo.IsEnum) {
- if (type == SQLite3.ColType.Text) {
- var value = SQLite3.ColumnString (stmt, index);
- return Enum.Parse (clrType, value.ToString (), true);
- }
- else
- return SQLite3.ColumnInt (stmt, index);
- }
- else if (clrType == typeof (Int64)) {
- return SQLite3.ColumnInt64 (stmt, index);
- }
- else if (clrType == typeof (UInt64)) {
- return (ulong)SQLite3.ColumnInt64 (stmt, index);
- }
- else if (clrType == typeof (UInt32)) {
- return (uint)SQLite3.ColumnInt64 (stmt, index);
- }
- else if (clrType == typeof (decimal)) {
- return (decimal)SQLite3.ColumnDouble (stmt, index);
- }
- else if (clrType == typeof (Byte)) {
- return (byte)SQLite3.ColumnInt (stmt, index);
- }
- else if (clrType == typeof (UInt16)) {
- return (ushort)SQLite3.ColumnInt (stmt, index);
- }
- else if (clrType == typeof (Int16)) {
- return (short)SQLite3.ColumnInt (stmt, index);
- }
- else if (clrType == typeof (sbyte)) {
- return (sbyte)SQLite3.ColumnInt (stmt, index);
- }
- else if (clrType == typeof (byte[])) {
- return SQLite3.ColumnByteArray (stmt, index);
- }
- else if (clrType == typeof (Guid)) {
- var text = SQLite3.ColumnString (stmt, index);
- return new Guid (text);
- }
- else if (clrType == typeof (Uri)) {
- var text = SQLite3.ColumnString (stmt, index);
- return new Uri (text);
- }
- else if (clrType == typeof (StringBuilder)) {
- var text = SQLite3.ColumnString (stmt, index);
- return new StringBuilder (text);
- }
- else if (clrType == typeof (UriBuilder)) {
- var text = SQLite3.ColumnString (stmt, index);
- return new UriBuilder (text);
- }
- else {
- throw new NotSupportedException ("Don't know how to read " + clrType);
- }
- }
- }
- }
- internal class FastColumnSetter
- {
- /// <summary>
- /// Creates a delegate that can be used to quickly set object members from query columns.
- ///
- /// Note that this frontloads the slow reflection-based type checking for columns to only happen once at the beginning of a query,
- /// and then afterwards each row of the query can invoke the delegate returned by this function to get much better performance (up to 10x speed boost, depending on query size and platform).
- /// </summary>
- /// <typeparam name="T">The type of the destination object that the query will read into</typeparam>
- /// <param name="conn">The active connection. Note that this is primarily needed in order to read preferences regarding how certain data types (such as TimeSpan / DateTime) should be encoded in the database.</param>
- /// <param name="column">The table mapping used to map the statement column to a member of the destination object type</param>
- /// <returns>
- /// A delegate for fast-setting of object members from statement columns.
- ///
- /// If no fast setter is available for the requested column (enums in particular cause headache), then this function returns null.
- /// </returns>
- internal static Action<object, Sqlite3Statement, int> GetFastSetter<T> (SQLiteConnection conn, TableMapping.Column column)
- {
- Action<object, Sqlite3Statement, int> fastSetter = null;
- Type clrType = column.IsProperty ? column.PropertyInfo.PropertyType: column.FieldInfo.FieldType;
- var clrTypeInfo = clrType.GetTypeInfo ();
- if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
- clrType = clrTypeInfo.GenericTypeArguments[0];
- clrTypeInfo = clrType.GetTypeInfo ();
- }
- if (clrType == typeof (String)) {
- fastSetter = CreateTypedSetterDelegate<T, string> (column, (stmt, index) => {
- return SQLite3.ColumnString (stmt, index);
- });
- }
- else if (clrType == typeof (Int32)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, int> (column, (stmt, index)=>{
- return SQLite3.ColumnInt (stmt, index);
- });
- }
- else if (clrType == typeof (Boolean)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, bool> (column, (stmt, index) => {
- return SQLite3.ColumnInt (stmt, index) == 1;
- });
- }
- else if (clrType == typeof (double)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, double> (column, (stmt, index) => {
- return SQLite3.ColumnDouble (stmt, index);
- });
- }
- else if (clrType == typeof (float)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, float> (column, (stmt, index) => {
- return (float) SQLite3.ColumnDouble (stmt, index);
- });
- }
- else if (clrType == typeof (TimeSpan)) {
- if (conn.StoreTimeSpanAsTicks) {
- fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
- return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
- });
- }
- else {
- fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
- var text = SQLite3.ColumnString (stmt, index);
- TimeSpan resultTime;
- if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
- resultTime = TimeSpan.Parse (text);
- }
- return resultTime;
- });
- }
- }
- else if (clrType == typeof (DateTime)) {
- if (conn.StoreDateTimeAsTicks) {
- fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
- return new DateTime (SQLite3.ColumnInt64 (stmt, index));
- });
- }
- else {
- fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
- var text = SQLite3.ColumnString (stmt, index);
- DateTime resultDate;
- if (!DateTime.TryParseExact (text, conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, conn.DateTimeStyle, out resultDate)) {
- resultDate = DateTime.Parse (text);
- }
- return resultDate;
- });
- }
- }
- else if (clrType == typeof (DateTimeOffset)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, DateTimeOffset> (column, (stmt, index) => {
- return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
- });
- }
- else if (clrTypeInfo.IsEnum) {
- // NOTE: Not sure of a good way (if any?) to do a strongly-typed fast setter like this for enumerated types -- for now, return null and column sets will revert back to the safe (but slow) Reflection-based method of column prop.Set()
- }
- else if (clrType == typeof (Int64)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, Int64> (column, (stmt, index) => {
- return SQLite3.ColumnInt64 (stmt, index);
- });
- }
- else if (clrType == typeof(UInt64))
- {
- fastSetter = CreateNullableTypedSetterDelegate<T, UInt64>(column, (stmt, index) => {
- return (ulong)SQLite3.ColumnInt64(stmt, index);
- });
- }
- else if (clrType == typeof (UInt32)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, UInt32> (column, (stmt, index) => {
- return (uint)SQLite3.ColumnInt64 (stmt, index);
- });
- }
- else if (clrType == typeof (decimal)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, decimal> (column, (stmt, index) => {
- return (decimal)SQLite3.ColumnDouble (stmt, index);
- });
- }
- else if (clrType == typeof (Byte)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, Byte> (column, (stmt, index) => {
- return (byte)SQLite3.ColumnInt (stmt, index);
- });
- }
- else if (clrType == typeof (UInt16)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, UInt16> (column, (stmt, index) => {
- return (ushort)SQLite3.ColumnInt (stmt, index);
- });
- }
- else if (clrType == typeof (Int16)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, Int16> (column, (stmt, index) => {
- return (short)SQLite3.ColumnInt (stmt, index);
- });
- }
- else if (clrType == typeof (sbyte)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, sbyte> (column, (stmt, index) => {
- return (sbyte)SQLite3.ColumnInt (stmt, index);
- });
- }
- else if (clrType == typeof (byte[])) {
- fastSetter = CreateTypedSetterDelegate<T, byte[]> (column, (stmt, index) => {
- return SQLite3.ColumnByteArray (stmt, index);
- });
- }
- else if (clrType == typeof (Guid)) {
- fastSetter = CreateNullableTypedSetterDelegate<T, Guid> (column, (stmt, index) => {
- var text = SQLite3.ColumnString (stmt, index);
- return new Guid (text);
- });
- }
- else if (clrType == typeof (Uri)) {
- fastSetter = CreateTypedSetterDelegate<T, Uri> (column, (stmt, index) => {
- var text = SQLite3.ColumnString (stmt, index);
- return new Uri (text);
- });
- }
- else if (clrType == typeof (StringBuilder)) {
- fastSetter = CreateTypedSetterDelegate<T, StringBuilder> (column, (stmt, index) => {
- var text = SQLite3.ColumnString (stmt, index);
- return new StringBuilder (text);
- });
- }
- else if (clrType == typeof (UriBuilder)) {
- fastSetter = CreateTypedSetterDelegate<T, UriBuilder> (column, (stmt, index) => {
- var text = SQLite3.ColumnString (stmt, index);
- return new UriBuilder (text);
- });
- }
- else {
- // NOTE: Will fall back to the slow setter method in the event that we are unable to create a fast setter delegate for a particular column type
- }
- return fastSetter;
- }
- /// <summary>
- /// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
- ///
- /// Note that this is identical to CreateTypedSetterDelegate(), but has an extra check to see if it should create a nullable version of the delegate.
- /// </summary>
- /// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
- /// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
- /// <param name="column">The column mapping that identifies the target member of the destination object</param>
- /// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
- /// <returns>A strongly-typed delegate</returns>
- private static Action<object, Sqlite3Statement, int> CreateNullableTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue) where ColumnMemberType : struct
- {
- var clrTypeInfo =column.IsProperty ? column.PropertyInfo.PropertyType.GetTypeInfo():column.FieldInfo.FieldType.GetTypeInfo();
- bool isNullable = false;
- if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
- isNullable = true;
- }
- if (isNullable) {
- var setProperty = (Action<ObjectType, ColumnMemberType?>)Delegate.CreateDelegate (
- typeof (Action<ObjectType, ColumnMemberType?>), null,
- column.PropertyInfo.GetSetMethod ());
- return (o, stmt, i) => {
- var colType = SQLite3.ColumnType (stmt, i);
- if (colType != SQLite3.ColType.Null)
- setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
- };
- }
- return CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (column, getColumnValue);
- }
- /// <summary>
- /// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
- /// </summary>
- /// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
- /// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
- /// <param name="column">The column mapping that identifies the target member of the destination object</param>
- /// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
- /// <returns>A strongly-typed delegate</returns>
- private static Action<object, Sqlite3Statement, int> CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue)
- {
- if (column.IsProperty)
- {
- var setProperty = (Action<ObjectType, ColumnMemberType>)Delegate.CreateDelegate(
- typeof(Action<ObjectType, ColumnMemberType>), null,
- column.PropertyInfo.GetSetMethod());
- return (o, stmt, i) =>
- {
- var colType = SQLite3.ColumnType(stmt, i);
- if (colType != SQLite3.ColType.Null)
- setProperty.Invoke((ObjectType)o, getColumnValue.Invoke(stmt, i));
- };
- }
- else
- {
- return null;
- }
- }
- }
- /// <summary>
- /// Since the insert never changed, we only need to prepare once.
- /// </summary>
- class PreparedSqlLiteInsertCommand : IDisposable
- {
- bool Initialized;
- SQLiteConnection Connection;
- string CommandText;
- Sqlite3Statement Statement;
- static readonly Sqlite3Statement NullStatement = default (Sqlite3Statement);
- public PreparedSqlLiteInsertCommand (SQLiteConnection conn, string commandText)
- {
- Connection = conn;
- CommandText = commandText;
- }
- public int ExecuteNonQuery (object[] source)
- {
- if (Initialized && Statement == NullStatement) {
- throw new ObjectDisposedException (nameof (PreparedSqlLiteInsertCommand));
- }
- if (Connection.Trace) {
- Connection.Tracer?.Invoke ("Executing: " + CommandText);
- }
- var r = SQLite3.Result.OK;
- if (!Initialized) {
- Statement = SQLite3.Prepare2 (Connection.Handle, CommandText);
- Initialized = true;
- }
- //bind the values.
- if (source != null) {
- for (int i = 0; i < source.Length; i++) {
- SQLiteCommand.BindParameter (Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks, Connection.DateTimeStringFormat, Connection.StoreTimeSpanAsTicks);
- }
- }
- r = SQLite3.Step (Statement);
- if (r == SQLite3.Result.Done) {
- int rowsAffected = SQLite3.Changes (Connection.Handle);
- SQLite3.Reset (Statement);
- return rowsAffected;
- }
- else if (r == SQLite3.Result.Error) {
- string msg = SQLite3.GetErrmsg (Connection.Handle);
- SQLite3.Reset (Statement);
- throw SQLiteException.New (r, msg);
- }
- else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
- SQLite3.Reset (Statement);
- throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle));
- }
- else {
- SQLite3.Reset (Statement);
- throw SQLiteException.New (r, SQLite3.GetErrmsg (Connection.Handle));
- }
- }
- public void Dispose ()
- {
- Dispose (true);
- GC.SuppressFinalize (this);
- }
- void Dispose (bool disposing)
- {
- var s = Statement;
- Statement = NullStatement;
- Connection = null;
- if (s != NullStatement) {
- SQLite3.Finalize (s);
- }
- }
- ~PreparedSqlLiteInsertCommand ()
- {
- Dispose (false);
- }
- }
- public enum CreateTableResult
- {
- Created,
- Migrated,
- }
- public class CreateTablesResult
- {
- public Dictionary<Type, CreateTableResult> Results { get; private set; }
- public CreateTablesResult ()
- {
- Results = new Dictionary<Type, CreateTableResult> ();
- }
- }
- public abstract class BaseTableQuery
- {
- protected class Ordering
- {
- public string ColumnName { get; set; }
- public bool Ascending { get; set; }
- }
- }
- public class TableQuery<T> : BaseTableQuery, IEnumerable<T>
- {
- public SQLiteConnection Connection { get; private set; }
- public TableMapping Table { get; private set; }
- Expression _where;
- List<Ordering> _orderBys;
- int? _limit;
- int? _offset;
- BaseTableQuery _joinInner;
- Expression _joinInnerKeySelector;
- BaseTableQuery _joinOuter;
- Expression _joinOuterKeySelector;
- Expression _joinSelector;
- Expression _selector;
- TableQuery (SQLiteConnection conn, TableMapping table)
- {
- Connection = conn;
- Table = table;
- }
- public TableQuery (SQLiteConnection conn,string tableName = "")
- {
- Connection = conn;
- Table = Connection.GetMapping (typeof (T),tableName:tableName);
- }
- public TableQuery<U> Clone<U> ()
- {
- var q = new TableQuery<U> (Connection, Table);
- q._where = _where;
- q._deferred = _deferred;
- if (_orderBys != null) {
- q._orderBys = new List<Ordering> (_orderBys);
- }
- q._limit = _limit;
- q._offset = _offset;
- q._joinInner = _joinInner;
- q._joinInnerKeySelector = _joinInnerKeySelector;
- q._joinOuter = _joinOuter;
- q._joinOuterKeySelector = _joinOuterKeySelector;
- q._joinSelector = _joinSelector;
- q._selector = _selector;
- return q;
- }
- /// <summary>
- /// Filters the query based on a predicate.
- /// </summary>
- public TableQuery<T> Where (Expression<Func<T, bool>> predExpr)
- {
- if (predExpr.NodeType == ExpressionType.Lambda) {
- var lambda = (LambdaExpression)predExpr;
- var pred = lambda.Body;
- var q = Clone<T> ();
- q.AddWhere (pred);
- return q;
- }
- else {
- throw new NotSupportedException ("Must be a predicate");
- }
- }
- /// <summary>
- /// Delete all the rows that match this query.
- /// </summary>
- public int Delete ()
- {
- return Delete (null);
- }
- /// <summary>
- /// Delete all the rows that match this query and the given predicate.
- /// </summary>
- public int Delete (Expression<Func<T, bool>> predExpr)
- {
- if (_limit.HasValue || _offset.HasValue)
- throw new InvalidOperationException ("Cannot delete with limits or offsets");
- if (_where == null && predExpr == null)
- throw new InvalidOperationException ("No condition specified");
- var pred = _where;
- if (predExpr != null && predExpr.NodeType == ExpressionType.Lambda) {
- var lambda = (LambdaExpression)predExpr;
- pred = pred != null ? Expression.AndAlso (pred, lambda.Body) : lambda.Body;
- }
- var args = new List<object> ();
- var cmdText = "delete from \"" + Table.TableName + "\"";
- var w = CompileExpr (pred, args);
- cmdText += " where " + w.CommandText;
- var command = Connection.CreateCommand (cmdText, args.ToArray ());
- int result = command.ExecuteNonQuery ();
- return result;
- }
- /// <summary>
- /// Yields a given number of elements from the query and then skips the remainder.
- /// </summary>
- public TableQuery<T> Take (int n)
- {
- var q = Clone<T> ();
- q._limit = n;
- return q;
- }
- /// <summary>
- /// Skips a given number of elements from the query and then yields the remainder.
- /// </summary>
- public TableQuery<T> Skip (int n)
- {
- var q = Clone<T> ();
- q._offset = n;
- return q;
- }
- /// <summary>
- /// Returns the element at a given index
- /// </summary>
- public T ElementAt (int index)
- {
- return Skip (index).Take (1).First ();
- }
- bool _deferred;
- public TableQuery<T> Deferred ()
- {
- var q = Clone<T> ();
- q._deferred = true;
- return q;
- }
- /// <summary>
- /// Order the query results according to a key.
- /// </summary>
- public TableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
- {
- return AddOrderBy<U> (orderExpr, true);
- }
- /// <summary>
- /// Order the query results according to a key.
- /// </summary>
- public TableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
- {
- return AddOrderBy<U> (orderExpr, false);
- }
- /// <summary>
- /// Order the query results according to a key.
- /// </summary>
- public TableQuery<T> ThenBy<U> (Expression<Func<T, U>> orderExpr)
- {
- return AddOrderBy<U> (orderExpr, true);
- }
- /// <summary>
- /// Order the query results according to a key.
- /// </summary>
- public TableQuery<T> ThenByDescending<U> (Expression<Func<T, U>> orderExpr)
- {
- return AddOrderBy<U> (orderExpr, false);
- }
- TableQuery<T> AddOrderBy<U> (Expression<Func<T, U>> orderExpr, bool asc)
- {
- if (orderExpr.NodeType == ExpressionType.Lambda) {
- var lambda = (LambdaExpression)orderExpr;
- MemberExpression mem = null;
- var unary = lambda.Body as UnaryExpression;
- if (unary != null && unary.NodeType == ExpressionType.Convert) {
- mem = unary.Operand as MemberExpression;
- }
- else {
- mem = lambda.Body as MemberExpression;
- }
- if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) {
- var q = Clone<T> ();
- if (q._orderBys == null) {
- q._orderBys = new List<Ordering> ();
- }
- q._orderBys.Add (new Ordering {
- ColumnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name,
- Ascending = asc
- });
- return q;
- }
- else {
- throw new NotSupportedException ("Order By does not support: " + orderExpr);
- }
- }
- else {
- throw new NotSupportedException ("Must be a predicate");
- }
- }
- private void AddWhere (Expression pred)
- {
- if (_where == null) {
- _where = pred;
- }
- else {
- _where = Expression.AndAlso (_where, pred);
- }
- }
- ///// <summary>
- ///// Performs an inner join of two queries based on matching keys extracted from the elements.
- ///// </summary>
- //public TableQuery<TResult> Join<TInner, TKey, TResult> (
- // TableQuery<TInner> inner,
- // Expression<Func<T, TKey>> outerKeySelector,
- // Expression<Func<TInner, TKey>> innerKeySelector,
- // Expression<Func<T, TInner, TResult>> resultSelector)
- //{
- // var q = new TableQuery<TResult> (Connection, Connection.GetMapping (typeof (TResult))) {
- // _joinOuter = this,
- // _joinOuterKeySelector = outerKeySelector,
- // _joinInner = inner,
- // _joinInnerKeySelector = innerKeySelector,
- // _joinSelector = resultSelector,
- // };
- // return q;
- //}
- // Not needed until Joins are supported
- // Keeping this commented out forces the default Linq to objects processor to run
- //public TableQuery<TResult> Select<TResult> (Expression<Func<T, TResult>> selector)
- //{
- // var q = Clone<TResult> ();
- // q._selector = selector;
- // return q;
- //}
- private SQLiteCommand GenerateCommand (string selectionList)
- {
- if (_joinInner != null && _joinOuter != null) {
- throw new NotSupportedException ("Joins are not supported.");
- }
- else {
- var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\"";
- var args = new List<object> ();
- if (_where != null) {
- var w = CompileExpr (_where, args);
- cmdText += " where " + w.CommandText;
- }
- if ((_orderBys != null) && (_orderBys.Count > 0)) {
- var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ());
- cmdText += " order by " + t;
- }
- if (_limit.HasValue) {
- cmdText += " limit " + _limit.Value;
- }
- if (_offset.HasValue) {
- if (!_limit.HasValue) {
- cmdText += " limit -1 ";
- }
- cmdText += " offset " + _offset.Value;
- }
- return Connection.CreateCommand (cmdText, args.ToArray ());
- }
- }
- class CompileResult
- {
- public string CommandText { get; set; }
- public object Value { get; set; }
- }
- private CompileResult CompileExpr (Expression expr, List<object> queryArgs)
- {
- if (expr == null) {
- throw new NotSupportedException ("Expression is NULL");
- }
- else if (expr is BinaryExpression) {
- var bin = (BinaryExpression)expr;
- // VB turns 'x=="foo"' into 'CompareString(x,"foo",true/false)==0', so we need to unwrap it
- // http://blogs.msdn.com/b/vbteam/archive/2007/09/18/vb-expression-trees-string-comparisons.aspx
- if (bin.Left.NodeType == ExpressionType.Call) {
- var call = (MethodCallExpression)bin.Left;
- if (call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators"
- && call.Method.Name == "CompareString")
- bin = Expression.MakeBinary (bin.NodeType, call.Arguments[0], call.Arguments[1]);
- }
- var leftr = CompileExpr (bin.Left, queryArgs);
- var rightr = CompileExpr (bin.Right, queryArgs);
- //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
- string text;
- if (leftr.CommandText == "?" && leftr.Value == null)
- text = CompileNullBinaryExpression (bin, rightr);
- else if (rightr.CommandText == "?" && rightr.Value == null)
- text = CompileNullBinaryExpression (bin, leftr);
- else
- text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")";
- return new CompileResult { CommandText = text };
- }
- else if (expr.NodeType == ExpressionType.Not) {
- var operandExpr = ((UnaryExpression)expr).Operand;
- var opr = CompileExpr (operandExpr, queryArgs);
- object val = opr.Value;
- if (val is bool)
- val = !((bool)val);
- return new CompileResult {
- CommandText = "NOT(" + opr.CommandText + ")",
- Value = val
- };
- }
- else if (expr.NodeType == ExpressionType.Call) {
- var call = (MethodCallExpression)expr;
- var args = new CompileResult[call.Arguments.Count];
- var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null;
- for (var i = 0; i < args.Length; i++) {
- args[i] = CompileExpr (call.Arguments[i], queryArgs);
- }
- var sqlCall = "";
- if (call.Method.Name == "Like" && args.Length == 2) {
- sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
- }
- else if (call.Method.Name == "Contains" && args.Length == 2) {
- sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
- }
- else if (call.Method.Name == "Contains" && args.Length == 1) {
- if (call.Object != null && call.Object.Type == typeof (string)) {
- sqlCall = "( instr(" + obj.CommandText + "," + args[0].CommandText + ") >0 )";
- }
- else {
- sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
- }
- }
- else if (call.Method.Name == "StartsWith" && args.Length >= 1) {
- var startsWithCmpOp = StringComparison.CurrentCulture;
- if (args.Length == 2) {
- startsWithCmpOp = (StringComparison)args[1].Value;
- }
- switch (startsWithCmpOp) {
- case StringComparison.Ordinal:
- case StringComparison.CurrentCulture:
- sqlCall = "( substr(" + obj.CommandText + ", 1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
- break;
- case StringComparison.OrdinalIgnoreCase:
- case StringComparison.CurrentCultureIgnoreCase:
- sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
- break;
- }
- }
- else if (call.Method.Name == "EndsWith" && args.Length >= 1) {
- var endsWithCmpOp = StringComparison.CurrentCulture;
- if (args.Length == 2) {
- endsWithCmpOp = (StringComparison)args[1].Value;
- }
- switch (endsWithCmpOp) {
- case StringComparison.Ordinal:
- case StringComparison.CurrentCulture:
- sqlCall = "( substr(" + obj.CommandText + ", length(" + obj.CommandText + ") - " + args[0].Value.ToString ().Length + "+1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
- break;
- case StringComparison.OrdinalIgnoreCase:
- case StringComparison.CurrentCultureIgnoreCase:
- sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
- break;
- }
- }
- else if (call.Method.Name == "Equals" && args.Length == 1) {
- sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
- }
- else if (call.Method.Name == "ToLower") {
- sqlCall = "(lower(" + obj.CommandText + "))";
- }
- else if (call.Method.Name == "ToUpper") {
- sqlCall = "(upper(" + obj.CommandText + "))";
- }
- else if (call.Method.Name == "Replace" && args.Length == 2) {
- sqlCall = "(replace(" + obj.CommandText + "," + args[0].CommandText + "," + args[1].CommandText + "))";
- }
- else if (call.Method.Name == "IsNullOrEmpty" && args.Length == 1) {
- sqlCall = "(" + args[0].CommandText + " is null or" + args[0].CommandText + " ='' )";
- }
- else {
- sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")";
- }
- return new CompileResult { CommandText = sqlCall };
- }
- else if (expr.NodeType == ExpressionType.Constant) {
- var c = (ConstantExpression)expr;
- queryArgs.Add (c.Value);
- return new CompileResult {
- CommandText = "?",
- Value = c.Value
- };
- }
- else if (expr.NodeType == ExpressionType.Convert) {
- var u = (UnaryExpression)expr;
- var ty = u.Type;
- var valr = CompileExpr (u.Operand, queryArgs);
- return new CompileResult {
- CommandText = valr.CommandText,
- Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null
- };
- }
- else if (expr.NodeType == ExpressionType.MemberAccess) {
- var mem = (MemberExpression)expr;
- var paramExpr = mem.Expression as ParameterExpression;
- if (paramExpr == null) {
- var convert = mem.Expression as UnaryExpression;
- if (convert != null && convert.NodeType == ExpressionType.Convert) {
- paramExpr = convert.Operand as ParameterExpression;
- }
- }
- if (paramExpr != null) {
- //
- // This is a column of our table, output just the column name
- // Need to translate it if that column name is mapped
- //
- var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name;
- return new CompileResult { CommandText = "\"" + columnName + "\"" };
- }
- else {
- object obj = null;
- if (mem.Expression != null) {
- var r = CompileExpr (mem.Expression, queryArgs);
- if (r.Value == null) {
- throw new NotSupportedException ("Member access failed to compile expression");
- }
- if (r.CommandText == "?") {
- queryArgs.RemoveAt (queryArgs.Count - 1);
- }
- obj = r.Value;
- }
- //
- // Get the member value
- //
- object val = null;
- if (mem.Member is PropertyInfo) {
- var m = (PropertyInfo)mem.Member;
- val = m.GetValue (obj, null);
- }
- else if (mem.Member is FieldInfo) {
- var m = (FieldInfo)mem.Member;
- val = m.GetValue (obj);
- }
- else {
- throw new NotSupportedException ("MemberExpr: " + mem.Member.GetType ());
- }
- //
- // Work special magic for enumerables
- //
- if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable<byte>)) {
- var sb = new System.Text.StringBuilder ();
- sb.Append ("(");
- var head = "";
- foreach (var a in (System.Collections.IEnumerable)val) {
- queryArgs.Add (a);
- sb.Append (head);
- sb.Append ("?");
- head = ",";
- }
- sb.Append (")");
- return new CompileResult {
- CommandText = sb.ToString (),
- Value = val
- };
- }
- else {
- queryArgs.Add (val);
- return new CompileResult {
- CommandText = "?",
- Value = val
- };
- }
- }
- }
- throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ());
- }
- static object ConvertTo (object obj, Type t)
- {
- Type nut = Nullable.GetUnderlyingType (t);
- if (nut != null) {
- if (obj == null)
- return null;
- return Convert.ChangeType (obj, nut);
- }
- else {
- return Convert.ChangeType (obj, t);
- }
- }
- /// <summary>
- /// Compiles a BinaryExpression where one of the parameters is null.
- /// </summary>
- /// <param name="expression">The expression to compile</param>
- /// <param name="parameter">The non-null parameter</param>
- private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter)
- {
- if (expression.NodeType == ExpressionType.Equal)
- return "(" + parameter.CommandText + " is ?)";
- else if (expression.NodeType == ExpressionType.NotEqual)
- return "(" + parameter.CommandText + " is not ?)";
- else if (expression.NodeType == ExpressionType.GreaterThan
- || expression.NodeType == ExpressionType.GreaterThanOrEqual
- || expression.NodeType == ExpressionType.LessThan
- || expression.NodeType == ExpressionType.LessThanOrEqual)
- return "(" + parameter.CommandText + " < ?)"; // always false
- else
- throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ());
- }
- string GetSqlName (Expression expr)
- {
- var n = expr.NodeType;
- if (n == ExpressionType.GreaterThan)
- return ">";
- else if (n == ExpressionType.GreaterThanOrEqual) {
- return ">=";
- }
- else if (n == ExpressionType.LessThan) {
- return "<";
- }
- else if (n == ExpressionType.LessThanOrEqual) {
- return "<=";
- }
- else if (n == ExpressionType.And) {
- return "&";
- }
- else if (n == ExpressionType.AndAlso) {
- return "and";
- }
- else if (n == ExpressionType.Or) {
- return "|";
- }
- else if (n == ExpressionType.OrElse) {
- return "or";
- }
- else if (n == ExpressionType.Equal) {
- return "=";
- }
- else if (n == ExpressionType.NotEqual) {
- return "!=";
- }
- else {
- throw new NotSupportedException ("Cannot get SQL for: " + n);
- }
- }
- /// <summary>
- /// Execute SELECT COUNT(*) on the query
- /// </summary>
- public int Count ()
- {
- return GenerateCommand ("count(*)").ExecuteScalar<int> ();
- }
- /// <summary>
- /// Execute SELECT COUNT(*) on the query with an additional WHERE clause.
- /// </summary>
- public int Count (Expression<Func<T, bool>> predExpr)
- {
- return Where (predExpr).Count ();
- }
- public IEnumerator<T> GetEnumerator ()
- {
- if (!_deferred)
- return GenerateCommand ("*").ExecuteQuery<T> ().GetEnumerator ();
- return GenerateCommand ("*").ExecuteDeferredQuery<T> ().GetEnumerator ();
- }
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
- {
- return GetEnumerator ();
- }
- /// <summary>
- /// Queries the database and returns the results as a List.
- /// </summary>
- public List<T> ToList ()
- {
- return GenerateCommand ("*").ExecuteQuery<T> ();
- }
- /// <summary>
- /// Queries the database and returns the results as an array.
- /// </summary>
- public T[] ToArray ()
- {
- return GenerateCommand ("*").ExecuteQuery<T> ().ToArray ();
- }
- /// <summary>
- /// Returns the first element of this query.
- /// </summary>
- public T First ()
- {
- var query = Take (1);
- return query.ToList ().First ();
- }
- /// <summary>
- /// Returns the first element of this query, or null if no element is found.
- /// </summary>
- public T FirstOrDefault ()
- {
- var query = Take (1);
- return query.ToList ().FirstOrDefault ();
- }
- /// <summary>
- /// Returns the first element of this query that matches the predicate.
- /// </summary>
- public T First (Expression<Func<T, bool>> predExpr)
- {
- return Where (predExpr).First ();
- }
- /// <summary>
- /// Returns the first element of this query that matches the predicate, or null
- /// if no element is found.
- /// </summary>
- public T FirstOrDefault (Expression<Func<T, bool>> predExpr)
- {
- return Where (predExpr).FirstOrDefault ();
- }
- }
- public static class SQLite3
- {
- public enum Result : int
- {
- OK = 0,
- Error = 1,
- Internal = 2,
- Perm = 3,
- Abort = 4,
- Busy = 5,
- Locked = 6,
- NoMem = 7,
- ReadOnly = 8,
- Interrupt = 9,
- IOError = 10,
- Corrupt = 11,
- NotFound = 12,
- Full = 13,
- CannotOpen = 14,
- LockErr = 15,
- Empty = 16,
- SchemaChngd = 17,
- TooBig = 18,
- Constraint = 19,
- Mismatch = 20,
- Misuse = 21,
- NotImplementedLFS = 22,
- AccessDenied = 23,
- Format = 24,
- Range = 25,
- NonDBFile = 26,
- Notice = 27,
- Warning = 28,
- Row = 100,
- Done = 101
- }
- public enum ExtendedResult : int
- {
- IOErrorRead = (Result.IOError | (1 << 8)),
- IOErrorShortRead = (Result.IOError | (2 << 8)),
- IOErrorWrite = (Result.IOError | (3 << 8)),
- IOErrorFsync = (Result.IOError | (4 << 8)),
- IOErrorDirFSync = (Result.IOError | (5 << 8)),
- IOErrorTruncate = (Result.IOError | (6 << 8)),
- IOErrorFStat = (Result.IOError | (7 << 8)),
- IOErrorUnlock = (Result.IOError | (8 << 8)),
- IOErrorRdlock = (Result.IOError | (9 << 8)),
- IOErrorDelete = (Result.IOError | (10 << 8)),
- IOErrorBlocked = (Result.IOError | (11 << 8)),
- IOErrorNoMem = (Result.IOError | (12 << 8)),
- IOErrorAccess = (Result.IOError | (13 << 8)),
- IOErrorCheckReservedLock = (Result.IOError | (14 << 8)),
- IOErrorLock = (Result.IOError | (15 << 8)),
- IOErrorClose = (Result.IOError | (16 << 8)),
- IOErrorDirClose = (Result.IOError | (17 << 8)),
- IOErrorSHMOpen = (Result.IOError | (18 << 8)),
- IOErrorSHMSize = (Result.IOError | (19 << 8)),
- IOErrorSHMLock = (Result.IOError | (20 << 8)),
- IOErrorSHMMap = (Result.IOError | (21 << 8)),
- IOErrorSeek = (Result.IOError | (22 << 8)),
- IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)),
- IOErrorMMap = (Result.IOError | (24 << 8)),
- LockedSharedcache = (Result.Locked | (1 << 8)),
- BusyRecovery = (Result.Busy | (1 << 8)),
- CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)),
- CannotOpenIsDir = (Result.CannotOpen | (2 << 8)),
- CannotOpenFullPath = (Result.CannotOpen | (3 << 8)),
- CorruptVTab = (Result.Corrupt | (1 << 8)),
- ReadonlyRecovery = (Result.ReadOnly | (1 << 8)),
- ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)),
- ReadonlyRollback = (Result.ReadOnly | (3 << 8)),
- AbortRollback = (Result.Abort | (2 << 8)),
- ConstraintCheck = (Result.Constraint | (1 << 8)),
- ConstraintCommitHook = (Result.Constraint | (2 << 8)),
- ConstraintForeignKey = (Result.Constraint | (3 << 8)),
- ConstraintFunction = (Result.Constraint | (4 << 8)),
- ConstraintNotNull = (Result.Constraint | (5 << 8)),
- ConstraintPrimaryKey = (Result.Constraint | (6 << 8)),
- ConstraintTrigger = (Result.Constraint | (7 << 8)),
- ConstraintUnique = (Result.Constraint | (8 << 8)),
- ConstraintVTab = (Result.Constraint | (9 << 8)),
- NoticeRecoverWAL = (Result.Notice | (1 << 8)),
- NoticeRecoverRollback = (Result.Notice | (2 << 8))
- }
- public enum ConfigOption : int
- {
- SingleThread = 1,
- MultiThread = 2,
- Serialized = 3
- }
- const string LibraryPath = "libsqlite3.so.0";
- //const string LibraryPath = "e_sqlite3.dll";
- #if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE && !USE_SQLITEPCL_RAW
- [DllImport(LibraryPath, EntryPoint = "sqlite3_threadsafe", CallingConvention=CallingConvention.Cdecl)]
- public static extern int Threadsafe ();
- [DllImport(LibraryPath, EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result Open(byte[] filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result EnableLoadExtension (IntPtr db, int onoff);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Close (IntPtr db);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_close_v2", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result Close2(IntPtr db);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Initialize();
- [DllImport(LibraryPath, EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Shutdown();
- [DllImport(LibraryPath, EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Config (ConfigOption option);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
- public static extern int SetDirectory (uint directoryType, string directoryPath);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result BusyTimeout (IntPtr db, int milliseconds);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)]
- public static extern int Changes (IntPtr db);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail);
- #if NETFX_CORE
- [DllImport (LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail);
- #endif
- public static IntPtr Prepare2 (IntPtr db, string query)
- {
- IntPtr stmt;
- #if NETFX_CORE
- byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query);
- var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero);
- #else
- var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero);
- #endif
- if (r != Result.OK) {
- throw SQLiteException.New (r, GetErrmsg (db));
- }
- return stmt;
- }
- [DllImport(LibraryPath, EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Step (IntPtr stmt);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Reset (IntPtr stmt);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)]
- public static extern Result Finalize (IntPtr stmt);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)]
- public static extern long LastInsertRowid (IntPtr db);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)]
- public static extern IntPtr Errmsg (IntPtr db);
- public static string GetErrmsg (IntPtr db)
- {
- return Marshal.PtrToStringUni (Errmsg (db));
- }
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)]
- public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)]
- public static extern int BindNull (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)]
- public static extern int BindInt (IntPtr stmt, int index, int val);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)]
- public static extern int BindInt64 (IntPtr stmt, int index, long val);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)]
- public static extern int BindDouble (IntPtr stmt, int index, double val);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
- public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)]
- public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)]
- public static extern int ColumnCount (IntPtr stmt);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)]
- public static extern IntPtr ColumnName (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)]
- static extern IntPtr ColumnName16Internal (IntPtr stmt, int index);
- public static string ColumnName16(IntPtr stmt, int index)
- {
- return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index));
- }
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)]
- public static extern ColType ColumnType (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)]
- public static extern int ColumnInt (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)]
- public static extern long ColumnInt64 (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)]
- public static extern double ColumnDouble (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)]
- public static extern IntPtr ColumnText (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)]
- public static extern IntPtr ColumnText16 (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)]
- public static extern IntPtr ColumnBlob (IntPtr stmt, int index);
- [DllImport(LibraryPath, EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)]
- public static extern int ColumnBytes (IntPtr stmt, int index);
- public static string ColumnString (IntPtr stmt, int index)
- {
- return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index));
- }
- public static byte[] ColumnByteArray (IntPtr stmt, int index)
- {
- int length = ColumnBytes (stmt, index);
- var result = new byte[length];
- if (length > 0)
- Marshal.Copy (ColumnBlob (stmt, index), result, 0, length);
- return result;
- }
- [DllImport (LibraryPath, EntryPoint = "sqlite3_errcode", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result GetResult (Sqlite3DatabaseHandle db);
- [DllImport (LibraryPath, EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
- public static extern ExtendedResult ExtendedErrCode (IntPtr db);
- [DllImport (LibraryPath, EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
- public static extern int LibVersionNumber ();
- [DllImport (LibraryPath, EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)]
- public static extern Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, [MarshalAs (UnmanagedType.LPStr)] string destName, Sqlite3DatabaseHandle sourceDb, [MarshalAs (UnmanagedType.LPStr)] string sourceName);
- [DllImport (LibraryPath, EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result BackupStep (Sqlite3BackupHandle backup, int numPages);
- [DllImport (LibraryPath, EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)]
- public static extern Result BackupFinish (Sqlite3BackupHandle backup);
- #else
- public static Result Open (string filename, out Sqlite3DatabaseHandle db)
- {
- return (Result)Sqlite3.sqlite3_open (filename, out db);
- }
- public static Result Open (string filename, out Sqlite3DatabaseHandle db, int flags, string vfsName)
- {
- #if USE_WP8_NATIVE_SQLITE
- return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, vfsName ?? "");
- #else
- return (Result)Sqlite3.sqlite3_open_v2 (filename, out db, flags, vfsName);
- #endif
- }
- public static Result Close (Sqlite3DatabaseHandle db)
- {
- return (Result)Sqlite3.sqlite3_close (db);
- }
- public static Result Close2 (Sqlite3DatabaseHandle db)
- {
- return (Result)Sqlite3.sqlite3_close_v2 (db);
- }
- public static Result BusyTimeout (Sqlite3DatabaseHandle db, int milliseconds)
- {
- return (Result)Sqlite3.sqlite3_busy_timeout (db, milliseconds);
- }
- public static int Changes (Sqlite3DatabaseHandle db)
- {
- return Sqlite3.sqlite3_changes (db);
- }
- public static Sqlite3Statement Prepare2 (Sqlite3DatabaseHandle db, string query)
- {
- Sqlite3Statement stmt = default (Sqlite3Statement);
- #if USE_WP8_NATIVE_SQLITE || USE_SQLITEPCL_RAW
- var r = Sqlite3.sqlite3_prepare_v2 (db, query, out stmt);
- #else
- stmt = new Sqlite3Statement();
- var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0);
- #endif
- if (r != 0) {
- throw SQLiteException.New ((Result)r, GetErrmsg (db));
- }
- return stmt;
- }
- public static Result Step (Sqlite3Statement stmt)
- {
- return (Result)Sqlite3.sqlite3_step (stmt);
- }
- public static Result Reset (Sqlite3Statement stmt)
- {
- return (Result)Sqlite3.sqlite3_reset (stmt);
- }
- public static Result Finalize (Sqlite3Statement stmt)
- {
- return (Result)Sqlite3.sqlite3_finalize (stmt);
- }
- public static long LastInsertRowid (Sqlite3DatabaseHandle db)
- {
- return Sqlite3.sqlite3_last_insert_rowid (db);
- }
- public static string GetErrmsg (Sqlite3DatabaseHandle db)
- {
- return Sqlite3.sqlite3_errmsg (db).utf8_to_string ();
- }
- public static int BindParameterIndex (Sqlite3Statement stmt, string name)
- {
- return Sqlite3.sqlite3_bind_parameter_index (stmt, name);
- }
- public static int BindNull (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_bind_null (stmt, index);
- }
- public static int BindInt (Sqlite3Statement stmt, int index, int val)
- {
- return Sqlite3.sqlite3_bind_int (stmt, index, val);
- }
- public static int BindInt64 (Sqlite3Statement stmt, int index, long val)
- {
- return Sqlite3.sqlite3_bind_int64 (stmt, index, val);
- }
- public static int BindDouble (Sqlite3Statement stmt, int index, double val)
- {
- return Sqlite3.sqlite3_bind_double (stmt, index, val);
- }
- public static int BindText (Sqlite3Statement stmt, int index, string val, int n, IntPtr free)
- {
- #if USE_WP8_NATIVE_SQLITE
- return Sqlite3.sqlite3_bind_text(stmt, index, val, n);
- #elif USE_SQLITEPCL_RAW
- return Sqlite3.sqlite3_bind_text (stmt, index, val);
- #else
- return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null);
- #endif
- }
- public static int BindBlob (Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free)
- {
- #if USE_WP8_NATIVE_SQLITE
- return Sqlite3.sqlite3_bind_blob(stmt, index, val, n);
- #elif USE_SQLITEPCL_RAW
- return Sqlite3.sqlite3_bind_blob (stmt, index, val);
- #else
- return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null);
- #endif
- }
- public static int ColumnCount (Sqlite3Statement stmt)
- {
- return Sqlite3.sqlite3_column_count (stmt);
- }
- public static string ColumnName (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
- }
- public static string ColumnName16 (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
- }
- public static ColType ColumnType (Sqlite3Statement stmt, int index)
- {
- return (ColType)Sqlite3.sqlite3_column_type (stmt, index);
- }
- public static int ColumnInt (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_int (stmt, index);
- }
- public static long ColumnInt64 (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_int64 (stmt, index);
- }
- public static double ColumnDouble (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_double (stmt, index);
- }
- public static string ColumnText (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
- }
- public static string ColumnText16 (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
- }
- public static byte[] ColumnBlob (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_blob (stmt, index).ToArray ();
- }
- public static int ColumnBytes (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_bytes (stmt, index);
- }
- public static string ColumnString (Sqlite3Statement stmt, int index)
- {
- return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
- }
- public static byte[] ColumnByteArray (Sqlite3Statement stmt, int index)
- {
- int length = ColumnBytes (stmt, index);
- if (length > 0) {
- return ColumnBlob (stmt, index);
- }
- return new byte[0];
- }
- public static Result EnableLoadExtension (Sqlite3DatabaseHandle db, int onoff)
- {
- return (Result)Sqlite3.sqlite3_enable_load_extension (db, onoff);
- }
- public static int LibVersionNumber ()
- {
- return Sqlite3.sqlite3_libversion_number ();
- }
- public static Result GetResult (Sqlite3DatabaseHandle db)
- {
- return (Result)Sqlite3.sqlite3_errcode (db);
- }
- public static ExtendedResult ExtendedErrCode (Sqlite3DatabaseHandle db)
- {
- return (ExtendedResult)Sqlite3.sqlite3_extended_errcode (db);
- }
- public static Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, string destName, Sqlite3DatabaseHandle sourceDb, string sourceName)
- {
- return Sqlite3.sqlite3_backup_init (destDb, destName, sourceDb, sourceName);
- }
- public static Result BackupStep (Sqlite3BackupHandle backup, int numPages)
- {
- return (Result)Sqlite3.sqlite3_backup_step (backup, numPages);
- }
- public static Result BackupFinish (Sqlite3BackupHandle backup)
- {
- return (Result)Sqlite3.sqlite3_backup_finish (backup);
- }
- #endif
- public enum ColType : int
- {
- Integer = 1,
- Float = 2,
- Text = 3,
- Blob = 4,
- Null = 5
- }
- }
- }
|