Ejemplo n.º 1
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            List <IndexColumn> columns = new List <IndexColumn>();

            int order = 1;

            foreach (DataGridViewRow row in this.dgvColumns.Rows)
            {
                if (!row.IsNewRow)
                {
                    IndexColumn columnInfo = new IndexColumn()
                    {
                        Order = order
                    };
                    columnInfo.ColumnName = row.Cells[this.colColumName.Name].Value?.ToString();
                    columnInfo.IsDesc     = row.Cells[this.colSort.Name].Value?.ToString() == SortType.Descending.ToString();

                    columns.Add(columnInfo);

                    order++;
                }
            }

            if (columns.Count == 0)
            {
                MessageBox.Show("Please select column(s).");
                return;
            }

            this.SelectedColumns = columns;

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Ejemplo n.º 2
0
        private static void LoadEntityIndexes(Entity entity, DiskModel diskModel)
        {
            foreach (var indexNode in diskModel.Indexes.Where(x => new Guid(x.id) == entity.Id).SelectMany(x => x.index))
            {
                var id       = new Guid(indexNode.id);
                var newIndex = entity.Indexes.FirstOrDefault(x => x.Id == id);
                if (newIndex == null)
                {
                    newIndex = new Index(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                    entity.Indexes.Add(newIndex);
                }
                newIndex.Clustered    = indexNode.clustered != 0;
                newIndex.ImportedName = indexNode.importedname;
                newIndex.IndexType    = (IndexTypeConstants)indexNode.indextype;
                newIndex.IsUnique     = indexNode.isunique != 0;

                foreach (var indexColumnNode in indexNode.indexcolumnset)
                {
                    id = new Guid(indexColumnNode.id);
                    var newIndexColumn = newIndex.IndexColumns.FirstOrDefault(x => x.Id == id);
                    if (newIndexColumn == null)
                    {
                        newIndexColumn = new IndexColumn(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                        newIndex.IndexColumns.Add(newIndexColumn);
                    }
                    newIndexColumn.Ascending  = indexColumnNode.ascending != 0;
                    newIndexColumn.FieldID    = new Guid(indexColumnNode.fieldid);
                    newIndexColumn.SortOrder  = indexColumnNode.sortorder;
                    newIndexColumn.IsInternal = true;
                }
            }
        }
Ejemplo n.º 3
0
        private void CompareTableIndexes(Index i1, Index i2)
        {
            Assert.IsNotNull(i1);
            Assert.IsNotNull(i2);
            Assert.AreEqual(i1.DataTable.Name, i2.DataTable.Name);
            Assert.AreEqual(i1.Filegroup, i2.Filegroup);

            Version ver = connection.Driver.CoreServerInfo.ServerVersion;

            if (ver.Major * 100 + ver.Minor >= 802)
            {
                if (i1.FillFactor != null)
                {
                    Assert.AreEqual(i1.FillFactor, i2.FillFactor);
                }
            }
            Assert.AreEqual(i1.IsBitmap, i2.IsBitmap);
            Assert.AreEqual(i1.IsClustered, i2.IsClustered);
            Assert.AreEqual(i1.IsUnique, i2.IsUnique);

            Assert.AreEqual(i1.Columns.Count, i2.Columns.Count);
            foreach (IndexColumn ic1 in i1.Columns)
            {
                IndexColumn ic2 = i2.Columns[ic1.Name];
                Assert.IsNotNull(ic2);
                CompareIndexColumns(ic1, ic2);
            }
        }
Ejemplo n.º 4
0
        internal override void PopulateKeyConstraints(DatabaseObjects.Database database, DbCommand cmd, bool includeSystemSchemas, BackgroundWorker worker)
        {
            if (worker != null)
            {
                worker.ReportProgress(0, $"Populating key constraints for {database.DatabaseName}...");
            }

            foreach (var tbl in database.Schemas.SelectMany(s => s.Tables))
            {
                cmd.CommandText = "pragma table_info(" + tbl.TableName + ")";
                using (var rdr = cmd.ExecuteReader())
                {
                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            if ((long)rdr["pk"] == 1)
                            {
                                var constraint = new KeyConstraint(database);
                                constraint.ConstraintName = tbl + "_pkey";
                                constraint.IsPrimaryKey   = true;
                                constraint.Parent         = tbl;
                                tbl.KeyConstraints.Add(constraint);

                                var col = new IndexColumn();
                                col.ColumnName = rdr["name"].ToString();
                                constraint.Columns.Add(col);
                            }
                        }
                    }
                    rdr.Close();
                }
            }
        }
Ejemplo n.º 5
0
        public override void Visit(SqlCreateIndex node, IndexColumn item)
        {
            base.Visit(node, item);

            if (item.TypeColumn != null)
            {
                context.Output.AppendText(string.Format("TYPE COLUMN {0} ", translator.QuoteIdentifier(item.TypeColumn.Name)));
            }
            switch (item.Languages.Count)
            {
            case 0:
                break;

            case 1:
                if (!string.IsNullOrEmpty(item.Languages[0].Name))
                {
                    context.Output.AppendText(string.Format("LANGUAGE '{0}'", item.Languages[0].Name));
                }
                break;

            default:
                throw new InvalidOperationException(string.Format(
                                                        Strings.ExMultipleLanguagesNotSupportedForFulltextColumnXOfIndexY, item.Name, item.Index.Name));
            }
        }
Ejemplo n.º 6
0
 public override void Visit(SqlCreateIndex node, IndexColumn item)
 {
     if (!node.Index.IsFullText)
     {
         base.Visit(node, item);
     }
     // FullText builds expression instead of list of columns in Translate(SqlCompilerContext context, SqlCreateIndex node, CreateIndexSection section)
 }
Ejemplo n.º 7
0
        /// <summary>
        /// initialize the internal DataSet for the Class
        /// </summary>
        /// <param name="Index">the Index-Column(s) to use (set to unique)</param>
        private void _initializeDataSet(IndexColumn Index)
        {
            // save internal Index-Mode
            _set_IdxMode = Index;
            // basic DataSet
            DataSet _tds = new DataSet("UserNameList");    // internal DataSet
            // Table-Defninition
            DataTable _tabUsr = new DataTable("UserData"); // internal Table for Users

            // Column-Definition for basic User-Table
            // ======================================
            //
            // AutoID-Column (always Index)
            DataColumn _col1 = new DataColumn("colID", System.Type.GetType("System.Int32"));

            _col1.AutoIncrement     = true;
            _col1.AutoIncrementSeed = 0;
            _col1.AutoIncrementStep = 1;
            _col1.Unique            = true;
            _col1.ReadOnly          = true;
            _col1.AllowDBNull       = true;
            // other Base-Data:
            // ================
            //
            // Display-Name / Username
            DataColumn _col2 = new DataColumn("colUsername", System.Type.GetType("System.String"));

            if ((Index == IndexColumn.Username) || (Index == IndexColumn.UserAndNT))
            {
                _col2.Unique = true;
            }
            // Password for User
            DataColumn _col3 = new DataColumn("colPassword", System.Type.GetType("System.String"));
            // User full Name
            DataColumn _col4 = new DataColumn("colFirstName", System.Type.GetType("System.String"));
            DataColumn _col5 = new DataColumn("colLastName", System.Type.GetType("System.String"));
            // NT-Username of User (unique)
            DataColumn _col6 = new DataColumn("colNtUser", System.Type.GetType("System.String"));

            if ((Index == IndexColumn.NT_User) || (Index == IndexColumn.UserAndNT))
            {
                _col6.Unique = true;
            }
            //
            // add Columns to Table
            _tabUsr.Columns.Add(_col1);
            _tabUsr.Columns.Add(_col2);
            _tabUsr.Columns.Add(_col3);
            _tabUsr.Columns.Add(_col4);
            _tabUsr.Columns.Add(_col5);
            _tabUsr.Columns.Add(_col6);
            // add Table to DataSet
            _tds.Tables.Add(_tabUsr);
            // Save DataSet to internal Object
            _int_DataSet = _tds;
            _int_DataSet.AcceptChanges();
        }
Ejemplo n.º 8
0
        //----------------------------------------------------------------------------------------------------
        public static Index[] Index__Get(TableStructure tableStructure)
        {
            AjaxService.ASPdatabaseService.GetSetVal();
            var    rtn = new Dictionary <string, Index>(); // key : indexName_L
            string sql = SQLServer_SQLBuilders.BuildSql__Index_Select(tableStructure);

            using (DbConnectionCommand command = UniversalADO.OpenConnectionCommand(tableStructure.ConnectionId, sql))
            {
                using (DbReaderWrapper reader = command.ExecuteReaderWrapper())
                {
                    while (reader.Read())
                    {
                        string schema      = reader.Get("Schema", "");
                        string tableName   = reader.Get("TableName", "");
                        string indexName   = reader.Get("IndexName", "");
                        string indexName_L = indexName.ToLower();
                        bool   isUnique    = reader.Get("IsUnique", false);

                        int    columnId     = reader.Get("ColumnId", 0);
                        string columnName   = reader.Get("ColumnName", "");
                        bool   isDescending = reader.Get("IsDescending", false);

                        Index index;
                        if (rtn.ContainsKey(indexName_L))
                        {
                            index = rtn[indexName_L];
                        }
                        else
                        {
                            index = new Index();
                            rtn.Add(indexName_L, index);
                            index.ConnectionId = tableStructure.ConnectionId;
                            index.Schema       = schema;
                            index.TableName    = tableName;
                            index.IndexName    = indexName;
                            index.IsUnique     = isUnique;
                            index.Columns      = new IndexColumn[0];
                        }
                        var indexColumnsList = index.Columns.ToList();
                        var indexColumn      = new IndexColumn()
                        {
                            ColumnId      = columnId,
                            ColumnName    = columnName,
                            SortDirection = IndexColumn.E_SortTypes.Ascending
                        };
                        if (isDescending)
                        {
                            indexColumn.SortDirection = IndexColumn.E_SortTypes.Descending;
                        }
                        indexColumnsList.Add(indexColumn);
                        index.Columns = indexColumnsList.ToArray();
                    }
                }
            }
            return(rtn.Values.ToArray());
        }
Ejemplo n.º 9
0
 private void CompareIndexColumns(IndexColumn ic1, IndexColumn ic2)
 {
     Assert.IsNotNull(ic1);
     Assert.IsNotNull(ic2);
     Assert.IsNotNull(ic2.Name);
     Assert.AreEqual(ic1.Name, ic2.Name);
     Assert.AreEqual(ic1.Ascending, ic2.Ascending);
     Assert.AreEqual(ic1.Column.Name, ic2.Column.Name);
     Assert.AreEqual(ic1.Index.Name, ic2.Index.Name);
 }
Ejemplo n.º 10
0
        private static void LoadEntityIndexes(string folder, Entity entity)
        {
            XmlDocument document = null;
            var         fileName = Path.Combine(folder, entity.Name + ".indexes.xml");

            if (!File.Exists(fileName))
            {
                return;
            }
            try
            {
                document = new XmlDocument();
                document.Load(fileName);
            }
            catch (Exception ex)
            {
                //Do Nothing
                MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (XmlNode n in document.DocumentElement)
            {
                var id       = XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid());
                var newIndex = entity.Indexes.FirstOrDefault(x => x.Id == id);
                if (newIndex == null)
                {
                    newIndex = new Index(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                    entity.Indexes.Add(newIndex);
                }
                newIndex.Clustered    = XmlHelper.GetAttributeValue(n, "clustered", newIndex.Clustered);
                newIndex.ImportedName = XmlHelper.GetAttributeValue(n, "importedname", newIndex.ImportedName);
                newIndex.IndexType    = (IndexTypeConstants)XmlHelper.GetAttributeValue(n, "indextype", int.Parse(newIndex.IndexType.ToString("d")));
                newIndex.IsUnique     = XmlHelper.GetAttributeValue(n, "isunique", newIndex.IsUnique);

                var indexColumnsNode = n.SelectSingleNode("indexcolumnset");
                if (indexColumnsNode != null)
                {
                    foreach (XmlNode m in indexColumnsNode.ChildNodes)
                    {
                        id = XmlHelper.GetAttributeValue(m, "id", Guid.NewGuid());
                        var newIndexColumn = newIndex.IndexColumns.FirstOrDefault(x => x.Id == id);
                        if (newIndexColumn == null)
                        {
                            newIndexColumn = new IndexColumn(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                            newIndex.IndexColumns.Add(newIndexColumn);
                        }
                        newIndexColumn.Ascending  = XmlHelper.GetAttributeValue(m, "ascending", newIndexColumn.Ascending);
                        newIndexColumn.FieldID    = XmlHelper.GetAttributeValue(m, "fieldid", newIndexColumn.FieldID);
                        newIndexColumn.SortOrder  = XmlHelper.GetAttributeValue(m, "sortorder", newIndexColumn.SortOrder);
                        newIndexColumn.IsInternal = true;
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public override void Visit(SqlCreateIndex node, IndexColumn item)
        {
            base.Visit(node, item);

            var column = item.Column as TableColumn;

            if (column != null && column.Collation != null)
            {
                context.Output.AppendText(translator.Translate(context, column, TableColumnSection.Collate));
            }
        }
Ejemplo n.º 12
0
        //TODO SIZE
        /// <summary>
        /// Loads columns of an index of a database object.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        internal override IEnumerable <KeyValuePair <string, IndexColumn> > LoadIndexColumns(Index index)
        {
            var sql = @"
SELECT 
	kcu.column_name,
	kcu.ordinal_position,
	c.is_nullable,
	c.is_identity,
	c.udt_name,
	COALESCE(c.character_maximum_length, -1),
	COALESCE(c.numeric_scale, -1),
	COALESCE(c.numeric_precision, -1)
FROM information_schema.key_column_usage  kcu 
INNER JOIN information_schema.columns c ON kcu.table_name = c.table_name AND kcu.column_name=c.column_name
WHERE constraint_catalog ILIKE @databaseName AND constraint_schema ILIKE @schemaName AND kcu.table_name ILIKE @objectName AND constraint_name ILIKE @indexName;";

            using (var cn = OpenConnection())
            {
                using (var cmd = new NpgsqlCommand(sql, cn))
                {
                    cmd.Parameters.Add("@databaseName", NpgsqlTypes.NpgsqlDbType.Varchar, 128).Value = index.TableOrView.DatabaseName;
                    cmd.Parameters.Add("@schemaName", NpgsqlTypes.NpgsqlDbType.Varchar, 128).Value   = index.TableOrView.SchemaName;
                    cmd.Parameters.Add("@objectName", NpgsqlTypes.NpgsqlDbType.Varchar, 128).Value   = index.TableOrView.ObjectName;
                    cmd.Parameters.Add("@indexName", NpgsqlTypes.NpgsqlDbType.Varchar, 128).Value    = index.IndexName;

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var nullable = (StringComparer.InvariantCultureIgnoreCase.Compare(dr.GetString(2), "yes") == 0);
                            var identity = (StringComparer.InvariantCultureIgnoreCase.Compare(dr.GetString(3), "yes") == 0);

                            var ic = new IndexColumn()
                            {
                                ID         = 0,
                                Name       = dr.GetString(0),
                                KeyOrdinal = dr.GetInt32(1),
                                IsIdentity = identity,
                                Ordering   = IndexColumnOrdering.Ascending
                            };

                            ic.DataType = GetTypeFromProviderSpecificName(
                                dr.GetString(4),
                                Convert.ToInt32(dr.GetValue(5)),
                                Convert.ToByte(dr.GetValue(6)),
                                Convert.ToByte(dr.GetValue(7)),
                                nullable);

                            yield return(new KeyValuePair <string, IndexColumn>(ic.Name, ic));
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private void addButton_Click(object sender, EventArgs e)
        {
            Index       index = table.CreateIndexWithUniqueName(false);
            IndexColumn ic    = new IndexColumn();

            ic.OwningIndex = index;
            ic.ColumnName  = table.Columns[0].ColumnName;
            ic.SortOrder   = IndexSortOrder.Ascending;
            index.Columns.Add(ic);
            table.Indexes.Add(index);
            indexList.SelectedIndex = indexList.Items.Add(index.Name);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Loads columns of an index of a database object.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        internal override IEnumerable <KeyValuePair <string, IndexColumn> > LoadIndexColumns(Index index)
        {
            var sql = @"
SELECT c.column_name,
       kcu.ordinal_position,
       t.auto_increment,
       c.data_type,
       COALESCE(character_maximum_length, -1) AS `max_length`,
       COALESCE(numeric_scale, -1) AS `scale`,
       COALESCE(numeric_precision, -1) AS `precision`,
       c.is_nullable
FROM information_schema.key_column_usage kcu 
INNER JOIN information_schema.columns c ON kcu.table_schema = c.table_schema AND kcu.table_name = c.table_name AND kcu.column_name = c.column_name
INNER JOIN information_schema.tables t ON kcu.table_schema = t.table_schema AND kcu.table_name = t.table_name
WHERE t.table_schema LIKE @databaseName AND kcu.table_name LIKE @tableName AND kcu.constraint_name LIKE @indexName;";

            using (var cn = OpenConnection())
            {
                using (var cmd = new MySqlCommand(sql, cn))
                {
                    cmd.Parameters.Add("@databaseName", MySqlDbType.VarChar, 128).Value = index.DatabaseName;
                    cmd.Parameters.Add("@tableName", MySqlDbType.VarChar, 128).Value    = index.TableOrView.ObjectName;
                    cmd.Parameters.Add("@indexName", MySqlDbType.VarChar, 128).Value    = index.ObjectName;

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var nullable = (StringComparer.InvariantCultureIgnoreCase.Compare(dr.GetString(7), "yes") == 0);

                            var ic = new IndexColumn()
                            {
                                ID         = 0,
                                Name       = dr.GetString(0),
                                KeyOrdinal = dr.GetInt32(1),
                                Ordering   = IndexColumnOrdering.Ascending,
                                IsIdentity = dr.IsDBNull(7) ? false : true
                            };

                            ic.DataType = GetTypeFromProviderSpecificName(
                                dr.GetString(3),
                                dr.GetInt64(4) > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(dr.GetInt64(4)),
                                Convert.ToByte(dr.GetValue(5)),
                                Convert.ToByte(dr.GetValue(6)),
                                nullable);

                            yield return(new KeyValuePair <string, IndexColumn>(ic.Name, ic));
                        }
                    }
                }
            }
        }
Ejemplo n.º 15
0
 private void okButton_Click(object sender, EventArgs e)
 {
     indexColumns.Clear();
     foreach (IndexColumnGridRow row in gridRows)
     {
         if (String.IsNullOrEmpty(row.ColumnName))
         {
             continue;
         }
         IndexColumn ic = new IndexColumn();
         ic.ColumnName = row.ColumnName;
         ic.SortOrder  = (IndexSortOrder)Enum.Parse(typeof(IndexSortOrder), row.SortOrder);
         indexColumns.Add(ic);
     }
 }
Ejemplo n.º 16
0
        private string GetColumnControlId()
        {
            string controlId = "";

            if (IndexColumn >= 0 && IndexColumn <= 9)
            {
                controlId = "ctl0" + IndexColumn.ToString();
            }
            if (IndexColumn >= 10 && IndexColumn <= 99)
            {
                controlId = "ctl" + IndexColumn.ToString();
            }

            return(controlId);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Loads columns of an index of a database object.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        internal override IEnumerable <KeyValuePair <string, IndexColumn> > LoadIndexColumns(Index index)
        {
            var sql = @"
SELECT ic.column_id, ic.key_ordinal, c.name, ic.is_descending_key, t.name, c.max_length, c.scale, c.precision, c.is_nullable, c.is_identity
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic 
    ON i.object_id = ic.object_id AND i.index_id = ic.index_id
INNER JOIN sys.columns AS c 
    ON ic.object_id = c.object_id AND c.column_id = ic.column_id
INNER JOIN sys.types t ON t.user_type_id = c.user_type_id
WHERE i.name = @indexName
ORDER BY ic.key_ordinal";

            using (var cn = OpenConnection())
            {
                using (var cmd = new SqlCommand(sql, cn))
                {
                    cmd.Parameters.Add("@indexName", SqlDbType.NVarChar, 128).Value = index.IndexName;

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var ic = new IndexColumn()
                            {
                                ID         = dr.GetInt32(0),
                                KeyOrdinal = dr.GetByte(1),
                                Name       = dr.GetString(2),
                                Ordering   = dr.GetBoolean(3) ? IndexColumnOrdering.Descending : IndexColumnOrdering.Ascending,
                                IsIdentity = dr.GetBoolean(8),
                            };

                            ic.DataType = GetTypeFromProviderSpecificName(
                                dr.GetString(4),
                                Convert.ToInt32(dr.GetValue(5)),
                                Convert.ToByte(dr.GetValue(6)),
                                Convert.ToByte(dr.GetValue(7)),
                                dr.GetBoolean(9));

                            yield return(new KeyValuePair <string, IndexColumn>(ic.Name, ic));
                        }
                    }
                }
            }
        }
        public void GetIndexColumns(Database db, Table table, Index index)
        {
            SqlCommand qry = new SqlCommand(
                "select " +
                "  c.name, " +
                "  k.is_descending_key " +
                "from " +
                "  sys.index_columns k " +
                "    inner join syscolumns c on " +
                "      c.id = k.object_id and " +
                "      c.colid = k.column_id " +
                "    inner join sysobjects o on " +
                "      k.object_id = o.id " +
                "    inner join sysindexes i on " +
                "      i.id = k.object_id and " +
                "      i.indid = k.index_id  " +
                "where " +
                "  o.uid = 1 and " +
                "  o.name = @TableName and " +
                "  i.name = @IndexName " +
                "order by " +
                "  k.index_column_id ", SqlConn);
            SqlDataAdapter dat = new SqlDataAdapter();

            dat.SelectCommand = qry;
            qry.Parameters.Add("@TableName", SqlDbType.VarChar).Value = table.TableName;
            qry.Parameters.Add("@IndexName", SqlDbType.VarChar).Value = index.IndexName;
            DataSet ds = new DataSet();

            dat.Fill(ds);

            foreach (DataRow r2 in ds.Tables[0].Rows)
            {
                IndexColumn c = new IndexColumn();
                c.Column = (string)r2[0];
                c.Order  = ((IndexColumn.EnumOrder)Convert.ToInt32(r2[1]));
                if (c == null)
                {
                    throw new Exception("Não foi localizada a coluna " + (string)r2[0] + " do índice " + table.TableName + "." + index.IndexName);
                }
                index.Columns.Add(c);
            }
        }
Ejemplo n.º 19
0
        private void OnPrimaryKey(object sender, EventArgs e)
        {
            OleMenuCommand primaryKey = sender as OleMenuCommand;

            foreach (Column c in Columns)
            {
                c.PrimaryKey = false;
            }
            tableNode.Table.DeleteKey(null);

            // if not checked then we are setting the key columns
            if (!primaryKey.Checked)
            {
                Index index = tableNode.Table.CreateIndexWithUniqueName(true);

                List <int> rows = new List <int>();

                foreach (DataGridViewRow row in columnGrid.SelectedRows)
                {
                    rows.Add(row.Index);
                }
                if (columnGrid.SelectedRows.Count == 0)
                {
                    rows.Add(columnGrid.CurrentCell.RowIndex);
                }
                foreach (int row in rows)
                {
                    Columns[row].PrimaryKey = true;
                    IndexColumn ic = new IndexColumn();
                    ic.OwningIndex = index;
                    ic.ColumnName  = Columns[row].ColumnName;
                    ic.SortOrder   = IndexSortOrder.Ascending;
                    index.Columns.Add(ic);
                }
                if (index.Columns.Count > 0)
                {
                    Indexes.Add(index);
                }
            }
            columnGrid.Refresh();
        }
Ejemplo n.º 20
0
        public void Refresh()
        {
            OracleCommand    cmd = new OracleCommand(ALL_IND_COLUMNS, conn);
            OracleDataReader odr = cmd.ExecuteReader();

            if (!odr.HasRows)
            {
                return;
            }

            // purge old data
            columns.Clear();

            while (odr.Read())
            {
                IndexColumn column = LoadColumn(odr);
                columns.Add(column);
            }

            // notify
        }
Ejemplo n.º 21
0
        private static void LoadEntityIndexes(Entity entity, DiskModelYaml diskModel)
        {
            var entityYaml = diskModel.Entities.FirstOrDefault(x => x.Id == entity.Id);

            if (entityYaml == null)
            {
                return;
            }
            foreach (var indexNode in entityYaml.Indexes)
            {
                var newId    = indexNode.Id; //Guid.NewGuid();
                var newIndex = entity.Indexes.FirstOrDefault(x => x.Id == newId);
                if (newIndex == null)
                {
                    newIndex = new Index(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, newId) });
                    entity.Indexes.Add(newIndex);
                }
                newIndex.Clustered    = indexNode.Clustered;
                newIndex.ImportedName = indexNode.ImportedName;
                newIndex.IndexType    = (IndexTypeConstants)indexNode.IndexType;
                newIndex.IsUnique     = indexNode.IsUnique;

                var loopIndex = 0;
                foreach (var indexColumnNode in indexNode.Fields)
                {
                    var newId2         = Guid.NewGuid(); //indexColumnNode.Id
                    var newIndexColumn = newIndex.IndexColumns.FirstOrDefault(x => x.Id == newId2);
                    if (newIndexColumn == null)
                    {
                        newIndexColumn = new IndexColumn(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, newId2) });
                        newIndex.IndexColumns.Add(newIndexColumn);
                    }
                    newIndexColumn.Ascending  = indexColumnNode.Ascending;
                    newIndexColumn.FieldID    = indexColumnNode.FieldId;
                    newIndexColumn.SortOrder  = loopIndex++;
                    newIndexColumn.IsInternal = true;
                }
            }
        }
Ejemplo n.º 22
0
    private static IndexSchema BuildIndexSchema(string indexName, string desc, string keys)
    {
        IndexSchema indexSchema = new IndexSchema();

        indexSchema.IndexName = indexName;
        string[] array = desc.Split(',');
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i].Trim().Contains("unique"))
            {
                indexSchema.IsUnique = true;
                break;
            }
        }
        indexSchema.Columns = new List <IndexColumn>();
        array = keys.Split(',');
        foreach (string text in array)
        {
            Match match = _keyRx.Match(text.Trim());
            if (!match.Success)
            {
                throw new ApplicationException("Illegal key name [" + text + "] in index [" + indexName + "]");
            }
            string      value       = match.Groups[1].Value;
            IndexColumn indexColumn = new IndexColumn();
            indexColumn.ColumnName = value;
            if (match.Groups[2].Success)
            {
                indexColumn.IsAscending = false;
            }
            else
            {
                indexColumn.IsAscending = true;
            }
            indexSchema.Columns.Add(indexColumn);
        }
        return(indexSchema);
    }
        /// <summary>
        /// Builds an index schema object from the specified components (Read from SQL Server).
        /// </summary>
        /// <param name="indexName">The name of the index</param>
        /// <param name="desc">The description of the index</param>
        /// <param name="keys">Key columns that are part of the index.</param>
        /// <returns>An index schema object that represents our knowledge of the index</returns>
        private IndexSchema BuildIndexSchema(string indexName, string desc, string keys)
        {
            IndexSchema res = new IndexSchema();

            res.IndexName = indexName;

            // Determine if this is a unique index or not.
            string[] descParts = desc.Split(',');
            foreach (string p in descParts)
            {
                if (p.Trim().Contains("unique"))
                {
                    res.IsUnique = true;
                    break;
                }
            }

            // Get all key names and check if they are ASCENDING or DESCENDING
            res.Columns = new List <IndexColumn>();
            string[] keysParts = keys.Split(',');
            foreach (string p in keysParts)
            {
                Match m = _keyRx.Match(p.Trim());
                if (!m.Success)
                {
                    throw new ApplicationException("Illegal key name [" + p + "] in index [" + indexName + "]");
                }

                string      key = m.Groups[1].Value;
                IndexColumn ic  = new IndexColumn();
                ic.ColumnName  = key;
                ic.IsAscending = !m.Groups[2].Success;

                res.Columns.Add(ic);
            }
            return(res);
        }
Ejemplo n.º 24
0
        internal protected string GetFulltextVector(SqlCompilerContext context, FullTextIndex index)
        {
            var sb = new StringBuilder();

            sb.Append("(");
            var languageGroups = index
                                 .Columns
                                 .SelectMany(column => column.Languages, (column, language) => new { column, language })
                                 .GroupBy(pair => pair.language, pair => pair.column)
                                 .ToList();

            for (int i = 0; i < languageGroups.Count; i++)
            {
                if (i != 0)
                {
                    sb.Append(" || ");
                }
                var group   = languageGroups[i];
                var columns = group.ToList();
                sb.Append("to_tsvector('");
                sb.Append(group.Key.Name);
                sb.Append("'::regconfig, ");
                for (int j = 0; j < columns.Count; j++)
                {
                    if (j != 0)
                    {
                        sb.Append(" || ' '::text");
                    }
                    IndexColumn column = columns[j];
                    sb.AppendFormat("({0})::text", QuoteIdentifier(column.Name));
                }
                sb.Append(")");
            }
            sb.Append(")");
            return(sb.ToString());
        }
Ejemplo n.º 25
0
        public SchemaInfo GetSchemaInfo(SchemaDesignerInfo schemaDesignerInfo)
        {
            SchemaInfo schemaInfo = new SchemaInfo();

            Table table = new Table();

            ObjectHelper.CopyProperties(schemaDesignerInfo.TableDesignerInfo, table);

            schemaInfo.Tables.Add(table);

            #region Columns
            TablePrimaryKey primaryKey = null;

            foreach (TableColumnDesingerInfo column in schemaDesignerInfo.TableColumnDesingerInfos)
            {
                TableColumn tableColumn = new TableColumn();
                ObjectHelper.CopyProperties(column, tableColumn);

                if (!tableColumn.IsUserDefined)
                {
                    ColumnManager.SetColumnLength(this.dbInterpreter.DatabaseType, tableColumn, column.Length);
                }

                if (column.IsPrimary)
                {
                    if (primaryKey == null)
                    {
                        primaryKey = new TablePrimaryKey()
                        {
                            Owner = table.Owner, TableName = table.Name, Name = IndexManager.GetPrimaryKeyDefaultName(table)
                        };
                    }

                    IndexColumn indexColumn = new IndexColumn()
                    {
                        ColumnName = column.Name, IsDesc = false, Order = primaryKey.Columns.Count + 1
                    };

                    if (!schemaDesignerInfo.IgnoreTableIndex)
                    {
                        TableIndexDesignerInfo indexDesignerInfo = schemaDesignerInfo.TableIndexDesingerInfos
                                                                   .FirstOrDefault(item => item.Type == IndexType.Primary.ToString() && item.Columns.Any(t => t.ColumnName == column.Name));

                        if (indexDesignerInfo != null)
                        {
                            primaryKey.Name    = indexDesignerInfo.Name;
                            primaryKey.Comment = indexDesignerInfo.Comment;

                            IndexColumn columnInfo = indexDesignerInfo.Columns.FirstOrDefault(item => item.ColumnName == column.Name);

                            if (columnInfo != null)
                            {
                                indexColumn.IsDesc = columnInfo.IsDesc;
                            }

                            if (indexDesignerInfo.ExtraPropertyInfo != null)
                            {
                                primaryKey.Clustered = indexDesignerInfo.ExtraPropertyInfo.Clustered;
                            }
                        }
                    }

                    primaryKey.Columns.Add(indexColumn);
                }

                TableColumnExtraPropertyInfo extralProperty = column.ExtraPropertyInfo;

                if (column.IsIdentity)
                {
                    if (extralProperty != null)
                    {
                        table.IdentitySeed      = extralProperty.Seed;
                        table.IdentityIncrement = extralProperty.Increment;
                    }
                    else
                    {
                        table.IdentitySeed      = 1;
                        table.IdentityIncrement = 1;
                    }
                }

                if (extralProperty?.Expression != null)
                {
                    tableColumn.ComputeExp = extralProperty.Expression;
                }

                schemaInfo.TableColumns.Add(tableColumn);
            }

            if (primaryKey != null)
            {
                schemaInfo.TablePrimaryKeys.Add(primaryKey);
            }
            #endregion

            #region Indexes
            if (!schemaDesignerInfo.IgnoreTableIndex)
            {
                foreach (TableIndexDesignerInfo indexDesignerInfo in schemaDesignerInfo.TableIndexDesingerInfos)
                {
                    if (!indexDesignerInfo.IsPrimary)
                    {
                        TableIndex index = new TableIndex()
                        {
                            Owner = indexDesignerInfo.Owner, TableName = indexDesignerInfo.TableName
                        };
                        index.Name = indexDesignerInfo.Name;

                        index.IsUnique  = indexDesignerInfo.Type == IndexType.Unique.ToString();
                        index.Clustered = indexDesignerInfo.Clustered;
                        index.Comment   = indexDesignerInfo.Comment;

                        index.Columns.AddRange(indexDesignerInfo.Columns);

                        int order = 1;
                        index.Columns.ForEach(item => { item.Order = order++; });

                        schemaInfo.TableIndexes.Add(index);
                    }
                }
            }
            #endregion

            #region Foreign Keys
            if (!schemaDesignerInfo.IgnoreTableForeignKey)
            {
                foreach (TableForeignKeyDesignerInfo keyDesignerInfo in schemaDesignerInfo.TableForeignKeyDesignerInfos)
                {
                    TableForeignKey foreignKey = new TableForeignKey()
                    {
                        Owner = keyDesignerInfo.Owner, TableName = keyDesignerInfo.TableName
                    };
                    foreignKey.Name = keyDesignerInfo.Name;

                    foreignKey.ReferencedTableName = keyDesignerInfo.ReferencedTableName;
                    foreignKey.UpdateCascade       = keyDesignerInfo.UpdateCascade;
                    foreignKey.DeleteCascade       = keyDesignerInfo.DeleteCascade;
                    foreignKey.Comment             = keyDesignerInfo.Comment;

                    foreignKey.Columns.AddRange(keyDesignerInfo.Columns);

                    int order = 1;
                    foreignKey.Columns.ForEach(item => { item.Order = order++; });

                    schemaInfo.TableForeignKeys.Add(foreignKey);
                }
            }
            #endregion

            #region Constraint
            if (!schemaDesignerInfo.IgnoreTableConstraint)
            {
                foreach (TableConstraintDesignerInfo constraintDesignerInfo in schemaDesignerInfo.TableConstraintDesignerInfos)
                {
                    TableConstraint constraint = new TableConstraint()
                    {
                        Owner = constraintDesignerInfo.Owner, TableName = constraintDesignerInfo.TableName
                    };
                    constraint.Name       = constraintDesignerInfo.Name;
                    constraint.Definition = constraintDesignerInfo.Definition;
                    constraint.Comment    = constraintDesignerInfo.Comment;

                    schemaInfo.TableConstraints.Add(constraint);
                }
            }
            #endregion

            return(schemaInfo);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// (initial) load Data from File / DataSource
        /// </summary>
        /// <returns>TRUE on success, FALSE on error</returns>
        private bool _loadData(string FileName)
        {
            // something set in FileName? Exit if not...
            if (FileName.Trim() == "")
            {
                return(false);
            }
            // read Data from file
            string _fileContent;

            try
            {
                _fileContent = System.IO.File.ReadAllText(FileName, System.Text.Encoding.UTF8);
            }
            catch (Exception)
            {
                return(false);
            }
            // read Data from file
            StringBuilder _cData  = new StringBuilder();  // Element for ciphered Data
            IndexColumn   _fIndex = IndexColumn.Username; // Username as Default-index

            _set_Version = "";                            // init with default-version
            // split into lines
            string[] _lines = _fileContent.Split(Environment.NewLine.ToCharArray());
            // cleanup empty lines
            List <string> _cleaned = new List <string>();

            foreach (string _rawLine in _lines)
            {
                if (_rawLine.Trim() != "")
                {
                    _cleaned.Add(_rawLine);
                }
            }
            // check Version
            bool _dataActive = false; // reminder for active data-block

            foreach (string _line in _cleaned)
            {
                // detect headline
                if (_line.Trim().ToLower().StartsWith("cux"))
                {
                    // nothing for the moment...
                }
                // detect version
                if (_line.Trim().ToLower().StartsWith("version"))
                {
                    if (!_CheckFileVersion(_line.Trim())) // if invalid version
                    {
                        return(false);                    // exit
                    }
                }
                // detect index
                if (_line.Trim().ToLower().StartsWith("index"))
                {
                    _fIndex = _GetFileIndex(_line.Trim());
                }

                // detect end
                if (_line.Trim().ToLower() == "-| end |-")
                {
                    _dataActive = false;
                }
                // save data if active
                if (_dataActive)
                {
                    _cData.Append(_line.Trim());
                }
                // detect start
                if (_line.Trim().ToLower() == "-| start |-")
                {
                    _dataActive = true;
                }
            }
            // decrypt data
            DDPro.Software.Net20.Library.Rijndael _cipher = new DDPro.Software.Net20.Library.Rijndael(System.Text.Encoding.UTF8);
            string _xmlString;

            try
            {
                _xmlString = _cipher.EasyDecrypt(_cData.ToString(), _set_DataCipherPhrase);
            }
            catch (Exception)
            {
                return(false);
            }
            // initialize the internal DataSet by used Index-Column(s)
            _initializeDataSet(_fIndex);
            // apply XML to dataset
            try
            {
                System.IO.TextReader _dsData = new System.IO.StringReader(_xmlString);
                _int_DataSet.ReadXml(_dsData);
                _int_DataSet.AcceptChanges();
            }
            catch (Exception)
            {
                return(false);
            }
            // everything was ok
            return(true);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// initialize a new Instance including defined Index and Path
 /// </summary>
 /// <param name="Index">the IndexColumn to use for this Instance</param>
 /// <param name="File">full Path to the .cux-File to use</param>
 public UserList(IndexColumn Index, string File)
 {
     _initializeDataSet(Index);
     _int_Path    = File;
     _set_Version = "";
 }
Ejemplo n.º 28
0
 /// <summary>
 /// initialize a new Instance with defined Index
 /// </summary>
 /// <param name="Index">the IndexColumn to use for this Instance</param>
 public UserList(IndexColumn Index)
 {
     _initializeDataSet(Index);
     _int_Path    = "";
     _set_Version = "";
 }
        private static void LoadEntityIndexes(string folder, Entity entity)
        {
            XmlDocument document = null;
            var fileName = Path.Combine(folder, entity.Name + ".indexes.xml");
            if (!File.Exists(fileName)) return;
            try
            {
                document = new XmlDocument();
                document.Load(fileName);
            }
            catch (Exception ex)
            {
                //Do Nothing
                MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (XmlNode n in document.DocumentElement)
            {
                var id = XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid());
                var newIndex = entity.Indexes.FirstOrDefault(x => x.Id == id);
                if (newIndex == null)
                {
                    newIndex = new Index(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                    entity.Indexes.Add(newIndex);
                }
                newIndex.Clustered = XmlHelper.GetAttributeValue(n, "clustered", newIndex.Clustered);
                newIndex.ImportedName = XmlHelper.GetAttributeValue(n, "importedname", newIndex.ImportedName);
                newIndex.IndexType = (IndexTypeConstants)XmlHelper.GetAttributeValue(n, "indextype", int.Parse(newIndex.IndexType.ToString("d")));
                newIndex.IsUnique = XmlHelper.GetAttributeValue(n, "isunique", newIndex.IsUnique);

                var indexColumnsNode = n.SelectSingleNode("indexcolumnset");
                if (indexColumnsNode != null)
                {
                    foreach (XmlNode m in indexColumnsNode.ChildNodes)
                    {
                        id = XmlHelper.GetAttributeValue(m, "id", Guid.NewGuid());
                        var newIndexColumn = newIndex.IndexColumns.FirstOrDefault(x => x.Id == id);
                        if (newIndexColumn == null)
                        {
                            newIndexColumn = new IndexColumn(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                            newIndex.IndexColumns.Add(newIndexColumn);
                        }
                        newIndexColumn.Ascending = XmlHelper.GetAttributeValue(m, "ascending", newIndexColumn.Ascending);
                        newIndexColumn.FieldID = XmlHelper.GetAttributeValue(m, "fieldid", newIndexColumn.FieldID);
                        newIndexColumn.SortOrder = XmlHelper.GetAttributeValue(m, "sortorder", newIndexColumn.SortOrder);
                        newIndexColumn.IsInternal = true;
                    }
                }
            }
        }
 /// <inheritdoc/>
 /// <exception cref="NotSupportedException">Method is not supported.</exception>
 protected override IPathNode VisitIndexColumn(IndexColumn indexColumn)
 {
     throw new NotSupportedException();
 }
        List<TableIndex> LoadIndices(string tableName)
        {
            var result=new List<TableIndex>();
		
            using (var cmd1=this._factory.CreateCommand())
            {			
                cmd1.Connection=this._connection;
                cmd1.CommandText=String.Format(INDEX_SQL,tableName);
                using (IDataReader rdr1=cmd1.ExecuteReader())
                {
                    while(rdr1.Read())
                    {			
                        TableIndex indx=new TableIndex();
                        indx.Name=rdr1["name"].ToString();					
                        indx.SQL=rdr1["sql"].ToString();
                        indx.IndexColumns = new List<IndexColumn>();
                        indx.IsUnique = indx.SQL.ToUpper().Contains("UNIQUE");
                        using (var cmd2=this._factory.CreateCommand())
                        {
                            cmd2.Connection=this._connection;
                            cmd2.CommandText=String.Format(INDEX_INFO_SQL,indx.Name);			            
                            using (IDataReader rdr2=cmd2.ExecuteReader())
                            {
                                while(rdr2.Read())
                                {	IndexColumn col = new IndexColumn();								
                                    col.Name = rdr2["name"].ToString();
                                    indx.IndexColumns.Add(col);
                                }
                            }
                        }
                        result.Add(indx);
                    }
                }
            }
            return result;
        }
Ejemplo n.º 32
0
        public void Fill(Database database, string connectionString)
        {
            int indexid = 0;
            int parentId = 0;
            bool change = false;
            string type;
            ISchemaBase parent = null;
            root.RaiseOnReading(new ProgressEventArgs("Reading Index...", Constants.READING_INDEXES));
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand(IndexSQLCommand.Get(database.Info.Version), conn))
                {
                    conn.Open();
                    command.CommandTimeout = 0;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        Index item = null;
                        while (reader.Read())
                        {
                            root.RaiseOnReadingOne(reader["Name"]);
                            type = reader["ObjectType"].ToString().Trim();
                            if (parentId != (int)reader["object_id"])
                            {
                                parentId = (int)reader["object_id"];
                                if (type.Equals("V"))
                                    parent = database.Views.Find(parentId);
                                else
                                    parent = database.Tables.Find(parentId);
                                change = true;
                            }
                            else
                                change = false;
                            if ((indexid != (int)reader["Index_id"]) || (change))
                            {
                                item = new Index(parent);
                                item.Name = reader["Name"].ToString();
                                item.Owner = parent.Owner;
                                item.Type = (Index.IndexTypeEnum)(byte)reader["type"];
                                item.Id = (int)reader["Index_id"];
                                item.IgnoreDupKey = (bool)reader["ignore_dup_key"];
                                item.IsAutoStatistics = (bool)reader["NoAutomaticRecomputation"];
                                item.IsDisabled = (bool)reader["is_disabled"];
                                item.IsPrimaryKey = (bool)reader["is_primary_key"];
                                item.IsUniqueKey = (bool)reader["is_unique"];
                                if (database.Options.Ignore.FilterIndexRowLock)
                                {
                                    item.AllowPageLocks = (bool)reader["allow_page_locks"];
                                    item.AllowRowLocks = (bool)reader["allow_row_locks"];
                                }
                                if (database.Options.Ignore.FilterIndexFillFactor)
                                {
                                    item.FillFactor = (byte)reader["fill_factor"];
                                    item.IsPadded = (bool)reader["is_padded"];
                                }
                                if ((database.Options.Ignore.FilterTableFileGroup) && (item.Type != Index.IndexTypeEnum.XML))
                                    item.FileGroup = reader["FileGroup"].ToString();

                                if ((database.Info.Version == DatabaseInfo.VersionTypeEnum.SQLServer2008) && (database.Options.Ignore.FilterIndexFilter))
                                {
                                    item.FilterDefintion = reader["FilterDefinition"].ToString();
                                }
                                indexid = (int)reader["Index_id"];
                                if (type.Equals("V"))
                                    ((View)parent).Indexes.Add(item);
                                else
                                    ((Table)parent).Indexes.Add(item);
                            }
                            IndexColumn ccon = new IndexColumn(item.Parent);
                            ccon.Name = reader["ColumnName"].ToString();
                            ccon.IsIncluded = (bool)reader["is_included_column"];
                            ccon.Order = (bool)reader["is_descending_key"];
                            ccon.Id = (int)reader["column_id"];
                            ccon.KeyOrder = (byte)reader["key_ordinal"];
                            ccon.DataTypeId = (int)reader["user_type_id"];
                            if ((!ccon.IsIncluded) || (ccon.IsIncluded && database.Options.Ignore.FilterIndexIncludeColumns))
                                item.Columns.Add(ccon);
                        }
                    }
                }
            }
        }
Ejemplo n.º 33
0
        public static void ImportDatabase(nHydrate.Dsl.nHydrateModel model, Store store, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, nHydrate.DataImport.Database database)
        {
            ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = true;
            model.IsLoading = true;
            var pkey = ProgressHelper.ProgressingStarted("Processing Import...", true);

            model.IsLoading = true;
            try
            {
                var addedEntities   = new List <Entity>();
                var diagramEntities = model.Entities.ToList();
                var diagramViews    = model.Views.ToList();
                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    #region TEMP TEMP - RESET THE PARAMETERS AND FIELDS OF ALL NON-ENTITY OBJECTS - USED FOR DEBUGGING

                    //foreach (var entity in model.Entities)
                    //{
                    //  var table = database.EntityList.FirstOrDefault(x => x.Name == entity.Name);
                    //  if (table != null)
                    //  {
                    //    foreach (var field in entity.Fields)
                    //    {
                    //      var column = table.FieldList.FirstOrDefault(x => x.Name == field.Name);
                    //      if (column != null)
                    //      {
                    //        field.SortOrder = column.SortOrder;
                    //      }
                    //    }
                    //  }
                    //  entity.Fields.Sort((x, y) => (x.SortOrder < y.SortOrder ? -1 : 0));
                    //}

                    //foreach (var view in database.ViewList)
                    //{
                    //  var newView = diagramViews.FirstOrDefault(x => x.Name.ToLower() == view.Name.ToLower());
                    //  if (newView != null)
                    //  {
                    //    foreach (var field in view.FieldList)
                    //    {
                    //      var newField = newView.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var index in database.IndexList.Where(x => x.FieldList.Count == 1 && !x.FieldList.First().IsDescending))
                    //{
                    //  var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                    //  if (entity != null)
                    //  {
                    //    var field = entity.Fields.FirstOrDefault(x => x.Name == index.FieldList.First().Name);
                    //    if (field != null)
                    //    {
                    //      field.IsIndexed = true;
                    //    }
                    //  }
                    //}

                    //transaction.Commit();
                    //return;

                    #endregion

                    #region Load Entities

                    var addedChangedEntities = database.EntityList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified).ToList();

                    #region Entities

                    foreach (var entity in addedChangedEntities)
                    {
                        var newEntity = diagramEntities.FirstOrDefault(x => x.Id == entity.ID);
                        if (newEntity == null)
                        {
                            newEntity = diagramEntities.FirstOrDefault(x => x.Name.ToLower() == entity.Name.ToLower());
                        }
                        if (newEntity == null)
                        {
                            newEntity = new Entity(model.Partition)
                            {
                                Name = entity.Name
                            };
                            model.Entities.Add(newEntity);
                            addedEntities.Add(newEntity);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newEntity.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newEntity.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newEntity.Name))
                            {
                                newEntity.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifier(newEntity.Name, string.Empty);
                            }
                        }
                        newEntity.AllowCreateAudit = entity.AllowCreateAudit;
                        newEntity.AllowModifyAudit = entity.AllowModifyAudit;
                        newEntity.AllowTimestamp   = entity.AllowTimestamp;
                        newEntity.IsTenant         = entity.IsTenant;
                        newEntity.Name             = entity.Name;
                        newEntity.Schema           = entity.Schema;

                        PopulateFields(model, entity, newEntity);

                        //Order columns by database
                        //newEntity.Fields.Sort((x, y) => x.Name.CompareTo(y.Name));
                        newEntity.Fields.Sort((x, y) => (x.SortOrder < y.SortOrder ? -1 : 0));
                    }

                    #endregion

                    //Remove the ones that need to be remove
                    model.Entities.Remove(x => database.EntityList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Load Relations
                    if (!database.IgnoreRelations)
                    {
                        var allRelationElementList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements
                                                     .ToList()
                                                     .Where(x => x is EntityHasEntities)
                                                     .ToList()
                                                     .Cast <EntityHasEntities>()
                                                     .ToList();

                        foreach (var entity in database.EntityList)
                        {
                            foreach (var relation in entity.RelationshipList)
                            {
                                var isNewConnection = false;
                                var connection      = allRelationElementList.FirstOrDefault(x => x.ImportData == relation.ImportData);

                                //Now verify that this is the table has not been renamed
                                if (connection != null)
                                {
                                    //If the table names no longer match then create a new relation
                                    if (!connection.ChildEntity.Name.Match(relation.TargetEntity.Name) || !connection.ParentEntity.Name.Match(relation.SourceEntity.Name))
                                    {
                                        connection.ImportData = string.Empty;
                                        connection            = null;
                                    }
                                }

                                if (connection == null)
                                {
                                    //try to find this relation by table/fields/role
                                    connection = allRelationElementList.FirstOrDefault(x => x.GetCorePropertiesHash() == relation.CorePropertiesHash);
                                }
                                var parent = model.Entities.FirstOrDefault(x => x.Name == relation.SourceEntity.Name);
                                var child  = model.Entities.FirstOrDefault(x => x.Name == relation.TargetEntity.Name);
                                if (connection == null)
                                {
                                    var existingRelation = diagram.NestedChildShapes.FirstOrDefault(x => x.Id == relation.ID);
                                    if (existingRelation == null)
                                    {
                                        if (child != null && parent != null)
                                        {
                                            //var currentList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
                                            //parent.ChildEntities.Add(child);
                                            //var updatedList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
                                            //var last = updatedList.Last();
                                            //updatedList.RemoveAll(x => currentList.Contains(x));
                                            //connection = updatedList.First() as EntityHasEntities;
                                            //if (connection != last) System.Diagnostics.Debug.Write("");

                                            parent.ChildEntities.Add(child);
                                            connection = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.Last() as EntityHasEntities;

                                            isNewConnection       = true;
                                            connection.ImportData = relation.ImportData;
                                        }
                                    }
                                } //Relation does not exist

                                //Add the relation fields
                                if (parent != null && child != null)
                                {
                                    foreach (var ritem in relation.RelationshipColumnList)
                                    {
                                        var parentField = parent.Fields.FirstOrDefault(x => x.Name == ritem.ParentField.Name);
                                        var childField  = child.Fields.FirstOrDefault(x => x.Name == ritem.ChildField.Name);
                                        if (parentField != null && childField != null)
                                        {
                                            //Do not import the role name again.
                                            if (isNewConnection)
                                            {
                                                connection.RoleName = relation.RoleName;
                                                connection.ImportedConstraintName = relation.ConstraintName;
                                            }

                                            var currentRelationField = model.RelationFields.FirstOrDefault(x =>
                                                                                                           x.SourceFieldId == parentField.Id &&
                                                                                                           x.TargetFieldId == childField.Id &&
                                                                                                           x.RelationID == connection.Id);

                                            //Only add if not there already
                                            if (currentRelationField == null)
                                            {
                                                model.RelationFields.Add(
                                                    new RelationField(model.Partition)
                                                {
                                                    SourceFieldId = parentField.Id,
                                                    TargetFieldId = childField.Id,
                                                    RelationID    = connection.Id,
                                                }
                                                    );
                                            }
                                        }
                                    } //Relation Columns
                                }
                            }
                        }
                    }
                    #endregion

                    #region Process Indexes

                    //Only get the single column indexes ascending
                    var isIndexedList = database.IndexList.Where(x => x.FieldList.Count == 1 && !x.FieldList.First().IsDescending).ToList();
                    var allIndexList  = database.IndexList.Where(x => addedChangedEntities.Select(z => z.Name.ToLower()).Contains(x.TableName.ToLower())).ToList();

                    //Delete existing indexes by name. These will be recreated.
                    foreach (var index in allIndexList)
                    {
                        var existing = model.Entities.SelectMany(x => x.Indexes).FirstOrDefault(x => x.ImportedName == index.IndexName);
                        if (existing != null)
                        {
                            existing.Delete();
                        }
                    }

                    //Delete existing IsIndexed indexes with no import names as they will be recreated
                    var existingIsIndexedList = model.Entities.Where(x => addedChangedEntities.Select(z => z.Name.ToLower()).Contains(x.Name.ToLower())).SelectMany(x => x.Indexes).Where(x => x.IsIndexedType).ToList();
                    foreach (var index in isIndexedList)
                    {
                        foreach (var existing in existingIsIndexedList)
                        {
                            if (index.IsMatch(existing))
                            {
                                existing.Delete();
                            }
                        }
                    }

                    //Create all indexes
                    foreach (var index in allIndexList)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                        if (entity != null)
                        {
                            var realFields = entity.Fields.Where(x => index.FieldList.Select(z => z.Name).Contains(x.Name)).ToList();
                            if (realFields.Count > 0)
                            {
                                //Try to get the PK if one exists
                                var   isNew    = true;
                                Index newIndex = null;
                                if (index.IsPrimaryKey)
                                {
                                    newIndex = entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                                    if (newIndex != null)
                                    {
                                        isNew = false;
                                        newIndex.IndexColumns.Clear();
                                    }
                                }

                                //Create an index
                                if (newIndex == null)
                                {
                                    newIndex = new Index(entity.Partition);
                                }

                                newIndex.ParentEntityID = entity.Id;
                                newIndex.ImportedName   = index.IndexName;
                                newIndex.Clustered      = index.Clustered;
                                newIndex.IsUnique       = index.IsUnique;

                                if (index.IsPrimaryKey)
                                {
                                    newIndex.IndexType = IndexTypeConstants.PrimaryKey;
                                }
                                else if (isIndexedList.Contains(index))
                                {
                                    newIndex.IndexType = IndexTypeConstants.IsIndexed;
                                }
                                else
                                {
                                    newIndex.IndexType = IndexTypeConstants.User;
                                }

                                if (isNew)
                                {
                                    entity.Indexes.Add(newIndex);
                                }

                                foreach (var ic in index.FieldList)
                                {
                                    var field = realFields.FirstOrDefault(x => x.Name == ic.Name);
                                    if (field != null)
                                    {
                                        var newIndexColumn = new IndexColumn(entity.Partition);
                                        newIndexColumn.Ascending  = !ic.IsDescending;
                                        newIndexColumn.FieldID    = field.Id;
                                        newIndexColumn.IsInternal = true;
                                        newIndexColumn.SortOrder  = ic.OrderIndex;
                                        newIndex.IndexColumns.Add(newIndexColumn);
                                    }
                                }
                            }
                        }
                    }

                    //Create the special IsIndexed settings
                    //This will not create a new index since it was created above
                    foreach (var index in isIndexedList)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                        if ((entity != null) && addedChangedEntities.Select(z => z.Name.ToLower()).Contains(entity.Name.ToLower()))
                        {
                            var field = entity.Fields.FirstOrDefault(x => x.Name == index.FieldList.First().Name);
                            if (field != null)
                            {
                                field.IsIndexed = true;
                            }
                        }
                    }

                    #endregion

                    #region Add Views

                    foreach (var view in database.ViewList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newView = diagramViews.FirstOrDefault(x => x.Id == view.ID);
                        if (newView == null)
                        {
                            newView = diagramViews.FirstOrDefault(x => x.Name.ToLower() == view.Name.ToLower());
                        }
                        if (newView == null)
                        {
                            newView = new nHydrate.Dsl.View(model.Partition)
                            {
                                Name = view.Name
                            };
                            model.Views.Add(newView);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newView.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newView.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newView.Name))
                            {
                                newView.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifier(newView.Name, string.Empty);
                            }
                        }
                        newView.Name   = view.Name;
                        newView.Schema = view.Schema;
                        newView.SQL    = view.SQL;

                        PopulateFields(model, view, newView);
                    }

                    //Remove the ones that need to be remove
                    model.Views.Remove(x => database.ViewList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                model.IsLoading = false;

                ProgressHelper.ProgressingComplete(pkey);
                ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = false;
                model.IsLoading = false;
            }
        }