コード例 #1
0
ファイル: MsAccessAnalyzer.cs プロジェクト: fabrimaciel/gda
        /// <summary>
        /// Recupera as informações sobre as chaves primárias da tabela.
        /// </summary>
        private DataTable GetPrimaryKeyInfo(string tableName)
        {
            OleDbConnection conn = ProviderConfiguration.CreateConnection() as OleDbConnection;

            GDAConnectionManager.NotifyConnectionCreated(conn);
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
                GDAConnectionManager.NotifyConnectionOpened(conn);
            }
            try
            {
                OleDbCommand    cmd = new OleDbCommand("SELECT * FROM " + tableName, conn);
                OleDbDataReader dr  = cmd.ExecuteReader(CommandBehavior.KeyInfo);
                return(dr.GetSchemaTable());
            }
            finally
            {
                conn.Close();
            }
        }
コード例 #2
0
ファイル: MsAccessAnalyzer.cs プロジェクト: fabrimaciel/gda
        /// <summary>
        /// http://msdn.microsoft.com/library/en-us/oledb/htm/oledbprimary_keys_rowset.asp
        /// Restriction columns: TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME
        /// Schema columns: COLUMN_NAME, COLUMN_GUID, COLUMN_PROPID, ORDINAL, PK_NAME
        /// </summary>
        private DataTable GetPrimaryKeys(string tableName)
        {
            OleDbConnection conn = ProviderConfiguration.CreateConnection() as OleDbConnection;

            GDAConnectionManager.NotifyConnectionCreated(conn);
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
                GDAConnectionManager.NotifyConnectionOpened(conn);
            }
            try
            {
                return(conn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, new object[] {
                    null,
                    null,
                    tableName
                }));
            }
            finally
            {
                conn.Close();
            }
        }
コード例 #3
0
        /// <summary>
        /// Cria o enumerador.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        protected IEnumerator <T> CreateEnumerator <T>() where T : GDADataRecord
        {
            _enumeratorCreated = true;
            if (_session == null && _connection.State != ConnectionState.Open)
            {
                try
                {
                    _connection.Open();
                }
                catch (Exception ex)
                {
                    try
                    {
                        _connection.Dispose();
                    }
                    catch
                    {
                    }
                    _connection = null;
                    throw new GDAException(ex);
                }
                GDAConnectionManager.NotifyConnectionOpened(_connection);
            }
            IDataReader dReader = null;

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("GDADataRecordCursor: {0}\r\n", _command.CommandText);
                if (_command.Parameters.Count > 0)
                {
                    sb.Append("--> Parameters:");
                    foreach (IDataParameter parameter in _command.Parameters)
                    {
                        if (parameter.Value is byte[])
                        {
                            sb.Append("\r\n").Append(parameter.ParameterName).Append(" = byte[]");
                        }
                        else
                        {
                            sb.Append("\r\n").Append(parameter.ParameterName).Append(" = ").Append(parameter.Value == null ? "NULL" : '"' + parameter.Value.ToString() + '"');
                        }
                    }
                }
                SendMessageDebugTrace(sb.ToString());
                using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(_command))
                    try
                    {
                        dReader = _command.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        ex = new GDAException(ex);
                        executionHandler.Fail(ex);
                        throw ex;
                    }
                if (!_mapFieldsLoaded)
                {
                    _mapFields       = OnLoadTranslator(dReader);
                    _mapFieldsLoaded = true;
                }
                int startPage     = _startPage;
                int countPageSize = 0;
                while (dReader.Read())
                {
                    if (countPageSize == 0 && _startProcess != null)
                    {
                        _startProcess(this, EventArgs.Empty);
                    }
                    if (_usingPaging && !_provider.SupportSQLCommandLimit && startPage < _pageSize)
                    {
                        startPage++;
                        continue;
                    }
                    yield return(CreateDataRecord <T>(dReader, _mapFields));

                    countPageSize++;
                    if (_usingPaging && !_provider.SupportSQLCommandLimit && countPageSize >= _pageSize)
                    {
                        break;
                    }
                }
            }
            finally
            {
                try
                {
                    if (dReader != null)
                    {
                        dReader.Close();
                        dReader.Dispose();
                    }
                    if (_command != null)
                    {
                        _command.Dispose();
                    }
                    _command = null;
                }
                finally
                {
                    if (_session == null)
                    {
                        try
                        {
                            _connection.Close();
                            _connection.Dispose();
                        }
                        catch
                        {
                            SendMessageDebugTrace("Error close connection.");
                        }
                    }
                }
            }
        }
コード例 #4
0
ファイル: MsSql92Analyzer.cs プロジェクト: fabrimaciel/gda
 /// <summary>
 /// Please refer to the <see cref="DatabaseAnalyzer"/> class and the <see cref="DatabaseAnalyzer"/>
 /// interface it implements a description of this method.
 /// </summary>
 public override void Analyze(string tableName, string tableSchema)
 {
     try
     {
         bool          isSingleRun = tableName != null;
         IDbConnection conn        = ProviderConfiguration.CreateConnection();
         GDAConnectionManager.NotifyConnectionCreated(conn);
         IDataReader reader = null;
         if (conn.State != ConnectionState.Open)
         {
             conn.Open();
             GDAConnectionManager.NotifyConnectionOpened(conn);
         }
         try
         {
             IDbCommand fkCmd = conn.CreateCommand();
             if (isSingleRun)
             {
                 if (!string.IsNullOrEmpty(tableSchema))
                 {
                     fkCmd.CommandText = foreignKeysTables + string.Format("\r\nWHERE FK.TABLE_NAME='{0}' AND FK.TABLE_SCHEMA = '{1}'", tableName, tableSchema);
                 }
                 else
                 {
                     fkCmd.CommandText = foreignKeysTables + string.Format("\r\nWHERE FK.TABLE_NAME='{0}'", tableName);
                 }
             }
             else
             {
                 fkCmd.CommandText = foreignKeysTables;
             }
             using (reader = fkCmd.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     var fk = ForeignKeys[reader["Constraint_Name"].ToString()];
                     if (fk == null)
                     {
                         ForeignKeys.Add(new ForeignKeyMap()
                         {
                             ConstraintName        = reader["Constraint_Name"].ToString(),
                             ConstraintSchema      = reader["Constraint_Schema"].ToString(),
                             ForeignKeyTable       = reader["FK_Table"].ToString(),
                             ForeignKeyTableSchema = reader["FK_Schema"].ToString(),
                             ForeignKeyColumn      = reader["FK_Column"].ToString(),
                             PrimaryKeyTable       = reader["PK_Table"].ToString(),
                             PrimaryKeyTableSchema = reader["PK_Schema"].ToString(),
                             PrimaryKeyColumn      = reader["PK_Column"].ToString()
                         });
                     }
                 }
             }
             IDbCommand cmd = conn.CreateCommand();
             cmd.Connection = conn;
             if (isSingleRun)
             {
                 if (!string.IsNullOrEmpty(tableSchema))
                 {
                     cmd.CommandText = select + String.Format(" and t.TABLE_NAME = '{0}' and t.TABLE_SCHEMA = '{1}'", tableName, tableSchema);
                 }
                 else
                 {
                     cmd.CommandText = select + String.Format(" and t.TABLE_NAME = '{0}'", tableName);
                 }
             }
             else
             {
                 cmd.CommandText = select;
             }
             using (reader = cmd.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     string dbTableName   = reader["tablename"].ToString();
                     string dbTableSchema = (reader["tableschema"] ?? "").ToString();
                     if (!isSingleRun || (string.Compare(tableName, dbTableName, true) == 0 && (string.IsNullOrEmpty(tableSchema) || string.Compare(tableSchema, dbTableSchema) == 0)))
                     {
                         TableMap map = GetTableMap(dbTableName, dbTableSchema);
                         if (map == null)
                         {
                             map = new TableMap(ProviderConfiguration, dbTableName, dbTableSchema);
                             tablesMaps[dbTableName.ToLower()] = map;
                         }
                         map.IsView = reader["TableType"].ToString() == "VIEW";
                         string   columnName = reader["ColumnName"].ToString();
                         FieldMap fm         = map.GetFieldMapFromColumn(columnName);
                         if (fm == null)
                         {
                             fm = new FieldMap(map, columnName);
                             map.Fields.Add(fm);
                         }
                         fm.SetDbType(reader["Type"].ToString(), false);
                         fm.DbTypeName = reader["Type"].ToString();
                         fm.IsNullable = GetBoolean(reader["IsNullable"].ToString());
                         if ((reader["Size"] != null && reader["Size"] != DBNull.Value) && fm.DbType != (long)SqlDbType.Text)
                         {
                             fm.Size = int.Parse(reader["Size"].ToString());
                         }
                         if (reader["ConstraintName"] != null && reader["ConstraintName"] != DBNull.Value)
                         {
                             string type = reader["ConstraintType"].ToString();
                             if (type.ToLower().Equals("primary key"))
                             {
                                 fm.IsPrimaryKey = true;
                             }
                             else if (type.ToLower().Equals("foreign key"))
                             {
                                 string conref = reader["ConstraintReference"].ToString();
                                 fm.ForeignKeyConstraintName = reader["ConstraintName"].ToString();
                                 if (conref.StartsWith("IDX"))
                                 {
                                     string fkRef = reader["ConstraintName"].ToString();
                                     if (fkRef != null && fkRef.StartsWith("FK"))
                                     {
                                         conref = fkRef;
                                     }
                                 }
                                 IDbConnection conn2 = ProviderConfiguration.CreateConnection();
                                 GDAConnectionManager.NotifyConnectionCreated(conn2);
                                 IDbCommand cmd2 = conn2.CreateCommand();
                                 cmd2.CommandText = String.Format("select c.TABLE_NAME as TableName, c.TABLE_SCHEMA as TableSchema, c.COLUMN_NAME as ColumnName " + "from INFORMATION_SCHEMA.COLUMNS c " + "inner join INFORMATION_SCHEMA.TABLES t " + " on c.TABLE_NAME = t.TABLE_NAME " + "left join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu " + " on c.TABLE_NAME = ccu.TABLE_NAME and c.COLUMN_NAME = ccu.COLUMN_NAME " + "where t.TABLE_TYPE = 'BASE TABLE' and ccu.CONSTRAINT_NAME = '{0}'", conref);
                                 try
                                 {
                                     if (conn2.State != ConnectionState.Open)
                                     {
                                         conn2.Open();
                                         GDAConnectionManager.NotifyConnectionOpened(conn2);
                                     }
                                     using (IDataReader reader2 = cmd2.ExecuteReader())
                                     {
                                         if (reader2.Read())
                                         {
                                             fm.ForeignKeyTableName   = reader2["TableName"].ToString();
                                             fm.ForeignKeyTableSchema = (reader2["TableSchema"] ?? "").ToString();
                                             fm.ForeignKeyColumnName  = reader2["ColumnName"].ToString();
                                         }
                                     }
                                 }
                                 catch (Exception ex)
                                 {
                                     throw new GDAException(string.Format("Unable to obtain foreign key information for column {0} of table {1}.", fm.ColumnName, map.TableName), ex);
                                 }
                                 finally
                                 {
                                     if (conn2.State == ConnectionState.Open)
                                     {
                                         conn2.Close();
                                         conn2.Dispose();
                                     }
                                 }
                             }
                         }
                         fm.IsAutoGenerated = (reader["DefaultValue"].ToString().Length > 0 && fm.IsPrimaryKey ? true : false);
                         if (map.IsView)
                         {
                         }
                     }
                 }
             }
         }
         finally
         {
             conn.Close();
             conn.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw new GDAException("An error occurred while analyzing the database schema.", ex);
     }
 }
コード例 #5
0
        /// <summary>
        /// Recupera o Enumerator dos dados.
        /// </summary>
        /// <returns></returns>
        public IEnumerator <Model> GetEnumerator()
        {
            _enumeratorCreated = true;
            if (_session == null && _connection.State != ConnectionState.Open)
            {
                try
                {
                    _connection.Open();
                }
                catch (Exception ex)
                {
                    try
                    {
                        _connection.Dispose();
                    }
                    catch
                    {
                    }
                    _connection = null;
                    throw new GDAException(ex);
                }
                GDAConnectionManager.NotifyConnectionOpened(_connection);
            }
            IDataReader dReader = null;

            try
            {
                SendMessageDebugTrace("GDACursor: " + _command.CommandText);
                using (var executionHandler = Diagnostics.GDATrace.CreateExecutionHandler(_command))
                    try
                    {
                        dReader = _command.ExecuteReader();
                    }
                    catch (Exception ex)
                    {
                        ex = new GDAException(ex);
                        executionHandler.Fail(ex);
                        throw ex;
                    }
                if (dReader == null)
                {
                    throw new InvalidOperationException(string.Format("Execute Reader result from IDbCommand \"{0}\" couldn't be null.", _command.GetType().FullName));
                }
                _translatorDataInfo.ProcessFieldsPositions(dReader);
                int startPage     = _startPage;
                int countPageSize = 0;
                while (dReader.Read())
                {
                    if (countPageSize == 0 && _startProcess != null)
                    {
                        _startProcess(this, EventArgs.Empty);
                    }
                    if (_usingPaging && !_provider.SupportSQLCommandLimit && startPage < _pageSize)
                    {
                        startPage++;
                        continue;
                    }
                    if (!_isLoadValues)
                    {
                        Model       objItem = new Model();
                        IDataRecord record  = dReader;
                        PersistenceObject <Model> .RecoverValueOfResult(ref record, _translatorDataInfo, ref objItem, false);

                        yield return(objItem);
                    }
                    else
                    {
                        if (dReader[0] == DBNull.Value)
                        {
                            yield return(default(Model));
                        }
                        else
                        {
                            yield return((Model)dReader[0]);
                        }
                    }
                    countPageSize++;
                    if (_usingPaging && !_provider.SupportSQLCommandLimit && countPageSize >= _pageSize)
                    {
                        break;
                    }
                }
            }
            finally
            {
                try
                {
                    if (dReader != null)
                    {
                        dReader.Close();
                        dReader.Dispose();
                    }
                    _command.Dispose();
                    _command = null;
                }
                finally
                {
                    if (_session == null)
                    {
                        try
                        {
                            _connection.Close();
                            _connection.Dispose();
                            _connection = null;
                        }
                        catch
                        {
                            SendMessageDebugTrace("Error close connection.");
                        }
                    }
                }
            }
        }