diff --git a/src/Commons/Data/DataAccess.cs b/src/Commons/Data/DataAccess.cs index 3bad94b1c..c43de7ba7 100644 --- a/src/Commons/Data/DataAccess.cs +++ b/src/Commons/Data/DataAccess.cs @@ -89,10 +89,10 @@ public DataTable GetDataTable(string sql) /// /// Returns a DataTable object populated by a . /// - public DataTable GetDataTable(DataAccessCommand cmd) + public DataTable GetDataTable(DataAccessCommand command) { var dataTable = new DataTable(); - ExecuteDataCommand(cmd, dataAdapter => dataAdapter.Fill(dataTable)); + ExecuteDataCommand(command, dataAdapter => dataAdapter.Fill(dataTable)); return dataTable; } @@ -107,18 +107,18 @@ public DataSet GetDataSet(string sql) /// /// Returns a DataSet object populated by a . /// - public DataSet GetDataSet(DataAccessCommand cmd) + public DataSet GetDataSet(DataAccessCommand command) { var dataSet = new DataSet(); - ExecuteDataCommand(cmd, dataAdapter => dataAdapter.Fill(dataSet)); + ExecuteDataCommand(command, dataAdapter => dataAdapter.Fill(dataSet)); return dataSet; } - private void ExecuteDataCommand(DataAccessCommand cmd, Action fillAction) + private void ExecuteDataCommand(DataAccessCommand command, Action fillAction) { try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = CreateConnection(); using (dbCommand.Connection) @@ -127,16 +127,12 @@ private void ExecuteDataCommand(DataAccessCommand cmd, Action fil dataAdapter!.SelectCommand = dbCommand; fillAction(dataAdapter); - foreach (var parameter in cmd.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } } @@ -184,28 +180,24 @@ public DataTable GetDataTable(ref DbConnection sqlConn, string sql) /// ExecuteScalar command and returns the first column of the first row in the result set returned by the query. /// All other columns and rows are ignored. /// - public object? GetResult(DataAccessCommand cmd) + public object? GetResult(DataAccessCommand command) { object? scalarResult; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = CreateConnection(); using (dbCommand.Connection) { scalarResult = dbCommand.ExecuteScalar(); - foreach (var param in cmd.Parameters) - { - if (param.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - param.Value = dbCommand.Parameters[param.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return scalarResult; @@ -215,18 +207,18 @@ public DataTable GetDataTable(ref DbConnection sqlConn, string sql) /// ExecuteScalar command and returns the first column of the first row in the result set returned by the query. /// All other columns and rows are ignored. /// - /// Command + /// Command /// Open Connection /// Transactions with Connection /// Returns a DataTable object populated by a . /// This method uses a by ref. /// - public object? GetResult(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTransaction trans) + public object? GetResult(DataAccessCommand command, ref DbConnection sqlConn, ref DbTransaction trans) { object? scalarResult; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = sqlConn; dbCommand.Transaction = trans; @@ -237,7 +229,7 @@ public DataTable GetDataTable(ref DbConnection sqlConn, string sql) } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return scalarResult; @@ -246,28 +238,24 @@ public DataTable GetDataTable(ref DbConnection sqlConn, string sql) /// /// ExecuteNonQuery command in the database and return the number of affected records. /// - public int SetCommand(DataAccessCommand cmd) + public int SetCommand(DataAccessCommand command) { int rowsAffected = 0; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = CreateConnection(); using (dbCommand.Connection) { rowsAffected += dbCommand.ExecuteNonQuery(); - foreach (var parameter in cmd.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command,dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return rowsAffected; @@ -278,7 +266,7 @@ public int SetCommand(DataAccessCommand cmd) /// Author: Lucio Pelinson 14-04-2012 public int SetCommand(IEnumerable commands) { - int numberOfRowsAffected = 0; + var numberOfRowsAffected = 0; DataAccessCommand? currentCommand = null; var connection = CreateConnection(); @@ -324,28 +312,29 @@ public int SetCommand(string sql) /// Author: Lucio Pelinson 14-04-2012 public int SetCommand(IEnumerable sqlList) { - var commandList = from string sql in sqlList select new DataAccessCommand(sql); + var commandList = sqlList.Select(sql => new DataAccessCommand(sql)); - int numberOfRowsAffected = SetCommand(commandList); + var numberOfRowsAffected = SetCommand(commandList); + return numberOfRowsAffected; } /// /// Execute the command in the database and return the number of affected records. /// - /// Command + /// Command /// Open Connection /// Transactions with Connection /// /// Returns a DataTable object populated by a . /// This method uses a and a by ref. /// - public int SetCommand(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTransaction trans) + public int SetCommand(DataAccessCommand command, ref DbConnection sqlConn, ref DbTransaction trans) { int numberOfRowsAffected = 0; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = sqlConn; dbCommand.Transaction = trans; using (dbCommand.Connection) @@ -355,7 +344,7 @@ public int SetCommand(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTra } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return numberOfRowsAffected; @@ -378,17 +367,17 @@ public int SetCommand(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTra /// Retrieves the first record of the sql statement in a Hashtable object. /// [key(database field), value(value stored in database)] /// - /// Command + /// Command /// /// Return a Hashtable Object. /// If no record is found it returns null. /// - public Hashtable? GetHashtable(DataAccessCommand cmd) + public Hashtable? GetHashtable(DataAccessCommand command) { Hashtable? retCollection = null; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = CreateConnection(); using (dbCommand.Connection) @@ -398,30 +387,23 @@ public int SetCommand(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTra while (dr.Read()) { retCollection = new Hashtable(StringComparer.InvariantCultureIgnoreCase); - int nQtd = 0; - - while (nQtd < dr.FieldCount) + for (var nQtd = 0; nQtd < dr.FieldCount; nQtd++) { string fieldName = dr.GetName(nQtd); if (retCollection.ContainsKey(fieldName)) throw new DataAccessException($"[{fieldName}] field duplicated in get procedure"); retCollection.Add(fieldName, dr.GetValue(nQtd)); - nQtd += 1; } } } - foreach (var parameter in cmd.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return retCollection; @@ -431,17 +413,17 @@ public int SetCommand(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTra /// Retrieves the records of the sql statement in a Dictionary object. /// [key(database field), value(value stored in database)] /// - /// Command + /// Command /// /// Return a Dictionary Object. /// If no record is found it returns null. /// - public Dictionary? GetDictionary(DataAccessCommand cmd) + public Dictionary? GetDictionary(DataAccessCommand command) { Dictionary? retCollection = null; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = CreateConnection(); using (dbCommand.Connection) @@ -462,32 +444,17 @@ public int SetCommand(DataAccessCommand cmd, ref DbConnection sqlConn, ref DbTra } } - foreach (var parameter in cmd.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return retCollection; } - /// - /// Check if table exists in the database - /// - public bool TableExists(string tableName) - { - var ret = GetResult(GetTableExistsCommand(tableName)); - var result = ret as int? == 1; - - return result; - } - /// Verify the database connection /// True if the connection is successful. /// Author: Lucio Pelinson 28-04-2014 @@ -568,25 +535,52 @@ public bool ExecuteBatch(string script) return true; } - - private static DataAccessCommand GetTableExistsCommand(string table) + + public List> GetDictionaryList(DataAccessCommand command) { - const string sql = "SELECT COUNT(1) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @Table"; - var command = new DataAccessCommand + var dictionaryList = new List>(); + + try { - Sql = sql, - Parameters = + using var dbCommand = CreateDbCommand(command); + dbCommand.Connection = CreateConnection(); + using (dbCommand.Connection) { - new DataAccessParameter + using (var dataReader = dbCommand.ExecuteReader()) { - Name = "@Table", - Value = table + List columnNames = []; + for (var i = 0; i < dataReader.FieldCount; i++) + { + columnNames.Add(dataReader.GetName(i)); + } + + while ( dataReader.Read()) + { + var dictionary = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + foreach (var columnName in columnNames) + { + var ordinal = dataReader.GetOrdinal(columnName); + var value = dataReader.IsDBNull(ordinal) + ? null + : dataReader.GetValue(ordinal); + dictionary[columnName] = value; + } + + dictionaryList.Add(dictionary); + } } + + SetOutputParameters(command, dbCommand); } - }; + } + catch (Exception ex) + { + throw GetDataAccessException(ex, command); + } - return command; + return dictionaryList; } + private static Exception GetDataAccessException(Exception ex, DataAccessCommand? cmd) { return GetDataAccessException(ex, cmd?.Sql ?? string.Empty, cmd?.Parameters); @@ -622,14 +616,17 @@ private static Exception GetDataAccessException( private DbCommand CreateDbCommand(DataAccessCommand command) { var dbCommand = _dbProviderFactory.CreateCommand(); + if (dbCommand == null) throw new ArgumentException(nameof(dbCommand)); if (string.IsNullOrEmpty(command.Sql)) throw new DataAccessException("Sql Command cannot be null or empty."); + dbCommand.CommandType = command.Type; dbCommand.CommandText = command.Sql; dbCommand.CommandTimeout = TimeOut; + foreach (var parameter in command.Parameters) { var dbParameter = CreateDbParameter(parameter); @@ -653,67 +650,13 @@ private DbParameter CreateDbParameter(DataAccessParameter parameter) return dbParameter; } - - private static DataAccessCommand GetColumnExistsCommand(string tableName, string columnName) - { - var command = new DataAccessCommand - { - Sql = - "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName" - }; - - command.AddParameter("@TableName", tableName, DbType.AnsiString); - command.AddParameter("@ColumnName", columnName, DbType.AnsiString); - - return command; - } - public List> GetDictionaryList(DataAccessCommand cmd) + private static void SetOutputParameters(DataAccessCommand dataAccessCommand, DbCommand dbCommand) { - var dictionaryList = new List>(); - - try + foreach (var parameter in dataAccessCommand.Parameters) { - using var dbCommand = CreateDbCommand(cmd); - dbCommand.Connection = CreateConnection(); - using (dbCommand.Connection) - { - using (var dataReader = dbCommand.ExecuteReader()) - { - List columnNames = []; - for (var i = 0; i < dataReader.FieldCount; i++) - { - columnNames.Add(dataReader.GetName(i)); - } - - while ( dataReader.Read()) - { - var dictionary = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - foreach (var columnName in columnNames) - { - var ordinal = dataReader.GetOrdinal(columnName); - var value = dataReader.IsDBNull(ordinal) - ? null - : dataReader.GetValue(ordinal); - dictionary[columnName] = value; - } - - dictionaryList.Add(dictionary); - } - } - - foreach (var param in cmd.Parameters.Where(param => - param.Direction is ParameterDirection.Output or ParameterDirection.InputOutput)) - { - param.Value = dbCommand.Parameters[param.Name].Value; - } - } - } - catch (Exception ex) - { - throw GetDataAccessException(ex, cmd); + if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) + parameter.Value = dbCommand.Parameters[parameter.Name].Value; } - - return dictionaryList; } } \ No newline at end of file diff --git a/src/Commons/Data/DataAccessAsync.cs b/src/Commons/Data/DataAccessAsync.cs index 652abd799..6051c7e9b 100644 --- a/src/Commons/Data/DataAccessAsync.cs +++ b/src/Commons/Data/DataAccessAsync.cs @@ -47,11 +47,7 @@ public async Task GetDataTableAsync(DataAccessCommand command, Cancel var dataTable = new DataTable(); dataTable.Load(reader); - foreach (var parameter in command.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); return dataTable; } @@ -93,11 +89,7 @@ public async Task GetDataSetAsync(DataAccessCommand command, Cancellati index++; } while(!reader.IsClosed); - foreach (var parameter in command.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); return dataSet; } @@ -116,54 +108,46 @@ public async Task GetDataSetAsync(DataAccessCommand command, Cancellati } /// - public async Task GetResultAsync(DataAccessCommand cmd, CancellationToken cancellationToken = default) + public async Task GetResultAsync(DataAccessCommand command, CancellationToken cancellationToken = default) { object? scalarResult; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = await CreateConnectionAsync(cancellationToken); using (dbCommand.Connection) { scalarResult = await dbCommand.ExecuteScalarAsync(cancellationToken); - foreach (var parameter in cmd.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return scalarResult; } /// - public async Task SetCommandAsync(DataAccessCommand cmd, CancellationToken cancellationToken = default) + public async Task SetCommandAsync(DataAccessCommand command, CancellationToken cancellationToken = default) { int rowsAffected; try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = await CreateConnectionAsync(cancellationToken); using (dbCommand.Connection) { rowsAffected = await dbCommand.ExecuteNonQueryAsync(cancellationToken); - foreach (var parameter in cmd.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return rowsAffected; @@ -254,11 +238,7 @@ await dbCommand.ExecuteReaderAsync(CommandBehavior.SingleRow, cancellationToken) } } - foreach (var parameter in command.Parameters) - { - if (parameter.Direction is ParameterDirection.Output or ParameterDirection.InputOutput) - parameter.Value = dbCommand.Parameters[parameter.Name].Value; - } + SetOutputParameters(command, dbCommand); } } catch (Exception ex) @@ -269,13 +249,14 @@ await dbCommand.ExecuteReaderAsync(CommandBehavior.SingleRow, cancellationToken) return result; } - public async Task>> GetDictionaryListAsync(DataAccessCommand cmd, CancellationToken cancellationToken = default) + + public async Task>> GetDictionaryListAsync(DataAccessCommand command, CancellationToken cancellationToken = default) { var dictionaryList = new List>(); try { - using var dbCommand = CreateDbCommand(cmd); + using var dbCommand = CreateDbCommand(command); dbCommand.Connection = await CreateConnectionAsync(cancellationToken); using var connection = dbCommand.Connection; @@ -304,27 +285,15 @@ await dbCommand.ExecuteReaderAsync(CommandBehavior.SingleRow, cancellationToken) } } - foreach (var param in cmd.Parameters.Where(param => - param.Direction is ParameterDirection.Output or ParameterDirection.InputOutput)) - { - param.Value = dbCommand.Parameters[param.Name].Value; - } + SetOutputParameters(command, dbCommand); } catch (Exception ex) { - throw GetDataAccessException(ex, cmd); + throw GetDataAccessException(ex, command); } return dictionaryList; } - - /// - public async Task TableExistsAsync(string tableName, CancellationToken cancellationToken = default) - { - var command = GetTableExistsCommand(tableName); - var result = await GetResultAsync(command, cancellationToken); - return (int)result! == 1; - } /// public async Task TryConnectionAsync(CancellationToken cancellationToken = default) @@ -401,26 +370,4 @@ public async Task ExecuteBatchAsync(string script, CancellationToken cance await SetCommandAsync(sqlList, cancellationToken); return true; } - - public async Task ColumnExistsAsync(string tableName, string columnName, CancellationToken cancellationToken = default) - { - var command = GetColumnExistsCommand(tableName, columnName); - try - { - using var dbCommand = CreateDbCommand(command); - dbCommand.Connection = await CreateConnectionAsync(cancellationToken); - using (dbCommand.Connection) - { - using (var reader = - await dbCommand.ExecuteReaderAsync(CommandBehavior.SingleRow, cancellationToken)) - { - return await reader.ReadAsync(cancellationToken); - } - } - } - catch (Exception ex) - { - throw GetDataAccessException(ex, command); - } - } } \ No newline at end of file diff --git a/src/Commons/Data/Entity/Providers/EntityProviderBase.cs b/src/Commons/Data/Entity/Providers/EntityProviderBase.cs index 64cf4624c..d54a22df9 100644 --- a/src/Commons/Data/Entity/Providers/EntityProviderBase.cs +++ b/src/Commons/Data/Entity/Providers/EntityProviderBase.cs @@ -5,6 +5,7 @@ using System.Data; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using JJMasterData.Commons.Configuration.Options; using JJMasterData.Commons.Data.Entity.Models; @@ -300,4 +301,13 @@ internal DataAccess GetDataAccess(Guid? connectionId) var connection = Options.GetConnectionString(connectionId); return new DataAccess(connection.Connection, connection.ConnectionProvider); } + + public abstract bool TableExists(string tableName, Guid? connectionId = null); + public abstract Task TableExistsAsync(string tableName, Guid? connectionId = null, CancellationToken cancellationToken = default); + + public abstract Task ColumnExistsAsync( + string tableName, + string columnName, + Guid? connectionId = null, + CancellationToken cancellationToken = default); } diff --git a/src/Commons/Data/Entity/Providers/OracleProvider.cs b/src/Commons/Data/Entity/Providers/OracleProvider.cs index 512217894..583e1c51f 100644 --- a/src/Commons/Data/Entity/Providers/OracleProvider.cs +++ b/src/Commons/Data/Entity/Providers/OracleProvider.cs @@ -4,6 +4,7 @@ using System.Data; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using JJMasterData.Commons.Configuration.Options; using JJMasterData.Commons.Data.Entity.Models; @@ -802,6 +803,23 @@ protected override DataAccessCommand GetInsertOrReplaceCommand(Element element, return GetCommandWrite(string.Empty, element, values); } + public override bool TableExists(string tableName, Guid? connectionId = null) + { + throw new NotImplementedException(); + } + + public override Task TableExistsAsync(string tableName, Guid? connectionId = null, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public override Task ColumnExistsAsync(string tableName, string columnName, Guid? connectionId = null, + CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public override string GetAlterTableScript(Element element, IEnumerable fields) { return "Not implemented"; diff --git a/src/Commons/Data/Entity/Providers/SQLiteProvider.cs b/src/Commons/Data/Entity/Providers/SQLiteProvider.cs index 7b370d066..004a9147a 100644 --- a/src/Commons/Data/Entity/Providers/SQLiteProvider.cs +++ b/src/Commons/Data/Entity/Providers/SQLiteProvider.cs @@ -4,6 +4,7 @@ using System.Data; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using JJMasterData.Commons.Configuration.Options; using JJMasterData.Commons.Data.Entity.Models; @@ -269,6 +270,22 @@ protected override DataAccessCommand GetInsertOrReplaceCommand(Element element, return GetScriptInsert(element, values, true); } + public override bool TableExists(string tableName, Guid? connectionId = null) + { + throw new NotImplementedException(); + } + + public override Task TableExistsAsync(string tableName, Guid? connectionId = null, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public override Task ColumnExistsAsync(string tableName, string columnName, Guid? connectionId = null, + CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + public override DataAccessCommand GetReadCommand(Element element, EntityParameters entityParameters, DataAccessParameter totalOfRecordsParameter) { diff --git a/src/Commons/Data/Entity/Providers/SqlServer/SqlServerProvider.cs b/src/Commons/Data/Entity/Providers/SqlServer/SqlServerProvider.cs index f59ef24a0..9f44ddf6c 100644 --- a/src/Commons/Data/Entity/Providers/SqlServer/SqlServerProvider.cs +++ b/src/Commons/Data/Entity/Providers/SqlServer/SqlServerProvider.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Data; +using System.Threading; using System.Threading.Tasks; using JJMasterData.Commons.Configuration.Options; using JJMasterData.Commons.Data.Entity.Models; @@ -301,7 +302,7 @@ public override async Task GetElementFromTableAsync(string tableName, G if (string.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName)); - if (!await dataAccess.TableExistsAsync(tableName)) + if (!await TableExistsAsync(tableName)) throw new JJMasterDataException($"Table {tableName} not found"); var element = new Element @@ -353,4 +354,63 @@ public override async Task GetElementFromTableAsync(string tableName, G return element; } + + /// + /// Check if table exists in the database + /// + public override bool TableExists(string tableName, Guid? connectionId = null) + { + var dataAccess = GetDataAccess(connectionId); + var result = dataAccess.GetResult(GetTableExistsCommand(tableName)); + return result as int? == 1; + } + + /// + public override async Task TableExistsAsync(string tableName, Guid? connectionId = null, CancellationToken cancellationToken = default) + { + var dataAccess = GetDataAccess(connectionId); + var command = GetTableExistsCommand(tableName); + var result = await dataAccess.GetResultAsync(command, cancellationToken); + return result as int? == 1; + } + + public override async Task ColumnExistsAsync(string tableName, string columnName, Guid? connectionId = null, CancellationToken cancellationToken = default) + { + var dataAccess = GetDataAccess(connectionId); + var command = GetColumnExistsCommand(tableName, columnName); + var result = await dataAccess.GetResultAsync(command, cancellationToken); + return result as int? == 1; + } + + private static DataAccessCommand GetTableExistsCommand(string table) + { + const string sql = "SELECT COUNT(1) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @Table"; + var command = new DataAccessCommand + { + Sql = sql, + Parameters = + { + new DataAccessParameter + { + Name = "@Table", + Value = table + } + } + }; + + return command; + } + + private static DataAccessCommand GetColumnExistsCommand(string tableName, string columnName) + { + var command = new DataAccessCommand + { + Sql = "SELECT COUNT(1) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName" + }; + + command.AddParameter("@TableName", tableName, DbType.AnsiString); + command.AddParameter("@ColumnName", columnName, DbType.AnsiString); + + return command; + } } \ No newline at end of file diff --git a/src/Commons/Data/Entity/Repository/EntityRepository.cs b/src/Commons/Data/Entity/Repository/EntityRepository.cs index 66e6a8633..77f8ed371 100644 --- a/src/Commons/Data/Entity/Repository/EntityRepository.cs +++ b/src/Commons/Data/Entity/Repository/EntityRepository.cs @@ -73,14 +73,12 @@ public Task GetElementFromTableAsync(string tableName, Guid? connection public Task TableExistsAsync(string tableName, Guid? connectionId = null) { - var dataAccess = GetDataAccess(connectionId); - return dataAccess.TableExistsAsync(tableName); + return provider.TableExistsAsync(tableName); } public bool TableExists(string tableName, Guid? connectionId = null) { - var dataAccess = GetDataAccess(connectionId); - return dataAccess.TableExists(tableName); + return provider.TableExists(tableName, connectionId); } public async Task SetCommandAsync(DataAccessCommand command, Guid? connectionId = null) @@ -97,8 +95,7 @@ public Task SetCommandListAsync(IEnumerable commandList, private Task ColumnExistsAsync(string tableName, string columnName, Guid? connectionId = null) { - var dataAccess = GetDataAccess(connectionId); - return dataAccess.ColumnExistsAsync(tableName, columnName); + return provider.ColumnExistsAsync(tableName, columnName, connectionId); } public Task ExecuteBatchAsync(string script, Guid? connectionId = null) diff --git a/test/Commons.Test/Data/DataAccessTest.cs b/test/Commons.Test/Data/DataAccessTest.cs index 87793fa24..a7abfc709 100644 --- a/test/Commons.Test/Data/DataAccessTest.cs +++ b/test/Commons.Test/Data/DataAccessTest.cs @@ -20,14 +20,6 @@ private void ConfigureSeedValues() DataAccess.ExecuteBatch(sql); } - [Theory] - [InlineData(TableName,true)] - [InlineData("Foo",false)] - public async Task TableExistsTest(string table, bool exists) - { - Assert.Equal(exists, await DataAccess.TableExistsAsync(table)); - } - [Fact] public async Task GetDataTableTest() {