SqliteExtensions.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using System.Text;
  2. using MediaBrowser.Model.Logging;
  3. using MediaBrowser.Model.Serialization;
  4. using System;
  5. using System.Data;
  6. using System.Data.SQLite;
  7. using System.IO;
  8. using System.Threading.Tasks;
  9. namespace MediaBrowser.Server.Implementations.Persistence
  10. {
  11. /// <summary>
  12. /// Class SQLiteExtensions
  13. /// </summary>
  14. static class SqliteExtensions
  15. {
  16. /// <summary>
  17. /// Determines whether the specified conn is open.
  18. /// </summary>
  19. /// <param name="conn">The conn.</param>
  20. /// <returns><c>true</c> if the specified conn is open; otherwise, <c>false</c>.</returns>
  21. public static bool IsOpen(this IDbConnection conn)
  22. {
  23. return conn.State == ConnectionState.Open;
  24. }
  25. public static IDataParameter GetParameter(this IDbCommand cmd, int index)
  26. {
  27. return (IDataParameter)cmd.Parameters[index];
  28. }
  29. public static IDataParameter Add(this IDataParameterCollection paramCollection, IDbCommand cmd, string name, DbType type)
  30. {
  31. var param = cmd.CreateParameter();
  32. param.ParameterName = name;
  33. param.DbType = type;
  34. paramCollection.Add(param);
  35. return param;
  36. }
  37. public static IDataParameter Add(this IDataParameterCollection paramCollection, IDbCommand cmd, string name)
  38. {
  39. var param = cmd.CreateParameter();
  40. param.ParameterName = name;
  41. paramCollection.Add(param);
  42. return param;
  43. }
  44. /// <summary>
  45. /// Gets a stream from a DataReader at a given ordinal
  46. /// </summary>
  47. /// <param name="reader">The reader.</param>
  48. /// <param name="ordinal">The ordinal.</param>
  49. /// <returns>Stream.</returns>
  50. /// <exception cref="System.ArgumentNullException">reader</exception>
  51. public static Stream GetMemoryStream(this IDataReader reader, int ordinal)
  52. {
  53. if (reader == null)
  54. {
  55. throw new ArgumentNullException("reader");
  56. }
  57. var memoryStream = new MemoryStream();
  58. var num = 0L;
  59. var array = new byte[4096];
  60. long bytes;
  61. do
  62. {
  63. bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
  64. memoryStream.Write(array, 0, (int)bytes);
  65. num += bytes;
  66. }
  67. while (bytes > 0L);
  68. memoryStream.Position = 0;
  69. return memoryStream;
  70. }
  71. /// <summary>
  72. /// Runs the queries.
  73. /// </summary>
  74. /// <param name="connection">The connection.</param>
  75. /// <param name="queries">The queries.</param>
  76. /// <param name="logger">The logger.</param>
  77. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  78. /// <exception cref="System.ArgumentNullException">queries</exception>
  79. public static void RunQueries(this IDbConnection connection, string[] queries, ILogger logger)
  80. {
  81. if (queries == null)
  82. {
  83. throw new ArgumentNullException("queries");
  84. }
  85. using (var tran = connection.BeginTransaction())
  86. {
  87. try
  88. {
  89. using (var cmd = connection.CreateCommand())
  90. {
  91. foreach (var query in queries)
  92. {
  93. cmd.Transaction = tran;
  94. cmd.CommandText = query;
  95. cmd.ExecuteNonQuery();
  96. }
  97. }
  98. tran.Commit();
  99. }
  100. catch (Exception e)
  101. {
  102. logger.ErrorException("Error running queries", e);
  103. tran.Rollback();
  104. throw;
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Connects to db.
  110. /// </summary>
  111. /// <param name="dbPath">The db path.</param>
  112. /// <param name="logger">The logger.</param>
  113. /// <returns>Task{IDbConnection}.</returns>
  114. /// <exception cref="System.ArgumentNullException">dbPath</exception>
  115. public static async Task<IDbConnection> ConnectToDb(string dbPath, ILogger logger)
  116. {
  117. if (string.IsNullOrEmpty(dbPath))
  118. {
  119. throw new ArgumentNullException("dbPath");
  120. }
  121. logger.Info("Sqlite {0} opening {1}", SQLiteConnection.SQLiteVersion, dbPath);
  122. var connectionstr = new SQLiteConnectionStringBuilder
  123. {
  124. PageSize = 4096,
  125. CacheSize = 2000,
  126. SyncMode = SynchronizationModes.Full,
  127. DataSource = dbPath,
  128. JournalMode = SQLiteJournalModeEnum.Wal
  129. };
  130. var connection = new SQLiteConnection(connectionstr.ConnectionString);
  131. await connection.OpenAsync().ConfigureAwait(false);
  132. return connection;
  133. }
  134. public static void Attach(IDbConnection db, string path, string alias)
  135. {
  136. using (var cmd = db.CreateCommand())
  137. {
  138. cmd.CommandText = string.Format("attach '{0}' as {1};", path, alias);
  139. cmd.ExecuteNonQuery();
  140. }
  141. }
  142. /// <summary>
  143. /// Serializes to bytes.
  144. /// </summary>
  145. /// <param name="json">The json.</param>
  146. /// <param name="obj">The obj.</param>
  147. /// <returns>System.Byte[][].</returns>
  148. /// <exception cref="System.ArgumentNullException">obj</exception>
  149. public static byte[] SerializeToBytes(this IJsonSerializer json, object obj)
  150. {
  151. if (obj == null)
  152. {
  153. throw new ArgumentNullException("obj");
  154. }
  155. using (var stream = new MemoryStream())
  156. {
  157. json.SerializeToStream(obj, stream);
  158. return stream.ToArray();
  159. }
  160. }
  161. public static void AddColumn(this IDbConnection connection, ILogger logger, string table, string columnName, string type)
  162. {
  163. using (var cmd = connection.CreateCommand())
  164. {
  165. cmd.CommandText = "PRAGMA table_info(" + table + ")";
  166. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  167. {
  168. while (reader.Read())
  169. {
  170. if (!reader.IsDBNull(1))
  171. {
  172. var name = reader.GetString(1);
  173. if (string.Equals(name, columnName, StringComparison.OrdinalIgnoreCase))
  174. {
  175. return;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. var builder = new StringBuilder();
  182. builder.AppendLine("alter table " + table);
  183. builder.AppendLine("add column " + columnName + " " + type);
  184. connection.RunQueries(new[] { builder.ToString() }, logger);
  185. }
  186. }
  187. }