static global::System.Data.Common.DbCommand __dapper__CreateCommand(global::System.Data.Common.DbConnection connection)
        {
            var command = connection.CreateCommand();

            if (command is global::Oracle.ManagedDataAccess.Client.OracleCommand typed0)
            {
                typed0.BindByName           = true;
                typed0.InitialLONGFetchSize = -1;
            }
            command.CommandType = global::System.Data.CommandType.StoredProcedure;
            command.CommandText = @"sproc";
            var args = command.Parameters;

            var p = command.CreateParameter();

            p.ParameterName = @"id";
            p.Direction     = global::System.Data.ParameterDirection.Input;
            args.Add(p);

            p = command.CreateParameter();
            p.ParameterName = @"name";
            p.Direction     = global::System.Data.ParameterDirection.Input;
            p.Size          = -1;
            args.Add(p);

            return(command);
        }
Example #2
0
        internal IDbCommand SetupCommand(IDbConnection cnn, Action <IDbCommand, object> paramReader)
        {
            var cmd  = cnn.CreateCommand();
            var init = GetInit(cmd.GetType());

            if (init != null)
            {
                init(cmd);
            }
            if (transaction != null)
            {
                cmd.Transaction = transaction;
            }
            cmd.CommandText = commandText;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            else if (SqlMapper.Settings.CommandTimeout.HasValue)
            {
                cmd.CommandTimeout = SqlMapper.Settings.CommandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (paramReader != null)
            {
                paramReader(cmd, parameters);
            }
            return(cmd);
        }
        static global::System.Data.Common.DbCommand __dapper__CreateCommand(global::System.Data.Common.DbConnection connection)
        {
            var command = connection.CreateCommand();

            if (command is global::Oracle.ManagedDataAccess.Client.OracleCommand typed0)
            {
                typed0.BindByName           = true;
                typed0.InitialLONGFetchSize = -1;
            }
            command.CommandType = global::System.Data.CommandType.Text;
            command.CommandText = @"/* Test.ImplicitCommandText, Samples/Commands.input.cs #14 */ this is CommandText";
            var args = command.Parameters;

            var p = command.CreateParameter();

            p.ParameterName = @"id";
            p.Direction     = global::System.Data.ParameterDirection.Input;
            args.Add(p);

            p = command.CreateParameter();
            p.ParameterName = @"name";
            p.Direction     = global::System.Data.ParameterDirection.Input;
            p.Size          = -1;
            args.Add(p);

            return(command);
        }
        private static async Task <int> ExecuteImplAsync(IDbConnection cnn, CommandDefinition command, object param)
        {
            var  identity  = new Identity(command.CommandText, command.CommandType, cnn, null, param == null ? null : param.GetType(), null);
            var  info      = GetCacheInfo(identity, param, command.AddToCache);
            bool wasClosed = cnn.State == ConnectionState.Closed;

            using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
            {
                try
                {
                    if (wasClosed)
                    {
                        await((DbConnection)cnn).OpenAsync(command.CancellationToken).ConfigureAwait(false);
                    }
                    var result = await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false);

                    command.OnCompleted();
                    return(result);
                }
                finally
                {
                    if (wasClosed)
                    {
                        cnn.Close();
                    }
                }
            }
        }
        private static async Task <IEnumerable <TReturn> > MultiMapAsync <TReturn>(this IDbConnection cnn, CommandDefinition command, Type[] types, Func <object[], TReturn> map, string splitOn)
        {
            if (types.Length < 1)
            {
                throw new ArgumentException("you must provide at least one type to deserialize");
            }

            object param     = command.Parameters;
            var    identity  = new Identity(command.CommandText, command.CommandType, cnn, types[0], param == null ? null : param.GetType(), types);
            var    info      = GetCacheInfo(identity, param, command.AddToCache);
            bool   wasClosed = cnn.State == ConnectionState.Closed;

            try {
                if (wasClosed)
                {
                    await((DbConnection)cnn).OpenAsync().ConfigureAwait(false);
                }
                using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
                    using (var reader = await cmd.ExecuteReaderAsync(command.CancellationToken).ConfigureAwait(false)) {
                        var results = MultiMapImpl <TReturn>(null, default(CommandDefinition), types, map, splitOn, reader, identity, true);
                        return(command.Buffered ? results.ToList() : results);
                    }
            }
            finally {
                if (wasClosed)
                {
                    cnn.Close();
                }
            }
        }
 /// <summary>
 /// Execute a query asynchronously using .NET 4.5 Task.
 /// </summary>
 public static Task <IEnumerable <object> > QueryAsync(this IDbConnection cnn, Type type, string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null)
 {
     if (type == null)
     {
         throw new ArgumentNullException("type");
     }
     return(QueryAsync <object>(cnn, type, new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))));
 }
Example #7
0
        /// <summary>
        /// Gets the feature set based on the passed connection
        /// </summary>
        public static FeatureSupport Get(IDbConnection connection)
        {
            string name = connection == null ? null : connection.GetType().Name;

            if (string.Equals(name, "npgsqlconnection", StringComparison.OrdinalIgnoreCase))
            {
                return(postgres);
            }
            return(@default);
        }
Example #8
0
    public async partial global::System.Threading.Tasks.Task TaskAsync(global::System.Data.Common.DbConnection connection, int id, string name)
    {
        // locals
        global::System.Data.Common.DbCommand?__dapper__command = null;
        bool __dapper__close = false;

        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                await connection !.OpenAsync(global::System.Threading.CancellationToken.None).ConfigureAwait(false);
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Async_NonQuery_input_cs_TaskAsync_8, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // assign parameter values
#pragma warning disable CS0618
            __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(id);
            __dapper__command.Parameters[1].Value = global::Dapper.Internal.InternalUtilities.AsValue(name);
#pragma warning restore CS0618

            // execute non-query
            await __dapper__command.ExecuteNonQueryAsync(global::System.Threading.CancellationToken.None).ConfigureAwait(false);

            // TODO: post-process parameters
        }
        finally
        {
            // cleanup
            if (__dapper__command is not null)
            {
                __dapper__command.Connection = default;
                __dapper__command            = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Async_NonQuery_input_cs_TaskAsync_8, __dapper__command);
                if (__dapper__command is not null)
                {
                    await __dapper__command.DisposeAsync().ConfigureAwait(false);
                }
            }
            if (__dapper__close)
            {
                await(connection?.CloseAsync() ?? global::System.Threading.Tasks.Task.CompletedTask).ConfigureAwait(false);
            }
        }
Example #9
0
    public partial int ReturnViaReturn(global::System.Data.Common.DbConnection connection, int id, string inputOutput, global::System.DateTime output)
    {
        // locals
        global::System.Data.Common.DbCommand?__dapper__command = null;
        bool __dapper__close = false;

        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                connection !.Open();
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Sync_Parameters_input_cs_ReturnViaReturn_9, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // assign parameter values
#pragma warning disable CS0618
            __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(id);
            __dapper__command.Parameters[1].Value = global::Dapper.Internal.InternalUtilities.AsValue(inputOutput);
            __dapper__command.Parameters[2].Value = global::Dapper.Internal.InternalUtilities.AsValue(output);
#pragma warning restore CS0618

            // execute non-query
            __dapper__command.ExecuteNonQuery();

            // TODO: post-process parameters
        }
        finally
        {
            // cleanup
            if (__dapper__command is not null)
            {
                __dapper__command.Connection = default;
                __dapper__command            = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Sync_Parameters_input_cs_ReturnViaReturn_9, __dapper__command);
                __dapper__command?.Dispose();
            }
            if (__dapper__close)
            {
                connection?.Close();
            }
        }
        /// <summary>
        /// Execute a command asynchronously using .NET 4.5 Task.
        /// </summary>
        public static Task <int> ExecuteAsync(this IDbConnection cnn, CommandDefinition command)
        {
            object      param     = command.Parameters;
            IEnumerable multiExec = GetMultiExec(param);

            if (multiExec != null)
            {
                return(ExecuteMultiImplAsync(cnn, command, multiExec));
            }
            else
            {
                return(ExecuteImplAsync(cnn, command, param));
            }
        }
Example #11
0
        private void LiteralReplacement(IDbConnection connection)
        {
            try { connection.ExecuteAsync("drop table literal1").Wait(); } catch { }
            connection.ExecuteAsync("create table literal1 (id int not null, foo int not null)").Wait();
            connection.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", new { id = 123, foo = 456 }).Wait();
            var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } };

            connection.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", rows).Wait();
            var count = connection.QueryAsync <int>("select count(1) from literal1 where id={=foo}", new { foo = 123 }).Result.Single();

            count.IsEqualTo(1);
            int sum = connection.QueryAsync <int>("select sum(id) + sum(foo) from literal1").Result.Single();

            sum.IsEqualTo(123 + 456 + 1 + 2 + 3 + 4);
        }
Example #12
0
        private void LiteralReplacementDynamic(IDbConnection connection)
        {
            var args = new DynamicParameters();

            args.Add("id", 123);
            try { connection.ExecuteAsync("drop table literal2").Wait(); } catch { }
            connection.ExecuteAsync("create table literal2 (id int not null)").Wait();
            connection.ExecuteAsync("insert literal2 (id) values ({=id})", args).Wait();

            args = new DynamicParameters();
            args.Add("foo", 123);
            var count = connection.QueryAsync <int>("select count(1) from literal2 where id={=foo}", args).Result.Single();

            count.IsEqualTo(1);
        }
    public async partial global::PooledAwait.PooledTask <global::SomeType> TaskAsync(global::System.Data.Common.DbConnection connection, int id, string name)
    {
        // locals
        global::System.Data.Common.DbCommand?   __dapper__command = null;
        global::System.Data.Common.DbDataReader?__dapper__reader  = null;
        bool __dapper__close = false;

        int[]? __dapper__tokenBuffer = null;
        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                await connection !.OpenAsync(global::System.Threading.CancellationToken.None).ConfigureAwait(false);
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Async_SinglePooled_input_cs_TaskAsync_8, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // assign parameter values
#pragma warning disable CS0618
            __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(id);
            __dapper__command.Parameters[1].Value = global::Dapper.Internal.InternalUtilities.AsValue(name);
#pragma warning restore CS0618

            // execute reader
            const global::System.Data.CommandBehavior __dapper__behavior = global::System.Data.CommandBehavior.SequentialAccess | global::System.Data.CommandBehavior.SingleResult | global::System.Data.CommandBehavior.SingleRow;
            __dapper__reader = await __dapper__command.ExecuteReaderAsync(__dapper__close?(__dapper__behavior | global::System.Data.CommandBehavior.CloseConnection) : __dapper__behavior, global::System.Threading.CancellationToken.None).ConfigureAwait(false);

            __dapper__close = false;             // performed via CommandBehavior

            // process single row
            global::SomeType __dapper__result;
            if (__dapper__reader.HasRows && await __dapper__reader.ReadAsync(global::System.Threading.CancellationToken.None).ConfigureAwait(false))
            {
                __dapper__result = await global::Dapper.TypeReader.TryGetReader <global::SomeType>() !.ReadAsync(__dapper__reader, ref __dapper__tokenBuffer, global::System.Threading.CancellationToken.None).ConfigureAwait(false);
            }
            else
            {
                __dapper__result = default !;
Example #14
0
    public partial int?ShouldDetectThis(global::System.Data.Common.DbConnection connection, string region)
    {
        // locals
        global::System.Data.Common.DbCommand?   __dapper__command = null;
        global::System.Data.Common.DbDataReader?__dapper__reader  = null;
        bool __dapper__close = false;

        int[]? __dapper__tokenBuffer = null;
        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                connection !.Open();
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Basic_input_cs_ShouldDetectThis_11, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // assign parameter values
#pragma warning disable CS0618
            __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(region);
#pragma warning restore CS0618

            // execute reader
            const global::System.Data.CommandBehavior __dapper__behavior = global::System.Data.CommandBehavior.SequentialAccess | global::System.Data.CommandBehavior.SingleResult | global::System.Data.CommandBehavior.SingleRow;
            __dapper__reader = __dapper__command.ExecuteReader(__dapper__close ? (__dapper__behavior | global::System.Data.CommandBehavior.CloseConnection) : __dapper__behavior);
            __dapper__close  = false;            // performed via CommandBehavior

            // process single row
            int?__dapper__result;
            if (__dapper__reader.HasRows && __dapper__reader.Read())
            {
                __dapper__result = global::Dapper.TypeReader.TryGetReader <int?>() !.Read(__dapper__reader, ref __dapper__tokenBuffer);
            }
            else
            {
                __dapper__result = default !;
    public partial global::System.Collections.Generic.List <global::SomeType> List(global::System.Data.Common.DbConnection connection, int id, string name)
    {
        // locals
        global::System.Data.Common.DbCommand?   __dapper__command = null;
        global::System.Data.Common.DbDataReader?__dapper__reader  = null;
        bool __dapper__close = false;

        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                connection !.Open();
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Sync_Multiple_input_cs_List_8, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // assign parameter values
#pragma warning disable CS0618
            __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(id);
            __dapper__command.Parameters[1].Value = global::Dapper.Internal.InternalUtilities.AsValue(name);
#pragma warning restore CS0618

            // execute reader
            const global::System.Data.CommandBehavior __dapper__behavior = global::System.Data.CommandBehavior.SequentialAccess | global::System.Data.CommandBehavior.SingleResult | global::System.Data.CommandBehavior.SingleRow;
            __dapper__reader = __dapper__command.ExecuteReader(__dapper__close ? (__dapper__behavior | global::System.Data.CommandBehavior.CloseConnection) : __dapper__behavior);
            __dapper__close  = false;            // performed via CommandBehavior

            // process single row
            global::System.Collections.Generic.List <global::SomeType> __dapper__result;
            if (__dapper__reader.HasRows && __dapper__reader.Read())
            {
                __dapper__result = global::Dapper.SqlMapper.GetRowParser <global::System.Collections.Generic.List <global::SomeType> >(__dapper__reader).Invoke(__dapper__reader);
            }
            else
            {
                __dapper__result = default !;
Example #16
0
    public partial void Abstract(global::System.Data.Common.DbConnection connection)
    {
        // locals
        global::System.Data.Common.DbCommand?__dapper__command = null;
        bool __dapper__close = false;

        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                connection !.Open();
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Transactions_input_cs_Abstract_9, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // execute non-query
            __dapper__command.ExecuteNonQuery();

            // TODO: post-process parameters
        }
        finally
        {
            // cleanup
            if (__dapper__command is not null)
            {
                __dapper__command.Connection = default;
                __dapper__command            = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Transactions_input_cs_Abstract_9, __dapper__command);
                __dapper__command?.Dispose();
            }
            if (__dapper__close)
            {
                connection?.Close();
            }
        }
 /// <summary>
 /// Execute a query asynchronously using .NET 4.5 Task.
 /// </summary>
 /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks>
 public static async Task <IEnumerable <dynamic> > QueryAsync(this IDbConnection cnn, CommandDefinition command)
 {
     return(await QueryAsync <DapperRow>(cnn, typeof(DapperRow), command).ConfigureAwait(false));
 }
 /// <summary>
 /// Perform a multi mapping query with 7 input parameters
 /// </summary>
 public static Task <IEnumerable <TReturn> > QueryAsync <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, Func <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int?commandTimeout = null, CommandType?commandType = null)
 {
     return(MultiMapAsync <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn,
                                                                                                new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken)), map, splitOn));
 }
 internal IDbCommand SetupCommand(IDbConnection cnn, Action<IDbCommand, object> paramReader)
 {
     var cmd = cnn.CreateCommand();
     var init = GetInit(cmd.GetType());
     if (init != null) init(cmd);
     if (transaction != null)
         cmd.Transaction = transaction;
     cmd.CommandText = commandText;
     if (commandTimeout.HasValue)
     {
         cmd.CommandTimeout = commandTimeout.Value;
     }
     else if (SqlMapper.Settings.CommandTimeout.HasValue)
     {
         cmd.CommandTimeout = SqlMapper.Settings.CommandTimeout.Value;
     }
     if (commandType.HasValue)
         cmd.CommandType = commandType.Value;
     if (paramReader != null)
     {
         paramReader(cmd, parameters);
     }
     return cmd;
 }
 /// <summary>
 /// Perform a multi mapping query with 7 input parameters
 /// </summary>
 public static Task <IEnumerable <TReturn> > QueryAsync <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, CommandDefinition command, Func <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, string splitOn = "Id")
 {
     return(MultiMapAsync <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, command, map, splitOn));
 }
        private static async Task <IEnumerable <TReturn> > MultiMapAsync <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, CommandDefinition command, Delegate map, string splitOn)
        {
            object param     = command.Parameters;
            var    identity  = new Identity(command.CommandText, command.CommandType, cnn, typeof(TFirst), param == null ? null : param.GetType(), new[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) });
            var    info      = GetCacheInfo(identity, param, command.AddToCache);
            bool   wasClosed = cnn.State == ConnectionState.Closed;

            try
            {
                if (wasClosed)
                {
                    await((DbConnection)cnn).OpenAsync(command.CancellationToken).ConfigureAwait(false);
                }
                using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
                    using (var reader = await cmd.ExecuteReaderAsync(wasClosed ? CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess : CommandBehavior.SequentialAccess, command.CancellationToken).ConfigureAwait(false))
                    {
                        if (!command.Buffered)
                        {
                            wasClosed = false;                // handing back open reader; rely on command-behavior
                        }
                        var results = MultiMapImpl <TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(null, CommandDefinition.ForCallback(command.Parameters), map, splitOn, reader, identity, true);
                        return(command.Buffered ? results.ToList() : results);
                    }
            } finally
            {
                if (wasClosed)
                {
                    cnn.Close();
                }
            }
        }
        /// <summary>
        /// Perform a multi mapping query with arbitrary input parameters
        /// </summary>
        /// <typeparam name="TReturn">The return type</typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="types">array of types in the recordset</param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <param name="commandType">Is it a stored proc or a batch?</param>
        /// <returns></returns>
        public static Task <IEnumerable <TReturn> > QueryAsync <TReturn>(this IDbConnection cnn, string sql, Type[] types, Func <object[], TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int?commandTimeout = null, CommandType?commandType = null)
        {
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None, default(CancellationToken));

            return(MultiMapAsync <TReturn>(cnn, command, types, map, splitOn));
        }
Example #23
0
        private void LiteralReplacementDynamic(IDbConnection connection)
        {
            var args = new DynamicParameters();
            args.Add("id", 123);
            try { connection.ExecuteAsync("drop table literal2").Wait(); } catch { }
            connection.ExecuteAsync("create table literal2 (id int not null)").Wait();
            connection.ExecuteAsync("insert literal2 (id) values ({=id})", args).Wait();

            args = new DynamicParameters();
            args.Add("foo", 123);
            var count = connection.QueryAsync<int>("select count(1) from literal2 where id={=foo}", args).Result.Single();
            count.IsEqualTo(1);
        }
Example #24
0
 public partial global::System.Collections.Generic.IAsyncEnumerable <global::SomeType> SequenceAsync(global::System.Data.Common.DbConnection connection, int id, string name)
 {
     // use wrapper method to add support for enumerator cancellation
     return(__dapper__SequenceAsync(connection, id, name, global::System.Threading.CancellationToken.None));
 /// <summary>
 /// Gets the feature set based on the passed connection
 /// </summary>
 public static FeatureSupport Get(IDbConnection connection)
 {
     string name = connection?.GetType().Name;
     if (string.Equals(name, "npgsqlconnection", StringComparison.OrdinalIgnoreCase)) return postgres;
     return @default;
 }
 internal IDbCommand SetupCommand(IDbConnection cnn, Action<IDbCommand, object> paramReader)
 {
     var cmd = cnn.CreateCommand();
     var init = GetInit(cmd.GetType());
     init?.Invoke(cmd);
     if (Transaction != null)
         cmd.Transaction = Transaction;
     cmd.CommandText = CommandText;
     if (CommandTimeout.HasValue)
     {
         cmd.CommandTimeout = CommandTimeout.Value;
     }
     else if (SqlMapper.Settings.CommandTimeout.HasValue)
     {
         cmd.CommandTimeout = SqlMapper.Settings.CommandTimeout.Value;
     }
     if (CommandType.HasValue)
         cmd.CommandType = CommandType.Value;
     paramReader?.Invoke(cmd, Parameters);
     return cmd;
 }
    public partial global::System.Collections.Generic.IEnumerable <global::SomeType> Sequence(global::System.Data.Common.DbConnection connection, int id, string name)
    {
        // locals
        global::System.Data.Common.DbCommand?   __dapper__command = null;
        global::System.Data.Common.DbDataReader?__dapper__reader  = null;
        bool __dapper__close = false;

        int[]? __dapper__tokenBuffer = null;
        try
        {
            // prepare connection
            if (connection !.State == global::System.Data.ConnectionState.Closed)
            {
                connection !.Open();
                __dapper__close = true;
            }

            // prepare command (excluding parameter values)
            if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Sync_Sequence_input_cs_Sequence_7, null)) is null)
            {
                __dapper__command = __dapper__CreateCommand(connection !);
            }
            else
            {
                __dapper__command.Connection = connection;
            }

            // assign parameter values
#pragma warning disable CS0618
            __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(id);
            __dapper__command.Parameters[1].Value = global::Dapper.Internal.InternalUtilities.AsValue(name);
#pragma warning restore CS0618

            // execute reader
            const global::System.Data.CommandBehavior __dapper__behavior = global::System.Data.CommandBehavior.SequentialAccess | global::System.Data.CommandBehavior.SingleResult | global::System.Data.CommandBehavior.SingleRow;
            __dapper__reader = __dapper__command.ExecuteReader(__dapper__close ? (__dapper__behavior | global::System.Data.CommandBehavior.CloseConnection) : __dapper__behavior);
            __dapper__close  = false;            // performed via CommandBehavior

            // process multiple rows
            if (__dapper__reader.HasRows)
            {
                var __dapper__parser = global::Dapper.TypeReader.TryGetReader <global::SomeType>() !;
                global::System.Span <int> __dapper__tokens = __dapper__reader.FieldCount <= global::Dapper.TypeReader.MaxStackTokens ? stackalloc int[__dapper__reader.FieldCount] : global::Dapper.TypeReader.RentSpan(ref __dapper__tokenBuffer, __dapper__reader.FieldCount);
                __dapper__parser.IdentifyFieldTokensFromSchema(__dapper__reader, __dapper__tokens);
                while (__dapper__reader.Read())
                {
                    yield return(__dapper__parser.Read(__dapper__reader, __dapper__tokens));
                }
            }
            // consume additional results (ensures errors from the server are observed)
            while (__dapper__reader.NextResult())
            {
            }

            // TODO: post-process parameters
        }
        finally
        {
            // cleanup
            global::Dapper.TypeReader.Return(ref __dapper__tokenBuffer);
            __dapper__reader?.Dispose();
            if (__dapper__command is not null)
            {
                __dapper__command.Connection = default;
                __dapper__command            = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Sync_Sequence_input_cs_Sequence_7, __dapper__command);
                __dapper__command?.Dispose();
            }
            if (__dapper__close)
            {
                connection?.Close();
            }
        }
 /// <summary>
 /// Execute a query asynchronously using .NET 4.5 Task.
 /// </summary>
 public static Task <IEnumerable <T> > QueryAsync <T>(this IDbConnection cnn, CommandDefinition command)
 {
     return(QueryAsync <T>(cnn, typeof(T), command));
 }
 /// <summary>
 /// Execute a query asynchronously using .NET 4.5 Task.
 /// </summary>
 /// <remarks>Note: each row can be accessed via "dynamic", or by casting to an IDictionary&lt;string,object&gt;</remarks>
 public static async Task <IEnumerable <dynamic> > QueryAsync(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null)
 {
     return(await QueryAsync <DapperRow>(cnn, typeof(DapperRow), new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))).ConfigureAwait(false));
 }
Example #30
0
 private void LiteralReplacement(IDbConnection connection)
 {
     try { connection.ExecuteAsync("drop table literal1").Wait(); } catch { }
     connection.ExecuteAsync("create table literal1 (id int not null, foo int not null)").Wait();
     connection.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", new { id = 123, foo = 456 }).Wait();
     var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } };
     connection.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", rows).Wait();
     var count = connection.QueryAsync<int>("select count(1) from literal1 where id={=foo}", new { foo = 123 }).Result.Single();
     count.IsEqualTo(1);
     int sum = connection.QueryAsync<int>("select sum(id) + sum(foo) from literal1").Result.Single();
     sum.IsEqualTo(123 + 456 + 1 + 2 + 3 + 4);
 }
Example #31
0
        static async global::System.Collections.Generic.IAsyncEnumerable <global::SomeType> __dapper__SequenceAsync(global::System.Data.Common.DbConnection connection, int id, string name, [global::System.Runtime.CompilerServices.EnumeratorCancellationAttribute] global::System.Threading.CancellationToken __dapper__cancellation)
        {
            // locals
            global::System.Data.Common.DbCommand?   __dapper__command = null;
            global::System.Data.Common.DbDataReader?__dapper__reader  = null;
            bool __dapper__close = false;

            int[]? __dapper__tokenBuffer = null;
            try
            {
                // prepare connection
                if (connection !.State == global::System.Data.ConnectionState.Closed)
                {
                    await connection !.OpenAsync(__dapper__cancellation).ConfigureAwait(false);
                    __dapper__close = true;
                }

                // prepare command (excluding parameter values)
                if ((__dapper__command = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Async_Sequence_input_cs_SequenceAsync_8, null)) is null)
                {
                    __dapper__command = __dapper__CreateCommand(connection !);
                }
                else
                {
                    __dapper__command.Connection = connection;
                }

                // assign parameter values
#pragma warning disable CS0618
                __dapper__command.Parameters[0].Value = global::Dapper.Internal.InternalUtilities.AsValue(id);
                __dapper__command.Parameters[1].Value = global::Dapper.Internal.InternalUtilities.AsValue(name);
#pragma warning restore CS0618

                // execute reader
                const global::System.Data.CommandBehavior __dapper__behavior = global::System.Data.CommandBehavior.SequentialAccess | global::System.Data.CommandBehavior.SingleResult | global::System.Data.CommandBehavior.SingleRow;
                __dapper__reader = await __dapper__command.ExecuteReaderAsync(__dapper__close?(__dapper__behavior | global::System.Data.CommandBehavior.CloseConnection) : __dapper__behavior, __dapper__cancellation).ConfigureAwait(false);

                __dapper__close = false;                 // performed via CommandBehavior

                // process multiple rows
                if (__dapper__reader.HasRows)
                {
                    var __dapper__parser = global::Dapper.TypeReader.TryGetReader <global::SomeType>() !;
                    var __dapper__tokens = global::Dapper.TypeReader.RentSegment(ref __dapper__tokenBuffer, __dapper__reader.FieldCount);
                    __dapper__parser.IdentifyFieldTokensFromSchema(__dapper__reader, __dapper__tokens);
                    while (await __dapper__reader.ReadAsync(__dapper__cancellation).ConfigureAwait(false))
                    {
                        yield return(await __dapper__parser.ReadAsync(__dapper__reader, __dapper__tokens, __dapper__cancellation).ConfigureAwait(false));
                    }
                }
                // consume additional results (ensures errors from the server are observed)
                while (await __dapper__reader.NextResultAsync(__dapper__cancellation).ConfigureAwait(false))
                {
                }

                // TODO: post-process parameters
            }
            finally
            {
                // cleanup
                global::Dapper.TypeReader.Return(ref __dapper__tokenBuffer);
                __dapper__reader?.Dispose();
                if (__dapper__command is not null)
                {
                    __dapper__command.Connection = default;
                    __dapper__command            = global::System.Threading.Interlocked.Exchange(ref s___dapper__command_Samples_Async_Sequence_input_cs_SequenceAsync_8, __dapper__command);
                    __dapper__command?.Dispose();
                }
                if (__dapper__close)
                {
                    connection?.Close();
                }
            }
        }
 /// <summary>
 /// Execute a query asynchronously using .NET 4.5 Task.
 /// </summary>
 public static Task <IEnumerable <T> > QueryAsync <T>(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null)
 {
     return(QueryAsync <T>(cnn, typeof(T), new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered, default(CancellationToken))));
 }
        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
        public static Task <GridReader> QueryMultipleAsync(
#if CSHARP30
            this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int?commandTimeout, CommandType?commandType
#else
            this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int?commandTimeout = null, CommandType?commandType = null
 /// <summary>
 /// Execute a query asynchronously using .NET 4.5 Task.
 /// </summary>
 public static Task <IEnumerable <object> > QueryAsync(this IDbConnection cnn, Type type, CommandDefinition command)
 {
     return(QueryAsync <object>(cnn, type, command));
 }
        private static async Task <IEnumerable <T> > QueryAsync <T>(this IDbConnection cnn, Type effectiveType, CommandDefinition command)
        {
            object param     = command.Parameters;
            var    identity  = new Identity(command.CommandText, command.CommandType, cnn, effectiveType, param == null ? null : param.GetType(), null);
            var    info      = GetCacheInfo(identity, param, command.AddToCache);
            bool   wasClosed = cnn.State == ConnectionState.Closed;
            var    cancel    = command.CancellationToken;

            using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
            {
                DbDataReader reader = null;
                try
                {
                    if (wasClosed)
                    {
                        await((DbConnection)cnn).OpenAsync(cancel).ConfigureAwait(false);
                    }
                    reader = await cmd.ExecuteReaderAsync(wasClosed?CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess : CommandBehavior.SequentialAccess, cancel).ConfigureAwait(false);

                    var tuple = info.Deserializer;
                    int hash  = GetColumnHash(reader);
                    if (tuple.Func == null || tuple.Hash != hash)
                    {
                        tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
                        if (command.AddToCache)
                        {
                            SetQueryCache(identity, info);
                        }
                    }

                    var func = tuple.Func;

                    if (command.Buffered)
                    {
                        List <T> buffer = new List <T>();
                        while (await reader.ReadAsync(cancel).ConfigureAwait(false))
                        {
                            buffer.Add((T)func(reader));
                        }
                        while (await reader.NextResultAsync().ConfigureAwait(false))
                        {
                        }
                        command.OnCompleted();
                        return(buffer);
                    }
                    else
                    {
                        // can't use ReadAsync / cancellation; but this will have to do
                        wasClosed = false; // don't close if handing back an open reader; rely on the command-behavior
                        var deferred = ExecuteReaderSync <T>(reader, func, command.Parameters);
                        reader = null;     // to prevent it being disposed before the caller gets to see it
                        return(deferred);
                    }
                }
                finally
                {
                    using (reader) { } // dispose if non-null
                    if (wasClosed)
                    {
                        cnn.Close();
                    }
                }
            }
        }