Example #1
0
        public string GetAssignValue(SchemaExplorer.TableSchema SourceTable)
        {
            string ret = "";

            foreach (ColumnSchema column in SourceTable.Columns)
            {
                ret += GetMemberVariableName(column) + (new String(' ', GetPropertyNameMaxLength(SourceTable) - GetPropertyNameLength(column))) + " = " + GetCamelCaseName(GetPropertyName(column)) + ";\n\t\t\t";
            }
            return(ret);
        }
Example #2
0
        public string GetConstructorParameters(SchemaExplorer.TableSchema SourceTable)
        {
            string ret = "";

            foreach (ColumnSchema column in SourceTable.Columns)
            {
                ret += GetCSharpVariableType(column) + " " + GetCamelCaseName(GetPropertyName(column)) + ",\n\t\t\t";
            }
            return(ret.Substring(0, ret.Length - 5));
        }
Example #3
0
        public int GetPropertyNameMaxLength(SchemaExplorer.TableSchema SourceTable)
        {
            int ret = 0;

            foreach (ColumnSchema column in SourceTable.Columns)
            {
                ret = ret < GetPropertyNameLength(column)?GetPropertyNameLength(column):ret;
            }
            return(ret);
        }
    //获取表对应的类名
    public static string GetTableClassName(SchemaExplorer.TableSchema table)
    {
        string tableName = table.Name;

        string className = GetClassName(table);

        if (tableName.EndsWith("s"))
        {
            if (!className.EndsWith("s"))
            {
                className = className + "s";
            }
        }
        return(className);
    }
Example #5
0
 public string GetFileName(SchemaExplorer.TableSchema SourceTable)
 {
     return(this.GetClassName(SourceTable) + ".cs");
 }
Example #6
0
 public string GetTableName(SchemaExplorer.TableSchema SourceTable)
 {
     return("_" + GetCamelCaseName(SourceTable.Name));
 }
Example #7
0
        public bool IsDependantOf(TableSchema table)
        {
            TableSchemaCollection checkedTables = new TableSchemaCollection();

            return(this.IsDependantOfInternal(table, checkedTables));
        }
Example #8
0
        /// <summary>
        /// Gets all columns for a given table.
        /// </summary>
        /// <param name="connectionString">The connection string used to connect to the target database.</param>
        /// <param name="table"></param>
        /// <returns></returns>
        public ColumnSchema[] GetTableColumns(string connectionString, TableSchema table)
        {
            //Erik Ejlskov - exclude system columns
            string getColumnSql = string.Format(@"SELECT 
                                                    COLUMN_NAME as [Name], 
                                                    COLUMN_DEFAULT as [Default], 
                                                    IS_NULLABLE as [IsNullable], 
                                                    DATA_TYPE as [DataType], 
                                                    CHARACTER_MAXIMUM_LENGTH as [Length], 
                                                    NUMERIC_PRECISION as [Precision], 
                                                    NUMERIC_SCALE as [Scale], 
                                                    AUTOINC_SEED, 
                                                    AUTOINC_INCREMENT, 
                                                    COLUMN_HASDEFAULT, 
                                                    COLUMN_FLAGS 
                                                 FROM 
                                                    INFORMATION_SCHEMA.COLUMNS 
                                                 WHERE 
                                                    TABLE_NAME = '{0}' AND 
                                                    COLUMN_FLAGS <> 98 AND 
                                                    COLUMN_FLAGS <> 114 
                                                 ORDER BY 
                                                    ORDINAL_POSITION", table.Name);

            var columns = new List <ColumnSchema>();

            using (SqlCeCommand cmd = GetCeCommand(connectionString, getColumnSql))
            {
                using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                {
                    while (results.Read())
                    {
                        var extendedProperties = new List <ExtendedProperty>();

                        if (!results.IsDBNull(7))
                        {
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IsIdentity, true, DbType.Boolean));
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IdentitySeed, results["AUTOINC_SEED"].ToString(), DbType.String));
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IdentityIncrement, results["AUTOINC_INCREMENT"].ToString(), DbType.String));
                        }
                        else
                        {
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IsIdentity, false, DbType.Boolean));
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IdentitySeed, "0", DbType.String));
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IdentityIncrement, "0", DbType.String));
                        }

                        if (results["COLUMN_HASDEFAULT"] != null)
                        {
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.DefaultValue, results["Default"].ToString(), DbType.String));
                        }
                        else
                        {
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.DefaultValue, string.Empty, DbType.String));
                        }

                        var name       = (string)results["Name"];
                        var nativeType = (string)results["DataType"];
                        //Erik Ejlskov - should be "timestamp" instead
                        if (nativeType == "rowversion")
                        {
                            nativeType = "timestamp";
                        }
                        DbType dataType = GetDbTypeFromString(nativeType);
                        if ((dataType == DbType.Guid && results.GetInt32(10) == 378) || (dataType == DbType.Guid && results.GetInt32(10) == 282))
                        {
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IsRowGuidColumn, true, DbType.Boolean));
                        }
                        else
                        {
                            extendedProperties.Add(new ExtendedProperty(ExtendedPropertyNames.IsRowGuidColumn, false, DbType.Boolean));
                        }

                        int size;
                        int.TryParse(results["Length"].ToString(), out size);

                        byte precision;
                        byte.TryParse(results["Precision"].ToString(), out precision);

                        int scale;
                        int.TryParse(results["scale"].ToString(), out scale);

                        bool allowNull = GetBoolFromYesNo((string)results["IsNullable"]);

                        var s = new ColumnSchema(table, name, dataType, nativeType, size, precision, scale, allowNull, extendedProperties.ToArray());
                        columns.Add(s);
                    } // while(read)
                }     // using(results)
            }         // using(command)

            return(columns.ToArray());
        }
Example #9
0
        /// <summary>
        /// Gets all of the table keys for a given table.
        /// </summary>
        /// <param name="connectionString">The connection string used to connect to the target database.</param>
        /// <param name="table"></param>
        /// <returns></returns>
        public TableKeySchema[] GetTableKeys(string connectionString, TableSchema table)
        {
            var keyNames = new List <string>();

            string sql = string.Format("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_TABLE_NAME = '{0}' ", table.Name);

            using (SqlCeCommand cmd = GetCeCommand(connectionString, sql))
            {
                using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                {
                    while (results.Read())
                    {
                        keyNames.Add(results[0].ToString());
                    } // while
                }
            }

            var keys = new List <TableKeySchema>();

            string name    = string.Empty;
            string fkTable = string.Empty;
            string pkTable = string.Empty;

            foreach (string keyName in keyNames)
            {
                sql = string.Format("SELECT KCU1.TABLE_NAME AS FK_TABLE_NAME, KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, KCU1.COLUMN_NAME AS FK_COLUMN_NAME, KCU2.TABLE_NAME AS UQ_TABLE_NAME, KCU2.CONSTRAINT_NAME AS UQ_CONSTRAINT_NAME, KCU2.COLUMN_NAME AS UQ_COLUMN_NAME, KCU2.ORDINAL_POSITION AS UQ_ORDINAL_POSITION, KCU1.ORDINAL_POSITION AS FK_ORDINAL_POSITION FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1 ON KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 ON  KCU2.CONSTRAINT_NAME =  RC.UNIQUE_CONSTRAINT_NAME AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION WHERE KCU1.TABLE_NAME = '{0}' AND KCU2.TABLE_NAME = RC.UNIQUE_CONSTRAINT_TABLE_NAME AND  KCU1.CONSTRAINT_NAME = '{1}' ORDER BY FK_TABLE_NAME, FK_CONSTRAINT_NAME, FK_ORDINAL_POSITION", table.Name, keyName);

                using (SqlCeCommand cmd = GetCeCommand(connectionString, sql))
                {
                    using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                    {
                        bool hasRows = false;
                        var  pkCols  = new List <string>();
                        var  fkCols  = new List <string>();

                        while (results.Read())
                        {
                            hasRows = true;
                            name    = (string)results["FK_CONSTRAINT_NAME"];
                            fkTable = (string)results["FK_TABLE_NAME"];
                            pkTable = (string)results["UQ_TABLE_NAME"];
                            fkCols.Add((string)results["FK_COLUMN_NAME"]);
                            pkCols.Add((string)results["UQ_COLUMN_NAME"]);
                        } // while
                        if (hasRows)
                        {
                            keys.Add(new TableKeySchema(table.Database, name, fkCols.ToArray(), fkTable, pkCols.ToArray(), pkTable));
                        }
                    }
                }
            }

            keyNames.Clear();

            sql = string.Format("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE UNIQUE_CONSTRAINT_TABLE_NAME = '{0}' ", table.Name);

            using (SqlCeCommand cmd = GetCeCommand(connectionString, sql))
            {
                using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                {
                    while (results.Read())
                    {
                        keyNames.Add(results[0].ToString());
                    } // while
                }
            }

            foreach (string keyName in keyNames)
            {
                //Then get keys pointing to this table
                sql = string.Format("SELECT KCU1.TABLE_NAME AS FK_TABLE_NAME, KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, KCU1.COLUMN_NAME AS FK_COLUMN_NAME, KCU2.TABLE_NAME AS UQ_TABLE_NAME, KCU2.CONSTRAINT_NAME AS UQ_CONSTRAINT_NAME, KCU2.COLUMN_NAME AS UQ_COLUMN_NAME, KCU2.ORDINAL_POSITION AS UQ_ORDINAL_POSITION, KCU1.ORDINAL_POSITION AS FK_ORDINAL_POSITION FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1 ON KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 ON  KCU2.CONSTRAINT_NAME =  RC.UNIQUE_CONSTRAINT_NAME AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION WHERE KCU2.TABLE_NAME = '{0}' AND KCU1.TABLE_NAME <> '{0}' AND KCU2.TABLE_NAME = RC.UNIQUE_CONSTRAINT_TABLE_NAME AND KCU1.CONSTRAINT_NAME = '{1}' ORDER BY FK_TABLE_NAME, FK_CONSTRAINT_NAME, FK_ORDINAL_POSITION", table.Name, keyName);

                using (SqlCeCommand cmd = GetCeCommand(connectionString, sql))
                {
                    using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                    {
                        bool hasRows = false;
                        var  pkCols  = new List <string>();
                        var  fkCols  = new List <string>();

                        while (results.Read())
                        {
                            hasRows = true;
                            name    = (string)results["FK_CONSTRAINT_NAME"];

                            pkTable = (string)results["UQ_TABLE_NAME"];
                            pkCols.Add((string)results["UQ_COLUMN_NAME"]);

                            fkTable = (string)results["FK_TABLE_NAME"];
                            fkCols.Add((string)results["FK_COLUMN_NAME"]);
                        } // while
                        if (hasRows)
                        {
                            keys.Add(new TableKeySchema(table.Database, name, fkCols.ToArray(), fkTable, pkCols.ToArray(), pkTable));
                        }
                    }
                }
            }

            return(keys.ToArray());
        }
Example #10
0
        /// <summary>
        /// Gats all of the indexes for a given table.
        /// </summary>
        /// <param name="connectionString">The connection string used to connect to the target database.</param>
        /// <param name="table"></param>
        /// <returns></returns>
        public IndexSchema[] GetTableIndexes(string connectionString, TableSchema table)
        {
            string sql = string.Format("SELECT DISTINCT INDEX_NAME as [IndexName] FROM INFORMATION_SCHEMA.INDEXES WHERE TABLE_NAME = '{0}'  AND SUBSTRING(COLUMN_NAME, 1,5) <> '__sys' ORDER BY INDEX_NAME ASC", table.Name);

            var indexNames = new List <string>();
            var indices    = new List <IndexSchema>();

            using (SqlCeCommand cmd = GetCeCommand(connectionString, sql))
            {
                using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                {
                    while (results.Read())
                    {
                        indexNames.Add((string)results["IndexName"] ?? String.Empty);
                    }
                }
            }

            foreach (string indexName in indexNames)
            {
                //Erik Ejlskov - corrected SQL statement to include table name!
                string getIndexSql = string.Format(@"SELECT 
                                                        INDEX_NAME as [Name],
                                                        PRIMARY_KEY as [IsPrimaryKey],
                                                        [UNIQUE] as [IsUnique],
                                                        [CLUSTERED] as [IsClustered],
                                                        [COLUMN_NAME] as [ColumnName] 
                                                    FROM 
                                                        INFORMATION_SCHEMA.INDEXES 
                                                    WHERE 
                                                        INDEX_NAME = '{0}' AND 
                                                        TABLE_NAME = '{1}' 
                                                    ORDER BY 
                                                        [Name],
                                                        [ORDINAL_POSITION]", indexName, table.Name);

                // string indexName = String.Empty;
                bool isPrimaryKey  = false;
                bool isUnique      = false;
                bool isClustered   = false;
                var  memberColumns = new List <string>();
                bool read          = false;

                using (SqlCeCommand cmd = GetCeCommand(connectionString, getIndexSql))
                {
                    using (SqlCeResultSet results = cmd.ExecuteResultSet(ResultSetOptions.None))
                    {
                        while (results.Read())
                        {
                            if (!read)
                            {
                                // indexName = (string)results["Name"];
                                isPrimaryKey = (bool)results["IsPrimaryKey"];
                                isUnique     = (bool)results["IsUnique"];
                                isClustered  = (bool)results["IsClustered"];
                                memberColumns.Add((string)results["ColumnName"]);
                                read = true;
                            }
                            else
                            {
                                memberColumns.Add((string)results["ColumnName"]);
                            } // if(!read)
                        }     // while

                        indices.Add(new IndexSchema(table, indexName, isPrimaryKey, isUnique, isClustered, memberColumns.ToArray()));
                    } // using(results)
                }     // using(cmd)
            }         //foreach(indexName)

            return(indices.ToArray());
        }
Example #11
0
 public ColumnSchema(TableSchema table, string name, DbType dataType, string nativeType, int size, byte precision, int scale, bool allowDBNull, ExtendedProperty[] extendedProperties) : this(table, name, dataType, nativeType, size, precision, scale, allowDBNull)
 {
     this._defaultExtendedProperties = extendedProperties;
     base._extendedProperties        = new ExtendedPropertyCollection(this._defaultExtendedProperties);
 }
        public ExtendedProperty[] GetExtendedProperties(string connectionString, SchemaObjectBase schemaObject)
        {
            if (schemaObject is TableSchema)
            {
                TableSchema             tableSchema = (TableSchema)schemaObject;
                string                  text        = $"select cast(obj_description(relfilenode,'pg_class') as varchar) as comment from pg_class where relname='{tableSchema.Name}';";
                List <ExtendedProperty> list        = new List <ExtendedProperty>();
                using (NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connectionString))
                {
                    npgsqlConnection.Open();

                    using (NpgsqlCommand npgsqlCommand = new NpgsqlCommand(text, npgsqlConnection))
                    {
                        var comment = npgsqlCommand.ExecuteScalar();
                        list.Add(ExtendedProperty.Readonly("CS_Description", comment?.ToString()));
                    }
                    if (npgsqlConnection.State != ConnectionState.Closed)
                    {
                        npgsqlConnection.Close();
                    }
                }
                return(list.ToArray());
            }
            if (schemaObject is ColumnSchema)
            {
                List <ExtendedProperty> list         = new List <ExtendedProperty>();
                ColumnSchema            columnSchema = schemaObject as ColumnSchema;
                string text = $"select pg_get_serial_sequence(a.table_name, a.column_name) as EXTRA,a.COLUMN_DEFAULT,a.data_type,c.DeText as description from information_schema.columns as a left join( select pg_attr.attname as colname,pg_constraint.conname as pk_name from pg_constraint inner join pg_class on pg_constraint.conrelid = pg_class.oid inner join pg_attribute pg_attr on pg_attr.attrelid = pg_class.oid and  pg_attr.attnum = pg_constraint.conkey[1] inner join pg_type on pg_type.oid = pg_attr.atttypid where pg_class.relname = '{columnSchema.Table.Name}' and pg_constraint.contype = 'p')as b on b.colname = a.column_name left join( select attname, description as DeText from pg_class left join pg_attribute pg_attr on pg_attr.attrelid = pg_class.oid left join pg_description pg_desc on pg_desc.objoid = pg_attr.attrelid and pg_desc.objsubid = pg_attr.attnum where pg_attr.attnum > 0 and pg_attr.attrelid = pg_class.oid and pg_class.relname = '{columnSchema.Table.Name}')as c on c.attname = a.column_name where table_schema = 'public' and table_name = '{columnSchema.Table.Name}' and COLUMN_NAME = '{columnSchema.Name}' order by ordinal_position; ";
                using (NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connectionString))
                {
                    npgsqlConnection.Open();
                    using (NpgsqlCommand npgsqlCommand = new NpgsqlCommand(text, npgsqlConnection))
                    {
                        using (IDataReader dataReader = npgsqlCommand.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dataReader.Read())
                            {
                                string text2       = dataReader.IsDBNull(0) ? string.Empty : dataReader.GetString(0).ToLower();
                                string value       = dataReader.IsDBNull(1) ? null : dataReader.GetString(1).ToUpper();
                                string value2      = dataReader.GetString(2).ToUpper();
                                string description = dataReader.GetString(3);
                                bool   flag        = !string.IsNullOrEmpty(text2);
                                list.Add(new ExtendedProperty("CS_IsIdentity", flag, columnSchema.DataType));
                                if (flag)
                                {
                                    list.Add(new ExtendedProperty("CS_IdentitySeed", 1, columnSchema.DataType));
                                    list.Add(new ExtendedProperty("CS_IdentityIncrement", 1, columnSchema.DataType));
                                }
                                list.Add(new ExtendedProperty("CS_Default", value, DbType.String));
                                list.Add(new ExtendedProperty("CS_SystemType", value2, DbType.String));
                                list.Add(new ExtendedProperty("CS_Sequence", text2.ToUpper(), DbType.String));
                                list.Add(ExtendedProperty.Readonly("CS_Description", description?.ToString()));
                            }
                            if (!dataReader.IsClosed)
                            {
                                dataReader.Close();
                            }
                        }
                    }
                    if (npgsqlConnection.State != ConnectionState.Closed)
                    {
                        npgsqlConnection.Close();
                    }
                }
                return(list.ToArray());
            }

            return(new ExtendedProperty[0]);
        }
        public TableKeySchema[] GetTableKeys(string connectionString, TableSchema table)
        {
            List <TableKeySchema> list = new List <TableKeySchema>();

            using (NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connectionString))
            {
                npgsqlConnection.Open();
                string text = string.Format("SELECT constraint_name as constrname FROM information_schema.table_constraints WHERE table_name = '{0}' AND constraint_type = 'FOREIGN KEY' AND constraint_schema='public'", table.Name);
                using (NpgsqlCommand npgsqlCommand = new NpgsqlCommand(text, npgsqlConnection))
                {
                    string text2 = string.Format("SELECT px.conname as constrname, att.attname as colname, fore.relname as reftabname, fatt.attname as refcolname, CASE px.confupdtype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END AS on_update, CASE px.confdeltype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END AS on_delete, CASE px.contype WHEN 'p' THEN true WHEN 'f' THEN false END as IsPrimaryKey from pg_constraint px left join pg_class home on (home.oid = px.conrelid) left join pg_class fore on (fore.oid = px.confrelid) left join pg_attribute att on (att.attrelid = px.conrelid AND att.attnum = ANY(px.conkey)) left join pg_attribute fatt on (fatt.attrelid = px.confrelid AND fatt.attnum = ANY(px.confkey)) where (home.relname = '{0}') and px.contype = 'f' order by constrname", table.Name);
                    using (NpgsqlCommand npgsqlCommand2 = new NpgsqlCommand(text2, npgsqlConnection))
                    {
                        NpgsqlDataAdapter npgsqlDataAdapter = new NpgsqlDataAdapter();
                        DataSet           dataSet           = new DataSet();
                        npgsqlDataAdapter.SelectCommand = npgsqlCommand;
                        npgsqlDataAdapter.Fill(dataSet, "constraint");
                        npgsqlDataAdapter.SelectCommand = npgsqlCommand2;
                        npgsqlDataAdapter.Fill(dataSet, "keys");
                        if (dataSet.Tables[0].Rows.Count > 0)
                        {
                            dataSet.Relations.Add("Contraint_to_Keys", dataSet.Tables[0].Columns["constrname"], dataSet.Tables[1].Columns["constrname"]);
                            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                            {
                                string    name            = dataRow["constrname"].ToString();
                                DataRow[] childRows       = dataRow.GetChildRows("Contraint_to_Keys");
                                string[]  array           = new string[childRows.Length];
                                string[]  array2          = new string[childRows.Length];
                                string    name2           = table.Name;
                                string    primaryKeyTable = childRows[0]["reftabname"].ToString();
                                for (int i = 0; i < childRows.Length; i++)
                                {
                                    array2[i] = childRows[i]["colname"].ToString();
                                    array[i]  = childRows[i]["refcolname"].ToString();
                                }
                                list.Add(new TableKeySchema(table.Database, name, array2, name2, array, primaryKeyTable));
                            }
                        }
                    }
                }
                string text3 = string.Format("SELECT px.conname as constrname FROM pg_constraint px left join pg_class fore on fore.oid = px.confrelid where fore.relname = '{0}'", table.Name);
                using (NpgsqlCommand npgsqlCommand3 = new NpgsqlCommand(text3, npgsqlConnection))
                {
                    string text4 = string.Format("SELECT px.conname as constrname, fatt.attname as colname, home.relname as reftabname, att.attname as refcolname, CASE px.confupdtype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END AS on_update, CASE px.confdeltype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END AS on_delete, CASE px.contype WHEN 'p' THEN true WHEN 'f' THEN false END as IsPrimaryKey from pg_constraint px left join pg_class home on (home.oid = px.conrelid) left join pg_class fore on (fore.oid = px.confrelid) left join pg_attribute att on (att.attrelid = px.conrelid AND att.attnum = ANY(px.conkey)) left join pg_attribute fatt on (fatt.attrelid = px.confrelid AND fatt.attnum = ANY(px.confkey)) where (fore.relname = '{0}') order by constrname", table.Name);
                    using (NpgsqlCommand npgsqlCommand4 = new NpgsqlCommand(text4, npgsqlConnection))
                    {
                        NpgsqlDataAdapter npgsqlDataAdapter2 = new NpgsqlDataAdapter();
                        DataSet           dataSet2           = new DataSet();
                        npgsqlDataAdapter2.SelectCommand = npgsqlCommand3;
                        npgsqlDataAdapter2.Fill(dataSet2, "constraint");
                        npgsqlDataAdapter2.SelectCommand = npgsqlCommand4;
                        npgsqlDataAdapter2.Fill(dataSet2, "keys");
                        if (dataSet2.Tables[0].Rows.Count > 0)
                        {
                            dataSet2.Relations.Add("Contraint_to_Keys", dataSet2.Tables[0].Columns["constrname"], dataSet2.Tables[1].Columns["constrname"]);
                            foreach (DataRow dataRow2 in dataSet2.Tables[0].Rows)
                            {
                                string    name3           = dataRow2["constrname"].ToString();
                                DataRow[] childRows2      = dataRow2.GetChildRows("Contraint_to_Keys");
                                string[]  array3          = new string[childRows2.Length];
                                string[]  array4          = new string[childRows2.Length];
                                string    foreignKeyTable = childRows2[0]["reftabname"].ToString();
                                string    name4           = table.Name;
                                for (int j = 0; j < childRows2.Length; j++)
                                {
                                    array4[j] = childRows2[j]["refcolname"].ToString();
                                    array3[j] = childRows2[j]["colname"].ToString();
                                }
                                list.Add(new TableKeySchema(table.Database, name3, array4, foreignKeyTable, array3, name4));
                            }
                        }
                    }
                }
            }
            return(list.ToArray());
        }
        public ColumnSchema[] GetTableColumns(string connectionString, TableSchema table)
        {
            List <ColumnSchema> list = new List <ColumnSchema>();

            using (NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connectionString))
            {
                npgsqlConnection.Open();
                string text = string.Format("select column_name, is_nullable, character_maximum_length, numeric_precision, numeric_scale, data_type, udt_name from information_schema.columns where table_schema = 'public' and table_name='{0}'", table.Name);
                using (NpgsqlCommand npgsqlCommand = new NpgsqlCommand(text, npgsqlConnection))
                {
                    DataTable dt = new DataTable();
                    using (NpgsqlDataAdapter nda = new NpgsqlDataAdapter(npgsqlCommand))
                    {
                        nda.Fill(dt);
                        nda.Dispose();
                    }

                    foreach (DataRow item in dt.Rows)
                    {
                        bool   allowDBNull       = item["is_nullable"] == null ? false : item["is_nullable"].ToString().Equals("YES");
                        int?   numeric_precision = item.Field <int?>("numeric_precision");
                        byte   precision         = (byte)(numeric_precision ?? 0);
                        int?   size  = item.Field <int?>("character_maximum_length");
                        int?   scale = item.Field <int?>("numeric_scale");
                        string name  = item["column_name"] == null ? string.Empty : item["column_name"].ToString();
                        string text2 = item["data_type"] == null ? string.Empty : item["data_type"].ToString();
                        string type  = item["udt_name"] == null ? string.Empty : item["udt_name"].ToString();
                        list.Add(new ColumnSchema(table, name, PostgreSQLSchemaProvider.GetDbType(type), text2, size ?? 0, precision, scale ?? 0, allowDBNull, new ExtendedProperty[]
                        {
                            new ExtendedProperty("NpgsqlDbType", PostgreSQLSchemaProvider.GetNativeDbType(text2), DbType.String)
                        }));
                    }

                    //using (NpgsqlDataReader npgsqlDataReader = npgsqlCommand.ExecuteReader(CommandBehavior.CloseConnection))
                    //{
                    //    while (npgsqlDataReader.Read())
                    //    {
                    //        bool allowDBNull = npgsqlDataReader.IsDBNull(1) || npgsqlDataReader.GetString(1) == "YES";
                    //        byte precision = (byte)(npgsqlDataReader.IsDBNull(3) ? 0 : npgsqlDataReader.GetInt32(3));
                    //        int size = npgsqlDataReader.IsDBNull(2) ? 0 : npgsqlDataReader.GetInt32(2);
                    //        int scale = npgsqlDataReader.IsDBNull(4) ? 0 : npgsqlDataReader.GetInt32(4);
                    //        string name = npgsqlDataReader.IsDBNull(0) ? string.Empty : npgsqlDataReader.GetString(0);
                    //        string text2 = npgsqlDataReader.IsDBNull(5) ? string.Empty : npgsqlDataReader.GetString(5);
                    //        string type = npgsqlDataReader.IsDBNull(6) ? string.Empty : npgsqlDataReader.GetString(6);
                    //        list.Add(new ColumnSchema(table, name, PostgreSQLSchemaProvider.GetDbType(type), text2, size, precision, scale, allowDBNull, new ExtendedProperty[]
                    //        {
                    //            new ExtendedProperty("NpgsqlDbType", PostgreSQLSchemaProvider.GetNativeDbType(text2), DbType.String)
                    //        }));
                    //    }
                    //    if (!npgsqlDataReader.IsClosed)
                    //    {
                    //        npgsqlDataReader.Close();
                    //    }
                    //}
                }
                if (npgsqlConnection.State != ConnectionState.Closed)
                {
                    npgsqlConnection.Close();
                }
            }
            return(list.ToArray());
        }