internal void CreateFirebirdIdTable(string tableName, string columnName, DatabaseAgent agent)
        {
            string IdTableName = string.Format("{0}NID", tableName);

            // create a table to hold the next id for the specified table

            /*
             * This is specifically for Firebird since it doesn't have a way to
             * easily create an autoincrementing id field.  The closest thing they
             * have is "Generators" used in "before insert" triggers.  Attempts
             * to go in that direction is proving time consuming.  So, I'm
             * implementing my own ID Generator to be used internally to this component.
             */
            try
            {
                agent.ExecuteSqlFormat(DatabaseAgent.CREATETABLEFORMAT, IdTableName, string.Format("{0} BIGINT", columnName));
                agent.ExecuteSqlFormat(DatabaseAgent.INSERTFORMAT, IdTableName, columnName, "0");
            }
            catch (Exception ex)
            {
                CreateTableResult result = CatchException(ex, IdTableName);
                if (result != CreateTableResult.Success && result != CreateTableResult.AlreadyExists)
                {
                    throw ex;
                }
            }
        }
예제 #2
0
 public DaoObjectCollection(List <long> ids, int pageSize, DatabaseAgent agent)
 {
     this.PageSize = pageSize;
     this.pagedIds = new Book <long>(ids, pageSize);
     this.agent    = agent;
     GetNextPage();
 }
        private AddForeignKeyResult AddAllForeignKeys(DatabaseAgent agent, Assembly daoAssembly, string contextName)
        {
            List <DaoForeignKeyInfo> foreignKeys = new List <DaoForeignKeyInfo>();

            foreach (Type type in daoAssembly.GetTypes())
            {
                object[] tableAttributes = type.GetCustomAttributes(typeof(DaoTable), false);
                if (tableAttributes.Length == 1)
                {
                    DaoTable        tableAttribute = (DaoTable)tableAttributes[0];
                    ConstructorInfo ctor           = type.GetConstructor(Type.EmptyTypes);
                    DaoObject       obj            = (DaoObject)ctor.Invoke(null);
                    if (obj.DataContextName.Equals(contextName))
                    {
                        foreignKeys.AddRange(this.GetForeignKeys(obj, tableAttribute.TableName));
                    }
                }
            }

            AddForeignKeyResult retVal = AddForeignKeyResult.Success;

            foreach (DaoForeignKeyInfo foreignKey in foreignKeys)
            {
                if (this.AddForeignKey(foreignKey, agent) == AddForeignKeyResult.Error)
                {
                    retVal = AddForeignKeyResult.Error;
                }
            }
            return(retVal);
        }
예제 #4
0
        public DaoForeignKeyList(string fkColumnName, DaoObject parent, Func <string, object, DatabaseAgent, T[]> selectFunction)
        {
            if (parent.IsNew)
            {
                throw new InvalidOperationException("Parent object not committed");
            }

            this.selectFunction           = selectFunction;
            this.fkColumnName             = fkColumnName;
            this.id                       = parent.GetLongValue(parent.IdColumnName);//id;
            this.agent                    = parent.DatabaseAgent;
            this.updated                  = new List <DaoObject>();
            this.parent                   = parent;
            this.parent.ChangesCommitted += new DaoObjectEventHandler(parent_ChangesCommitted);
            this.parent.BeforeDelete     += (dao) =>
            {
                foreach (T obj in this)
                {
                    obj.AllowDelete = true;
                    obj.Delete(parent.DatabaseAgent);
                }
            };

            this.values   = new List <T>();
            this.toInsert = new List <T>();
            this.Refresh();
        }
예제 #5
0
        public void SetUp()
        {
            try
            {
                var providers = new ProviderCollection <StorageProviderDefinition>();
                providers.Add(new RdbmsProviderDefinition("TheStorageProvider", new SqlStorageObjectFactory(), TestDomainConnectionString));
                var storageConfiguration = new StorageConfiguration(providers, providers["TheStorageProvider"]);

                DomainObjectsConfiguration.SetCurrent(new FakeDomainObjectsConfiguration(storage: storageConfiguration));

                SqlConnection.ClearAllPools();

                var scriptGenerator = new ScriptGenerator(
                    pd => pd.Factory.CreateSchemaScriptBuilder(pd),
                    new RdbmsStorageEntityDefinitionProvider(),
                    new ScriptToStringConverter());
                var scripts = scriptGenerator.GetScripts(MappingConfiguration.Current.GetTypeDefinitions()).Single();

                var masterAgent = new DatabaseAgent(MasterConnectionString);
                masterAgent.ExecuteBatchFile("Database\\CreateDB.sql", false, DatabaseConfiguration.GetReplacementDictionary());

                var databaseAgent = new DatabaseAgent(TestDomainConnectionString);
                databaseAgent.ExecuteBatchString(scripts.SetUpScript, true);
            }
            catch (Exception e)
            {
                Console.WriteLine("SetUpFixture failed: " + e);
                Console.WriteLine();
                throw;
            }
        }
        public void Relation_WithMoreThan2100Objects()
        {
            SetDatabaseModifyable();

            var insertedIDs      = Enumerable.Range(0, 4000).Select(x => Guid.NewGuid()).ToArray();
            var insertStatements = insertedIDs.Select(
                id => string.Format(
                    "insert into [OrderItem] (ID, ClassID, OrderID, [Position], [Product]) values ('{0}', 'OrderItem', '{1}', 1, 'Test2100')",
                    id,
                    DomainObjectIDs.Order1.Value));

            var script = string.Join(Environment.NewLine, insertStatements);

            DatabaseAgent.ExecuteCommand(script);

            var order      = DomainObjectIDs.Order1.GetObject <Order> ();
            var orderItems = order.OrderItems;

            Assert.That(orderItems.Count, Is.EqualTo(4002));

            var loadedIDs   = orderItems.Select(oi => (Guid)oi.ID.Value);
            var expectedIDs = insertedIDs.Concat(new[] { (Guid)DomainObjectIDs.OrderItem1.Value, (Guid)DomainObjectIDs.OrderItem2.Value });

            Assert.That(loadedIDs.SetEquals(expectedIDs), Is.True);
        }
        public void Relation_WithMoreThan2100Objects_WithTableInheritance()
        {
            SetDatabaseModifyable();

            var domainObjectIDs = new TableInheritanceDomainObjectIDs(Configuration);

            var insertedIDs      = Enumerable.Range(0, 4000).Select(x => Guid.NewGuid()).ToArray();
            var insertStatements = insertedIDs.Select(
                id => string.Format(
                    "insert into [TableInheritance_File] (ID, ClassID, [Name], [ParentFolderID], [ParentFolderIDClassID], [Size], [FileCreatedAt]) "
                    + "values ('{0}', 'TI_File', 'Test', '{1}', 'TI_Folder', 42, '2006/02/03')",
                    id,
                    domainObjectIDs.Folder1.Value));

            var script = string.Join(Environment.NewLine, insertStatements);

            DatabaseAgent.ExecuteCommand(script);

            var folder          = domainObjectIDs.Folder1.GetObject <TIFolder> ();
            var fileSystemItems = folder.FileSystemItems;

            Assert.That(fileSystemItems.Count, Is.EqualTo(4001));
            var loadedIDs   = fileSystemItems.Select(oi => (Guid)oi.ID.Value);
            var expectedIDs = insertedIDs.Concat(new[] { (Guid)domainObjectIDs.File1.Value });

            Assert.That(loadedIDs.SetEquals(expectedIDs), Is.True);
        }
예제 #8
0
        /// <summary>
        /// Get the current DaoContext instance for the specified logicalName.
        /// If a DaoContext has already been instantiated for the specified logicalName
        /// the connection string is updated with the one specified.
        /// </summary>
        /// <param name="contextName">The name of the DaoContext to retrieve.</param>
        /// <param name="connString">The connection string to assign to the specified</param>
        /// <returns>DaoContext instance.</returns>
        public static DaoContext Get(string contextName, string connString)
        {
            if (contexts.ContainsKey(contextName))
            {
                return(contexts[contextName]);
            }

            // if no connection string was specified check if this logical name has
            // been initialized
            string connectionString = connString;

            if (string.IsNullOrEmpty(connectionString))
            {
                connectionString = GetContextConnectionString(contextName);
            }

            DatabaseAgent agent = DatabaseAgent.CreateAgent(GetContextDatabaseType(contextName), connectionString);

            DaoContext dao = new DaoContext();

            dao.DatabaseAgent = agent;

            if (!contexts.ContainsKey(contextName))
            {
                contexts.Add(contextName, dao);
            }
            else
            {
                contexts[contextName] = dao;
            }

            OnDaoContextConnectionStringSet(dao, contextName);

            return(dao);
        }
예제 #9
0
        protected DatabaseTest(DatabaseAgent databaseAgent, string createTestDataFileName)
        {
            ArgumentUtility.CheckNotNull("databaseAgent", databaseAgent);
            ArgumentUtility.CheckNotNullOrEmpty("createTestDataFileName", createTestDataFileName);

            _databaseAgent          = databaseAgent;
            _createTestDataFileName = createTestDataFileName;
        }
예제 #10
0
        public static DaoObjectCollection <DaoType> LoadAll <DaoType>(int pageSize, DatabaseAgent agent) where DaoType : DaoObject, new()
        {
            DaoSearchFilter filter = new DaoSearchFilter();
            DaoType         proxy  = new DaoType();

            filter.AddParameter(proxy.IdColumnName, null, Comparison.NotEqualTo);
            return(new DaoObjectCollection <DaoType>(filter, pageSize, agent));
        }
        public void ExecuteScriptForThirdStorageProvider()
        {
            DatabaseAgent.SetConnectionString(SchemaGenerationConnectionString3);

            var scripts = _extendedScriptGenerator.GetScripts(MappingConfiguration.GetTypeDefinitions())
                          .Single(s => s.StorageProviderDefinition == SchemaGenerationThirdStorageProviderDefinition);

            DatabaseAgent.ExecuteBatchString(scripts.TearDownScript + scripts.SetUpScript, false, DatabaseConfiguration.GetReplacementDictionary());
        }
        public void CreateDaoSchema <T>(DatabaseAgent agent) where T : DaoObject, new()
        {
            Assembly assembly    = typeof(T).Assembly;
            string   contextName = new T().DataContextName;

            CreateDaoTables(agent, assembly, contextName);

            this.AddAllForeignKeys <T>(agent);
        }
        public AddForeignKeyResult AddAllForeignKeys <T>(DatabaseAgent agent) where T : DaoObject, new()
        {
            Assembly daoAssembly = typeof(T).Assembly;
            string   contextName = new T().DataContextName;

            AddForeignKeyResult retVal = AddAllForeignKeys(agent, daoAssembly, contextName);

            return(retVal);
        }
예제 #14
0
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();

            SetDatabaseModifyable();
            DatabaseAgent.ExecuteBatchFile("DataDomainObjects_DropFulltextIndices.sql", false, DatabaseConfiguration.GetReplacementDictionary());
            DatabaseAgent.ExecuteBatchFile("DataDomainObjects_CreateFulltextIndices.sql", false, DatabaseConfiguration.GetReplacementDictionary());
            WaitForIndices();
        }
        public CreateTableResult CreateDaoTable(DaoObject daoObject, DatabaseAgent agent)
        {
            DaoTable tableAttribute = (DaoTable)daoObject.GetType().GetCustomAttributes(typeof(DaoTable), true)[0];

            Expect.IsNotNull(tableAttribute);
            string tableName    = tableAttribute.TableName;
            string idColumnName = this.GetIdColumnName(daoObject);
            Dictionary <PropertyInfo, DaoColumn> columns = this.GetColumns(daoObject);

            StringBuilder sqlColumns = new StringBuilder();
            bool          first      = true;

            foreach (PropertyInfo key in columns.Keys)
            {
                string dataType   = this.TranslateToDataType(key);
                string special    = "";
                bool   primaryKey = false;
                if (key.HasCustomAttributeOfType <DaoIdColumn>(true, true))// -- old -> key.Name.Equals(idColumnName))
                {
                    special += this.GetIdentitySpec();
                } // -- added 2/1/11
                else if (key.HasCustomAttributeOfType <DaoPrimaryKeyColumn>(true, true))
                {
                    special   += this.GetPrimaryKeySpec();
                    primaryKey = true;
                }
                // -- end added

                if (!columns[key].AllowNulls && !primaryKey)
                {
                    special += " NOT NULL";
                }

                if (!first)
                {
                    sqlColumns.Append(", ");
                }
                sqlColumns.AppendFormat("\"{0}\" {1} {2}", columns[key].ColumnName, dataType, special);
                first = false;
            }

            try
            {
                agent.ExecuteSql(string.Format(DatabaseAgent.CREATETABLEFORMAT, tableName, sqlColumns.ToString()));
                if (agent.DbType == DaoDbType.Firebird)
                {
                    this.CreateFirebirdIdTable(tableName, idColumnName, agent);
                }
            }
            catch (Exception ex)
            {
                return(CatchException(ex, tableName));//CreateDaoTableResult.UnknownError;
            }

            return(CreateTableResult.Success);
        }
예제 #16
0
        public static object ToDynamicInstance(this DataRow row, string typeName)
        {
            AssemblyBuilder ignore;
            Type            dynamicType = ToDynamicType(row, typeName, out ignore);
            ConstructorInfo ctor        = dynamicType.GetConstructor(new Type[] { });
            object          instance    = ctor.Invoke(null);//Activator.CreateInstance(dynamicType);

            DatabaseAgent.FromDataRow(instance, row);
            return(instance);
        }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();

            var createDBScript = ResourceUtility.GetResourceString(GetType(), "TestData.SchemaGeneration_CreateDB.sql");

            var masterAgent = new DatabaseAgent(MasterConnectionString);

            masterAgent.ExecuteBatchString(createDBScript, false, DatabaseConfiguration.GetReplacementDictionary());
        }
예제 #18
0
        private void WaitForIndices()
        {
            var rowCount = DatabaseAgent.ExecuteScalarCommand("SELECT COUNT(*) FROM CeoView WHERE Contains ([CeoView].[Name], 'Fischer')");

            if (!rowCount.Equals(1))
            {
                Thread.Sleep(100);
                WaitForIndices();
            }
        }
예제 #19
0
        public DaoObjectCollection(DaoSearchFilter filter)
            : base()
        {
            this.filter   = filter;
            this.pagedIds = new Book <long>(new List <long>(), DefaultPageSize);
            T proxy = new T();

            this.agent = DaoContext.Get(proxy.DataContextName).DatabaseAgent;
            this.GetIds();
        }
예제 #20
0
        public DaoObjectCollection(DaoSearchFilter filter, int pageSize, DatabaseAgent agent)
            : base()
        {
            this.filter   = filter;
            this.PageSize = pageSize;
            this.pagedIds = new Book <long>(new List <long>(), pageSize);

            this.agent = agent;
            this.GetIds();
        }
예제 #21
0
        public void InitStore(EventStoreTypes type)
        {
            //this.EventStoreType = type.ToString();
            switch (type)
            {
            case EventStoreTypes.None:
                store = new NullEventStore();
                break;

            case EventStoreTypes.Xml:
                storeFile = FsUtil.GetCurrentUserAppDataFolder() + "EventStore.xml";
                store     = new EventStore();
                if (File.Exists(storeFile))
                {
                    FileInfo info = new FileInfo(storeFile);
                    if (info.IsReadOnly)
                    {
                        throw new EventStoreInitializationException(storeFile);
                    }

                    store.Hydrate(storeFile);
                }

                break;

            case EventStoreTypes.MSSql:
                store = new DatabaseEventStore(DaoDbType.MSSql);
                try
                {
                    DatabaseAgent.GetAgent(LogEventData.ContextName, DaoDbType.MSSql).EnsureSchema <EventDefinition>();
                }
                catch
                {
                    // we tried
                }
                break;

            case EventStoreTypes.SQLite:
                store = new DatabaseEventStore(DaoDbType.SQLite);
                try
                {
                    DatabaseAgent.GetAgent(LogEventData.ContextName, DaoDbType.SQLite).EnsureSchema <EventDefinition>();
                }
                catch (UnableToDetermineConnectionStringException utdcse)
                {
                    //AppDb.Current;
                }
                catch
                {
                    //we tried
                }
                break;
            }
        }
예제 #22
0
        public CustomIndex(DatabaseAgent agent, PropertyInfo propertyToIndex)
        {
            Expect.IsNotNull(propertyToIndex, "PropertyToIndex cannot be null, double check the spelling if using the ctor CustomIndex(DatabaseAgent agent, string propertyName).");
            this.agent        = agent;
            this.index        = new List <IndexInfo>();
            this.PropertyInfo = propertyToIndex;

            Type   tdaoType = typeof(TDao);
            string namespaceQualifiedTypeName = tdaoType.Namespace + "." + tdaoType.Name;

            Expect.IsObjectOfType <TDao>(propertyToIndex.DeclaringType, "Specified property is invalid, must be a property from Type " + namespaceQualifiedTypeName);
        }
예제 #23
0
        public override void WireScriptsAndValidate()
        {
            Expect.IsNotNullOrEmpty(this.jsonId, "JsonId must be explicitly set: " + this.ToString());
            this.DomId = this.JsonId;
            DatabaseAgent agent = GetAgent();

            this.tree = Doodad.GetDoodad(this.JsonId, agent);

            this.OnFolderOptionClicked = "JSUI." + this.JsonId + ".folderAction"; // in datatree.util.js
            this.OnFileOptionClicked   = "JSUI." + this.JsonId + ".fileAction";
            base.WireScriptsAndValidate();
        }
예제 #24
0
 public static LogEventData FromLogEvent(LogEvent logEvent, DatabaseAgent agent)
 {
     LogEventData retVal = LogEventData.New(agent);
     retVal.Category = logEvent.Category;
     retVal.Computer = logEvent.Computer;
     retVal.EventID = logEvent.EventID;
     retVal.Message = logEvent.Message;
     retVal.Severity = logEvent.Severity.ToString();
     retVal.TimeOccurred = logEvent.TimeOccurred;
     retVal.Source = logEvent.Source;
     retVal.User = logEvent.User;
     return retVal;
 }
        private AddForeignKeyResult AddForeignKey(DaoForeignKeyInfo foreignKey, DatabaseAgent agent)
        {
            if (agent.DbType == DaoDbType.SQLite)
            {
                return(AddForeignKeyResult.Success); // foreign key constraints aren't supported in SQLite
            }
            string foreignKeyName = string.Empty;

            try
            {
                foreignKeyName = foreignKey.DaoForeignKeyColumn.ForeignKeyName;
                if (agent.DbType == DaoDbType.Firebird)
                {
                    foreignKeyName = StringExtensions.RandomString(31, false, false);
                }
                // table1Name, fkName, column1Name, table2Name, column2Name
                agent.ExecuteSql(string.Format(
                                     DatabaseAgent.ADDFOREIGNKEYFORMAT,
                                     foreignKey.TableName,
                                     foreignKeyName,
                                     foreignKey.DaoForeignKeyColumn.ColumnName,
                                     foreignKey.DaoForeignKeyColumn.ReferencedTable,
                                     foreignKey.DaoForeignKeyColumn.ReferencedKey));
            }
            catch (FbException ex)
            {
                if (ex.ErrorCode == -2147467259)// foreign key already exists
                {
                    return(AddForeignKeyResult.Success);
                }
            }
            catch (SqlException sqlEx)
            {
                if (sqlEx.Message.ToLower().Contains(string.Format("already an object named '{0}'", foreignKeyName).ToLower()))
                {
                    return(AddForeignKeyResult.Success);
                }
                else
                {
                    return(AddForeignKeyResult.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("An error occurred adding foreign key: {0}\r\n{1}", ex.Message, ex.StackTrace));
                return(AddForeignKeyResult.Error);
            }

            return(AddForeignKeyResult.Success);
        }
예제 #26
0
        public static LogEventData FromLogEvent(LogEvent logEvent, DatabaseAgent agent)
        {
            LogEventData retVal = LogEventData.New(agent);

            retVal.Category     = logEvent.Category;
            retVal.Computer     = logEvent.Computer;
            retVal.EventID      = logEvent.EventID;
            retVal.Message      = logEvent.Message;
            retVal.Severity     = logEvent.Severity.ToString();
            retVal.TimeOccurred = logEvent.TimeOccurred;
            retVal.Source       = logEvent.Source;
            retVal.User         = logEvent.User;
            return(retVal);
        }
예제 #27
0
        public CustomIndex <TDao> GetIndex <TDao>(DatabaseAgent agent, string propertyName) where TDao : DaoObject, new()
        {
            if (!this.indexesByProperty.ContainsKey(propertyName))
            {
                this.indexesByProperty.Add(propertyName, new Dictionary <Type, object>());
            }

            if (!this.indexesByProperty[propertyName].ContainsKey(typeof(TDao)))
            {
                this.indexesByProperty[propertyName].Add(typeof(TDao), new CustomIndex <TDao>(agent, propertyName));
            }

            return((CustomIndex <TDao>) this.indexesByProperty[propertyName][typeof(TDao)]);
        }
예제 #28
0
        public override EventStore.EventDefinitionInfo GetEventDefinition(string applicationName, string messageSignature)
        {
            //if (this.eventDefinitions == null)
            //    this.eventDefinitions = new Dictionary<EventDefinitionInfo, EventDefinitionInfo>();

            EventDefinitionInfo retVal = new EventDefinitionInfo(applicationName, messageSignature);

            //if( eventDefinitions.ContainsKey(retVal))
            //{
            //    return eventDefinitions[retVal];
            //}

            DatabaseAgent agent = GetAgent();

            lock (working)
            {
                EventDefinitionSearchFilter filter = new EventDefinitionSearchFilter();
                filter.AddParameter(EventDefinitionFields.ApplicationName, applicationName);
                filter.AddParameter(EventDefinitionFields.MessageSignature, messageSignature);
                EventDefinition[] definitions = EventDefinition.SelectListWhere(filter, agent);

                EventDefinition definition = null;
                if (definitions.Length == 0)
                {
                    definition = EventDefinition.New(agent);
                    definition.ApplicationName  = applicationName;
                    definition.MessageSignature = messageSignature;

                    if (definition.Insert() != -1)
                    {
                        retVal.EventId = definition.EventId;
                        //this.eventDefinitions.Add(retVal, retVal);
                    }
                }
                else if (definitions.Length > 1)
                {
                    //LogManager.CurrentLog.AddEntry("The event data on {0}, in the database {1} is corrupt.  More than one definition was found with the same app name and signature", this.EventStoreLocation, this.EventStoreName);
                    Log(string.Format("The event data in the database {0} is corrupt.  More than one definition was found with the same app name ({1}) and signature ({2})", agent.ConnectionString, applicationName, messageSignature));
                }
                else if (definitions.Length == 1)
                {
                    retVal.EventId = definitions[0].EventId;
                    //if (!this.eventDefinitions.ContainsKey(retVal))
                    //    this.eventDefinitions.Add(retVal, retVal);
                }
            }
            return(retVal);
        }
 private void CreateDaoTables(DatabaseAgent agent, Assembly assembly, string contextName)
 {
     foreach (Type type in assembly.GetTypes())
     {
         object[] tableAttributes = type.GetCustomAttributes(typeof(DaoTable), true);
         if (tableAttributes.Length == 1)
         {
             ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
             DaoObject       obj  = (DaoObject)ctor.Invoke(null);
             if (obj.DataContextName.Equals(contextName))
             {
                 CreateDaoTable(obj, agent);
             }
         }
     }
 }
        public static DataRelationshipDefinition[] GetDataRelationshipDefinitions(DatabaseAgent sourceDb)
        {
            if (dataRelationships == null)
            {
                dataRelationships = new Dictionary <DatabaseAgent, DataRelationshipDefinition[]>();
            }

            if (!dataRelationships.ContainsKey(sourceDb))
            {
                string sql = @"SELECT FK.constraint_name as ForeignKeyName, 
                FK.table_name as ForeignKeyTable, 
                FKU.column_name as ForeignKeyColumn,
                UK.constraint_name as PrimaryKeyName, 
                UK.table_name as PrimaryKeyTable, 
                UKU.column_name as PrimaryKeyColumn
                FROM Information_Schema.Table_Constraints AS FK
                INNER JOIN
                Information_Schema.Key_Column_Usage AS FKU
                ON FK.constraint_type = 'FOREIGN KEY' AND
                FKU.constraint_name = FK.constraint_name
                INNER JOIN
                Information_Schema.Referential_Constraints AS RC
                ON RC.constraint_name = FK.constraint_name
                INNER JOIN
                Information_Schema.Table_Constraints AS UK
                ON UK.constraint_name = RC.unique_constraint_name
                INNER JOIN
                Information_Schema.Key_Column_Usage AS UKU
                ON UKU.constraint_name = UK.constraint_name AND
                UKU.ordinal_position =FKU.ordinal_position";

                List <DataRelationshipDefinition> list = new List <DataRelationshipDefinition>();
                DataTable foreignKeyData = sourceDb.GetDataTableFromSql(sql);
                foreach (DataRow row in foreignKeyData.Rows)
                {
                    list.Add(DataRelationshipDefinition.CreateFromDataRow(row));
                }

                DataRelationshipDefinition[] retVal = list.ToArray();
                dataRelationships.Add(sourceDb, retVal);
                return(retVal);
            }
            else
            {
                return(dataRelationships[sourceDb]);
            }
        }
예제 #31
0
        public void SetUp()
        {
            try
            {
                ServiceLocator.SetLocatorProvider(() => null);

                LogManager.ResetConfiguration();
                Assert.That(LogManager.GetLogger(typeof(LoggingClientTransactionListener)).IsDebugEnabled, Is.False);

                StandardConfiguration.Initialize();
                TableInheritanceConfiguration.Initialize();

                SqlConnection.ClearAllPools();

                var masterAgent = new DatabaseAgent(DatabaseTest.MasterConnectionString);
                masterAgent.ExecuteBatchFile("DataDomainObjects_CreateDB.sql", false, DatabaseConfiguration.GetReplacementDictionary());
                var testDomainAgent = new DatabaseAgent(DatabaseTest.TestDomainConnectionString);
                testDomainAgent.ExecuteBatchFile("DataDomainObjects_SetupDB.sql", true, DatabaseConfiguration.GetReplacementDictionary());

                _standardMappingDatabaseAgent = new StandardMappingDatabaseAgent(DatabaseTest.TestDomainConnectionString);
                string sqlFileName = StandardMappingTest.CreateTestDataFileName;
                _standardMappingDatabaseAgent.ExecuteBatchFile(sqlFileName, true, DatabaseConfiguration.GetReplacementDictionary());
                string sqlFileName1 = TableInheritanceMappingTest.CreateTestDataFileName;
                _standardMappingDatabaseAgent.ExecuteBatchFile(sqlFileName1, true, DatabaseConfiguration.GetReplacementDictionary());
                _standardMappingDatabaseAgent.SetDatabaseReadOnly(DatabaseTest.DatabaseName);

                // We don't want the tests to initialize a default mapping; therefore, modify MappingConfiguration.s_mappingConfiguration so that it will
                // throw when asked to generate a new MappingConfiguration.

                _previousMappingConfigurationContainer = (DoubleCheckedLockingContainer <IMappingConfiguration>)PrivateInvoke.GetNonPublicStaticField(
                    typeof(MappingConfiguration),
                    "s_mappingConfiguration");
                var throwingMappingConfigurationContainer = new DoubleCheckedLockingContainer <IMappingConfiguration> (
                    () =>
                {
                    throw new InvalidOperationException(
                        "This test failed to setup the mapping configuration. Did you forget to derive from StandardMappingTest or to call base.SetUp?");
                });
                PrivateInvoke.SetNonPublicStaticField(typeof(MappingConfiguration), "s_mappingConfiguration", throwingMappingConfigurationContainer);
            }
            catch (Exception ex)
            {
                Console.WriteLine("SetUpFixture failed: " + ex);
                Console.WriteLine();
                throw;
            }
        }
예제 #32
0
 public DbLogger(DatabaseAgent agent)
     : this()
 {
     this.DatabaseAgent = agent;
 }
예제 #33
0
 public DbParameter CreateParameter(DatabaseAgent agent)
 {
     return agent.CreateParameter(ParameterName, this.value);
 }
        public static DataRelationshipDefinition[] GetDataRelationshipDefinitions(DatabaseAgent sourceDb)
        {
            if (dataRelationships == null)
                dataRelationships = new Dictionary<DatabaseAgent, DataRelationshipDefinition[]>();

            if (!dataRelationships.ContainsKey(sourceDb))
            {
                string sql = @"SELECT FK.constraint_name as ForeignKeyName,
                FK.table_name as ForeignKeyTable,
                FKU.column_name as ForeignKeyColumn,
                UK.constraint_name as PrimaryKeyName,
                UK.table_name as PrimaryKeyTable,
                UKU.column_name as PrimaryKeyColumn
                FROM Information_Schema.Table_Constraints AS FK
                INNER JOIN
                Information_Schema.Key_Column_Usage AS FKU
                ON FK.constraint_type = 'FOREIGN KEY' AND
                FKU.constraint_name = FK.constraint_name
                INNER JOIN
                Information_Schema.Referential_Constraints AS RC
                ON RC.constraint_name = FK.constraint_name
                INNER JOIN
                Information_Schema.Table_Constraints AS UK
                ON UK.constraint_name = RC.unique_constraint_name
                INNER JOIN
                Information_Schema.Key_Column_Usage AS UKU
                ON UKU.constraint_name = UK.constraint_name AND
                UKU.ordinal_position =FKU.ordinal_position";

                List<DataRelationshipDefinition> list = new List<DataRelationshipDefinition>();
                DataTable foreignKeyData = sourceDb.GetDataTableFromSql(sql);
                foreach (DataRow row in foreignKeyData.Rows)
                {
                    list.Add(DataRelationshipDefinition.CreateFromDataRow(row));
                }

                DataRelationshipDefinition[] retVal = list.ToArray();
                dataRelationships.Add(sourceDb, retVal);
                return retVal;
            }
            else
            {
                return dataRelationships[sourceDb];
            }
        }
        public static DataRelationshipDefinition[] GetDataRelationshipDefinitionsWhereTableIsForeignKey(DatabaseAgent sourcedb, string tableName)
        {
            if (!dataRelationships.ContainsKey(sourcedb))
                GetDataRelationshipDefinitions(sourcedb);

            List<DataRelationshipDefinition> returnValues = new List<DataRelationshipDefinition>();
            foreach (DataRelationshipDefinition definition in dataRelationships[sourcedb])
            {
                if (definition.ForeignKeyTable.Equals(tableName))
                    returnValues.Add(definition);
            }

            return returnValues.ToArray();
        }