Ejemplo n.º 1
0
        protected string GetProcName(SqlStatementType statementType)
        {
            switch (statementType)
            {
            case SqlStatementType.Select:
                return(string.Format(FetchCommandFormat, SourceTable.Name));

            case SqlStatementType.SelectBy:
                if (ParentTable == null)
                {
                    throw new InvalidOperationException("ParentTable must be specified for SelectBy procs.");
                }
                return(string.Format(FetchByCommandFormat, SourceTable.Name, ParentTable.Name));

            case SqlStatementType.Insert:
                return(string.Format(InsertCommandFormat, SourceTable.Name));

            case SqlStatementType.Update:
                return(string.Format(UpdateCommandFormat, SourceTable.Name));

            case SqlStatementType.Delete:
                return(string.Format(DeleteCommandFormat, SourceTable.Name));

            default:
                throw new ArgumentOutOfRangeException("statementType", statementType.ToString(), "No command format has been defined for this SqlStatementType");
            }
        }
		public CommandExecutedEventArgs(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
		{
			DataReader = dataReader;
			CommandText = commandText;
			StatementType = statementType;
			RowsAffected = rowsAffected;
		}
Ejemplo n.º 3
0
 /// <summary>
 /// Create new Store proc parameter.
 /// </summary>
 /// <param name="paramName">Sql parameter name.</param>
 /// <param name="paramType"><see cref="SqlDbType"/> parameter type.</param>
 /// <param name="size"><see cref="Int32"/> sql parameter size - use with string.</param>
 /// <param name="usedFor">Array of <see cref="SqlStatementType"/> values to determine the SP usage.</param>
 internal StoredProcParameter(string paramName,
     SqlDbType paramType,
     int size,
     SqlStatementType[] usedFor)
     : this(new SqlParameter(paramName, paramType, size), usedFor)
 {
 }
Ejemplo n.º 4
0
 public CommandExecutedEventArgs(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
 {
     DataReader    = dataReader;
     CommandText   = commandText;
     StatementType = statementType;
     RowsAffected  = rowsAffected;
 }
Ejemplo n.º 5
0
        protected string GetTableTimeStampSelect(SqlStatementType statementType, int indentLevel)
        {
            StringBuilder select = new StringBuilder(Indent(indentLevel, true));

            select.Append(SelectStatementTemplate);
            select.Replace("[SELECTCOLUMNS]", string.Format("SELECT @New{0} = {0}", TimeStampColumn));
            select.Replace("[FROM]", string.Format("FROM {0}", SourceTable.Name));

            string parameterName;

            StringBuilder where = new StringBuilder("WHERE ");
            foreach (ColumnSchema column in SourceTable.PrimaryKey.MemberColumns)
            {
                if (SourceTable.PrimaryKey.MemberColumns.IndexOf(column) > 0)
                {
                    where.Append(" AND ");
                }

                if (statementType == SqlStatementType.Insert && IsIdentity(column))
                {
                    parameterName = string.Format("@New{0}", column.Name);
                }
                else
                {
                    parameterName = string.Format("@{0}", column.Name);
                }
                where.Append(string.Format("{0} = {1}", column.Name, parameterName));
            }

            select.Replace("[WHERE]", where.ToString());

            return(select.ToString());
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Create new Store proc parameter.
 /// </summary>
 /// <param name="paramName">Sql parameter name.</param>
 /// <param name="paramType"><see cref="SqlDbType"/> parameter type.</param>
 /// <param name="paramSize"><see cref="Int32"/> sql parameter size - use with string.</param>
 /// <param name="usedFor1">Identifies the purpose of the parameter.</param>
 internal StoredProcParameter(string paramName,
     SqlDbType paramType,
     int paramSize,
     SqlStatementType usedFor1)
     : this(paramName, paramType, paramSize, new[] {usedFor1})
 {
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets the corresponding <see cref="SqlStatementType"/> for a SQL statement.
        /// </summary>
        /// <param name="sqlStatement">The SQL statement.</param>
        /// <returns>Type of operation done against the database server by the given statement.</returns>
        public static SqlStatementType GetSqlStatementType(string sqlStatement)
        {
            if (string.IsNullOrEmpty(sqlStatement))
            {
                return(SqlStatementType.None);
            }

            SqlStatementType statementType = SqlStatementType.Other;

            sqlStatement = sqlStatement.TrimStart().ToUpperInvariant();
            if (sqlStatement.StartsWith(STATEMENT_UPDATE))
            {
                statementType = SqlStatementType.Update;
            }
            else if (sqlStatement.StartsWith(STATEMENT_INSERT))
            {
                statementType = SqlStatementType.Insert;
            }
            else if (sqlStatement.StartsWith(STATEMENT_DELETE))
            {
                statementType = SqlStatementType.Delete;
            }
            else if (sqlStatement.StartsWith(STATEMENT_SET_GLOBAL))
            {
                statementType = SqlStatementType.SetGlobal;
            }
            else if (sqlStatement.StartsWith(STATEMENT_SET))
            {
                statementType = SqlStatementType.Set;
            }
            else if (sqlStatement.StartsWith(STATEMENT_CREATE_TABLE))
            {
                statementType = SqlStatementType.CreateTable;
            }
            else if (sqlStatement.StartsWith(STATEMENT_CREATE_SCHEMA))
            {
                statementType = SqlStatementType.CreateSchema;
            }
            else if (sqlStatement.StartsWith(STATEMENT_ALTER_TABLE))
            {
                statementType = SqlStatementType.AlterTable;
            }
            else if (sqlStatement.StartsWith(STATEMENT_LOCK_TABLES))
            {
                statementType = SqlStatementType.LockTables;
            }
            else if (sqlStatement.StartsWith(STATEMENT_UNLOCK_TABLES))
            {
                statementType = SqlStatementType.UnlockTables;
            }
            else if (sqlStatement.StartsWith(STATEMENT_GRANT_ALL))
            {
                statementType = SqlStatementType.GrantAll;
            }

            return(statementType);
        }
Ejemplo n.º 8
0
        // logging ////////////////////////////////////////////////

        protected internal virtual void logStatement(SqlStatementType type, object parameters, string statement, long duration)
        {
            IList <SqlStatementLog> log = threadStatementLog.get();

            if (log != null)
            {
                log.Add(new SqlStatementLog(type, parameters, statement, duration));
            }
        }
Ejemplo n.º 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") protected void processResults(org.camunda.bpm.qa.performance.engine.framework.PerfTestResults results, TabularResultSet tabularResultSet)
        protected internal override void processResults(PerfTestResults results, TabularResultSet tabularResultSet)
        {
            List <object> row = new List <object>();

            row.Add(results.TestName);

            int insertCount = 0;
            int deleteCount = 0;
            int updateCount = 0;
            int selectCount = 0;

            if (results.PassResults.Count == 0)
            {
                return;
            }

            IList <PerfTestStepResult> stepResults = results.PassResults[0].StepResults;

            foreach (PerfTestStepResult stepResult in stepResults)
            {
                IList <LinkedHashMap <string, string> > statementLogs = (IList <LinkedHashMap <string, string> >)stepResult.ResultData;
                foreach (LinkedHashMap <string, string> statementLog in statementLogs)
                {
                    string           type          = statementLog.get("statementType");
                    SqlStatementType statementType = Enum.Parse(typeof(SqlStatementType), type);

                    switch (statementType)
                    {
                    case SqlStatementType.DELETE:
                        deleteCount++;
                        break;

                    case SqlStatementType.INSERT:
                        insertCount++;
                        break;

                    case SqlStatementType.UPDATE:
                        updateCount++;
                        break;

                    default:
                        selectCount++;
                        break;
                    }
                }
            }

            row.Add(insertCount);
            row.Add(deleteCount);
            row.Add(updateCount);
            row.Add(selectCount);

            tabularResultSet.addResultRow(row);
        }
Ejemplo n.º 10
0
        protected string GetProcCreateStatement(string procName, SqlStatementType statementType,
                                                int indentLevel)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Indent(indentLevel, true));
            sb.Append("CREATE PROCEDURE ");
            sb.Append(procName);
            sb.Append(Indent(indentLevel++, true));
            sb.Append("(");

            ColumnSchemaCollection columns;
            bool ignoreAutoSetColumns = true;

            switch (statementType)
            {
            case SqlStatementType.Insert:
            case SqlStatementType.Update:
                columns = SourceTable.Columns;
                ignoreAutoSetColumns = false;
                break;

            case SqlStatementType.SelectBy:
                CheckForPrimaryKey(ParentTable);
                columns = ParentTable.PrimaryKey.MemberColumns;
                break;

            default:
                CheckForPrimaryKey(SourceTable);
                columns = SourceTable.PrimaryKey.MemberColumns;
                break;
            }

            for (int i = 0; i < columns.Count; i++)
            {
                sb.Append(Indent(indentLevel, true));
                sb.Append(GetSqlParameterStatement(columns[i], statementType));
                if (IsCommaNecessary(columns, i, ignoreAutoSetColumns))
                {
                    sb.Append(",");
                }
            }

            sb.Append(Indent(--indentLevel, true));
            sb.Append(")");
            sb.Append(Indent(indentLevel++, true));
            sb.Append("AS");
            sb.Append(GetSqlStatement(statementType, indentLevel));
            sb.Append(Indent(--indentLevel, true));
            sb.Append("GO");

            return(sb.ToString());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 根据类型构造SQL语句
        /// </summary>
        /// <param name="sqlStatementType">SQL语句类型</param>
        /// <param name="dbType">数据库类型</param>
        /// <returns>SQL语句</returns>
        public static SqlStatement CreateSqlStatement(SqlStatementType sqlStatementType, DbType dbType)
        {
            switch (sqlStatementType)
            {
            case SqlStatementType.Select:
                switch (dbType)
                {
                case DbType.SQLServer:
                    return(new SelectSqlStaForMSS());

                case DbType.Oracle:
                    return(new SelectSqlStaForORA());

                default:
                    return(new SelectSqlStatement());
                }

            case SqlStatementType.Insert:
            {
                switch (dbType)
                {
                case DbType.SQLServer:
                    return(new InsertSqlStaMSS());

                case DbType.Oracle:
                    return(new InsertSqlStaORA());

                default:
                    return(new InsertSqlStaMSS());
                }
            }

            case SqlStatementType.Delete:
                return(new DeleteSqlStatement());

            case SqlStatementType.Update:
                switch (dbType)
                {
                case DbType.SQLServer:
                    return(new UpdateSqlStaForMSS());

                case DbType.Oracle:
                    return(new UpdateSqlStaForORA());

                default:
                    return(new UpdateSqlStatement());
                }

            default:
                return(null);
            }
        }
Ejemplo n.º 12
0
 public SqlStatementLog(SqlStatementType type, object parameters, string statement, long duration)
 {
     statementType   = type;
     this.statement  = statement;
     this.durationMs = duration;
     try
     {
         statementParameters = JsonUtil.Mapper.writeValueAsString(parameters).replaceAll("\"", "'");
     }
     catch (Exception)
     {
         //        e.printStackTrace();
     }
 }
		public string GetProcDeclaration(SqlStatementType statementType, int indentLevel)
		{
			string procName = GetProcName(statementType);
			StringBuilder sb = new StringBuilder(GetProcDropStatement(procName, indentLevel));
			
			sb.Append(Indent(indentLevel, true));
			sb.Append(GetProcCreateStatement(procName, statementType, indentLevel));

			if(ExecuteRoles.Count > 0) {
				sb.Append(Indent(indentLevel, true));
				foreach(string role in ExecuteRoles) {
					sb.Append(GetProcGrantExecuteStatement(procName, role, indentLevel));
				}
				sb.Append(Indent(indentLevel, true));
				sb.Append("GO");
			}
			
			return sb.ToString();
		}
Ejemplo n.º 14
0
        public string GetProcDeclaration(SqlStatementType statementType, int indentLevel)
        {
            string        procName = GetProcName(statementType);
            StringBuilder sb       = new StringBuilder(GetProcDropStatement(procName, indentLevel));

            sb.Append(Indent(indentLevel, true));
            sb.Append(GetProcCreateStatement(procName, statementType, indentLevel));

            if (ExecuteRoles.Count > 0)
            {
                sb.Append(Indent(indentLevel, true));
                foreach (string role in ExecuteRoles)
                {
                    sb.Append(GetProcGrantExecuteStatement(procName, role, indentLevel));
                }
                sb.Append(Indent(indentLevel, true));
                sb.Append("GO");
            }

            return(sb.ToString());
        }
Ejemplo n.º 15
0
        public string GetSqlParameterStatement(ColumnSchema column, SqlStatementType statementType)
        {
            bool isOutput = false;

            if (statementType == SqlStatementType.Insert || statementType == SqlStatementType.Update)
            {
                isOutput = string.Compare(column.Name, TimeStampColumn, true) == 0;
            }
            if (!isOutput && statementType == SqlStatementType.Insert)
            {
                isOutput = IsIdentity(column);
            }
            string parameterStatement = GetSqlParameterStatement(column, isOutput);

            if (isOutput)
            {
                parameterStatement = parameterStatement.Replace("@", "@New");
            }

            return(parameterStatement);
        }
Ejemplo n.º 16
0
        protected string GetSqlStatement(SqlStatementType statementType, int indentLevel)
        {
            switch (statementType)
            {
            case SqlStatementType.Select:
                return(this.GetSelectStatement(false, indentLevel));

            case SqlStatementType.SelectBy:
                return(this.GetSelectStatement(true, indentLevel));

            case SqlStatementType.Insert:
                return(GetInsertStatement(indentLevel));

            case SqlStatementType.Update:
                return(GetUpdateStatement(indentLevel));

            case SqlStatementType.Delete:
                return(GetDeleteStatement(indentLevel));

            default:
                throw new ArgumentOutOfRangeException("statementType", statementType.ToString(), "No statement template has been defined for this SqlStatementType");
            }
        }
		public string GetProcDeclaration(SqlStatementType statementType)
		{
			return GetProcDeclaration(statementType, 0);
		}
Ejemplo n.º 18
0
        private static List <Statement> GetDefaultSqlStatement(String logicDbName, IShardingStrategy shardingStrategy,
                                                               String sql, StatementParameterCollection parameters, IDictionary hints, SqlStatementType sqlType, OperationType?operationType = null)
        {
            if (String.IsNullOrEmpty(logicDbName))
            {
                throw new DalException("Please specify databaseSet.");
            }
            if (String.IsNullOrEmpty(sql))
            {
                throw new DalException("Please specify sql.");
            }

            var result    = new List <Statement>();
            var tupleList = ShardingUtil.GetShardInfo(logicDbName, shardingStrategy, parameters, hints);

            if (tupleList.Count < 1)
            {
                //非sharding的场合
                Statement statement = GetStatement(logicDbName, StatementType.Sql,
                                                   operationType ?? OperationType.Default, sqlType, hints, null);
                statement.StatementText = GetSql(sql, null);
                statement.Parameters    = parameters;
#if !NETSTANDARD
                CurrentStackCustomizedLog(statement);
#endif
                result.Add(statement);
            }
            else
            {
                var bulkCopy = false;
                if (hints != null && hints.Contains(DALExtStatementConstant.BULK_COPY))//查看是否是批量插入的case
                {
                    bulkCopy = Convert.ToBoolean(hints[DALExtStatementConstant.BULK_COPY]);
                }

                if (bulkCopy)
                {
                    result.AddRange(BulkCopyCase(logicDbName, shardingStrategy, sql, parameters, hints, tupleList, sqlType, operationType));
                }
                else
                {
                    foreach (var tuple in tupleList)
                    {
                        Statement statement = GetStatement(logicDbName, StatementType.Sql, operationType ?? OperationType.Default, sqlType, hints, tuple.Item1);
                        statement.StatementText = GetSql(sql, tuple.Item2);
                        statement.Parameters    = parameters;
#if !NETSTANDARD
                        CurrentStackCustomizedLog(statement);
#endif
                        result.Add(statement);
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Create new Stored proc parameter.
 /// </summary>
 /// <param name="paramName">Sql parameter name.</param>
 /// <param name="paramType"><see cref="SqlDbType"/> parameter type.</param>
 /// <param name="usedFor">Identifies the purpose of the parameter.</param>
 private StoredProcParameter(string paramName, SqlDbType paramType, SqlStatementType[] usedFor)
     : this(new SqlParameter(paramName, paramType), usedFor)
 {
 }
		internal void SetStatementType(SqlStatementType statementType)
		{
			StatementType = statementType;
		}
Ejemplo n.º 21
0
        //private static IDictionary<String, IList<T>> ShuffledByDb<T>(String logicDbName, IShardingStrategy shardingStrategy, StatementParameterCollection parameters,
        //    IList<T> list, IDictionary hints)
        //{
        //    if (String.IsNullOrEmpty(logicDbName))
        //        return null;
        //    if (list == null || list.Count == 0)
        //        return null;
        //    var dict = new Dictionary<String, IList<T>>();

        //    foreach (var item in list)
        //    {
        //        String shardId = GetShardId(logicDbName, shardingStrategy, parameters, hints);
        //        if (String.IsNullOrEmpty(shardId))
        //            continue;

        //        if (!dict.ContainsKey(shardId))
        //            dict.Add(shardId, new List<T>());
        //        dict[shardId].Add(item);
        //    }

        //    return dict;
        //}

        //private static IDictionary<String, IList<T>> ShuffledByTable<T>(String logicDbName, IShardingStrategy shardingStrategy, StatementParameterCollection parameters,
        //    IList<T> list,IDictionary hints)
        //{
        //    if (String.IsNullOrEmpty(logicDbName))
        //        return null;
        //    if (list == null || list.Count == 0)
        //        return null;
        //    var dict = new Dictionary<String, IList<T>>();

        //    foreach (var item in list)
        //    {
        //        String tableId = GetTableId(logicDbName, shardingStrategy, parameters, hints);
        //        if (String.IsNullOrEmpty(tableId))
        //            continue;

        //        if (!dict.ContainsKey(tableId))
        //            dict.Add(tableId, new List<T>());
        //        dict[tableId].Add(item);
        //    }

        //    return dict;
        //}

        //private static IDictionary<String, IDictionary<String, IList<T>>> ShuffledByDbTable<T>(String logicDbName, IShardingStrategy shardingStrategy, StatementParameterCollection parameters,
        //    IList<T> list, IDictionary hints)
        //{
        //    if (String.IsNullOrEmpty(logicDbName))
        //        return null;
        //    if (list == null || list.Count == 0)
        //        return null;

        //    var dict = new Dictionary<String, IDictionary<String, IList<T>>>();

        //    foreach (var item in list)
        //    {
        //        String shardId = GetShardId(logicDbName, shardingStrategy, parameters, hints);
        //        String tableId = GetTableId(logicDbName, shardingStrategy , parameters,hints);

        //        if (!dict.ContainsKey(shardId))
        //            dict.Add(shardId, new Dictionary<String, IList<T>>());
        //        if (!dict[shardId].ContainsKey(tableId))
        //            dict[shardId].Add(tableId, new List<T>());
        //        dict[shardId][tableId].Add(item);
        //    }

        //    return dict;
        //}

        #endregion Shuffled Items

        public static IList <Statement> GetShardStatement(String logicDbName, IShardingStrategy shardingStrategy,
                                                          StatementParameterCollection parameters, IDictionary hints, Func <IDictionary, List <Statement> > func, SqlStatementType sqlStatementType)
        {
            IList <Statement> statements;

            if (shardingStrategy == null)
            {
                return(null);
            }
            var shardingType = GetShardingType(shardingStrategy);

            if (shardingType != ShardingType.ShardByDBAndTable)
            {
                IList <String> shards = null;

                //Get shards from hints
                if (hints != null)
                {
                    IList <String> temp = null;

                    if (shardingType == ShardingType.ShardByDB)                //是分库的情况
                    {
                        if (hints.Contains(DALExtStatementConstant.SHARD_IDS)) //看下hints里面有没有指定分配id(一组)
                        {
                            temp = hints[DALExtStatementConstant.SHARD_IDS] as List <String>;
                        }
                        else if (hints.Contains(DALExtStatementConstant.SHARDID))//单个的分配id
                        {
                            temp = new List <String> {
                                hints[DALExtStatementConstant.SHARDID] as String
                            };
                        }
                    }
                    else if (shardingType == ShardingType.ShardByTable)//是分表的情况
                    {
                        if (hints.Contains(DALExtStatementConstant.TABLE_IDS))
                        {
                            temp = hints[DALExtStatementConstant.TABLE_IDS] as List <String>;
                        }
                        else if (hints.Contains(DALExtStatementConstant.TABLEID))
                        {
                            temp = new List <String> {
                                hints[DALExtStatementConstant.TABLEID] as String
                            };
                        }
                    }

                    if (temp != null)
                    {
                        shards = temp;
                    }
                }


                var bulkCopy = false;
                if (hints != null && hints.Contains(DALExtStatementConstant.BULK_COPY))//查看是否是批量插入的case
                {
                    bulkCopy = Convert.ToBoolean(hints[DALExtStatementConstant.BULK_COPY]);
                }

                if (bulkCopy)
                {
                    return(func.Invoke(hints));
                }
                //Get shards from parameters 这里会根据 查询参数得出分配的信息
                if (shards == null)
                {
                    if (shardingType == ShardingType.ShardByDB)
                    {
                        shards = GetShardId(logicDbName, shardingStrategy, parameters, hints);
                    }
                    else if (shardingType == ShardingType.ShardByTable)
                    {
                        shards = GetTableId(logicDbName, shardingStrategy, parameters, hints);
                    }
                }

                //对于不带条件的查询 都默认查询所有的
                if ((shards == null || shards.Count == 0) && sqlStatementType.Equals(SqlStatementType.SELECT))
                {
                    shards = shardingStrategy.AllShards;
                }

                if (shards == null || shards.Count == 0)
                {
                    throw new DalException("Please provide shard information.");
                }

                //Build statements
                statements = new List <Statement>();

                foreach (var item in shards.Distinct())
                {
                    var newHints = HintsUtil.CloneHints(hints);

                    switch (shardingType)
                    {
                    case ShardingType.ShardByDB:
                        newHints[DALExtStatementConstant.SHARDID] = item;
                        break;

                    case ShardingType.ShardByTable:
                        newHints[DALExtStatementConstant.TABLEID] = item;
                        break;
                    }

                    var statement = func.Invoke(newHints);
                    foreach (var ss in statement)
                    {
                        statements.Add(ss);
                    }
                }
            }
            else
            {
                statements = new List <Statement>();
                IDictionary <String, IList <String> > shardDict = null;
                if (hints != null && hints.Contains(DALExtStatementConstant.SHARD_TABLE_DICT))
                {
                    shardDict = hints[DALExtStatementConstant.SHARD_TABLE_DICT] as IDictionary <String, IList <String> >;
                }

                if (shardDict == null)
                {
                    var newHints = HintsUtil.CloneHints(hints);
                    newHints[DALExtStatementConstant.SHARDID] = GetShardIdByHints(hints);
                    newHints[DALExtStatementConstant.TABLEID] = GetTableIdByHints(hints);
                    var statement = func.Invoke(newHints);
                    foreach (var ss in statement)
                    {
                        statements.Add(ss);
                    }
                }
                else
                {
                    foreach (var shard in shardDict)
                    {
                        foreach (var table in shard.Value)
                        {
                            var newHints = HintsUtil.CloneHints(hints);
                            newHints[DALExtStatementConstant.SHARDID] = shard.Key;
                            newHints[DALExtStatementConstant.TABLEID] = table;
                            var statement = func.Invoke(newHints);
                            foreach (var ss in statement)
                            {
                                statements.Add(ss);
                            }
                        }
                    }
                }
            }

            return(statements);
        }
Ejemplo n.º 22
0
 public CommandExecutingEventArgs(FbCommand sqlCommand, SqlStatementType statementType)
 {
     SqlCommand    = sqlCommand;
     StatementType = statementType;
 }
		public CommandExecutingEventArgs(FbCommand sqlCommand, SqlStatementType statementType)
		{
			SqlCommand = sqlCommand;
			StatementType = statementType;
		}
Ejemplo n.º 24
0
 /// <summary>
 /// The trigger function for <see cref="CommandExecuted"/> event.
 /// </summary>
 /// <param name="commandText">The <see cref="FbCommand.CommandText"/> of the executed SQL command.</param>
 /// <param name="dataReader">The <see cref="FbDataReader"/> instance with the returned data. If the
 /// command executed is not meant to return data (ex: UPDATE, INSERT...) this parameter must be
 /// setled to <b>null</b>.</param>
 /// <param name="rowsAffected">The rows that were affected by the executed SQL command. If the executed
 /// command is not meant to return this kind of information (ex: SELECT) this parameter must
 /// be setled to <b>-1</b>.</param>
 private void OnCommandExecuted(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
 {
     CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(dataReader, commandText, statementType, rowsAffected));
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Starts the ordered execution of the SQL statements that are in <see cref="SqlStatements"/> collection.
        /// </summary>
        /// <param name="autoCommit">Specifies if the transaction should be committed after a DDL command execution</param>
        public void Execute(bool autoCommit = true)
        {
            if (this.SqlStatements == null || this.SqlStatements.Count == 0)
            {
                throw new InvalidOperationException("There are no commands for execution.");
            }

            foreach (string sqlStatement in this.SqlStatements)
            {
                if (string.IsNullOrEmpty(sqlStatement))
                {
                    continue;
                }

                // initializate outputs to default
                int              rowsAffected  = -1;
                FbDataReader     dataReader    = null;
                SqlStatementType statementType = FbBatchExecution.GetStatementType(sqlStatement);

                if (!(statementType == SqlStatementType.Connect ||
                      statementType == SqlStatementType.CreateDatabase ||
                      statementType == SqlStatementType.Disconnect ||
                      statementType == SqlStatementType.DropDatabase ||
                      statementType == SqlStatementType.SetAutoDDL ||
                      statementType == SqlStatementType.SetDatabase ||
                      statementType == SqlStatementType.SetNames ||
                      statementType == SqlStatementType.SetSQLDialect))
                {
                    this.ProvideCommand();
                    this.sqlCommand.CommandText = sqlStatement;
                    if (this.sqlTransaction == null && !(statementType == SqlStatementType.Commit || statementType == SqlStatementType.Rollback))
                    {
                        this.sqlTransaction = this.sqlConnection.BeginTransaction();
                    }
                    this.sqlCommand.Transaction = this.sqlTransaction;
                }

                try
                {
                    switch (statementType)
                    {
                    case SqlStatementType.AlterDatabase:
                    case SqlStatementType.AlterDomain:
                    case SqlStatementType.AlterException:
                    case SqlStatementType.AlterIndex:
                    case SqlStatementType.AlterProcedure:
                    case SqlStatementType.AlterRole:
                    case SqlStatementType.AlterTable:
                    case SqlStatementType.AlterTrigger:
                    case SqlStatementType.AlterView:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Commit:
                        this.OnCommandExecuting(null);

                        this.CommitTransaction();

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.Connect:
                        this.OnCommandExecuting(null);

                        this.ConnectToDatabase(sqlStatement);

                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.CreateDatabase:
                        this.OnCommandExecuting(null);

                        this.CreateDatabase(sqlStatement);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.CommentOn:
                    case SqlStatementType.CreateCollation:
                    case SqlStatementType.CreateDomain:
                    case SqlStatementType.CreateException:
                    case SqlStatementType.CreateGenerator:
                    case SqlStatementType.CreateIndex:
                    case SqlStatementType.CreateProcedure:
                    case SqlStatementType.CreateRole:
                    case SqlStatementType.CreateSequence:
                    case SqlStatementType.CreateShadow:
                    case SqlStatementType.CreateTable:
                    case SqlStatementType.CreateTrigger:
                    case SqlStatementType.CreateView:
                    case SqlStatementType.DeclareCursor:
                    case SqlStatementType.DeclareExternalFunction:
                    case SqlStatementType.DeclareFilter:
                    case SqlStatementType.DeclareStatement:
                    case SqlStatementType.DeclareTable:
                    case SqlStatementType.Delete:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Describe:
                        break;

                    case SqlStatementType.Disconnect:
                        this.OnCommandExecuting(null);

                        this.sqlConnection.Close();
                        FbConnection.ClearPool(this.sqlConnection);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.DropDatabase:
                        this.OnCommandExecuting(null);

                        FbConnection.DropDatabase(this.connectionString.ToString());
                        this.requiresNewConnection = true;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.DropCollation:
                    case SqlStatementType.DropDomain:
                    case SqlStatementType.DropException:
                    case SqlStatementType.DropExternalFunction:
                    case SqlStatementType.DropFilter:
                    case SqlStatementType.DropGenerator:
                    case SqlStatementType.DropIndex:
                    case SqlStatementType.DropProcedure:
                    case SqlStatementType.DropSequence:
                    case SqlStatementType.DropRole:
                    case SqlStatementType.DropShadow:
                    case SqlStatementType.DropTable:
                    case SqlStatementType.DropTrigger:
                    case SqlStatementType.DropView:
                    case SqlStatementType.EventInit:
                    case SqlStatementType.EventWait:
                    case SqlStatementType.Execute:
                    case SqlStatementType.ExecuteImmediate:
                    case SqlStatementType.ExecuteProcedure:
                        this.ProvideCommand().CommandText = sqlStatement;

                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.ExecuteBlock:
                        this.ProvideCommand().CommandText = sqlStatement;

                        this.OnCommandExecuting(this.sqlCommand);

                        dataReader = this.sqlCommand.ExecuteReader();
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, dataReader, -1);
                        if (!dataReader.IsClosed)
                        {
                            dataReader.Close();
                        }
                        break;

                    case SqlStatementType.Fetch:
                        break;

                    case SqlStatementType.Grant:
                    case SqlStatementType.Insert:
                    case SqlStatementType.InsertCursor:
                    case SqlStatementType.Open:
                    case SqlStatementType.Prepare:
                    case SqlStatementType.Revoke:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.RecreateProcedure:
                    case SqlStatementType.RecreateTable:
                    case SqlStatementType.RecreateTrigger:
                    case SqlStatementType.RecreateView:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Rollback:
                        this.OnCommandExecuting(null);

                        this.RollbackTransaction();

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.Select:
                        this.ProvideCommand().CommandText = sqlStatement;

                        this.OnCommandExecuting(this.sqlCommand);

                        dataReader = this.sqlCommand.ExecuteReader();
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, dataReader, -1);
                        if (!dataReader.IsClosed)
                        {
                            dataReader.Close();
                        }
                        break;

                    case SqlStatementType.SetAutoDDL:
                        this.OnCommandExecuting(null);

                        this.SetAutoDdl(sqlStatement, ref autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.SetGenerator:
                    case SqlStatementType.AlterSequence:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.SetNames:
                        this.OnCommandExecuting(null);

                        this.SetNames(sqlStatement);
                        this.requiresNewConnection = true;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.SetSQLDialect:
                        this.OnCommandExecuting(null);

                        this.SetSqlDialect(sqlStatement);
                        this.requiresNewConnection = true;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.SetDatabase:
                    case SqlStatementType.SetStatistics:
                    case SqlStatementType.SetTransaction:
                    case SqlStatementType.ShowSQLDialect:
                        throw new NotImplementedException();

                    case SqlStatementType.Update:
                    case SqlStatementType.Whenever:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    this.RollbackTransaction();

                    throw new FbException(string.Format("An exception was thrown when executing command: {1}.{0}Batch execution aborted.{0}The returned message was: {2}.",
                                                        Environment.NewLine,
                                                        sqlStatement,
                                                        ex.Message));
                }
            }

            this.CommitTransaction();

            this.sqlConnection.Close();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 批量插入分片规则: 解析sqlstring 按照分片进行分组 在重新组合 如果没有找到分片的默认第一个分片
        /// </summary>
        /// <param name="logicDbName"></param>
        /// <param name="shardingStrategy"></param>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="hints"></param>
        /// <param name="tupleList"></param>
        /// <param name="sqlType"></param>
        /// <param name="operationType"></param>
        /// <returns></returns>
        private static List <Statement> BulkCopyCase(String logicDbName, IShardingStrategy shardingStrategy,
                                                     String sql, StatementParameterCollection parameters, IDictionary hints, List <Tuple <String, String> > tupleList, SqlStatementType sqlType, OperationType?operationType = null)
        {
            var result = new List <Statement>();


            //var shardingDB = tuple.Item1;
            //var sharingTable = tuple.Item2;
            if (shardingStrategy.ShardByDB && shardingStrategy.ShardByTable)
            {
                //又分表又分库的情况
            }
            else if (shardingStrategy.ShardByDB || shardingStrategy.ShardByTable)
            {
                var dicValues = new Dictionary <string, Tuple <List <string>, StatementParameterCollection> >();
                foreach (var tuple in tupleList)
                {
                    dicValues.Add(shardingStrategy.ShardByDB?tuple.Item1: tuple.Item2, Tuple.Create(new List <string>(), new StatementParameterCollection()));
                }
                var defaultSharding = dicValues.Keys.First();
                //分库的情况
                var arr = sql.Split(new string[] { "VALUES" }, StringSplitOptions.None);
                if (arr.Length != 2)
                {
                    throw new DalException("sharding db for bulkInsert sql string err.");
                }
                var title       = arr[0] + " VALUES ";
                var body        = arr[1].Replace("\r\n", "");
                var values      = body.Split(')').Where(r => !string.IsNullOrEmpty(r)).Select(r => r.StartsWith(",")?r.Substring(1):r).ToArray(); //总共有多少行
                var first       = values.First();
                var cloumnCount = first.Split(',').Length;                                                                                        //每行总共有多少列

                if (parameters.Count != (cloumnCount * values.Length))
                {
                    throw new DalException("sharding db for bulkInsert sql parameters counts err.");
                }
                var ii = 0;
                //将parameters 按 分库进行分组
                for (int i = 0; i < values.Length; i++)
                {
                    var columns       = values[i].Split(',');
                    var haveShardingC = false;
                    var shardingValue = string.Empty;
                    List <StatementParameter> newC = new List <StatementParameter>();
                    for (int j = 0; j < columns.Length; j++)
                    {
                        var p = parameters.ElementAt(ii);
                        if (p.IsShardingColumn)
                        {
                            haveShardingC = true;
                            shardingValue = p.ShardingValue;
                        }
                        newC.Add(p);
                        ii++;
                    }

                    if (haveShardingC)
                    {
                        if (!string.IsNullOrEmpty(shardingValue))
                        {
                            if (dicValues.ContainsKey(shardingValue))
                            {
                                dicValues[shardingValue].Item1.Add(values[i] + ")");
                                foreach (var pp in newC)
                                {
                                    dicValues[shardingValue].Item2.Add(pp);
                                }
                            }
                        }
                        else
                        {
                            //添加到第一个分片
                            dicValues[defaultSharding].Item1.Add(values[i] + ")");
                            foreach (var pp in newC)
                            {
                                dicValues[defaultSharding].Item2.Add(pp);
                            }
                        }
                    }
                }

                foreach (var dic in dicValues)
                {
                    if (dic.Value.Item1.Count == 0)
                    {
                        continue;
                    }
                    var newHints = HintsUtil.CloneHints(hints);
                    if (shardingStrategy.ShardByDB)
                    {
                        newHints[DALExtStatementConstant.SHARDID] = dic.Key;
                    }
                    else
                    {
                        newHints[DALExtStatementConstant.TABLEID] = dic.Key;
                    }

                    var statement = GetStatement(logicDbName, StatementType.Sql, operationType ?? OperationType.Default, sqlType, newHints, shardingStrategy.ShardByDB? dic.Key:null);
                    statement.StatementText = shardingStrategy.ShardByDB ? (title + string.Join(",", dic.Value.Item1)): GetSql(title + string.Join(",", dic.Value.Item1), dic.Key);
                    statement.Parameters    = dic.Value.Item2;
#if !NETSTANDARD
                    CurrentStackCustomizedLog(statement);
#endif
                    result.Add(statement);
                }
            }

            return(result);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Private Create new Stored proc parameter.
 /// </summary>
 /// <param name="parameter"><see cref="SqlParameter"/>.</param>
 /// <param name="usedFor">The array of <see cref="SqlStatementType"/> define where is the parameter used.</param>
 private StoredProcParameter(SqlParameter parameter, SqlStatementType[] usedFor)
 {
     SqlParameter = parameter;
     IsForDelete = usedFor.Contains(SqlStatementType.Delete);
     IsForInsert = usedFor.Contains(SqlStatementType.Insert);
     IsForSelect = usedFor.Contains(SqlStatementType.Select);
     IsForUpdate = usedFor.Contains(SqlStatementType.Update);
 }
Ejemplo n.º 28
0
 public string GetProcDeclaration(SqlStatementType statementType)
 {
     return(GetProcDeclaration(statementType, 0));
 }
		public string GetSqlParameterStatement(ColumnSchema column, SqlStatementType statementType)
		{
			bool isOutput = false;

			if(statementType == SqlStatementType.Insert || statementType == SqlStatementType.Update) {
				isOutput = string.Compare(column.Name, TimeStampColumn, true) == 0;
			}
			if(!isOutput && statementType == SqlStatementType.Insert) {
				isOutput = IsIdentity(column);
			}
			string parameterStatement = GetSqlParameterStatement(column, isOutput);

			if(isOutput) {
				parameterStatement = parameterStatement.Replace("@", "@New");
			}

			return parameterStatement;
		}
		protected string GetProcCreateStatement(string procName, SqlStatementType statementType, 
			int indentLevel)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append(Indent(indentLevel, true));
			sb.Append("CREATE PROCEDURE ");
			sb.Append(procName);
			sb.Append(Indent(indentLevel++, true));
			sb.Append("(");

			ColumnSchemaCollection columns;
			bool ignoreAutoSetColumns = true;
			switch(statementType) {
				case SqlStatementType.Insert:
				case SqlStatementType.Update:
					columns = SourceTable.Columns;
					ignoreAutoSetColumns = false;
					break;
				case SqlStatementType.SelectBy:
					CheckForPrimaryKey(ParentTable);
					columns = ParentTable.PrimaryKey.MemberColumns;
					break;
				default:
					CheckForPrimaryKey(SourceTable);
					columns = SourceTable.PrimaryKey.MemberColumns;
					break;
			}
			
			for(int i = 0; i < columns.Count; i++) {
				sb.Append(Indent(indentLevel, true));
				sb.Append(GetSqlParameterStatement(columns[i], statementType));
				if(IsCommaNecessary(columns, i, ignoreAutoSetColumns)) {
					sb.Append(",");
				}
			}

			sb.Append(Indent(--indentLevel, true));
			sb.Append(")");
			sb.Append(Indent(indentLevel++, true));
			sb.Append("AS");
			sb.Append(GetSqlStatement(statementType, indentLevel));
			sb.Append(Indent(--indentLevel, true));
			sb.Append("GO");

			return sb.ToString();
		}
Ejemplo n.º 31
0
 /// <summary>
 /// The trigger function for <see cref="CommandExecuting"/>	event.
 /// </summary>
 /// <param name="sqlCommand">The SQL command that is going for execution.</param>
 private void OnCommandExecuting(FbCommand sqlCommand, SqlStatementType statementType)
 {
     CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(sqlCommand, statementType));
 }
		protected string GetSqlStatement(SqlStatementType statementType, int indentLevel)
		{
			switch(statementType) {
				case SqlStatementType.Select:
					return this.GetSelectStatement(false, indentLevel);
				case SqlStatementType.SelectBy:
					return this.GetSelectStatement(true, indentLevel);
				case SqlStatementType.Insert:
					return GetInsertStatement(indentLevel);
				case SqlStatementType.Update:
					return GetUpdateStatement(indentLevel);
				case SqlStatementType.Delete:
					return GetDeleteStatement(indentLevel);
				default:
					throw new ArgumentOutOfRangeException("statementType", statementType.ToString(), "No statement template has been defined for this SqlStatementType");
			}
		}
Ejemplo n.º 33
0
 internal void SetStatementType(SqlStatementType statementType)
 {
     StatementType = statementType;
 }
		protected string GetProcName(SqlStatementType statementType)
		{
			switch(statementType) {
				case SqlStatementType.Select:
					return string.Format(FetchCommandFormat, SourceTable.Name);
				case SqlStatementType.SelectBy:
					if(ParentTable == null) throw new InvalidOperationException("ParentTable must be specified for SelectBy procs.");
					return string.Format(FetchByCommandFormat, SourceTable.Name, ParentTable.Name);
				case SqlStatementType.Insert:
					return string.Format(InsertCommandFormat, SourceTable.Name);
				case SqlStatementType.Update:
					return string.Format(UpdateCommandFormat, SourceTable.Name);
				case SqlStatementType.Delete:
					return string.Format(DeleteCommandFormat, SourceTable.Name);
				default:
					throw new ArgumentOutOfRangeException("statementType", statementType.ToString(), "No command format has been defined for this SqlStatementType");
			}
		}
Ejemplo n.º 35
0
 private static Statement GetStatement(String logicDbName, StatementType statementType, OperationType operationType, SqlStatementType sqlType, IDictionary hints, String shardId = null)
 {
     return(new Statement
     {
         DatabaseSet = logicDbName,
         StatementType = statementType,
         OperationType = operationType,
         Hints = hints,
         ShardID = shardId,
         SqlOperationType = sqlType,
     });
 }
		protected string GetTableTimeStampSelect(SqlStatementType statementType, int indentLevel)
		{
			StringBuilder select = new StringBuilder(Indent(indentLevel, true));
			select.Append(SelectStatementTemplate);
			select.Replace("[SELECTCOLUMNS]", string.Format("SELECT @New{0} = {0}", TimeStampColumn));
			select.Replace("[FROM]", string.Format("FROM {0}", SourceTable.Name));
			
			string parameterName;

			StringBuilder where = new StringBuilder("WHERE ");
			foreach(ColumnSchema column in SourceTable.PrimaryKey.MemberColumns) {
				if(SourceTable.PrimaryKey.MemberColumns.IndexOf(column) > 0) {
					where.Append(" AND ");
				}

				if(statementType == SqlStatementType.Insert && IsIdentity(column)) {
					parameterName = string.Format("@New{0}", column.Name);
				}
				else {
					parameterName = string.Format("@{0}", column.Name);
				}
				where.Append(string.Format("{0} = {1}", column.Name, parameterName));
			}

			select.Replace("[WHERE]", where.ToString());

			return select.ToString();
		}
Ejemplo n.º 37
0
        /// <summary>
        /// Starts the ordered execution of the SQL statements that are in <see cref="SqlStatements"/> collection.
        /// </summary>
        /// <param name="autoCommit">Specifies if the transaction should be committed after a DDL command execution</param>
        public void Execute(bool autoCommit)
        {
            if (this.SqlStatements == null || this.SqlStatements.Count == 0)
            {
                throw new InvalidOperationException("There are no commands for execution.");
            }

            foreach (string sqlStatement in this.SqlStatements)
            {
                if (string.IsNullOrEmpty(sqlStatement))
                {
                    continue;
                }

                // initializate outputs to default
                int              rowsAffected  = -1;
                FbDataReader     dataReader    = null;
                SqlStatementType statementType = FbBatchExecution.GetStatementType(sqlStatement);

                if (!(statementType == SqlStatementType.Connect ||
                      statementType == SqlStatementType.CreateDatabase ||
                      statementType == SqlStatementType.Disconnect ||
                      statementType == SqlStatementType.DropDatabase ||
                      statementType == SqlStatementType.SetDatabase ||
                      statementType == SqlStatementType.SetNames ||
                      statementType == SqlStatementType.SetSQLDialect))
                {
                    // Update command configuration
                    this.ProvideCommand();
                    this.sqlCommand.CommandText = sqlStatement;

                    // Check how transactions are going to be handled
                    if (statementType == SqlStatementType.Insert ||
                        statementType == SqlStatementType.Update ||
                        statementType == SqlStatementType.Delete)
                    {
                        // DML commands should be inside a transaction
                        if (this.sqlTransaction == null)
                        {
                            this.sqlTransaction = this.sqlConnection.BeginTransaction();
                        }
                        this.sqlCommand.Transaction = this.sqlTransaction;
                    }
                    else if (this.sqlTransaction != null && !(statementType == SqlStatementType.Commit || statementType == SqlStatementType.Rollback))
                    {
                        // Non DML Statements should be executed using
                        // implicit transaction support
                        this.sqlTransaction.Commit();
                        this.sqlTransaction = null;
                    }
                }

                try
                {
                    switch (statementType)
                    {
                    case SqlStatementType.AlterDatabase:
                    case SqlStatementType.AlterDomain:
                    case SqlStatementType.AlterException:
                    case SqlStatementType.AlterIndex:
                    case SqlStatementType.AlterProcedure:
                    case SqlStatementType.AlterTable:
                    case SqlStatementType.AlterTrigger:
                    case SqlStatementType.AlterView:
                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Commit:
                        // raise the event
                        this.OnCommandExecuting(null);

                        this.sqlTransaction.Commit();
                        this.sqlTransaction = null;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.Connect:
                        // raise the event
                        this.OnCommandExecuting(null);

                        this.ConnectToDatabase(sqlStatement);

                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.CreateDatabase:
                        // raise the event
                        this.OnCommandExecuting(null);

                        this.CreateDatabase(sqlStatement);

                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.CommentOn:
                    case SqlStatementType.CreateDomain:
                    case SqlStatementType.CreateException:
                    case SqlStatementType.CreateGenerator:
                    case SqlStatementType.CreateIndex:
                    case SqlStatementType.CreateProcedure:
                    case SqlStatementType.CreateRole:
                    case SqlStatementType.CreateSequence:
                    case SqlStatementType.CreateShadow:
                    case SqlStatementType.CreateTable:
                    case SqlStatementType.CreateTrigger:
                    case SqlStatementType.CreateView:
                    case SqlStatementType.DeclareCursor:
                    case SqlStatementType.DeclareExternalFunction:
                    case SqlStatementType.DeclareFilter:
                    case SqlStatementType.DeclareStatement:
                    case SqlStatementType.DeclareTable:
                    case SqlStatementType.Delete:
                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Describe:
                        break;

                    case SqlStatementType.Disconnect:
                        // raise the event
                        this.OnCommandExecuting(null);

                        this.sqlConnection.Close();
                        FbConnection.ClearPool(this.sqlConnection);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.DropDatabase:
                        // raise the event
                        this.OnCommandExecuting(null);

                        FbConnection.DropDatabase(this.connectionString.ToString());
                        //this.sqlConnection = null;
                        this.requiresNewConnection = true;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.DropDomain:
                    case SqlStatementType.DropException:
                    case SqlStatementType.DropExternalFunction:
                    case SqlStatementType.DropFilter:
                    case SqlStatementType.DropGenerator:
                    case SqlStatementType.DropIndex:
                    case SqlStatementType.DropProcedure:
                    case SqlStatementType.DropSequence:
                    case SqlStatementType.DropRole:
                    case SqlStatementType.DropShadow:
                    case SqlStatementType.DropTable:
                    case SqlStatementType.DropTrigger:
                    case SqlStatementType.DropView:
                    case SqlStatementType.EventInit:
                    case SqlStatementType.EventWait:
                    case SqlStatementType.Execute:
                    case SqlStatementType.ExecuteImmediate:
                    case SqlStatementType.ExecuteProcedure:
                        this.ProvideCommand().CommandText = sqlStatement;

                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Fetch:
                        break;

                    case SqlStatementType.Grant:
                    case SqlStatementType.Insert:
                    case SqlStatementType.InsertCursor:
                    case SqlStatementType.Open:
                    case SqlStatementType.Prepare:
                    case SqlStatementType.Revoke:
                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.RecreateProcedure:
                    case SqlStatementType.RecreateTable:
                    case SqlStatementType.RecreateTrigger:
                    case SqlStatementType.RecreateView:
                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Rollback:
                        // raise the event
                        this.OnCommandExecuting(null);

                        this.sqlTransaction.Rollback();
                        this.sqlTransaction = null;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.Select:
                        this.ProvideCommand().CommandText = sqlStatement;

                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        dataReader = this.sqlCommand.ExecuteReader();
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, dataReader, -1);
                        if (!dataReader.IsClosed)
                        {
                            dataReader.Close();
                        }
                        break;

                    case SqlStatementType.SetGenerator:
                    case SqlStatementType.AlterSequence:
                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.SetDatabase:
                    case SqlStatementType.SetNames:
                    case SqlStatementType.SetSQLDialect:
                    case SqlStatementType.SetStatistics:
                    case SqlStatementType.SetTransaction:
                    case SqlStatementType.ShowSQLDialect:
                        throw new NotImplementedException();

                    case SqlStatementType.Update:
                    case SqlStatementType.Whenever:
                        // raise the event
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(this.sqlCommand, autoCommit);
                        this.requiresNewConnection = false;

                        // raise the event
                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (this.sqlTransaction != null)
                    {
                        this.sqlTransaction.Rollback();
                        this.sqlTransaction = null;
                    }

                    throw new FbException(string.Format(CultureInfo.CurrentUICulture, "An exception was thrown when executing command: {0}{2}Batch execution aborted{2}The returned message was: {1}", sqlStatement, ex.Message, Environment.NewLine));
                }
            }

            if (this.sqlTransaction != null)
            {
                // commit root transaction
                this.sqlTransaction.Commit();
                this.sqlTransaction = null;
            }

            this.sqlConnection.Close();
        }
Ejemplo n.º 38
0
        private static Statement GetDefaultSqlStatement(String logicDbName,
                                                        String sql, StatementParameterCollection parameters, IDictionary hints, SqlStatementType sqlType, OperationType?operationType = null)
        {
            if (String.IsNullOrEmpty(logicDbName))
            {
                throw new DalException("Please specify databaseSet.");
            }
            if (String.IsNullOrEmpty(sql))
            {
                throw new DalException("Please specify sql.");
            }

            Statement statement = GetStatement(logicDbName, StatementType.Sql, operationType ?? OperationType.Default, sqlType, hints);

            statement.StatementText = sql;
            statement.Parameters    = parameters;
            CurrentStackCustomizedLog(statement);
            return(statement);
        }