Ejemplo n.º 1
1
        public int Update(AdoAdapter adapter, string tableName, IList<IDictionary<string, object>> data, IDbTransaction transaction, IList<string> keyFields)
        {
            int count = 0;
            if (data == null) throw new ArgumentNullException("data");
            if (data.Count < 2) throw new ArgumentException("UpdateMany requires more than one record.");

            if (keyFields.Count == 0) throw new NotSupportedException("Adapter does not support key-based update for this object.");
            if (!AllRowsHaveSameKeys(data)) throw new SimpleDataException("Records have different structures. Bulk updates are only valid on consistent records.");
            var table = adapter.GetSchema().FindTable(tableName);

            var exampleRow = new Dictionary<string, object>(data.First(), HomogenizedEqualityComparer.DefaultInstance);

            var commandBuilder = new UpdateHelper(adapter.GetSchema()).GetUpdateCommand(tableName, exampleRow,
                                                                    ExpressionHelper.CriteriaDictionaryToExpression(
                                                                        tableName, GetCriteria(keyFields, exampleRow)));

            using (var connectionScope = ConnectionScope.Create(transaction, adapter.CreateConnection))
            using (var command = commandBuilder.GetRepeatableCommand(connectionScope.Connection))
            {
                var propertyToParameterMap = CreatePropertyToParameterMap(data, table, command);

                foreach (var row in data)
                {
                    foreach (var kvp in row)
                    {
                        propertyToParameterMap[kvp.Key].Value = kvp.Value ?? DBNull.Value;
                    }
                    count += command.ExecuteNonQuery();
                }
            }

            return count;
        }
Ejemplo n.º 2
0
        public Func <object[], IDictionary <string, object> > CreateGetDelegate(string tableName, params object[] keyValues)
        {
            var primaryKey = _adapter.GetSchema().FindTable(tableName).PrimaryKey;

            if (primaryKey == null)
            {
                throw new InvalidOperationException(string.Format("Table '{0}' has no primary key.", tableName));
            }
            if (primaryKey.Length != keyValues.Length)
            {
                throw new ArgumentException("Incorrect number of values for key.");
            }


            var commandBuilder = new GetHelper(_adapter.GetSchema()).GetCommand(_adapter.GetSchema().FindTable(tableName), keyValues);

            var command = commandBuilder.GetCommand(_adapter.CreateConnection(), _adapter.AdoOptions);

            command = _adapter.CommandOptimizer.OptimizeFindOne(command);

            var commandTemplate =
                commandBuilder.GetCommandTemplate(
                    _adapter.GetSchema().FindTable(_adapter.GetSchema().BuildObjectName(tableName)));

            var cloneable = command as ICloneable;

            if (cloneable != null)
            {
                return(args => ExecuteSingletonQuery((IDbCommand)cloneable.Clone(), args, commandTemplate.Index));
            }
            return(args => ExecuteSingletonQuery(commandTemplate, args));
        }
Ejemplo n.º 3
0
        public int Update(AdoAdapter adapter, string tableName, IList <IDictionary <string, object> > data, IEnumerable <string> criteriaFieldNames, IDbTransaction transaction)
        {
            int count = 0;

            if (data == null || !data.Any())
            {
                return(count);
            }

            var criteriaFieldNameList = criteriaFieldNames.ToList();

            if (criteriaFieldNameList.Count == 0)
            {
                throw new NotSupportedException("Adapter does not support key-based update for this object.");
            }

            if (!AllRowsHaveSameKeys(data))
            {
                throw new SimpleDataException("Records have different structures. Bulk updates are only valid on consistent records.");
            }
            var table = adapter.GetSchema().FindTable(tableName);

            var exampleRow = new Dictionary <string, object>(data.First(), HomogenizedEqualityComparer.DefaultInstance);

            var commandBuilder = new UpdateHelper(adapter.GetSchema()).GetUpdateCommand(tableName, exampleRow,
                                                                                        ExpressionHelper.CriteriaDictionaryToExpression(
                                                                                            tableName, GetCriteria(criteriaFieldNameList, exampleRow)));

            var connection = adapter.CreateConnection();

            using (connection.MaybeDisposable())
                using (var command = commandBuilder.GetRepeatableCommand(connection, adapter.Options as AdoOptions))
                {
                    if (transaction != null)
                    {
                        command.Transaction = transaction;
                    }
                    connection.OpenIfClosed();
                    var propertyToParameterMap = CreatePropertyToParameterMap(data, table, command);

                    foreach (var row in data)
                    {
                        foreach (var kvp in row)
                        {
                            if (propertyToParameterMap.ContainsKey(kvp.Key))
                            {
                                propertyToParameterMap[kvp.Key].Value = kvp.Value ?? DBNull.Value;
                            }
                        }
                        count += command.TryExecuteNonQuery();
                    }
                }

            return(count);
        }
Ejemplo n.º 4
0
        public IEnumerable <IDictionary <string, object> > Find(string tableName, SimpleExpression criteria)
        {
            if (criteria == null)
            {
                return(FindAll(ObjectName.Parse(tableName)));
            }

            var commandBuilder = new FindHelper(_adapter.GetSchema()).GetFindByCommand(ObjectName.Parse(tableName), criteria);

            return(ExecuteQuery(commandBuilder));
        }
Ejemplo n.º 5
0
        public IEnumerable <IDictionary <string, object> > FindRelated(string tableName, IDictionary <string, object> row, string relatedTableName)
        {
            var join = TryJoin(tableName, relatedTableName);

            if (join == null)
            {
                throw new AdoAdapterException("Could not resolve relationship.");
            }

            return(join.Master == _adapter.GetSchema().FindTable(tableName) ? GetDetail(row, join) : GetMaster(row, join));
        }
Ejemplo n.º 6
0
        private CommandTemplate GetCommandTemplate(string tableName, SimpleExpression criteria)
        {
            var tableCommandCache = _commandCaches.GetOrAdd(tableName,
                                                            _ => new ConcurrentDictionary <string, CommandTemplate>());

            var hash = new ExpressionHasher().Format(criteria);

            return(tableCommandCache.GetOrAdd(hash,
                                              _ =>
                                              new FindHelper(_adapter.GetSchema())
                                              .GetFindByCommand(ObjectName.Parse(tableName), criteria)
                                              .GetCommandTemplate(_adapter.GetSchema().FindTable(ObjectName.Parse(tableName)))));
        }
        public object FindRelated(string tableName, IDictionary <string, object> row, string relatedTableName)
        {
            var join = TryJoin(tableName, relatedTableName);

            if (join == null)
            {
                throw new AdoAdapterException(string.Format("Could not resolve relationship of tables '{0}' and '{1}'.", tableName, relatedTableName));
            }

            if (join.Master == _adapter.GetSchema().FindTable(tableName))
            {
                return(GetDetail(row, join));
            }
            return(GetMaster(row, join));
        }
Ejemplo n.º 8
0
        public IEnumerable<IDictionary<string, object>> Insert(AdoAdapter adapter, string tableName, IEnumerable<IDictionary<string, object>> data, IDbTransaction transaction)
        {
            var table = adapter.GetSchema().FindTable(tableName);
            var columns = table.Columns.Where(c => !c.IsIdentity).ToList();

            string columnList = string.Join(",", columns.Select(c => c.QuotedName));
            string valueList = string.Join(",", columns.Select(c => "?"));

            string insertSql = "insert into " + table.QualifiedName + " (" + columnList + ") values (" + valueList + ")";

            var identityFunction = adapter.GetIdentityFunction();
            if (!string.IsNullOrWhiteSpace(identityFunction))
            {
                var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);

                if (identityColumn != null)
                {
                    var selectSql = "select * from " + table.QualifiedName + " where " + identityColumn.QuotedName +
                                     " = " + identityFunction;
                    if (adapter.ProviderSupportsCompoundStatements)
                    {
                        return InsertRowsWithCompoundStatement(adapter, data, transaction, table, columns, selectSql, insertSql);
                    }

                    return InsertRowsWithSeparateStatements(adapter, data, transaction, table, columns, insertSql, selectSql);
                }
            }

            InsertRowsWithoutFetchBack(adapter, data, table, columns, insertSql);

            return null;
        }
Ejemplo n.º 9
0
        public IEnumerable <IDictionary <string, object> > Insert(AdoAdapter adapter, string tableName, IEnumerable <IDictionary <string, object> > data, IDbTransaction transaction)
        {
            var table   = adapter.GetSchema().FindTable(tableName);
            var columns = table.Columns.Where(c => !c.IsIdentity).ToList();

            string columnList = string.Join(",", columns.Select(c => c.QuotedName));
            string valueList  = string.Join(",", columns.Select(c => "?"));

            string insertSql = "insert into " + table.QualifiedName + " (" + columnList + ") values (" + valueList + ")";

            var helper = transaction == null
                             ? new BulkInserterHelper(adapter, data, table, columns)
                             : new BulkInserterTransactionHelper(adapter, data, table, columns, transaction);

            var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);

            if (identityColumn != null)
            {
                var identityFunction = adapter.GetIdentityFunction();
                if (!string.IsNullOrWhiteSpace(identityFunction))
                {
                    return(InsertRowsAndReturn(adapter, identityFunction, helper, insertSql, table));
                }
            }

            helper.InsertRowsWithoutFetchBack(insertSql);

            return(null);
        }
Ejemplo n.º 10
0
        public IEnumerable <ResultSet> Execute(IDictionary <string, object> suppliedParameters)
        {
            var procedure = _adapter.GetSchema().FindProcedure(_procedureName);

            if (procedure == null)
            {
                throw new UnresolvableObjectException(_procedureName.ToString());
            }

            using (var cn = _adapter.CreateConnection())
                using (var command = cn.CreateCommand())
                {
                    command.CommandText = procedure.QualifiedName;
                    command.CommandType = CommandType.StoredProcedure;
                    SetParameters(procedure, command, suppliedParameters);
                    try
                    {
                        var result = _executeImpl(command);
                        if (command.Parameters.Contains(SimpleReturnParameterName))
                        {
                            suppliedParameters["__ReturnValue"] = command.Parameters.GetValue(SimpleReturnParameterName);
                        }
                        RetrieveOutputParameterValues(procedure, command, suppliedParameters);
                        return(result);
                    }
                    catch (DbException ex)
                    {
                        throw new AdoAdapterException(ex.Message, command);
                    }
                }
        }
Ejemplo n.º 11
0
        public IEnumerable<IDictionary<string, object>> Insert(AdoAdapter adapter, string tableName, IEnumerable<IDictionary<string, object>> data, IDbTransaction transaction, Func<IDictionary<string,object>, Exception, bool> onError, bool resultRequired)
        {
            var table = adapter.GetSchema().FindTable(tableName);
            var columns = table.Columns.Where(c => !c.IsIdentity).ToList();

            string columnList = string.Join(",", columns.Select(c => c.QuotedName));
            string valueList = string.Join(",", columns.Select(c => "?"));

            string insertSql = "insert into " + table.QualifiedName + " (" + columnList + ") values (" + valueList + ")";

            var helper = transaction == null
                             ? new BulkInserterHelper(adapter, data, table, columns)
                             : new BulkInserterTransactionHelper(adapter, data, table, columns, transaction);

            if (resultRequired)
            {
                var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);
                if (identityColumn != null)
                {
                    var identityFunction = adapter.GetIdentityFunction();
                    if (!string.IsNullOrWhiteSpace(identityFunction))
                    {
                        return InsertRowsAndReturn(adapter, identityFunction, helper, insertSql, table, onError);
                    }
                }
            }

            helper.InsertRowsWithoutFetchBack(insertSql, onError);

            return null;
        }
        public IEnumerable <ResultSet> Execute(IDictionary <string, object> suppliedParameters, IDbTransaction transaction)
        {
            var procedure = _adapter.GetSchema().FindProcedure(_procedureName);

            if (procedure == null)
            {
                throw new UnresolvableObjectException(_procedureName.ToString(), string.Format("Procedure '{0}' not found.", _procedureName));
            }

            var cn = transaction == null?_adapter.CreateConnection() : transaction.Connection;

            using (cn.MaybeDisposable())
                using (var command = cn.CreateCommand(_adapter.AdoOptions))
                {
                    command.Transaction = transaction;
                    command.CommandText = procedure.QualifiedName;
                    command.CommandType = CommandType.StoredProcedure;
                    SetParameters(procedure, command, suppliedParameters);
                    try
                    {
                        var result = _executeImpl(command);
                        if (command.Parameters.Contains(SimpleReturnParameterName))
                        {
                            suppliedParameters["__ReturnValue"] = command.Parameters.GetValue(SimpleReturnParameterName);
                        }
                        RetrieveOutputParameterValues(procedure, command, suppliedParameters);
                        return(result);
                    }
                    catch (DbException ex)
                    {
                        throw new AdoAdapterException(ex.Message, command, ex);
                    }
                }
        }
Ejemplo n.º 13
0
        public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction = null, bool resultRequired = false)
        {
            var table = adapter.GetSchema().FindTable(tableName);
            var dataDictionary = BuildDataDictionary(adapter, data, table);

            string columnList = dataDictionary.Keys.Select(c => c.QuotedName).Aggregate((agg, next) => agg + "," + next);
            string valueList = dataDictionary.Keys.Select(s => "?").Aggregate((agg, next) => agg + "," + next);

            var insertSql = new StringBuilder();
            bool identityInsert = adapter.AdoOptions != null && adapter.AdoOptions.IdentityInsert;
            if (identityInsert)
            {
                insertSql.AppendFormat("SET IDENTITY_INSERT {0} ON; ", table.QualifiedName);
            }
            insertSql.AppendFormat("INSERT INTO {0} ({1})", table.QualifiedName, columnList);
            if (resultRequired)
            {
                insertSql.Append(" OUTPUT INSERTED.*");
            }
            insertSql.AppendFormat(" VALUES ({0})", valueList);
            
            if (identityInsert)
            {
                insertSql.AppendFormat("; SET IDENTITY_INSERT {0} OFF; ", table.QualifiedName);
            }

            if (resultRequired)
            {
                return ExecuteSingletonQuery(adapter, insertSql.ToString(), dataDictionary.Keys,
                                             dataDictionary.Values, transaction);
            }
            Execute(adapter, insertSql.ToString(), dataDictionary.Keys, dataDictionary.Values, transaction);
            return null;
        }
Ejemplo n.º 14
0
        public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction = null,
            bool resultRequired = false)
        {
            var table = adapter.GetSchema().FindTable(tableName);

            var insertData = data.Where(p => table.HasColumn(p.Key)).Select((kv, idx) => new InsertColumn
            {
                Name = kv.Key,
                ParameterName = "@p" + idx,
                Value = kv.Value,
                Column = (FbColumn) table.FindColumn(kv.Key)
            }).ToArray();

            if (transaction == null)
            {
                using (var connection = adapter.ConnectionProvider.CreateConnection())
                {
                    connection.Open();
                    return CreateAndExecuteInsertCommand(connection, table, insertData, resultRequired);
                }
            }
            else
            {
                return CreateAndExecuteInsertCommand(transaction.Connection, table, insertData, resultRequired, transaction);
            }
            
        }
        public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction = null,
                                  bool resultRequired = false)
        {
            var table = adapter.GetSchema().FindTable(tableName);
            var dataDictionary = BuildDataDictionary(adapter, data, table);

            string columnList = dataDictionary.Keys.Select(c => c.QuotedName).Aggregate((agg, next) => agg + "," + next);
            string valueList = dataDictionary.Keys.Select(s => "?").Aggregate((agg, next) => agg + "," + next);

            var insertSql = new StringBuilder();
            insertSql.AppendFormat("INSERT INTO {0} ({1}) VALUES ({2});", table.QualifiedName, columnList, valueList);
            if (resultRequired)
            {
                var identityColumn = table.Columns.FirstOrDefault(c => c.IsIdentity);
                if (identityColumn != null)
                {
                    insertSql.AppendFormat(" SELECT * FROM {0} WHERE {1} = LAST_INSERT_ID();", table.QualifiedName,
                                           identityColumn.QuotedName);
                    return ExecuteSingletonQuery(adapter, insertSql.ToString(), dataDictionary.Keys,
                                                 dataDictionary.Values, transaction);
                }
            }
            Execute(adapter, insertSql.ToString(), dataDictionary.Keys, dataDictionary.Values, transaction);
            return null;
        }
Ejemplo n.º 16
0
 public QueryBuilder(AdoAdapter adoAdapter, int bulkIndex)
 {
     _adoAdapter               = adoAdapter;
     _bulkIndex                = bulkIndex;
     _schema                   = _adoAdapter.GetSchema();
     _commandBuilder           = new CommandBuilder(_schema, _bulkIndex);
     _simpleReferenceFormatter = new SimpleReferenceFormatter(_schema, _commandBuilder);
 }
Ejemplo n.º 17
0
 protected QueryBuilderBase(AdoAdapter adapter, int bulkIndex, IFunctionNameConverter functionNameConverter)
 {
     _adoAdapter = adapter;
     _bulkIndex = bulkIndex;
     _schema = _adoAdapter.GetSchema();
     _commandBuilder = new CommandBuilder(_schema, _bulkIndex);
     _simpleReferenceFormatter = new SimpleReferenceFormatter(_schema, _commandBuilder, functionNameConverter);
 }
 protected QueryBuilderBase(AdoAdapter adapter, int bulkIndex, IFunctionNameConverter functionNameConverter)
 {
     _adoAdapter               = adapter;
     _bulkIndex                = bulkIndex;
     _schema                   = _adoAdapter.GetSchema();
     _commandBuilder           = new CommandBuilder(_schema, _bulkIndex);
     _simpleReferenceFormatter = new SimpleReferenceFormatter(_schema, _commandBuilder, functionNameConverter);
 }
Ejemplo n.º 19
0
 public QueryBuilder(AdoAdapter adoAdapter, int bulkIndex)
 {
     _adoAdapter = adoAdapter;
     _bulkIndex = bulkIndex;
     _schema = _adoAdapter.GetSchema();
     _commandBuilder = new CommandBuilder(_schema, _bulkIndex);
     _simpleReferenceFormatter = new SimpleReferenceFormatter(_schema, _commandBuilder);
 }
Ejemplo n.º 20
0
        public IEnumerable <IDictionary <string, object> > InsertMany(string tableName, IEnumerable <IDictionary <string, object> > data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            var list  = data.ToList();
            var table = _adapter.GetSchema().FindTable(tableName);

            foreach (var row in list)
            {
                CheckInsertablePropertiesAreAvailable(table, row);
            }

            var bulkInserter = _adapter.ProviderHelper.GetCustomProvider <IBulkInserter>(_adapter.ConnectionProvider) ?? new BulkInserter();

            return(bulkInserter.Insert(_adapter, tableName, list, _transaction));
        }
Ejemplo n.º 21
0
        public IEnumerable <IDictionary <string, object> > RunQuery(SimpleQuery query,
                                                                    out IEnumerable <SimpleQueryClauseBase>
                                                                    unhandledClauses)
        {
            IEnumerable <IDictionary <string, object> > result;

            if (query.Clauses.OfType <WithCountClause>().Any())
            {
                return(new EagerLoadingEnumerable(RunQueryWithCount(query, out unhandledClauses)));
            }

            ICommandBuilder[] commandBuilders = GetQueryCommandBuilders(ref query, out unhandledClauses);
            IDbConnection     connection      = _adapter.CreateConnection();

            if (_adapter.ProviderSupportsCompoundStatements || commandBuilders.Length == 1)
            {
                var command =
                    new CommandBuilder(_adapter.GetSchema()).CreateCommand(
                        _adapter.ProviderHelper.GetCustomProvider <IDbParameterFactory>(_adapter.SchemaProvider),
                        commandBuilders,
                        connection, _adapter.AdoOptions);

                if (_transaction != null)
                {
                    command.Transaction = _transaction.DbTransaction;
                    result = command.ToEnumerable(_transaction.DbTransaction);
                }
                else
                {
                    result = command.ToEnumerable(_adapter.CreateConnection);
                }
            }
            else
            {
                result = commandBuilders.SelectMany(cb => cb.GetCommand(connection, _adapter.AdoOptions).ToEnumerable(_adapter.CreateConnection));
            }

            if (query.Clauses.OfType <WithClause>().Any())
            {
                result = new EagerLoadingEnumerable(result);
            }

            return(result);
        }
Ejemplo n.º 22
0
        public int Update(AdoAdapter adapter, string tableName, IList<IDictionary<string, object>> data, IEnumerable<string> criteriaFieldNames, IDbTransaction transaction)
        {
            int count = 0;
            if (data == null || !data.Any()) 
                return count;

            var criteriaFieldNameList = criteriaFieldNames.ToList();
            if (criteriaFieldNameList.Count == 0) throw new NotSupportedException("Adapter does not support key-based update for this object.");

            if (!AllRowsHaveSameKeys(data)) throw new SimpleDataException("Records have different structures. Bulk updates are only valid on consistent records.");
            var table = adapter.GetSchema().FindTable(tableName);

            var exampleRow = new Dictionary<string, object>(data.First(), HomogenizedEqualityComparer.DefaultInstance);

            var commandBuilder = new UpdateHelper(adapter.GetSchema()).GetUpdateCommand(tableName, exampleRow,
                                                                    ExpressionHelper.CriteriaDictionaryToExpression(
                                                                        tableName, GetCriteria(criteriaFieldNameList, exampleRow)));

            var connection = adapter.CreateConnection();
            using (connection.MaybeDisposable())
            using (var command = commandBuilder.GetRepeatableCommand(connection))
            {
                if (transaction != null)
                {
                    command.Transaction = transaction;
                }
                connection.OpenIfClosed();
                var propertyToParameterMap = CreatePropertyToParameterMap(data, table, command);

                foreach (var row in data)
                {
                    foreach (var kvp in row)
                    {
                        if (propertyToParameterMap.ContainsKey(kvp.Key))
                        {
                            propertyToParameterMap[kvp.Key].Value = kvp.Value ?? DBNull.Value;
                        }
                    }
                    count += command.ExecuteNonQuery();
                }
            }

            return count;
        }
Ejemplo n.º 23
0
        public IDbCommand GetDbCommand(AdoAdapter adapter, IDbConnection connection, IEnumerable<object> parameterValues)
        {
            var command = connection.CreateCommand(adapter.AdoOptions);
            command.CommandText = _commandText;

            foreach (var parameter in CreateParameters(adapter.GetSchema(), command, parameterValues))
            {
                command.Parameters.Add(parameter);
            }
            return command;
        }
Ejemplo n.º 24
0
        public IDbCommand GetDbCommand(AdoAdapter adapter, IDbConnection connection, IEnumerable <object> parameterValues)
        {
            var command = connection.CreateCommand(adapter.AdoOptions);

            command.CommandText = _commandText;

            foreach (var parameter in CreateParameters(adapter.GetSchema(), command, parameterValues))
            {
                command.Parameters.Add(parameter);
            }
            return(command);
        }
Ejemplo n.º 25
0
        public IDictionary <string, object> Insert(string tableName, IDictionary <string, object> data)
        {
            var customInserter = _adapter.ProviderHelper.GetCustomProvider <ICustomInserter>(_adapter.ConnectionProvider);

            if (customInserter != null)
            {
                return(customInserter.Insert(_adapter, tableName, data));
            }

            var table = _adapter.GetSchema().FindTable(tableName);

            data = data.Where(kvp => !table.FindColumn(kvp.Key).IsIdentity)
                   .ToDictionary();
            string columnList =
                data.Keys.Select(table.FindColumn)
                //.Where(c => !c.IsIdentity)
                .Select(c => c.QuotedName)
                .Aggregate((agg, next) => agg + "," + next);
            string valueList = columnList.Split(',').Select(s => "?").Aggregate((agg, next) => agg + "," + next);

            string insertSql = "insert into " + table.QualifiedName + " (" + columnList + ") values (" + valueList + ")";

            var identityFunction = _adapter.GetIdentityFunction();

            if (!string.IsNullOrWhiteSpace(identityFunction))
            {
                var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);

                if (identityColumn != null)
                {
                    var selectSql = "select * from " + table.QualifiedName + " where " + identityColumn.QuotedName +
                                    " = " + identityFunction;
                    if (_adapter.ProviderSupportsCompoundStatements)
                    {
                        insertSql += "; " + selectSql;
                        return(ExecuteSingletonQuery(insertSql, data.Values.ToArray()));
                    }
                    else
                    {
                        return(ExecuteSingletonQuery(insertSql, selectSql, data.Values.ToArray()));
                    }
                }
            }

            Execute(insertSql, data.Values.ToArray());
            return(null);
        }
Ejemplo n.º 26
0
        public IDictionary <string, object> Insert(string tableName, IDictionary <string, object> data)
        {
            var table = _adapter.GetSchema().FindTable(tableName);

            string columnList =
                data.Keys.Select(s => table.FindColumn(s).QuotedName).Aggregate((agg, next) => agg + "," + next);
            string valueList = data.Keys.Select(s => "?").Aggregate((agg, next) => agg + "," + next);

            string insertSql = "insert into " + table.QuotedName + " (" + columnList + ") values (" + valueList + ")";

            var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);

            if (identityColumn != null)
            {
                insertSql += "; select * from " + table.QuotedName + " where " + identityColumn.QuotedName +
                             " = scope_identity()";
                return(ExecuteSingletonQuery(insertSql, data.Values.ToArray()));
            }

            Execute(insertSql, data.Values.ToArray());
            return(null);
        }
Ejemplo n.º 27
0
        private IDictionary <string, object> Upsert(string tableName, IDictionary <string, object> data, SimpleExpression criteria, bool resultRequired,
                                                    IDbConnection connection)
        {
            var finder = _transaction == null
                             ? new AdoAdapterFinder(_adapter, connection)
                             : new AdoAdapterFinder(_adapter, _transaction);

            var existing = finder.FindOne(tableName, criteria);

            if (existing != null)
            {
                // Don't update columns used as criteria
                var keys       = criteria.GetOperandsOfType <ObjectReference>().Select(o => o.GetName().Homogenize());
                var updateData = data.Where(kvp => keys.All(k => k != kvp.Key.Homogenize())).ToDictionary();
                if (updateData.Count == 0)
                {
                    return(existing);
                }

                var commandBuilder = new UpdateHelper(_adapter.GetSchema()).GetUpdateCommand(tableName, updateData, criteria);
                if (_transaction == null)
                {
                    _adapter.Execute(commandBuilder, connection);
                }
                else
                {
                    _adapter.Execute(commandBuilder, _transaction);
                }
                return(resultRequired ? finder.FindOne(tableName, criteria) : null);
            }
            var inserter = _transaction == null
                               ? new AdoAdapterInserter(_adapter, connection)
                               : new AdoAdapterInserter(_adapter, _transaction);

            return(inserter.Insert(tableName, data, resultRequired));
        }
Ejemplo n.º 28
0
        public IDictionary <string, object> FindOne(string tableName, SimpleExpression criteria)
        {
            if (criteria == null)
            {
                return(FindAll(_adapter.GetSchema().BuildObjectName(tableName)).FirstOrDefault());
            }
            var commandTemplate = GetCommandTemplate(tableName, criteria);

            return(ExecuteSingletonQuery(commandTemplate, criteria.GetValues()));
        }
Ejemplo n.º 29
0
        public object Max(string tableName, string columnName, SimpleExpression criteria)
        {
            var commandBuilder = new AggregationHelper(_adapter.GetSchema()).GetMaxCommand(tableName, columnName, criteria);

            return(ExecuteScalar(commandBuilder));
        }
Ejemplo n.º 30
0
 public QueryBuilder(AdoAdapter adoAdapter)
 {
     _adoAdapter = adoAdapter;
     _schema = _adoAdapter.GetSchema();
     _simpleReferenceFormatter = new SimpleReferenceFormatter(_schema);
 }
        public IEnumerable<IDictionary<string, object>> Insert(AdoAdapter adapter, string tableName, IEnumerable<IDictionary<string, object>> dataList, IDbTransaction transaction, Func<IDictionary<string, object>, Exception, bool> onError,
            bool resultRequired)
        {
            //ToDo: support onError collection
            List<IDictionary<string, object>> result = new List<IDictionary<string, object>>();
          
            if (transaction == null)
            {
                adapter.InTransaction(currentTransaction =>
                {
                    result = (List<IDictionary<string, object>>) Insert(adapter, tableName, dataList, currentTransaction, onError, resultRequired);
                });
                return result;
            }


            var table = adapter.GetSchema().FindTable(tableName);
            var tableColumns = table.Columns.Select(c => (FbColumn)c).ToArray();
            var nameToFbColumns = tableColumns.ToDictionary(c => c.HomogenizedName, c => c);

            var insertContext = CreateInsertSqlContext(table.QualifiedName, tableColumns);

            var queryBuilder = new FbBulkInsertQueryBuilder(resultRequired, insertContext.ReturnsExecuteBlockSql);
            var insertSqlProvider = new FbBulkInsertSqlProvider();
            var currentColumns = new List<InsertColumn>();

            foreach (var data in dataList)
            {
                var insertData = data.Where(p => nameToFbColumns.ContainsKey(p.Key.Homogenize())).Select(kv => new InsertColumn
                {
                    Value = kv.Value,
                    Column =  nameToFbColumns[kv.Key.Homogenize()]
                }).ToArray();

                ExecuteBlockInsertSql insertSql = insertSqlProvider.GetInsertSql(insertContext, insertData, resultRequired);

                if (insertContext.SkipCommandParameters && !CanInsertInExecuteBlock(insertSql.InsertSql, queryBuilder))
                {
                    insertSql = insertSqlProvider.GetInsertSql(insertContext, insertData, resultRequired, skipCommandParameters: false); 
                }

                if (queryBuilder.CanAddQuery(insertSql))
                {
                    queryBuilder.AddQuery(insertSql);
                    if (!insertContext.SkipCommandParameters) currentColumns.AddRange(insertData);
                }
                else
                {
                    var subResult = CreateAndExecuteInsertCommand(transaction, currentColumns, queryBuilder.GetSql(), resultRequired);
                    if (resultRequired) result.AddRange(subResult);
                    currentColumns.Clear();

                    queryBuilder = new FbBulkInsertQueryBuilder(resultRequired, insertContext.ReturnsExecuteBlockSql);
                    queryBuilder.AddQuery(insertSql);
                    if (!insertContext.SkipCommandParameters) currentColumns.AddRange(insertData);
                }
            }

            if (queryBuilder.QueryCount > 0)
            {
                var subResult = CreateAndExecuteInsertCommand(transaction, currentColumns, queryBuilder.GetSql(), resultRequired);
                if (resultRequired) result.AddRange(subResult);
            }

            return result;
        }
Ejemplo n.º 32
0
 public QueryBuilder(AdoAdapter adoAdapter)
 {
     _adoAdapter = adoAdapter;
     _schema = _adoAdapter.GetSchema();
 }
Ejemplo n.º 33
0
 public QueryBuilder(AdoAdapter adoAdapter)
 {
     _adoAdapter = adoAdapter;
     _schema     = _adoAdapter.GetSchema();
 }