Migration.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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(DbConnection, Assembly, "Users");
  55. /// um.Update();
  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. using (DbCommand cmd = _conn.CreateCommand())
  103. {
  104. cmd.CommandText = _migrations_create;
  105. cmd.ExecuteNonQuery();
  106. }
  107. InsertVersion("migrations", 1);
  108. }
  109. public void Update()
  110. {
  111. int version = 0;
  112. version = FindVersion(_conn, _type);
  113. SortedList<int, string> migrations = GetMigrationsAfter(version);
  114. if (migrations.Count < 1)
  115. return;
  116. // to prevent people from killing long migrations.
  117. m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]);
  118. m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
  119. using (DbCommand cmd = _conn.CreateCommand())
  120. {
  121. foreach (KeyValuePair<int, string> kvp in migrations)
  122. {
  123. int newversion = kvp.Key;
  124. cmd.CommandText = kvp.Value;
  125. // we need to up the command timeout to infinite as we might be doing long migrations.
  126. cmd.CommandTimeout = 0;
  127. try
  128. {
  129. cmd.ExecuteNonQuery();
  130. }
  131. catch (Exception e)
  132. {
  133. m_log.DebugFormat("[MIGRATIONS] Cmd was {0}", cmd.CommandText);
  134. m_log.DebugFormat("[MIGRATIONS]: An error has occurred in the migration {0}.\n This may mean you could see errors trying to run OpenSim. If you see database related errors, you will need to fix the issue manually. Continuing.", e.Message);
  135. cmd.CommandText = "ROLLBACK;";
  136. cmd.ExecuteNonQuery();
  137. }
  138. if (version == 0)
  139. {
  140. InsertVersion(_type, newversion);
  141. }
  142. else
  143. {
  144. UpdateVersion(_type, newversion);
  145. }
  146. version = newversion;
  147. }
  148. }
  149. }
  150. // private int MaxVersion()
  151. // {
  152. // int max = 0;
  153. // string[] names = _assem.GetManifestResourceNames();
  154. // foreach (string s in names)
  155. // {
  156. // Match m = _match.Match(s);
  157. // if (m.Success)
  158. // {
  159. // int MigrationVersion = int.Parse(m.Groups[1].ToString());
  160. // if (MigrationVersion > max)
  161. // max = MigrationVersion;
  162. // }
  163. // }
  164. // return max;
  165. // }
  166. public int Version
  167. {
  168. get { return FindVersion(_conn, _type); }
  169. set {
  170. if (Version < 1)
  171. {
  172. InsertVersion(_type, value);
  173. }
  174. else
  175. {
  176. UpdateVersion(_type, value);
  177. }
  178. }
  179. }
  180. protected virtual int FindVersion(DbConnection conn, string type)
  181. {
  182. int version = 0;
  183. using (DbCommand cmd = conn.CreateCommand())
  184. {
  185. try
  186. {
  187. cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
  188. using (IDataReader reader = cmd.ExecuteReader())
  189. {
  190. if (reader.Read())
  191. {
  192. version = Convert.ToInt32(reader["version"]);
  193. }
  194. reader.Close();
  195. }
  196. }
  197. catch
  198. {
  199. // Something went wrong, so we're version 0
  200. }
  201. }
  202. return version;
  203. }
  204. private void InsertVersion(string type, int version)
  205. {
  206. using (DbCommand cmd = _conn.CreateCommand())
  207. {
  208. cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
  209. m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
  210. cmd.ExecuteNonQuery();
  211. }
  212. }
  213. private void UpdateVersion(string type, int version)
  214. {
  215. using (DbCommand cmd = _conn.CreateCommand())
  216. {
  217. cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
  218. m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
  219. cmd.ExecuteNonQuery();
  220. }
  221. }
  222. // private SortedList<int, string> GetAllMigrations()
  223. // {
  224. // return GetMigrationsAfter(0);
  225. // }
  226. private SortedList<int, string> GetMigrationsAfter(int after)
  227. {
  228. string[] names = _assem.GetManifestResourceNames();
  229. SortedList<int, string> migrations = new SortedList<int, string>();
  230. // because life is funny if we don't
  231. Array.Sort(names);
  232. foreach (string s in names)
  233. {
  234. Match m = _match.Match(s);
  235. if (m.Success)
  236. {
  237. int version = int.Parse(m.Groups[1].ToString());
  238. if (version > after)
  239. {
  240. using (Stream resource = _assem.GetManifestResourceStream(s))
  241. {
  242. using (StreamReader resourceReader = new StreamReader(resource))
  243. {
  244. string resourceString = resourceReader.ReadToEnd();
  245. migrations.Add(version, resourceString);
  246. }
  247. }
  248. }
  249. }
  250. }
  251. if (migrations.Count < 1) {
  252. m_log.InfoFormat("[MIGRATIONS]: {0} up to date, no migrations to apply", _type);
  253. }
  254. return migrations;
  255. }
  256. }
  257. }