예제 #1
0
        private IEnumerable <IDictionary <string, object> > ExecuteQuery(ICommandBuilder commandBuilder)
        {
            var connection = _adapter.CreateConnection();
            var command    = commandBuilder.GetCommand(connection);

            return(TryExecuteQuery(connection, command));
        }
예제 #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));
        }
예제 #3
0
        internal IDictionary <string, object> ExecuteSingletonQuery(string sql, params object[] values)
        {
            using (var connection = _adapter.CreateConnection())
            {
                using (var command = CommandHelper.Create(connection, sql, values.ToArray()))
                {
                    try
                    {
                        connection.Open();
                        using (var reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                return(reader.ToDictionary());
                            }
                        }
                    }
                    catch (DbException ex)
                    {
                        throw new AdoAdapterException(ex.Message, command);
                    }
                }
            }

            return(null);
        }
예제 #4
0
        public Func <object[], IDictionary <string, object> > CreateFindOneDelegate(string tableName, SimpleExpression criteria)
        {
            if (criteria == null)
            {
                return(_ => FindAll(_adapter.GetSchema().BuildObjectName(tableName)).FirstOrDefault());
            }
            var commandBuilder = new FindHelper(_adapter.GetSchema())
                                 .GetFindByCommand(_adapter.GetSchema().BuildObjectName(tableName), criteria);

            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));
            }
            else
            {
                return(args => ExecuteSingletonQuery(commandTemplate, args));
            }
        }
예제 #5
0
        private IEnumerable <IDictionary <string, object> > ExecuteQuery(CommandTemplate commandTemplate, IEnumerable <object> parameterValues)
        {
            var connection = _connection ?? _adapter.CreateConnection();
            var command    = commandTemplate.GetDbCommand(connection, parameterValues);

            command.Transaction = _transaction;
            return(TryExecuteQuery(connection, command, commandTemplate.Index));
        }
예제 #6
0
        private static IEnumerable<IDictionary<string, object>> InsertRowsWithSeparateStatements(AdoAdapter adapter, IEnumerable<IDictionary<string, object>> data,
                                                                    IDbTransaction transaction, Table table, List<Column> columns,
                                                                    string insertSql, string selectSql)
        {
            if (transaction != null)
            {
                var insertCommand = new CommandHelper(adapter.SchemaProvider).Create(transaction.Connection, insertSql);
                var selectCommand = transaction.Connection.CreateCommand();
                selectCommand.CommandText = selectSql;
                insertCommand.Transaction = transaction;
                selectCommand.Transaction = transaction;
                return data.Select(row => InsertRow(row, columns, table, insertCommand, selectCommand)).ToList();
            }

            using (var connection = adapter.CreateConnection())
            {
                using (var insertCommand = new CommandHelper(adapter.SchemaProvider).Create(connection, insertSql))
                using (var selectCommand = connection.CreateCommand())
                {
                    selectCommand.CommandText = selectSql;
                    connection.Open();
                    return data.Select(row => InsertRow(row, columns, table, insertCommand, selectCommand)).ToList();
                }
            }
        }
예제 #7
0
 public virtual void InsertRowsWithoutFetchBack(string insertSql)
 {
     using (var connection = Adapter.CreateConnection())
     {
         using (var insertCommand = new CommandHelper(Adapter).CreateInsert(connection, insertSql, _columns))
         {
             connection.Open();
             TryPrepare(insertCommand);
             insertCommand.Prepare();
             foreach (var row in Data)
             {
                 InsertRow(row, insertCommand);
             }
         }
     }
 }
        public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction, bool returnRequired)
        {
            var s = DatabaseSchema.Get(adapter.ConnectionProvider, new ProviderHelper());
            var table = s.FindTable(tableName);
            
            var tuples = InitializeInsertion(table);
            foreach (var d in data)
                tuples[d.Key.Homogenize()].InsertedValue = d.Value;

            Func<IDbCommand> command =
                () =>
                    {
                        var c = transaction != null
                                    ? transaction.Connection.CreateCommand()
                                    : adapter.CreateConnection().CreateCommand();
                        return c;
                    };

            IDbCommand cmd;
            using (cmd = ConstructCommand(tuples, table.QualifiedName, command))
            {
                cmd.WriteTrace();
                cmd.Connection.TryOpen();
                cmd.ExecuteNonQuery();
                var returnData = new DbDictionary();
                foreach (var it in tuples.Values)
                    returnData.Add(it.SimpleDataColumn, NormalizeReturningValue((IDbDataParameter)cmd.Parameters[it.ReturningParameterName]));
                data = returnData;
            }

            return data;
        }
        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);
                    }
                }
        }
예제 #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);
                    }
                }
        }
예제 #11
0
        public virtual void InsertRowsWithoutFetchBack(string insertSql, Func <IDictionary <string, object>, Exception, bool> onError)
        {
            var connection = Adapter.CreateConnection();

            using (connection.MaybeDisposable())
            {
                using (var insertCommand = new CommandHelper(Adapter).CreateInsert(connection, insertSql, _columns))
                {
                    connection.OpenIfClosed();
                    TryPrepare(insertCommand);
                    foreach (var row in Data)
                    {
                        InsertRow(row, insertCommand, onError);
                    }
                }
            }
        }
예제 #12
0
        private object ExecuteScalar(ICommandBuilder commandBuilder)
        {
            var connection = _connection ?? _adapter.CreateConnection();
            var command    = commandBuilder.GetCommand(connection);

            command.Transaction = _transaction;
            return(TryExecuteScalar(command));
        }
예제 #13
0
        internal IDictionary <string, object> ExecuteSingletonQuery(string sql, params object[] values)
        {
            if (_transaction != null)
            {
                var command = new CommandHelper(_adapter.SchemaProvider).Create(_transaction.Connection, sql, values.ToArray());
                command.Transaction = _transaction;
                return(TryExecuteSingletonQuery(command));
            }

            using (var connection = _adapter.CreateConnection())
            {
                using (var command = new CommandHelper(_adapter.SchemaProvider).Create(connection, sql, values.ToArray()))
                {
                    connection.Open();
                    return(TryExecuteSingletonQuery(command));
                }
            }
        }
예제 #14
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);
        }
예제 #15
0
        public IDictionary <string, object> Upsert(string tableName, IDictionary <string, object> data, SimpleExpression criteria, bool resultRequired)
        {
            var connection = _connection ?? _adapter.CreateConnection();

            using (connection.MaybeDisposable())
            {
                connection.OpenIfClosed();
                return(Upsert(tableName, data, criteria, resultRequired, connection));
            }
        }
예제 #16
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);
        }
예제 #17
0
        internal IDictionary <string, object> ExecuteSingletonQuery(string sql, IEnumerable <Column> columns, IEnumerable <Object> values)
        {
            if (_transaction != null)
            {
                var command = new CommandHelper(_adapter).CreateInsert(_transaction.Connection, sql, columns, values.ToArray());
                command.Transaction = _transaction;
                return(TryExecuteSingletonQuery(command));
            }

            var connection = _connection ?? _adapter.CreateConnection();

            using (connection.MaybeDisposable())
            {
                using (var command = new CommandHelper(_adapter).CreateInsert(connection, sql, columns, values.ToArray()))
                {
                    connection.OpenIfClosed();
                    return(TryExecuteSingletonQuery(command));
                }
            }
        }
예제 #18
0
 private static void InsertRowsWithoutFetchBack(AdoAdapter adapter, IEnumerable<IDictionary<string, object>> data, Table table, List<Column> columns,
                                                string insertSql)
 {
     using (var connection = adapter.CreateConnection())
     {
         using (var insertCommand = new CommandHelper(adapter.SchemaProvider).Create(connection, insertSql))
         {
             connection.Open();
             foreach (var row in data)
             {
                 InsertRow(row, columns, table, insertCommand);
             }
         }
     }
 }
예제 #19
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;
        }
예제 #20
0
        internal IDictionary<string, object> ExecuteSingletonQuery(AdoAdapter adapter, string sql, IEnumerable<Column> columns, IEnumerable<Object> values, IDbTransaction transaction)
        {
            if (transaction != null)
            {
                var command = new CommandHelper(adapter).CreateInsert(transaction.Connection, sql, columns, values.ToArray());
                command.Transaction = transaction;
                return TryExecuteSingletonQuery(command);
            }

            var connection = adapter.CreateConnection();
            using (connection.MaybeDisposable())
            {
                using (var command = new CommandHelper(adapter).CreateInsert(connection, sql, columns, values.ToArray()))
                {
                    connection.OpenIfClosed();
                    return TryExecuteSingletonQuery(command);
                }
            }
        }
예제 #21
0
        private static IEnumerable<IDictionary<string, object>> InsertRowsWithCompoundStatement(AdoAdapter adapter, IEnumerable<IDictionary<string, object>> data,
                                                                   IDbTransaction transaction, Table table, List<Column> columns,
                                                                   string selectSql, string insertSql)
        {
            insertSql += "; " + selectSql;
            if (transaction != null)
            {
                var command = new CommandHelper(adapter.SchemaProvider).Create(transaction.Connection, insertSql);
                command.Transaction = transaction;
                return data.Select(row => InsertRowAndSelect(row, columns, table, command)).ToList();
            }

            using (var connection = adapter.CreateConnection())
            {
                using (var command = new CommandHelper(adapter.SchemaProvider).Create(connection, insertSql))
                {
                    connection.Open();
                    return data.Select(row => InsertRowAndSelect(row, columns, table, command)).ToList();
                }
            }
        }