Migration.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Data;
  30. using System.Data.Common;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Text.RegularExpressions;
  34. using log4net;
  35. namespace OpenSim.Data
  36. {
  37. /// <summary>
  38. ///
  39. /// The Migration theory is based on the ruby on rails concept.
  40. /// Each database driver is going to be allowed to have files in
  41. /// Resources that specify the database migrations. They will be
  42. /// of the form:
  43. ///
  44. /// 001_Users.sql
  45. /// 002_Users.sql
  46. /// 003_Users.sql
  47. /// 001_Prims.sql
  48. /// 002_Prims.sql
  49. /// ...etc...
  50. ///
  51. /// When a database driver starts up, it specifies a resource that
  52. /// needs to be brought up to the current revision. For instance:
  53. ///
  54. /// Migration um = new Migration(Assembly, DbConnection, "Users");
  55. /// um.Upgrade();
  56. ///
  57. /// This works out which version Users is at, and applies all the
  58. /// revisions past it to it. If there is no users table, all
  59. /// revisions are applied in order. Consider each future
  60. /// migration to be an incremental roll forward of the tables in
  61. /// question.
  62. ///
  63. /// Assembly must be specifically passed in because otherwise you
  64. /// get the assembly that Migration.cs is part of, and what you
  65. /// really want is the assembly of your database class.
  66. ///
  67. /// </summary>
  68. public class Migration
  69. {
  70. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  71. private string _type;
  72. private DbConnection _conn;
  73. // private string _subtype;
  74. private Assembly _assem;
  75. private Regex _match;
  76. private static readonly string _migrations_create = "create table migrations(name varchar(100), version int)";
  77. // private static readonly string _migrations_init = "insert into migrations values('migrations', 1)";
  78. // private static readonly string _migrations_find = "select version from migrations where name='migrations'";
  79. public Migration(DbConnection conn, Assembly assem, string type)
  80. {
  81. _type = type;
  82. _conn = conn;
  83. _assem = assem;
  84. _match = new Regex(@"\.(\d\d\d)_" + _type + @"\.sql");
  85. Initialize();
  86. }
  87. public Migration(DbConnection conn, Assembly assem, string subtype, string type)
  88. {
  89. _type = type;
  90. _conn = conn;
  91. _assem = assem;
  92. _match = new Regex(subtype + @"\.(\d\d\d)_" + _type + @"\.sql");
  93. Initialize();
  94. }
  95. private void Initialize()
  96. {
  97. // clever, eh, we figure out which migrations version we are
  98. int migration_version = FindVersion(_conn, "migrations");
  99. if (migration_version > 0)
  100. return;
  101. // If not, create the migration tables
  102. DbCommand cmd = _conn.CreateCommand();
  103. cmd.CommandText = _migrations_create;
  104. cmd.ExecuteNonQuery();
  105. cmd.Dispose();
  106. InsertVersion("migrations", 1);
  107. }
  108. public void Update()
  109. {
  110. int version = 0;
  111. version = FindVersion(_conn, _type);
  112. SortedList<int, string> migrations = GetMigrationsAfter(version);
  113. if (migrations.Count < 1)
  114. return;
  115. // to prevent people from killing long migrations.
  116. m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type);
  117. m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
  118. DbCommand cmd = _conn.CreateCommand();
  119. foreach (KeyValuePair<int, string> kvp in migrations)
  120. {
  121. int newversion = kvp.Key;
  122. cmd.CommandText = kvp.Value;
  123. // we need to up the command timeout to infinite as we might be doing long migrations.
  124. cmd.CommandTimeout = 0;
  125. cmd.ExecuteNonQuery();
  126. if (version == 0)
  127. {
  128. InsertVersion(_type, newversion);
  129. }
  130. else
  131. {
  132. UpdateVersion(_type, newversion);
  133. }
  134. version = newversion;
  135. }
  136. cmd.Dispose();
  137. }
  138. // private int MaxVersion()
  139. // {
  140. // int max = 0;
  141. // string[] names = _assem.GetManifestResourceNames();
  142. // foreach (string s in names)
  143. // {
  144. // Match m = _match.Match(s);
  145. // if (m.Success)
  146. // {
  147. // int MigrationVersion = int.Parse(m.Groups[1].ToString());
  148. // if (MigrationVersion > max)
  149. // max = MigrationVersion;
  150. // }
  151. // }
  152. // return max;
  153. // }
  154. public int Version
  155. {
  156. get { return FindVersion(_conn, _type); }
  157. set {
  158. if (Version < 1)
  159. {
  160. InsertVersion(_type, value);
  161. }
  162. else
  163. {
  164. UpdateVersion(_type, value);
  165. }
  166. }
  167. }
  168. protected virtual int FindVersion(DbConnection conn, string type)
  169. {
  170. int version = 0;
  171. DbCommand cmd = conn.CreateCommand();
  172. try
  173. {
  174. cmd.CommandText = "select version from migrations where name='" + type +"' order by version desc";
  175. using (IDataReader reader = cmd.ExecuteReader())
  176. {
  177. if (reader.Read())
  178. {
  179. version = Convert.ToInt32(reader["version"]);
  180. }
  181. reader.Close();
  182. }
  183. }
  184. catch
  185. {
  186. // Something went wrong, so we're version 0
  187. }
  188. cmd.Dispose();
  189. return version;
  190. }
  191. private void InsertVersion(string type, int version)
  192. {
  193. DbCommand cmd = _conn.CreateCommand();
  194. cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
  195. m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
  196. cmd.ExecuteNonQuery();
  197. cmd.Dispose();
  198. }
  199. private void UpdateVersion(string type, int version)
  200. {
  201. DbCommand cmd = _conn.CreateCommand();
  202. cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
  203. m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
  204. cmd.ExecuteNonQuery();
  205. cmd.Dispose();
  206. }
  207. // private SortedList<int, string> GetAllMigrations()
  208. // {
  209. // return GetMigrationsAfter(0);
  210. // }
  211. private SortedList<int, string> GetMigrationsAfter(int after)
  212. {
  213. string[] names = _assem.GetManifestResourceNames();
  214. SortedList<int, string> migrations = new SortedList<int, string>();
  215. // because life is funny if we don't
  216. Array.Sort(names);
  217. foreach (string s in names)
  218. {
  219. Match m = _match.Match(s);
  220. if (m.Success)
  221. {
  222. int version = int.Parse(m.Groups[1].ToString());
  223. if (version > after) {
  224. using (Stream resource = _assem.GetManifestResourceStream(s))
  225. {
  226. using (StreamReader resourceReader = new StreamReader(resource))
  227. {
  228. string resourceString = resourceReader.ReadToEnd();
  229. migrations.Add(version, resourceString);
  230. }
  231. }
  232. }
  233. }
  234. }
  235. if (migrations.Count < 1) {
  236. m_log.InfoFormat("[MIGRATIONS]: {0} up to date, no migrations to apply", _type);
  237. }
  238. return migrations;
  239. }
  240. }
  241. }