Пример #1
0
        /// <summary>
        /// Metadata okuma iþini yapan asýl metod. Sýrayla bütün veritabaný nesnelerini okur.
        /// </summary>
        public void ReadDatabaseMetadata(bool readAllMetadata)
        {
            #region tables and views
            db.Tables = new TableCollection(db);

            // columns
            DataTable dtTables = db.GetDataTable(GetSQLTableList());
            foreach (DataRow drTable in dtTables.Rows)
            {
                Table tbl = new Table();
                tbl.Name = drTable["TABLE_NAME"].ToString();
                tbl.IsView = drTable["TABLE_TYPE"].ToString() == "VIEW";
                db.Tables.Add(tbl);

                DataTable dtColumns = db.GetDataTable(GetSQLColumnList(tbl.Name));
                foreach (DataRow drColumn in dtColumns.Rows)
                {
                    Column f = new Column();
                    f.DefaultValue = drColumn["COLUMN_DEFAULT"].ToString();
                    f.ColumnTypeOriginal = drColumn["DATA_TYPE"].ToString().ToUpperInvariant();
                    f.ColumnType = StringToDbType(f.ColumnTypeOriginal);
                    f.Length = drColumn.IsNull("CHARACTER_MAXiMUM_LENGTH") ? 0 : Convert.ToInt64(drColumn["CHARACTER_MAXiMUM_LENGTH"]);
                    f.IsNullable = drColumn["iS_NULLABLE"].ToString() != "NO";
                    f.Name = drColumn["COLUMN_NAME"].ToString();
                    f.IsAutoIncrement = !string.IsNullOrEmpty(drColumn["iS_AUTO_iNCREMENT"].ToString());

                    tbl.Columns.Add(f);
                }
            }
            #endregion

            #region constraints
            // Con.Name, Con.TableName, Con.Type, Col.ColumnName, Con.RefConstraintName, Con.UpdateRule, Con.DeleteRule
            DataTable dtCons = db.GetDataTable(this.GetSQLConstraintList());
            foreach (DataRow drCon in dtCons.Rows)
            {
                Constraint con = db.Tables[drCon["TableName"].ToString()].Constraints[drCon["Name"].ToString()];
                if (con != null)
                {
                    con.ColumnNames.Add(drCon["ColumnName"].ToString());
                    continue;
                }

                switch (drCon["Type"].ToString())
                {
                    case "FOREIGN KEY":
                        con = new ForeignKeyConstraint();
                        (con as ForeignKeyConstraint).RefConstraintName = drCon["RefConstraintName"].ToString();
                        //(con as ForeignKeyConstraint).RefTableName = drCon["RefConstraintName"].ToString();
                        (con as ForeignKeyConstraint).DeleteRule = drCon["DeleteRule"].ToString();
                        (con as ForeignKeyConstraint).UpdateRule = drCon["UpdateRule"].ToString();
                        break;
                    case "PRIMARY KEY":
                        con = new PrimaryKeyConstraint();
                        break;
                    case "UNIQUE":
                        con = new UniqueConstraint();
                        break;
                    default:
                        throw new Exception("Unknown constraint type: " + drCon["Type"].ToString());
                }
                con.Name = drCon["Name"].ToString();
                con.ColumnNames.Add(drCon["ColumnName"].ToString());

                db.Tables[drCon["TableName"].ToString()].Constraints.Add(con);
            }
            foreach (Table tbl in db.Tables)
                foreach (ForeignKeyConstraint fk in tbl.Constraints.Where(c => c is ForeignKeyConstraint))
                    fk.RefTableName = db.GetConstraint(fk.RefConstraintName).Table.Name;

            #endregion

            if (!readAllMetadata) return; //***

            #region indices
            foreach (Table tbl in db.Tables)
            {
                DataTable dtKeys = db.GetDataTable(@"select
                                                        t.relname as table_name,
                                                        i.relname as index_name,
                                                        array_to_string(array_agg(a.attname), ', ') as index_keys
                                                    from
                                                        pg_class t,
                                                        pg_class i,
                                                        pg_index ix,
                                                        pg_attribute a
                                                    where
                                                        t.oid = ix.indrelid
                                                        and i.oid = ix.indexrelid
                                                        and a.attrelid = t.oid
                                                        and a.attnum = ANY(ix.indkey)
                                                        and t.relkind = 'r'
                                                        and t.relname like '" + tbl.Name + @"%'
                                                    group by
                                                        t.relname,
                                                        i.relname
                                                    order by
                                                        t.relname,
                                                        i.relname;
                                                    ");
                if (dtKeys != null)
                    foreach (DataRow drKey in dtKeys.Rows)
                    {
                        if (db.GetConstraint(drKey["index_name"].ToString()) != null)
                            continue;

                        Index index = new Index();
                        index.Name = drKey["index_name"].ToString();

                        index.ColumnNames = new List<string>();
                        foreach (string columnName in drKey["index_keys"].ToString().Split(','))
                            index.ColumnNames.Add(columnName.Trim().Replace("(-)", ""));

                        tbl.Indices.Add(index);
                    }
            }
            #endregion
        }
Пример #2
0
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void BeginLoadData() {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<ds.DataTable.BeginLoadData|API> %d#\n", ObjectID);
            try {
                if (inDataLoad)
                    return;

                inDataLoad = true;
                Debug.Assert(null == loadIndex, "loadIndex should already be null");
                loadIndex  = null;
                // LoadDataRow may have been called before BeginLoadData and already
                // initialized loadIndexwithOriginalAdded & loadIndexwithCurrentDeleted 

                initialLoad = (Rows.Count == 0);
                if(initialLoad) {
                    SuspendIndexEvents();
                } else {
                    if (primaryKey != null) {
                        loadIndex = primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows);
                    }
                    if(loadIndex != null) {
                        loadIndex.AddRef();
                    }
                }

                if (DataSet != null) {
                    savedEnforceConstraints = DataSet.EnforceConstraints;
                    DataSet.EnforceConstraints = false;
                }
                else {
                    this.EnforceConstraints = false;
                }
            }
            finally{
                Bid.ScopeLeave(ref hscp);
            }
        }
Пример #3
0
        /// <devdoc>
        ///    <para>Finds and updates a specific row. If no matching
        ///       row is found, a new row is created using the given values.</para>
        /// </devdoc>
        public DataRow LoadDataRow(object[] values, LoadOption loadOption) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<ds.DataTable.LoadDataRow|API> %d#, loadOption=%d{ds.LoadOption}\n", ObjectID,  (int)loadOption);
            try {
                Index indextoUse = null;
                if (this.primaryKey != null) {
                    if (loadOption == LoadOption.Upsert) { // CurrentVersion, and Deleted
                        if (loadIndexwithCurrentDeleted == null) {
                            loadIndexwithCurrentDeleted = this.primaryKey.Key.GetSortIndex(DataViewRowState.CurrentRows |DataViewRowState.Deleted);
                            Debug.Assert(loadIndexwithCurrentDeleted != null, "loadIndexwithCurrentDeleted should not be null" );
                            if (loadIndexwithCurrentDeleted != null) {
                                loadIndexwithCurrentDeleted.AddRef();
                            }
                        }
                        indextoUse = loadIndexwithCurrentDeleted;
                    }
                    else {// CurrentVersion, and Deleted : OverwriteRow, PreserveCurrentValues
                        if (loadIndexwithOriginalAdded == null) {
                            loadIndexwithOriginalAdded  = this.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows |DataViewRowState.Added);
                            Debug.Assert(loadIndexwithOriginalAdded != null, "loadIndexwithOriginalAdded should not be null");
                            if (loadIndexwithOriginalAdded != null) {
                                loadIndexwithOriginalAdded.AddRef();
                            }
                        }
                        indextoUse = loadIndexwithOriginalAdded;
                    }
                    // not expecting LiveIndexes to clear the index we use between calls to LoadDataRow
                    Debug.Assert(2 <= indextoUse.RefCount, "bad indextoUse.RefCount");
                }
                if(inDataLoad && !AreIndexEventsSuspended) { // we do not want to fire any listchanged in new Load/Fill
                    SuspendIndexEvents();// so suspend events here(not suspended == table already has some rows initially)
                }

                DataRow dataRow = LoadRow(values, loadOption, indextoUse);// if indextoUse == null, it means we dont have PK,
                                                                          // so LoadRow will take care of just adding the row to end

                return dataRow;
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }
Пример #4
0
 internal DataRow FindByIndex(Index ndx, object[] key) {
     Range range = ndx.FindRecords(key);
     if (range.IsNull) {
         return null;
     }
     return this.recordManager[ndx.GetRecord(range.Min)];
 }
Пример #5
0
        internal DataRow MergeRow(DataRow row, DataRow targetRow, bool preserveChanges, Index idxSearch) {
             if (targetRow == null) {
                targetRow = this.NewEmptyRow();
                targetRow.oldRecord = recordManager.ImportRecord(row.Table, row.oldRecord);
                targetRow.newRecord = targetRow.oldRecord;
                if(row.oldRecord != row.newRecord) {
                    targetRow.newRecord = recordManager.ImportRecord(row.Table, row.newRecord);
                }
                InsertRow(targetRow, -1);
            }
            else {
                // SQLBU 500789: Record Manager corruption during Merge when target row in edit state
                // the newRecord would be freed and overwrite tempRecord (which became the newRecord)
                // this would leave the DataRow referencing a freed record and leaking memory for the now lost record
                int proposedRecord = targetRow.tempRecord; // by saving off the tempRecord, EndEdit won't free newRecord
                targetRow.tempRecord = -1;
                try {
                    DataRowState saveRowState = targetRow.RowState;
                    int saveIdxRecord = (saveRowState == DataRowState.Added) ? targetRow.newRecord : saveIdxRecord = targetRow.oldRecord;
                     int newRecord;
                     int oldRecord;
                    if (targetRow.RowState == DataRowState.Unchanged && row.RowState == DataRowState.Unchanged) {
                        // unchanged row merging with unchanged row
                        oldRecord = targetRow.oldRecord;
                        newRecord = (preserveChanges) ? recordManager.CopyRecord(this, oldRecord, -1) : targetRow.newRecord;
                        oldRecord = recordManager.CopyRecord(row.Table, row.oldRecord, targetRow.oldRecord);
                        SetMergeRecords(targetRow, newRecord, oldRecord, DataRowAction.Change);
                    }
                    else if (row.newRecord == -1) {
                        // Incoming row is deleted
                        oldRecord = targetRow.oldRecord;
                        if (preserveChanges) {
                          newRecord = (targetRow.RowState == DataRowState.Unchanged)? recordManager.CopyRecord(this, oldRecord, -1) : targetRow.newRecord;
                        }
                        else
                            newRecord = -1;
                        oldRecord = recordManager.CopyRecord(row.Table, row.oldRecord, oldRecord);

                        // Change index record, need to update index
                        if (saveIdxRecord != ((saveRowState == DataRowState.Added) ? newRecord : oldRecord)) {
                            SetMergeRecords(targetRow, newRecord, oldRecord, (newRecord == -1) ? DataRowAction.Delete : DataRowAction.Change);
                            idxSearch.Reset();
                            saveIdxRecord = ((saveRowState == DataRowState.Added) ? newRecord : oldRecord);
                        } else {
                            SetMergeRecords(targetRow, newRecord, oldRecord, (newRecord == -1) ? DataRowAction.Delete : DataRowAction.Change);
                        }
                    }
                    else {
                        // incoming row is added, modified or unchanged (targetRow is not unchanged)
                        oldRecord = targetRow.oldRecord;
                        newRecord = targetRow.newRecord;
                        if (targetRow.RowState == DataRowState.Unchanged) {
                            newRecord = recordManager.CopyRecord(this, oldRecord, -1);
                        }
                        oldRecord = recordManager.CopyRecord(row.Table, row.oldRecord, oldRecord);

                        if (!preserveChanges) {
                            newRecord = recordManager.CopyRecord(row.Table, row.newRecord, newRecord);
                        }
                        SetMergeRecords(targetRow, newRecord, oldRecord, DataRowAction.Change);
                    }

                    if (saveRowState == DataRowState.Added && targetRow.oldRecord != -1)
                        idxSearch.Reset();
                    Debug.Assert(saveIdxRecord == ((saveRowState == DataRowState.Added) ? targetRow.newRecord : targetRow.oldRecord), "oops, you change index record without noticing it");
                }
                finally {
                    targetRow.tempRecord = proposedRecord;
                }
            }

            // Merge all errors
            if (row.HasErrors) {
                if (targetRow.RowError.Length == 0) {
                    targetRow.RowError = row.RowError;
                } else {
                    targetRow.RowError += " ]:[ " + row.RowError;
                }
                DataColumn[] cols = row.GetColumnsInError();

                for (int i = 0; i < cols.Length; i++) {
                    DataColumn col = targetRow.Table.Columns[cols[i].ColumnName];
                    targetRow.SetColumnError(col, row.GetColumnError(cols[i]));
                }
            }else {
                if (!preserveChanges) {
                    targetRow.ClearErrors();
                }
            }

            return targetRow;
        }
Пример #6
0
		internal void DropIndex (Index index)
		{
			if (index != null && index.RefCount == 0) {
				_indexes.Remove (index);
			}
		}
Пример #7
0
        // Returns whether the found index (if any) is a sort index as well
        private bool FindClosestCandidateIndex() {
            index = null;
            matchedCandidates = 0;
            bool sortPriority = true;
            this.table.indexesLock.AcquireReaderLock(-1);
            try {
                int count = this.table.indexes.Count;
                int rowsCount = this.table.Rows.Count;
                for (int i = 0; i < count; i++) {
                    Index ndx = (Index)table.indexes[i];
                    if (ndx.RecordStates != recordStates)
                        continue;
                    if(!ndx.IsSharable)
                        continue;
                    int match = CompareClosestCandidateIndexDesc(ndx.IndexFields);
                    if (match > matchedCandidates || (match == matchedCandidates && !sortPriority)) {
                        matchedCandidates = match;
                        index = ndx;
                        sortPriority = CompareSortIndexDesc(ndx.IndexFields);
                        if (matchedCandidates == nCandidates && sortPriority) {
                            return true;
                        }
                    }
                }
            }
            finally {
        this.table.indexesLock.ReleaseReaderLock();
        }

            return (index != null ? sortPriority : false);
        }
Пример #8
0
        // Returns whether the found index (if any) is a sort index as well
        private bool FindClosestCandidateIndex()
        {
            _index = null;
            _matchedCandidates = 0;
            bool sortPriority = true;
            _table._indexesLock.EnterUpgradeableReadLock();
            try
            {
                int count = _table._indexes.Count;
                int rowsCount = _table.Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    Index ndx = _table._indexes[i];
                    if (ndx.RecordStates != _recordStates)
                        continue;
                    if (!ndx.IsSharable)
                        continue;
                    int match = CompareClosestCandidateIndexDesc(ndx._indexFields);
                    if (match > _matchedCandidates || (match == _matchedCandidates && !sortPriority))
                    {
                        _matchedCandidates = match;
                        _index = ndx;
                        sortPriority = CompareSortIndexDesc(ndx._indexFields);
                        if (_matchedCandidates == _nCandidates && sortPriority)
                        {
                            return true;
                        }
                    }
                }
            }
            finally
            {
                _table._indexesLock.ExitUpgradeableReadLock();
            }

            return (_index != null ? sortPriority : false);
        }
Пример #9
0
        internal void SetOrdinalInternal(int ordinal)
        {
            if (_ordinal != ordinal)
            {
                if (Unique && _ordinal != -1 && ordinal == -1)
                {
                    UniqueConstraint key = _table.Constraints.FindKeyConstraint(this);
                    if (key != null)
                    {
                        _table.Constraints.Remove(key);
                    }
                }

                if ((null != _sortIndex) && (-1 == ordinal))
                {
                    Debug.Assert(2 <= _sortIndex.RefCount, "bad sortIndex refcount");
                    _sortIndex.RemoveRef();
                    _sortIndex.RemoveRef(); // second should remove it from index collection
                    _sortIndex = null;
                }

                int originalOrdinal = _ordinal;
                _ordinal = ordinal;
                if (originalOrdinal == -1 && _ordinal != -1)
                {
                    if (Unique)
                    {
                        UniqueConstraint key = new UniqueConstraint(this);
                        _table.Constraints.Add(key);
                    }
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Metadata okuma iþini yapan asýl metod. Sýrayla bütün veritabaný nesnelerini okur.
        /// </summary>
        public void ReadDatabaseMetadata(bool readAllMetadata)
        {
            #region tables and views
            db.Tables = new TableCollection(db);

            bool connectionAlreadyOpen = connection.State == ConnectionState.Open;

            // columns
            if(!connectionAlreadyOpen) connection.Open();
            DataTable dtTables = ((DbConnection)connection).GetSchema("Tables");
            if (!connectionAlreadyOpen) connection.Close();
            foreach (DataRow drTable in dtTables.Rows)
            {
                Table tbl = new Table();
                tbl.Name = drTable["TABLE_NAME"].ToString();
                tbl.IsView = drTable["TABLE_TYPE"].ToString() == "VIEW";
                db.Tables.Add(tbl);
            }

            if (!connectionAlreadyOpen) connection.Open();
            DataTable dtColumns = ((DbConnection)connection).GetSchema("Columns");
            if (!connectionAlreadyOpen) connection.Close();
            foreach (DataRow drColumn in dtColumns.Rows)
            {
                Table tbl = db.Tables[drColumn["TABLE_NAME"].ToString()];
                if (tbl==null)
                    continue;

                Column f = new Column();
                f.DefaultValue = drColumn["COLUMN_DEFAULT"].ToString();
                if (f.DefaultValue == "\0") f.DefaultValue = "";
                f.ColumnTypeOriginal = drColumn["DATA_TYPE"].ToString().ToUpperInvariant();
                f.ColumnType = StringToDbType(f.ColumnTypeOriginal);
                f.Length = drColumn.IsNull("CHARACTER_MAXIMUM_LENGTH") ? 0 : Convert.ToInt64(drColumn["CHARACTER_MAXIMUM_LENGTH"]);
                f.IsNullable = drColumn["IS_NULLABLE"].ToString() != "NO";
                f.Name = drColumn["COLUMN_NAME"].ToString();
                f.IsAutoIncrement = drColumn["AUTOINCREMENT"].ToString() == "True";

                tbl.Columns.Add(f);
            }
            #endregion

            //if (!readAllMetadata) return; //***

            #region indices
            if (!connectionAlreadyOpen) connection.Open();
            DataTable dtIndexes = ((DbConnection)connection).GetSchema("Indexes");
            if (!connectionAlreadyOpen) connection.Close();
            foreach (DataRow drIndex in dtIndexes.Rows)
            {
                bool primary = (bool)drIndex["PRIMARY_KEY"];
                bool unique = (bool)drIndex["UNIQUE"];

                if(primary && unique)
                {
                    PrimaryKeyConstraint pk = new PrimaryKeyConstraint();
                    pk.Name = drIndex["INDEX_NAME"].ToString();
                    db.Tables[drIndex["TABLE_NAME"].ToString()].Constraints.Add(pk);
                }
                else if (unique)
                {
                    UniqueConstraint uc = new UniqueConstraint();
                    uc.Name = drIndex["INDEX_NAME"].ToString();
                    db.Tables[drIndex["TABLE_NAME"].ToString()].Constraints.Add(uc);
                }
                else
                {
                    Index index = new Index();
                    index.Name = drIndex["INDEX_NAME"].ToString();
                    db.Tables[drIndex["TABLE_NAME"].ToString()].Indices.Add(index);
                }
            }

            if (!connectionAlreadyOpen) connection.Open();
            DataTable dtIndexColumns = ((DbConnection)connection).GetSchema("IndexColumns");
            if (!connectionAlreadyOpen) connection.Close();
            foreach (DataRow drCol in dtIndexColumns.Rows)
            {
                BaseIndexConstraint index = db.GetConstraint(drCol["CONSTRAINT_NAME"].ToString());
                if(index==null)
                    index = db.Tables[drCol["TABLE_NAME"].ToString()].Indices[drCol["CONSTRAINT_NAME"].ToString()];

                if (index == null) continue; //***

                index.ColumnNames.Add(drCol["COLUMN_NAME"].ToString());
            }
            #endregion
        }
Пример #11
0
 private bool FindSortIndex()
 {
     _index = null;
     _table._indexesLock.EnterUpgradeableReadLock();
     try
     {
         int count = _table._indexes.Count;
         int rowsCount = _table.Rows.Count;
         for (int i = 0; i < count; i++)
         {
             Index ndx = _table._indexes[i];
             if (ndx.RecordStates != _recordStates)
                 continue;
             if (!ndx.IsSharable)
             {
                 continue;
             }
             if (CompareSortIndexDesc(ndx._indexFields))
             {
                 _index = ndx;
                 return true;
             }
         }
     }
     finally
     {
         _table._indexesLock.ExitUpgradeableReadLock();
     }
     return false;
 }
Пример #12
0
 public string GetSQLIndexRemove(Index index)
 {
     return string.Format("DROP INDEX `{0}` ON `{1}`", index.Name, index.Table.Name);
 }
Пример #13
0
 public string GetSQLIndexAdd(Index index)
 {
     return string.Format("CREATE INDEX `{0}` ON `{1}` (`{2}`)", index.Name, index.Table.Name, string.Join("`,`", index.ColumnNames.ToArray()));
 }
Пример #14
0
 internal void SetOrdinalInternal(int ordinal) {
     // 
     if (this._ordinal != ordinal) {
         if (Unique && this._ordinal != -1 && ordinal == -1) {
             UniqueConstraint key = table.Constraints.FindKeyConstraint(this);
             if (key != null)
                 table.Constraints.Remove(key);
         }
         // SQLBU 429176: remove the sortIndex when DataColumn is removed
         if ((null != sortIndex) && (-1 == ordinal)) {
             Debug.Assert(2 <= sortIndex.RefCount, "bad sortIndex refcount");
             sortIndex.RemoveRef();
             sortIndex.RemoveRef(); // second should remove it from index collection
             sortIndex = null;
         }
         int originalOrdinal = this._ordinal;
         this._ordinal = ordinal;
         if (originalOrdinal == -1 && this._ordinal != -1) {
             if (Unique) {
                 UniqueConstraint key = new UniqueConstraint(this);
                 table.Constraints.Add(key);
             }
         }
     }
 }
Пример #15
0
		private void AddIndex (Index index)
		{
			if (_indexes == null)
				_indexes = new ArrayList();
			_indexes.Add (index);
		}
Пример #16
0
 public string GetSQLIndexAdd(Index index)
 {
     return string.Format("CREATE INDEX [{0}] ON [{1}] ([{2}])", index.Name, index.Table.Name, string.Join("],[", index.ColumnNames.ToArray()));
 }
Пример #17
0
		internal Index GetIndex (DataColumn[] columns, ListSortDirection[] sort,
					 DataViewRowState rowState, IExpression filter,
					 bool reset, bool addIndex)
		{
			Index index = FindIndex(columns, sort, rowState, filter);
			if (index == null) {
				index = new Index(new Key (this, columns, sort, rowState, filter));

				if (addIndex)
					AddIndex (index);
			} else if (reset) {
				// reset existing index only if asked for this
				index.Reset ();
			}
			return index;
		}
Пример #18
0
 public string GetSQLIndexRemove(Index index)
 {
     return string.Format("DROP INDEX [{0}] ON [{1}]", index.Name, index.Table.Name);
 }
Пример #19
0
 private bool FindSortIndex() {
     index = null;
     this.table.indexesLock.AcquireReaderLock(-1);
      try{
         int count = this.table.indexes.Count;
         int rowsCount = this.table.Rows.Count;
         for (int i = 0; i < count; i++) {
             Index ndx = (Index)table.indexes[i];
             if (ndx.RecordStates != recordStates)
                 continue;
             if(!ndx.IsSharable) {
                 continue;
             }
             if (CompareSortIndexDesc(ndx.IndexFields)) {
                 index = ndx;
                 return true;
             }
         }
      }
     finally {
         this.table.indexesLock.ReleaseReaderLock();
     }
     return false;
 }
Пример #20
0
        /// <summary>
        /// Metadata okuma işini yapan asıl metod. Sırayla bütün veritabanı nesnelerini okur.
        /// </summary>
        public void ReadDatabaseMetadata(bool readAllMetadata)
        {
            #region tables and views
            db.Tables = new TableCollection(db);

            // columns
            DataTable dtTables = db.GetDataTable(GetSQLTableList());
            foreach (DataRow drTable in dtTables.Rows)
            {
                //if (drTable["TABLE_TYPE"].ToString() == "VIEW") continue;

                Table tbl = new Table();
                tbl.Name = drTable["TABLE_NAME"].ToString();
                tbl.IsView = drTable["TABLE_TYPE"].ToString() == "VIEW";
                db.Tables.Add(tbl);

                DataTable dtColumns = db.GetDataTable(GetSQLColumnList(tbl.Name));
                foreach (DataRow drColumn in dtColumns.Rows)
                {
                    Column f = new Column();
                    f.DefaultValue = drColumn["COLUMN_DEFAULT"].ToString();
                    f.ColumnTypeOriginal = drColumn["DATA_TYPE"].ToString().ToUpperInvariant();
                    f.ColumnType = StringToDbType(f.ColumnTypeOriginal);
                    f.Length = drColumn.IsNull("CHARACTER_MAXIMUM_LENGTH") ? 0 : Convert.ToInt32(drColumn["CHARACTER_MAXIMUM_LENGTH"]);
                    f.IsNullable = drColumn["IS_NULLABLE"].ToString() != "NO";
                    f.Name = drColumn["COLUMN_NAME"].ToString();
                    f.IsAutoIncrement = drColumn["IS_AUTO_INCREMENT"].ToString() == "1";

                    tbl.Columns.Add(f);
                }
            }
            #endregion

            #region constraints
            // Con.Name, Con.TableName, Con.Type, Col.ColumnName, Con.RefConstraintName, Con.UpdateRule, Con.DeleteRule
            DataTable dtCons = db.GetDataTable(this.GetSQLConstraintList());
            foreach (DataRow drCon in dtCons.Rows)
            {
                Constraint con = db.Tables[drCon["TableName"].ToString()].Constraints[drCon["Name"].ToString()];
                if (con != null)
                {
                    con.ColumnNames.Add(drCon["ColumnName"].ToString());
                    continue;
                }

                switch (drCon["Type"].ToString())
                {
                    case "FOREIGN KEY":
                        con = new ForeignKeyConstraint();
                        (con as ForeignKeyConstraint).RefConstraintName = drCon["RefConstraintName"].ToString();
                        //(con as ForeignKeyConstraint).RefTableName = drCon["RefConstraintName"].ToString();
                        (con as ForeignKeyConstraint).DeleteRule = drCon["DeleteRule"].ToString();
                        (con as ForeignKeyConstraint).UpdateRule = drCon["UpdateRule"].ToString();
                        break;
                    case "PRIMARY KEY":
                        con = new PrimaryKeyConstraint();
                        break;
                    case "UNIQUE":
                        con = new UniqueConstraint();
                        break;
                    default:
                        throw new Exception("Unknown constraint type: " + drCon["Type"].ToString());
                }
                con.Name = drCon["Name"].ToString();
                con.ColumnNames.Add(drCon["ColumnName"].ToString());

                db.Tables[drCon["TableName"].ToString()].Constraints.Add(con);
            }
            foreach (Table tbl in db.Tables)
                foreach (ForeignKeyConstraint fk in tbl.Constraints.Where(c => c is ForeignKeyConstraint))
                    fk.RefTableName = db.GetConstraint(fk.RefConstraintName).Table.Name;

            #endregion

            if (!readAllMetadata) return; //***

            #region indices
            foreach (Table tbl in db.Tables)
            {
                DataTable dtKeys = db.GetDataTable("EXEC sp_helpindex [" + tbl.Name + "]");
                if (dtKeys != null)
                    foreach (DataRow drKey in dtKeys.Rows)
                    {
                        if (db.GetConstraint(drKey["index_name"].ToString()) != null)
                            continue;

                        Index index = new Index();
                        index.Name = drKey["index_name"].ToString();

                        index.ColumnNames = new List<string>();
                        foreach (string columnName in drKey["index_keys"].ToString().Split(','))
                            index.ColumnNames.Add(columnName.Trim().Replace("(-)", ""));

                        tbl.Indices.Add(index);
                    }
            }
            #endregion
        }
Пример #21
0
        // Based on the required sorting and candidate columns settings, create a new index; Should be called only when there is no existing index to be reused
        private void CreateIndex() {
            if (index == null) {
                if (nCandidates == 0) {
                    index = new Index(table, IndexFields, recordStates, null);
                    index.AddRef();
                }
                else {
                    int i;
                    int lenCanColumns = candidateColumns.Length;
                    int lenIndexDesc = IndexFields.Length;
                    bool equalsOperator = true;
                    for (i=0; i<lenCanColumns; i++) {
                        if (candidateColumns[i] != null) {
                            if (!candidateColumns[i].equalsOperator) {
                                equalsOperator = false;
                                break;
                            }
                        }
                    }

                    int j=0;
                    for (i=0; i < lenIndexDesc; i++) {
                        ColumnInfo candidateColumn = candidateColumns[IndexFields[i].Column.Ordinal];
                        if (candidateColumn != null) {
                            candidateColumn.flag = true;
                            j++;
                        }
                    }
                    int indexNotInCandidates = lenIndexDesc - j;
                    int candidatesNotInIndex = nCandidates - j;
                    IndexField[] ndxFields = new IndexField[nCandidates + indexNotInCandidates];

                    if (equalsOperator) {
                        j=0;
                        for (i=0; i<lenCanColumns; i++) {
                            if (candidateColumns[i] != null) {
                                ndxFields[j++] = new IndexField(this.table.Columns[i], isDescending: false);
                                candidateColumns[i].flag = false;// this means it is processed
                            }
                        }
                        for (i=0; i<lenIndexDesc; i++) {
                            ColumnInfo canColumn = candidateColumns[IndexFields[i].Column.Ordinal];
                            if (canColumn == null || canColumn.flag) { // if sort column is not a filter col , or not processed
                                ndxFields[j++] = IndexFields[i];
                                if (canColumn != null) {
                                    canColumn.flag = false;
                                }
                            }                                
                        }

                        for(i = 0; i < candidateColumns.Length; i++) {
                            if (candidateColumns[i] != null) {
                                candidateColumns[i].flag = false;// same as before, it is false when it returns 
                            }
                            
                        }

                        // Debug.Assert(j == candidatesNotInIndex, "Whole ndxDesc should be filled!");

                        index = new Index(table, ndxFields, recordStates, null);
                        if (!IsOperatorIn(this.expression)) {
                            // if the expression contains an 'IN' operator, the index will not be shared
                            // therefore we do not need to index.AddRef, also table would track index consuming more memory until first write
                            index.AddRef();
                        }


                        matchedCandidates = nCandidates;
                     }
                     else {
                        for (i=0; i<lenIndexDesc; i++) {
                            ndxFields[i] = IndexFields[i];
                            ColumnInfo canColumn = candidateColumns[IndexFields[i].Column.Ordinal];
                            if (canColumn != null)
                                canColumn.flag = true;
                        }
                         j=i;
                        for (i=0; i<lenCanColumns; i++) {
                            if (candidateColumns[i] != null) {
                                if(!candidateColumns[i].flag) {
                                    ndxFields[j++] = new IndexField(this.table.Columns[i], isDescending: false);
                                }
                                else {
                                    candidateColumns[i].flag = false;
                                }
                            }
                        }
//                        Debug.Assert(j == nCandidates+indexNotInCandidates, "Whole ndxDesc should be filled!");
                                                
                        index = new Index(table, ndxFields, recordStates, null);
                        matchedCandidates = 0;
                        if (this.linearExpression != this.expression) {
                            IndexField[] fields = index.IndexFields;
                            while (matchedCandidates < j) { // [....] : j = index.IndexDesc.Length
                                ColumnInfo canColumn = candidateColumns[fields[matchedCandidates].Column.Ordinal];
                                if (canColumn == null || canColumn.expr == null)
                                    break;
                                matchedCandidates++;
                                if (!canColumn.equalsOperator)
                                    break;
                            }
                        }
                        for(i = 0; i < candidateColumns.Length; i++) {
                            if (candidateColumns[i] != null) {
                                candidateColumns[i].flag = false;// same as before, it is false when it returns 
                            }
                        }
                    }
                }
            }
        }
Пример #22
0
 public void CreateIndex(Table t, Index index)
 {
     executeLog(string.Format("ALTER TABLE `{0}` ADD CONSTRAINT `{1}` UNIQUE ({2})", t.Name, index.Name,
         string.Join(",", index.Fields.Select(f => "`" + f.Name + "` ASC").ToArray())));
 }
Пример #23
0
        internal DataRow FindMergeTarget(DataRow row, DataKey key, Index ndx) {
            DataRow targetRow = null;

            // Primary key match
            if (key.HasValue) {
                Debug.Assert(ndx != null);
                int   findRecord = (row.oldRecord == -1) ? row.newRecord : row.oldRecord;
                object[] values = key.GetKeyValues(findRecord);
                targetRow = FindByIndex(ndx, values);
            }
            return targetRow;
        }
Пример #24
0
 public void DropIndex(Table t, Index index)
 {
     executeLogSafe(string.Format("ALTER TABLE `{0}` DROP INDEX `{1}`", t.Name, index.Name));
 }
Пример #25
0
 internal Index GetIndex(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) {
     indexesLock.AcquireReaderLock(-1);
     try {
         for (int i = 0; i < indexes.Count; i++) {
             Index index = indexes[i];
             if (index != null) {
                 if (index.Equal(indexDesc, recordStates, rowFilter)) {
                     return index;
                 }
             }
         }
     }
     finally {
         indexesLock.ReleaseReaderLock();
     }
     Index ndx = new Index(this, indexDesc, recordStates, rowFilter);
     ndx.AddRef();
     return ndx;
 }
Пример #26
0
		protected void Close ()
		{
			if (dataTable != null)
				UnregisterEventHandlers ();
			Index = null;
			rowCache = new DataRowView [0];
			isOpen = false;
		}
Пример #27
0
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void EndLoadData() {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<ds.DataTable.EndLoadData|API> %d#\n", ObjectID);
            try {
                if (!inDataLoad)
                    return;

                if(loadIndex != null) {
                    loadIndex.RemoveRef();
                }
                if (loadIndexwithOriginalAdded  != null) {
                    loadIndexwithOriginalAdded.RemoveRef();
                }
                if (loadIndexwithCurrentDeleted  != null) {
                    loadIndexwithCurrentDeleted.RemoveRef();
                }

                loadIndex  = null;
                loadIndexwithOriginalAdded = null;
                loadIndexwithCurrentDeleted = null;

                inDataLoad = false;

                RestoreIndexEvents(false);

                if (DataSet != null)
                    DataSet.EnforceConstraints = savedEnforceConstraints;
                else
                    this.EnforceConstraints = true;
            }
            finally{
                Bid.ScopeLeave(ref hscp);
            }
        }
Пример #28
0
		// This is method is internal to 
		// the Mono implementation of DataView; it
		// is not to be used from your code.
		//
		// Update the DataRowView array which is an index cache
		// into the DataTable's DataRowCollection.
		//
		// I assume this is what UpdateIndex is used for
		protected virtual void UpdateIndex(bool force) 
		{
			if (Table == null) {
				// FIXME
				return;
			}

			if (Index == null || force) {
				ListSortDirection[] sortOrder = null;
				DataColumn[] columns = DataTable.ParseSortString(Table, Sort, out sortOrder, false);
				Index = dataTable.GetIndex(columns,sortOrder,RowStateFilter,FilterExpression,true);
			}
			else {
				Index.Key.RowStateFilter = RowStateFilter;
				Index.Reset();
			}

			int[] records = Index.GetAll();

			if (records != null) {
				InitDataRowViewArray(records,Index.Size);
			}
			else {
				rowCache = new DataRowView[0];
			}
		}
Пример #29
0
        private DataRow LoadRow(object[] values, LoadOption loadOption, Index searchIndex) {
            int recordNo;
            DataRow dataRow = null;

            if (searchIndex != null) {
                int[] primaryKeyIndex = new int[0];
                if (this.primaryKey != null) { // I do check above for PK, but in case if someone else gives me some index unrelated to PK
                    primaryKeyIndex = new int[this.primaryKey.ColumnsReference.Length];
                    for(int i = 0; i < this.primaryKey.ColumnsReference.Length; i++) {
                        primaryKeyIndex[i] = this.primaryKey.ColumnsReference[i].Ordinal;
                    }
                }

                object[] keys = new object[primaryKeyIndex.Length];
                for(int i = 0; i < primaryKeyIndex.Length; i++) {
                    keys[i] = values[primaryKeyIndex[i]];
                }

                Range result = searchIndex.FindRecords(keys);

                if (!result.IsNull) {
                    int deletedRowUpsertCount = 0;
                    for(int i = result.Min; i <= result.Max; i++) {
                        int resultRecord = searchIndex.GetRecord(i);
                        dataRow = this.recordManager[resultRecord];
                        recordNo = NewRecordFromArray(values);

                        //SQLBU DT 33648
                        // values array is being reused by DataAdapter, do not modify the values array
                        for(int count = 0; count < values.Length; count++) {
                            if (null == values[count]) {
                                columnCollection[count].Copy(resultRecord, recordNo);
                            }
                        }
                        for(int count = values.Length; count < columnCollection.Count ; count++) {
                            columnCollection[count].Copy(resultRecord, recordNo); // if there are missing values
                        }

                        if (loadOption != LoadOption.Upsert || dataRow.RowState != DataRowState.Deleted) {
                            SetDataRowWithLoadOption(dataRow , recordNo, loadOption, true);
                        }
                        else {
                            deletedRowUpsertCount++;
                        }
                    }
                    if (0 == deletedRowUpsertCount) {
                        return dataRow;
                    }
                }
            }

            recordNo = NewRecordFromArray(values);
            dataRow = NewRow(recordNo);
            // fire rowChanging event here
            DataRowAction action;
            DataRowChangeEventArgs drcevent = null;
            switch(loadOption) {
                case LoadOption.OverwriteChanges:
                case LoadOption.PreserveChanges:
                    action = DataRowAction.ChangeCurrentAndOriginal;
                    break;
                case LoadOption.Upsert:
                    action = DataRowAction.Add;
                    break;
                default:
                    throw ExceptionBuilder.ArgumentOutOfRange("LoadOption");
            }

            drcevent = RaiseRowChanging(null, dataRow, action);

            this.InsertRow (dataRow, -1, -1, false);
            switch(loadOption) {
                case LoadOption.OverwriteChanges:
                case LoadOption.PreserveChanges:
                    this.SetOldRecord(dataRow,  recordNo);
                    break;
                case LoadOption.Upsert:
                    break;
                default:
                    throw ExceptionBuilder.ArgumentOutOfRange("LoadOption");
            }
            RaiseRowChanged(drcevent, dataRow, action);

            return dataRow;
        }
Пример #30
0
 public string GetSQLIndexRemove(Index index)
 {
     return string.Format("DROP INDEX \"{0}\"", index.Name);
 }