Beispiel #1
0
        public static TableName[] GetTableNames(ApplicationCommand cmd, PathManager mgr)
        {
            var pt = mgr.current;

            if (!(pt.Item is Locator) && !(pt.Item is TableName))
            {
                if (cmd.arg1 != null)
                {
                    PathName path = new PathName(cmd.arg1);
                    var      node = mgr.Navigate(path);
                    if (node != null)
                    {
                        var dname = mgr.GetPathFrom <DatabaseName>(node);
                        if (dname != null)
                        {
                            if (cmd.wildcard != null)
                            {
                                var m = new MatchedDatabase(dname, cmd);
                                return(m.TableNames());
                            }
                            else
                            {
                                var _tname = mgr.GetPathFrom <TableName>(node);
                                if (_tname != null)
                                {
                                    return new TableName[] { _tname }
                                }
                                ;
                                else
                                {
                                    cerr.WriteLine("invalid path");

                                    return(null);
                                }
                            }
                        }
                        else
                        {
                            cerr.WriteLine("database is unavailable");
                            return(null);
                        }
                    }
                    else
                    {
                        cerr.WriteLine("invalid path");
                        return(null);
                    }
                }
            }


            if (pt.Item is TableName)
            {
                var tname = (TableName)pt.Item;
                return(new TableName[] { tname });
            }

            return(null);
        }
Beispiel #2
0
        private bool SetSource(string source, string sourceText)
        {
            if (source == null)
            {
                cerr.WriteLine("invalid argument");
                return(false);
            }

            var path = new PathName(source);

            node = mgr.Navigate(path);
            if (node == null)
            {
                cerr.WriteLine("invalid path:" + path);
                return(false);
            }

            dname = mgr.GetPathFrom <DatabaseName>(node);
            if (dname == null)
            {
                cerr.WriteLine($"warning: {sourceText} database is unavailable");
                return(false);
            }

            var server = mgr.GetPathFrom <ServerName>(node);

            side = new Side(dname);

            T = new TableName[] { };

            if (path.wildcard != null)
            {
                var m1 = new MatchedDatabase(dname, path.wildcard)
                {
                    Includedtables = cmd.Includes,
                    Excludedtables = cmd.Excludes
                };

                T = m1.TableNames();
            }
            else
            {
                TableName tname = mgr.GetPathFrom <TableName>(node);
                if (tname == null)
                {
                    T = dname.GetTableNames();
                }
                else
                {
                    T = new TableName[] { tname };
                }
            }

            return(true);
        }
Beispiel #3
0
        public void ExportData()
        {
            string directory = cmd.OutputDirectory();

            if (directory != null)
            {
                xmlDbFile.XmlDbFolder = directory;
            }

            if (tname != null)
            {
                cout.WriteLine("start to generate {0} data file", tname);
                var dt   = new TableReader(tname).Table;
                var file = xmlDbFile.WriteData(tname, dt);
                cout.WriteLine("completed {0} =>{1}", tname.ShortName, file);
            }

            else if (dname != null)
            {
                cout.WriteLine("start to generate {0}", dname);
                var mt = new MatchedDatabase(dname, cmd);
                CancelableWork.CanCancel(cts =>
                {
                    foreach (var tname in mt.TableNames())
                    {
                        if (cts.IsCancellationRequested)
                        {
                            return;
                        }


                        cout.WriteLine("start to generate {0}", tname);
                        var dt   = new SqlBuilder().SELECT().TOP(cmd.Top).COLUMNS().FROM(tname).SqlCmd.FillDataTable();
                        var file = xmlDbFile.WriteData(tname, dt);
                        cout.WriteLine("completed {0} => {1}", tname.ShortName, file);
                    }
                    return;
                }
                                         );

                if (cmd.Top == 0)
                {
                    cout.WriteLine("completed");
                }
                else
                {
                    cout.WriteLine("completed to export TOP {0} row(s) for each table", cmd.Top);
                }
            }
            else
            {
                cerr.WriteLine("warning: table or database is not seleted");
            }
        }
Beispiel #4
0
        private TableName[] getTableNames(ApplicationCommand cmd)
        {
            TableName[] tnames;
            if (cmd.wildcard != null)
            {
                var md = new MatchedDatabase(dname, cmd);
                tnames = md.TableNames();
                if (tnames.Length == 0)
                {
                    cerr.WriteLine("warning: no table is matched");
                    return(new TableName[] { });
                }
            }
            else
            {
                tnames = dname.GetTableNames();
            }

            return(tnames);
        }
Beispiel #5
0
        public void ExportClass()
        {
            DpoOption option = new DpoOption
            {
                NameSpace          = cfg.GetValue <string>(ConfigKey._GENERATOR_DPO_NS, "Sys.DataModel.Dpo"),
                OutputPath         = cmd.OutputPath(ConfigKey._GENERATOR_DPO_PATH, $"{ConfigurationEnvironment.MyDocuments}\\DataModel\\Dpo"),
                Level              = cfg.GetValue <Level>(ConfigKey._GENERATOR_DPO_LEVEL, Level.Application),
                HasProvider        = cfg.GetValue <bool>(ConfigKey._GENERATOR_DPO_HASPROVIDER, false),
                HasTableAttribute  = cfg.GetValue <bool>(ConfigKey._GENERATOR_DPO_HASTABLEATTR, true),
                HasColumnAttribute = cfg.GetValue <bool>(ConfigKey._GENERATOR_DPO_HASCOLUMNATTR, true),
                IsPack             = cfg.GetValue <bool>(ConfigKey._GENERATOR_DPO_ISPACK, true),
                CodeSorted         = cmd.Has("sort"),

                ClassNameSuffix = cfg.GetValue <string>(ConfigKey._GENERATOR_DPO_SUFFIX, Setting.DPO_CLASS_SUFFIX_CLASS_NAME)
            };

            option.ClassNameRule =
                name => name.Substring(0, 1).ToUpper() + name.Substring(1).ToLower() + option.ClassNameSuffix;

            if (tname != null)
            {
                var clss = new DpoGenerator(tname)
                {
                    Option = option
                };
                clss.CreateClass();
                cout.WriteLine("generated class {0} at {1}", tname.ShortName, option.OutputPath);
            }
            else if (dname != null)
            {
                cout.WriteLine("start to generate database {0} class to directory: {1}", dname, option.OutputPath);
                CancelableWork.CanCancel(cts =>
                {
                    var md             = new MatchedDatabase(dname, cmd);
                    TableName[] tnames = md.TableNames();
                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                        {
                            return;
                        }


                        try
                        {
                            var clss = new DpoGenerator(tn)
                            {
                                Option = option
                            };
                            clss.CreateClass();
                            cout.WriteLine("generated class for {0} at {1}", tn.ShortName, option.OutputPath);
                        }
                        catch (Exception ex)
                        {
                            cerr.WriteLine($"failed to generate class {tn.ShortName}, {ex.Message}");
                        }
                    }

                    cout.WriteLine("completed");
                    return;
                });
            }
            else
            {
                cerr.WriteLine("warning: database is not selected");
            }
        }
Beispiel #6
0
        public void ExportCsvFile()
        {
            string path = this.cmd.OutputPath(ConfigKey._GENERATOR_CSV_PATH, $"{ConfigurationEnvironment.MyDocuments}\\csv");

            string file;

            string fullName(TableName tname) => $"{path}\\{sname.Path}\\{dname.Name}\\{tname.ShortName}.csv";

            if (tname != null)
            {
                cout.WriteLine("start to generate {0} csv file", tname);
                file = this.cmd.OutputFileName();
                if (file == null)
                {
                    file = fullName(tname);
                }

                var dt = new SqlBuilder().SELECT().COLUMNS(cmd.Columns).FROM(tname).SqlCmd.FillDataTable();
                using (var writer = file.CreateStreamWriter(cmd.Append))
                {
                    CsvFile.Write(dt, writer, true);
                }
                cout.WriteLine("completed {0} => {1}", tname.ShortName, file);
            }
            else if (dname != null)
            {
                cout.WriteLine("start to generate {0} csv to directory: {1}", dname, path);
                CancelableWork.CanCancel(cts =>
                {
                    var md             = new MatchedDatabase(dname, cmd);
                    TableName[] tnames = md.TableNames();
                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                        {
                            return;
                        }

                        try
                        {
                            file   = fullName(tn);
                            var dt = new TableReader(tn).Table;
                            using (var writer = file.CreateStreamWriter(cmd.Append))
                            {
                                CsvFile.Write(dt, writer, true);
                            }
                            cout.WriteLine("generated for {0} at {1}", tn.ShortName, path);
                        }
                        catch (Exception ex)
                        {
                            cerr.WriteLine($"failed to generate {tn.ShortName}, {ex.Message}");
                        }
                    }

                    cout.WriteLine("completed");
                    return;
                });
            }
            else
            {
                cerr.WriteLine("warning: table or database is not seleted");
            }
        }
Beispiel #7
0
        public void ExportInsertOrUpdateData(SqlScriptType type)
        {
            var option = new SqlScriptGenerationOption
            {
                HasIfExists          = cmd.HasIfExists,
                InsertWithoutColumns = cmd.Has("no-columns"),
            };

            if (tname != null)
            {
                var node  = mgr.GetCurrentNode <Locator>();
                int count = 0;
                using (var writer = SqlFileName.CreateStreamWriter(cmd.Append))
                {
                    //cout.WriteLine($"start to generate {tname} script to file: \"{SqlFileName}\"");
                    Locator locator = null;
                    string  WHERE   = "";
                    if (node != null)
                    {
                        locator = mgr.GetCombinedLocator(node);
                        WHERE   = $" WHERE {locator}";
                    }

                    long cnt = tname.GetTableRowCount(locator);
                    count = Tools.ForceLongToInteger(cnt);
                    using (var progress = new ProgressBar {
                        Count = count
                    })
                    {
                        count = Compare.GenerateRows(type, writer, new TableSchema(tname), locator, option, progress);
                    }
                    cout.WriteLine($"{type} clauses (SELECT * FROM {tname}{WHERE}) generated to \"{SqlFileName}\", Done on rows({cnt})");
                }
            }
            else if (dname != null)
            {
                //cout.WriteLine($"start to generate {dname} script to file: \"{SqlFileName}\"");
                using (var writer = SqlFileName.CreateStreamWriter(cmd.Append))
                {
                    var         md     = new MatchedDatabase(dname, cmd);
                    TableName[] tnames = md.TableNames();

                    if (tnames.Length > 5 && !cin.YesOrNo($"Are you sure to export {tnames.Length} tables on {dname} (y/n)?"))
                    {
                        return;
                    }

                    CancelableWork.CanCancel(cts =>
                    {
                        foreach (var tn in tnames)
                        {
                            if (cts.IsCancellationRequested)
                            {
                                return;
                            }

                            long cnt = tn.GetTableRowCount();
                            if (cnt > cfg.MaxRows)
                            {
                                if (!cin.YesOrNo($"Are you sure to export {cnt} rows on {tn.ShortName} (y/n)?"))
                                {
                                    cout.WriteLine("\n{0,10} skipped", tn.ShortName);
                                    continue;
                                }
                            }

                            int count = Tools.ForceLongToInteger(cnt);
                            using (var progress = new ProgressBar {
                                Count = count
                            })
                            {
                                count = Compare.GenerateRows(type, writer, new TableSchema(tn), null, option, progress);
                            }

                            cout.WriteLine($"{count,10} row(s) generated on {tn.ShortName}");
                        }

                        cout.WriteLine($"completed to generate {type} clauses to \"{SqlFileName}\"");
                    });
                }
            }
            else
            {
                cerr.WriteLine("warning: table or database is not selected");
            }
        }
Beispiel #8
0
        public void del(Command cmd)
        {
            if (cmd.HasHelp)
            {
                stdio.WriteLine("command del or erase: drop tables or delete data rows");
                stdio.WriteLine("del tablename               : drop table");
                stdio.WriteLine("del [sql where clause]      : delete current table filtered rows");
                stdio.WriteLine("example:");
                stdio.WriteLine(@"local> del Northwind\Products       : drop table [Products]");
                stdio.WriteLine(@"local\Northwind\Products> del       : delete all rows of table [Products]");
                stdio.WriteLine(@"local\Northwind\Products> del col1=1 and col2='match' : del rows matched on columns:c1 or c2");
                return;
            }

            var pt = mgr.current;
            if (!(pt.Item is Locator) && !(pt.Item is TableName))
            {
                TableName[] T = null;
                if (cmd.arg1 != null)
                {
                    PathName path = new PathName(cmd.arg1);
                    var node = mgr.Navigate(path);
                    if (node != null)
                    {
                        var dname = mgr.GetPathFrom<DatabaseName>(node);
                        if (dname != null)
                        {
                            if (cmd.wildcard != null)
                            {
                                var m = new MatchedDatabase(dname, cmd.wildcard, new string[] { });
                                T = m.MatchedTableNames;
                            }
                            else
                            {
                                var _tname = mgr.GetPathFrom<TableName>(node);
                                if (_tname != null)
                                    T = new TableName[] { _tname };
                                else
                                {
                                    stdio.ErrorFormat("invalid path");
                                    return;
                                }
                            }
                        }
                        else
                        {
                            stdio.ErrorFormat("database is unavailable");
                            return;
                        }
                    }
                    else
                    {
                        stdio.ErrorFormat("invalid path");
                        return;
                    }
                }

                if (T != null && T.Length > 0)
                {
                    if (!stdio.YesOrNo("are you sure to drop {0} tables (y/n)?", T.Length))
                        return;

                    try
                    {
                        var sqlcmd = new SqlCmd(T[0].Provider, string.Empty);
                        sqlcmd.ExecuteNonQueryTransaction(T.Select(row => string.Format("DROP TABLE {0}", row)));
                        stdio.ErrorFormat("completed to drop table(s):\n{0}", string.Join<TableName>("\n", T));
                    }
                    catch (Exception ex)
                    {
                        stdio.ErrorFormat(ex.Message);
                    }
                }
                else
                    stdio.ErrorFormat("table is not selected");

                return;
            }

            TableName tname = null;
            Locator locator = null;
            if (pt.Item is Locator)
            {
                locator = mgr.GetCombinedLocator(pt);
                tname = mgr.GetCurrentPath<TableName>();
                if (!string.IsNullOrEmpty(cmd.args))
                    locator.And(new Locator(cmd.args));
            }

            if (pt.Item is TableName)
            {
                tname = (TableName)pt.Item;
                if (!string.IsNullOrEmpty(cmd.args))
                    locator = new Locator(cmd.args);
            }

            if (locator == null)
                stdio.Write("are you sure to delete all rows (y/n)?");
            else
                stdio.Write("are you sure to delete (y/n)?");

            if (stdio.ReadKey() != ConsoleKey.Y)
                return;

            stdio.WriteLine();

            try
            {
                int count;
                if (locator == null)
                    count = new SqlBuilder().DELETE(tname).SqlCmd.ExecuteNonQuery();
                else
                    count = new SqlBuilder().DELETE(tname).WHERE(locator).SqlCmd.ExecuteNonQuery();

                stdio.WriteLine("{0} of row(s) affected", count);
            }
            catch (Exception ex)
            {
                stdio.ErrorFormat(ex.Message);
            }
        }
Beispiel #9
0
        public string Run(ActionType compareType, TableName[] N1, TableName[] N2, ApplicationCommand cmd)
        {
            string[] exceptColumns = cmd.Columns;

            DatabaseName dname1 = Side1.DatabaseName;
            DatabaseName dname2 = Side2.DatabaseName;

            cout.WriteLine("server1: {0} default database:{1}", Side1.Provider.DataSource, dname1.Name);
            cout.WriteLine("server2: {0} default database:{1}", Side2.Provider.DataSource, dname2.Name);

            if (!Exists(dname1) || !Exists(dname2))
            {
                return(string.Empty);
            }

            StringBuilder builder = new StringBuilder();

            builder.AppendFormat("-- sqlcon:", Side1.Provider.DataSource, dname1.Name).AppendLine();
            builder.AppendFormat("-- compare server={0} db={1}", Side1.Provider.DataSource, dname1.Name).AppendLine();
            builder.AppendFormat("--         server={0} db={1} @ {2}", Side2.Provider.DataSource, dname2.Name, DateTime.Now).AppendLine();

            Wildcard <TableName> match = MatchedDatabase.CreateWildcard(cmd);

            CancelableWork.CanCancel(cts =>
            {
                int i = 0;
                foreach (var tname1 in N1)
                {
                    if (cts.IsCancellationRequested)
                    {
                        return;
                    }

                    TableName tname2 = N2.Where(t => t.Name == tname1.Name).FirstOrDefault();
                    if (tname2 == null)
                    {
                        //when compare tables in the same database, the table name could be different
                        if (i < N2.Length && N2[i].DatabaseName == tname1.DatabaseName)
                        {
                            tname2 = N2[i];
                        }
                        else
                        {
                            tname2 = new TableName(dname2, tname1.SchemaName, tname1.Name);
                        }
                    }

                    if (compareType == ActionType.CompareData && !match.Contains(tname1))
                    {
                        cout.WriteLine("{0} is excluded", tname1);
                        continue;
                    }

                    if (tname2.Exists())
                    {
                        try
                        {
                            builder.Append(CompareTable(compareType, CompareSideType.compare, tname1, tname2, cmd.PK, exceptColumns));
                        }
                        catch (Exception ex)
                        {
                            cerr.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        if (compareType == ActionType.CompareSchema)
                        {
                            string sql = tname1.GenerateCreateTableClause(appendGO: false);
                            cout.WriteLine(sql);
                            builder
                            .Append(sql)
                            .AppendLine(SqlScript.GO);
                        }
                        else
                        {
                            cout.WriteLine("{0} doesn't exist", tname2);
                        }
                    }

                    i++;
                }
            });

            return(builder.ToString());
        }
Beispiel #10
0
        public void ExportCreate()
        {
            if (tname != null)
            {
                cout.WriteLine("start to generate CREATE TABLE script: {0}", dname);
                using (var writer = SqlFileName.CreateStreamWriter(cmd.Append))
                {
                    writer.WriteLine(tname.GenerateIfDropClause());
                    writer.WriteLine(tname.GenerateCreateTableClause(appendGO: true));
                }
                cout.WriteLine("completed to generate script on file: {0}", SqlFileName);
                return;
            }


            if (dname != null)
            {
                if (cmd.wildcard != null)
                {
                    var         md     = new MatchedDatabase(dname, cmd);
                    TableName[] tnames = md.TableNames();
                    if (tnames.Length > 0)
                    {
                        Stack <string> stack = new Stack <string>();
                        Queue <string> queue = new Queue <string>();
                        foreach (var tname in tnames)
                        {
                            cout.WriteLine("start to generate CREATE TABLE script: {0} ", tname);
                            stack.Push(tname.GenerateIfDropClause());
                            queue.Enqueue(tname.GenerateCreateTableClause(appendGO: true));
                        }

                        using (var writer = SqlFileName.CreateStreamWriter(cmd.Append))
                        {
                            while (stack.Count > 0)
                            {
                                writer.WriteLine(stack.Pop());
                            }

                            while (queue.Count > 0)
                            {
                                writer.WriteLine(queue.Dequeue());
                            }
                        }
                    }
                    else
                    {
                        cerr.WriteLine("warning: no table is matched");
                        return;
                    }
                }
                else
                {
                    cout.WriteLine("start to generate CREATE TABLE script: {0}", dname);
                    using (var writer = SqlFileName.CreateStreamWriter(cmd.Append))
                    {
                        writer.WriteLine(dname.GenerateClause());
                    }
                }

                cout.WriteLine("completed to generate script on file: {0}", SqlFileName);
                return;
            }

            cerr.WriteLine("warning: table or database is not seleted");
        }
Beispiel #11
0
        public void clean(Command cmd, Configuration cfg)
        {
            if (cmd.HasHelp)
            {
                stdio.WriteLine("clean duplicated rows");
                stdio.WriteLine("clean [path]|[pattern]|  : clean current database or table, or search pattern");
                stdio.WriteLine("options:");
                stdio.WriteLine("   /col:c1,c2,..         : clean columns, compare column c1, c2, ...");
                stdio.WriteLine("   /d                    : commit cleaning duplicated rows on database server, otherwise display # of duplicated rows");
                stdio.WriteLine("example:");
                stdio.WriteLine("clean match*s /col:c1,c2 : clean duplicated rows by comparing columns:c1 and c2");
                stdio.WriteLine("clean                    : clean by comparing entire row");
                return;
            }

            if (!Navigate(cmd.Path1))
                return;

            if (pt.Item is TableName)
            {
                var tname = (TableName)pt.Item;
                var dup = new DuplicatedTable(tname, cmd.Columns);
                if (cmd.Has("d"))
                {
                    int count = dup.Clean();
                    stdio.WriteLine("completed to clean {0} #rows at {1}", count, tname);
                }
                else
                {
                    int count = dup.DuplicatedRowCount();
                    if (count == 0)
                        stdio.WriteLine("no duplicated rows at {0}", tname);
                    else
                        stdio.WriteLine("{0} duplicated row(s) at {1}", count, tname);
                }
                return;
            }

            if (pt.Item is DatabaseName)
            {
                var dname = (DatabaseName)pt.Item;
                var m = new MatchedDatabase(dname, cmd.wildcard, cfg.compareExcludedTables);
                var T = m.MatchedTableNames;

                CancelableWork.CanCancel(cts =>
                {
                    foreach (var tn in T)
                    {
                        if (cts.IsCancellationRequested)
                            return;

                        if (cmd.Has("d"))
                        {
                            stdio.WriteLine("start to clean {0}", tn);
                            var dup = new DuplicatedTable(tn, cmd.Columns);
                            int count = dup.Clean();
                            stdio.WriteLine("cleaned {0} #rows", count);
                        }
                        else
                        {
                            stdio.WriteLine("start to query {0}", tn);
                            var dup = new DuplicatedTable(tn, cmd.Columns);
                            int count = dup.DuplicatedRowCount();
                            if (count == 0)
                                stdio.WriteLine("distinct rows");
                            else
                                stdio.WriteLine("{0} duplicated row(s)", count, tn);
                        }

                    }

                });

                return;
            }

            stdio.ErrorFormat("select database or table first");
        }
Beispiel #12
0
        public void ExportData(Command cmd)
        {
            if (tname != null)
            {
                stdio.WriteLine("start to generate {0} data file", tname);
                var dt = new TableReader(tname).Table;
                var file = xml.Write(tname, dt);
                stdio.WriteLine("completed {0} =>{1}", tname.ShortName, file);
            }

            else if (dname != null)
            {
                stdio.WriteLine("start to generate {0}", dname);
                var mt = new MatchedDatabase(dname, cmd.wildcard, cfg.exportExcludedTables);
                CancelableWork.CanCancel(cts =>
                {
                    foreach (var tname in mt.MatchedTableNames)
                    {
                        if (cts.IsCancellationRequested)
                            return;

                        stdio.WriteLine("start to generate {0}", tname);
                        var dt = new SqlBuilder().SELECT.TOP(cmd.top).COLUMNS().FROM(tname).SqlCmd.FillDataTable();
                        var file = xml.Write(tname, dt);
                        stdio.WriteLine("completed {0} => {1}", tname.ShortName, file);
                    }
                    return;
                }
               );

                if (cmd.top == 0)
                    stdio.WriteLine("completed");
                else
                    stdio.WriteLine("completed to export TOP {0} row(s) for each table", cmd.top);
            }
            else
            {
                stdio.ErrorFormat("warning: table or database is not seleted");
            }
        }
Beispiel #13
0
        public void ExportClass(Command cmd)
        {
            DpoOption option = new DpoOption();

            option.NameSpace = cfg.GetValue<string>("dpo.ns", "Sys.DataModel.Dpo");
            option.OutputPath = cfg.GetValue<string>("dpo.path", $"{Configuration.MyDocuments}\\DataModel\\Dpo");
            option.Level = cfg.GetValue<Level>("dpo.level", Level.Application);
            option.HasProvider = cfg.GetValue<bool>("dpo.hasProvider", false);
            option.HasTableAttribute = cfg.GetValue<bool>("dpo.hasTableAttr", true);
            option.HasColumnAttribute = cfg.GetValue<bool>("dpo.hasColumnAttr", true);
            option.IsPack = cfg.GetValue<bool>("dpo.isPack", true);
            option.CodeSorted = cmd.Has("sort");

            option.ClassNameSuffix = cfg.GetValue<string>("dpo.suffix", Setting.DPO_CLASS_SUFFIX_CLASS_NAME);
            option.ClassNameRule =
                name => name.Substring(0, 1).ToUpper() + name.Substring(1).ToLower() + option.ClassNameSuffix;

            if (tname != null)
            {
                var clss = new DpoGenerator(tname) { Option = option };
                clss.CreateClass();
                stdio.WriteLine("generated class {0} at {1}", tname.ShortName, option.OutputPath);
            }
            else if (dname != null)
            {
                stdio.WriteLine("start to generate database {0} class to directory: {1}", dname, option.OutputPath);
                CancelableWork.CanCancel(cts =>
                {
                    var md = new MatchedDatabase(dname, cmd.wildcard, cfg.exportExcludedTables);
                    TableName[] tnames = md.MatchedTableNames;
                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                            return;

                        try
                        {
                            var clss = new DpoGenerator(tn) { Option = option };
                            clss.CreateClass();
                            stdio.WriteLine("generated class for {0} at {1}", tn.ShortName, option.OutputPath);
                        }
                        catch (Exception ex)
                        {
                            stdio.ErrorFormat("failed to generate class {0}, {1}", tn.ShortName, ex.Message);
                        }
                    }

                    stdio.WriteLine("completed");
                    return;
                });
            }
            else
            {
                stdio.ErrorFormat("warning: database is not selected");
            }
        }
Beispiel #14
0
        public void ExportDataSetXml()
        {
            if (dname == null)
            {
                cerr.WriteLine("select a database first");
                return;
            }

            string path = cmd.OutputPath(ConfigKey._GENERATOR_DS_PATH, $"{ConfigurationEnvironment.MyDocuments}\\ds");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (tname != null)
            {
                cout.WriteLine($"start to generate data file: {tname}");
                var dt = new TableReader(tname).Table;
                dt.TableName = tname.ShortName;

                string  file = Path.Combine(path, $"{tname.ShortName}.xml");
                DataSet ds   = dt.DataSet;
                ds.DataSetName = dname.Name;

                ds.WriteXml(file, XmlWriteMode.WriteSchema);
                cout.WriteLine($"completed {tname} => {file}");
            }
            else if (dname != null)
            {
                cout.WriteLine($"start to generate data file to directory: {dname}");
                CancelableWork.CanCancel(cts =>
                {
                    var md             = new MatchedDatabase(dname, cmd); //cfg.exportExcludedTables);
                    TableName[] tnames = md.TableNames();
                    DataSet ds         = new DataSet
                    {
                        DataSetName = dname.Name,
                    };

                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                        {
                            return;
                        }

                        try
                        {
                            var dt       = new TableReader(tn).Table.Copy();
                            dt.TableName = tn.ShortName;
                            ds.Tables.Add(dt);
                            cout.WriteLine($"generated for {tn.ShortName}");
                        }
                        catch (Exception ex)
                        {
                            cerr.WriteLine($"failed to generate {tn.ShortName}, {ex.Message}");
                        }
                    }

                    string file = Path.Combine(path, $"{dname.Name}.xml");
                    ds.WriteXml(file, XmlWriteMode.WriteSchema);
                    cout.WriteLine($"completed generated: {file}");
                    return;
                });
            }
            else
            {
                cerr.WriteLine("warning: table or database is not seleted");
            }
        }
Beispiel #15
0
        public void ExportLinq2SQLClass(Command cmd)
        {
            string path = cfg.GetValue<string>("l2s.path", $"{Configuration.MyDocuments}\\dc");
            string ns = cmd.GetValue("ns") ?? cfg.GetValue<string>("l2s.ns", "Sys.DataModel.L2s");
            Dictionary<TableName, TableSchema> schemas = new Dictionary<TableName, TableSchema>();

            if (tname != null)
            {
                var builder = new Linq2SQLClassBuilder(ns, cmd, tname, schemas);
                string file = builder.WriteFile(path);
                stdio.WriteLine("code generated on {0}", file);
            }
            else if (dname != null)
            {
                TableName[] tnames;
                if (cmd.wildcard != null)
                {
                    var md = new MatchedDatabase(dname, cmd.wildcard, new string[] { });
                    tnames = md.MatchedTableNames;
                    if (tnames.Length == 0)
                    {
                        stdio.ErrorFormat("warning: no table is matched");
                        return;
                    }
                }
                else
                {
                    tnames = dname.GetTableNames();
                }

                foreach (var tname in tnames)
                {
                    var builder = new Linq2SQLClassBuilder(ns, cmd, tname, schemas);
                    string file = builder.WriteFile(path);
                    stdio.WriteLine("code generated on {0}", file);
                }

                return;
            }
            else
            {
                stdio.ErrorFormat("warning: table or database is not seleted");
            }
        }
Beispiel #16
0
        public void ExportInsert(Command cmd)
        {
            if (tname != null)
            {
                if (cmd.IsSchema)
                {
                    using (var writer = fileName.NewStreamWriter())
                    {
                        string sql = Compare.GenerateTemplate(new TableSchema(tname), SqlScriptType.INSERT);
                        stdio.WriteLine(sql);
                        writer.WriteLine(sql);
                    }
                }
                else
                {
                    var node = mgr.GetCurrentNode<Locator>();
                    int count;

                    using (var writer = fileName.NewStreamWriter())
                    {
                        if (node != null)
                        {
                            stdio.WriteLine("start to generate {0} INSERT script to file: {1}", tname, fileName);
                            Locator locator = mgr.GetCombinedLocator(node);
                            count = Compare.GenerateRows(writer, new TableSchema(tname), locator, cmd.HasIfExists);
                            stdio.WriteLine("insert clauses (SELECT * FROM {0} WHERE {1}) generated to {2}", tname, locator, fileName);
                        }
                        else
                        {
                            count = Compare.GenerateRows(writer, new TableSchema(tname), null, cmd.HasIfExists);
                            stdio.WriteLine("insert clauses (SELECT * FROM {0}) generated to {1}", tname, fileName);
                        }
                    }
                }
            }
            else if (dname != null)
            {
                stdio.WriteLine("start to generate {0} script to file: {1}", dname, fileName);
                using (var writer = fileName.NewStreamWriter())
                {
                    var md = new MatchedDatabase(dname, cmd.wildcard, cfg.exportExcludedTables);
                    TableName[] tnames = md.MatchedTableNames;
                    CancelableWork.CanCancel(cts =>
                    {
                        foreach (var tn in tnames)
                        {
                            if (cts.IsCancellationRequested)
                                return;

                            if (!cfg.exportExcludedTables.IsMatch(tn.ShortName))
                            {
                                int count = new SqlCmd(tn.Provider, string.Format("SELECT COUNT(*) FROM {0}", tn)).FillObject<int>();
                                if (count > cfg.Export_Max_Count)
                                {
                                    if (!stdio.YesOrNo("are you sure to export {0} rows on {1} (y/n)?", count, tn.ShortName))
                                    {
                                        stdio.WriteLine("\n{0,10} skipped", tn.ShortName);
                                        continue;
                                    }
                                }

                                count = Compare.GenerateRows(writer, new TableSchema(tn), null, cmd.HasIfExists);
                                stdio.WriteLine("{0,10} row(s) generated on {1}", count, tn.ShortName);
                            }
                            else
                                stdio.WriteLine("{0,10} skipped", tn.ShortName);
                        }
                        stdio.WriteLine("completed");

                    });
                }
            }
            else
                stdio.ErrorFormat("warning: table or database is not selected");
        }
Beispiel #17
0
        public void ExportEntityClass(Command cmd)
        {
            if (dname == null)
            {
                stdio.ErrorFormat("select a database first");
                return;
            }

            string path = cmd.GetValue("out") ?? cfg.GetValue<string>("dc.path", $"{Configuration.MyDocuments}\\dc");
            string ns = cmd.GetValue("ns") ?? cfg.GetValue<string>("dc.ns", "Sys.DataModel.DataContracts");

            if (tname != null)
            {
                stdio.WriteLine("start to generate {0} entity framework class file", tname);
                var builder = new EntityClassBuilder(ns, cmd, tname);

                string file = builder.WriteFile(path);
                stdio.WriteLine("completed {0} => {1}", tname.ShortName, file);
            }
            else if (dname != null)
            {
                stdio.WriteLine("start to generate {0} entity framework class to directory: {1}", dname, path);
                CancelableWork.CanCancel(cts =>
                {
                    var md = new MatchedDatabase(dname, cmd.wildcard, null); //cfg.exportExcludedTables);
                    TableName[] tnames = md.MatchedTableNames;
                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                            return;

                        try
                        {
                            var builder = new EntityClassBuilder(ns, cmd, tn);

                            string file = builder.WriteFile(path);
                            stdio.WriteLine("generated for {0} at {1}", tn.ShortName, path);
                        }
                        catch (Exception ex)
                        {
                            stdio.ErrorFormat("failed to generate {0}, {1}", tn.ShortName, ex.Message);
                        }
                    }

                    stdio.WriteLine("completed");
                    return;
                });
            }
            else
            {
                stdio.ErrorFormat("warning: table or database is not seleted");
            }
        }
Beispiel #18
0
        public void ExportEntityClass()
        {
            if (dname == null)
            {
                cerr.WriteLine("select a database first");
                return;
            }

            string path = cmd.OutputPath(ConfigKey._GENERATOR_DC_PATH, $"{ConfigurationEnvironment.MyDocuments}\\dc");
            string ns   = cmd.GetValue("ns", ConfigKey._GENERATOR_DC_NS, "Sys.DataModel.DataContracts");

            if (tname != null)
            {
                cout.WriteLine("start to generate {0} entity framework class file", tname);
                var builder = new EntityClassBuilder(cmd, tname)
                {
                };
                builder.SetNamespace(ns);
                if (!builder.IsAssocication)
                {
                    string file = builder.WriteFile(path);
                    cout.WriteLine("completed {0} => {1}", tname.ShortName, file);
                }
            }
            else if (dname != null)
            {
                cout.WriteLine("start to generate {0} entity framework class to directory: {1}", dname, path);
                CancelableWork.CanCancel(cts =>
                {
                    var md             = new MatchedDatabase(dname, cmd); //cfg.exportExcludedTables);
                    TableName[] tnames = md.TableNames();
                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                        {
                            return;
                        }

                        try
                        {
                            var builder = new EntityClassBuilder(cmd, tn);
                            builder.SetNamespace(ns);
                            if (!builder.IsAssocication)
                            {
                                string file = builder.WriteFile(path);
                                cout.WriteLine("generated for {0} at {1}", tn.ShortName, path);
                            }
                        }
                        catch (Exception ex)
                        {
                            cerr.WriteLine($"failed to generate {tn.ShortName}, {ex.Message}");
                        }
                    }

                    cout.WriteLine("completed");
                    return;
                });
            }
            else
            {
                cerr.WriteLine("warning: table or database is not seleted");
            }
        }
Beispiel #19
0
        public void ExportCreate(Command cmd)
        {
            if (tname != null)
            {
                stdio.WriteLine("start to generate CREATE TABLE script: {0}", dname);
                using (var writer = fileName.NewStreamWriter())
                {
                    writer.WriteLine(tname.GenerateCluase(true));
                }
                stdio.WriteLine("completed to generate script on file: {0}", fileName);
                return;
            }

            if (dname != null)
            {
                if (cmd.wildcard != null)
                {
                    var md = new MatchedDatabase(dname, cmd.wildcard, cfg.exportExcludedTables);
                    TableName[] tnames = md.MatchedTableNames;
                    if (tnames.Length > 0)
                    {
                        using (var writer = fileName.NewStreamWriter())
                        {
                            foreach (var tname in tnames)
                            {
                                stdio.WriteLine("start to generate CREATE TABLE script: {0} ", tname);
                                writer.WriteLine(tname.GenerateCluase(true));
                            }
                        }
                    }
                    else
                    {
                        stdio.ErrorFormat("warning: no table is matched");
                        return;
                    }
                }
                else
                {
                    stdio.WriteLine("start to generate CREATE TABLE script: {0}", dname);
                    using (var writer = fileName.NewStreamWriter())
                    {
                        writer.WriteLine(dname.GenerateClause());
                    }
                }

                stdio.WriteLine("completed to generate script on file: {0}", fileName);
                return;
            }

            stdio.ErrorFormat("warning: table or database is not seleted");
        }
Beispiel #20
0
        private void Show(string arg1, string arg2)
        {
            var dname = theSide.DatabaseName;
            TableName[] vnames;

            switch (arg1)
            {
                case "pk":
                    {
                        var PKS = dname.TableWithPrimaryKey();
                        int count = 0;
                        foreach (var tname in PKS)
                        {
                            count++;
                            stdio.WriteLine("{0,5} {1}", $"[{count}]", tname);
                        }
                        stdio.WriteLine("total <{0}> tables with primary keys", count);
                    }
                    break;

                case "npk":
                    {
                        var tnames = dname.GetTableNames();
                        var PKS = dname.TableWithPrimaryKey();
                        int count = 0;
                        foreach (var tname in tnames)
                        {
                            if (PKS.FirstOrDefault(row => row.Equals(tname)) == null)
                            {
                                count++;
                                stdio.WriteLine("{0,5} {1}", $"[{count}]", tname);
                            }
                        }
                        stdio.WriteLine("total <{0}> tables without primary keys", count);
                    }
                    break;

                case "vw":
                    vnames = new MatchedDatabase(dname, arg2, null).DefaultViewNames;
                    foreach (var vname in vnames)
                    {
                        DataTable dt = null;
                        dt = vname.ViewSchema();
                        if (dt.Rows.Count > 0)
                        {
                            stdio.WriteLine("<{0}>", vname.ShortName);
                            dt.ToConsole();
                        }
                        else
                            stdio.WriteLine("not found at <{0}>", vname.ShortName);
                    }
                    break;

                case "view":
                    vnames = new MatchedDatabase(dname, arg2, null).DefaultViewNames;
                    vnames.Select(tname => new { Schema = tname.SchemaName, View = tname.Name })
                        .ToConsole();
                    break;

                case "proc":
                    dname.AllProc().ToConsole();
                    break;

                case "index":
                    dname.AllIndices().ToConsole();
                    break;

                case "connection":
                    {
                        var list = cfg.GetValue("servers");
                        if (list.Defined)
                        {
                            list.Select(kvp => new { Alias = (string)kvp[0].HostValue, Connection = kvp[1].ToString() })
                            .ToConsole();
                        }
                        else
                            stdio.ErrorFormat("connection string not found");
                    }
                    break;

                case "current":
                    stdio.WriteLine("current: {0}({1})", theSide.Provider.Name, showConnection(theSide.Provider));
                    break;

                case "var":
                    Context.ToConsole();
                    break;
                default:
                    stdio.ErrorFormat("invalid argument");
                    break;
            }
        }
Beispiel #21
0
        public void ExportCsvFile(Command cmd)
        {
            string path = cfg.GetValue<string>("csv.path", $"{Configuration.MyDocuments}\\csv");

            string file;
            Func<TableName, string> fullName = tname => $"{path}\\{sname.Path}\\{dname.Name}\\{tname.ShortName}.csv";

            if (tname != null)
            {
                stdio.WriteLine("start to generate {0} csv file", tname);
                file = fullName(tname);
                var dt = new SqlBuilder().SELECT.COLUMNS(cmd.Columns).FROM(tname).SqlCmd.FillDataTable();
                using (var writer = file.NewStreamWriter())
                {
                    CsvFile.Write(dt, writer, true);
                }
                stdio.WriteLine("completed {0} => {1}", tname.ShortName, file);
            }
            else if (dname != null)
            {
                stdio.WriteLine("start to generate {0} csv to directory: {1}", dname, path);
                CancelableWork.CanCancel(cts =>
                {
                    var md = new MatchedDatabase(dname, cmd.wildcard, cfg.exportExcludedTables);
                    TableName[] tnames = md.MatchedTableNames;
                    foreach (var tn in tnames)
                    {
                        if (cts.IsCancellationRequested)
                            return;

                        try
                        {
                            file = fullName(tn);
                            var dt = new TableReader(tn).Table;
                            using (var writer = file.NewStreamWriter())
                            {
                                CsvFile.Write(dt, writer, true);
                            }
                            stdio.WriteLine("generated for {0} at {1}", tn.ShortName, path);
                        }
                        catch (Exception ex)
                        {
                            stdio.ErrorFormat("failed to generate {0}, {1}", tn.ShortName, ex.Message);
                        }
                    }

                    stdio.WriteLine("completed");
                    return;
                });
            }
            else
            {
                stdio.ErrorFormat("warning: table or database is not seleted");
            }
        }
Beispiel #22
0
        private void Show(string arg1, string arg2)
        {
            var dname = theSide.DatabaseName;

            TableName[] vnames;

            switch (arg1)
            {
            case "pk":
            {
                var PKS   = dname.TableWithPrimaryKey();
                int count = 0;
                foreach (var tname in PKS)
                {
                    count++;
                    cout.WriteLine("{0,5} {1}", $"[{count}]", tname);
                }
                cout.WriteLine("total <{0}> tables with primary keys", count);
            }
            break;

            case "npk":
            {
                var tnames = dname.GetTableNames();
                var PKS    = dname.TableWithPrimaryKey();
                int count  = 0;
                foreach (var tname in tnames)
                {
                    if (PKS.FirstOrDefault(row => row.Equals(tname)) == null)
                    {
                        count++;
                        cout.WriteLine("{0,5} {1}", $"[{count}]", tname);
                    }
                }
                cout.WriteLine("total <{0}> tables without primary keys", count);
            }
            break;

            case "vw":
                vnames = new MatchedDatabase(dname, arg2).ViewNames();
                foreach (var vname in vnames)
                {
                    DataTable dt = null;
                    dt = vname.ViewSchema();
                    if (dt.Rows.Count > 0)
                    {
                        cout.WriteLine("<{0}>", vname.ShortName);
                        dt.ToConsole();
                    }
                    else
                    {
                        cout.WriteLine("not found at <{0}>", vname.ShortName);
                    }
                }
                break;

            case "view":
                vnames = new MatchedDatabase(dname, arg2).ViewNames();
                vnames.Select(tname => new { Schema = tname.SchemaName, View = tname.Name })
                .ToConsole();
                break;

            case "proc":
                dname.AllProc().ToConsole();
                break;

            case "index":
                dname.AllIndices().ToConsole();
                break;

            case "connection":
            {
                var L = connection.Providers.OrderBy(x => x.ServerName.Path);
                if (L.Count() > 0)
                {
                    L.Select(pvd => new { Alias = pvd.ServerName.Path, Connection = pvd.ToSimpleString() })
                    .ToConsole();
                }
                else
                {
                    cerr.WriteLine("connection string not found");
                }
            }
            break;

            case "current":
                cout.WriteLine("current: {0}({1})", theSide.Provider.Name, showConnection(theSide.Provider));
                break;

            case "var":
            {
                ((VAL)Context.DS)
                .Where(row => row[1].VALTYPE != VALTYPE.nullcon && row[1].VALTYPE != VALTYPE.voidcon && !row[0].Str.StartsWith("$"))
                .Select(row => new { Variable = (string)row[0], Value = row[1] })
                .ToConsole();
            }
            break;

            default:
                cerr.WriteLine("invalid argument");
                break;
            }
        }
Beispiel #23
0
        private bool SetSource(string source,  string sourceText)
        {
            if (source == null)
            {
                stdio.ErrorFormat("invalid argument");
                return false;
            }

            var path = new PathName(source);

            node = mgr.Navigate(path);
            if (node == null)
            {
                stdio.ErrorFormat("invalid path:" + path);
                return false;
            }

            dname = mgr.GetPathFrom<DatabaseName>(node);
            if (dname == null)
            {
                stdio.ErrorFormat("warning: {0} database is unavailable", sourceText);
                return false;
            }

            var server = mgr.GetPathFrom<ServerName>(node);
            side = new Side(server.Provider, dname);

            T = new TableName[] { };

            if (path.wildcard != null)
            {
                var m1 = new MatchedDatabase(dname, path.wildcard, mgr.Configuration.compareExcludedTables);
                T = m1.MatchedTableNames;
            }
            else
            {
                TableName tname = mgr.GetPathFrom<TableName>(node);
                if (tname == null)
                {
                    T = dname.GetTableNames();
                }
                else
                {
                    T = new TableName[] { tname };
                }
            }

            return true;
        }