public bool Save(string connectionString) { try { using (var conn = new SqlConnection()) { conn.ConnectionString = connectionString; conn.Open(); using (var command = new SqlCommand(GetVersionUpdateScript(), conn)) { SqlServers.ExecuteCommand(command); } return(true); } } catch (Exception ex) { return(false); throw; } }
internal static void ExecuteSQL(SqlConnection connection, SqlTransaction transaction, string sql, InstallSetup setup, List <KeyValuePair <Guid, string> > failedScripts, List <Guid> successOrderScripts) { if (sql.StartsWith("--##METHODCALL")) { CallMethod(sql, connection, transaction, setup); return; } //Test for empty statements var originalSQL = sql.Trim(); sql = originalSQL; if (string.IsNullOrEmpty(sql)) { return; } //Test for noop statements (all comments/empty strings) var lines = sql.BreakLines().TrimAll(); lines.RemoveAll(x => x.StartsWith("--")); lines.RemoveAll(x => x == ""); if ([email protected]()) { return; } lines = sql.BreakLines().TrimAll(); //Reset #region Get Script Key var isBody = false; var key = Guid.NewGuid(); var l = lines.FirstOrDefault(x => x.StartsWith("--MODELID: ")); if (l != null) { lines.Remove(l); l = l.Replace("--MODELID:", string.Empty).Trim(); sql = string.Join("\n", lines.ToArray()); //Remove the model key from the SQL before run //if (!Guid.TryParse(l, out key)) key = Guid.NewGuid(); } else { l = lines.FirstOrDefault(x => x.StartsWith("--MODELID,BODY: ")); if (l != null) { lines.Remove(l); l = l.Replace("--MODELID,BODY:", string.Empty).Trim(); sql = string.Join("\n", lines.ToArray()); //Remove the model key from the SQL before run if (!Guid.TryParse(l, out key)) { key = Guid.NewGuid(); } else { isBody = true; } } } #endregion if (string.IsNullOrEmpty(sql)) { return; } #region Try to remove objects before creation var dropObjectName = string.Empty; var dropSQL = GetSQLDropScript(sql); //Add a bit of convenience for dropping DB objects before creation if (!string.IsNullOrEmpty(dropSQL)) { try { if (!setup.CheckOnly) { var dropCommand = new SqlCommand(dropSQL, connection); dropCommand.Transaction = transaction; dropCommand.CommandTimeout = 0; SqlServers.ExecuteCommand(dropCommand); } } catch (Exception ex) { //Ignore. The scripts should not need this. It has been added for convenience } } #endregion var command = new SqlCommand(sql, connection); command.Transaction = transaction; command.CommandTimeout = 0; try { if (!setup.CheckOnly) { var debugText = "[" + DateTime.Now.ToString() + "]\r\n"; const int MAX_SQL = 500; var sqlLength = Math.Min(sql.Length, MAX_SQL); debugText += sql.Substring(0, sqlLength); if (sqlLength == MAX_SQL) { debugText += "..."; } debugText += "\r\n\r\n"; Log.Verbose(debugText); _timer.Restart(); SqlServers.ExecuteCommand(command); _timer.Stop(); Log.Debug <long, string>("Time:{Elapsed:000} Sql:{sql}", _timer.ElapsedMilliseconds, sql); if (successOrderScripts != null && isBody) { successOrderScripts.Add(key); } } } catch (SqlException sqlexp) { if ((sqlexp.Number == 1779) && sql.StartsWith("--PRIMARY KEY FOR TABLE")) { //Ignore this error return; } else if ((sqlexp.Number == 1781) && sql.StartsWith("--DEFAULTS FOR TABLE")) { //Ignore this error return; } else if (failedScripts != null) { //Ignore this error, we will re-process it failedScripts.Add(new KeyValuePair <Guid, string>(key, originalSQL)); return; } else { throw new InvalidSQLException(sqlexp.Message, sqlexp) { SQL = sql, FileName = setup.DebugScriptName }; } } catch (Exception ex) { throw; } finally { if (command != null) { command.Dispose(); } } }
public static void Save(string connectionString, string modelKey, IEnumerable <nHydrateDbObject> list, SqlTransaction transaction) { SqlConnection conn = null; if (transaction == null) { conn = new SqlConnection(connectionString); conn.Open(); } else { conn = transaction.Connection; } try { //Create the table if need be using (var command3 = new SqlCommand("if not exists(select * from sys.tables where name = '__nhydrateobjects')" + Environment.NewLine + "CREATE TABLE [dbo].[__nhydrateobjects]" + "([rowid] [bigint] IDENTITY(1,1) NOT NULL," + "[id] [uniqueidentifier] NULL," + "[name] [nvarchar](450) NOT NULL," + "[type] [varchar](10) NOT NULL," + "[schema] [nvarchar](450) NULL," + "[CreatedDate] [datetime] NOT NULL," + "[ModifiedDate] [datetime] NOT NULL," + "[Hash] [varchar](32) NULL," + "[Status] [varchar](500) NULL," + "[ModelKey] [uniqueidentifier] NOT NULL)", conn)) { command3.Transaction = transaction; SqlServers.ExecuteCommand(command3); } //Add columns if missing { var sql = new StringBuilder(); sql.AppendLine("if exists(select * from sys.tables where name = '__nhydrateobjects') AND not exists (select * from sys.columns c inner join sys.tables t on c.object_id = t.object_id where c.name = 'status' and t.name = '__nhydrateobjects')"); sql.AppendLine("ALTER TABLE [dbo].[__nhydrateobjects] ADD [status] [Varchar] (500) NULL"); using (var command3 = new SqlCommand(sql.ToString(), conn)) { command3.Transaction = transaction; SqlServers.ExecuteCommand(command3); } } { var sql = new StringBuilder(); sql.AppendLine("delete from [__nhydrateobjects] where [id] IS NULL and ModelKey = '" + UpgradeInstaller.MODELKEY + "'"); using (var command3 = new SqlCommand(sql.ToString(), conn)) { command3.Transaction = transaction; SqlServers.ExecuteCommand(command3); } } //Save items to the table foreach (var item in list.Where(x => x.Changed)) { using (var command = new SqlCommand("if exists(select * from [__nhydrateobjects] where [id] = @id) " + "update [__nhydrateobjects] set [name] = @name, [type] = @type, [schema] = @schema, [CreatedDate] = @CreatedDate, [ModifiedDate] = @ModifiedDate, [Hash] = @Hash, [ModelKey] = @ModelKey, [Status] = @Status where [id] = @id " + "else " + "insert into [__nhydrateobjects] ([id], [name], [type], [schema], [CreatedDate], [ModifiedDate], [Hash], [ModelKey], [Status]) values (@id, @name, @type, @schema, @CreatedDate, @ModifiedDate, @Hash, @ModelKey, @Status)", conn)) { command.Transaction = transaction; command.Parameters.Add(new SqlParameter() { DbType = DbType.Guid, Value = (item.id == Guid.Empty ? System.DBNull.Value : (object)item.id), ParameterName = "@id", IsNullable = true }); command.Parameters.Add(new SqlParameter() { DbType = DbType.Int64, Value = item.rowid, ParameterName = "@rowid", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.String, Value = item.name, ParameterName = "@name", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.String, Value = item.type, ParameterName = "@type", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.String, Value = (item.schema == null ? System.DBNull.Value : (object)item.schema), ParameterName = "@schema", IsNullable = true }); command.Parameters.Add(new SqlParameter() { DbType = DbType.DateTime, Value = item.CreatedDate, ParameterName = "@CreatedDate", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.DateTime, Value = DateTime.Now, ParameterName = "@ModifiedDate", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.String, Value = item.Hash, ParameterName = "@Hash", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.Guid, Value = item.ModelKey, ParameterName = "@ModelKey", IsNullable = false }); command.Parameters.Add(new SqlParameter() { DbType = DbType.String, Value = item.Status, ParameterName = "@Status", IsNullable = true }); SqlServers.ExecuteCommand(command); } } } catch (Exception ex) { throw; } finally { if (transaction == null && conn != null) { conn.Close(); conn.Dispose(); } } }