SqliteExtensions.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 = 4096,
  126. SyncMode = SynchronizationModes.Normal,
  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. /// <summary>
  135. /// Serializes to bytes.
  136. /// </summary>
  137. /// <param name="json">The json.</param>
  138. /// <param name="obj">The obj.</param>
  139. /// <returns>System.Byte[][].</returns>
  140. /// <exception cref="System.ArgumentNullException">obj</exception>
  141. public static byte[] SerializeToBytes(this IJsonSerializer json, object obj)
  142. {
  143. if (obj == null)
  144. {
  145. throw new ArgumentNullException("obj");
  146. }
  147. using (var stream = new MemoryStream())
  148. {
  149. json.SerializeToStream(obj, stream);
  150. return stream.ToArray();
  151. }
  152. }
  153. public static void AddColumn(this IDbConnection connection, ILogger logger, string table, string columnName, string type)
  154. {
  155. using (var cmd = connection.CreateCommand())
  156. {
  157. cmd.CommandText = "PRAGMA table_info(" + table + ")";
  158. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  159. {
  160. while (reader.Read())
  161. {
  162. if (!reader.IsDBNull(1))
  163. {
  164. var name = reader.GetString(1);
  165. if (string.Equals(name, columnName, StringComparison.OrdinalIgnoreCase))
  166. {
  167. return;
  168. }
  169. }
  170. }
  171. }
  172. }
  173. var builder = new StringBuilder();
  174. builder.AppendLine("alter table " + table);
  175. builder.AppendLine("add column " + columnName + " " + type);
  176. connection.RunQueries(new[] { builder.ToString() }, logger);
  177. }
  178. }
  179. }