Пример #1
0
        private void InitializeThreaded(object state)
        {
            tables      = schemaProvider.GetTables();
            dataTypes   = schemaProvider.GetDataTypes();
            columns     = originalTable.Columns;
            constraints = originalTable.Constraints;
            triggers    = originalTable.Triggers;
            //TODO: indices
            indexes = new IndexSchemaCollection();

            Runtime.LoggingService.Error("TABLE " + originalTable.Name);
            Runtime.LoggingService.Error("   columns = " + columns.Count);
            Runtime.LoggingService.Error("   constraints = " + constraints.Count);

            try {
                foreach (ColumnSchema col in columns)
                {
                    int dummy = col.Constraints.Count;             //get column constraints
                    Runtime.LoggingService.Error("CONSTRAINTS " + col.Name + " " + dummy);
                }
            } catch (Exception ee) {
                Runtime.LoggingService.Error(ee);
                Runtime.LoggingService.Error(ee.StackTrace);
            }

            if (action == SchemaActions.Alter)             //make a duplicate if we are going to alter the table
            {
                this.table = originalTable.Clone() as TableSchema;
            }

            DispatchService.GuiDispatch(delegate() {
                InitializeGui();
            });
        }
Пример #2
0
        public static void RunTableCollectionTemplate(CodeTemplate Parent, TableSchemaCollection Tables, string Path, string Template, string Output, bool debug)
        {
            // admin datamodel
            try
            {

                PreserveRegionsMergeStrategy strategy = new PreserveRegionsMergeStrategy("^[ \t]*(?i:Custom)", "C#");
                CodeTemplate template = null;
                if (!debug)
                {
                    template = Parent.GetCodeTemplateInstance(Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }
                else
                {
                    template = CompileTemplate(Parent, Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }

                if (template != null)
                {
                    template.SetProperty("MultiSourceTable", Tables);
                    template.RenderToFile(Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Output, strategy);
                    Parent.Response.WriteLine("File: " + Output + " Created Successfully");
                }
                else
                {
                    Parent.Response.WriteLine("Template is null: " + Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }
            }
            catch (Exception ex)
            {
                Parent.Response.WriteLine("Template: " + Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                Parent.Response.WriteLine("Error: " + ex.Message);
                Parent.Response.WriteLine("StackTrace: " + ex.StackTrace);
            }
        }
        public override TableSchemaCollection GetTables()
        {
            TableSchemaCollection tables = new TableSchemaCollection();

            IPooledDbConnection conn = connectionPool.Request();
            // Tables need to be ordered bacause TableSchemaCollection is "created" as sorted by default.
            IDbCommand command = conn.CreateCommand(
                "SELECT name, sql FROM sqlite_master WHERE type = 'table' ORDER BY name"
                );

            try {
                using (command) {
                    using (IDataReader r = command.ExecuteReader()) {
                        while (r.Read())
                        {
                            TableSchema table = new TableSchema(this);

                            table.SchemaName    = "main";
                            table.Name          = r.GetString(0);
                            table.IsSystemTable = table.Name.StartsWith("sqlite_");
                            table.Definition    = r.GetString(1);

                            tables.Add(table);
                        }
                        r.Close();
                    }
                }
            } catch (Exception e) {
                QueryService.RaiseException(e);
            }
            conn.Release();

            return(tables);
        }
Пример #4
0
        public static void RunTableCollectionTemplate(CodeTemplate Parent, TableSchemaCollection Tables, string Path, string Template, string Output, bool debug)
        {
            // admin datamodel
            try
            {
                PreserveRegionsMergeStrategy strategy = new PreserveRegionsMergeStrategy("^[ \t]*(?i:Custom)", "C#");
                CodeTemplate template = null;
                if (!debug)
                {
                    template = Parent.GetCodeTemplateInstance(Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }
                else
                {
                    template = CompileTemplate(Parent, Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }

                if (template != null)
                {
                    template.SetProperty("MultiSourceTable", Tables);
                    template.RenderToFile(Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Output, strategy);
                    Parent.Response.WriteLine("File: " + Output + " Created Successfully");
                }
                else
                {
                    Parent.Response.WriteLine("Template is null: " + Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                }
            }
            catch (Exception ex)
            {
                Parent.Response.WriteLine("Template: " + Parent.CodeTemplateInfo.DirectoryName + Path + "\\" + Template);
                Parent.Response.WriteLine("Error: " + ex.Message);
                Parent.Response.WriteLine("StackTrace: " + ex.StackTrace);
            }
        }
Пример #5
0
        void ExportBWDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (_tpsReader == null)
            {
                throw new Exception("TPS Reader is null. Is a file open?");
            }

            object[] args = e.Argument as object[];

            int tableIndex = args[0] as int? ?? -1;

            if (!_tableInfo.ContainsKey(tableIndex))
            {
                return;
            }

            string outputFolder = args[1] as string ?? "";

            if (String.IsNullOrEmpty(outputFolder))
            {
                return;
            }

            //prep our selected tables - GetTableData can look for multiple tables/
            //we'll only be searching for one
            TableSchemaCollection tsc = new TableSchemaCollection();

            tsc.Add(tableIndex, _tableInfo[tableIndex]);
            e.Result = _tpsReader.ExportDataToCSV(tsc, outputFolder);

            return;
        }
Пример #6
0
        /// <summary>
        /// Load all the Entities into the EntityStore.
        /// </summary>
        protected virtual void Initialize(TableSchemaCollection tables, ViewSchemaCollection views, CommandSchemaCollection commands)
        {
            LoadTables(tables);

            LoadViews(views);

            LoadCommands(commands);

            foreach (IEntity entity in EntityStore.Instance.EntityCollection.Values)
            {
                List <IEntity> entities = EntityStore.Instance.EntityCollection.Values.Where(e => e.Name == entity.Name).ToList();
                if (entities.Count > 1)
                {
                    for (int index = 1; index < entities.Count(); index++)
                    {
                        entities[index].AppendNameSuffix(index);
                    }
                }
            }

            // For all entities, Initialize them.
            foreach (IEntity entity in EntityStore.Instance.EntityCollection.Values)
            {
                entity.Initialize();
            }

            foreach (IEntity entity in EntityStore.Instance.EntityCollection.Values)
            {
                entity.ValidateAllMembers();
            }
        }
        public void Initialize(TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }
            if (constraints == null)
            {
                throw new ArgumentNullException("constraints");
            }
            if (tables == null)
            {
                throw new ArgumentNullException("tables");
            }

            this.table       = table;
            this.tables      = tables;
            this.columns     = columns;
            this.constraints = constraints;
            columnSelecter.Initialize(columns);
            foreach (TableSchema tbl in tables)
            {
                if (tbl.Name != table.Name)
                {
                    storeTables.AppendValues(tbl.Name, tbl);
                }
            }
        }
		public override TableSchemaCollection GetTables ()
		{
			TableSchemaCollection tables = new TableSchemaCollection ();
			
			IPooledDbConnection conn = connectionPool.Request ();
			IDbCommand command = conn.CreateCommand (
				"SELECT name, sql FROM sqlite_master WHERE type = 'table'"
			);
			try {
				using (command) {
					using (IDataReader r = command.ExecuteReader()) {
						while (r.Read ()) {
							TableSchema table = new TableSchema (this);
		
							table.SchemaName = "main";
							table.Name = r.GetString (0);
							table.IsSystemTable = table.Name.StartsWith ("sqlite_");
							table.Definition = r.GetString (1);
							
							tables.Add (table);
						}
						r.Close ();
					}
				}
			} catch (Exception e) {
				QueryService.RaiseException (e);
			}
			conn.Release ();

			return tables;
		}
Пример #9
0
    /// <summary>
    /// 生成数据仓库代码
    /// </summary>
    /// <param name="tables"></param>
    /// <returns></returns>
    public int GenerateBusinessRepositoryClasses(TableSchemaCollection tables)
    {
        if (tables == null || tables.Count <= 0)
        {
            return(0);
        }
        int          tempIntTableNum            = 0;
        CodeTemplate BusinessRepositoryTemplate = GetCodeTemplate("BusinessRepository.cst");

        foreach (TableSchema table in tables)
        {
            BusinessRepositoryTemplate.SetProperty("TargetTable", table);
            BusinessRepositoryTemplate.SetProperty("CommonNamespace", CommonNamespace);
            BusinessRepositoryTemplate.SetProperty("BusinessRepositoryNamespace", BusinessRepositoryNamespace);
            BusinessRepositoryTemplate.SetProperty("EntityNamespace", EntityNamespace);
            BusinessRepositoryTemplate.SetProperty("DBUtilityNamespace", DBUtilityNamespace);
            BusinessRepositoryTemplate.SetProperty("CreatePerson", CreatePerson);
            BusinessRepositoryTemplate.SetProperty("CompanyName", CompanyName);
            BusinessRepositoryTemplate.SetProperty("BusinessRepositorySuffix", BusinessRepositorySuffix);
            BusinessRepositoryTemplate.SetProperty("FileDesc", "表[" + table.Name + "]的 BusinessReposity 层代码");
            string tempFilePath = string.Format(@"{0}{1}\{2}", this.OutputDirectory, BusinessRepositoryNamespace, BusinessRepositoryTemplate.GetFileName());
            BusinessRepositoryTemplate.RenderToFile(tempFilePath, true);
            WriteInfo("成功在路径[" + this.OutputDirectory + BusinessRepositoryNamespace + "] 生成 BusinessReposity 层代码文件:" + BusinessRepositoryTemplate.GetFileName() + "");
            tempIntTableNum++;
        }
        WriteInfo("-----成功在路径[" + this.OutputDirectory + BusinessRepositoryNamespace + "] 生成:" + tempIntTableNum + " 个 BusinessReposity 层代码文件-----");
        return(tempIntTableNum);
    }
        public void Initialize(TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints, DataTypeSchemaCollection dataTypes)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }
            if (constraints == null)
            {
                throw new ArgumentNullException("constraints");
            }
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }
            if (tables == null)
            {
                throw new ArgumentNullException("tables");
            }

            IDbFactory fac = schemaProvider.ConnectionPool.DbFactory;

            if (fac.IsCapabilitySupported("Table", action, TableCapabilities.PrimaryKeyConstraint))
            {
                //not for column constraints, since they are already editable in the column editor
                pkEditor = new PrimaryKeyConstraintEditorWidget(schemaProvider, action, table, columns, constraints);
                pkEditor.ContentChanged += new EventHandler(OnContentChanged);
                notebook.AppendPage(pkEditor, new Label(GettextCatalog.GetString("Primary Key")));
            }

            if (fac.IsCapabilitySupported("Table", action, TableCapabilities.ForeignKeyConstraint) ||
                fac.IsCapabilitySupported("TableColumn", action, TableCapabilities.ForeignKeyConstraint))
            {
                fkEditor = new ForeignKeyConstraintEditorWidget(schemaProvider, action, tables, table, columns, constraints);
                fkEditor.ContentChanged += new EventHandler(OnContentChanged);
                notebook.AppendPage(fkEditor, new Label(GettextCatalog.GetString("Foreign Key")));
            }

            if (fac.IsCapabilitySupported("Table", action, TableCapabilities.CheckConstraint) ||
                fac.IsCapabilitySupported("TableColumn", action, TableCapabilities.CheckConstraint))
            {
                checkEditor = new CheckConstraintEditorWidget(schemaProvider, action, table, columns, constraints);
                checkEditor.ContentChanged += new EventHandler(OnContentChanged);
                notebook.AppendPage(checkEditor, new Label(GettextCatalog.GetString("Check")));
            }

            if (fac.IsCapabilitySupported("Table", action, TableCapabilities.UniqueConstraint) ||
                fac.IsCapabilitySupported("TableColumn", action, TableCapabilities.CheckConstraint))
            {
                uniqueEditor = new UniqueConstraintEditorWidget(schemaProvider, action, table, columns, constraints);
                uniqueEditor.ContentChanged += new EventHandler(OnContentChanged);
                notebook.AppendPage(uniqueEditor, new Label(GettextCatalog.GetString("Unique")));
            }

            ShowAll();
        }
Пример #11
0
        public override TableSchemaCollection GetTables()
        {
            TableSchemaCollection tables = new TableSchemaCollection();

            using (IPooledDbConnection conn = connectionPool.Request()) {
                using (IDbCommand command = conn.CreateCommand(@"SELECT 
															su.name AS owner, 
															so.name as table_name, 
															so.id as table_id,										
															so.crdate as created_date, 
															so.xtype as table_type
														FROM dbo.sysobjects so, 
															dbo.sysusers su 
														WHERE
															xtype IN ('S','U')
															AND su.uid = so.uid
														ORDER BY 1, 2"                                                        )) {
                    try {
                        using (command) {
                            using (IDataReader r = command.ExecuteReader()) {
                                while (r.Read())
                                {
                                    TableSchema table = new TableSchema(this);
                                    table.Name = r.GetString(1);
                                    if (r.GetString(4) == "S")
                                    {
                                        table.IsSystemTable = true;
                                    }
                                    else
                                    if (Array.Exists(system_tables, delegate(string s) { return(s == table.Name); }))
                                    {
                                        table.IsSystemTable = true;
                                    }
                                    else
                                    {
                                        table.IsSystemTable = false;
                                    }
                                    table.OwnerName  = r.GetString(0);
                                    table.Definition = GetTableDefinition(table);
                                    tables.Add(table);
                                }
                                r.Close();
                            }
                        }
                    } catch (Exception e) {
                        QueryService.RaiseException(e);
                    } finally {
                        conn.Release();
                    }
                }
            }
            return(tables);
        }
Пример #12
0
        public void Initialize(TableSchemaCollection tables)
        {
            this.tables = tables;

            store = new SortedTableListStore(tables);
            store.TableToggled += delegate(object sender, EventArgs args) {
                if (TableToggled != null)
                {
                    TableToggled(this, args);
                }
            };
            list.Model = store.Store;
        }
Пример #13
0
        /// <summary>
        /// Converts one file
        /// </summary>
        static void ConvertSingleFile()
        {
            if (!File.Exists(_sourceFile))
            {
                Console.Error.WriteLine("Error: Cannot find source file: " + _sourceFile);
                return;
            }
            if (!Directory.Exists(_outputDirectory))
            {
                Console.Error.WriteLine("Error: Cannot find output directory: " + _outputDirectory);
                return;
            }

            if (!_quiet)
            {
                Console.WriteLine("Starting conversion of file: " + _sourceFile);
            }
            //Open th TPS File
            TPSReader.TPSReader tpsR = new TPSReader.TPSReader(_sourceFile);
            tpsR.Open();
            tpsR.Process();             //process the file

            TableSchemaCollection tsc           = tpsR.GetTableSchemas();
            TableSchemaCollection limittoTables = new TableSchemaCollection();

            //If we are going to limit the table output... then make sure they are in the collection
            if (_tables.Count > 0)
            {
                foreach (TableSchema ts in tsc.Values)
                {
                    if (_tables.Contains(ts.TableName))
                    {
                        limittoTables.Add(ts.TableID, ts);
                    }
                }
            }

            if (_tables.Count > 0)
            {
                tpsR.ExportDataToCSV(limittoTables, _outputDirectory);
            }
            else
            {
                tpsR.ExportDataToCSV(tsc, _outputDirectory);
            }

            if (!_quiet)
            {
                Console.WriteLine("Done converting file: " + _sourceFile);
            }
        }
Пример #14
0
        private void ExecuteQueryCallback(DatabaseConnectionContext context, bool connected, object state)
        {
            if (!connected)
            {
                MessageService.ShowError(
                    AddinCatalog.GetString("Unable to connect to database '{0}'"), context.ConnectionSettings.Name);
                return;
            }

            ISchemaProvider provider = context.SchemaProvider;

            tables = provider.GetTables();

            DispatchService.GuiDispatch(delegate() {
                //TODO: initialize the table mapper
            });
        }
Пример #15
0
        /// <summary>
        /// </summary>
        /// <param name="database"></param>
        public SchemaExplorerEntityProvider(DatabaseSchema database)
        {
            _database = database;

            if (_database != null)
            {
                if (!_database.DeepLoad)
                {
                    _database.DeepLoad = true;
                    _database.Refresh();
                }

                _tables   = _database.Tables;
                _views    = _database.Views;
                _commands = _database.Commands;
            }
        }
 public bool ContainsForeignKey(SearchCriteria sc, TableSchemaCollection tsc)
 {
     foreach (TableSchema ts in tsc)
     {
         foreach (TableKeySchema tks in ts.PrimaryKeys)
         {
             foreach (MemberColumnSchema mcs in sc.Items)
             {
                 if (tks.PrimaryKeyMemberColumns.Contains(mcs))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
Пример #17
0
        private void InitializeThreaded(object state)
        {
            tables      = schemaProvider.GetTables();
            dataTypes   = schemaProvider.GetDataTypes();
            columns     = originalTable.Columns;
            constraints = originalTable.Constraints;
            triggers    = originalTable.Triggers;
            //TODO: indices
            indexes = new IndexSchemaCollection();

            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            builder.Append("Loading editor for TABLE ");
            builder.Append(originalTable.Name);
            builder.AppendLine();
            builder.Append("    columns = ");
            builder.Append(columns.Count);
            builder.AppendLine();
            builder.Append("constraints = ");
            builder.Append(constraints.Count);
            builder.AppendLine();

            try {
                foreach (ColumnSchema col in columns)
                {
                    int dummy = col.Constraints.Count;                     //get column constraints
                    builder.Append("CONSTRAINTS ");
                    builder.Append(col.Name);
                    builder.Append(" ");
                    builder.Append(dummy);
                    builder.AppendLine();
                }
                LoggingService.LogDebug(builder.ToString());
            } catch (Exception ee) {
                LoggingService.LogDebug(builder.ToString());
                LoggingService.LogError(ee.ToString());
            }

            if (action == SchemaActions.Alter)             //make a duplicate if we are going to alter the table
            {
                this.table = originalTable.Clone() as TableSchema;
            }

            DispatchService.GuiDispatch(delegate() {
                InitializeGui();
            });
        }
 public override TableSchemaCollection GetTables()
 {
     TableSchemaCollection tables = new TableSchemaCollection ();
     Console.WriteLine("getTables");
     using (IPooledDbConnection conn = connectionPool.Request ()) {
         Console.WriteLine("conn:"+conn.ToString());
         MongoDbConnection connection = (MongoDbConnection) conn.DbConnection;
         Console.WriteLine("connection:"+connection.ToString());
         foreach(string colName in connection.getCollections()){
             TableSchema col = new TableSchema(this);
             Console.WriteLine("table add:"+colName);
             col.Name = colName;
             tables.Add(col);
         }
     }
     return tables;
 }
Пример #19
0
		public SortedTableListStore (TableSchemaCollection tables)
		{
			if (tables == null)
				throw new ArgumentNullException ("tables");
			
			this.tables = tables;
			
			store = new ListStore (typeof (bool), typeof (string), typeof (TableSchema));
			store.SetSortColumnId (ColNameIndex, SortType.Ascending);
			store.SetSortFunc (ColNameIndex, new TreeIterCompareFunc (SortName));
			
			foreach (TableSchema table in tables)
				AddTable (table);
			
			tables.ItemAdded += new SortedCollectionItemEventHandler<TableSchema> (OnTableAdded);
			tables.ItemRemoved += new SortedCollectionItemEventHandler<TableSchema> (OnTableRemoved);
		}
Пример #20
0
        void FileInfoBWRunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //Close the Please wait
            if (_pleaseWait != null)
            {
                try{
                    _pleaseWait.Close();
                }catch (Exception) {}
            }
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
                return;
            }

            if (e.Result == null)
            {
                return;
            }

            //save our new table info
            _tableInfo = e.Result as TableSchemaCollection;

            //clear out the other GUI items
            tableList.Items.Clear();
            tableFieldList.Items.Clear();

            try{
                //setup our new gui
                foreach (TableSchema ts in _tableInfo.Values)
                {
                    if (ts.TableName == null)
                    {
                        MessageBox.Show("Table Name is null:  " + ts.TableID.ToString());
                    }
                    tableList.Items.Add(ts.TableName);
                }
            }catch (Exception ex) {
                MessageBox.Show("Error: Cannot add table to table list: " + ex.ToString());
            }

            _selectedTableID         = -1;
            toolStripLoadedFile.Text = "File: " + _tpsFilename;
        }
Пример #21
0
        /// <summary>
        /// </summary>
        /// <param name="tables"></param>
        /// <param name="views"></param>
        /// <param name="commands"></param>
        public SchemaExplorerEntityProvider(TableSchemaCollection tables, ViewSchemaCollection views, CommandSchemaCollection commands)
        {
            _tables   = tables;
            _views    = views;
            _commands = commands;

            if (_tables != null && _tables.Count > 0)
            {
                _database = _tables[0].Database;
            }
            else if (_views != null && _views.Count > 0)
            {
                _database = _views[0].Database;
            }
            else if (_commands != null && _commands.Count > 0)
            {
                _database = _commands[0].Database;
            }
        }
		public void Initialize (TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints, DataTypeSchemaCollection dataTypes)
		{
			if (columns == null)
				throw new ArgumentNullException ("columns");
			if (constraints == null)
				throw new ArgumentNullException ("constraints");
			if (table == null)
				throw new ArgumentNullException ("table");
			if (tables == null)
				throw new ArgumentNullException ("tables");

			IDbFactory fac = schemaProvider.ConnectionPool.DbFactory;
			if (fac.IsCapabilitySupported ("Table", action, TableCapabilities.PrimaryKeyConstraint)) {
				//not for column constraints, since they are already editable in the column editor
				pkEditor = new PrimaryKeyConstraintEditorWidget (schemaProvider, action, table, columns, constraints);
				pkEditor.ContentChanged += new EventHandler (OnContentChanged);
				notebook.AppendPage (pkEditor, new Label (GettextCatalog.GetString ("Primary Key")));
			}
			
			if (fac.IsCapabilitySupported ("Table", action, TableCapabilities.ForeignKeyConstraint)
				|| fac.IsCapabilitySupported ("TableColumn", action, TableCapabilities.ForeignKeyConstraint)) {
				fkEditor = new ForeignKeyConstraintEditorWidget (schemaProvider, action, tables, table, columns, constraints);
				fkEditor.ContentChanged += new EventHandler (OnContentChanged);
				notebook.AppendPage (fkEditor, new Label (GettextCatalog.GetString ("Foreign Key")));
			}
			
			if (fac.IsCapabilitySupported ("Table", action, TableCapabilities.CheckConstraint)
				|| fac.IsCapabilitySupported ("TableColumn", action, TableCapabilities.CheckConstraint)) {
				checkEditor = new CheckConstraintEditorWidget (schemaProvider, action, table, columns, constraints);
				checkEditor.ContentChanged += new EventHandler (OnContentChanged);
				notebook.AppendPage (checkEditor, new Label (GettextCatalog.GetString ("Check")));
			}
			
			if (fac.IsCapabilitySupported ("Table", action, TableCapabilities.UniqueConstraint)
				|| fac.IsCapabilitySupported ("TableColumn", action, TableCapabilities.CheckConstraint)) {
				uniqueEditor = new UniqueConstraintEditorWidget (schemaProvider, action, table, columns, constraints);
				uniqueEditor.ContentChanged += new EventHandler (OnContentChanged);
				notebook.AppendPage (uniqueEditor, new Label (GettextCatalog.GetString ("Unique")));
			}

			ShowAll ();
		}
Пример #23
0
		public override TableSchemaCollection GetTables ()
		{
			TableSchemaCollection tables = new TableSchemaCollection ();
			using (IPooledDbConnection conn = connectionPool.Request ()) {
				using (IDbCommand command = conn.CreateCommand (
					@"SELECT DISTINCT 
						c.relname, 
						n.nspname, 
						u.usename
					FROM 
						pg_class c, 
						pg_namespace n, 
						pg_user u
					WHERE 	
						c.relnamespace = n.oid
						AND c.relowner = u.usesysid
						AND c.relkind='r' 
						AND NOT EXISTS
							(SELECT 1 FROM pg_rewrite r WHERE r.ev_class = c.oid AND r.ev_type = '1')
					ORDER BY relname;")) {
					try {
						using (IDataReader r = command.ExecuteReader()) {
							while (r.Read ()) {
								TableSchema table = new TableSchema (this);
								table.Name = r.GetString (0);
								table.IsSystemTable = table.Name.StartsWith ("pg_") || table.Name.StartsWith ("sql_");
								table.SchemaName = r.GetString (1);
								table.OwnerName = r.GetString (2);
								// TODO: Fill table.Definition
								tables.Add (table);
							}
							r.Close ();
						}
					} catch (Exception e) {
						QueryService.RaiseException (e);
					} finally {
						conn.Release ();
					}
				}
			}
			return tables;
        /// <summary>
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public static TableSchemaCollection ToCollection(this IEnumerable <IEntity> entities)
        {
            if (entities == null)
            {
                return(null);
            }

            var collection = new TableSchemaCollection();

            foreach (IEntity entity in entities)
            {
                var tableEntity = entity as TableEntity;
                if (tableEntity != null)
                {
                    collection.Add((tableEntity).EntitySource as TableSchema);
                }
            }

            return(collection);
        }
Пример #25
0
        private void BuildChildNodesThreaded(object state)
        {
            BaseNode              node              = state as BaseNode;
            ITreeBuilder          builder           = Context.GetTreeBuilder(state);
            bool                  showSystemObjects = (bool)builder.Options["ShowSystemObjects"];
            TableSchemaCollection tables            = node.ConnectionContext.SchemaProvider.GetTables();

            DispatchService.GuiDispatch(delegate {
                foreach (TableSchema table in tables)
                {
                    if (table.IsSystemTable && !showSystemObjects)
                    {
                        continue;
                    }

                    builder.AddChild(new TableNode(node.ConnectionContext, table));
                }
                builder.Expanded = true;
            });
        }
        private void EnsureEntitiesExists(TableSchemaCollection value)
        {
            // If entities exist then return.
            if (_entities != null && _entities.Count > 0)
            {
                return;
            }

            // The entities haven't been set yet, so lets set them if there is atleast one table passed in.
            if (value == null || value.Count <= 0)
            {
                return;
            }

            bool previousValue = _canPopulateEntities;

            _canPopulateEntities = true;
            SourceDatabase       = value[0].Database;
            _canPopulateEntities = previousValue;
        }
Пример #27
0
        protected void OnCreateTable()
        {
            BaseNode            node           = CurrentNode.DataItem as BaseNode;
            IDbFactory          fac            = node.ConnectionContext.DbFactory;
            IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;

            // Need to detect if it is a previous (saved) table with the same name.
            string name    = AddinCatalog.GetString("NewTable");
            int    lastIdx = 0;
            TableSchemaCollection tables = schemaProvider.GetTables();

            for (int t = tables.Count - 1; t > -1; t--)
            {
                if (tables[t].Name.ToLower() == name.ToLower())
                {
                    name = string.Concat(name, "1");
                    break;
                }
                else if (tables[t].Name.StartsWith(name, StringComparison.OrdinalIgnoreCase))
                {
                    string idx = tables[t].Name.Substring(name.Length);
                    int    newIdx;
                    if (int.TryParse(idx, out newIdx))
                    {
                        lastIdx = newIdx;
                        break;
                    }
                }
            }
            if (lastIdx != 0)
            {
                name = String.Concat(name, lastIdx + 1);
            }

            TableSchema table = schemaProvider.CreateTableSchema(name);

            if (fac.GuiProvider.ShowTableEditorDialog(schemaProvider, table, true))
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(OnCreateTableThreaded), new object[] { schemaProvider, table, node } as object);
            }
        }
        public SortedTableListStore(TableSchemaCollection tables)
        {
            if (tables == null)
            {
                throw new ArgumentNullException("tables");
            }

            this.tables = tables;

            store = new ListStore(typeof(bool), typeof(string), typeof(TableSchema));
            store.SetSortColumnId(ColNameIndex, SortType.Ascending);
            store.SetSortFunc(ColNameIndex, new TreeIterCompareFunc(SortName));

            foreach (TableSchema table in tables)
            {
                AddTable(table);
            }

            tables.ItemAdded   += new SortedCollectionItemEventHandler <TableSchema> (OnTableAdded);
            tables.ItemRemoved += new SortedCollectionItemEventHandler <TableSchema> (OnTableRemoved);
        }
Пример #29
0
        void FileInfoBWDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            string filename = e.Argument as string;

            if (!System.IO.File.Exists(filename))
            {
                throw new Exception("TPS File does not exist");
            }

            _tpsReader = new TPSReader.TPSReader(filename);
            _tpsReader.Open();

            //Process the TPS File
            _tpsReader.Process();

            //Get The Table List
            TableSchemaCollection tableSchemas = _tpsReader.GetTableSchemas();

            e.Result = tableSchemas;

            return;
        }
Пример #30
0
        private bool IsDependantOfInternal(TableSchema table, TableSchemaCollection checkedTables)
        {
            //        for(int i;i < table.ForeignKeys.Count;i++)
            //        {
            //            TableSchema primaryKeyTable = table.ForeignKeys[i].PrimaryKeyTable;
            //            if (!primaryKeyTable.Equals(this))
            //            {
            //                if (!checkedTables.Contains(primaryKeyTable))
            //                {
            //                    checkedTables.Add(primaryKeyTable);
            //                }
            //            }
            //        }



            //if (this.IsDependantOfInternal(primaryKeyTable, checkedTables))
            //{

            //}

            return(false);
        }
Пример #31
0
        public void Initialize(TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints, DataTypeSchemaCollection dataTypes)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }
            if (constraints == null)
            {
                throw new ArgumentNullException("constraints");
            }
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }
            if (tables == null)
            {
                throw new ArgumentNullException("tables");
            }

            if (pkEditor != null)
            {
                pkEditor.Initialize(table, columns, constraints);
            }
            if (fkEditor != null)
            {
                fkEditor.Initialize(tables, table, columns, constraints);
            }
            if (checkEditor != null)
            {
                checkEditor.Initialize(table, columns, constraints);
            }
            if (uniqueEditor != null)
            {
                uniqueEditor.Initialize(table, columns, constraints);
            }
        }
Пример #32
0
        void TableDataBWDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (_tpsReader == null)
            {
                throw new Exception("TPS Reader is null. Is a file open?");
            }

            int tableIndex = e.Argument as int? ?? -1;

            if (!_tableInfo.ContainsKey(tableIndex))
            {
                return;
            }


            //prep our selected tables - GetTableData can look for multiple tables/
            //we'll only be searching for one
            TableSchemaCollection tsc = new TableSchemaCollection();

            tsc.Add(tableIndex, _tableInfo[tableIndex]);
            e.Result = _tpsReader.GetTableData(tsc);

            return;
        }
Пример #33
0
        // see: http://dev.mysql.com/doc/refman/5.1/en/tables-table.html
        // // see: http://dev.mysql.com/doc/refman/5.1/en/show-create-table.html
        public override TableSchemaCollection GetTables()
        {
            TableSchemaCollection tables = new TableSchemaCollection();

            using (IPooledDbConnection conn = connectionPool.Request()) {
                // Second Connection - MySql Connector doesn't allow more than 1 datareader by connection.
                IPooledDbConnection conn2 = connectionPool.Request();
                using (IDbCommand command = conn.CreateCommand("SHOW TABLES;")) {
                    try {
                        if (GetMainVersion(command) >= 5)
                        {
                            //in mysql 5.x we can use an sql query to provide the comment
                            command.CommandText = string.Format(
                                @"SELECT 
														TABLE_NAME, 
														TABLE_SCHEMA, 
														TABLE_TYPE, 
														TABLE_COMMENT 
													FROM `information_schema`.`TABLES`
													WHERE 
														TABLE_TYPE='BASE TABLE' 
														AND TABLE_SCHEMA='{0}' 
													ORDER BY TABLE_NAME;"                                                    , command.Connection.Database);
                            using (IDataReader r = command.ExecuteReader()) {
                                while (r.Read())
                                {
                                    TableSchema table = new TableSchema(this);
                                    table.Name       = r.GetString(0);
                                    table.SchemaName = r.GetString(1);
                                    table.Comment    = r.IsDBNull(3) ? null : r.GetString(3);

                                    using (IDbCommand command2 = conn2.CreateCommand(
                                               string.Concat("SHOW CREATE TABLE `",
                                                             table.Name, "`;"))) {
                                        using (IDataReader r2 = command2.ExecuteReader()) {
                                            r2.Read();
                                            table.Definition = r2.GetString(1);
                                        }
                                    }
                                    tables.Add(table);
                                }
                                r.Close();
                            }
                        }
                        else
                        {
                            //use the default command for mysql 4.x and 3.23
                            using (IDataReader r = command.ExecuteReader()) {
                                while (r.Read())
                                {
                                    TableSchema table = new TableSchema(this);

                                    table.Name       = r.GetString(0);
                                    table.SchemaName = command.Connection.Database;

                                    using (IDbCommand command2 = conn2.CreateCommand(string.Concat(
                                                                                         "SHOW CREATE TABLE `",
                                                                                         table.Name, "`;"))) {
                                        using (IDataReader r2 = command2.ExecuteReader()) {
                                            r2.Read();
                                            table.Definition = r2.GetString(1);
                                        }
                                    }
                                    tables.Add(table);
                                }
                                r.Close();
                            }
                        }
                    } catch (Exception e) {
                        QueryService.RaiseException(e);
                    } finally {
                        conn.Release();
                        conn2.Release();
                    }
                }
            }
            return(tables);
        }
Пример #34
0
        /// <summary>
        /// 通用根据模板生成文件方法
        /// </summary>
        /// <param name="isRender"></param>
        /// <param name="templatePath"></param>
        /// <param name="directory"></param>
        /// <param name="Tables"></param>
        /// <param name="fileName"></param>
        public void RenderToFileByTablesFixFileName(bool isRender, string templatePath, string directory, TableSchemaCollection Tables, string fileName = null)
        {
            if (isRender)
            {
                if (directory.IndexOf("{dbname}") >= 0)
                {
                    directory = directory.Replace("{dbname}", Tables[0].Database.Name);
                }
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = Tables[0].Database.Name;
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(fileName) && fileName.IndexOf("{dbname}") >= 0)
                    {
                        fileName = fileName.Replace("{dbname}", Tables[0].Database.Name);
                    }
                }
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                //载入子模板
                CodeTemplate template = GetCodeTemplate(templatePath);

                //CopyPropertiesTo(template);

                template.SetProperty("Tables", Tables);

                template.RenderToFile(directory + fileName, true);

                Response.WriteLine(templatePath + "代码生成完毕!");
            }
        }
		public void Initialize (TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints)
		{
			if (columns == null)
				throw new ArgumentNullException ("columns");
			if (table == null)
				throw new ArgumentNullException ("table");
			if (constraints == null)
				throw new ArgumentNullException ("constraints");
			if (tables == null)
				throw new ArgumentNullException ("tables");
			
			this.table = table;
			this.tables = tables;
			this.columns = columns;
			this.constraints = constraints;
			columnSelecter.Initialize (columns);
			foreach (TableSchema tbl in tables)
				if (tbl.Name != table.Name)
					storeTables.AppendValues (tbl.Name, tbl);
		}
		//TODO: difference between columns and reference columns + combo events
		public ForeignKeyConstraintEditorWidget (ISchemaProvider schemaProvider, SchemaActions action, TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints)
		{
			if (columns == null)
				throw new ArgumentNullException ("columns");
			if (table == null)
				throw new ArgumentNullException ("table");
			if (constraints == null)
				throw new ArgumentNullException ("constraints");
			if (schemaProvider == null)
				throw new ArgumentNullException ("schemaProvider");
			if (tables == null)
				throw new ArgumentNullException ("tables");
			
			this.schemaProvider = schemaProvider;
			this.table = table;
			this.tables = tables;
			this.columns = columns;
			this.constraints = constraints;
			this.action = action;
			
			this.Build();
			
			store = new ListStore (typeof (string), typeof (string), typeof (bool), typeof (string), typeof (string), typeof (string), typeof (string), typeof (object));
			listFK.Model = store;
			
			storeActions = new ListStore (typeof (string), typeof (int));
			storeTables = new ListStore (typeof (string));
			
			IDbFactory fac = schemaProvider.ConnectionPool.DbFactory;
			if (fac.IsCapabilitySupported ("ForeignKeyConstraint", action,  ForeignKeyConstraintCapabilities.Cascade))
				storeActions.AppendValues ("Cascade", ForeignKeyAction.Cascade);
			if (fac.IsCapabilitySupported ("ForeignKeyConstraint", action,  ForeignKeyConstraintCapabilities.Restrict))
				storeActions.AppendValues ("Restrict", ForeignKeyAction.Restrict);
			if (fac.IsCapabilitySupported ("ForeignKeyConstraint", action,  ForeignKeyConstraintCapabilities.NoAction))
				storeActions.AppendValues ("No Action", ForeignKeyAction.NoAction);
			if (fac.IsCapabilitySupported ("ForeignKeyConstraint", action,  ForeignKeyConstraintCapabilities.SetNull))
				storeActions.AppendValues ("Set Null", ForeignKeyAction.SetNull);
			if (fac.IsCapabilitySupported ("ForeignKeyConstraint", action,  ForeignKeyConstraintCapabilities.SetDefault))
				storeActions.AppendValues ("Set Default", ForeignKeyAction.SetDefault);

			foreach (TableSchema tbl in tables)
				if (tbl.Name != table.Name)
					storeTables.AppendValues (tbl.Name);
			
			TreeViewColumn colName = new TreeViewColumn ();
			TreeViewColumn colRefTable = new TreeViewColumn ();
			TreeViewColumn colIsColumnConstraint = new TreeViewColumn ();
			TreeViewColumn colDeleteAction = new TreeViewColumn ();
			TreeViewColumn colUpdateAction = new TreeViewColumn ();
			
			colName.Title = GettextCatalog.GetString ("Name");
			colRefTable.Title = GettextCatalog.GetString ("Reference Table");
			colIsColumnConstraint.Title = GettextCatalog.GetString ("Column Constraint");
			colDeleteAction.Title = GettextCatalog.GetString ("Delete Action");
			colUpdateAction.Title = GettextCatalog.GetString ("Update Action");
			
			colRefTable.MinWidth = 120;
			
			CellRendererText nameRenderer = new CellRendererText ();
			CellRendererCombo refTableRenderer = new CellRendererCombo ();
			CellRendererToggle isColumnConstraintRenderer = new CellRendererToggle ();
			CellRendererCombo deleteActionRenderer = new CellRendererCombo ();
			CellRendererCombo updateActionRenderer = new CellRendererCombo ();
			
			nameRenderer.Editable = true;
			nameRenderer.Edited += new EditedHandler (NameEdited);
			
			refTableRenderer.Model = storeTables;
			refTableRenderer.TextColumn = 0;
			refTableRenderer.Editable = true;
			refTableRenderer.Edited += new EditedHandler (RefTableEdited);
			
			isColumnConstraintRenderer.Activatable = true;
			isColumnConstraintRenderer.Toggled += new ToggledHandler (IsColumnConstraintToggled);
			
			deleteActionRenderer.Model = storeActions;
			deleteActionRenderer.TextColumn = 0;
			deleteActionRenderer.Editable = true;
			deleteActionRenderer.Edited += new EditedHandler (DeleteActionEdited);
			
			updateActionRenderer.Model = storeActions;
			updateActionRenderer.TextColumn = 0;
			updateActionRenderer.Editable = true;
			updateActionRenderer.Edited += new EditedHandler (UpdateActionEdited);

			colName.PackStart (nameRenderer, true);
			colRefTable.PackStart (refTableRenderer, true);
			colIsColumnConstraint.PackStart (isColumnConstraintRenderer, true);
			colDeleteAction.PackStart (deleteActionRenderer, true);
			colUpdateAction.PackStart (updateActionRenderer, true);

			colName.AddAttribute (nameRenderer, "text", colNameIndex);
			colRefTable.AddAttribute (refTableRenderer, "text", colReferenceTableIndex);
			colIsColumnConstraint.AddAttribute (isColumnConstraintRenderer, "active", colIsColumnConstraintIndex);
			colDeleteAction.AddAttribute (deleteActionRenderer, "text", colDeleteActionIndex);			
			colUpdateAction.AddAttribute (updateActionRenderer, "text", colUpdateActionIndex);
			
			listFK.AppendColumn (colName);
			listFK.AppendColumn (colRefTable);
			listFK.AppendColumn (colIsColumnConstraint);
			listFK.AppendColumn (colDeleteAction);
			listFK.AppendColumn (colUpdateAction);
			
			columnSelecter.ColumnToggled += new EventHandler (ColumnToggled);
			referenceColumnSelecter.ColumnToggled += new EventHandler (ReferenceColumnToggled);
			listFK.Selection.Changed += new EventHandler (SelectionChanged);
			
			ShowAll ();
		}
Пример #37
0
 public CSLAEntityProvider(List<IEntity> entities, TableSchemaCollection tables, string extendedPropertyName)
 {
     _entities = entities;
     _tablesToKeep.AddRange(tables);
     _extendedPropertyName = extendedPropertyName;
 }
		public virtual TableSchemaCollection GetTables ()
		{
			TableSchemaCollection collection = new TableSchemaCollection ();
			
			IPooledDbConnection conn = connectionPool.Request ();
			try {
				//restrictions: database, schema, table, table type
				DataTable dt = conn.GetSchema (tablesCollectionString, null, connectionPool.ConnectionContext.ConnectionSettings.Database);
				for (int r = 0; r < dt.Rows.Count; r++) {
					DataRow row = dt.Rows[r];
					collection.Add (GetTable (row));
				}
			} catch (Exception e) {
				QueryService.RaiseException (e);
			}
			conn.Release ();
			
			return collection;
		}
		// see: http://dev.mysql.com/doc/refman/5.1/en/tables-table.html
		// // see: http://dev.mysql.com/doc/refman/5.1/en/show-create-table.html
		public override TableSchemaCollection GetTables ()
		{
			TableSchemaCollection tables = new TableSchemaCollection ();
			
			using (IPooledDbConnection conn = connectionPool.Request ()) {
				// Second Connection - MySql Connector doesn't allow more than 1 datareader by connection.
				IPooledDbConnection conn2 = connectionPool.Request ();
				using (IDbCommand command = conn.CreateCommand ("SHOW TABLES;")) {
					try {
						if (GetMainVersion (command) >= 5) {
							//in mysql 5.x we can use an sql query to provide the comment
							command.CommandText = string.Format(
													@"SELECT 
														TABLE_NAME, 
														TABLE_SCHEMA, 
														TABLE_TYPE, 
														TABLE_COMMENT 
													FROM `information_schema`.`TABLES`
													WHERE 
														TABLE_TYPE='BASE TABLE' 
														AND TABLE_SCHEMA='{0}' 
													ORDER BY TABLE_NAME;", command.Connection.Database);
							using (IDataReader r = command.ExecuteReader()) {
								while (r.Read ()) {
									TableSchema table = new TableSchema (this);
									table.Name = r.GetString (0);
									table.SchemaName = r.GetString (1);
									table.Comment = r.IsDBNull (3) ? null : r.GetString (3);
									
									using (IDbCommand command2 = conn2.CreateCommand (
																			string.Concat("SHOW CREATE TABLE `", 
																						table.Name, "`;"))) {
										using (IDataReader r2 = command2.ExecuteReader()) {
											r2.Read ();
											table.Definition = r2.GetString (1);
										}
									}
									tables.Add (table);
								}
								r.Close ();
							}
						} else {
							//use the default command for mysql 4.x and 3.23
							using (IDataReader r = command.ExecuteReader()) {
								while (r.Read ()) {
									TableSchema table = new TableSchema (this);
				
									table.Name = r.GetString (0);
									table.SchemaName = command.Connection.Database;
									
									using (IDbCommand command2 = conn2.CreateCommand (string.Concat(
									                                                    "SHOW CREATE TABLE `", 
																						table.Name,"`;"))) {
										using (IDataReader r2 = command2.ExecuteReader()) {
											r2.Read ();
											table.Definition = r2.GetString (1);
										}
									}
									tables.Add (table);
								}
								r.Close ();
							}
						}
					} catch (Exception e) {
						QueryService.RaiseException (e);
					} finally {
						conn.Release ();
						conn2.Release ();
					}
				}
			}
			return tables;
		}
        private void EnsureEntitiesExists(TableSchemaCollection value)
        {
            // If entities exist then return.
            if (_entities != null && _entities.Count > 0)
                return;

            // The entities haven't been set yet, so lets set them if there is atleast one table passed in.
            if (value == null || value.Count <= 0)
                return;

            bool previousValue = _canPopulateEntities;
            _canPopulateEntities = true;
            SourceDatabase = value[0].Database;
            _canPopulateEntities = previousValue;
        }
Пример #41
0
 public static TableSchemaCollection FilterTables(TableSchemaCollection tables)
 {
     TableSchemaCollection filtered = new TableSchemaCollection();
     foreach(TableSchema table in tables)
     {
         if(!SkipTable(table)) filtered.Add(table);
     }
     return filtered;
 }
Пример #42
0
		public override TableSchemaCollection GetTables ()
		{
			TableSchemaCollection tables = new TableSchemaCollection ();
			
			using (IPooledDbConnection conn = connectionPool.Request ()) {
				using (IDbCommand command = conn.CreateCommand (@"SELECT 
															su.name AS owner, 
															so.name as table_name, 
															so.id as table_id,										
															so.crdate as created_date, 
															so.xtype as table_type
														FROM dbo.sysobjects so, 
															dbo.sysusers su 
														WHERE
															xtype IN ('S','U')
															AND su.uid = so.uid
														ORDER BY 1, 2")) {
					try {
						using (command) {
							using (IDataReader r = command.ExecuteReader()) {
								while (r.Read()) {
									TableSchema table = new TableSchema (this);
									table.Name = r.GetString(1);
									if (r.GetString(4) == "S")
										table.IsSystemTable = true;
									else 
										if (Array.Exists (system_tables, delegate (string s) {return s == table.Name; }))
											table.IsSystemTable = true;
										else 
											table.IsSystemTable = false;
									table.OwnerName = r.GetString(0);
									tables.Add (table);
								}
								r.Close ();
							}
						}
					} catch (Exception e) {
						QueryService.RaiseException (e);
					} finally {
						conn.Release ();
					}
				}
			
			}
			return tables;
Пример #43
0
		public void Initialize (TableSchemaCollection tables)
		{
			this.tables = tables;
			
			store = new SortedTableListStore (tables);
			store.TableToggled += delegate (object sender, EventArgs args) {
				if (TableToggled != null)
					TableToggled (this, args);
			};
			list.Model = store.Store;
		}
		public virtual TableSchemaCollection GetTables ()
		{
			TableSchemaCollection collection = new TableSchemaCollection ();
			
			IPooledDbConnection conn = connectionPool.Request ();
			try {
				//restrictions: database, schema, table, table type
				DataTable dt = conn.GetSchema (tablesCollectionString, null, connectionPool.ConnectionContext.ConnectionSettings.Database);
				for (int r = 0; r < dt.Rows.Count; r++) {
					DataRow row = dt.Rows[r];
					collection.Add (GetTable (row));
				}
			} catch (Exception e) {
				// Don't raise error, if the triggers doesn't exists return an empty collection
			}
			conn.Release ();
			
			return collection;
		}
Пример #45
0
 public CSLAEntityProvider(List <IEntity> entities, TableSchemaCollection tables)
 {
     _entities = entities;
     _tablesToKeep.AddRange(tables);
 }
Пример #46
0
		private void InitializeThreaded (object state)
		{
			tables = schemaProvider.GetTables ();
			dataTypes = schemaProvider.GetDataTypes ();
			columns = originalTable.Columns;
			constraints = originalTable.Constraints;
			triggers = originalTable.Triggers;
			//TODO: indices
			indexes = new IndexSchemaCollection ();
			
			System.Text.StringBuilder builder = new System.Text.StringBuilder ();
			builder.Append ("Loading editor for TABLE ");
			builder.Append (originalTable.Name);
			builder.AppendLine ();
			builder.Append ("    columns = ");
			builder.Append (columns.Count);
			builder.AppendLine ();
			builder.Append ("constraints = ");
			builder.Append (constraints.Count);
			builder.AppendLine ();

			try {
				foreach (ColumnSchema col in columns) {				
					int dummy = col.Constraints.Count; //get column constraints
					builder.Append ("CONSTRAINTS ");
					builder.Append (col.Name);
					builder.Append (" ");
					builder.Append (dummy);
					builder.AppendLine ();
				}
				LoggingService.LogDebug (builder.ToString ());
			} catch (Exception ee) {
				LoggingService.LogDebug (builder.ToString ());
				LoggingService.LogError (ee.ToString ());
			}

			if (action == SchemaActions.Alter) //make a duplicate if we are going to alter the table
				this.table = originalTable.Clone () as TableSchema;

			DispatchService.GuiDispatch (delegate () {
				InitializeGui ();
			});
		}
Пример #47
0
 public CSLAEntityProvider(List <IEntity> entities, TableSchemaCollection tables, string extendedPropertyName)
 {
     _entities = entities;
     _tablesToKeep.AddRange(tables);
     _extendedPropertyName = extendedPropertyName;
 }
Пример #48
0
 public CSLAEntityProvider(List<IEntity> entities, TableSchemaCollection tables)
 {
     _entities = entities;
     _tablesToKeep.AddRange(tables);
 }
		private void ExecuteQueryCallback (DatabaseConnectionContext context, bool connected, object state)
		{
			if (!connected) {
				MessageService.ShowError (
					AddinCatalog.GetString ("Unable to connect to database '{0}'"), context.ConnectionSettings.Name);
				return;
			}
			
			ISchemaProvider provider = context.SchemaProvider;
			tables = provider.GetTables ();

			DispatchService.GuiDispatch (delegate () {
				//TODO: initialize the table mapper
			});
		}
Пример #50
0
		public void Initialize (TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints, DataTypeSchemaCollection dataTypes)
		{
			if (columns == null)
				throw new ArgumentNullException ("columns");
			if (constraints == null)
				throw new ArgumentNullException ("constraints");
			if (table == null)
				throw new ArgumentNullException ("table");
			if (tables == null)
				throw new ArgumentNullException ("tables");

			if (pkEditor != null)
				pkEditor.Initialize (table, columns, constraints);
			if (fkEditor != null)
				fkEditor.Initialize (tables, table, columns, constraints);
			if (checkEditor != null)
				checkEditor.Initialize (table, columns, constraints);
			if (uniqueEditor != null)
				uniqueEditor.Initialize (table, columns, constraints);
		}
		public override TableSchemaCollection GetTables ()
		{
			TableSchemaCollection tables = new TableSchemaCollection ();
			
			IPooledDbConnection conn = connectionPool.Request ();
			IDbCommand command = conn.CreateCommand (
				"SELECT DISTINCT c.relname, n.nspname, u.usename "
				+ "FROM pg_class c, pg_namespace n, pg_user u "
				+ "WHERE c.relnamespace = n.oid "
				+ "AND c.relowner = u.usesysid "
				+ "AND c.relkind='r' AND NOT EXISTS "
				+ "   (SELECT 1 FROM pg_rewrite r "
				+ "      WHERE r.ev_class = c.oid AND r.ev_type = '1') "
				+ "ORDER BY relname;"
			);		
			
			try {
				using (command) {
					using (IDataReader r = command.ExecuteReader()) {
						while (r.Read ()) {
							TableSchema table = new TableSchema (this);
		
							table.Name = r.GetString (0);
							table.IsSystemTable = table.Name.StartsWith ("pg_") || table.Name.StartsWith ("sql_");
							table.SchemaName = r.GetString (1);
							table.OwnerName = r.GetString (2);
							
//							StringBuilder sb = new StringBuilder();
//							sb.AppendFormat ("-- Table: {0}\n", table.Name);
//							sb.AppendFormat ("-- DROP TABLE {0};\n\n", table.Name);
//							sb.AppendFormat ("CREATE TABLE {0} (\n", table.Name);
//							
//							ColumnSchema[] columns = table.Columns;
//							string[] parts = new string[columns.Length];
//							for (int i = 0; i < parts.Length; i++) {
//								parts[i] = "\t" + columns[i].Definition;
//							}
//							sb.Append (String.Join (",\n", parts));
//							
//							ConstraintSchema[] cons = table.Constraints;
//							parts = new string[cons.Length];
//							if (cons.Length > 0)
//								sb.Append (",\n");
//							for (int i = 0; i < parts.Length; i++) {
//								parts[i] = "\t" + cons[i].Definition;
//							}
//							sb.Append (String.Join (",\n", parts));
//							
//							sb.Append ("\n);\n");
//							sb.AppendFormat ("COMMENT ON TABLE {0} IS '{1}';", table.Name, table.Comment);
//							table.Definition = sb.ToString();
							
							tables.Add (table);
						}
						r.Close ();
					}
				}
			} catch (Exception e) {
				QueryService.RaiseException (e);
			}
			conn.Release ();

			return tables;
Пример #52
0
		private void InitializeThreaded (object state)
		{
			tables = schemaProvider.GetTables ();
			dataTypes = schemaProvider.GetDataTypes ();
			columns = originalTable.Columns;
			constraints = originalTable.Constraints;
			triggers = originalTable.Triggers;
			//TODO: indices
			indexes = new IndexSchemaCollection ();
			
			Runtime.LoggingService.Error ("TABLE " + originalTable.Name);
			Runtime.LoggingService.Error ("   columns = " + columns.Count);
			Runtime.LoggingService.Error ("   constraints = " + constraints.Count);

			try {
			foreach (ColumnSchema col in columns) {				
				int dummy = col.Constraints.Count; //get column constraints
				Runtime.LoggingService.Error ("CONSTRAINTS " + col.Name + " " + dummy);
			}
			} catch (Exception ee) {
				Runtime.LoggingService.Error (ee);
				Runtime.LoggingService.Error (ee.StackTrace);
			}

			if (action == SchemaActions.Alter) //make a duplicate if we are going to alter the table
				this.table = originalTable.Clone () as TableSchema;

			DispatchService.GuiDispatch (delegate () {
				InitializeGui ();
			});
		}