Example #1
0
        internal static void SetupForTestExplorerMode()
        {
            var          servTypeStr = ConfigurationManager.AppSettings["ServerTypeForTestExplorer"];
            DbServerType servType    = ReflectionHelper.ParseEnum <DbServerType>(servTypeStr);

            Reset(servType);
        }
Example #2
0
        private string GetConnectionString(DbServerType serverType)
        {
            string connectionString = string.Empty;
            SQLiteConnectionStringBuilder sqliteStringBuilder;

            switch (DbInfoOption)
            {
            case DbInfoOption.ConnectionString:
                connectionString = ConfigurationManager.ConnectionStrings[SelectedConnectionStringItem].ConnectionString;
                break;

            case DbInfoOption.Manually:
                if (serverType == DbServerType.Sqlite)
                {
                    sqliteStringBuilder            = new SQLiteConnectionStringBuilder();
                    sqliteStringBuilder.DataSource = SqliteFile;
                    connectionString = sqliteStringBuilder.ConnectionString;
                }
                else
                {
                    connectionString = BuildConnectionString(serverType);
                }

                break;

            case DbInfoOption.File:
                sqliteStringBuilder            = new SQLiteConnectionStringBuilder();
                sqliteStringBuilder.DataSource = SqliteFile;
                connectionString = sqliteStringBuilder.ConnectionString;
                break;
            }

            return(connectionString);
        }
        /// <summary>
        /// This class represents a provier class to get right schema reader based on database type.
        /// </summary>
        public static SchemaReader GetReader(DbServerType dbServerType)
        {
            SchemaReader schemaReader = null;

            switch (dbServerType)
            {
            case DbServerType.MsSql:
                schemaReader = new SqlServerSchemaReader();
                break;

            case DbServerType.Sqlite:
                schemaReader = new SqliteSchemaReader();
                break;

            case DbServerType.MySql:
                schemaReader = new MySqlSchemaReader();
                break;

            case DbServerType.Postgres:
                schemaReader = new PostgreSqlSchemaReader();
                break;
            }

            return(schemaReader);
        }
Example #4
0
 public static DbSettings CreateDbSettings(DbServerType serverType, string connectionString = null)
 {
     var driver = CreateDriver(serverType, connectionString);
       var options = GetDefaultOptions(serverType);
       var dbStt = new DbSettings(driver, options, connectionString);
       return dbStt;
 }
Example #5
0
 /// <summary>
 /// 引发 <see cref="DbServerStateScanner"/> 类型对象的 <see cref="Scanned"/> 事件。
 /// </summary>
 /// <param name="connectionString"></param>
 /// <param name="serverType"></param>
 /// <param name="serverState"></param>
 protected void OnScanned(string connectionString, DbServerType serverType, DbServerState serverState)
 {
     if (this.Scanned != null)
     {
         DbServerStateScanEventArgs e = new DbServerStateScanEventArgs(connectionString, serverType, serverState);
         this.Scanned(this, e);
     }
 }
Example #6
0
        } //method

        public static DbSettings CreateDbSettings(DbServerType serverType, string connectionString)
        {
            var driver  = CreateDriver(serverType);
            var options = driver.GetDefaultOptions();
            var dbStt   = new DbSettings(driver, options, connectionString);

            return(dbStt);
        }
Example #7
0
 public string Translate(Expression expression, DbServerType dbServerType)
 {
     _dbServer = dbServerType;
     this.sb   = new StringBuilder();
     this.Visit(expression);
     _whereClause = this.sb.ToString();
     return(_whereClause);
 }
 /// <summary>
 /// 以指定的属性值初始化类型 <see cref="DbServerStateScanEventArgs"/> 的新实例。
 /// </summary>
 /// <param name="connectionString"></param>
 /// <param name="serverType"></param>
 /// <param name="serverState"></param>
 public DbServerStateScanEventArgs(string connectionString, DbServerType serverType, DbServerState serverState)
     : this()
 {
     connectionString = Check.EmptyCheck(connectionString);
     this.ConnectionString = connectionString;
     this.DbServerType = serverType;
     this.DbServerState = serverState;
 }
Example #9
0
 public static bool TryParseServerType(string str, out DbServerType serverType)
 {
     if (Enum.TryParse <DbServerType>(str, true, out serverType))
     {
         return(true);
     }
     return(false);
 }
Example #10
0
 /// <summary>
 /// 以指定的属性值初始化类型 <see cref="DbServerStateScanEventArgs"/> 的新实例。
 /// </summary>
 /// <param name="connectionString"></param>
 /// <param name="serverType"></param>
 /// <param name="serverState"></param>
 public DbServerStateScanEventArgs(string connectionString, DbServerType serverType, DbServerState serverState)
     : this()
 {
     connectionString      = Check.EmptyCheck(connectionString);
     this.ConnectionString = connectionString;
     this.DbServerType     = serverType;
     this.DbServerState    = serverState;
 }
Example #11
0
        public static string GetSqlUpdate(DbServerType DSType, string TableName,
                                          List <CSqlNameValueKeepValue> aNameValueKeepValue, string Where)
        {
            string Sql = GetSqlTemplateUpdate(DSType, TableName, aNameValueKeepValue, Where);

            Sql = GetSqlTemplateReplaced(Sql, DSType, aNameValueKeepValue);
            return(Sql);
        }
Example #12
0
        internal static void SetupForTestExplorerMode()
        {
            InitAppConfig();
            var          servTypeStr = AppConfig["ServerTypeForTestExplorer"];
            DbServerType servType    = StringHelper.ParseEnum <DbServerType>(servTypeStr);

            Reset(servType);
        }
Example #13
0
        public static string GetSqlInsertSelect(DbServerType DSType, string TableName,
                                                List <CSqlNameValueKeepValue> aNameValueKeepValue, string TableNameFrom, string Where)
        {
            string Sql = GetSqlTemplateInsertSelect(DSType, TableName, aNameValueKeepValue, TableNameFrom, Where);

            Sql = GetSqlTemplateReplaced(Sql, DSType, aNameValueKeepValue);
            return(Sql);
        }
Example #14
0
        public static void GetTableColumnAndComment(DbServerType DbType, string Script,
                                                    out Dictionary <string, string> dicTableIs,
                                                    out Dictionary <string, Dictionary <string, string> > dicColumnIs)
        {
            dicTableIs  = new Dictionary <string, string>();
            dicColumnIs = new Dictionary <string, Dictionary <string, string> >();

            string PatternTable  = "";
            string PatternColumn = "";

            switch (DbType)
            {
            case DbServerType.SQLServer:
                string PatternCommon = @"sp_addextendedproperty.*@value=N'(?<Description>[^']*)'.*@level1name=N'(?<Table>[^']*)'";
                PatternTable  = PatternCommon + @"[\r\n]";
                PatternColumn = PatternCommon + @".*@level2name=N'(?<Column>[^']*)'";
                break;

            case DbServerType.Oracle:
                PatternTable  = @"COMMENT\sON\sTABLE\s(?<Table>\w+)\sIS\s'(?<Description>[^']+)';";
                PatternColumn = @"COMMENT\sON\sCOLUMN\s(?<Table>\w+)\.(?<Column>\w+)\sIS\s'(?<Description>[^']+)';";
                break;

            default:
                throw new Exception(string.Format("{0} is not supported.", DbType));
            }

            {
                Regex r = new Regex(PatternTable, CRegex.Options.Compiled_Multiline_IgnoreCase_IgnorePatternWhitespace);
                foreach (Match m in r.Matches(Script))
                {
                    string Table       = m.Groups["Table"].Value;
                    string Description = m.Groups["Description"].Value;
                    dicTableIs.Add(Table, Description);
                }
            }

            {
                Regex r = new Regex(PatternColumn, CRegex.Options.Compiled_Multiline_IgnoreCase_IgnorePatternWhitespace);
                foreach (Match m in r.Matches(Script))
                {
                    string Table       = m.Groups["Table"].Value;
                    string Column      = m.Groups["Column"].Value;
                    string Description = m.Groups["Description"].Value;

                    if (dicColumnIs.ContainsKey(Table))
                    {
                        dicColumnIs[Table].Add(Column, Description);
                    }
                    else
                    {
                        Dictionary <string, string> dicSub = new Dictionary <string, string>();
                        dicSub.Add(Column, Description);
                        dicColumnIs.Add(Table, dicSub);
                    }
                }
            }
        }
Example #15
0
        //Prepares for full run with a specified server
        public static void Reset(DbServerType serverType)
        {
            DeleteLocalLogFiles();
            InitAppConfig();
            ServerType = serverType;
            if (ServerType == DbServerType.SQLite)
            {
                DeleteSqliteDbFile(); //it will be created on connect, creat-option in conn string
            }
            Driver = DataUtility.CreateDriver(ServerType);

            //Load connection string
            var connStringName = ServerType.ToString() + "ConnectionString";

            // For SQLite we can use either provider
            var useMsSqlite = AppConfig["UseMsSqliteProvider"] == "true";

            if (ServerType == DbServerType.SQLite && useMsSqlite)
            {
                var sqliteDriver = (Data.SQLite.SQLiteDbDriver)Driver;
                sqliteDriver.ConnectionFactory = (s) => new Microsoft.Data.Sqlite.SqliteConnection(s);
                sqliteDriver.CommandFactory    = () => new Microsoft.Data.Sqlite.SqliteCommand();
                connStringName += "_MS";
            }


            var connString = AppConfig[connStringName];

            Util.Check(!string.IsNullOrEmpty(connString), "Connection string not found for key: {0}.", connStringName);
            if (connString.Contains("{bin}"))
            {
                var asmPath   = Assembly.GetExecutingAssembly().Location;
                var binFolder = Path.GetDirectoryName(asmPath);
                connString = connString.Replace("{bin}", binFolder);
            }
            ConnectionString = connString;


            DbOptions = Driver.GetDefaultOptions();
            //enable batch
            var useBatch = AppConfig["useBatchMode"] == "true";

            if (useBatch && Driver.Supports(DbFeatures.BatchedUpdates))
            {
                DbOptions |= DbOptions.UseBatchMode;
            }
            else
            {
                DbOptions &= ~DbOptions.UseBatchMode;
            }
            //check connection
            if (!DataUtility.TestConnection(Driver, ConnectionString, out var error))
            {
                Util.Throw("Failed to connect to the database: {0} \r\n  Connection string: {1}", error, ConnectionString);
            }
        }
Example #16
0
 public static DbOptions GetDefaultOptions(DbServerType serverType)
 {
     switch(serverType) {
     case DbServerType.MsSql: return Data.MsSql.MsSqlDbDriver.DefaultMsSqlDbOptions;
     case DbServerType.SqlCe: return Vita.Data.SqlCe.SqlCeDbDriver.DefaultDbOptions;
     case DbServerType.MySql: return Vita.Data.MySql.MySqlDbDriver.DefaultMySqlDbOptions;
     case DbServerType.Postgres: return Vita.Data.Postgres.PgDbDriver.DefaultPgDbOptions;
     case DbServerType.Sqlite: return Vita.Data.SQLite.SQLiteDbDriver.DefaultSQLiteDbOptions;
     default: return DbOptions.Default;
       }
 }
Example #17
0
        private static string GetSqlTemplateReplaced(string Sql, DbServerType DSType, List <CSqlNameValueKeepValue> aNameValueKeepValue)
        {
            foreach (CSqlNameValueKeepValue nvk in aNameValueKeepValue)
            {
                string FieldName = nvk.Name;
                bool   KeepValue = nvk.KeepValue;

                string Value = "";
                if (nvk.Value == null)
                {
                    Value = "null";
                }
                else if (KeepValue)
                {
                    //함수나 연산자가 사용된 경우엔 변형하지 않음.
                    Value = nvk.Value.ToString();
                }
                else
                {
                    SqlColumnTypeSimple ColumnType = GetColumnTypeSimple(nvk.Value);

                    switch (ColumnType)
                    {
                    case SqlColumnTypeSimple.DateTime:
                    case SqlColumnTypeSimple.String:
                        Value = nvk.Value.ToString();

                        Value = "'" + Value.Replace("'", "''");

                        if (DSType == DbServerType.MySQL)
                        {
                            Value = Value.Replace(@"\", @"\\");
                        }

                        Value += "'";

                        break;

                    case SqlColumnTypeSimple.Boolean:
                        Value = CFindRep.IfTrueThen1FalseThen0((bool)nvk.Value);
                        break;

                    case SqlColumnTypeSimple.Numeric:
                        Value = nvk.Value.ToString();
                        break;
                    }
                }

                Sql = Sql.Replace("{{" + FieldName + "}}", Value);
            }

            return(Sql);
        }
Example #18
0
        private static string ReplaceFunction(DbServerType DbServerFrom, DbServerType DbServerTo, string Sql)
        {
            Dictionary <string, string> dicFromTo = new Dictionary <string, string>();

            if ((DbServerFrom == DbServerType.SQLite) && (DbServerTo == DbServerType.SQLServer))
            {
                dicFromTo.Add("datetime('now')", "getdate()");
            }

            bool IsStartQuot = false;

            StringBuilder sbNew = new StringBuilder();

            for (int i = 0; i < Sql.Length; i++)
            {
                char c = Sql[i];
                if (c == '\'')
                {
                    IsStartQuot = !IsStartQuot;
                }

                bool IsFound = false;
                foreach (KeyValuePair <string, string> kv in dicFromTo)
                {
                    string From = kv.Key;
                    string To   = kv.Value;

                    if ((i + From.Length) > Sql.Length)
                    {
                        continue;
                    }

                    if (Sql.Substring(i, From.Length) != From)
                    {
                        continue;
                    }

                    IsFound = true;
                    sbNew.Append(To);
                    i += From.Length - 1;
                }

                if (IsFound)
                {
                    continue;
                }

                sbNew.Append(c);
            }

            return(sbNew.ToString());
        }
Example #19
0
        //Prepares for full run with a specified server
        internal static void Reset(TestConfig config)
        {
            if (BooksApp != null)
            {
                BooksApp.Flush();
            }
            Thread.Sleep(100); //to allow log dump of buffered messages
            DeleteLogFiles();  //it will happen only once
            WriteLog("\r\n------------------------ " + config.ToString() + "---------------------------------------------\r\n\r\n");

            ServerType   = config.ServerType;
            CacheEnabled = config.EnableCache;
            UseBatchMode = config.UseBatchMode;
            BooksApp     = null;
            _initFailed  = false;

            var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");

            //Load connection string
            ConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "ConnectionString"]);
            Util.Check(!string.IsNullOrEmpty(ConnectionString), "Connection string not found for server: {0}.", ServerType);
            LogConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "LogConnectionString"]);
            LogConnectionString = LogConnectionString ?? ConnectionString;

            LoginCryptoKey = protectedSection["LoginInfoCryptoKey"];
            Driver         = ToolHelper.CreateDriver(ServerType, ConnectionString);
            var dbOptions = ToolHelper.GetDefaultOptions(ServerType);

            if (config.UseStoredProcs)
            {
                dbOptions |= DbOptions.UseStoredProcs;
            }
            else
            {
                dbOptions &= ~DbOptions.UseStoredProcs;
            }
            if (config.UseBatchMode)
            {
                dbOptions |= DbOptions.UseBatchMode;
            }
            else
            {
                dbOptions &= ~DbOptions.UseBatchMode;
            }

            // dbOptions |= DbOptions.ForceArraysAsLiterals; -- just to test this flag
            DbSettings = new DbSettings(Driver, dbOptions, ConnectionString, upgradeMode: DbUpgradeMode.Always);
            //Test: remap login schema into login2
            // if (ServerType == DbServerType.MsSql)
            //    DbSettings.ModelConfig.MapSchema("login", "login2");
        }
Example #20
0
        private static string GetSqlTemplateInsert(DbServerType DSType, string TableName,
                                                   List <CSqlNameValueKeepValue> aNameValueKeepValue)
        {
            string SqlTmpHeader = "";

            switch (DSType)
            {
            case DbServerType.MySQL:
                SqlTmpHeader = "insert into " + TableName + " set ";
                break;

            default:
                SqlTmpHeader = "insert into " + TableName + "(";
                break;
            }

            string SqlTmpBody = "", SqlTmpBody2 = "";

            foreach (CSqlNameValueKeepValue nvk in aNameValueKeepValue)
            {
                string FieldName = nvk.Name;
                switch (DSType)
                {
                case DbServerType.MySQL:
                    SqlTmpBody += ",\n" + FieldName + " = {{" + FieldName + "}}";
                    break;

                default:
                    SqlTmpBody  += ",\n" + FieldName;
                    SqlTmpBody2 += ",\n{{" + FieldName + "}}";
                    break;
                }
            }

            string SqlTmp = "";

            switch (DSType)
            {
            case DbServerType.MySQL:
                SqlTmp = SqlTmpHeader + " " + SqlTmpBody.Substring(2);
                break;

            default:
                SqlTmp = SqlTmpHeader + SqlTmpBody.Substring(2) + ")"
                         + "\nvalues(" + SqlTmpBody2.Substring(2) + ")";
                break;
            }

            return(SqlTmp);
        }
Example #21
0
        public static object GetValue <T>(PropertyInfo item, T obj, DbServerType dbServerType) where T : class, new()
        {
            var value = item.GetValue(obj);

            switch (item.PropertyType.Name)
            {
            case "String":
                if (value is null)
                {
                    return("null");
                }
                else
                {
                    return($"'{value.ToString().Replace("'", "''")}'");
                }

            case "Boolean":
                if (dbServerType == DbServerType.Hana || dbServerType == DbServerType.PostGres)
                {
                    return(((bool)item.GetValue(obj)) == true ? "true" : "false");
                }
                else
                {
                    return(((bool)item.GetValue(obj)) == true ? "1" : "0");
                }

            case "DateTime":
                return($"'{((DateTime)item.GetValue(obj)).ToString("yyyy-MM-dd HH:mm:ss")}'");

            case "Nullable`1":
                return(GetNullableValue(item, obj, dbServerType));

            case "Double":
                var nfiDouble = new NumberFormatInfo();
                nfiDouble.NumberDecimalSeparator = ".";
                return(Convert.ToDouble(item.GetValue(obj)).ToString(nfiDouble));

            case "Decimal":
                var nfiDecimal = new NumberFormatInfo();
                nfiDecimal.NumberDecimalSeparator = ".";
                return(Convert.ToDecimal(item.GetValue(obj)).ToString(nfiDecimal));

            case "Byte[]":
                return(item.GetValue(obj));

            default:
                return(item.GetValue(obj));
            }
        }
Example #22
0
        public static DbDriver CreateDriver(DbServerType serverType)
        {
            var className = GetDriverClassName(serverType);
            var type      = Type.GetType(className);

            if (type == null)
            {
                var asm = TryLoadingDriverAssembly(className);
                type = asm.GetType(className);
            }
            Util.Check(type != null, "Failed to locate driver class {0}; load (instantiate) driver explicitly.", className);
            var driver = (DbDriver)Activator.CreateInstance(type);

            return(driver);
        }
Example #23
0
        private static string MakeInsertOrUpdate(DbServerType DbServer, CSqlInfoInsert Info)
        {
            string Sql = "";

            if (DbServer == DbServerType.SQLServer)
            {
                string Table = Info.Table;

                string FieldValue = "";
                for (int i = 0; i < Info.Value.Length; i++)
                {
                    if (!Info.IsPrimaryKey[i])
                    {
                        FieldValue += ", " + Info.Field[i] + " = " + Info.Delim[i] + Info.Value[i] + Info.Delim[i];
                    }
                }
                FieldValue = FieldValue.Substring(2);

                string Where = Info.WhereByPrimaryKey;

                string FieldList = string.Join(", ", Info.Field);

                string ValueList = "";
                for (int i = 0; i < Info.Value.Length; i++)
                {
                    ValueList += ", " + Info.Delim[i] + Info.Value[i] + Info.Delim[i];
                }
                ValueList = ValueList.Substring(2);

                Sql =
                    @"
update	{{Table}}
set	{{FieldValue}}
where	{{Where}};
if (@@rowcount = 0)
	insert into {{Table}}
		({{FieldList}})
	values
		({{ValueList}})"        .Replace("{{Table}}", Table)
                    .Replace("{{FieldValue}}", FieldValue)
                    .Replace("{{Where}}", Where)
                    .Replace("{{FieldList}}", FieldList)
                    .Replace("{{ValueList}}", ValueList);
            }


            return(Sql);
        }
Example #24
0
        private string BuildConnectionString(DbServerType serverType)
        {
            string connectionString = string.Empty;

            switch (serverType)
            {
            case DbServerType.MsSql:
                var msSqlStringBuilder = new SqlConnectionStringBuilder();
                if (UseWindowsAuthentication)
                {
                    msSqlStringBuilder.DataSource         = Server;
                    msSqlStringBuilder.InitialCatalog     = Database;
                    msSqlStringBuilder.IntegratedSecurity = true;
                }
                else
                {
                    msSqlStringBuilder.DataSource         = Server;
                    msSqlStringBuilder.InitialCatalog     = Database;
                    msSqlStringBuilder.UserID             = Username;
                    msSqlStringBuilder.Password           = Password;
                    msSqlStringBuilder.IntegratedSecurity = false;
                }
                connectionString = msSqlStringBuilder.ConnectionString;
                break;

            case DbServerType.MySql:
                var mySqlStringBuilder = new MySqlConnectionStringBuilder();
                mySqlStringBuilder.Server   = Server;
                mySqlStringBuilder.Database = Database;
                mySqlStringBuilder.Port     = (uint)Convert.ToInt32(Port);
                mySqlStringBuilder.UserID   = Username;
                mySqlStringBuilder.Password = Password;
                connectionString            = mySqlStringBuilder.ConnectionString;
                break;

            case DbServerType.Postgres:
                var postgresStringBuilder = new NpgsqlConnectionStringBuilder();
                postgresStringBuilder.Host     = Server;
                postgresStringBuilder.Database = Database;
                postgresStringBuilder.Port     = Convert.ToInt32(Port);
                postgresStringBuilder.UserName = Username;
                postgresStringBuilder.Password = Password;
                connectionString = postgresStringBuilder.ConnectionString;
                break;
            }

            return(connectionString);
        }
Example #25
0
        } //method

        public static DbOptions GetDefaultOptions(DbServerType serverType)
        {
            switch (serverType)
            {
            case DbServerType.MsSql: return(Data.MsSql.MsSqlDbDriver.DefaultMsSqlDbOptions);

            case DbServerType.SqlCe: return(Vita.Data.SqlCe.SqlCeDbDriver.DefaultSqlCeDbOptions);

            case DbServerType.MySql: return(Vita.Data.MySql.MySqlDbDriver.DefaultMySqlDbOptions);

            case DbServerType.Postgres: return(Vita.Data.Postgres.PgDbDriver.DefaultPgDbOptions);

            case DbServerType.Sqlite: return(Vita.Data.SQLite.SQLiteDbDriver.DefaultSQLiteDbOptions);// & ~DbOptions.AddSchemaToTableNames;

            default: return(DbOptions.Default);
            }
        }
Example #26
0
        //Prepares for full run with a specified server
        internal static void Reset(TestRunConfig config)
        {
            CurrentConfig = config;
            ServerType    = config.ServerType;
            if (BooksApp != null)
            {
                BooksApp.Flush();
            }
            Thread.Sleep(100); //to allow log dump of buffered messages
            DeleteLogFiles();  //it will happen only once
            WriteLog("\r\n------------------------ " + config.ToString() + "---------------------------------------------\r\n\r\n");

            ServerType   = config.ServerType;
            UseBatchMode = config.UseBatchMode;
            BooksApp     = null;
            _initFailed  = false;

            //Check connection string
            Util.Check(!string.IsNullOrEmpty(config.ConnectionString), "Connection string not found for server: {0}.", ServerType);

            Driver = DataUtility.CreateDriver(ServerType);
            var dbOptions = Driver.GetDefaultOptions();

            if (config.UseBatchMode)
            {
                dbOptions |= DbOptions.UseBatchMode;
            }
            else
            {
                dbOptions &= ~DbOptions.UseBatchMode;
            }

            // Custom naming policy. Uncomment below to see how all-lower case policy works for Postgres
            IDbNamingPolicy customNamingPolicy = null;

            //if(ServerType == DbServerType.Postgres)
            //customNamingPolicy = new AllLowCaseNamingPolicy("books", "login");
            DbSettings = new DbSettings(Driver, dbOptions, config.ConnectionString, upgradeMode: DbUpgradeMode.Always,
                                        namingPolicy: customNamingPolicy);

            //Test: remap login schema into login2
            // Remapping schemas might used in MySql, where schemas are actually databases
            // if (ServerType == DbServerType.MsSql)
            //    DbSettings.ModelConfig.MapSchema("login", "login2");
        }
Example #27
0
        private static string GetSqlTemplateUpdate(DbServerType DSType, string TableName,
                                                   List <CSqlNameValueKeepValue> aNameValueKeepValue, string Where)
        {
            string SqlTmpHeader = "update " + TableName + " set ";

            string SqlTmpBody = "";

            foreach (CSqlNameValueKeepValue nvk in aNameValueKeepValue)
            {
                string FieldName = nvk.Name;
                SqlTmpBody += ",\n" + FieldName + " = {{" + FieldName + "}}";
            }

            string SqlTmpWhere = "\nwhere " + Where;

            string SqlTmp = SqlTmpHeader + "\n" + SqlTmpBody.Substring(2) + "\n" + SqlTmpWhere;

            return(SqlTmp);
        }
Example #28
0
        private static object GetNullableValue <T>(PropertyInfo item, T obj, DbServerType dbServerType) where T : class, new()
        {
            var nfiDecimal = new NumberFormatInfo();

            nfiDecimal.NumberDecimalSeparator = ".";

            var value = item.GetValue(obj);

            if (value is int)
            {
                return(value);
            }
            else if (value == null)
            {
                return("null");
            }
            else if (value is true && (dbServerType == DbServerType.SqlServer || dbServerType == DbServerType.Sqlite))
            {
                return("1");
            }
Example #29
0
        private async void Generate()
        {
            try
            {
                // Reset content
                FileItems    = new ObservableCollection <string>();
                SelectedFile = string.Empty;

                ShowBuildrogress = true;
                var          request    = new GeneratePocoRequest();
                DbServerType serverType = (DbServerType)Enum.Parse(typeof(DbServerType), SelectedDatabaseTypeItem);
                request.ServerType          = serverType;
                request.Namespace           = Namespace;
                request.FolderLocation      = ModelsFolderLocation;
                request.IncludeRelationship = IncludeRelationship;
                request.ConnectionString    = GetConnectionString(serverType);

                if (string.IsNullOrEmpty(request.ConnectionString))
                {
                    throw new Exception("Invalid database info provided!");
                }

                var pocoResponse = await GeneratePocoModels.Generate(request);

                if (pocoResponse != null && pocoResponse.Filenames != null)
                {
                    var fileNames = pocoResponse.Filenames;
                    FileItems    = new ObservableCollection <string>(fileNames);
                    SelectedFile = string.Empty;
                    if (fileNames.Count > 0)
                    {
                        SelectedFile = fileNames[0];
                        FileSelectionChanged();
                    }
                }
            }
            finally
            {
                ShowBuildrogress = false;
            }
        }
Example #30
0
        public static string ConvertSql(string Sql, Dictionary <string, string[]> dicPrimaryKey,
                                        DbServerType DbServerFrom, DbServerType DbServerTo)
        {
            Sql = ReplaceFunction(DbServerFrom, DbServerTo, Sql);

            List <string> aSqlNew = new List <string>();

            Dictionary <int, string> dicIdxSql = SplitSqlBySemicolon(Sql);

            foreach (KeyValuePair <int, string> kv in dicIdxSql)
            {
                string SqlCur = kv.Value;

                CParagraph    p     = new CParagraph(CParagraph.DelimWord.NoUnderbar);
                List <string> aWord = p.GetWords(SqlCur, false);
                string        Sql2  = string.Join(" ", aWord.ToArray());

                if (DbServerFrom == DbServerType.SQLite)
                {
                    bool IsInsertOrReplace = (Sql2.IndexOf("insert or replace") != -1);
                    if (IsInsertOrReplace)
                    {
                        CSqlInfoInsert InfoInsert = GetSqlInfoInsert(DbServerFrom, SqlCur);
                        if (dicPrimaryKey.ContainsKey(InfoInsert.Table))
                        {
                            InfoInsert.PrimaryKey = dicPrimaryKey[InfoInsert.Table];
                        }

                        SqlCur = MakeInsertOrUpdate(DbServerTo, InfoInsert);
                        aSqlNew.Add(SqlCur);
                    }
                    else
                    {
                        aSqlNew.Add(SqlCur);
                    }
                }
            }

            return(string.Join(";", aSqlNew.ToArray()));
        }
Example #31
0
        //Prepares for full run with a specified server
        public static void Reset(DbServerType serverType)
        {
            ServerType = serverType;
            //Load connection string
            var connStringName = ServerType.ToString() + "ConnectionString";
            var connString     = ConfigurationManager.AppSettings[connStringName];

            Util.Check(!string.IsNullOrEmpty(connString), "Connection string not found for key: {0}.", connStringName);
            if (connString.Contains("{bin}"))
            {
                var asmPath   = Assembly.GetExecutingAssembly().Location;
                var binFolder = Path.GetDirectoryName(asmPath);
                connString = connString.Replace("{bin}", binFolder);
            }
            ConnectionString = connString;
            Driver           = ToolHelper.CreateDriver(ServerType);
            DbOptions        = ToolHelper.GetDefaultOptions(ServerType);
            //enable stored procs
            DbOptions &= ~DbOptions.UseStoredProcs; //it is on by default
            var useSp = ConfigurationManager.AppSettings["useStoredProcs"] == "true";

            if (useSp && Driver.Supports(DbFeatures.StoredProcedures))
            {
                DbOptions |= Data.DbOptions.UseStoredProcs;
            }
            //enable batch
            var useBatch = ConfigurationManager.AppSettings["useBatchMode"] == "true";

            if (useBatch && Driver.Supports(DbFeatures.BatchedUpdates))
            {
                DbOptions |= DbOptions.UseBatchMode;
            }
            //check connection
            string error;

            if (!ToolHelper.TestConnection(Driver, ConnectionString, out error))
            {
                Util.Throw("Failed to connection to the database: {0} \r\n  Connection string: {1}", error, ConnectionString);
            }
        }
Example #32
0
        private static string GetSqlTemplateInsertSelect(DbServerType DSType, string TableName,
                                                         List <CSqlNameValueKeepValue> aNameValueKeepValue, string TableNameFrom, string Where)
        {
            string SqlTmpHeader = "insert into " + TableName + "(";

            string SqlTmpBody = "", SqlTmpBody2 = "";

            foreach (CSqlNameValueKeepValue nvk in aNameValueKeepValue)
            {
                string FieldName = nvk.Name;

                SqlTmpBody  += ",\n" + FieldName;
                SqlTmpBody2 += ",\n{{" + FieldName + "}}";
            }

            string SqlTmp = SqlTmpHeader + SqlTmpBody.Substring(2) + ")"
                            + "\nselect\n" + SqlTmpBody2.Substring(2)
                            + "\nfrom " + TableNameFrom
                            + (!string.IsNullOrEmpty(Where) ? "\nwhere " + Where : "");

            return(SqlTmp);
        }
Example #33
0
        /// <summary>
        /// Get reader based on database type
        /// </summary>
        /// <param name="dbserverType">Database type [MsSql, Sqlite, MySql PostgreSQL]</param>
        /// <returns>SchemaReader object</returns>
        public static SchemaReader GetReader(DbServerType dbserverType)
        {
            SchemaReader schemaReader = null;

            switch (dbserverType)
            {
            case DbServerType.MsSql:
                throw new NotImplementedException();

            case DbServerType.Sqlite:
                throw new NotImplementedException();

            case DbServerType.MySql:
                schemaReader = new MySqlSugarSchemaReader();
                break;

            case DbServerType.Postgres:
                throw new NotImplementedException();
            }

            return(schemaReader);
        }
Example #34
0
 public static DbDriver CreateDriver(DbServerType serverType, string connectionString = null)
 {
     return CreateDriver(serverType.ToString(), connectionString);
 }
Example #35
0
 public DbDriver(DbServerType serverType, DbFeatures features)
 {
     ServerType = serverType;
       Features = features;
 }
 internal void DbServerStateScanned(string connectionString, DbServerType serverType, DbServerState serverState, Type contextType)
 {
     this.Dispatch(
         interceptor => interceptor.DbServerStateScanned(connectionString, serverType, serverState),
         contextType);
 }
Example #37
0
 //Prepares for full run with a specified server
 public static void Reset(DbServerType serverType)
 {
     ServerType = serverType;
       //Load connection string
       var connStringName = ServerType.ToString() + "ConnectionString";
       var connString = ConfigurationManager.AppSettings[connStringName];
       Util.Check(!string.IsNullOrEmpty(connString), "Connection string not found for key: {0}.", connStringName);
       if(connString.Contains("{bin}")) {
     var asmPath = Assembly.GetExecutingAssembly().Location;
     var binFolder = Path.GetDirectoryName(asmPath);
     connString = connString.Replace("{bin}", binFolder);
       }
       ConnectionString = connString;
       Driver = ToolHelper.CreateDriver(ServerType); //, ConnectionString);
       DbOptions = ToolHelper.GetDefaultOptions(ServerType);
       //enable stored procs
       DbOptions &= ~DbOptions.UseStoredProcs; //it is on by default
       var useSp = ConfigurationManager.AppSettings["useStoredProcs"] == "true";
       if (useSp && Driver.Supports(DbFeatures.StoredProcedures))
     DbOptions |= Data.DbOptions.UseStoredProcs;
       //enable batch
       var useBatch = ConfigurationManager.AppSettings["useBatchMode"] == "true";
       if(useBatch && Driver.Supports(DbFeatures.BatchedUpdates))
     DbOptions |= DbOptions.UseBatchMode;
       //check connection
       string error;
       if(!ToolHelper.TestConnection(Driver, ConnectionString, out error)) {
     Util.Throw("Failed to connection to the database: {0} \r\n  Connection string: {1}", error, ConnectionString);
       }
 }
Example #38
0
        //Prepares for full run with a specified server
        internal static void Reset(TestConfig config)
        {
            if(BooksApp != null)
            BooksApp.Flush();
              Thread.Sleep(100); //to allow log dump of buffered messages
              DeleteLogFiles(); //it will happen only once
              WriteLog("\r\n------------------------ " + config.ToString() + "---------------------------------------------\r\n\r\n");

              ServerType = config.ServerType;
              CacheEnabled = config.EnableCache;
              UseBatchMode = config.UseBatchMode;
              BooksApp = null;
              _initFailed = false;

              var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");
              //Load connection string
              ConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "ConnectionString"]);
              Util.Check(!string.IsNullOrEmpty(ConnectionString), "Connection string not found for server: {0}.", ServerType);
              LogConnectionString = ReplaceBinFolderToken(protectedSection[ServerType + "LogConnectionString"]);
              LogConnectionString = LogConnectionString ?? ConnectionString;

              LoginCryptoKey = protectedSection["LoginInfoCryptoKey"];
              Driver = ToolHelper.CreateDriver(ServerType, ConnectionString);
              var dbOptions = ToolHelper.GetDefaultOptions(ServerType);

              if (config.UseStoredProcs)
            dbOptions |= DbOptions.UseStoredProcs;
              else
            dbOptions &= ~DbOptions.UseStoredProcs;
              if (config.UseBatchMode)
            dbOptions |= DbOptions.UseBatchMode;
              else
            dbOptions &= ~DbOptions.UseBatchMode;

              // dbOptions |= DbOptions.ForceArraysAsLiterals; -- just to test this flag
              DbSettings = new DbSettings(Driver, dbOptions, ConnectionString, upgradeMode: DbUpgradeMode.Always);
              //Test: remap login schema into login2
              DbSettings.ModelConfig.MapSchema("login", "login2");
        }
 public SqlConnectionFactory(string connectionString, DbServerType serverType)
 {
     _connectionString = connectionString;
     _serverType = serverType;
 }
 /// <summary>
 /// 引发 <see cref="DbServerStateScanner"/> 类型对象的 <see cref="Scanned"/> 事件。
 /// </summary>
 /// <param name="connectionString"></param>
 /// <param name="serverType"></param>
 /// <param name="serverState"></param>
 protected void OnScanned(string connectionString, DbServerType serverType, DbServerState serverState)
 {
     if (this.Scanned != null)
     {
         DbServerStateScanEventArgs e = new DbServerStateScanEventArgs(connectionString, serverType, serverState);
         this.Scanned(this, e);
     }
 }