Пример #1
0
        private bool TestConnection(bool showSuccess)
        {
            Monitor.Enter(databaseLock);


            try
            {
                IDatabaseLoader loader = CreateDatabaseLoader();
                loader.TestConnection();

                if (showSuccess)
                {
                    ShowMessageBox("Success", "Connection succeeded.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                //MessageBox.Show(this, "Connection succeeded.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return(true);
            }
            catch (DatabaseLoaderException e)
            {
                //if (showSuccess)
                ShowMessageBox("Failure", e.ActualMessage, MessageBoxButtons.OK, MessageBoxIcon.Error);
                //MessageBox.Show(this, e.ActualMessage, "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return(false);
            }
            finally
            {
                Monitor.Exit(databaseLock);
            }
        }
Пример #2
0
        private bool TestConnection(bool showSuccess)
        {
            Monitor.Enter(databaseLock);

            IDatabaseLoader loader = CreateDatabaseLoader(form);

            try
            {
                loader.TestConnection();
                if (showSuccess)
                {
                    form.SetDatabaseOperationResults(new DatabaseOperationResults("Connection Test", true));
                }

                return(true);
            }
            catch (DatabaseLoaderException e)
            {
                DatabaseOperationResults results = new DatabaseOperationResults("Connection Test", false, e.ActualMessage);

                form.SetDatabaseOperationResults(results);

                return(false);
            }
            finally
            {
                Monitor.Exit(databaseLock);
            }
        }
Пример #3
0
        private IDatabase GetDatabase(IDatabaseConnector databaseConnector, out IDatabaseLoader databaseLoader, List <SchemaData> tablesToFetch)
        {
            databaseLoader = null;
            _progress.SetCurrentState("Loading Database From Connection String in NHibernate Config File", ProgressState.Normal);

            databaseLoader = DatabaseLoaderFacade.GetDatabaseLoader(databaseConnector);
            databaseLoader.DatabaseObjectsToFetch = tablesToFetch;

            IDatabase database = null;
            bool      success  = false;

            while (success == false)
            {
                try
                {
                    database = databaseLoader.LoadDatabase(databaseLoader.DatabaseObjectsToFetch, null);
                    new DatabaseProcessor().CreateRelationships(database);
                    success = true;
                }
                catch (DatabaseLoaderException e)
                {
                    var loader = _userInteractor.GetDatabaseLoader(databaseConnector);
                    if (loader == null)
                    {
                        throw new NHibernateConfigException("Could not load the database specified in your config file.", e);
                    }
                    databaseLoader = loader;
                    _progress.SetCurrentState("Loading Database From Connection Information Given", ProgressState.Normal);
                }
            }
            return(database);
        }
Пример #4
0
        private void RefreshSchema()
        {
            // Note: this is only ok because this method only runs on the UI thread.
            // Two instances of it will not run at once, so this is not a race condition.
            // The moment it can run from another thread, this assumption is false and the
            // code is incorrect.
            if (RefreshingSchema)
            {
                return;
            }

            databaseLock.WaitOne();

            RefreshingSchema = true;
            IDatabaseLoader loader = CreateDatabaseLoader(form);

            // Test connection first
            if (TestConnection(false) == false)
            {
                databaseLock.Set();
                return;
            }

            Thread thread = new Thread(
                () =>
            {
                try
                {
                    IDatabase newDb = loader.LoadDatabase(loader.DatabaseObjectsToFetch, null);
                    new DatabaseProcessor().CreateRelationships(newDb);

                    if (Database == null || Database.IsEmpty)
                    {
                        Database          = newDb;
                        DatabaseConnector = loader.DatabaseConnector;
                        NewDatabaseCreated.RaiseEvent(this);
                        return;
                    }

                    var result = new DatabaseProcessor().MergeDatabases(Database, newDb);
                    if (result.AnyChanges)
                    {
                        mainPanel.ShowDatabaseRefreshResults(result, Database, newDb);
                        SchemaRefreshed.RaiseEvent(this);
                    }
                    else
                    {
                        form.SetDatabaseOperationResults(new DatabaseOperationResults("Schema Refresh", true, "No schema changes detected."));
                    }
                }
                finally
                {
                    databaseLock.Set();
                    RefreshingSchema = false;
                }
            });

            thread.Start();
        }
Пример #5
0
 public Form1()
 {
     InitializeComponent();
     _databaseLoader     = ServiceLocator.GetInstance <IDatabaseLoader>();
     _templateLoader     = ServiceLocator.GetInstance <ITemplateLoader>();
     _templateTranslator = ServiceLocator.GetInstance <ITemplateTranslator>();
     txtTemplate.Text    = @"F:\Projects2\CodeGen\CodeGen\CodeGen.Templates\ProductMS";
 }
Пример #6
0
        private void Save()
        {
            if (_Database.ConnectionInformation == null)
            {
                IDatabaseLoader dbLoader = DatabasePresenter.CreateDatabaseLoader(ucDatabaseInformation1);

                try
                {
                    _Database = dbLoader.LoadDatabase(dbLoader.DatabaseObjectsToFetch, null);
                }
                catch (DatabaseLoaderException e)
                {
                    #region Save what we can
                    _Database.DatabaseType = ucDatabaseInformation1.SelectedDatabaseType;

                    _Database.ConnectionInformation          = new Helper.ConnectionStringHelper();
                    _Database.ConnectionInformation.FileName = ucDatabaseInformation1.ConnectionStringHelper.FileName;
                    _Database.ConnectionInformation.UseIntegratedSecurity = ucDatabaseInformation1.ConnectionStringHelper.UseIntegratedSecurity;
                    _Database.ConnectionInformation.UserName    = ucDatabaseInformation1.ConnectionStringHelper.UserName;
                    _Database.ConnectionInformation.Password    = ucDatabaseInformation1.ConnectionStringHelper.Password;
                    _Database.ConnectionInformation.Port        = ucDatabaseInformation1.ConnectionStringHelper.Port;
                    _Database.ConnectionInformation.ServerName  = ucDatabaseInformation1.ConnectionStringHelper.ServerName;
                    _Database.ConnectionInformation.ServiceName = ucDatabaseInformation1.ConnectionStringHelper.ServiceName;
                    #endregion

                    //if (e.InnerException != null && e.InnerException.Message.StartsWith("Database cannot be null, the empty string, or string of only whitespace."))
                    //    return;
                    //else
                    //    throw;
                }
            }
            else
            {
                //_Database.Name = ucDatabaseInformation1.ConnectionStringHelper.DatabaseName;
                _Database.DatabaseType = ucDatabaseInformation1.SelectedDatabaseType;
                var connStringHelper = ucDatabaseInformation1.ConnectionStringHelper;

                _Database.ConnectionInformation.FileName = connStringHelper.FileName;
                _Database.ConnectionInformation.UseIntegratedSecurity = connStringHelper.UseIntegratedSecurity;
                _Database.ConnectionInformation.UserName    = connStringHelper.UserName;
                _Database.ConnectionInformation.Password    = connStringHelper.Password;
                _Database.ConnectionInformation.Port        = connStringHelper.Port;
                _Database.ConnectionInformation.ServerName  = connStringHelper.ServerName;
                _Database.ConnectionInformation.ServiceName = connStringHelper.ServiceName;
            }
        }
        internal static bool TestConnection(bool showSuccess, ArchAngel.Providers.EntityModel.UI.PropertyGrids.ucDatabaseInformation dbInfo)
        {
            Monitor.Enter(databaseLock);

            try
            {
                if (!dbInfo.ReadyToProceed())
                {
                    return(false);
                }

                dbInfo.SetDatabaseOperationResults(new DatabaseOperationResults("Testing connection...", true));

                IDatabaseLoader loader = DatabasePresenter.CreateDatabaseLoader(dbInfo);

                try
                {
                    loader.TestConnection();
                    if (showSuccess)
                    {
                        dbInfo.SetDatabaseOperationResults(new DatabaseOperationResults("Connection Test", true));
                    }

                    return(true);
                }
                catch (DatabaseLoaderException e)
                {
                    DatabaseOperationResults results = new DatabaseOperationResults("Connection Test", false, e.ActualMessage);

                    dbInfo.SetDatabaseOperationResults(results);

                    return(false);
                }
            }
            finally
            {
                Monitor.Exit(databaseLock);
            }
        }
        public void A_SQLCEDatabaseLoader_Is_Returned()
        {
            IDatabaseForm form  = MockRepository.GenerateMock <IDatabaseForm>();
            IMainPanel    panel = MockRepository.GenerateMock <IMainPanel>();

            DatabasePresenter presenter = new DatabasePresenter(panel, form);

            form.Stub(t => t.SelectedDatabaseType).Return(DatabaseTypes.SQLCE);
            form.Stub(t => t.SelectedDatabase).Return("1Table3Columns.sdf");

            IDatabaseLoader loader = presenter.CreateDatabaseLoader();

            Assert.That(loader, Is.Not.Null);
            Assert.That(loader, Is.TypeOf(typeof(SQLCEDatabaseLoader)));

            // Will throw an error if the database connection could not be established.
            loader.TestConnection();

            IDatabase db = loader.LoadDatabase();

            Assert.That(db.Name, Is.EqualTo("1Table3Columns"));
            Assert.That(db.Tables, Has.Count(1));             // Basic check to see if we got the correct database back.
        }
        public void A_SQLServer2005DatabaseLoader_Is_Returned()
        {
            IDatabaseForm form  = MockRepository.GenerateMock <IDatabaseForm>();
            IMainPanel    panel = MockRepository.GenerateMock <IMainPanel>();

            DatabasePresenter presenter = new DatabasePresenter(panel, form);

            form.Stub(t => t.SelectedDatabaseType).Return(DatabaseTypes.SQLServer2005);
            form.Stub(t => t.ConnectionStringHelper).Return(new ConnectionStringHelper
            {
                CurrentDbType         = DatabaseTypes.SQLServer2005,
                DatabaseName          = "TestDatabase",
                Password              = "******",
                ServerName            = ".",
                UseFileName           = false,
                UseIntegratedSecurity = false,
                UserName              = "******"
            });

            IDatabaseLoader loader = presenter.CreateDatabaseLoader();

            Assert.That(loader, Is.Not.Null);
            Assert.That(loader, Is.TypeOf(typeof(SQLServer2005DatabaseLoader)));
        }
Пример #10
0
        private void Populate()
        {
            nodeNewTables.Nodes.Clear();
            advTreeTables.BeginUpdate();

            try
            {
                // Fetch all schemas for
                IDatabaseLoader loader = FormDatabase.Instance.CreateDatabaseLoader();
                IDatabase       newDb  = loader.LoadDatabase(loader.DatabaseObjectsToFetch, null);

                foreach (var schema in newDb.Tables.Select(s => s.Schema).Distinct().Where(s => !ExistingSchemas.Contains(s)).OrderBy(s => s))
                {
                    Node schemaNode = new Node(schema)
                    {
                        CheckBoxVisible = true,
                        Checked         = false
                    };
                    nodeNewTables.Nodes.Add(schemaNode);

                    foreach (var table in newDb.Tables.Where(t => t.Schema == schema).Select(t => t.Name).OrderBy(t => t))
                    {
                        Node tableNode = new Node(table)
                        {
                            CheckBoxVisible = true,
                            Checked         = false
                        };
                        schemaNode.Nodes.Add(tableNode);
                    }
                }
            }
            finally
            {
                advTreeTables.EndUpdate();
            }
        }
Пример #11
0
 public ImportSqlDumpJobCommand(IDatabaseLoader loader, IDatabaseSource dst)
 {
     m_loader = loader;
     m_dst    = dst;
 }
Пример #12
0
 public static void LoadSingleFile(string filename, IDatabaseLoader loader)
 {
     AddTable(loader.LoadTableFromFile(filename));
 }
Пример #13
0
 public static void LoadAllMatchingStringFromDirectory(string directory, string searchString, IDatabaseLoader loader)
 {
     foreach (string filename in Directory.EnumerateFiles(directory, searchString))
     {
         LoadSingleFile(filename, loader);
     }
 }
Пример #14
0
        private void RefreshSchema()
        {
            // Note: this is only ok because this method only runs on the UI thread.
            // Two instances of it will not run at once, so this is not a race condition.
            // The moment it can run from another thread, this assumption is false and the
            // code is incorrect.
            if (RefreshingSchema)
            {
                return;
            }

            Cursor = Cursors.WaitCursor;
            databaseLock.WaitOne();
            RefreshingSchema = true;
            IDatabaseLoader loader = CreateDatabaseLoader();

            // Test connection first
            if (TestConnection(false) == false)
            {
                databaseLock.Set();
                RefreshingSchema = false;
                Cursor           = Cursors.Default;
                return;
            }
            labelNoChanges.Visible       = false;
            labelNoChangesExport.Visible = false;

            Thread thread = new Thread(
                () =>
            {
                try
                {
                    List <string> schemasToLimit = Database.Tables.Union(Database.Views).Select(t => t.Schema).Distinct().ToList();
                    IDatabase newDb = loader.LoadDatabase(loader.DatabaseObjectsToFetch, schemasToLimit);
                    new DatabaseProcessor().CreateRelationships(newDb);

                    if (Database.Name == "New Database" && Database.Tables.Count == 0)
                    {
                        var mappingSet = new EntityModel.Controller.MappingLayer.MappingProcessor(new EntityModel.Controller.MappingLayer.OneToOneEntityProcessor())
                                         .CreateOneToOneMapping(newDb, Database.MappingSet.TablePrefixes, Database.MappingSet.ColumnPrefixes, Database.MappingSet.TableSuffixes, Database.MappingSet.ColumnSuffixes);

                        MappingSet = mappingSet;
                        _Database  = newDb;

                        if (NewDatabaseCreated != null)
                        {
                            NewDatabaseCreated(mappingSet);
                        }
                    }
                    else
                    {
                        var result = new DatabaseProcessor().MergeDatabases(Database, newDb);

                        if (result.AnyChanges)
                        {
                            databaseChanges1.Fill(result, Database, newDb);
                            modelChanges1.Fill(result, Database, newDb);
                            SetControlEnabled(buttonImport, true);
                        }
                        else
                        {
                            ShowNoChangesLabel();
                        }
                    }
                }
                finally
                {
                    databaseLock.Set();
                    RefreshingSchema = false;
                    SetCursor(Cursors.Default);
                }
            });

            thread.Start();
        }
Пример #15
0
        private IDatabase GetDatabase(IDatabaseConnector databaseConnector, out IDatabaseLoader databaseLoader, List<SchemaData> tablesToFetch)
        {
            databaseLoader = null;
            _progress.SetCurrentState("Loading Database From Connection String in NHibernate Config File", ProgressState.Normal);

            databaseLoader = DatabaseLoaderFacade.GetDatabaseLoader(databaseConnector);
            databaseLoader.DatabaseObjectsToFetch = tablesToFetch;

            IDatabase database = null;
            bool success = false;

            while (success == false)
            {
                try
                {
                    database = databaseLoader.LoadDatabase(databaseLoader.DatabaseObjectsToFetch, null);
                    new DatabaseProcessor().CreateRelationships(database);
                    success = true;
                }
                catch (DatabaseLoaderException e)
                {
                    var loader = _userInteractor.GetDatabaseLoader(databaseConnector);
                    if (loader == null)
                        throw new NHibernateConfigException("Could not load the database specified in your config file.", e);
                    databaseLoader = loader;
                    _progress.SetCurrentState("Loading Database From Connection Information Given", ProgressState.Normal);
                }
            }
            return database;
        }
Пример #16
0
 public ScreenData(IDatabaseLoader loader)
 {
     Loader = loader;
 }
Пример #17
0
        protected static void Generic_Returns_Correct_Data(Database db, string databaseName, IDatabaseLoader loader)
        {
            Assert.That(db, Is.Not.Null);
            Assert.That(db.Tables, Is.Not.Null);
            Assert.That(db.Tables, Has.Count(1));
            Assert.That(db.Name, Is.EqualTo(databaseName));
            Assert.That(db.Loader, Is.SameAs(loader));

            var table = db.Tables[0];

            Assert.That(table, Is.Not.Null);
            Assert.That(table.Database, Is.SameAs(db));
            Assert.That(table.Name, Is.EqualTo("Table1"));
            Assert.That(table.Columns, Is.Not.Null);
            Assert.That(table.Columns, Has.Count(3));

            var column = table.Columns[0];

            Assert.That(column, Is.Not.Null);
            Assert.That(column.Parent, Is.SameAs(table));
            Assert.That(column.Name, Is.EqualTo("Column1"));
            Assert.That(column.Datatype, Is.EqualTo("int"));
            Assert.That(column.IsIdentity, Is.True, "Column1.IsIdentity should be true");
            Assert.That(column.InPrimaryKey, Is.True);
            Assert.That(column.IsNullable, Is.False);
            Assert.That(column.IsReadOnly, Is.False);
            Assert.That(column.IsUnique, Is.True);
            Assert.That(column.IsUserDefined, Is.False);
            Assert.That(column.OrdinalPosition, Is.EqualTo(1));
            Assert.That(column.Default, Is.EqualTo(""));

            column = table.Columns[1];

            Assert.That(column, Is.Not.Null);
            Assert.That(column.Parent, Is.SameAs(table));
            Assert.That(column.Name, Is.EqualTo("Column2"));
            Assert.That(column.Datatype, Is.EqualTo("nvarchar"));
            Assert.That(column.InPrimaryKey, Is.False);
            Assert.That(column.IsIdentity, Is.False);
            Assert.That(column.IsNullable, Is.True);
            Assert.That(column.IsReadOnly, Is.False);
            Assert.That(column.IsUnique, Is.False);
            Assert.That(column.IsUserDefined, Is.False);
            Assert.That(column.OrdinalPosition, Is.EqualTo(2));
            Assert.That(column.Default, Is.EqualTo(""));

            column = table.Columns[2];

            Assert.That(column, Is.Not.Null);
            Assert.That(column.Parent, Is.SameAs(table));
            Assert.That(column.Name, Is.EqualTo("Column3"));
            Assert.That(column.Datatype, Is.EqualTo("datetime"));
            Assert.That(column.InPrimaryKey, Is.False);
            Assert.That(column.IsIdentity, Is.False);
            Assert.That(column.IsNullable, Is.False);
            Assert.That(column.IsReadOnly, Is.False);
            Assert.That(column.IsUnique, Is.False);
            Assert.That(column.IsUserDefined, Is.False);
            Assert.That(column.OrdinalPosition, Is.EqualTo(3));
            Assert.That(column.Default, Is.EqualTo(""));

            IIndex index = table.Indexes[0];

            Assert.That(index, Is.Not.Null);
            Assert.That(index.Parent, Is.SameAs(table));
            Assert.That(index.Name, Is.EqualTo("PK_Table1"));
            Assert.That(index.Datatype, Is.EqualTo(DatabaseIndexType.PrimaryKey));
            Assert.That(index.IsClustered, Is.False);
            Assert.That(index.IsUnique, Is.True);
            Assert.That(index.IsUserDefined, Is.False);
            Assert.That(index.Columns, Is.Not.Null);
            Assert.That(index.Columns[0].Name, Is.EqualTo("Column1"));
            Assert.That(index.Columns[0].Parent, Is.EqualTo(table));

            index = table.Indexes[1];

            Assert.That(index, Is.Not.Null);
            Assert.That(index.Parent, Is.SameAs(table));
            Assert.That(index.Name, Is.EqualTo("UQ__Table1__000000000000000C"));
            Assert.That(index.Datatype, Is.EqualTo(DatabaseIndexType.Unique));
            Assert.That(index.IsClustered, Is.False);
            Assert.That(index.IsUnique, Is.True);
            Assert.That(index.IsUserDefined, Is.False);
            Assert.That(index.Columns, Is.Not.Null);
            Assert.That(index.Columns[0].Name, Is.EqualTo("Column1"));
            Assert.That(index.Columns[0].Parent, Is.EqualTo(table));
        }
Пример #18
0
        public async Task <IActionResult> Read(ConnectRequest request)
        {
            var loginId = ((Login)HttpContext.Items["Login"]).LoginId;

            int    connectionId = request.ConnectionId;
            string password     = request.Password;

            //check if user is allowed to connect to database
            var connectionProps = await ctx.ConnectionTables.Where(c => c.ConnectionId == connectionId && c.LoginId == loginId).FirstOrDefaultAsync();

            if (connectionProps == null)
            {
                return(BadRequest(new
                {
                    error = true,
                    message = "User not authorized to connect to specified database."
                }));
            }

            //get stereotypes
            var stereotypes = await ctx.Stereotypes.ToListAsync();

            var generationModes = await ctx.GenerationModes.ToListAsync();

            //get generation modes

            //get stereotype mappings
            var mappings = await ctx.NameMappings.ToListAsync();

            string connectionString = $"Host={connectionProps.Host}; Username={connectionProps.Username}; Password={password}; Database={connectionProps.Database}";

            //using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            //{
            //    try
            //    {
            //        connection.Open();
            //    }
            //    catch (Exception)
            //    {
            //        return BadRequest(new
            //        {
            //            error = true,
            //            message = "Could not connect to database"
            //        });
            //    }

            //    List<DatabaseTable> tables = new List<DatabaseTable>();

            //    //sql to get table names
            //    String sql = "SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'; ";

            //    using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
            //    {
            //        using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
            //        {
            //            while (await reader.ReadAsync())
            //            {
            //                tables.Add(new DatabaseTable
            //                {
            //                    Name = reader[1].ToString(),
            //                    DatabaseColumns = new List<DatabaseColumn>(),
            //                    ConnectionId = connectionId,
            //                    NumberOfColumnsToGenerate = 0
            //                });
            //            }
            //        }
            //    }

            //    //columns
            //    foreach (DatabaseTable table in tables)
            //    {
            //        sql = $@"SELECT c.column_name, c.data_type
            //                 FROM information_schema.columns as c
            //                 WHERE c.table_name = '{table.Name}'";

            //        using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
            //        {
            //            using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
            //            {
            //                while (await reader.ReadAsync())
            //                {
            //                    Console.WriteLine(reader[1]);
            //                    var mapping = mappings.Where(mapping => mapping.Name.Trim() == reader[1].ToString().Trim()).FirstOrDefault();
            //                    tables.Find(t => t == table).DatabaseColumns.Add(new DatabaseColumn
            //                    {
            //                        Name = reader[0].ToString(),
            //                        IsUnique = 0,
            //                        IsNullable = 0,
            //                        StereotypeName = stereotypes.Find(s => s.StereotypeId == mapping.StereotypeId).Name,
            //                        StereotypeId = mapping.StereotypeId
            //                    }
            //                    );
            //                }
            //            }
            //        }
            //    }

            //    //primary keys

            //    sql = $@"SELECT tc.table_name, c.column_name, c.data_type
            //                FROM information_schema.table_constraints tc
            //                JOIN information_schema.constraint_column_usage AS ccu USING(constraint_schema, constraint_name)
            //                JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
            //                    AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
            //                WHERE constraint_type = 'PRIMARY KEY' OR constraint_type = 'UNIQUE'; ";

            //    using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
            //    {
            //        using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
            //        {
            //            while (await reader.ReadAsync())
            //            {
            //                var tempColumn = tables.Find(t => t.Name == reader[0].ToString()).DatabaseColumns.Where(c => c.Name == reader[1].ToString()).FirstOrDefault();
            //                //since we just read metadata about the table it should exist if it does not something has gone wrong
            //                if (tempColumn == null)
            //                    throw new Exception($"Read from database that column {tempColumn.Name} is primary key of table {reader[0].ToString()}, but based on previous query that column should not exist.");

            //                tempColumn.IsUnique = 1;
            //            }
            //        }
            //    }


            //    //foreign keys
            //    sql = $@"SELECT
            //                tc.table_name,
            //                kcu.column_name,
            //                ccu.table_name AS foreign_table_name,
            //                ccu.column_name AS foreign_column_name
            //            FROM
            //                information_schema.table_constraints AS tc
            //                JOIN information_schema.key_column_usage AS kcu
            //                    ON tc.constraint_name = kcu.constraint_name
            //                    AND tc.table_schema = kcu.table_schema
            //                JOIN information_schema.constraint_column_usage AS ccu
            //                    ON ccu.constraint_name = tc.constraint_name
            //                    AND ccu.table_schema = tc.table_schema
            //            WHERE tc.constraint_type = 'FOREIGN KEY';";

            //    using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
            //    {
            //        using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
            //        {
            //            while (await reader.ReadAsync())
            //            {
            //                DatabaseColumn temp = tables.Find(t => t.Name == reader[0].ToString()).DatabaseColumns.Where(c => c.Name == reader[1].ToString()).FirstOrDefault();
            //                temp.ForeignTableName = reader[2].ToString();
            //                temp.ForeignColumnName = reader[3].ToString();

            //                // If it's a foreign key give it foreign key generation options
            //                temp.StereotypeId = GenerationModes.FOREIGN_KEY_STEREOTYPE_ID;
            //                temp.StereotypeName = stereotypes.Find(s => s.StereotypeId == GenerationModes.FOREIGN_KEY_STEREOTYPE_ID).Name;
            //            }
            //        }
            //    }

            //    // Check for nullables.
            //    sql = $@"select c.table_name,
            //                   c.column_name,
            //                   c.is_nullable
            //            from information_schema.columns c
            //            join information_schema.tables t
            //                 on c.table_schema = t.table_schema
            //                 and c.table_name = t.table_name
            //            where c.table_schema not in ('pg_catalog', 'information_schema')
            //                  and t.table_type = 'BASE TABLE'
            //            order by table_name,
            //                     column_name;";
            //    using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
            //    {
            //        using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
            //        {
            //            while (await reader.ReadAsync())
            //            {
            //                //Console.WriteLine(reader[2].ToString());
            //                //Console.WriteLine(reader[0].ToString());
            //                //Console.WriteLine(reader[1].ToString());
            //                if(reader[2].ToString() == "YES")
            //                {
            //                    DatabaseColumn temp = tables.Find(t => t.Name == reader[0].ToString()).DatabaseColumns.Where(c => c.Name == reader[1].ToString()).FirstOrDefault();
            //                    temp.IsNullable = 1;
            //                }

            //            }
            //        }
            //    }

            //    // Modify database data with data stored in database
            //    await getSavedData(connectionId, tables);

            //    // If no generation mode is specified give it one that fits with stereotype
            //    foreach(DatabaseTable table in tables)
            //    {
            //        foreach(DatabaseColumn column in table.DatabaseColumns)
            //        {
            //            if(column.GenerationModeId == null)
            //            {
            //                GenerationMode mode = generationModes.Where(m => m.StereotypeId == column.StereotypeId).FirstOrDefault();

            //                if(mode == null)
            //                {
            //                    return BadRequest(new
            //                    {
            //                        error = true,
            //                        message = $"No generation mode for stereotype id ${column.StereotypeId}"
            //                    });
            //                }

            //                column.GenerationModeId = mode.GenerationModeId;
            //            }
            //        }
            //    }

            SqlPlatform databasePlatform = ctx.SqlPlatforms.Where(p => p.SqlPlatformId == connectionProps.SqlPlatformId).FirstOrDefault();

            if (databasePlatform == null)
            {
                return(Ok(new
                {
                    error = true,
                    message = $"Invalid sql platform id {connectionProps.SqlPlatformId}."
                }));
            }

            DatabaseLoaderFactory dataHandlerFactory = new DatabaseLoaderFactory(connectionProps, connectionId, stereotypes, generationModes, mappings, ctx, request.Password);
            IDatabaseLoader       databaseHandler    = dataHandlerFactory.GetLoader(databasePlatform.Name);

            List <DatabaseTable> tables = await databaseHandler.GetTables();

            return(Ok(new
            {
                database = connectionProps.Database,
                host = connectionProps.Host,
                username = connectionProps.Username,
                tables = tables,
                error = false
            }));
            //}
        }
Пример #19
0
 public static Job CreateJob(IDatabaseLoader loader, IDatabaseSource dst, JobProperties jobProps)
 {
     return(Job.FromCommand(new ImportSqlDumpJobCommand(loader, dst), jobProps));
 }
Пример #20
0
        public LoadResult LoadEntityModelFromCSProj(string csprojFilePath, NHConfigFile nhConfigFile)
        {
            _progress.SetCurrentState("Loading Entities From Visual Studio Project", ProgressState.Normal);

            EntityLoader entityLoader = new EntityLoader(new FileController());

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(fileController.ReadAllText(csprojFilePath));
            CSProjFile csProjFile = new CSProjFile(doc, csprojFilePath);
            var        hbmFiles   = GetHBMFilesFromCSProj(csProjFile);

            if (IsFluentProject(csProjFile))
            {
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("UseFluentNHibernate", true);
                string tempFluentPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Visual NHibernate" + Path.DirectorySeparatorChar + "Temp" + Path.DirectorySeparatorChar + "FluentTemp");
                var    fluentHbmFiles = GetHBMFilesForFluentFromCSProj(csProjFile, tempFluentPath);
                // Combine the actual HBM files with the ones derived from FluentNH
                hbmFiles = hbmFiles.Union(fluentHbmFiles);
            }
            else
            {
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("UseFluentNHibernate", false);
            }

            var csFiles  = GetCSharpFilesFromCSProj(doc, csprojFilePath);
            var nhvFiles = GetNHVFilesFromCSProj(doc, csprojFilePath);

            //NHConfigFile nhConfigFile = GetNhConfigFile(csProjFile, fileController);

            var databaseConnector = nhConfigFile == null ? null : nhConfigFile.DatabaseConnector;

            //////// GFH
            // We need to fetch ALL tables, because HBM mappings don't include association tables, or at least it's difficult to find them.
            List <SchemaData> tablesToFetch = null;           // entityLoader.GetTablesFromHbmFiles(hbmFiles);

            IDatabaseLoader loader   = null;
            IDatabase       database = null;

            if (databaseConnector != null)
            {
                database = GetDatabase(databaseConnector, out loader, tablesToFetch);
            }

            _progress.SetCurrentState("Parsing your existing Model Project", ProgressState.Normal);
            var parseResults = ParseResults.ParseCSharpFiles(csFiles);

            _progress.SetCurrentState("Loading Mapping Information From NHibernate Mapping Files", ProgressState.Normal);
            var mappingSet = entityLoader.GetEntities(hbmFiles, parseResults, database);

            entityLoader.ApplyConstraints(mappingSet, nhvFiles, parseResults);

            #region Create References

            // Get a set of all Guids for tables that we will want to create references from
            HashSet <Guid> existingTables = new HashSet <Guid>(database.Tables.Select(t => t.InternalIdentifier));

            foreach (var mappedTable in mappingSet.Mappings.Select(m => m.FromTable))
            {
                existingTables.Add(mappedTable.InternalIdentifier);
            }

            HashSet <Guid> processedRelationships = new HashSet <Guid>();
            foreach (var table in database.Tables)
            {
                foreach (var directedRel in table.DirectedRelationships)
                {
                    var relationship = directedRel.Relationship;

                    if (processedRelationships.Contains(relationship.InternalIdentifier))
                    {
                        continue;                         // Skip relationships that have already been handled.
                    }
                    if (relationship.MappedReferences().Any())
                    {
                        continue;                         // Skip relationships that have been mapped by the user.
                    }
                    if (existingTables.Contains(directedRel.ToTable.InternalIdentifier) == false)
                    {
                        continue;                         // Skip relationships that have tables that have no mapped Entity
                    }
                    if (relationship.PrimaryTable.MappedEntities().FirstOrDefault() == null ||
                        relationship.ForeignTable.MappedEntities().FirstOrDefault() == null)
                    {
                        continue;
                    }
                    ArchAngel.Providers.EntityModel.Controller.MappingLayer.MappingProcessor.ProcessRelationshipInternal(mappingSet, relationship, new ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor());
                    processedRelationships.Add(relationship.InternalIdentifier);
                }
            }
            #endregion

            foreach (var entity in mappingSet.EntitySet.Entities)
            {
                foreach (var reference in entity.References)
                {
                    if (!mappingSet.EntitySet.References.Contains(reference))
                    {
                        mappingSet.EntitySet.AddReference(reference);
                    }
                }
            }

            LoadResult result = new LoadResult();
            result.MappingSet     = mappingSet;
            result.DatabaseLoader = loader;
            result.NhConfigFile   = nhConfigFile;
            result.CsProjFile     = csProjFile;
            return(result);
        }
Пример #21
0
        protected override void DoRun(IJobRunEnv env)
        {
            IDatabaseLoader loader = m_backup.GetLoader(m_dst);

            loader.LoadDatabase(m_dst);
        }
Пример #22
0
 public GameSelectorViewModel(IDatabaseLoader databaseLoader)
 {
     DatabaseLoader    = databaseLoader;
     LoadingVisibility = "Hidden";
 }
 public ScreenData(IDatabaseLoader loader)
 {
     Loader = loader;
 }
Пример #24
0
        protected static void Generic_Returns_Correct_Data(Database db, string databaseName, IDatabaseLoader loader)
        {
            Assert.That(db, Is.Not.Null);
            Assert.That(db.Tables, Is.Not.Null);
            Assert.That(db.Tables, Has.Count(1));
            Assert.That(db.Name, Is.EqualTo(databaseName));
            Assert.That(db.Loader, Is.SameAs(loader));

            var table = db.Tables[0];

            Assert.That(table, Is.Not.Null);
            Assert.That(table.Database, Is.SameAs(db));
            Assert.That(table.Name, Is.EqualTo("Table1"));
            Assert.That(table.Columns, Is.Not.Null);
            Assert.That(table.Columns, Has.Count(3));

            var column = table.Columns[0];

            Assert.That(column, Is.Not.Null);
            Assert.That(column.Parent, Is.SameAs(table));
            Assert.That(column.Name, Is.EqualTo("Column1"));
            Assert.That(column.Datatype, Is.EqualTo("int"));
            Assert.That(column.IsIdentity, Is.True, "Column1.IsIdentity should be true");
            Assert.That(column.InPrimaryKey, Is.True);
            Assert.That(column.IsNullable, Is.False);
            Assert.That(column.IsReadOnly, Is.False);
            Assert.That(column.IsUnique, Is.True);
            Assert.That(column.IsUserDefined, Is.False);
            Assert.That(column.OrdinalPosition, Is.EqualTo(1));
            Assert.That(column.Default, Is.EqualTo(""));

            column = table.Columns[1];

            Assert.That(column, Is.Not.Null);
            Assert.That(column.Parent, Is.SameAs(table));
            Assert.That(column.Name, Is.EqualTo("Column2"));
            Assert.That(column.Datatype, Is.EqualTo("nvarchar"));
            Assert.That(column.InPrimaryKey, Is.False);
            Assert.That(column.IsIdentity, Is.False);
            Assert.That(column.IsNullable, Is.True);
            Assert.That(column.IsReadOnly, Is.False);
            Assert.That(column.IsUnique, Is.False);
            Assert.That(column.IsUserDefined, Is.False);
            Assert.That(column.OrdinalPosition, Is.EqualTo(2));
            Assert.That(column.Default, Is.EqualTo(""));

            column = table.Columns[2];

            Assert.That(column, Is.Not.Null);
            Assert.That(column.Parent, Is.SameAs(table));
            Assert.That(column.Name, Is.EqualTo("Column3"));
            Assert.That(column.Datatype, Is.EqualTo("datetime"));
            Assert.That(column.InPrimaryKey, Is.False);
            Assert.That(column.IsIdentity, Is.False);
            Assert.That(column.IsNullable, Is.False);
            Assert.That(column.IsReadOnly, Is.False);
            Assert.That(column.IsUnique, Is.False);
            Assert.That(column.IsUserDefined, Is.False);
            Assert.That(column.OrdinalPosition, Is.EqualTo(3));
            Assert.That(column.Default, Is.EqualTo(""));

            IIndex index = table.Indexes[0];

            Assert.That(index, Is.Not.Null);
            Assert.That(index.Parent, Is.SameAs(table));
            Assert.That(index.Name, Is.EqualTo("PK_Table1"));
            Assert.That(index.Datatype, Is.EqualTo(DatabaseIndexType.PrimaryKey));
            Assert.That(index.IsClustered, Is.False);
            Assert.That(index.IsUnique, Is.True);
            Assert.That(index.IsUserDefined, Is.False);
            Assert.That(index.Columns, Is.Not.Null);
            Assert.That(index.Columns[0].Name, Is.EqualTo("Column1"));
            Assert.That(index.Columns[0].Parent, Is.EqualTo(table));

            index = table.Indexes[1];

            Assert.That(index, Is.Not.Null);
            Assert.That(index.Parent, Is.SameAs(table));
            Assert.That(index.Name, Is.EqualTo("UQ__Table1__000000000000000C"));
            Assert.That(index.Datatype, Is.EqualTo(DatabaseIndexType.Unique));
            Assert.That(index.IsClustered, Is.False);
            Assert.That(index.IsUnique, Is.True);
            Assert.That(index.IsUserDefined, Is.False);
            Assert.That(index.Columns, Is.Not.Null);
            Assert.That(index.Columns[0].Name, Is.EqualTo("Column1"));
            Assert.That(index.Columns[0].Parent, Is.EqualTo(table));
        }
Пример #25
0
 public override void LoadFromXml(XmlElement xml)
 {
     base.LoadFromXml(xml);
     m_loader = (IDatabaseLoader)DatabaseLoaderAddonType.Instance.LoadAddon(xml.FindElement("Loader"));
     m_dst    = (IDatabaseSource)DatabaseSourceAddonType.Instance.LoadAddon(xml.FindElement("Target"));
 }