/// <summary>Connect to the SQLite database.</summary> /// <param name="forWriting">if set to <c>true</c> [for writing].</param> /// <exception cref="Models.Core.ApsimXException">Cannot find name of .db file</exception> private void Open(bool forWriting) { lock (Locks) { if (Filename == null) { Simulations simulations = Apsim.Parent(this, typeof(Simulations)) as Simulations; if (simulations != null) Filename = Path.ChangeExtension(simulations.FileName, ".db"); } if (Filename != null && (Connection == null || (ForWriting == false && forWriting == true))) { if (Filename == null) throw new ApsimXException(this, "Cannot find name of .db file"); Disconnect(); ForWriting = forWriting; if (!Locks.ContainsKey(Filename)) Locks.Add(Filename, new DbMutex()); Locks[Filename].Aquire(); try { if (!File.Exists(Filename)) { Connection = new SQLite(); Connection.OpenDatabase(Filename, readOnly: false); Connection.ExecuteNonQuery("CREATE TABLE Simulations (ID INTEGER PRIMARY KEY ASC, Name TEXT COLLATE NOCASE)"); Connection.ExecuteNonQuery("CREATE TABLE Messages (SimulationID INTEGER, ComponentName TEXT, Date TEXT, Message TEXT, MessageType INTEGER)"); if (!forWriting) { Connection.CloseDatabase(); Connection.OpenDatabase(Filename, readOnly: !forWriting); } } else { Connection = new SQLite(); Connection.OpenDatabase(Filename, readOnly: !forWriting); } } finally { Locks[Filename].Release(); } } } }
/// <summary> /// Go through the specified names and add them to the specified table if they are not /// already there. /// </summary> /// <param name="Connection">The connection.</param> /// <param name="tableName">Name of the table.</param> /// <param name="names">The names.</param> /// <param name="types">The types.</param> private static void AddMissingColumnsToTable(SQLite Connection, string tableName, string[] names, Type[] types) { List<string> columnNames = Connection.GetColumnNames(tableName); for (int i = 0; i < names.Length; i++) { if (!columnNames.Contains(names[i], StringComparer.OrdinalIgnoreCase)) { string sql = "ALTER TABLE " + tableName + " ADD COLUMN ["; sql += names[i] + "] " + GetSQLColumnType(types[i]); Connection.ExecuteNonQuery(sql); } } }