/// <summary>
        ///  <para>Creates an <see cref="IDbJob{List{object}}"/> able to execute a reader based on the configured parameters.</para>
        /// <para>Valid types: <see cref="DataSet"/>, <see cref="DataTable"/>, <see cref="Dictionary{string,object}"/>, any .NET built-in type, or any struct or class with a parameterless constructor not assignable from <see cref="System.Collections.IEnumerable"/> (Note: only properties will be mapped).</para>
        ///  See also:
        ///  <seealso cref="DbCommand.ExecuteReader()"/>
        /// </summary>
        /// <remarks>
        /// This will use the <see cref="CommandBehavior.SingleResult"/> behavior by default.
        /// </remarks>
        /// <param name="type">The <see cref="Type"/> to use.</param>
        /// <param name="mapSettings">The <see cref="IColumnMapSetting"/> to use.</param>
        /// <param name="sql">The query text command to run against the data source.</param>
        /// <param name="param">The parameter to use. <see cref="DbJobParameterCollection.AddFor(object, bool, string, string)"/> restrictions apply. (Optional)</param>
        /// <param name="commandType">The <see cref="CommandType"/> to use. (Optional)</param>
        /// <param name="commandBehavior">The <see cref="CommandBehavior"/> to use. (Optional)</param>
        /// <param name="commandTimeout">The time in seconds to wait for the command to execute. (Optional)</param>
        /// <param name="flags">The flags to use. (Optional)</param>
        /// <returns>The <see cref="IDbJob{List{object}}"/>.</returns>
        public IDbJob <List <object> > ReadToList(
            Type type,
            IColumnMapSetting mapSettings,
            string sql,
            object param                    = null,
            CommandType commandType         = CommandType.Text,
            CommandBehavior?commandBehavior = null,
            int?commandTimeout              = null,
            DbJobCommandFlags flags         = DbJobCommandFlags.None)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type cannot be null!");
            }

            return(new DbJob <List <object>, TDbConnection>
                   (
                       setting: _jobSetting,
                       state: new DbConnectorSimpleState {
                Flags = _flags
            },
                       onCommands: (conn, state) => BuildJobCommandForSimpleState(conn, state, mapSettings, sql, param, commandType, commandBehavior, commandTimeout, flags),
                       onExecute: (d, p) => OnExecuteReadToList(type, p)
                   ).SetOnError((d, e) => new List <object>()));
        }
        /// <summary>
        ///  <para>Creates an <see cref="IDbJob{object}"/> able to execute a reader based on the configured parameters.</para>
        ///  <para>Use this to load only a single row from the query result into an object.</para>
        /// <para>Valid types: <see cref="DataSet"/>, <see cref="DataTable"/>, <see cref="Dictionary{string,object}"/>, any .NET built-in type, or any struct or class with a parameterless constructor not assignable from <see cref="System.Collections.IEnumerable"/> (Note: only properties will be mapped).</para>
        ///  See also:
        ///  <seealso cref="DbCommand.ExecuteReader()"/>
        /// </summary>
        /// <remarks>
        /// This will use the <see cref="CommandBehavior.SingleResult"/> behavior by default.
        /// </remarks>
        /// <param name="type">The <see cref="Type"/> to use.</param>
        /// <param name="mapSettings">The <see cref="IColumnMapSetting"/> to use.</param>
        /// <param name="sql">The query text command to run against the data source.</param>
        /// <param name="param">The parameter to use. <see cref="DbJobParameterCollection.AddFor(object, bool, string, string)"/> restrictions apply. (Optional)</param>
        /// <param name="commandType">The <see cref="CommandType"/> to use. (Optional)</param>
        /// <param name="commandBehavior">The <see cref="CommandBehavior"/> to use. (Optional)</param>
        /// <param name="commandTimeout">The time in seconds to wait for the command to execute. (Optional)</param>
        /// <param name="flags">The flags to use. (Optional)</param>
        /// <returns>The <see cref="IDbJob{object}"/>.</returns>
        /// <exception cref="InvalidOperationException">The query result has more than one result.</exception>
        public IDbJob <object> ReadSingleOrDefault(
            Type type,
            IColumnMapSetting mapSettings,
            string sql,
            object param                    = null,
            CommandType commandType         = CommandType.Text,
            CommandBehavior?commandBehavior = null,
            int?commandTimeout              = null,
            DbJobCommandFlags flags         = DbJobCommandFlags.None)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type cannot be null!");
            }

            return(new DbJob <object, TDbConnection>
                   (
                       setting: _jobSetting,
                       state: new DbConnectorSimpleState {
                Flags = _flags
            },
                       onInit: () => type.IsValueType ? Activator.CreateInstance(type) : null,
                       onCommands: (conn, state) => BuildJobCommandForSimpleState(conn, state, mapSettings, sql, param, commandType, commandBehavior, commandTimeout, flags),
                       onExecute: (d, p) => OnExecuteReadSingleOrDefault(type, p)
                   ));
        }
Esempio n. 3
0
        /// <summary>
        /// Creates the command.
        /// </summary>
        /// <param name="behavior">The behavior.</param>
        /// <returns>
        /// The data command.
        /// </returns>
        public IDataCommand CreateCommand(CommandBehavior?behavior = CommandBehavior.Default)
        {
            var cmd = this.Connection.CreateCommand(behavior);

            cmd.Transaction = this;
            return(cmd);
        }
Esempio n. 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataCommand"/> class.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="sqlDialect">The SQL dialect.</param>
 /// <param name="behavior">The behavior.</param>
 public DataCommand(
     IDbCommand command,
     ISqlDialect sqlDialect,
     CommandBehavior?behavior = null)
 {
     Check.NotNull(nameof(command), command);
     this.SqlDialect = sqlDialect;
     this.parameters = new DbParametersReadOnlyCollection(command.Parameters);
     this.command    = command;
     this.dbCommand  = command as DbCommand;
     this.Behavior   = behavior;
 }
        public static IDataReader PreparaAndExecuteQuery(this IDbCommand command, CommandBehavior?behavior = null)
        {
            command.Prepare();

            if (behavior.HasValue)
            {
                return(command.ExecuteReader(behavior.Value));
            }
            else
            {
                return(command.ExecuteReader());
            }
        }
Esempio n. 6
0
 /// <summary>
 ///  <para>Creates an <see cref="IDbJob{IEnumerable{dynamic}}"/> able to execute a reader based on the configured parameters.</para>
 ///  <para>Use this to dynamically load the query results into an IEnumerable of <see cref="System.Dynamic.ExpandoObject"/>.</para>
 ///  See also:
 ///  <seealso cref="DbCommand.ExecuteReader()"/>
 /// </summary>
 /// <remarks>
 /// This will use the <see cref="CommandBehavior.SingleResult"/> behavior by default.
 /// </remarks>
 /// <param name="mapSettings">The <see cref="IColumnMapSetting"/> to use.</param>
 /// <param name="sql">The query text command to run against the data source.</param>
 /// <param name="param">The parameter to use. <see cref="DbJobParameterCollection.AddFor(object, bool, string, string)"/> restrictions apply. (Optional)</param>
 /// <param name="commandType">The <see cref="CommandType"/> to use. (Optional)</param>
 /// <param name="commandBehavior">The <see cref="CommandBehavior"/> to use. (Optional)</param>
 /// <param name="commandTimeout">The time in seconds to wait for the command to execute. (Optional)</param>
 /// <param name="flags">The flags to use. (Optional)</param>
 /// <returns>The <see cref="IDbJob{IEnumerable{dynamic}}"/>.</returns>
 public IDbJob <IEnumerable <dynamic> > Read(
     IColumnMapSetting mapSettings,
     string sql,
     object param                    = null,
     CommandType commandType         = CommandType.Text,
     CommandBehavior?commandBehavior = null,
     int?commandTimeout              = null,
     DbJobCommandFlags flags         = DbJobCommandFlags.None)
 {
     return(new DbJob <IEnumerable <dynamic>, TDbConnection>
            (
                setting: _jobSetting,
                state: new DbConnectorSimpleState {
         Flags = _flags
     },
                onCommands: (conn, state) => BuildJobCommandForSimpleState(conn, state, mapSettings, sql, param, commandType, commandBehavior, commandTimeout, flags),
                onExecute: (d, p) => OnExecuteReadDynamic(d, p)
            ).SetOnError((d, e) => Enumerable.Empty <dynamic>()));
 }
Esempio n. 7
0
 /// <summary>
 ///  <para>Creates an <see cref="IDbJob{dynamic}"/> able to execute a reader based on the configured parameters.</para>
 ///  <para>Use this to dynamically load only a single row from the query result into a <see cref="System.Dynamic.ExpandoObject"/>.</para>
 ///  See also:
 ///  <seealso cref="DbCommand.ExecuteReader()"/>
 /// </summary>
 /// <remarks>
 /// This will use the <see cref="CommandBehavior.SingleResult"/> behavior by default.
 /// </remarks>
 /// <param name="mapSettings">The <see cref="IColumnMapSetting"/> to use.</param>
 /// <param name="sql">The query text command to run against the data source.</param>
 /// <param name="param">The parameter to use. <see cref="DbJobParameterCollection.AddFor(object, bool, string, string)"/> restrictions apply. (Optional)</param>
 /// <param name="commandType">The <see cref="CommandType"/> to use. (Optional)</param>
 /// <param name="commandBehavior">The <see cref="CommandBehavior"/> to use. (Optional)</param>
 /// <param name="commandTimeout">The time in seconds to wait for the command to execute. (Optional)</param>
 /// <param name="flags">The flags to use. (Optional)</param>
 /// <returns>The <see cref="IDbJob{dynamic}"/>.</returns>
 /// <exception cref="InvalidOperationException">The query result has more than one result.</exception>
 public IDbJob <dynamic> ReadSingleOrDefault(
     IColumnMapSetting mapSettings,
     string sql,
     object param                    = null,
     CommandType commandType         = CommandType.Text,
     CommandBehavior?commandBehavior = null,
     int?commandTimeout              = null,
     DbJobCommandFlags flags         = DbJobCommandFlags.None)
 {
     return(new DbJob <dynamic, TDbConnection>
            (
                setting: _jobSetting,
                state: new DbConnectorSimpleState {
         Flags = _flags
     },
                onCommands: (conn, state) => BuildJobCommandForSimpleState(conn, state, mapSettings, sql, param, commandType, commandBehavior, commandTimeout, flags),
                onExecute: (d, p) => OnExecuteReadSingleOrDefaultDynamic(d, p)
            ));
 }
        /// <summary>
        ///  <para>Creates an <see cref="IDbJob{object}"/> to get the first column of the first row in the result
        ///  set returned by the query. All other columns and rows are ignored.</para>
        ///  See also:
        ///  <seealso cref="DbCommand.ExecuteScalar"/>
        /// </summary>
        /// <param name="mapSettings">The <see cref="IColumnMapSetting"/> to use.</param>
        /// <param name="sql">The query text command to run against the data source.</param>
        /// <param name="param">The parameter to use. <see cref="DbJobParameterCollection.AddFor(object, bool, string, string)"/> restrictions apply. (Optional)</param>
        /// <param name="commandType">The <see cref="CommandType"/> to use. (Optional)</param>
        /// <param name="commandBehavior">The <see cref="CommandBehavior"/> to use. (Optional)</param>
        /// <param name="commandTimeout">The time in seconds to wait for the command to execute. (Optional)</param>
        /// <param name="flags">The flags to use. (Optional)</param>
        /// <returns>The <see cref="IDbJob{object}"/>.</returns>
        public IDbJob <object> Scalar(
            IColumnMapSetting mapSettings,
            string sql,
            object param                    = null,
            CommandType commandType         = CommandType.Text,
            CommandBehavior?commandBehavior = null,
            int?commandTimeout              = null,
            DbJobCommandFlags flags         = DbJobCommandFlags.None)
        {
            return(new DbJob <object, TDbConnection>
                   (
                       setting: _jobSetting,
                       state: new DbConnectorSimpleState {
                Flags = _flags
            },
                       onCommands: (conn, state) => BuildJobCommandForSimpleState(conn, state, mapSettings, sql, param, commandType, commandBehavior, commandTimeout, flags),
                       onExecute: (d, p) =>
            {
                object scalar = p.Command.ExecuteScalar();

                return scalar != DBNull.Value ? scalar : null;
            }
                   ));
        }
Esempio n. 9
0
 IDataReader IDatabase.ExecuteReader(IQueryCommand queryCommand, IDataSegment segment, ParameterCollection parameters, CommandBehavior?behavior = null)
 {
     return(_database.ExecuteReader(queryCommand, segment, parameters, behavior));
 }
Esempio n. 10
0
 public IDataReader ExecuteReader(String sql, Object param = null, Int32?commandTimeout = null, CommandType?commandType = null, CommandBehavior?behavior = null)
 {
     return(SqlMapper.ExecuteReader(Connection, sql, param, Transaction, commandTimeout, commandType));
 }
        private void OnCommandExecute(DbCommand command, DbCommandExecution execution, CommandBehavior?behavior)
        {
            var rawSql = command.CommandText;

            _commandStore.Append(new DbCommandInfo {
                Command = command, Execution = execution, Behavior = behavior
            });
        }
Esempio n. 12
0
 public static IDbCmd CommandBehavior(
     this IDbConnection source,
     CommandBehavior?behavior)
 {
     return(DbFactory.Instance.CreateDbCmd().Connection(source).CommandBehavior(behavior));
 }
Esempio n. 13
0
        /// <summary>
        /// 异步的,执行查询文本并返回一个 <see cref="IDataReader"/>。
        /// </summary>
        /// <param name="queryCommand">查询命令。</param>
        /// <param name="segment">数据分段对象。</param>
        /// <param name="parameters">查询参数集合。</param>
        /// <param name="cancellationToken">取消操作的通知。</param>
        /// <returns>一个 <see cref="IDataReader"/> 对象。</returns>
        public async virtual Task <IDataReader> ExecuteReaderAsync(IQueryCommand queryCommand, IDataSegment segment = null, ParameterCollection parameters = null, CommandBehavior?behavior = null, CancellationToken cancellationToken = default)
        {
            Guard.ArgumentNull(queryCommand, nameof(queryCommand));
            cancellationToken.ThrowIfCancellationRequested();

            var connection = GetConnection(DistributedMode.Slave);

            var command = new InternalDbCommand(CreateDbCommand(connection, queryCommand, parameters), _readerLocker);

            try
            {
                var context = new CommandContext(this, command, segment, parameters);
                await HandleSegmentCommandAsync(context, cancellationToken);

                return(await HandleCommandExecutedAsync(command, parameters, behavior ?? CommandBehavior.Default,
                                                        (command, behavior, cancelToken) => command.ExecuteReaderAsync(behavior, cancelToken), cancellationToken));
            }
            catch (DbException exp)
            {
                throw await HandleExceptionAsync(command, exp, cancellationToken);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 执行查询文本并返回一个 <see cref="IDataReader"/>。
        /// </summary>
        /// <param name="queryCommand">查询命令。</param>
        /// <param name="segment">数据分段对象。</param>
        /// <param name="parameters">查询参数集合。</param>
        /// <returns>一个 <see cref="IDataReader"/> 对象。</returns>
        public virtual IDataReader ExecuteReader(IQueryCommand queryCommand, IDataSegment segment = null, ParameterCollection parameters = null, CommandBehavior?behavior = null)
        {
            Guard.ArgumentNull(queryCommand, nameof(queryCommand));

            var connection = GetConnection(DistributedMode.Slave);

            var command = new InternalDbCommand(CreateDbCommand(connection, queryCommand, parameters), _readerLocker);

            try
            {
                var context = new CommandContext(this, command, segment, parameters);
                HandleSegmentCommand(context);
                return(HandleCommandExecuted(command, parameters, behavior ?? CommandBehavior.Default, (command, behavior) => command.ExecuteReader(behavior)));
            }
            catch (DbException exp)
            {
                throw HandleException(command, exp);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Executes an command statement and builds an <see cref="System.Data.IDataReader"/>.
        /// </summary>
        /// <param name="sql">the text command to run against the data source</param>
        /// <param name="param">the object which contains parameters</param>
        /// <param name="commandTimeout">the wait time before terminating the attempt to execute a command and generating an error</param>
        /// <param name="commandType">the type indicates or specifies how the command is interpreted</param>
        /// <param name="behavior">one of the <see cref="System.Data.CommandBehavior"/> values</param>
        /// <returns><see cref="System.Data.IDataReader"/></returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static IDataReader ExecuteReader(String sql, Object param, Int32?commandTimeout = null, CommandType?commandType = null, CommandBehavior?behavior = null)
        {
            IConnection conn = OpenConnection();

            try
            {
                return(conn.ExecuteReader(sql, param, commandTimeout, commandType));
            }
            finally
            {
                conn.Close();
            }
        }
Esempio n. 16
0
        public ColumnMapCacheModel(Type tType, IDbJobCommand jobCommand, int ordinalColumnNamesHash)
        {
            Ttype = tType;
            //CommandText = jobCommand.CommandText;
            //CommandType = jobCommand.CommandType;
            CommandBehavior = jobCommand.CommandBehavior;
            ParameterCount  = jobCommand.Parameters.Count;

            unchecked
            {
                int hash      = 5;
                int localHash = 0;

                hash = (hash * 11) + Ttype.GetHashCode();
                hash = (hash * 11) + ordinalColumnNamesHash;
                //hash = (hash * 11) + (byte)CommandType;
                //hash = (hash * 11) + (CommandText?.GetHashCode() ?? 0);
                hash = (hash * 11) + (CommandBehavior == null ? 0 : (int)CommandBehavior);

                if (ParameterCount != 0)
                {
                    for (int i = 0; i < ParameterCount; i++)
                    {
                        var item = jobCommand.Parameters._collection[i];

                        localHash +=
                            (item.Value?.GetType().GetHashCode() ?? 0)
                            + (int)item.Direction
                            + (item.ParameterName?.GetHashCode() ?? 0);
                    }

                    hash      = (hash * 11) + localHash;
                    localHash = 0;
                }

                if (jobCommand.MapSettings.HasNamesToInclude)
                {
                    foreach (var item in jobCommand.MapSettings.NamesToInclude)
                    {
                        localHash += item.GetHashCode();
                    }

                    hash      = (hash * 11) + localHash + 1;
                    localHash = 0;
                }

                if (jobCommand.MapSettings.HasNamesToExclude)
                {
                    foreach (var item in jobCommand.MapSettings.NamesToExclude)
                    {
                        localHash += item.GetHashCode();
                    }

                    hash      = (hash * 11) + localHash;
                    localHash = 0;
                }

                if (jobCommand.MapSettings.HasJoins)
                {
                    foreach (var item in jobCommand.MapSettings.Joins)
                    {
                        localHash += (item.Key.GetHashCode() + item.Value.GetHashCode());
                    }

                    hash      = (hash * 11) + localHash;
                    localHash = 0;
                }

                if (jobCommand.MapSettings.HasAliases)
                {
                    foreach (var item in jobCommand.MapSettings.Aliases)
                    {
                        foreach (var valueItem in item.Value)
                        {
                            localHash += (valueItem.Key.GetHashCode() + valueItem.Value.GetHashCode());
                        }

                        localHash += (item.Key.GetHashCode() + localHash);
                    }

                    hash = (hash * 11) + localHash;
                }

                HashCode = hash;
            }
        }
Esempio n. 17
0
        protected List <T> ExecuteQuery <T>(string sql, Func <SqlDataReader, T> mapFunc, CommandBehavior?behavior = null)
        {
            List <T> list = new List <T>(50);

            Exec(sql, cmd =>
            {
                using (var reader = cmd.ExecuteReader(!behavior.HasValue ? CommandBehavior.Default : behavior.Value))
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            list.Add(mapFunc(reader));
                        }
                    }
                }
            });

            return(list);
        }
Esempio n. 18
0
 Task <IDataReader> IDatabase.ExecuteReaderAsync(IQueryCommand queryCommand, IDataSegment segment, ParameterCollection parameters, CommandBehavior?behavior, CancellationToken cancellationToken)
 {
     return(_database.ExecuteReaderAsync(queryCommand, segment, parameters, behavior, cancellationToken));
 }
Esempio n. 19
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   An IDbConnection extension method that executes the reader operation. </summary>
        ///
        /// <remarks>   Msacli, 22.04.2019. </remarks>
        ///
        /// <param name="connection">       The connection to act on. </param>
        /// <param name="sql">              The SQL. </param>
        /// <param name="commandType">      (Optional) Type of the command. </param>
        /// <param name="transaction">      (Optional) The transaction. </param>
        /// <param name="inputParameters">  (Optional) Options for controlling the input. </param>
        /// <param name="outputParameters"> (Optional) Options for controlling the output. </param>
        ///
        /// <returns>   An IDataReader. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        public static IDataReader ExecuteReader(this IDbConnection connection,
                                                string sql, CommandType commandType          = CommandType.Text,
                                                IDbTransaction transaction                   = null,
                                                Dictionary <string, object> inputParameters  = null,
                                                Dictionary <string, object> outputParameters = null, CommandBehavior?commandBehavior = null)
        {
            IDataReader dataReader = null;

            try
            {
                using (IDbCommand command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    command.CommandType = commandType;

                    if (transaction != null)
                    {
                        command.Transaction = transaction;
                    }

                    DxDbCommandHelper.SetCommandParameters(command, inputParameters, outputParameters);

                    if (!commandBehavior.HasValue)
                    {
                        dataReader = command.ExecuteReader();
                    }
                    else
                    {
                        dataReader = command.ExecuteReader(commandBehavior.Value);
                    }

                    if (outputParameters != null && outputParameters.Count > 0)
                    {
                        outputParameters = (Dictionary <string, object>)DxDbCommandHelper.GetOutParametersOfCommand(command);
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }

            return(dataReader);
        }