Migration.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. protected string _type;
  72. protected DbConnection _conn;
  73. protected Assembly _assem;
  74. private Regex _match_old;
  75. private Regex _match_new;
  76. /// <summary>Have the parameterless constructor just so we can specify it as a generic parameter with the new() constraint.
  77. /// Currently this is only used in the tests. A Migration instance created this way must be then
  78. /// initialized with Initialize(). Regular creation should be through the parameterized constructors.
  79. /// </summary>
  80. public Migration()
  81. {
  82. }
  83. public Migration(DbConnection conn, Assembly assem, string subtype, string type)
  84. {
  85. Initialize(conn, assem, type, subtype);
  86. }
  87. public Migration(DbConnection conn, Assembly assem, string type)
  88. {
  89. Initialize(conn, assem, type, "");
  90. }
  91. /// <summary>Must be called after creating with the parameterless constructor.
  92. /// NOTE that the Migration class now doesn't access database in any way during initialization.
  93. /// Specifically, it won't check if the [migrations] table exists. Such checks are done later:
  94. /// automatically on Update(), or you can explicitly call InitMigrationsTable().
  95. /// </summary>
  96. /// <param name="conn"></param>
  97. /// <param name="assem"></param>
  98. /// <param name="subtype"></param>
  99. /// <param name="type"></param>
  100. public void Initialize (DbConnection conn, Assembly assem, string type, string subtype)
  101. {
  102. _type = type;
  103. _conn = conn;
  104. _assem = assem;
  105. _match_old = new Regex(subtype + @"\.(\d\d\d)_" + _type + @"\.sql");
  106. string s = String.IsNullOrEmpty(subtype) ? _type : _type + @"\." + subtype;
  107. _match_new = new Regex(@"\." + s + @"\.migrations(?:\.(?<ver>\d+)$|.*)");
  108. }
  109. public void InitMigrationsTable()
  110. {
  111. // NOTE: normally when the [migrations] table is created, the version record for 'migrations' is
  112. // added immediately. However, if for some reason the table is there but empty, we want to handle that as well.
  113. int ver = FindVersion(_conn, "migrations");
  114. if (ver <= 0) // -1 = no table, 0 = no version record
  115. {
  116. if( ver < 0 )
  117. ExecuteScript("create table migrations(name varchar(100), version int)");
  118. InsertVersion("migrations", 1);
  119. }
  120. }
  121. /// <summary>Executes a script, possibly in a database-specific way.
  122. /// It can be redefined for a specific DBMS, if necessary. Specifically,
  123. /// to avoid problems with proc definitions in MySQL, we must use
  124. /// MySqlScript class instead of just DbCommand. We don't want to bring
  125. /// MySQL references here, so instead define a MySQLMigration class
  126. /// in OpenSim.Data.MySQL
  127. /// </summary>
  128. /// <param name="conn"></param>
  129. /// <param name="script">Array of strings, one-per-batch (often just one)</param>
  130. protected virtual void ExecuteScript(DbConnection conn, string[] script)
  131. {
  132. using (DbCommand cmd = conn.CreateCommand())
  133. {
  134. cmd.CommandTimeout = 0;
  135. foreach (string sql in script)
  136. {
  137. cmd.CommandText = sql;
  138. try
  139. {
  140. cmd.ExecuteNonQuery();
  141. }
  142. catch(Exception e)
  143. {
  144. throw new Exception(e.Message + " in SQL: " + sql);
  145. }
  146. }
  147. }
  148. }
  149. protected void ExecuteScript(DbConnection conn, string sql)
  150. {
  151. ExecuteScript(conn, new string[]{sql});
  152. }
  153. protected void ExecuteScript(string sql)
  154. {
  155. ExecuteScript(_conn, sql);
  156. }
  157. protected void ExecuteScript(string[] script)
  158. {
  159. ExecuteScript(_conn, script);
  160. }
  161. public void Update()
  162. {
  163. InitMigrationsTable();
  164. int version = FindVersion(_conn, _type);
  165. SortedList<int, string[]> migrations = GetMigrationsAfter(version);
  166. if (migrations.Count < 1)
  167. return;
  168. // to prevent people from killing long migrations.
  169. m_log.InfoFormat("[MIGRATIONS]: Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]);
  170. m_log.Info("[MIGRATIONS]: NOTE - this may take a while, don't interrupt this process!");
  171. foreach (KeyValuePair<int, string[]> kvp in migrations)
  172. {
  173. int newversion = kvp.Key;
  174. // we need to up the command timeout to infinite as we might be doing long migrations.
  175. /* [AlexRa 01-May-10]: We can't always just run any SQL in a single batch (= ExecuteNonQuery()). Things like
  176. * stored proc definitions might have to be sent to the server each in a separate batch.
  177. * This is certainly so for MS SQL; not sure how the MySQL connector sorts out the mess
  178. * with 'delimiter @@'/'delimiter ;' around procs. So each "script" this code executes now is not
  179. * a single string, but an array of strings, executed separately.
  180. */
  181. try
  182. {
  183. ExecuteScript(kvp.Value);
  184. }
  185. catch (Exception e)
  186. {
  187. m_log.DebugFormat("[MIGRATIONS]: Cmd was {0}", e.Message.Replace("\n", " "));
  188. m_log.Debug("[MIGRATIONS]: An error has occurred in the migration. 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.");
  189. ExecuteScript("ROLLBACK;");
  190. }
  191. if (version == 0)
  192. {
  193. InsertVersion(_type, newversion);
  194. }
  195. else
  196. {
  197. UpdateVersion(_type, newversion);
  198. }
  199. version = newversion;
  200. }
  201. }
  202. public int Version
  203. {
  204. get { return FindVersion(_conn, _type); }
  205. set {
  206. if (Version < 1)
  207. {
  208. InsertVersion(_type, value);
  209. }
  210. else
  211. {
  212. UpdateVersion(_type, value);
  213. }
  214. }
  215. }
  216. protected virtual int FindVersion(DbConnection conn, string type)
  217. {
  218. int version = 0;
  219. using (DbCommand cmd = conn.CreateCommand())
  220. {
  221. try
  222. {
  223. cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
  224. using (DbDataReader reader = cmd.ExecuteReader())
  225. {
  226. if (reader.Read())
  227. {
  228. version = Convert.ToInt32(reader["version"]);
  229. }
  230. reader.Close();
  231. }
  232. }
  233. catch
  234. {
  235. // Something went wrong (probably no table), so we're at version -1
  236. version = -1;
  237. }
  238. }
  239. return version;
  240. }
  241. private void InsertVersion(string type, int version)
  242. {
  243. m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
  244. ExecuteScript("insert into migrations(name, version) values('" + type + "', " + version + ")");
  245. }
  246. private void UpdateVersion(string type, int version)
  247. {
  248. m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
  249. ExecuteScript("update migrations set version=" + version + " where name='" + type + "'");
  250. }
  251. private delegate void FlushProc();
  252. /// <summary>Scans for migration resources in either old-style "scattered" (one file per version)
  253. /// or new-style "integrated" format (single file with ":VERSION nnn" sections).
  254. /// In the new-style migrations it also recognizes ':GO' separators for parts of the SQL script
  255. /// that must be sent to the server separately. The old-style migrations are loaded each in one piece
  256. /// and don't support the ':GO' feature.
  257. /// </summary>
  258. /// <param name="after">The version we are currently at. Scan for any higher versions</param>
  259. /// <returns>A list of string arrays, representing the scripts.</returns>
  260. private SortedList<int, string[]> GetMigrationsAfter(int after)
  261. {
  262. SortedList<int, string[]> migrations = new SortedList<int, string[]>();
  263. string[] names = _assem.GetManifestResourceNames();
  264. if( names.Length == 0 ) // should never happen
  265. return migrations;
  266. Array.Sort(names); // we want all the migrations ordered
  267. int nLastVerFound = 0;
  268. Match m = null;
  269. string sFile = Array.FindLast(names, nm => { m = _match_new.Match(nm); return m.Success; }); // ; nm.StartsWith(sPrefix, StringComparison.InvariantCultureIgnoreCase
  270. if( (m != null) && !String.IsNullOrEmpty(sFile) )
  271. {
  272. /* The filename should be '<StoreName>.migrations[.NNN]' where NNN
  273. * is the last version number defined in the file. If the '.NNN' part is recognized, the code can skip
  274. * the file without looking inside if we have a higher version already. Without the suffix we read
  275. * the file anyway and use the version numbers inside. Any unrecognized suffix (such as '.sql')
  276. * is valid but ignored.
  277. *
  278. * NOTE that we expect only one 'merged' migration file. If there are several, we take the last one.
  279. * If you are numbering them, leave only the latest one in the project or at least make sure they numbered
  280. * to come up in the correct order (e.g. 'SomeStore.migrations.001' rather than 'SomeStore.migrations.1')
  281. */
  282. if (m.Groups.Count > 1 && int.TryParse(m.Groups[1].Value, out nLastVerFound))
  283. {
  284. if( nLastVerFound <= after )
  285. goto scan_old_style;
  286. }
  287. System.Text.StringBuilder sb = new System.Text.StringBuilder(4096);
  288. int nVersion = -1;
  289. List<string> script = new List<string>();
  290. FlushProc flush = delegate()
  291. {
  292. if (sb.Length > 0) // last SQL stmt to script list
  293. {
  294. script.Add(sb.ToString());
  295. sb.Length = 0;
  296. }
  297. if ( (nVersion > 0) && (nVersion > after) && (script.Count > 0) && !migrations.ContainsKey(nVersion)) // script to the versioned script list
  298. {
  299. migrations[nVersion] = script.ToArray();
  300. }
  301. script.Clear();
  302. };
  303. using (Stream resource = _assem.GetManifestResourceStream(sFile))
  304. using (StreamReader resourceReader = new StreamReader(resource))
  305. {
  306. int nLineNo = 0;
  307. while (!resourceReader.EndOfStream)
  308. {
  309. string sLine = resourceReader.ReadLine();
  310. nLineNo++;
  311. if( String.IsNullOrEmpty(sLine) || sLine.StartsWith("#") ) // ignore a comment or empty line
  312. continue;
  313. if (sLine.Trim().Equals(":GO", StringComparison.InvariantCultureIgnoreCase))
  314. {
  315. if (sb.Length == 0) continue;
  316. if (nVersion > after)
  317. script.Add(sb.ToString());
  318. sb.Length = 0;
  319. continue;
  320. }
  321. if (sLine.StartsWith(":VERSION ", StringComparison.InvariantCultureIgnoreCase)) // ":VERSION nnn"
  322. {
  323. flush();
  324. int n = sLine.IndexOf('#'); // Comment is allowed in version sections, ignored
  325. if (n >= 0)
  326. sLine = sLine.Substring(0, n);
  327. if (!int.TryParse(sLine.Substring(9).Trim(), out nVersion))
  328. {
  329. m_log.ErrorFormat("[MIGRATIONS]: invalid version marker at {0}: line {1}. Migration failed!", sFile, nLineNo);
  330. break;
  331. }
  332. }
  333. else
  334. {
  335. sb.AppendLine(sLine);
  336. }
  337. }
  338. flush();
  339. // If there are scattered migration files as well, only look for those with higher version numbers.
  340. if (after < nVersion)
  341. after = nVersion;
  342. }
  343. }
  344. scan_old_style:
  345. // scan "old style" migration pieces anyway, ignore any versions already filled from the single file
  346. foreach (string s in names)
  347. {
  348. m = _match_old.Match(s);
  349. if (m.Success)
  350. {
  351. int version = int.Parse(m.Groups[1].ToString());
  352. if ( (version > after) && !migrations.ContainsKey(version) )
  353. {
  354. using (Stream resource = _assem.GetManifestResourceStream(s))
  355. {
  356. using (StreamReader resourceReader = new StreamReader(resource))
  357. {
  358. string sql = resourceReader.ReadToEnd();
  359. migrations.Add(version, new string[]{sql});
  360. }
  361. }
  362. }
  363. }
  364. }
  365. if (migrations.Count < 1)
  366. {
  367. m_log.InfoFormat("[MIGRATIONS]: {0} up to date, no migrations to apply", _type);
  368. }
  369. return migrations;
  370. }
  371. }
  372. }