Ejemplo n.º 1
0
        public void MixingParametersAndValues()
        {
            Configuration   cfg     = new Configuration();
            ISessionFactory factory = cfg.BuildSessionFactory();

            ISessionFactoryImplementor factoryImpl = (ISessionFactoryImplementor)factory;
            SqlInsertBuilder           insert      = new SqlInsertBuilder(factoryImpl);

            insert.SetTableName("test_insert_builder");

            insert.AddColumn("literalColumn", false, (ILiteralType)NHibernateUtil.Boolean);
            insert.AddColumn("intColumn", NHibernateUtil.Int32);
            insert.AddColumn("stringColumn", 5.ToString());
            insert.AddColumn("longColumn", NHibernateUtil.Int64);

            SqlCommandInfo sqlCommand = insert.ToSqlCommandInfo();

            SqlType[] actualParameterTypes = sqlCommand.ParameterTypes;

            string expectedSql =
                "INSERT INTO test_insert_builder (literalColumn, intColumn, stringColumn, longColumn) VALUES (0, ?, 5, ?)";

            Assert.AreEqual(expectedSql, sqlCommand.Text.ToString(), "SQL String");

            Assert.AreEqual(2, actualParameterTypes.Length);
            Assert.AreEqual(SqlTypeFactory.Int32, actualParameterTypes[0], "First Parameter Type");
            Assert.AreEqual(SqlTypeFactory.Int64, actualParameterTypes[1], "Second Parameter Type");
        }
Ejemplo n.º 2
0
        internal decimal GetCurrentTemperature()
        {
            var selectCommand = new SqlCommandInfo("SELECT TOP 1 temperature FROM TemperatureLog ORDER BY origin_datetime DESC");
            var temperature   = SqlExecutionHelper.ExecuteScalar <decimal>(selectCommand);

            return(temperature);
        }
Ejemplo n.º 3
0
        public void DeleteSqlStringTest()
        {
            Configuration   cfg     = new Configuration();
            ISessionFactory factory = cfg.BuildSessionFactory();

            ISessionFactoryImplementor factoryImpl = (ISessionFactoryImplementor)factory;
            SqlDeleteBuilder           delete      = new SqlDeleteBuilder(factoryImpl.Dialect, factoryImpl);

            delete.SetTableName("test_delete_builder");


            delete.SetIdentityColumn(new string[] { "decimalColumn" }, NHibernateUtil.Decimal);
            delete.SetVersionColumn(new string[] { "versionColumn" }, (IVersionType)NHibernateUtil.Int32);

            delete.AddWhereFragment("a=b");

            SqlCommandInfo sqlCommand = delete.ToSqlCommandInfo();

            string expectedSql = "DELETE FROM test_delete_builder WHERE decimalColumn = ? AND versionColumn = ? AND a=b";

            Assert.AreEqual(expectedSql, sqlCommand.Text.ToString(), "SQL String");

            SqlType[] actualParameterTypes = sqlCommand.ParameterTypes;
            Assert.AreEqual(2, actualParameterTypes.Length, "Two parameters");

            Assert.AreEqual(SqlTypeFactory.Decimal, actualParameterTypes[0], "firstParam Type");
            Assert.AreEqual(SqlTypeFactory.Int32, actualParameterTypes[1], "secondParam Type");
        }
Ejemplo n.º 4
0
        protected internal override DbCommand Prepare(SqlCommandInfo insertSQL, ISessionImplementor session)
        {
            var command = session.Batcher.PrepareCommand(CommandType.Text, insertSQL.Text, insertSQL.ParameterTypes);
            //Add the output parameter
            var idParameter = factory.ConnectionProvider.Driver.GenerateParameter(command, ReturnParameterName,
                                                                                  paramType);

            driveGeneratedParamName = idParameter.ParameterName;

            if (factory.Dialect.InsertGeneratedIdentifierRetrievalMethod == InsertGeneratedIdentifierRetrievalMethod.OutputParameter)
            {
                idParameter.Direction = ParameterDirection.Output;
            }
            else if (factory.Dialect.InsertGeneratedIdentifierRetrievalMethod == InsertGeneratedIdentifierRetrievalMethod.ReturnValueParameter)
            {
                idParameter.Direction = ParameterDirection.ReturnValue;
            }
            else
            {
                throw new System.NotImplementedException("Unsupported InsertGeneratedIdentifierRetrievalMethod: " + factory.Dialect.InsertGeneratedIdentifierRetrievalMethod);
            }

            command.Parameters.Add(idParameter);
            return(command);
        }
Ejemplo n.º 5
0
        internal IEnumerable <RebootLogRecord> GetRebootLog(int numberOfRecords)
        {
            var records = new List <RebootLogRecord>();

            var selectCommand = new SqlCommandInfo(
                $@"SELECT TOP {numberOfRecords} reboot_time, uptime
					FROM
						(
							SELECT
								origin_datetime AS reboot_time,
								uptime,
								LAG(uptime) OVER(ORDER BY origin_datetime DESC) AS next_uptime
							FROM DiagnosticInfoLog
						) subq
					WHERE
						uptime > next_uptime"                        );

            SqlExecutionHelper.ExecuteReader(
                selectCommand,
                row =>
            {
                DateTime rebootDateTime = row.GetDateTime(row.GetOrdinal("reboot_time"));
                long uptime             = row.GetInt64(row.GetOrdinal("uptime"));

                records.Add(new RebootLogRecord(rebootDateTime, uptime));
            });

            return(records);
        }
Ejemplo n.º 6
0
        protected internal override async Task <DbCommand> PrepareAsync(SqlCommandInfo insertSQL, ISessionImplementor session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var command = await(session.Batcher.PrepareCommandAsync(CommandType.Text, insertSQL.Text, insertSQL.ParameterTypes, cancellationToken)).ConfigureAwait(false);
            //Add the output parameter
            var idParameter = factory.ConnectionProvider.Driver.GenerateParameter(command, ReturnParameterName,
                                                                                  paramType);

            driveGeneratedParamName = idParameter.ParameterName;

            if (factory.Dialect.InsertGeneratedIdentifierRetrievalMethod == InsertGeneratedIdentifierRetrievalMethod.OutputParameter)
            {
                idParameter.Direction = ParameterDirection.Output;
            }
            else if (factory.Dialect.InsertGeneratedIdentifierRetrievalMethod == InsertGeneratedIdentifierRetrievalMethod.ReturnValueParameter)
            {
                idParameter.Direction = ParameterDirection.ReturnValue;
            }
            else
            {
                throw new System.NotImplementedException("Unsupported InsertGeneratedIdentifierRetrievalMethod: " + factory.Dialect.InsertGeneratedIdentifierRetrievalMethod);
            }

            command.Parameters.Add(idParameter);
            return(command);
        }
Ejemplo n.º 7
0
        public IEnumerable <DeviceControlOptionsRecord> GetDeviceControlOptions()
        {
            var records = new List <DeviceControlOptionsRecord>();

            var selectCommand = new SqlCommandInfo(
                "SELECT" +
                " device," +
                " current_state," +
                " use_schedule," +
                " target_state " +
                " FROM DeviceStates");

            SqlExecutionHelper.ExecuteReader(
                selectCommand,
                row =>
            {
                var device      = row.GetFieldValue <Devices>("device");
                var useSchedule = row.GetFieldValue <bool>("use_schedule");

                var record = new DeviceControlOptionsRecord(device, useSchedule)
                {
                    CurrentState = row.GetFieldValue <DeviceStates?>("current_state"),
                    TargetState  = row.GetFieldValue <DeviceStates?>("target_state")
                };

                records.Add(record);
            });

            return(records);
        }
Ejemplo n.º 8
0
        private IEnumerable <DeviceStateLogRecord> getDeviceStateLog(SqlCommandText whereClause)
        {
            var records = new List <DeviceStateLogRecord>();

            var selectCommand = new SqlCommandInfo(
                "SELECT" +
                " switch_datetime," +
                " device," +
                " state" +
                " FROM DeviceStateLog" +
                (whereClause.IsEmpty ? string.Empty : " WHERE " + whereClause.CommandText) +
                " ORDER BY switch_datetime DESC");

            selectCommand.AddParameters(whereClause);

            SqlExecutionHelper.ExecuteReader(
                selectCommand,
                row =>
            {
                DateTime datetime = row.GetDateTime(row.GetOrdinal("switch_datetime"));
                var device        = (Devices)row.GetInt16(row.GetOrdinal("device"));
                var state         = (DeviceStates)row.GetInt16(row.GetOrdinal("state"));

                records.Add(new DeviceStateLogRecord(datetime, device, state));
            });

            return(records);
        }
Ejemplo n.º 9
0
 protected internal override Task <DbCommand> PrepareAsync(SqlCommandInfo insertSQL, ISessionImplementor session, CancellationToken cancellationToken)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         return(Task.FromCanceled <DbCommand>(cancellationToken));
     }
     return(session.Batcher.PrepareCommandAsync(CommandType.Text, insertSQL.Text, insertSQL.ParameterTypes, cancellationToken));
 }
Ejemplo n.º 10
0
        private void addDeviceStateLogRecord(Devices device, DeviceStates state)
        {
            var insertCommand = new SqlCommandInfo("INSERT INTO DeviceStateLog(device, state) VALUES (@device, @state)");

            insertCommand.Parameters.Add("device", device);
            insertCommand.Parameters.Add("state", state);

            _sqlExecutionHelper.ExecuteNonQuery(insertCommand);
        }
Ejemplo n.º 11
0
        public object PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)
        {
            try
            {
                // prepare and execute the insert
                IDbCommand insert = session.Batcher.PrepareCommand(insertSQL.CommandType, insertSQL.Text, insertSQL.ParameterTypes);
                try
                {
                    binder.BindValues(insert);
                    session.Batcher.ExecuteNonQuery(insert);
                }
                finally
                {
                    session.Batcher.CloseCommand(insert, null);
                }
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                 "could not insert: " + persister.GetInfoString(), insertSQL.Text);
            }

            SqlString selectSQL = SelectSQL;

            using (new SessionIdLoggingContext(session.SessionId))
                try
                {
                    //fetch the generated id in a separate query
                    IDbCommand idSelect = session.Batcher.PrepareCommand(CommandType.Text, selectSQL, ParametersTypes);
                    try
                    {
                        BindParameters(session, idSelect, binder.Entity);
                        IDataReader rs = session.Batcher.ExecuteReader(idSelect);
                        try
                        {
                            return(GetResult(session, rs, binder.Entity));
                        }
                        finally
                        {
                            session.Batcher.CloseReader(rs);
                        }
                    }
                    finally
                    {
                        session.Batcher.CloseCommand(idSelect, null);
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                     "could not retrieve generated id after insert: " + persister.GetInfoString(),
                                                     insertSQL.Text);
                }
        }
Ejemplo n.º 12
0
 private void CombineCriteriaQueries()
 {
     foreach (CriteriaLoader loader in loaders)
     {
         CriteriaQueryTranslator translator = loader.Translator;
         translators.Add(translator);
         QueryParameters queryParameters = translator.GetQueryParameters();
         parameters.Add(queryParameters);
         SqlCommandInfo commandInfo = loader.GetQueryStringAndTypes(session, queryParameters, resultSetsCommand.ParametersCount);
         resultSetsCommand.Append(commandInfo);
     }
 }
Ejemplo n.º 13
0
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="command">Сведения о запросе, который должен быть выполнен в БД</param>
        /// <param name="connectionStringName">Имя строки подключения в конфигурационном файле</param>
        /// <param name="converter">Конвертер для перевода сущностей в DTO и обратно</param>
        public SqlFilteredRepository(
            SqlCommandInfo command,
            string connectionStringName,
            IEntityDtoConverter <TEntity, TDto> converter) : base(connectionStringName)
        {
            Contract.Requires(!string.IsNullOrEmpty(command.Command));
            Contract.Requires(!string.IsNullOrEmpty(connectionStringName));
            Contract.Requires(converter != null);

            this.command   = command;
            this.converter = converter;
        }
Ejemplo n.º 14
0
        protected internal override IDbCommand Prepare(SqlCommandInfo insertSQL, ISessionImplementor session)
        {
            IDbCommand command = session.Batcher.PrepareCommand(CommandType.Text, insertSQL.Text, insertSQL.ParameterTypes);
            //Add the output parameter
            IDbDataParameter idParameter = factory.ConnectionProvider.Driver.GenerateParameter(command, ReturnParameterName,
                                                                                               paramType);

            driveGeneratedParamName = idParameter.ParameterName;
            idParameter.Direction   = ParameterDirection.ReturnValue;

            command.Parameters.Add(idParameter);
            return(command);
        }
Ejemplo n.º 15
0
        public DeviceStates GetDeviceState(Devices device)
        {
            var selectCommand = new SqlCommandInfo(
                "SELECT current_state" +
                " FROM DeviceStates" +
                " WHERE device = @device");

            selectCommand.Parameters.Add("device", device);

            var rawDeviceState = SqlExecutionHelper.ExecuteScalar <bool>(selectCommand);

            return(rawDeviceState ? DeviceStates.On : DeviceStates.Off);
        }
Ejemplo n.º 16
0
 private void CombineCriteriaQueries()
 {
     foreach (CriteriaLoader loader in loaders)
     {
         CriteriaQueryTranslator translator = loader.Translator;
         translators.Add(translator);
         QueryParameters queryParameters = translator.GetQueryParameters();
         parameters.Add(queryParameters);
         SqlCommandInfo commandInfo = loader.GetQueryStringAndTypes(session, queryParameters);
         sqlString = sqlString.Append(commandInfo.Text)
                     .Append(session.Factory.ConnectionProvider.Driver.MultipleQueriesSeparator)
                     .Append(Environment.NewLine);
         types.AddRange(commandInfo.ParameterTypes);
     }
 }
Ejemplo n.º 17
0
        internal DateTime GetBootDateTime()
        {
            var selectCommand = new SqlCommandInfo(
                @"SELECT TOP 1 boot_time
					FROM
					(
						SELECT
							LAG(origin_datetime) OVER(ORDER BY origin_datetime DESC) AS boot_time,
							uptime,
							LAG(uptime) OVER(ORDER BY origin_datetime DESC) AS next_uptime
						FROM DiagnosticInfoLog
					) subq
				WHERE uptime > next_uptime"                );

            return(SqlExecutionHelper.ExecuteScalar <DateTime>(selectCommand));
        }
Ejemplo n.º 18
0
        private SqlCommandInfo GetSqlCommandInfo(Transaction transaction, DbEntityEntry entry, EntityMapping entityMapping)
        {
            if (entityMapping.TableName.Contains("_Transacciones"))
            {
                return(null);
            }

            string sqlInsert;

            object[] param;
            CreateTransactionInsertStatement(entityMapping, entry, transaction, out sqlInsert, out param);

            var sqlCommandInfo = new SqlCommandInfo(sqlInsert, param);

            return(sqlCommandInfo);
        }
Ejemplo n.º 19
0
 private void AggregateQueriesInformation()
 {
     foreach (AbstractQueryImpl query in queries)
     {
         QueryParameters queryParameters = query.GetQueryParameters();
         queryParameters.ValidateParameters();
         query.VerifyParameters();
         foreach (var translator in GetTranslators(query, queryParameters))
         {
             translators.Add(translator);
             parameters.Add(queryParameters);
             queryParameters = GetFilteredQueryParameters(queryParameters, translator);
             SqlCommandInfo commandInfo = translator.Loader.GetQueryStringAndTypes(session, queryParameters, resultSetsCommand.ParametersCount);
             resultSetsCommand.Append(commandInfo);
         }
     }
 }
Ejemplo n.º 20
0
        public void PostData(PostDataRequest request)
        {
            var insertTemperatureCommand = new SqlCommandInfo("INSERT INTO TemperatureLog(temperature) VALUES (@temperature)");

            insertTemperatureCommand.Parameters.Add("temperature", request.Temperature);
            _sqlExecutionHelper.ExecuteNonQuery(insertTemperatureCommand);

            var insertDiagnosticInfoCommand = new SqlCommandInfo("INSERT INTO DiagnosticInfoLog(uptime) VALUES (@uptime)");

            insertDiagnosticInfoCommand.Parameters.Add("uptime", request.Uptime);
            _sqlExecutionHelper.ExecuteNonQuery(insertDiagnosticInfoCommand);

            foreach (var deviceState in request.DeviceStates)
            {
                onDeviceStateChanged(deviceState.Key, deviceState.Value);
            }
        }
Ejemplo n.º 21
0
        public void MergeDeviceState <T>(Devices device, string fieldName, T fieldValue)
        {
            string commandText = " MERGE DeviceStates AS target" +
                                 $" USING(SELECT @device, @fieldValue) AS source (device, {fieldName})" +
                                 " ON(target.device = source.device)" +
                                 " WHEN MATCHED THEN" +
                                 $" UPDATE SET {fieldName} = source.{fieldName}" +
                                 " WHEN NOT MATCHED THEN" +
                                 $" INSERT(device, {fieldName})" +
                                 $" VALUES(source.device, source.{fieldName});";

            var mergeCommand = new SqlCommandInfo(commandText);

            mergeCommand.Parameters.Add("device", device);
            mergeCommand.Parameters.Add("fieldValue", fieldValue);

            SqlExecutionHelper.ExecuteNonQuery(mergeCommand);
        }
        public void UpdateStringSqlTest()
        {
            Configuration   cfg     = new Configuration();
            ISessionFactory factory = cfg.BuildSessionFactory();

            ISessionFactoryImplementor factoryImpl = (ISessionFactoryImplementor)factory;
            SqlUpdateBuilder           update      = new SqlUpdateBuilder(factoryImpl.Dialect, factoryImpl);

            update.SetTableName("test_update_builder");

            update.AddColumns(new string[] { "intColumn" }, NHibernateUtil.Int32);
            update.AddColumns(new string[] { "longColumn" }, NHibernateUtil.Int64);
            update.AddColumn("literalColumn", false, (ILiteralType)NHibernateUtil.Boolean);
            update.AddColumn("stringColumn", 5.ToString());

            update.SetIdentityColumn(new string[] { "decimalColumn" }, NHibernateUtil.Decimal);
            update.SetVersionColumn(new string[] { "versionColumn" }, (IVersionType)NHibernateUtil.Int32);

            update.AddWhereFragment("a=b");
            SqlCommandInfo sqlCommand = update.ToSqlCommandInfo();

            Assert.AreEqual(CommandType.Text, sqlCommand.CommandType);
            string falseString = factoryImpl.Dialect.ToBooleanValueString(false);
            string expectedSql =
                "UPDATE test_update_builder SET intColumn = ?, longColumn = ?, literalColumn = " + falseString + ", stringColumn = 5 WHERE decimalColumn = ? AND versionColumn = ? AND a=b";

            Assert.AreEqual(expectedSql, sqlCommand.Text.ToString(), "SQL String");

            SqlType[] actualParameterTypes = sqlCommand.ParameterTypes;
            Assert.AreEqual(4, actualParameterTypes.Length, "Four parameters");

            SqlType[] expectedParameterTypes = new SqlType[]
            {
                SqlTypeFactory.Int32,
                SqlTypeFactory.Int64,
                SqlTypeFactory.Decimal,
                SqlTypeFactory.Int32
            };

            Assert.AreEqual(expectedParameterTypes[0], actualParameterTypes[0], "firstParam Type");
            Assert.AreEqual(expectedParameterTypes[1], actualParameterTypes[1], "secondParam Type");
            Assert.AreEqual(expectedParameterTypes[2], actualParameterTypes[2], "thirdParam Type");
            Assert.AreEqual(expectedParameterTypes[3], actualParameterTypes[3], "fourthParam Type");
        }
Ejemplo n.º 23
0
 private void AggregateQueriesInformation()
 {
     sqlString = new SqlString();
     foreach (AbstractQueryImpl query in queries)
     {
         QueryParameters queryParameters = query.GetQueryParameters();
         queryParameters.ValidateParameters();
         query.VerifyParameters();
         IQueryTranslator[] queryTranslators =
             session.GetQueries(query.ExpandParameterLists(queryParameters.NamedParameters), false);
         foreach (IQueryTranslator translator in queryTranslators)
         {
             translators.Add(translator);
             parameters.Add(queryParameters);
             queryParameters = GetFilteredQueryParameters(queryParameters, translator);
             SqlCommandInfo commandInfo = translator.Loader.GetQueryStringAndTypes(session, queryParameters);
             sqlString = sqlString.Append(commandInfo.Text).Append(session.Factory.ConnectionProvider.Driver.MultipleQueriesSeparator).Append(Environment.NewLine);
             types.AddRange(commandInfo.ParameterTypes);
         }
     }
 }
Ejemplo n.º 24
0
 public object PerformInsert(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder)
 {
     try
     {
         // prepare and execute the insert
         IDbCommand insert = Prepare(insertSQL, session);
         try
         {
             binder.BindValues(insert);
             return(ExecuteAndExtract(insert, session));
         }
         finally
         {
             ReleaseStatement(insert, session);
         }
     }
     catch (DbException sqle)
     {
         throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                          "could not insert: " + persister.GetInfoString(), insertSQL.Text);
     }
 }
Ejemplo n.º 25
0
 public async Task <object> PerformInsertAsync(SqlCommandInfo insertSQL, ISessionImplementor session, IBinder binder, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     try
     {
         // prepare and execute the insert
         var insert = await(PrepareAsync(insertSQL, session, cancellationToken)).ConfigureAwait(false);
         try
         {
             await(binder.BindValuesAsync(insert, cancellationToken)).ConfigureAwait(false);
             return(await(ExecuteAndExtractAsync(insert, session, cancellationToken)).ConfigureAwait(false));
         }
         finally
         {
             ReleaseStatement(insert, session);
         }
     }
     catch (DbException sqle)
     {
         throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                          "could not insert: " + persister.GetInfoString(), insertSQL.Text);
     }
 }
Ejemplo n.º 26
0
        private IEnumerable <TemperatureLogRecord> getTemperatureChartData(SqlCommandText whereClause)
        {
            var data = new List <TemperatureLogRecord>();

            var selectCommand = new SqlCommandInfo("SELECT origin_datetime, temperature FROM TemperatureLog");

            if (!whereClause.IsEmpty)
            {
                selectCommand.CommandText += " WHERE " + whereClause.CommandText;
                selectCommand.AddParameters(whereClause);
            }

            SqlExecutionHelper.ExecuteReader(
                selectCommand,
                row =>
            {
                DateTime datetime   = row.GetDateTime(row.GetOrdinal("origin_datetime"));
                decimal temperature = row.GetDecimal(row.GetOrdinal("temperature"));

                data.Add(new TemperatureLogRecord(datetime, temperature));
            });

            return(data.ToArray());
        }
Ejemplo n.º 27
0
        protected override int DoUpdateRows(object id, IPersistentCollection collection, ISessionImplementor session)
        {
            // we finish all the "removes" first to take care of possible unique
            // constraints and so that we can take better advantage of batching

            try
            {
                int count = 0;
                if (RowDeleteEnabled)
                {
                    bool       useBatch = true;
                    IDbCommand st       = null;
                    // update removed rows fks to null
                    try
                    {
                        int          i           = 0;
                        IEnumerable  entries     = collection.Entries(this);
                        int          offset      = 0;
                        IExpectation expectation = Expectations.None;

                        foreach (object entry in entries)
                        {
                            if (collection.NeedsUpdating(entry, i, ElementType))
                            {
                                // will still be issued when it used to be null
                                if (st == null)
                                {
                                    SqlCommandInfo sql = SqlDeleteRowString;
                                    if (DeleteCallable)
                                    {
                                        expectation = Expectations.AppropriateExpectation(DeleteCheckStyle);
                                        useBatch    = expectation.CanBeBatched;
                                        st          = useBatch
                                                                                        ? session.Batcher.PrepareBatchCommand(SqlDeleteRowString.CommandType, sql.Text,
                                                                                                                              SqlDeleteRowString.ParameterTypes)
                                                                                        : session.Batcher.PrepareCommand(SqlDeleteRowString.CommandType, sql.Text,
                                                                                                                         SqlDeleteRowString.ParameterTypes);
                                        //offset += expectation.prepare(st);
                                    }
                                    else
                                    {
                                        st =
                                            session.Batcher.PrepareBatchCommand(SqlDeleteRowString.CommandType, sql.Text,
                                                                                SqlDeleteRowString.ParameterTypes);
                                    }
                                }

                                int loc = WriteKey(st, id, offset, session);
                                WriteElementToWhere(st, collection.GetSnapshotElement(entry, i), loc, session);
                                if (useBatch)
                                {
                                    session.Batcher.AddToBatch(expectation);
                                }
                                else
                                {
                                    expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                                }
                                count++;
                            }
                            i++;
                        }
                    }
                    catch (Exception e)
                    {
                        if (useBatch)
                        {
                            session.Batcher.AbortBatch(e);
                        }
                        throw;
                    }
                    finally
                    {
                        if (!useBatch && st != null)
                        {
                            session.Batcher.CloseCommand(st, null);
                        }
                    }
                }

                if (RowInsertEnabled)
                {
                    IExpectation expectation = Expectations.AppropriateExpectation(InsertCheckStyle);
                    //bool callable = InsertCallable;
                    bool           useBatch = expectation.CanBeBatched;
                    SqlCommandInfo sql      = SqlInsertRowString;
                    IDbCommand     st       = null;

                    // now update all changed or added rows fks
                    try
                    {
                        int         i       = 0;
                        IEnumerable entries = collection.Entries(this);
                        foreach (object entry in entries)
                        {
                            int offset = 0;
                            if (collection.NeedsUpdating(entry, i, ElementType))
                            {
                                if (useBatch)
                                {
                                    if (st == null)
                                    {
                                        st =
                                            session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, sql.Text,
                                                                                SqlInsertRowString.ParameterTypes);
                                    }
                                }
                                else
                                {
                                    st =
                                        session.Batcher.PrepareCommand(SqlInsertRowString.CommandType, sql.Text, SqlInsertRowString.ParameterTypes);
                                }

                                //offset += expectation.Prepare(st, Factory.ConnectionProvider.Driver);
                                int loc = WriteKey(st, id, offset, session);
                                if (HasIndex && !indexContainsFormula)
                                {
                                    loc = WriteIndexToWhere(st, collection.GetIndex(entry, i, this), loc, session);
                                }
                                WriteElementToWhere(st, collection.GetElement(entry), loc, session);
                                if (useBatch)
                                {
                                    session.Batcher.AddToBatch(expectation);
                                }
                                else
                                {
                                    expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
                                }
                                count++;
                            }
                            i++;
                        }
                    }
                    catch (Exception e)
                    {
                        if (useBatch)
                        {
                            session.Batcher.AbortBatch(e);
                        }
                        throw;
                    }
                    finally
                    {
                        if (st != null)
                        {
                            session.Batcher.CloseCommand(st, null);
                        }
                    }
                }
                return(count);
            }
            catch (DbException sqle)
            {
                throw ADOExceptionHelper.Convert(SQLExceptionConverter, sqle,
                                                 "could not update collection rows: " + MessageHelper.InfoString(this, id));
            }
        }
        public object PerformInsert(SqlCommandInfo insertSql, ISessionImplementor session, IBinder binder)
        {
            // NH-2145: Prevent connection releases between insert and select when we cannot perform
            // them as a single statement. Retrieving id most of the time relies on using the same connection.
            session.ConnectionManager.FlushBeginning();
            try
            {
                try
                {
                    // prepare and execute the insert
                    var insert = session.Batcher.PrepareCommand(insertSql.CommandType, insertSql.Text, insertSql.ParameterTypes);
                    try
                    {
                        binder.BindValues(insert);
                        session.Batcher.ExecuteNonQuery(insert);
                    }
                    finally
                    {
                        session.Batcher.CloseCommand(insert, null);
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                     "could not insert: " + persister.GetInfoString(), insertSql.Text);
                }

                var selectSql = SelectSQL;
                using (session.BeginProcess())
                {
                    try
                    {
                        //fetch the generated id in a separate query
                        var idSelect = session.Batcher.PrepareCommand(CommandType.Text, selectSql, ParametersTypes);
                        try
                        {
                            BindParameters(session, idSelect, binder);
                            var rs = session.Batcher.ExecuteReader(idSelect);
                            try
                            {
                                return(GetResult(session, rs, binder.Entity));
                            }
                            finally
                            {
                                session.Batcher.CloseReader(rs);
                            }
                        }
                        finally
                        {
                            session.Batcher.CloseCommand(idSelect, null);
                        }
                    }
                    catch (DbException sqle)
                    {
                        throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                         "could not retrieve generated id after insert: " + persister.GetInfoString(),
                                                         insertSql.Text);
                    }
                }
            }
            finally
            {
                session.ConnectionManager.FlushEnding();
            }
        }
        public async Task <object> PerformInsertAsync(SqlCommandInfo insertSql, ISessionImplementor session, IBinder binder, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            // NH-2145: Prevent connection releases between insert and select when we cannot perform
            // them as a single statement. Retrieving id most of the time relies on using the same connection.
            session.ConnectionManager.FlushBeginning();
            try
            {
                try
                {
                    // prepare and execute the insert
                    var insert = await(session.Batcher.PrepareCommandAsync(insertSql.CommandType, insertSql.Text, insertSql.ParameterTypes, cancellationToken)).ConfigureAwait(false);
                    try
                    {
                        await(binder.BindValuesAsync(insert, cancellationToken)).ConfigureAwait(false);
                        await(session.Batcher.ExecuteNonQueryAsync(insert, cancellationToken)).ConfigureAwait(false);
                    }
                    finally
                    {
                        session.Batcher.CloseCommand(insert, null);
                    }
                }
                catch (DbException sqle)
                {
                    throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                     "could not insert: " + persister.GetInfoString(), insertSql.Text);
                }

                var selectSql = SelectSQL;
                using (new SessionIdLoggingContext(session.SessionId))
                {
                    try
                    {
                        //fetch the generated id in a separate query
                        var idSelect = await(session.Batcher.PrepareCommandAsync(CommandType.Text, selectSql, ParametersTypes, cancellationToken)).ConfigureAwait(false);
                        try
                        {
                            await(BindParametersAsync(session, idSelect, binder.Entity, cancellationToken)).ConfigureAwait(false);
                            var rs = await(session.Batcher.ExecuteReaderAsync(idSelect, cancellationToken)).ConfigureAwait(false);
                            try
                            {
                                return(await(GetResultAsync(session, rs, binder.Entity, cancellationToken)).ConfigureAwait(false));
                            }
                            finally
                            {
                                session.Batcher.CloseReader(rs);
                            }
                        }
                        finally
                        {
                            session.Batcher.CloseCommand(idSelect, null);
                        }
                    }
                    catch (DbException sqle)
                    {
                        throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle,
                                                         "could not retrieve generated id after insert: " + persister.GetInfoString(),
                                                         insertSql.Text);
                    }
                }
            }
            finally
            {
                session.ConnectionManager.FlushEnding();
            }
        }
 protected internal override DbCommand Prepare(SqlCommandInfo insertSQL, ISessionImplementor session)
 {
     return(session.Batcher.PrepareCommand(CommandType.Text, insertSQL.Text, insertSQL.ParameterTypes));
 }