SQLite.cs 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279
  1. //
  2. // Copyright (c) 2009-2012 Krueger Systems, Inc.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
  23. #define USE_CSHARP_SQLITE
  24. #endif
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Diagnostics;
  28. using System.Linq;
  29. using System.Linq.Expressions;
  30. using System.Reflection;
  31. using System.Runtime.InteropServices;
  32. using System.Threading;
  33. #if USE_CSHARP_SQLITE
  34. using Sqlite3 = Community.CsharpSqlite.Sqlite3;
  35. using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
  36. using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
  37. #elif USE_WP8_NATIVE_SQLITE
  38. using Sqlite3 = Sqlite.Sqlite3;
  39. using Sqlite3DatabaseHandle = Sqlite.Database;
  40. using Sqlite3Statement = Sqlite.Statement;
  41. #else
  42. using Sqlite3DatabaseHandle = System.IntPtr;
  43. using Sqlite3Statement = System.IntPtr;
  44. #endif
  45. namespace SQLite
  46. {
  47. public class SQLiteException : Exception
  48. {
  49. public SQLite3.Result Result { get; private set; }
  50. protected SQLiteException (SQLite3.Result r,string message) : base(message)
  51. {
  52. Result = r;
  53. }
  54. public static SQLiteException New (SQLite3.Result r, string message)
  55. {
  56. return new SQLiteException (r, message);
  57. }
  58. }
  59. public class NotNullConstraintViolationException : SQLiteException
  60. {
  61. public IEnumerable<TableMapping.Column> Columns { get; protected set; }
  62. protected NotNullConstraintViolationException (SQLite3.Result r, string message)
  63. : this (r, message, null, null)
  64. {
  65. }
  66. protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
  67. : base (r, message)
  68. {
  69. if (mapping != null && obj != null) {
  70. this.Columns = from c in mapping.Columns
  71. where c.IsNullable == false && c.GetValue (obj) == null
  72. select c;
  73. }
  74. }
  75. public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
  76. {
  77. return new NotNullConstraintViolationException (r, message);
  78. }
  79. public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
  80. {
  81. return new NotNullConstraintViolationException (r, message, mapping, obj);
  82. }
  83. public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
  84. {
  85. return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
  86. }
  87. }
  88. [Flags]
  89. public enum SQLiteOpenFlags {
  90. ReadOnly = 1, ReadWrite = 2, Create = 4,
  91. NoMutex = 0x8000, FullMutex = 0x10000,
  92. SharedCache = 0x20000, PrivateCache = 0x40000,
  93. ProtectionComplete = 0x00100000,
  94. ProtectionCompleteUnlessOpen = 0x00200000,
  95. ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
  96. ProtectionNone = 0x00400000
  97. }
  98. [Flags]
  99. public enum CreateFlags
  100. {
  101. None = 0,
  102. ImplicitPK = 1, // create a primary key for field called 'Id' (Orm.ImplicitPkName)
  103. ImplicitIndex = 2, // create an index for fields ending in 'Id' (Orm.ImplicitIndexSuffix)
  104. AllImplicit = 3, // do both above
  105. AutoIncPK = 4 // force PK field to be auto inc
  106. }
  107. /// <summary>
  108. /// Represents an open connection to a SQLite database.
  109. /// </summary>
  110. public partial class SQLiteConnection : IDisposable
  111. {
  112. private bool _open;
  113. private TimeSpan _busyTimeout;
  114. private Dictionary<string, TableMapping> _mappings = null;
  115. private Dictionary<string, TableMapping> _tables = null;
  116. private System.Diagnostics.Stopwatch _sw;
  117. private long _elapsedMilliseconds = 0;
  118. private int _transactionDepth = 0;
  119. private Random _rand = new Random ();
  120. public Sqlite3DatabaseHandle Handle { get; private set; }
  121. internal static readonly Sqlite3DatabaseHandle NullHandle = default(Sqlite3DatabaseHandle);
  122. public string DatabasePath { get; private set; }
  123. public bool TimeExecution { get; set; }
  124. public bool Trace { get; set; }
  125. public bool StoreDateTimeAsTicks { get; private set; }
  126. /// <summary>
  127. /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
  128. /// </summary>
  129. /// <param name="databasePath">
  130. /// Specifies the path to the database file.
  131. /// </param>
  132. /// <param name="storeDateTimeAsTicks">
  133. /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
  134. /// absolutely do want to store them as Ticks in all new projects. The default of false is
  135. /// only here for backwards compatibility. There is a *significant* speed advantage, with no
  136. /// down sides, when setting storeDateTimeAsTicks = true.
  137. /// </param>
  138. public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false)
  139. : this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
  140. {
  141. }
  142. /// <summary>
  143. /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
  144. /// </summary>
  145. /// <param name="databasePath">
  146. /// Specifies the path to the database file.
  147. /// </param>
  148. /// <param name="storeDateTimeAsTicks">
  149. /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
  150. /// absolutely do want to store them as Ticks in all new projects. The default of false is
  151. /// only here for backwards compatibility. There is a *significant* speed advantage, with no
  152. /// down sides, when setting storeDateTimeAsTicks = true.
  153. /// </param>
  154. public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
  155. {
  156. if (string.IsNullOrEmpty (databasePath))
  157. throw new ArgumentException ("Must be specified", "databasePath");
  158. DatabasePath = databasePath;
  159. #if NETFX_CORE
  160. SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
  161. #endif
  162. Sqlite3DatabaseHandle handle;
  163. #if SILVERLIGHT || USE_CSHARP_SQLITE
  164. var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero);
  165. #else
  166. // open using the byte[]
  167. // in the case where the path may include Unicode
  168. // force open to using UTF-8 using sqlite3_open_v2
  169. var databasePathAsBytes = GetNullTerminatedUtf8 (DatabasePath);
  170. var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero);
  171. #endif
  172. Handle = handle;
  173. if (r != SQLite3.Result.OK) {
  174. throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
  175. }
  176. _open = true;
  177. StoreDateTimeAsTicks = storeDateTimeAsTicks;
  178. BusyTimeout = TimeSpan.FromSeconds (0.1);
  179. }
  180. static SQLiteConnection ()
  181. {
  182. if (_preserveDuringLinkMagic) {
  183. var ti = new ColumnInfo ();
  184. ti.Name = "magic";
  185. }
  186. }
  187. public void EnableLoadExtension(int onoff)
  188. {
  189. SQLite3.Result r = SQLite3.EnableLoadExtension(Handle, onoff);
  190. if (r != SQLite3.Result.OK) {
  191. string msg = SQLite3.GetErrmsg (Handle);
  192. throw SQLiteException.New (r, msg);
  193. }
  194. }
  195. static byte[] GetNullTerminatedUtf8 (string s)
  196. {
  197. var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
  198. var bytes = new byte [utf8Length + 1];
  199. utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
  200. return bytes;
  201. }
  202. /// <summary>
  203. /// Used to list some code that we want the MonoTouch linker
  204. /// to see, but that we never want to actually execute.
  205. /// </summary>
  206. #pragma warning disable 649
  207. static bool _preserveDuringLinkMagic;
  208. #pragma warning restore 649
  209. /// <summary>
  210. /// Sets a busy handler to sleep the specified amount of time when a table is locked.
  211. /// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated.
  212. /// </summary>
  213. public TimeSpan BusyTimeout {
  214. get { return _busyTimeout; }
  215. set {
  216. _busyTimeout = value;
  217. if (Handle != NullHandle) {
  218. SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Returns the mappings from types to tables that the connection
  224. /// currently understands.
  225. /// </summary>
  226. public IEnumerable<TableMapping> TableMappings {
  227. get {
  228. return _tables != null ? _tables.Values : Enumerable.Empty<TableMapping> ();
  229. }
  230. }
  231. /// <summary>
  232. /// Retrieves the mapping that is automatically generated for the given type.
  233. /// </summary>
  234. /// <param name="type">
  235. /// The type whose mapping to the database is returned.
  236. /// </param>
  237. /// <param name="createFlags">
  238. /// Optional flags allowing implicit PK and indexes based on naming conventions
  239. /// </param>
  240. /// <returns>
  241. /// The mapping represents the schema of the columns of the database and contains
  242. /// methods to set and get properties of objects.
  243. /// </returns>
  244. public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None)
  245. {
  246. if (_mappings == null) {
  247. _mappings = new Dictionary<string, TableMapping> ();
  248. }
  249. TableMapping map;
  250. if (!_mappings.TryGetValue (type.FullName, out map)) {
  251. map = new TableMapping (type, createFlags);
  252. _mappings [type.FullName] = map;
  253. }
  254. return map;
  255. }
  256. /// <summary>
  257. /// Retrieves the mapping that is automatically generated for the given type.
  258. /// </summary>
  259. /// <returns>
  260. /// The mapping represents the schema of the columns of the database and contains
  261. /// methods to set and get properties of objects.
  262. /// </returns>
  263. public TableMapping GetMapping<T> ()
  264. {
  265. return GetMapping (typeof (T));
  266. }
  267. private struct IndexedColumn
  268. {
  269. public int Order;
  270. public string ColumnName;
  271. }
  272. private struct IndexInfo
  273. {
  274. public string IndexName;
  275. public string TableName;
  276. public bool Unique;
  277. public List<IndexedColumn> Columns;
  278. }
  279. /// <summary>
  280. /// Executes a "drop table" on the database. This is non-recoverable.
  281. /// </summary>
  282. public int DropTable<T>()
  283. {
  284. var map = GetMapping (typeof (T));
  285. var query = string.Format("drop table if exists \"{0}\"", map.TableName);
  286. return Execute (query);
  287. }
  288. /// <summary>
  289. /// Executes a "create table if not exists" on the database. It also
  290. /// creates any specified indexes on the columns of the table. It uses
  291. /// a schema automatically generated from the specified type. You can
  292. /// later access this schema by calling GetMapping.
  293. /// </summary>
  294. /// <returns>
  295. /// The number of entries added to the database schema.
  296. /// </returns>
  297. public int CreateTable<T>(CreateFlags createFlags = CreateFlags.None)
  298. {
  299. return CreateTable(typeof (T), createFlags);
  300. }
  301. /// <summary>
  302. /// Executes a "create table if not exists" on the database. It also
  303. /// creates any specified indexes on the columns of the table. It uses
  304. /// a schema automatically generated from the specified type. You can
  305. /// later access this schema by calling GetMapping.
  306. /// </summary>
  307. /// <param name="ty">Type to reflect to a database table.</param>
  308. /// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
  309. /// <returns>
  310. /// The number of entries added to the database schema.
  311. /// </returns>
  312. public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None)
  313. {
  314. if (_tables == null) {
  315. _tables = new Dictionary<string, TableMapping> ();
  316. }
  317. TableMapping map;
  318. if (!_tables.TryGetValue (ty.FullName, out map)) {
  319. map = GetMapping (ty, createFlags);
  320. _tables.Add (ty.FullName, map);
  321. }
  322. var query = "create table if not exists \"" + map.TableName + "\"(\n";
  323. var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks));
  324. var decl = string.Join (",\n", decls.ToArray ());
  325. query += decl;
  326. query += ")";
  327. var count = Execute (query);
  328. if (count == 0) { //Possible bug: This always seems to return 0?
  329. // Table already exists, migrate it
  330. MigrateTable (map);
  331. }
  332. var indexes = new Dictionary<string, IndexInfo> ();
  333. foreach (var c in map.Columns) {
  334. foreach (var i in c.Indices) {
  335. var iname = i.Name ?? map.TableName + "_" + c.Name;
  336. IndexInfo iinfo;
  337. if (!indexes.TryGetValue (iname, out iinfo)) {
  338. iinfo = new IndexInfo {
  339. IndexName = iname,
  340. TableName = map.TableName,
  341. Unique = i.Unique,
  342. Columns = new List<IndexedColumn> ()
  343. };
  344. indexes.Add (iname, iinfo);
  345. }
  346. if (i.Unique != iinfo.Unique)
  347. throw new Exception ("All the columns in an index must have the same value for their Unique property");
  348. iinfo.Columns.Add (new IndexedColumn {
  349. Order = i.Order,
  350. ColumnName = c.Name
  351. });
  352. }
  353. }
  354. foreach (var indexName in indexes.Keys) {
  355. var index = indexes[indexName];
  356. var columns = index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray();
  357. count += CreateIndex(indexName, index.TableName, columns, index.Unique);
  358. }
  359. return count;
  360. }
  361. /// <summary>
  362. /// Creates an index for the specified table and columns.
  363. /// </summary>
  364. /// <param name="indexName">Name of the index to create</param>
  365. /// <param name="tableName">Name of the database table</param>
  366. /// <param name="columnNames">An array of column names to index</param>
  367. /// <param name="unique">Whether the index should be unique</param>
  368. public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false)
  369. {
  370. const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
  371. var sql = String.Format(sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
  372. return Execute(sql);
  373. }
  374. /// <summary>
  375. /// Creates an index for the specified table and column.
  376. /// </summary>
  377. /// <param name="indexName">Name of the index to create</param>
  378. /// <param name="tableName">Name of the database table</param>
  379. /// <param name="columnName">Name of the column to index</param>
  380. /// <param name="unique">Whether the index should be unique</param>
  381. public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false)
  382. {
  383. return CreateIndex(indexName, tableName, new string[] { columnName }, unique);
  384. }
  385. /// <summary>
  386. /// Creates an index for the specified table and column.
  387. /// </summary>
  388. /// <param name="tableName">Name of the database table</param>
  389. /// <param name="columnName">Name of the column to index</param>
  390. /// <param name="unique">Whether the index should be unique</param>
  391. public int CreateIndex(string tableName, string columnName, bool unique = false)
  392. {
  393. return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique);
  394. }
  395. /// <summary>
  396. /// Creates an index for the specified table and columns.
  397. /// </summary>
  398. /// <param name="tableName">Name of the database table</param>
  399. /// <param name="columnNames">An array of column names to index</param>
  400. /// <param name="unique">Whether the index should be unique</param>
  401. public int CreateIndex(string tableName, string[] columnNames, bool unique = false)
  402. {
  403. return CreateIndex(tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
  404. }
  405. /// <summary>
  406. /// Creates an index for the specified object property.
  407. /// e.g. CreateIndex<Client>(c => c.Name);
  408. /// </summary>
  409. /// <typeparam name="T">Type to reflect to a database table.</typeparam>
  410. /// <param name="property">Property to index</param>
  411. /// <param name="unique">Whether the index should be unique</param>
  412. public void CreateIndex<T>(Expression<Func<T, object>> property, bool unique = false)
  413. {
  414. MemberExpression mx;
  415. if (property.Body.NodeType == ExpressionType.Convert)
  416. {
  417. mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
  418. }
  419. else
  420. {
  421. mx= (property.Body as MemberExpression);
  422. }
  423. var propertyInfo = mx.Member as PropertyInfo;
  424. if (propertyInfo == null)
  425. {
  426. throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
  427. }
  428. var propName = propertyInfo.Name;
  429. var map = GetMapping<T>();
  430. var colName = map.FindColumnWithPropertyName(propName).Name;
  431. CreateIndex(map.TableName, colName, unique);
  432. }
  433. public class ColumnInfo
  434. {
  435. // public int cid { get; set; }
  436. [Column ("name")]
  437. public string Name { get; set; }
  438. // [Column ("type")]
  439. // public string ColumnType { get; set; }
  440. public int notnull { get; set; }
  441. // public string dflt_value { get; set; }
  442. // public int pk { get; set; }
  443. public override string ToString ()
  444. {
  445. return Name;
  446. }
  447. }
  448. public List<ColumnInfo> GetTableInfo (string tableName)
  449. {
  450. var query = "pragma table_info(\"" + tableName + "\")";
  451. return Query<ColumnInfo> (query);
  452. }
  453. void MigrateTable (TableMapping map)
  454. {
  455. var existingCols = GetTableInfo (map.TableName);
  456. var toBeAdded = new List<TableMapping.Column> ();
  457. foreach (var p in map.Columns) {
  458. var found = false;
  459. foreach (var c in existingCols) {
  460. found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
  461. if (found)
  462. break;
  463. }
  464. if (!found) {
  465. toBeAdded.Add (p);
  466. }
  467. }
  468. foreach (var p in toBeAdded) {
  469. var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks);
  470. Execute (addCol);
  471. }
  472. }
  473. /// <summary>
  474. /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
  475. /// </summary>
  476. /// <seealso cref="SQLiteCommand.OnInstanceCreated"/>
  477. protected virtual SQLiteCommand NewCommand ()
  478. {
  479. return new SQLiteCommand (this);
  480. }
  481. /// <summary>
  482. /// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
  483. /// in the command text for each of the arguments.
  484. /// </summary>
  485. /// <param name="cmdText">
  486. /// The fully escaped SQL.
  487. /// </param>
  488. /// <param name="args">
  489. /// Arguments to substitute for the occurences of '?' in the command text.
  490. /// </param>
  491. /// <returns>
  492. /// A <see cref="SQLiteCommand"/>
  493. /// </returns>
  494. public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
  495. {
  496. if (!_open)
  497. throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
  498. var cmd = NewCommand ();
  499. cmd.CommandText = cmdText;
  500. foreach (var o in ps) {
  501. cmd.Bind (o);
  502. }
  503. return cmd;
  504. }
  505. /// <summary>
  506. /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
  507. /// in the command text for each of the arguments and then executes that command.
  508. /// Use this method instead of Query when you don't expect rows back. Such cases include
  509. /// INSERTs, UPDATEs, and DELETEs.
  510. /// You can set the Trace or TimeExecution properties of the connection
  511. /// to profile execution.
  512. /// </summary>
  513. /// <param name="query">
  514. /// The fully escaped SQL.
  515. /// </param>
  516. /// <param name="args">
  517. /// Arguments to substitute for the occurences of '?' in the query.
  518. /// </param>
  519. /// <returns>
  520. /// The number of rows modified in the database as a result of this execution.
  521. /// </returns>
  522. public int Execute (string query, params object[] args)
  523. {
  524. var cmd = CreateCommand (query, args);
  525. if (TimeExecution) {
  526. if (_sw == null) {
  527. _sw = new Stopwatch ();
  528. }
  529. _sw.Reset ();
  530. _sw.Start ();
  531. }
  532. var r = cmd.ExecuteNonQuery ();
  533. if (TimeExecution) {
  534. _sw.Stop ();
  535. _elapsedMilliseconds += _sw.ElapsedMilliseconds;
  536. Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
  537. }
  538. return r;
  539. }
  540. public T ExecuteScalar<T> (string query, params object[] args)
  541. {
  542. var cmd = CreateCommand (query, args);
  543. if (TimeExecution) {
  544. if (_sw == null) {
  545. _sw = new Stopwatch ();
  546. }
  547. _sw.Reset ();
  548. _sw.Start ();
  549. }
  550. var r = cmd.ExecuteScalar<T> ();
  551. if (TimeExecution) {
  552. _sw.Stop ();
  553. _elapsedMilliseconds += _sw.ElapsedMilliseconds;
  554. Debug.WriteLine (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
  555. }
  556. return r;
  557. }
  558. /// <summary>
  559. /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
  560. /// in the command text for each of the arguments and then executes that command.
  561. /// It returns each row of the result using the mapping automatically generated for
  562. /// the given type.
  563. /// </summary>
  564. /// <param name="query">
  565. /// The fully escaped SQL.
  566. /// </param>
  567. /// <param name="args">
  568. /// Arguments to substitute for the occurences of '?' in the query.
  569. /// </param>
  570. /// <returns>
  571. /// An enumerable with one result for each row returned by the query.
  572. /// </returns>
  573. public List<T> Query<T> (string query, params object[] args) where T : new()
  574. {
  575. var cmd = CreateCommand (query, args);
  576. return cmd.ExecuteQuery<T> ();
  577. }
  578. /// <summary>
  579. /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
  580. /// in the command text for each of the arguments and then executes that command.
  581. /// It returns each row of the result using the mapping automatically generated for
  582. /// the given type.
  583. /// </summary>
  584. /// <param name="query">
  585. /// The fully escaped SQL.
  586. /// </param>
  587. /// <param name="args">
  588. /// Arguments to substitute for the occurences of '?' in the query.
  589. /// </param>
  590. /// <returns>
  591. /// An enumerable with one result for each row returned by the query.
  592. /// The enumerator will call sqlite3_step on each call to MoveNext, so the database
  593. /// connection must remain open for the lifetime of the enumerator.
  594. /// </returns>
  595. public IEnumerable<T> DeferredQuery<T>(string query, params object[] args) where T : new()
  596. {
  597. var cmd = CreateCommand(query, args);
  598. return cmd.ExecuteDeferredQuery<T>();
  599. }
  600. /// <summary>
  601. /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
  602. /// in the command text for each of the arguments and then executes that command.
  603. /// It returns each row of the result using the specified mapping. This function is
  604. /// only used by libraries in order to query the database via introspection. It is
  605. /// normally not used.
  606. /// </summary>
  607. /// <param name="map">
  608. /// A <see cref="TableMapping"/> to use to convert the resulting rows
  609. /// into objects.
  610. /// </param>
  611. /// <param name="query">
  612. /// The fully escaped SQL.
  613. /// </param>
  614. /// <param name="args">
  615. /// Arguments to substitute for the occurences of '?' in the query.
  616. /// </param>
  617. /// <returns>
  618. /// An enumerable with one result for each row returned by the query.
  619. /// </returns>
  620. public List<object> Query (TableMapping map, string query, params object[] args)
  621. {
  622. var cmd = CreateCommand (query, args);
  623. return cmd.ExecuteQuery<object> (map);
  624. }
  625. /// <summary>
  626. /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
  627. /// in the command text for each of the arguments and then executes that command.
  628. /// It returns each row of the result using the specified mapping. This function is
  629. /// only used by libraries in order to query the database via introspection. It is
  630. /// normally not used.
  631. /// </summary>
  632. /// <param name="map">
  633. /// A <see cref="TableMapping"/> to use to convert the resulting rows
  634. /// into objects.
  635. /// </param>
  636. /// <param name="query">
  637. /// The fully escaped SQL.
  638. /// </param>
  639. /// <param name="args">
  640. /// Arguments to substitute for the occurences of '?' in the query.
  641. /// </param>
  642. /// <returns>
  643. /// An enumerable with one result for each row returned by the query.
  644. /// The enumerator will call sqlite3_step on each call to MoveNext, so the database
  645. /// connection must remain open for the lifetime of the enumerator.
  646. /// </returns>
  647. public IEnumerable<object> DeferredQuery(TableMapping map, string query, params object[] args)
  648. {
  649. var cmd = CreateCommand(query, args);
  650. return cmd.ExecuteDeferredQuery<object>(map);
  651. }
  652. /// <summary>
  653. /// Returns a queryable interface to the table represented by the given type.
  654. /// </summary>
  655. /// <returns>
  656. /// A queryable object that is able to translate Where, OrderBy, and Take
  657. /// queries into native SQL.
  658. /// </returns>
  659. public TableQuery<T> Table<T> () where T : new()
  660. {
  661. return new TableQuery<T> (this);
  662. }
  663. /// <summary>
  664. /// Attempts to retrieve an object with the given primary key from the table
  665. /// associated with the specified type. Use of this method requires that
  666. /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
  667. /// </summary>
  668. /// <param name="pk">
  669. /// The primary key.
  670. /// </param>
  671. /// <returns>
  672. /// The object with the given primary key. Throws a not found exception
  673. /// if the object is not found.
  674. /// </returns>
  675. public T Get<T> (object pk) where T : new()
  676. {
  677. var map = GetMapping (typeof(T));
  678. return Query<T> (map.GetByPrimaryKeySql, pk).First ();
  679. }
  680. /// <summary>
  681. /// Attempts to retrieve the first object that matches the predicate from the table
  682. /// associated with the specified type.
  683. /// </summary>
  684. /// <param name="predicate">
  685. /// A predicate for which object to find.
  686. /// </param>
  687. /// <returns>
  688. /// The object that matches the given predicate. Throws a not found exception
  689. /// if the object is not found.
  690. /// </returns>
  691. public T Get<T> (Expression<Func<T, bool>> predicate) where T : new()
  692. {
  693. return Table<T> ().Where (predicate).First ();
  694. }
  695. /// <summary>
  696. /// Attempts to retrieve an object with the given primary key from the table
  697. /// associated with the specified type. Use of this method requires that
  698. /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
  699. /// </summary>
  700. /// <param name="pk">
  701. /// The primary key.
  702. /// </param>
  703. /// <returns>
  704. /// The object with the given primary key or null
  705. /// if the object is not found.
  706. /// </returns>
  707. public T Find<T> (object pk) where T : new ()
  708. {
  709. var map = GetMapping (typeof (T));
  710. return Query<T> (map.GetByPrimaryKeySql, pk).FirstOrDefault ();
  711. }
  712. /// <summary>
  713. /// Attempts to retrieve an object with the given primary key from the table
  714. /// associated with the specified type. Use of this method requires that
  715. /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
  716. /// </summary>
  717. /// <param name="pk">
  718. /// The primary key.
  719. /// </param>
  720. /// <param name="map">
  721. /// The TableMapping used to identify the object type.
  722. /// </param>
  723. /// <returns>
  724. /// The object with the given primary key or null
  725. /// if the object is not found.
  726. /// </returns>
  727. public object Find (object pk, TableMapping map)
  728. {
  729. return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault ();
  730. }
  731. /// <summary>
  732. /// Attempts to retrieve the first object that matches the predicate from the table
  733. /// associated with the specified type.
  734. /// </summary>
  735. /// <param name="predicate">
  736. /// A predicate for which object to find.
  737. /// </param>
  738. /// <returns>
  739. /// The object that matches the given predicate or null
  740. /// if the object is not found.
  741. /// </returns>
  742. public T Find<T> (Expression<Func<T, bool>> predicate) where T : new()
  743. {
  744. return Table<T> ().Where (predicate).FirstOrDefault ();
  745. }
  746. /// <summary>
  747. /// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>.
  748. /// </summary>
  749. public bool IsInTransaction {
  750. get { return _transactionDepth > 0; }
  751. }
  752. /// <summary>
  753. /// Begins a new transaction. Call <see cref="Commit"/> to end the transaction.
  754. /// </summary>
  755. /// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example>
  756. public void BeginTransaction ()
  757. {
  758. // The BEGIN command only works if the transaction stack is empty,
  759. // or in other words if there are no pending transactions.
  760. // If the transaction stack is not empty when the BEGIN command is invoked,
  761. // then the command fails with an error.
  762. // Rather than crash with an error, we will just ignore calls to BeginTransaction
  763. // that would result in an error.
  764. if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) {
  765. try {
  766. Execute ("begin transaction");
  767. } catch (Exception ex) {
  768. var sqlExp = ex as SQLiteException;
  769. if (sqlExp != null) {
  770. // It is recommended that applications respond to the errors listed below
  771. // by explicitly issuing a ROLLBACK command.
  772. // TODO: This rollback failsafe should be localized to all throw sites.
  773. switch (sqlExp.Result) {
  774. case SQLite3.Result.IOError:
  775. case SQLite3.Result.Full:
  776. case SQLite3.Result.Busy:
  777. case SQLite3.Result.NoMem:
  778. case SQLite3.Result.Interrupt:
  779. RollbackTo (null, true);
  780. break;
  781. }
  782. } else {
  783. // Call decrement and not VolatileWrite in case we've already
  784. // created a transaction point in SaveTransactionPoint since the catch.
  785. Interlocked.Decrement (ref _transactionDepth);
  786. }
  787. throw;
  788. }
  789. } else {
  790. // Calling BeginTransaction on an already open transaction is invalid
  791. throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction.");
  792. }
  793. }
  794. /// <summary>
  795. /// Creates a savepoint in the database at the current point in the transaction timeline.
  796. /// Begins a new transaction if one is not in progress.
  797. ///
  798. /// Call <see cref="RollbackTo"/> to undo transactions since the returned savepoint.
  799. /// Call <see cref="Release"/> to commit transactions after the savepoint returned here.
  800. /// Call <see cref="Commit"/> to end the transaction, committing all changes.
  801. /// </summary>
  802. /// <returns>A string naming the savepoint.</returns>
  803. public string SaveTransactionPoint ()
  804. {
  805. int depth = Interlocked.Increment (ref _transactionDepth) - 1;
  806. string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth;
  807. try {
  808. Execute ("savepoint " + retVal);
  809. } catch (Exception ex) {
  810. var sqlExp = ex as SQLiteException;
  811. if (sqlExp != null) {
  812. // It is recommended that applications respond to the errors listed below
  813. // by explicitly issuing a ROLLBACK command.
  814. // TODO: This rollback failsafe should be localized to all throw sites.
  815. switch (sqlExp.Result) {
  816. case SQLite3.Result.IOError:
  817. case SQLite3.Result.Full:
  818. case SQLite3.Result.Busy:
  819. case SQLite3.Result.NoMem:
  820. case SQLite3.Result.Interrupt:
  821. RollbackTo (null, true);
  822. break;
  823. }
  824. } else {
  825. Interlocked.Decrement (ref _transactionDepth);
  826. }
  827. throw;
  828. }
  829. return retVal;
  830. }
  831. /// <summary>
  832. /// Rolls back the transaction that was begun by <see cref="BeginTransaction"/> or <see cref="SaveTransactionPoint"/>.
  833. /// </summary>
  834. public void Rollback ()
  835. {
  836. RollbackTo (null, false);
  837. }
  838. /// <summary>
  839. /// Rolls back the savepoint created by <see cref="BeginTransaction"/> or SaveTransactionPoint.
  840. /// </summary>
  841. /// <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>
  842. public void RollbackTo (string savepoint)
  843. {
  844. RollbackTo (savepoint, false);
  845. }
  846. /// <summary>
  847. /// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>.
  848. /// </summary>
  849. /// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param>
  850. void RollbackTo (string savepoint, bool noThrow)
  851. {
  852. // Rolling back without a TO clause rolls backs all transactions
  853. // and leaves the transaction stack empty.
  854. try {
  855. if (String.IsNullOrEmpty (savepoint)) {
  856. if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) {
  857. Execute ("rollback");
  858. }
  859. } else {
  860. DoSavePointExecute (savepoint, "rollback to ");
  861. }
  862. } catch (SQLiteException) {
  863. if (!noThrow)
  864. throw;
  865. }
  866. // No need to rollback if there are no transactions open.
  867. }
  868. /// <summary>
  869. /// Releases a savepoint returned from <see cref="SaveTransactionPoint"/>. Releasing a savepoint
  870. /// makes changes since that savepoint permanent if the savepoint began the transaction,
  871. /// or otherwise the changes are permanent pending a call to <see cref="Commit"/>.
  872. ///
  873. /// The RELEASE command is like a COMMIT for a SAVEPOINT.
  874. /// </summary>
  875. /// <param name="savepoint">The name of the savepoint to release. The string should be the result of a call to <see cref="SaveTransactionPoint"/></param>
  876. public void Release (string savepoint)
  877. {
  878. DoSavePointExecute (savepoint, "release ");
  879. }
  880. void DoSavePointExecute (string savepoint, string cmd)
  881. {
  882. // Validate the savepoint
  883. int firstLen = savepoint.IndexOf ('D');
  884. if (firstLen >= 2 && savepoint.Length > firstLen + 1) {
  885. int depth;
  886. if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) {
  887. // TODO: Mild race here, but inescapable without locking almost everywhere.
  888. if (0 <= depth && depth < _transactionDepth) {
  889. #if NETFX_CORE
  890. Volatile.Write (ref _transactionDepth, depth);
  891. #elif SILVERLIGHT
  892. _transactionDepth = depth;
  893. #else
  894. Thread.VolatileWrite (ref _transactionDepth, depth);
  895. #endif
  896. Execute (cmd + savepoint);
  897. return;
  898. }
  899. }
  900. }
  901. throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint");
  902. }
  903. /// <summary>
  904. /// Commits the transaction that was begun by <see cref="BeginTransaction"/>.
  905. /// </summary>
  906. public void Commit ()
  907. {
  908. if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) {
  909. Execute ("commit");
  910. }
  911. // Do nothing on a commit with no open transaction
  912. }
  913. /// <summary>
  914. /// Executes <param name="action"> within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an
  915. /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception
  916. /// is rethrown.
  917. /// </summary>
  918. /// <param name="action">
  919. /// The <see cref="Action"/> to perform within a transaction. <param name="action"> can contain any number
  920. /// of operations on the connection but should never call <see cref="BeginTransaction"/> or
  921. /// <see cref="Commit"/>.
  922. /// </param>
  923. public void RunInTransaction (Action action)
  924. {
  925. try {
  926. var savePoint = SaveTransactionPoint ();
  927. action ();
  928. Release (savePoint);
  929. } catch (Exception) {
  930. Rollback ();
  931. throw;
  932. }
  933. }
  934. /// <summary>
  935. /// Inserts all specified objects.
  936. /// </summary>
  937. /// <param name="objects">
  938. /// An <see cref="IEnumerable"/> of the objects to insert.
  939. /// </param>
  940. /// <returns>
  941. /// The number of rows added to the table.
  942. /// </returns>
  943. public int InsertAll (System.Collections.IEnumerable objects)
  944. {
  945. var c = 0;
  946. RunInTransaction(() => {
  947. foreach (var r in objects) {
  948. c += Insert (r);
  949. }
  950. });
  951. return c;
  952. }
  953. /// <summary>
  954. /// Inserts all specified objects.
  955. /// </summary>
  956. /// <param name="objects">
  957. /// An <see cref="IEnumerable"/> of the objects to insert.
  958. /// </param>
  959. /// <param name="extra">
  960. /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
  961. /// </param>
  962. /// <returns>
  963. /// The number of rows added to the table.
  964. /// </returns>
  965. public int InsertAll (System.Collections.IEnumerable objects, string extra)
  966. {
  967. var c = 0;
  968. RunInTransaction (() => {
  969. foreach (var r in objects) {
  970. c += Insert (r, extra);
  971. }
  972. });
  973. return c;
  974. }
  975. /// <summary>
  976. /// Inserts all specified objects.
  977. /// </summary>
  978. /// <param name="objects">
  979. /// An <see cref="IEnumerable"/> of the objects to insert.
  980. /// </param>
  981. /// <param name="objType">
  982. /// The type of object to insert.
  983. /// </param>
  984. /// <returns>
  985. /// The number of rows added to the table.
  986. /// </returns>
  987. public int InsertAll (System.Collections.IEnumerable objects, Type objType)
  988. {
  989. var c = 0;
  990. RunInTransaction (() => {
  991. foreach (var r in objects) {
  992. c += Insert (r, objType);
  993. }
  994. });
  995. return c;
  996. }
  997. /// <summary>
  998. /// Inserts the given object and retrieves its
  999. /// auto incremented primary key if it has one.
  1000. /// </summary>
  1001. /// <param name="obj">
  1002. /// The object to insert.
  1003. /// </param>
  1004. /// <returns>
  1005. /// The number of rows added to the table.
  1006. /// </returns>
  1007. public int Insert (object obj)
  1008. {
  1009. if (obj == null) {
  1010. return 0;
  1011. }
  1012. return Insert (obj, "", obj.GetType ());
  1013. }
  1014. /// <summary>
  1015. /// Inserts the given object and retrieves its
  1016. /// auto incremented primary key if it has one.
  1017. /// If a UNIQUE constraint violation occurs with
  1018. /// some pre-existing object, this function deletes
  1019. /// the old object.
  1020. /// </summary>
  1021. /// <param name="obj">
  1022. /// The object to insert.
  1023. /// </param>
  1024. /// <returns>
  1025. /// The number of rows modified.
  1026. /// </returns>
  1027. public int InsertOrReplace (object obj)
  1028. {
  1029. if (obj == null) {
  1030. return 0;
  1031. }
  1032. return Insert (obj, "OR REPLACE", obj.GetType ());
  1033. }
  1034. /// <summary>
  1035. /// Inserts the given object and retrieves its
  1036. /// auto incremented primary key if it has one.
  1037. /// </summary>
  1038. /// <param name="obj">
  1039. /// The object to insert.
  1040. /// </param>
  1041. /// <param name="objType">
  1042. /// The type of object to insert.
  1043. /// </param>
  1044. /// <returns>
  1045. /// The number of rows added to the table.
  1046. /// </returns>
  1047. public int Insert (object obj, Type objType)
  1048. {
  1049. return Insert (obj, "", objType);
  1050. }
  1051. /// <summary>
  1052. /// Inserts the given object and retrieves its
  1053. /// auto incremented primary key if it has one.
  1054. /// If a UNIQUE constraint violation occurs with
  1055. /// some pre-existing object, this function deletes
  1056. /// the old object.
  1057. /// </summary>
  1058. /// <param name="obj">
  1059. /// The object to insert.
  1060. /// </param>
  1061. /// <param name="objType">
  1062. /// The type of object to insert.
  1063. /// </param>
  1064. /// <returns>
  1065. /// The number of rows modified.
  1066. /// </returns>
  1067. public int InsertOrReplace (object obj, Type objType)
  1068. {
  1069. return Insert (obj, "OR REPLACE", objType);
  1070. }
  1071. /// <summary>
  1072. /// Inserts the given object and retrieves its
  1073. /// auto incremented primary key if it has one.
  1074. /// </summary>
  1075. /// <param name="obj">
  1076. /// The object to insert.
  1077. /// </param>
  1078. /// <param name="extra">
  1079. /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
  1080. /// </param>
  1081. /// <returns>
  1082. /// The number of rows added to the table.
  1083. /// </returns>
  1084. public int Insert (object obj, string extra)
  1085. {
  1086. if (obj == null) {
  1087. return 0;
  1088. }
  1089. return Insert (obj, extra, obj.GetType ());
  1090. }
  1091. /// <summary>
  1092. /// Inserts the given object and retrieves its
  1093. /// auto incremented primary key if it has one.
  1094. /// </summary>
  1095. /// <param name="obj">
  1096. /// The object to insert.
  1097. /// </param>
  1098. /// <param name="extra">
  1099. /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
  1100. /// </param>
  1101. /// <param name="objType">
  1102. /// The type of object to insert.
  1103. /// </param>
  1104. /// <returns>
  1105. /// The number of rows added to the table.
  1106. /// </returns>
  1107. public int Insert (object obj, string extra, Type objType)
  1108. {
  1109. if (obj == null || objType == null) {
  1110. return 0;
  1111. }
  1112. var map = GetMapping (objType);
  1113. #if NETFX_CORE
  1114. if (map.PK != null && map.PK.IsAutoGuid)
  1115. {
  1116. // no GetProperty so search our way up the inheritance chain till we find it
  1117. PropertyInfo prop;
  1118. while (objType != null)
  1119. {
  1120. var info = objType.GetTypeInfo();
  1121. prop = info.GetDeclaredProperty(map.PK.PropertyName);
  1122. if (prop != null)
  1123. {
  1124. if (prop.GetValue(obj, null).Equals(Guid.Empty))
  1125. {
  1126. prop.SetValue(obj, Guid.NewGuid(), null);
  1127. }
  1128. break;
  1129. }
  1130. objType = info.BaseType;
  1131. }
  1132. }
  1133. #else
  1134. if (map.PK != null && map.PK.IsAutoGuid) {
  1135. var prop = objType.GetProperty(map.PK.PropertyName);
  1136. if (prop != null) {
  1137. if (prop.GetValue(obj, null).Equals(Guid.Empty)) {
  1138. prop.SetValue(obj, Guid.NewGuid(), null);
  1139. }
  1140. }
  1141. }
  1142. #endif
  1143. var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
  1144. var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns;
  1145. var vals = new object[cols.Length];
  1146. for (var i = 0; i < vals.Length; i++) {
  1147. vals [i] = cols [i].GetValue (obj);
  1148. }
  1149. var insertCmd = map.GetInsertCommand (this, extra);
  1150. int count;
  1151. try {
  1152. count = insertCmd.ExecuteNonQuery (vals);
  1153. }
  1154. catch (SQLiteException ex) {
  1155. if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
  1156. throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj);
  1157. }
  1158. throw;
  1159. }
  1160. if (map.HasAutoIncPK)
  1161. {
  1162. var id = SQLite3.LastInsertRowid (Handle);
  1163. map.SetAutoIncPK (obj, id);
  1164. }
  1165. return count;
  1166. }
  1167. /// <summary>
  1168. /// Updates all of the columns of a table using the specified object
  1169. /// except for its primary key.
  1170. /// The object is required to have a primary key.
  1171. /// </summary>
  1172. /// <param name="obj">
  1173. /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
  1174. /// </param>
  1175. /// <returns>
  1176. /// The number of rows updated.
  1177. /// </returns>
  1178. public int Update (object obj)
  1179. {
  1180. if (obj == null) {
  1181. return 0;
  1182. }
  1183. return Update (obj, obj.GetType ());
  1184. }
  1185. /// <summary>
  1186. /// Updates all of the columns of a table using the specified object
  1187. /// except for its primary key.
  1188. /// The object is required to have a primary key.
  1189. /// </summary>
  1190. /// <param name="obj">
  1191. /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
  1192. /// </param>
  1193. /// <param name="objType">
  1194. /// The type of object to insert.
  1195. /// </param>
  1196. /// <returns>
  1197. /// The number of rows updated.
  1198. /// </returns>
  1199. public int Update (object obj, Type objType)
  1200. {
  1201. int rowsAffected = 0;
  1202. if (obj == null || objType == null) {
  1203. return 0;
  1204. }
  1205. var map = GetMapping (objType);
  1206. var pk = map.PK;
  1207. if (pk == null) {
  1208. throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK");
  1209. }
  1210. var cols = from p in map.Columns
  1211. where p != pk
  1212. select p;
  1213. var vals = from c in cols
  1214. select c.GetValue (obj);
  1215. var ps = new List<object> (vals);
  1216. ps.Add (pk.GetValue (obj));
  1217. var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols
  1218. select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name);
  1219. try {
  1220. rowsAffected = Execute (q, ps.ToArray ());
  1221. }
  1222. catch (SQLiteException ex) {
  1223. if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
  1224. throw NotNullConstraintViolationException.New (ex, map, obj);
  1225. }
  1226. throw ex;
  1227. }
  1228. return rowsAffected;
  1229. }
  1230. /// <summary>
  1231. /// Updates all specified objects.
  1232. /// </summary>
  1233. /// <param name="objects">
  1234. /// An <see cref="IEnumerable"/> of the objects to insert.
  1235. /// </param>
  1236. /// <returns>
  1237. /// The number of rows modified.
  1238. /// </returns>
  1239. public int UpdateAll (System.Collections.IEnumerable objects)
  1240. {
  1241. var c = 0;
  1242. RunInTransaction (() => {
  1243. foreach (var r in objects) {
  1244. c += Update (r);
  1245. }
  1246. });
  1247. return c;
  1248. }
  1249. /// <summary>
  1250. /// Deletes the given object from the database using its primary key.
  1251. /// </summary>
  1252. /// <param name="objectToDelete">
  1253. /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute.
  1254. /// </param>
  1255. /// <returns>
  1256. /// The number of rows deleted.
  1257. /// </returns>
  1258. public int Delete (object objectToDelete)
  1259. {
  1260. var map = GetMapping (objectToDelete.GetType ());
  1261. var pk = map.PK;
  1262. if (pk == null) {
  1263. throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
  1264. }
  1265. var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
  1266. return Execute (q, pk.GetValue (objectToDelete));
  1267. }
  1268. /// <summary>
  1269. /// Deletes the object with the specified primary key.
  1270. /// </summary>
  1271. /// <param name="primaryKey">
  1272. /// The primary key of the object to delete.
  1273. /// </param>
  1274. /// <returns>
  1275. /// The number of objects deleted.
  1276. /// </returns>
  1277. /// <typeparam name='T'>
  1278. /// The type of object.
  1279. /// </typeparam>
  1280. public int Delete<T> (object primaryKey)
  1281. {
  1282. var map = GetMapping (typeof (T));
  1283. var pk = map.PK;
  1284. if (pk == null) {
  1285. throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
  1286. }
  1287. var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
  1288. return Execute (q, primaryKey);
  1289. }
  1290. /// <summary>
  1291. /// Deletes all the objects from the specified table.
  1292. /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
  1293. /// specified table. Do you really want to do that?
  1294. /// </summary>
  1295. /// <returns>
  1296. /// The number of objects deleted.
  1297. /// </returns>
  1298. /// <typeparam name='T'>
  1299. /// The type of objects to delete.
  1300. /// </typeparam>
  1301. public int DeleteAll<T> ()
  1302. {
  1303. var map = GetMapping (typeof (T));
  1304. var query = string.Format("delete from \"{0}\"", map.TableName);
  1305. return Execute (query);
  1306. }
  1307. ~SQLiteConnection ()
  1308. {
  1309. Dispose (false);
  1310. }
  1311. public void Dispose ()
  1312. {
  1313. Dispose (true);
  1314. GC.SuppressFinalize (this);
  1315. }
  1316. protected virtual void Dispose (bool disposing)
  1317. {
  1318. Close ();
  1319. }
  1320. public void Close ()
  1321. {
  1322. if (_open && Handle != NullHandle) {
  1323. try {
  1324. if (_mappings != null) {
  1325. foreach (var sqlInsertCommand in _mappings.Values) {
  1326. sqlInsertCommand.Dispose();
  1327. }
  1328. }
  1329. var r = SQLite3.Close (Handle);
  1330. if (r != SQLite3.Result.OK) {
  1331. string msg = SQLite3.GetErrmsg (Handle);
  1332. throw SQLiteException.New (r, msg);
  1333. }
  1334. }
  1335. finally {
  1336. Handle = NullHandle;
  1337. _open = false;
  1338. }
  1339. }
  1340. }
  1341. }
  1342. /// <summary>
  1343. /// Represents a parsed connection string.
  1344. /// </summary>
  1345. class SQLiteConnectionString
  1346. {
  1347. public string ConnectionString { get; private set; }
  1348. public string DatabasePath { get; private set; }
  1349. public bool StoreDateTimeAsTicks { get; private set; }
  1350. #if NETFX_CORE
  1351. static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
  1352. #endif
  1353. public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks)
  1354. {
  1355. ConnectionString = databasePath;
  1356. StoreDateTimeAsTicks = storeDateTimeAsTicks;
  1357. #if NETFX_CORE
  1358. DatabasePath = System.IO.Path.Combine (MetroStyleDataPath, databasePath);
  1359. #else
  1360. DatabasePath = databasePath;
  1361. #endif
  1362. }
  1363. }
  1364. [AttributeUsage (AttributeTargets.Class)]
  1365. public class TableAttribute : Attribute
  1366. {
  1367. public string Name { get; set; }
  1368. public TableAttribute (string name)
  1369. {
  1370. Name = name;
  1371. }
  1372. }
  1373. [AttributeUsage (AttributeTargets.Property)]
  1374. public class ColumnAttribute : Attribute
  1375. {
  1376. public string Name { get; set; }
  1377. public ColumnAttribute (string name)
  1378. {
  1379. Name = name;
  1380. }
  1381. }
  1382. [AttributeUsage (AttributeTargets.Property)]
  1383. public class PrimaryKeyAttribute : Attribute
  1384. {
  1385. }
  1386. [AttributeUsage (AttributeTargets.Property)]
  1387. public class AutoIncrementAttribute : Attribute
  1388. {
  1389. }
  1390. [AttributeUsage (AttributeTargets.Property)]
  1391. public class IndexedAttribute : Attribute
  1392. {
  1393. public string Name { get; set; }
  1394. public int Order { get; set; }
  1395. public virtual bool Unique { get; set; }
  1396. public IndexedAttribute()
  1397. {
  1398. }
  1399. public IndexedAttribute(string name, int order)
  1400. {
  1401. Name = name;
  1402. Order = order;
  1403. }
  1404. }
  1405. [AttributeUsage (AttributeTargets.Property)]
  1406. public class IgnoreAttribute : Attribute
  1407. {
  1408. }
  1409. [AttributeUsage (AttributeTargets.Property)]
  1410. public class UniqueAttribute : IndexedAttribute
  1411. {
  1412. public override bool Unique {
  1413. get { return true; }
  1414. set { /* throw? */ }
  1415. }
  1416. }
  1417. [AttributeUsage (AttributeTargets.Property)]
  1418. public class MaxLengthAttribute : Attribute
  1419. {
  1420. public int Value { get; private set; }
  1421. public MaxLengthAttribute (int length)
  1422. {
  1423. Value = length;
  1424. }
  1425. }
  1426. [AttributeUsage (AttributeTargets.Property)]
  1427. public class CollationAttribute: Attribute
  1428. {
  1429. public string Value { get; private set; }
  1430. public CollationAttribute (string collation)
  1431. {
  1432. Value = collation;
  1433. }
  1434. }
  1435. [AttributeUsage (AttributeTargets.Property)]
  1436. public class NotNullAttribute : Attribute
  1437. {
  1438. }
  1439. public class TableMapping
  1440. {
  1441. public Type MappedType { get; private set; }
  1442. public string TableName { get; private set; }
  1443. public Column[] Columns { get; private set; }
  1444. public Column PK { get; private set; }
  1445. public string GetByPrimaryKeySql { get; private set; }
  1446. Column _autoPk;
  1447. Column[] _insertColumns;
  1448. Column[] _insertOrReplaceColumns;
  1449. public TableMapping(Type type, CreateFlags createFlags = CreateFlags.None)
  1450. {
  1451. MappedType = type;
  1452. #if NETFX_CORE
  1453. var tableAttr = (TableAttribute)System.Reflection.CustomAttributeExtensions
  1454. .GetCustomAttribute(type.GetTypeInfo(), typeof(TableAttribute), true);
  1455. #else
  1456. var tableAttr = (TableAttribute)type.GetCustomAttributes (typeof (TableAttribute), true).FirstOrDefault ();
  1457. #endif
  1458. TableName = tableAttr != null ? tableAttr.Name : MappedType.Name;
  1459. #if !NETFX_CORE
  1460. var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
  1461. #else
  1462. var props = from p in MappedType.GetRuntimeProperties()
  1463. where ((p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic) || (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic))
  1464. select p;
  1465. #endif
  1466. var cols = new List<Column> ();
  1467. foreach (var p in props) {
  1468. #if !NETFX_CORE
  1469. var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0;
  1470. #else
  1471. var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Count() > 0;
  1472. #endif
  1473. if (p.CanWrite && !ignore) {
  1474. cols.Add (new Column (p, createFlags));
  1475. }
  1476. }
  1477. Columns = cols.ToArray ();
  1478. foreach (var c in Columns) {
  1479. if (c.IsAutoInc && c.IsPK) {
  1480. _autoPk = c;
  1481. }
  1482. if (c.IsPK) {
  1483. PK = c;
  1484. }
  1485. }
  1486. HasAutoIncPK = _autoPk != null;
  1487. if (PK != null) {
  1488. GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
  1489. }
  1490. else {
  1491. // People should not be calling Get/Find without a PK
  1492. GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName);
  1493. }
  1494. }
  1495. public bool HasAutoIncPK { get; private set; }
  1496. public void SetAutoIncPK (object obj, long id)
  1497. {
  1498. if (_autoPk != null) {
  1499. _autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null));
  1500. }
  1501. }
  1502. public Column[] InsertColumns {
  1503. get {
  1504. if (_insertColumns == null) {
  1505. _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray ();
  1506. }
  1507. return _insertColumns;
  1508. }
  1509. }
  1510. public Column[] InsertOrReplaceColumns {
  1511. get {
  1512. if (_insertOrReplaceColumns == null) {
  1513. _insertOrReplaceColumns = Columns.ToArray ();
  1514. }
  1515. return _insertOrReplaceColumns;
  1516. }
  1517. }
  1518. public Column FindColumnWithPropertyName (string propertyName)
  1519. {
  1520. var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName);
  1521. return exact;
  1522. }
  1523. public Column FindColumn (string columnName)
  1524. {
  1525. var exact = Columns.FirstOrDefault (c => c.Name == columnName);
  1526. return exact;
  1527. }
  1528. PreparedSqlLiteInsertCommand _insertCommand;
  1529. string _insertCommandExtra;
  1530. public PreparedSqlLiteInsertCommand GetInsertCommand(SQLiteConnection conn, string extra)
  1531. {
  1532. if (_insertCommand == null) {
  1533. _insertCommand = CreateInsertCommand(conn, extra);
  1534. _insertCommandExtra = extra;
  1535. }
  1536. else if (_insertCommandExtra != extra) {
  1537. _insertCommand.Dispose();
  1538. _insertCommand = CreateInsertCommand(conn, extra);
  1539. _insertCommandExtra = extra;
  1540. }
  1541. return _insertCommand;
  1542. }
  1543. PreparedSqlLiteInsertCommand CreateInsertCommand(SQLiteConnection conn, string extra)
  1544. {
  1545. var cols = InsertColumns;
  1546. string insertSql;
  1547. if (!cols.Any() && Columns.Count() == 1 && Columns[0].IsAutoInc)
  1548. {
  1549. insertSql = string.Format("insert {1} into \"{0}\" default values", TableName, extra);
  1550. }
  1551. else
  1552. {
  1553. var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
  1554. if (replacing) {
  1555. cols = InsertOrReplaceColumns;
  1556. }
  1557. insertSql = string.Format("insert {3} into \"{0}\"({1}) values ({2})", TableName,
  1558. string.Join(",", (from c in cols
  1559. select "\"" + c.Name + "\"").ToArray()),
  1560. string.Join(",", (from c in cols
  1561. select "?").ToArray()), extra);
  1562. }
  1563. var insertCommand = new PreparedSqlLiteInsertCommand(conn);
  1564. insertCommand.CommandText = insertSql;
  1565. return insertCommand;
  1566. }
  1567. protected internal void Dispose()
  1568. {
  1569. if (_insertCommand != null) {
  1570. _insertCommand.Dispose();
  1571. _insertCommand = null;
  1572. }
  1573. }
  1574. public class Column
  1575. {
  1576. PropertyInfo _prop;
  1577. public string Name { get; private set; }
  1578. public string PropertyName { get { return _prop.Name; } }
  1579. public Type ColumnType { get; private set; }
  1580. public string Collation { get; private set; }
  1581. public bool IsAutoInc { get; private set; }
  1582. public bool IsAutoGuid { get; private set; }
  1583. public bool IsPK { get; private set; }
  1584. public IEnumerable<IndexedAttribute> Indices { get; set; }
  1585. public bool IsNullable { get; private set; }
  1586. public int? MaxStringLength { get; private set; }
  1587. public Column(PropertyInfo prop, CreateFlags createFlags = CreateFlags.None)
  1588. {
  1589. var colAttr = (ColumnAttribute)prop.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
  1590. _prop = prop;
  1591. Name = colAttr == null ? prop.Name : colAttr.Name;
  1592. //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
  1593. ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
  1594. Collation = Orm.Collation(prop);
  1595. IsPK = Orm.IsPK(prop) ||
  1596. (((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
  1597. string.Compare (prop.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);
  1598. var isAuto = Orm.IsAutoInc(prop) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));
  1599. IsAutoGuid = isAuto && ColumnType == typeof(Guid);
  1600. IsAutoInc = isAuto && !IsAutoGuid;
  1601. Indices = Orm.GetIndices(prop);
  1602. if (!Indices.Any()
  1603. && !IsPK
  1604. && ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex)
  1605. && Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
  1606. )
  1607. {
  1608. Indices = new IndexedAttribute[] { new IndexedAttribute() };
  1609. }
  1610. IsNullable = !(IsPK || Orm.IsMarkedNotNull(prop));
  1611. MaxStringLength = Orm.MaxStringLength(prop);
  1612. }
  1613. public void SetValue (object obj, object val)
  1614. {
  1615. _prop.SetValue (obj, val, null);
  1616. }
  1617. public object GetValue (object obj)
  1618. {
  1619. return _prop.GetValue (obj, null);
  1620. }
  1621. }
  1622. }
  1623. public static class Orm
  1624. {
  1625. public const int DefaultMaxStringLength = 140;
  1626. public const string ImplicitPkName = "Id";
  1627. public const string ImplicitIndexSuffix = "Id";
  1628. public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks)
  1629. {
  1630. string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks) + " ";
  1631. if (p.IsPK) {
  1632. decl += "primary key ";
  1633. }
  1634. if (p.IsAutoInc) {
  1635. decl += "autoincrement ";
  1636. }
  1637. if (!p.IsNullable) {
  1638. decl += "not null ";
  1639. }
  1640. if (!string.IsNullOrEmpty (p.Collation)) {
  1641. decl += "collate " + p.Collation + " ";
  1642. }
  1643. return decl;
  1644. }
  1645. public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks)
  1646. {
  1647. var clrType = p.ColumnType;
  1648. if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) {
  1649. return "integer";
  1650. } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) {
  1651. return "bigint";
  1652. } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) {
  1653. return "float";
  1654. } else if (clrType == typeof(String)) {
  1655. int? len = p.MaxStringLength;
  1656. if (len.HasValue)
  1657. return "varchar(" + len.Value + ")";
  1658. return "varchar";
  1659. } else if (clrType == typeof(TimeSpan)) {
  1660. return "bigint";
  1661. } else if (clrType == typeof(DateTime)) {
  1662. return storeDateTimeAsTicks ? "bigint" : "datetime";
  1663. } else if (clrType == typeof(DateTimeOffset)) {
  1664. return "bigint";
  1665. #if !NETFX_CORE
  1666. } else if (clrType.IsEnum) {
  1667. #else
  1668. } else if (clrType.GetTypeInfo().IsEnum) {
  1669. #endif
  1670. return "integer";
  1671. } else if (clrType == typeof(byte[])) {
  1672. return "blob";
  1673. } else if (clrType == typeof(Guid)) {
  1674. return "varchar(36)";
  1675. } else {
  1676. throw new NotSupportedException ("Don't know about " + clrType);
  1677. }
  1678. }
  1679. public static bool IsPK (MemberInfo p)
  1680. {
  1681. var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true);
  1682. #if !NETFX_CORE
  1683. return attrs.Length > 0;
  1684. #else
  1685. return attrs.Count() > 0;
  1686. #endif
  1687. }
  1688. public static string Collation (MemberInfo p)
  1689. {
  1690. var attrs = p.GetCustomAttributes (typeof(CollationAttribute), true);
  1691. #if !NETFX_CORE
  1692. if (attrs.Length > 0) {
  1693. return ((CollationAttribute)attrs [0]).Value;
  1694. #else
  1695. if (attrs.Count() > 0) {
  1696. return ((CollationAttribute)attrs.First()).Value;
  1697. #endif
  1698. } else {
  1699. return string.Empty;
  1700. }
  1701. }
  1702. public static bool IsAutoInc (MemberInfo p)
  1703. {
  1704. var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true);
  1705. #if !NETFX_CORE
  1706. return attrs.Length > 0;
  1707. #else
  1708. return attrs.Count() > 0;
  1709. #endif
  1710. }
  1711. public static IEnumerable<IndexedAttribute> GetIndices(MemberInfo p)
  1712. {
  1713. var attrs = p.GetCustomAttributes(typeof(IndexedAttribute), true);
  1714. return attrs.Cast<IndexedAttribute>();
  1715. }
  1716. public static int? MaxStringLength(PropertyInfo p)
  1717. {
  1718. var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true);
  1719. #if !NETFX_CORE
  1720. if (attrs.Length > 0)
  1721. return ((MaxLengthAttribute)attrs [0]).Value;
  1722. #else
  1723. if (attrs.Count() > 0)
  1724. return ((MaxLengthAttribute)attrs.First()).Value;
  1725. #endif
  1726. return null;
  1727. }
  1728. public static bool IsMarkedNotNull(MemberInfo p)
  1729. {
  1730. var attrs = p.GetCustomAttributes (typeof (NotNullAttribute), true);
  1731. #if !NETFX_CORE
  1732. return attrs.Length > 0;
  1733. #else
  1734. return attrs.Count() > 0;
  1735. #endif
  1736. }
  1737. }
  1738. public partial class SQLiteCommand
  1739. {
  1740. SQLiteConnection _conn;
  1741. private List<Binding> _bindings;
  1742. public string CommandText { get; set; }
  1743. internal SQLiteCommand (SQLiteConnection conn)
  1744. {
  1745. _conn = conn;
  1746. _bindings = new List<Binding> ();
  1747. CommandText = "";
  1748. }
  1749. public int ExecuteNonQuery ()
  1750. {
  1751. if (_conn.Trace) {
  1752. Debug.WriteLine ("Executing: " + this);
  1753. }
  1754. var r = SQLite3.Result.OK;
  1755. var stmt = Prepare ();
  1756. r = SQLite3.Step (stmt);
  1757. Finalize (stmt);
  1758. if (r == SQLite3.Result.Done) {
  1759. int rowsAffected = SQLite3.Changes (_conn.Handle);
  1760. return rowsAffected;
  1761. } else if (r == SQLite3.Result.Error) {
  1762. string msg = SQLite3.GetErrmsg (_conn.Handle);
  1763. throw SQLiteException.New (r, msg);
  1764. }
  1765. else if (r == SQLite3.Result.Constraint) {
  1766. if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
  1767. throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle));
  1768. }
  1769. }
  1770. throw SQLiteException.New(r, r.ToString());
  1771. }
  1772. public IEnumerable<T> ExecuteDeferredQuery<T> ()
  1773. {
  1774. return ExecuteDeferredQuery<T>(_conn.GetMapping(typeof(T)));
  1775. }
  1776. public List<T> ExecuteQuery<T> ()
  1777. {
  1778. return ExecuteDeferredQuery<T>(_conn.GetMapping(typeof(T))).ToList();
  1779. }
  1780. public List<T> ExecuteQuery<T> (TableMapping map)
  1781. {
  1782. return ExecuteDeferredQuery<T>(map).ToList();
  1783. }
  1784. /// <summary>
  1785. /// Invoked every time an instance is loaded from the database.
  1786. /// </summary>
  1787. /// <param name='obj'>
  1788. /// The newly created object.
  1789. /// </param>
  1790. /// <remarks>
  1791. /// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand"/>
  1792. /// method to hook into the life-cycle of objects.
  1793. ///
  1794. /// Type safety is not possible because MonoTouch does not support virtual generic methods.
  1795. /// </remarks>
  1796. protected virtual void OnInstanceCreated (object obj)
  1797. {
  1798. // Can be overridden.
  1799. }
  1800. public IEnumerable<T> ExecuteDeferredQuery<T> (TableMapping map)
  1801. {
  1802. if (_conn.Trace) {
  1803. Debug.WriteLine ("Executing Query: " + this);
  1804. }
  1805. var stmt = Prepare ();
  1806. try
  1807. {
  1808. var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)];
  1809. for (int i = 0; i < cols.Length; i++) {
  1810. var name = SQLite3.ColumnName16 (stmt, i);
  1811. cols [i] = map.FindColumn (name);
  1812. }
  1813. while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
  1814. var obj = Activator.CreateInstance(map.MappedType);
  1815. for (int i = 0; i < cols.Length; i++) {
  1816. if (cols [i] == null)
  1817. continue;
  1818. var colType = SQLite3.ColumnType (stmt, i);
  1819. var val = ReadCol (stmt, i, colType, cols [i].ColumnType);
  1820. cols [i].SetValue (obj, val);
  1821. }
  1822. OnInstanceCreated (obj);
  1823. yield return (T)obj;
  1824. }
  1825. }
  1826. finally
  1827. {
  1828. SQLite3.Finalize(stmt);
  1829. }
  1830. }
  1831. public T ExecuteScalar<T> ()
  1832. {
  1833. if (_conn.Trace) {
  1834. Debug.WriteLine ("Executing Query: " + this);
  1835. }
  1836. T val = default(T);
  1837. var stmt = Prepare ();
  1838. try
  1839. {
  1840. var r = SQLite3.Step (stmt);
  1841. if (r == SQLite3.Result.Row) {
  1842. var colType = SQLite3.ColumnType (stmt, 0);
  1843. val = (T)ReadCol (stmt, 0, colType, typeof(T));
  1844. }
  1845. else if (r == SQLite3.Result.Done) {
  1846. }
  1847. else
  1848. {
  1849. throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
  1850. }
  1851. }
  1852. finally
  1853. {
  1854. Finalize (stmt);
  1855. }
  1856. return val;
  1857. }
  1858. public void Bind (string name, object val)
  1859. {
  1860. _bindings.Add (new Binding {
  1861. Name = name,
  1862. Value = val
  1863. });
  1864. }
  1865. public void Bind (object val)
  1866. {
  1867. Bind (null, val);
  1868. }
  1869. public override string ToString ()
  1870. {
  1871. var parts = new string[1 + _bindings.Count];
  1872. parts [0] = CommandText;
  1873. var i = 1;
  1874. foreach (var b in _bindings) {
  1875. parts [i] = string.Format (" {0}: {1}", i - 1, b.Value);
  1876. i++;
  1877. }
  1878. return string.Join (Environment.NewLine, parts);
  1879. }
  1880. Sqlite3Statement Prepare()
  1881. {
  1882. var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText);
  1883. BindAll (stmt);
  1884. return stmt;
  1885. }
  1886. void Finalize (Sqlite3Statement stmt)
  1887. {
  1888. SQLite3.Finalize (stmt);
  1889. }
  1890. void BindAll (Sqlite3Statement stmt)
  1891. {
  1892. int nextIdx = 1;
  1893. foreach (var b in _bindings) {
  1894. if (b.Name != null) {
  1895. b.Index = SQLite3.BindParameterIndex (stmt, b.Name);
  1896. } else {
  1897. b.Index = nextIdx++;
  1898. }
  1899. BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks);
  1900. }
  1901. }
  1902. internal static IntPtr NegativePointer = new IntPtr (-1);
  1903. internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks)
  1904. {
  1905. if (value == null) {
  1906. SQLite3.BindNull (stmt, index);
  1907. } else {
  1908. if (value is Int32) {
  1909. SQLite3.BindInt (stmt, index, (int)value);
  1910. } else if (value is String) {
  1911. SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer);
  1912. } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) {
  1913. SQLite3.BindInt (stmt, index, Convert.ToInt32 (value));
  1914. } else if (value is Boolean) {
  1915. SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0);
  1916. } else if (value is UInt32 || value is Int64) {
  1917. SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value));
  1918. } else if (value is Single || value is Double || value is Decimal) {
  1919. SQLite3.BindDouble (stmt, index, Convert.ToDouble (value));
  1920. } else if (value is TimeSpan) {
  1921. SQLite3.BindInt64(stmt, index, ((TimeSpan)value).Ticks);
  1922. } else if (value is DateTime) {
  1923. if (storeDateTimeAsTicks) {
  1924. SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks);
  1925. }
  1926. else {
  1927. SQLite3.BindText (stmt, index, ((DateTime)value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer);
  1928. }
  1929. } else if (value is DateTimeOffset) {
  1930. SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks);
  1931. #if !NETFX_CORE
  1932. } else if (value.GetType().IsEnum) {
  1933. #else
  1934. } else if (value.GetType().GetTypeInfo().IsEnum) {
  1935. #endif
  1936. SQLite3.BindInt (stmt, index, Convert.ToInt32 (value));
  1937. } else if (value is byte[]){
  1938. SQLite3.BindBlob(stmt, index, (byte[]) value, ((byte[]) value).Length, NegativePointer);
  1939. } else if (value is Guid) {
  1940. SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer);
  1941. } else {
  1942. throw new NotSupportedException("Cannot store type: " + value.GetType());
  1943. }
  1944. }
  1945. }
  1946. class Binding
  1947. {
  1948. public string Name { get; set; }
  1949. public object Value { get; set; }
  1950. public int Index { get; set; }
  1951. }
  1952. object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType)
  1953. {
  1954. if (type == SQLite3.ColType.Null) {
  1955. return null;
  1956. } else {
  1957. if (clrType == typeof(String)) {
  1958. return SQLite3.ColumnString (stmt, index);
  1959. } else if (clrType == typeof(Int32)) {
  1960. return (int)SQLite3.ColumnInt (stmt, index);
  1961. } else if (clrType == typeof(Boolean)) {
  1962. return SQLite3.ColumnInt (stmt, index) == 1;
  1963. } else if (clrType == typeof(double)) {
  1964. return SQLite3.ColumnDouble (stmt, index);
  1965. } else if (clrType == typeof(float)) {
  1966. return (float)SQLite3.ColumnDouble (stmt, index);
  1967. } else if (clrType == typeof(TimeSpan)) {
  1968. return new TimeSpan(SQLite3.ColumnInt64(stmt, index));
  1969. } else if (clrType == typeof(DateTime)) {
  1970. if (_conn.StoreDateTimeAsTicks) {
  1971. return new DateTime (SQLite3.ColumnInt64 (stmt, index));
  1972. }
  1973. else {
  1974. var text = SQLite3.ColumnString (stmt, index);
  1975. return DateTime.Parse (text);
  1976. }
  1977. } else if (clrType == typeof(DateTimeOffset)) {
  1978. return new DateTimeOffset(SQLite3.ColumnInt64 (stmt, index),TimeSpan.Zero);
  1979. #if !NETFX_CORE
  1980. } else if (clrType.IsEnum) {
  1981. #else
  1982. } else if (clrType.GetTypeInfo().IsEnum) {
  1983. #endif
  1984. return SQLite3.ColumnInt (stmt, index);
  1985. } else if (clrType == typeof(Int64)) {
  1986. return SQLite3.ColumnInt64 (stmt, index);
  1987. } else if (clrType == typeof(UInt32)) {
  1988. return (uint)SQLite3.ColumnInt64 (stmt, index);
  1989. } else if (clrType == typeof(decimal)) {
  1990. return (decimal)SQLite3.ColumnDouble (stmt, index);
  1991. } else if (clrType == typeof(Byte)) {
  1992. return (byte)SQLite3.ColumnInt (stmt, index);
  1993. } else if (clrType == typeof(UInt16)) {
  1994. return (ushort)SQLite3.ColumnInt (stmt, index);
  1995. } else if (clrType == typeof(Int16)) {
  1996. return (short)SQLite3.ColumnInt (stmt, index);
  1997. } else if (clrType == typeof(sbyte)) {
  1998. return (sbyte)SQLite3.ColumnInt (stmt, index);
  1999. } else if (clrType == typeof(byte[])) {
  2000. return SQLite3.ColumnByteArray (stmt, index);
  2001. } else if (clrType == typeof(Guid)) {
  2002. var text = SQLite3.ColumnString(stmt, index);
  2003. return new Guid(text);
  2004. } else{
  2005. throw new NotSupportedException ("Don't know how to read " + clrType);
  2006. }
  2007. }
  2008. }
  2009. }
  2010. /// <summary>
  2011. /// Since the insert never changed, we only need to prepare once.
  2012. /// </summary>
  2013. public class PreparedSqlLiteInsertCommand : IDisposable
  2014. {
  2015. public bool Initialized { get; set; }
  2016. protected SQLiteConnection Connection { get; set; }
  2017. public string CommandText { get; set; }
  2018. protected Sqlite3Statement Statement { get; set; }
  2019. internal static readonly Sqlite3Statement NullStatement = default(Sqlite3Statement);
  2020. internal PreparedSqlLiteInsertCommand (SQLiteConnection conn)
  2021. {
  2022. Connection = conn;
  2023. }
  2024. public int ExecuteNonQuery (object[] source)
  2025. {
  2026. if (Connection.Trace) {
  2027. Debug.WriteLine ("Executing: " + CommandText);
  2028. }
  2029. var r = SQLite3.Result.OK;
  2030. if (!Initialized) {
  2031. Statement = Prepare ();
  2032. Initialized = true;
  2033. }
  2034. //bind the values.
  2035. if (source != null) {
  2036. for (int i = 0; i < source.Length; i++) {
  2037. SQLiteCommand.BindParameter (Statement, i + 1, source [i], Connection.StoreDateTimeAsTicks);
  2038. }
  2039. }
  2040. r = SQLite3.Step (Statement);
  2041. if (r == SQLite3.Result.Done) {
  2042. int rowsAffected = SQLite3.Changes (Connection.Handle);
  2043. SQLite3.Reset (Statement);
  2044. return rowsAffected;
  2045. } else if (r == SQLite3.Result.Error) {
  2046. string msg = SQLite3.GetErrmsg (Connection.Handle);
  2047. SQLite3.Reset (Statement);
  2048. throw SQLiteException.New (r, msg);
  2049. } else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
  2050. SQLite3.Reset (Statement);
  2051. throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle));
  2052. } else {
  2053. SQLite3.Reset (Statement);
  2054. throw SQLiteException.New (r, r.ToString ());
  2055. }
  2056. }
  2057. protected virtual Sqlite3Statement Prepare ()
  2058. {
  2059. var stmt = SQLite3.Prepare2 (Connection.Handle, CommandText);
  2060. return stmt;
  2061. }
  2062. public void Dispose ()
  2063. {
  2064. Dispose (true);
  2065. GC.SuppressFinalize (this);
  2066. }
  2067. private void Dispose (bool disposing)
  2068. {
  2069. if (Statement != NullStatement) {
  2070. try {
  2071. SQLite3.Finalize (Statement);
  2072. } finally {
  2073. Statement = NullStatement;
  2074. Connection = null;
  2075. }
  2076. }
  2077. }
  2078. ~PreparedSqlLiteInsertCommand ()
  2079. {
  2080. Dispose (false);
  2081. }
  2082. }
  2083. public abstract class BaseTableQuery
  2084. {
  2085. protected class Ordering
  2086. {
  2087. public string ColumnName { get; set; }
  2088. public bool Ascending { get; set; }
  2089. }
  2090. }
  2091. public class TableQuery<T> : BaseTableQuery, IEnumerable<T>
  2092. {
  2093. public SQLiteConnection Connection { get; private set; }
  2094. public TableMapping Table { get; private set; }
  2095. Expression _where;
  2096. List<Ordering> _orderBys;
  2097. int? _limit;
  2098. int? _offset;
  2099. BaseTableQuery _joinInner;
  2100. Expression _joinInnerKeySelector;
  2101. BaseTableQuery _joinOuter;
  2102. Expression _joinOuterKeySelector;
  2103. Expression _joinSelector;
  2104. Expression _selector;
  2105. TableQuery (SQLiteConnection conn, TableMapping table)
  2106. {
  2107. Connection = conn;
  2108. Table = table;
  2109. }
  2110. public TableQuery (SQLiteConnection conn)
  2111. {
  2112. Connection = conn;
  2113. Table = Connection.GetMapping (typeof(T));
  2114. }
  2115. public TableQuery<U> Clone<U> ()
  2116. {
  2117. var q = new TableQuery<U> (Connection, Table);
  2118. q._where = _where;
  2119. q._deferred = _deferred;
  2120. if (_orderBys != null) {
  2121. q._orderBys = new List<Ordering> (_orderBys);
  2122. }
  2123. q._limit = _limit;
  2124. q._offset = _offset;
  2125. q._joinInner = _joinInner;
  2126. q._joinInnerKeySelector = _joinInnerKeySelector;
  2127. q._joinOuter = _joinOuter;
  2128. q._joinOuterKeySelector = _joinOuterKeySelector;
  2129. q._joinSelector = _joinSelector;
  2130. q._selector = _selector;
  2131. return q;
  2132. }
  2133. public TableQuery<T> Where (Expression<Func<T, bool>> predExpr)
  2134. {
  2135. if (predExpr.NodeType == ExpressionType.Lambda) {
  2136. var lambda = (LambdaExpression)predExpr;
  2137. var pred = lambda.Body;
  2138. var q = Clone<T> ();
  2139. q.AddWhere (pred);
  2140. return q;
  2141. } else {
  2142. throw new NotSupportedException ("Must be a predicate");
  2143. }
  2144. }
  2145. public TableQuery<T> Take (int n)
  2146. {
  2147. var q = Clone<T> ();
  2148. q._limit = n;
  2149. return q;
  2150. }
  2151. public TableQuery<T> Skip (int n)
  2152. {
  2153. var q = Clone<T> ();
  2154. q._offset = n;
  2155. return q;
  2156. }
  2157. public T ElementAt (int index)
  2158. {
  2159. return Skip (index).Take (1).First ();
  2160. }
  2161. bool _deferred;
  2162. public TableQuery<T> Deferred ()
  2163. {
  2164. var q = Clone<T> ();
  2165. q._deferred = true;
  2166. return q;
  2167. }
  2168. public TableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
  2169. {
  2170. return AddOrderBy<U> (orderExpr, true);
  2171. }
  2172. public TableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
  2173. {
  2174. return AddOrderBy<U> (orderExpr, false);
  2175. }
  2176. public TableQuery<T> ThenBy<U>(Expression<Func<T, U>> orderExpr)
  2177. {
  2178. return AddOrderBy<U>(orderExpr, true);
  2179. }
  2180. public TableQuery<T> ThenByDescending<U>(Expression<Func<T, U>> orderExpr)
  2181. {
  2182. return AddOrderBy<U>(orderExpr, false);
  2183. }
  2184. private TableQuery<T> AddOrderBy<U> (Expression<Func<T, U>> orderExpr, bool asc)
  2185. {
  2186. if (orderExpr.NodeType == ExpressionType.Lambda) {
  2187. var lambda = (LambdaExpression)orderExpr;
  2188. MemberExpression mem = null;
  2189. var unary = lambda.Body as UnaryExpression;
  2190. if (unary != null && unary.NodeType == ExpressionType.Convert) {
  2191. mem = unary.Operand as MemberExpression;
  2192. }
  2193. else {
  2194. mem = lambda.Body as MemberExpression;
  2195. }
  2196. if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) {
  2197. var q = Clone<T> ();
  2198. if (q._orderBys == null) {
  2199. q._orderBys = new List<Ordering> ();
  2200. }
  2201. q._orderBys.Add (new Ordering {
  2202. ColumnName = Table.FindColumnWithPropertyName(mem.Member.Name).Name,
  2203. Ascending = asc
  2204. });
  2205. return q;
  2206. } else {
  2207. throw new NotSupportedException ("Order By does not support: " + orderExpr);
  2208. }
  2209. } else {
  2210. throw new NotSupportedException ("Must be a predicate");
  2211. }
  2212. }
  2213. private void AddWhere (Expression pred)
  2214. {
  2215. if (_where == null) {
  2216. _where = pred;
  2217. } else {
  2218. _where = Expression.AndAlso (_where, pred);
  2219. }
  2220. }
  2221. public TableQuery<TResult> Join<TInner, TKey, TResult> (
  2222. TableQuery<TInner> inner,
  2223. Expression<Func<T, TKey>> outerKeySelector,
  2224. Expression<Func<TInner, TKey>> innerKeySelector,
  2225. Expression<Func<T, TInner, TResult>> resultSelector)
  2226. {
  2227. var q = new TableQuery<TResult> (Connection, Connection.GetMapping (typeof (TResult))) {
  2228. _joinOuter = this,
  2229. _joinOuterKeySelector = outerKeySelector,
  2230. _joinInner = inner,
  2231. _joinInnerKeySelector = innerKeySelector,
  2232. _joinSelector = resultSelector,
  2233. };
  2234. return q;
  2235. }
  2236. public TableQuery<TResult> Select<TResult> (Expression<Func<T, TResult>> selector)
  2237. {
  2238. var q = Clone<TResult> ();
  2239. q._selector = selector;
  2240. return q;
  2241. }
  2242. private SQLiteCommand GenerateCommand (string selectionList)
  2243. {
  2244. if (_joinInner != null && _joinOuter != null) {
  2245. throw new NotSupportedException ("Joins are not supported.");
  2246. }
  2247. else {
  2248. var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\"";
  2249. var args = new List<object> ();
  2250. if (_where != null) {
  2251. var w = CompileExpr (_where, args);
  2252. cmdText += " where " + w.CommandText;
  2253. }
  2254. if ((_orderBys != null) && (_orderBys.Count > 0)) {
  2255. var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ());
  2256. cmdText += " order by " + t;
  2257. }
  2258. if (_limit.HasValue) {
  2259. cmdText += " limit " + _limit.Value;
  2260. }
  2261. if (_offset.HasValue) {
  2262. if (!_limit.HasValue) {
  2263. cmdText += " limit -1 ";
  2264. }
  2265. cmdText += " offset " + _offset.Value;
  2266. }
  2267. return Connection.CreateCommand (cmdText, args.ToArray ());
  2268. }
  2269. }
  2270. class CompileResult
  2271. {
  2272. public string CommandText { get; set; }
  2273. public object Value { get; set; }
  2274. }
  2275. private CompileResult CompileExpr (Expression expr, List<object> queryArgs)
  2276. {
  2277. if (expr == null) {
  2278. throw new NotSupportedException ("Expression is NULL");
  2279. } else if (expr is BinaryExpression) {
  2280. var bin = (BinaryExpression)expr;
  2281. var leftr = CompileExpr (bin.Left, queryArgs);
  2282. var rightr = CompileExpr (bin.Right, queryArgs);
  2283. //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
  2284. string text;
  2285. if (leftr.CommandText == "?" && leftr.Value == null)
  2286. text = CompileNullBinaryExpression(bin, rightr);
  2287. else if (rightr.CommandText == "?" && rightr.Value == null)
  2288. text = CompileNullBinaryExpression(bin, leftr);
  2289. else
  2290. text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")";
  2291. return new CompileResult { CommandText = text };
  2292. } else if (expr.NodeType == ExpressionType.Call) {
  2293. var call = (MethodCallExpression)expr;
  2294. var args = new CompileResult[call.Arguments.Count];
  2295. var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null;
  2296. for (var i = 0; i < args.Length; i++) {
  2297. args [i] = CompileExpr (call.Arguments [i], queryArgs);
  2298. }
  2299. var sqlCall = "";
  2300. if (call.Method.Name == "Like" && args.Length == 2) {
  2301. sqlCall = "(" + args [0].CommandText + " like " + args [1].CommandText + ")";
  2302. }
  2303. else if (call.Method.Name == "Contains" && args.Length == 2) {
  2304. sqlCall = "(" + args [1].CommandText + " in " + args [0].CommandText + ")";
  2305. }
  2306. else if (call.Method.Name == "Contains" && args.Length == 1) {
  2307. if (call.Object != null && call.Object.Type == typeof(string)) {
  2308. sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + " || '%'))";
  2309. }
  2310. else {
  2311. sqlCall = "(" + args [0].CommandText + " in " + obj.CommandText + ")";
  2312. }
  2313. }
  2314. else if (call.Method.Name == "StartsWith" && args.Length == 1) {
  2315. sqlCall = "(" + obj.CommandText + " like (" + args [0].CommandText + " || '%'))";
  2316. }
  2317. else if (call.Method.Name == "EndsWith" && args.Length == 1) {
  2318. sqlCall = "(" + obj.CommandText + " like ('%' || " + args [0].CommandText + "))";
  2319. }
  2320. else if (call.Method.Name == "Equals" && args.Length == 1) {
  2321. sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
  2322. } else if (call.Method.Name == "ToLower") {
  2323. sqlCall = "(lower(" + obj.CommandText + "))";
  2324. } else if (call.Method.Name == "ToUpper") {
  2325. sqlCall = "(upper(" + obj.CommandText + "))";
  2326. } else {
  2327. sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")";
  2328. }
  2329. return new CompileResult { CommandText = sqlCall };
  2330. } else if (expr.NodeType == ExpressionType.Constant) {
  2331. var c = (ConstantExpression)expr;
  2332. queryArgs.Add (c.Value);
  2333. return new CompileResult {
  2334. CommandText = "?",
  2335. Value = c.Value
  2336. };
  2337. } else if (expr.NodeType == ExpressionType.Convert) {
  2338. var u = (UnaryExpression)expr;
  2339. var ty = u.Type;
  2340. var valr = CompileExpr (u.Operand, queryArgs);
  2341. return new CompileResult {
  2342. CommandText = valr.CommandText,
  2343. Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null
  2344. };
  2345. } else if (expr.NodeType == ExpressionType.MemberAccess) {
  2346. var mem = (MemberExpression)expr;
  2347. if (mem.Expression!=null && mem.Expression.NodeType == ExpressionType.Parameter) {
  2348. //
  2349. // This is a column of our table, output just the column name
  2350. // Need to translate it if that column name is mapped
  2351. //
  2352. var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name;
  2353. return new CompileResult { CommandText = "\"" + columnName + "\"" };
  2354. } else {
  2355. object obj = null;
  2356. if (mem.Expression != null) {
  2357. var r = CompileExpr (mem.Expression, queryArgs);
  2358. if (r.Value == null) {
  2359. throw new NotSupportedException ("Member access failed to compile expression");
  2360. }
  2361. if (r.CommandText == "?") {
  2362. queryArgs.RemoveAt (queryArgs.Count - 1);
  2363. }
  2364. obj = r.Value;
  2365. }
  2366. //
  2367. // Get the member value
  2368. //
  2369. object val = null;
  2370. #if !NETFX_CORE
  2371. if (mem.Member.MemberType == MemberTypes.Property) {
  2372. #else
  2373. if (mem.Member is PropertyInfo) {
  2374. #endif
  2375. var m = (PropertyInfo)mem.Member;
  2376. val = m.GetValue (obj, null);
  2377. #if !NETFX_CORE
  2378. } else if (mem.Member.MemberType == MemberTypes.Field) {
  2379. #else
  2380. } else if (mem.Member is FieldInfo) {
  2381. #endif
  2382. #if SILVERLIGHT
  2383. val = Expression.Lambda (expr).Compile ().DynamicInvoke ();
  2384. #else
  2385. var m = (FieldInfo)mem.Member;
  2386. val = m.GetValue (obj);
  2387. #endif
  2388. } else {
  2389. #if !NETFX_CORE
  2390. throw new NotSupportedException ("MemberExpr: " + mem.Member.MemberType);
  2391. #else
  2392. throw new NotSupportedException ("MemberExpr: " + mem.Member.DeclaringType);
  2393. #endif
  2394. }
  2395. //
  2396. // Work special magic for enumerables
  2397. //
  2398. if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable<byte>)) {
  2399. var sb = new System.Text.StringBuilder();
  2400. sb.Append("(");
  2401. var head = "";
  2402. foreach (var a in (System.Collections.IEnumerable)val) {
  2403. queryArgs.Add(a);
  2404. sb.Append(head);
  2405. sb.Append("?");
  2406. head = ",";
  2407. }
  2408. sb.Append(")");
  2409. return new CompileResult {
  2410. CommandText = sb.ToString(),
  2411. Value = val
  2412. };
  2413. }
  2414. else {
  2415. queryArgs.Add (val);
  2416. return new CompileResult {
  2417. CommandText = "?",
  2418. Value = val
  2419. };
  2420. }
  2421. }
  2422. }
  2423. throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ());
  2424. }
  2425. static object ConvertTo (object obj, Type t)
  2426. {
  2427. Type nut = Nullable.GetUnderlyingType(t);
  2428. if (nut != null) {
  2429. if (obj == null) return null;
  2430. return Convert.ChangeType (obj, nut);
  2431. } else {
  2432. return Convert.ChangeType (obj, t);
  2433. }
  2434. }
  2435. /// <summary>
  2436. /// Compiles a BinaryExpression where one of the parameters is null.
  2437. /// </summary>
  2438. /// <param name="parameter">The non-null parameter</param>
  2439. private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter)
  2440. {
  2441. if (expression.NodeType == ExpressionType.Equal)
  2442. return "(" + parameter.CommandText + " is ?)";
  2443. else if (expression.NodeType == ExpressionType.NotEqual)
  2444. return "(" + parameter.CommandText + " is not ?)";
  2445. else
  2446. throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString());
  2447. }
  2448. string GetSqlName (Expression expr)
  2449. {
  2450. var n = expr.NodeType;
  2451. if (n == ExpressionType.GreaterThan)
  2452. return ">"; else if (n == ExpressionType.GreaterThanOrEqual) {
  2453. return ">=";
  2454. } else if (n == ExpressionType.LessThan) {
  2455. return "<";
  2456. } else if (n == ExpressionType.LessThanOrEqual) {
  2457. return "<=";
  2458. } else if (n == ExpressionType.And) {
  2459. return "&";
  2460. } else if (n == ExpressionType.AndAlso) {
  2461. return "and";
  2462. } else if (n == ExpressionType.Or) {
  2463. return "|";
  2464. } else if (n == ExpressionType.OrElse) {
  2465. return "or";
  2466. } else if (n == ExpressionType.Equal) {
  2467. return "=";
  2468. } else if (n == ExpressionType.NotEqual) {
  2469. return "!=";
  2470. } else {
  2471. throw new NotSupportedException ("Cannot get SQL for: " + n);
  2472. }
  2473. }
  2474. public int Count ()
  2475. {
  2476. return GenerateCommand("count(*)").ExecuteScalar<int> ();
  2477. }
  2478. public int Count (Expression<Func<T, bool>> predExpr)
  2479. {
  2480. return Where (predExpr).Count ();
  2481. }
  2482. public IEnumerator<T> GetEnumerator ()
  2483. {
  2484. if (!_deferred)
  2485. return GenerateCommand("*").ExecuteQuery<T>().GetEnumerator();
  2486. return GenerateCommand("*").ExecuteDeferredQuery<T>().GetEnumerator();
  2487. }
  2488. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
  2489. {
  2490. return GetEnumerator ();
  2491. }
  2492. public T First ()
  2493. {
  2494. var query = Take (1);
  2495. return query.ToList<T>().First ();
  2496. }
  2497. public T FirstOrDefault ()
  2498. {
  2499. var query = Take (1);
  2500. return query.ToList<T>().FirstOrDefault ();
  2501. }
  2502. }
  2503. public static class SQLite3
  2504. {
  2505. public enum Result : int
  2506. {
  2507. OK = 0,
  2508. Error = 1,
  2509. Internal = 2,
  2510. Perm = 3,
  2511. Abort = 4,
  2512. Busy = 5,
  2513. Locked = 6,
  2514. NoMem = 7,
  2515. ReadOnly = 8,
  2516. Interrupt = 9,
  2517. IOError = 10,
  2518. Corrupt = 11,
  2519. NotFound = 12,
  2520. Full = 13,
  2521. CannotOpen = 14,
  2522. LockErr = 15,
  2523. Empty = 16,
  2524. SchemaChngd = 17,
  2525. TooBig = 18,
  2526. Constraint = 19,
  2527. Mismatch = 20,
  2528. Misuse = 21,
  2529. NotImplementedLFS = 22,
  2530. AccessDenied = 23,
  2531. Format = 24,
  2532. Range = 25,
  2533. NonDBFile = 26,
  2534. Notice = 27,
  2535. Warning = 28,
  2536. Row = 100,
  2537. Done = 101
  2538. }
  2539. public enum ExtendedResult : int
  2540. {
  2541. IOErrorRead = (Result.IOError | (1 << 8)),
  2542. IOErrorShortRead = (Result.IOError | (2 << 8)),
  2543. IOErrorWrite = (Result.IOError | (3 << 8)),
  2544. IOErrorFsync = (Result.IOError | (4 << 8)),
  2545. IOErrorDirFSync = (Result.IOError | (5 << 8)),
  2546. IOErrorTruncate = (Result.IOError | (6 << 8)),
  2547. IOErrorFStat = (Result.IOError | (7 << 8)),
  2548. IOErrorUnlock = (Result.IOError | (8 << 8)),
  2549. IOErrorRdlock = (Result.IOError | (9 << 8)),
  2550. IOErrorDelete = (Result.IOError | (10 << 8)),
  2551. IOErrorBlocked = (Result.IOError | (11 << 8)),
  2552. IOErrorNoMem = (Result.IOError | (12 << 8)),
  2553. IOErrorAccess = (Result.IOError | (13 << 8)),
  2554. IOErrorCheckReservedLock = (Result.IOError | (14 << 8)),
  2555. IOErrorLock = (Result.IOError | (15 << 8)),
  2556. IOErrorClose = (Result.IOError | (16 << 8)),
  2557. IOErrorDirClose = (Result.IOError | (17 << 8)),
  2558. IOErrorSHMOpen = (Result.IOError | (18 << 8)),
  2559. IOErrorSHMSize = (Result.IOError | (19 << 8)),
  2560. IOErrorSHMLock = (Result.IOError | (20 << 8)),
  2561. IOErrorSHMMap = (Result.IOError | (21 << 8)),
  2562. IOErrorSeek = (Result.IOError | (22 << 8)),
  2563. IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)),
  2564. IOErrorMMap = (Result.IOError | (24 << 8)),
  2565. LockedSharedcache = (Result.Locked | (1 << 8)),
  2566. BusyRecovery = (Result.Busy | (1 << 8)),
  2567. CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)),
  2568. CannotOpenIsDir = (Result.CannotOpen | (2 << 8)),
  2569. CannotOpenFullPath = (Result.CannotOpen | (3 << 8)),
  2570. CorruptVTab = (Result.Corrupt | (1 << 8)),
  2571. ReadonlyRecovery = (Result.ReadOnly | (1 << 8)),
  2572. ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)),
  2573. ReadonlyRollback = (Result.ReadOnly | (3 << 8)),
  2574. AbortRollback = (Result.Abort | (2 << 8)),
  2575. ConstraintCheck = (Result.Constraint | (1 << 8)),
  2576. ConstraintCommitHook = (Result.Constraint | (2 << 8)),
  2577. ConstraintForeignKey = (Result.Constraint | (3 << 8)),
  2578. ConstraintFunction = (Result.Constraint | (4 << 8)),
  2579. ConstraintNotNull = (Result.Constraint | (5 << 8)),
  2580. ConstraintPrimaryKey = (Result.Constraint | (6 << 8)),
  2581. ConstraintTrigger = (Result.Constraint | (7 << 8)),
  2582. ConstraintUnique = (Result.Constraint | (8 << 8)),
  2583. ConstraintVTab = (Result.Constraint | (9 << 8)),
  2584. NoticeRecoverWAL = (Result.Notice | (1 << 8)),
  2585. NoticeRecoverRollback = (Result.Notice | (2 << 8))
  2586. }
  2587. public enum ConfigOption : int
  2588. {
  2589. SingleThread = 1,
  2590. MultiThread = 2,
  2591. Serialized = 3
  2592. }
  2593. #if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE
  2594. [DllImport("sqlite3", EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)]
  2595. public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
  2596. [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)]
  2597. public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, IntPtr zvfs);
  2598. [DllImport("sqlite3", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
  2599. public static extern Result Open(byte[] filename, out IntPtr db, int flags, IntPtr zvfs);
  2600. [DllImport("sqlite3", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
  2601. public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
  2602. [DllImport("sqlite3", EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)]
  2603. public static extern Result EnableLoadExtension (IntPtr db, int onoff);
  2604. [DllImport("sqlite3", EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)]
  2605. public static extern Result Close (IntPtr db);
  2606. [DllImport("sqlite3", EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)]
  2607. public static extern Result Initialize();
  2608. [DllImport("sqlite3", EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)]
  2609. public static extern Result Shutdown();
  2610. [DllImport("sqlite3", EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)]
  2611. public static extern Result Config (ConfigOption option);
  2612. [DllImport("sqlite3", EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
  2613. public static extern int SetDirectory (uint directoryType, string directoryPath);
  2614. [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)]
  2615. public static extern Result BusyTimeout (IntPtr db, int milliseconds);
  2616. [DllImport("sqlite3", EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)]
  2617. public static extern int Changes (IntPtr db);
  2618. [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)]
  2619. public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail);
  2620. #if NETFX_CORE
  2621. [DllImport ("sqlite3", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)]
  2622. public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail);
  2623. #endif
  2624. public static IntPtr Prepare2 (IntPtr db, string query)
  2625. {
  2626. IntPtr stmt;
  2627. #if NETFX_CORE
  2628. byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query);
  2629. var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero);
  2630. #else
  2631. var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero);
  2632. #endif
  2633. if (r != Result.OK) {
  2634. throw SQLiteException.New (r, GetErrmsg (db));
  2635. }
  2636. return stmt;
  2637. }
  2638. [DllImport("sqlite3", EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)]
  2639. public static extern Result Step (IntPtr stmt);
  2640. [DllImport("sqlite3", EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)]
  2641. public static extern Result Reset (IntPtr stmt);
  2642. [DllImport("sqlite3", EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)]
  2643. public static extern Result Finalize (IntPtr stmt);
  2644. [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)]
  2645. public static extern long LastInsertRowid (IntPtr db);
  2646. [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)]
  2647. public static extern IntPtr Errmsg (IntPtr db);
  2648. public static string GetErrmsg (IntPtr db)
  2649. {
  2650. return Marshal.PtrToStringUni (Errmsg (db));
  2651. }
  2652. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)]
  2653. public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
  2654. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)]
  2655. public static extern int BindNull (IntPtr stmt, int index);
  2656. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)]
  2657. public static extern int BindInt (IntPtr stmt, int index, int val);
  2658. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)]
  2659. public static extern int BindInt64 (IntPtr stmt, int index, long val);
  2660. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)]
  2661. public static extern int BindDouble (IntPtr stmt, int index, double val);
  2662. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
  2663. public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free);
  2664. [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)]
  2665. public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free);
  2666. [DllImport("sqlite3", EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)]
  2667. public static extern int ColumnCount (IntPtr stmt);
  2668. [DllImport("sqlite3", EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)]
  2669. public static extern IntPtr ColumnName (IntPtr stmt, int index);
  2670. [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)]
  2671. static extern IntPtr ColumnName16Internal (IntPtr stmt, int index);
  2672. public static string ColumnName16(IntPtr stmt, int index)
  2673. {
  2674. return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index));
  2675. }
  2676. [DllImport("sqlite3", EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)]
  2677. public static extern ColType ColumnType (IntPtr stmt, int index);
  2678. [DllImport("sqlite3", EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)]
  2679. public static extern int ColumnInt (IntPtr stmt, int index);
  2680. [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)]
  2681. public static extern long ColumnInt64 (IntPtr stmt, int index);
  2682. [DllImport("sqlite3", EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)]
  2683. public static extern double ColumnDouble (IntPtr stmt, int index);
  2684. [DllImport("sqlite3", EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)]
  2685. public static extern IntPtr ColumnText (IntPtr stmt, int index);
  2686. [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)]
  2687. public static extern IntPtr ColumnText16 (IntPtr stmt, int index);
  2688. [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)]
  2689. public static extern IntPtr ColumnBlob (IntPtr stmt, int index);
  2690. [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)]
  2691. public static extern int ColumnBytes (IntPtr stmt, int index);
  2692. public static string ColumnString (IntPtr stmt, int index)
  2693. {
  2694. return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index));
  2695. }
  2696. public static byte[] ColumnByteArray (IntPtr stmt, int index)
  2697. {
  2698. int length = ColumnBytes (stmt, index);
  2699. var result = new byte[length];
  2700. if (length > 0)
  2701. Marshal.Copy (ColumnBlob (stmt, index), result, 0, length);
  2702. return result;
  2703. }
  2704. [DllImport ("sqlite3", EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
  2705. public static extern ExtendedResult ExtendedErrCode (IntPtr db);
  2706. [DllImport ("sqlite3", EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
  2707. public static extern int LibVersionNumber ();
  2708. #else
  2709. public static Result Open(string filename, out Sqlite3DatabaseHandle db)
  2710. {
  2711. return (Result) Sqlite3.sqlite3_open(filename, out db);
  2712. }
  2713. public static Result Open(string filename, out Sqlite3DatabaseHandle db, int flags, IntPtr zVfs)
  2714. {
  2715. #if USE_WP8_NATIVE_SQLITE
  2716. return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, "");
  2717. #else
  2718. return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, null);
  2719. #endif
  2720. }
  2721. public static Result Close(Sqlite3DatabaseHandle db)
  2722. {
  2723. return (Result)Sqlite3.sqlite3_close(db);
  2724. }
  2725. public static Result BusyTimeout(Sqlite3DatabaseHandle db, int milliseconds)
  2726. {
  2727. return (Result)Sqlite3.sqlite3_busy_timeout(db, milliseconds);
  2728. }
  2729. public static int Changes(Sqlite3DatabaseHandle db)
  2730. {
  2731. return Sqlite3.sqlite3_changes(db);
  2732. }
  2733. public static Sqlite3Statement Prepare2(Sqlite3DatabaseHandle db, string query)
  2734. {
  2735. Sqlite3Statement stmt = default(Sqlite3Statement);
  2736. #if USE_WP8_NATIVE_SQLITE
  2737. var r = Sqlite3.sqlite3_prepare_v2(db, query, out stmt);
  2738. #else
  2739. stmt = new Sqlite3Statement();
  2740. var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0);
  2741. #endif
  2742. if (r != 0)
  2743. {
  2744. throw SQLiteException.New((Result)r, GetErrmsg(db));
  2745. }
  2746. return stmt;
  2747. }
  2748. public static Result Step(Sqlite3Statement stmt)
  2749. {
  2750. return (Result)Sqlite3.sqlite3_step(stmt);
  2751. }
  2752. public static Result Reset(Sqlite3Statement stmt)
  2753. {
  2754. return (Result)Sqlite3.sqlite3_reset(stmt);
  2755. }
  2756. public static Result Finalize(Sqlite3Statement stmt)
  2757. {
  2758. return (Result)Sqlite3.sqlite3_finalize(stmt);
  2759. }
  2760. public static long LastInsertRowid(Sqlite3DatabaseHandle db)
  2761. {
  2762. return Sqlite3.sqlite3_last_insert_rowid(db);
  2763. }
  2764. public static string GetErrmsg(Sqlite3DatabaseHandle db)
  2765. {
  2766. return Sqlite3.sqlite3_errmsg(db);
  2767. }
  2768. public static int BindParameterIndex(Sqlite3Statement stmt, string name)
  2769. {
  2770. return Sqlite3.sqlite3_bind_parameter_index(stmt, name);
  2771. }
  2772. public static int BindNull(Sqlite3Statement stmt, int index)
  2773. {
  2774. return Sqlite3.sqlite3_bind_null(stmt, index);
  2775. }
  2776. public static int BindInt(Sqlite3Statement stmt, int index, int val)
  2777. {
  2778. return Sqlite3.sqlite3_bind_int(stmt, index, val);
  2779. }
  2780. public static int BindInt64(Sqlite3Statement stmt, int index, long val)
  2781. {
  2782. return Sqlite3.sqlite3_bind_int64(stmt, index, val);
  2783. }
  2784. public static int BindDouble(Sqlite3Statement stmt, int index, double val)
  2785. {
  2786. return Sqlite3.sqlite3_bind_double(stmt, index, val);
  2787. }
  2788. public static int BindText(Sqlite3Statement stmt, int index, string val, int n, IntPtr free)
  2789. {
  2790. #if USE_WP8_NATIVE_SQLITE
  2791. return Sqlite3.sqlite3_bind_text(stmt, index, val, n);
  2792. #else
  2793. return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null);
  2794. #endif
  2795. }
  2796. public static int BindBlob(Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free)
  2797. {
  2798. #if USE_WP8_NATIVE_SQLITE
  2799. return Sqlite3.sqlite3_bind_blob(stmt, index, val, n);
  2800. #else
  2801. return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null);
  2802. #endif
  2803. }
  2804. public static int ColumnCount(Sqlite3Statement stmt)
  2805. {
  2806. return Sqlite3.sqlite3_column_count(stmt);
  2807. }
  2808. public static string ColumnName(Sqlite3Statement stmt, int index)
  2809. {
  2810. return Sqlite3.sqlite3_column_name(stmt, index);
  2811. }
  2812. public static string ColumnName16(Sqlite3Statement stmt, int index)
  2813. {
  2814. return Sqlite3.sqlite3_column_name(stmt, index);
  2815. }
  2816. public static ColType ColumnType(Sqlite3Statement stmt, int index)
  2817. {
  2818. return (ColType)Sqlite3.sqlite3_column_type(stmt, index);
  2819. }
  2820. public static int ColumnInt(Sqlite3Statement stmt, int index)
  2821. {
  2822. return Sqlite3.sqlite3_column_int(stmt, index);
  2823. }
  2824. public static long ColumnInt64(Sqlite3Statement stmt, int index)
  2825. {
  2826. return Sqlite3.sqlite3_column_int64(stmt, index);
  2827. }
  2828. public static double ColumnDouble(Sqlite3Statement stmt, int index)
  2829. {
  2830. return Sqlite3.sqlite3_column_double(stmt, index);
  2831. }
  2832. public static string ColumnText(Sqlite3Statement stmt, int index)
  2833. {
  2834. return Sqlite3.sqlite3_column_text(stmt, index);
  2835. }
  2836. public static string ColumnText16(Sqlite3Statement stmt, int index)
  2837. {
  2838. return Sqlite3.sqlite3_column_text(stmt, index);
  2839. }
  2840. public static byte[] ColumnBlob(Sqlite3Statement stmt, int index)
  2841. {
  2842. return Sqlite3.sqlite3_column_blob(stmt, index);
  2843. }
  2844. public static int ColumnBytes(Sqlite3Statement stmt, int index)
  2845. {
  2846. return Sqlite3.sqlite3_column_bytes(stmt, index);
  2847. }
  2848. public static string ColumnString(Sqlite3Statement stmt, int index)
  2849. {
  2850. return Sqlite3.sqlite3_column_text(stmt, index);
  2851. }
  2852. public static byte[] ColumnByteArray(Sqlite3Statement stmt, int index)
  2853. {
  2854. return ColumnBlob(stmt, index);
  2855. }
  2856. public static Result EnableLoadExtension(Sqlite3DatabaseHandle db, int onoff)
  2857. {
  2858. return (Result)Sqlite3.sqlite3_enable_load_extension(db, onoff);
  2859. }
  2860. public static ExtendedResult ExtendedErrCode(Sqlite3DatabaseHandle db)
  2861. {
  2862. return (ExtendedResult)Sqlite3.sqlite3_extended_errcode(db);
  2863. }
  2864. #endif
  2865. public enum ColType : int
  2866. {
  2867. Integer = 1,
  2868. Float = 2,
  2869. Text = 3,
  2870. Blob = 4,
  2871. Null = 5
  2872. }
  2873. }
  2874. }