SQLite.cs 101 KB

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