Migration.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 OpenSim 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 log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.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("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. InsertVersion("migrations", 1);
  106. }
  107. public void Update()
  108. {
  109. int version = 0;
  110. version = FindVersion(_type);
  111. SortedList<int, string> migrations = GetMigrationsAfter(version);
  112. if (migrations.Count < 1)
  113. return;
  114. // to prevent people from killing long migrations.
  115. m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type);
  116. m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
  117. DbCommand cmd = _conn.CreateCommand();
  118. foreach (KeyValuePair<int, string> kvp in migrations)
  119. {
  120. int newversion = kvp.Key;
  121. cmd.CommandText = kvp.Value;
  122. // we need to up the command timeout to infinite as we might be doing long migrations.
  123. cmd.CommandTimeout = 0;
  124. cmd.ExecuteNonQuery();
  125. if (version == 0)
  126. {
  127. InsertVersion(_type, newversion);
  128. }
  129. else
  130. {
  131. UpdateVersion(_type, newversion);
  132. }
  133. version = newversion;
  134. }
  135. }
  136. // private int MaxVersion()
  137. // {
  138. // int max = 0;
  139. // string[] names = _assem.GetManifestResourceNames();
  140. // foreach (string s in names)
  141. // {
  142. // Match m = _match.Match(s);
  143. // if (m.Success)
  144. // {
  145. // int MigrationVersion = int.Parse(m.Groups[1].ToString());
  146. // if (MigrationVersion > max)
  147. // max = MigrationVersion;
  148. // }
  149. // }
  150. // return max;
  151. // }
  152. public int Version
  153. {
  154. get { return FindVersion(_type); }
  155. set {
  156. if (Version < 1)
  157. {
  158. InsertVersion(_type, value);
  159. }
  160. else
  161. {
  162. UpdateVersion(_type, value);
  163. }
  164. }
  165. }
  166. private int FindVersion(string type)
  167. {
  168. int version = 0;
  169. DbCommand cmd = _conn.CreateCommand();
  170. try
  171. {
  172. cmd.CommandText = "select version from migrations where name='" + type + "' limit 1";
  173. using (IDataReader reader = cmd.ExecuteReader())
  174. {
  175. if (reader.Read())
  176. {
  177. version = Convert.ToInt32(reader["version"]);
  178. }
  179. reader.Close();
  180. }
  181. }
  182. catch
  183. {
  184. // Something went wrong, so we're version 0
  185. }
  186. return version;
  187. }
  188. private void InsertVersion(string type, int version)
  189. {
  190. DbCommand cmd = _conn.CreateCommand();
  191. cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
  192. m_log.InfoFormat("[MIGRATIONS] Creating {0} at version {1}", type, version);
  193. cmd.ExecuteNonQuery();
  194. }
  195. private void UpdateVersion(string type, int version)
  196. {
  197. DbCommand cmd = _conn.CreateCommand();
  198. cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
  199. m_log.InfoFormat("[MIGRATIONS] Updating {0} to version {1}", type, version);
  200. cmd.ExecuteNonQuery();
  201. }
  202. // private SortedList<int, string> GetAllMigrations()
  203. // {
  204. // return GetMigrationsAfter(0);
  205. // }
  206. private SortedList<int, string> GetMigrationsAfter(int after)
  207. {
  208. string[] names = _assem.GetManifestResourceNames();
  209. SortedList<int, string> migrations = new SortedList<int, string>();
  210. // because life is funny if we don't
  211. Array.Sort(names);
  212. foreach (string s in names)
  213. {
  214. m_log.InfoFormat("[MIGRATION] - testing resoure {0}", s);
  215. Match m = _match.Match(s);
  216. if (m.Success)
  217. {
  218. m_log.Info("MIGRATION: Match: " + m.Groups[1].ToString());
  219. int version = int.Parse(m.Groups[1].ToString());
  220. if (version > after) {
  221. using (Stream resource = _assem.GetManifestResourceStream(s))
  222. {
  223. using (StreamReader resourceReader = new StreamReader(resource))
  224. {
  225. string resourceString = resourceReader.ReadToEnd();
  226. migrations.Add(version, resourceString);
  227. }
  228. }
  229. }
  230. }
  231. }
  232. if (migrations.Count < 1) {
  233. m_log.InfoFormat("[MIGRATIONS] {0} up to date, no migrations to apply", _type);
  234. }
  235. return migrations;
  236. }
  237. }
  238. }