Esempio n. 1
0
 public abstract SmartSqlMapConfig Load(string path, ISmartSqlMapper smartSqlMapper);
Esempio n. 2
0
 public PostgreSql()
 {
     _sqlMapper = MapperContainer.Instance.GetSqlMapper("SmartSqlMapConfig-PostgreSql.xml");
 }
Esempio n. 3
0
        public SmartSqlMapConfig Load(string path, ISmartSqlMapper smartSqlMapper)
        {
            var config = LoadAsync(path, smartSqlMapper).Result;

            return(config);
        }
Esempio n. 4
0
 public BatchInsert(ISmartSqlMapper sqlMapper) : base(sqlMapper)
 {
 }
Esempio n. 5
0
 public DataSourceManager(ILoggerFactory loggerFactory, ISmartSqlMapper sqlMaper)
 {
     _logger        = loggerFactory.CreateLogger <DataSourceManager>();
     SmartSqlMapper = sqlMaper;
 }
Esempio n. 6
0
 public SmartSqlMapper_Test()
 {
     _sqlMapper = MapperContainer.Instance.GetSqlMapper();
 }
Esempio n. 7
0
 public SqlBuilder(ILoggerFactory loggerFactory, ISmartSqlMapper smartSqlMapper)
 {
     _logger        = loggerFactory.CreateLogger <SqlBuilder>();
     SmartSqlMapper = smartSqlMapper;
 }
Esempio n. 8
0
 public MySql()
 {
     _sqlMapper = MapperContainer.Instance.GetSqlMapper("SmartSqlMapConfig-MySql.xml");
 }
Esempio n. 9
0
 public DataSourceManager(ISmartSqlMapper sqlMaper)
 {
     SmartSqlMapper = sqlMaper;
 }
Esempio n. 10
0
        private StatementAttribute PreStatement(Type interfaceType, string scope, MethodInfo methodInfo, Type returnType, bool isTaskReturnType, ISmartSqlMapper smartSqlMapper)
        {
            returnType = isTaskReturnType ? returnType.GetGenericArguments().FirstOrDefault() : returnType;
            var statementAttr = methodInfo.GetCustomAttribute <StatementAttribute>();

            var methodName = _sqlIdNamingConvert == null ? methodInfo.Name : _sqlIdNamingConvert.Invoke(interfaceType, methodInfo);

            if (isTaskReturnType && methodInfo.Name.EndsWith("Async") && _sqlIdNamingConvert == null)
            {
                methodName = methodName.Substring(0, methodName.Length - 5);
            }
            if (statementAttr != null)
            {
                statementAttr.Id    = !String.IsNullOrEmpty(statementAttr.Id) ? statementAttr.Id : methodName;
                statementAttr.Scope = !String.IsNullOrEmpty(statementAttr.Scope) ? statementAttr.Scope : scope;
            }
            else
            {
                statementAttr = new StatementAttribute
                {
                    Scope = scope,
                    Id    = methodName
                };
            }

            if (returnType == typeof(DataTable))
            {
                statementAttr.Execute = ExecuteBehavior.GetDataTable;
                return(statementAttr);
            }
            if (returnType == typeof(DataSet))
            {
                statementAttr.Execute = ExecuteBehavior.GetDataSet;
                return(statementAttr);
            }
            if (IsValueTuple(returnType))
            {
                statementAttr.Execute = ExecuteBehavior.FillMultiple;
                return(statementAttr);
            }

            if (statementAttr.Execute == ExecuteBehavior.Auto)
            {
                SqlCommandType cmdType = SqlCommandType.Unknown;
                if (String.IsNullOrEmpty(statementAttr.Sql))
                {
                    var sqlStatement = smartSqlMapper.SmartSqlOptions.SmartSqlContext.GetStatement($"{statementAttr.Scope}.{statementAttr.Id}");
                    cmdType = sqlStatement.SqlCommandType;
                    if (sqlStatement.MultipleResultMap != null && !returnType.IsValueType)
                    {
                        statementAttr.Execute = ExecuteBehavior.GetNested;
                        return(statementAttr);
                    }
                }
                else
                {
                    cmdType = _commandAnalyzer.Analyse(statementAttr.Sql);
                }

                if (returnType == typeof(int) || returnType == _voidType || returnType == null)
                {
                    statementAttr.Execute = ExecuteBehavior.Execute;
                    if (returnType == typeof(int))
                    {
                        if (cmdType.HasFlag(SqlCommandType.Select))
                        {
                            statementAttr.Execute = ExecuteBehavior.ExecuteScalar;
                        }
                    }
                }
                else if (returnType.IsValueType || returnType == typeof(string))
                {
                    statementAttr.Execute = ExecuteBehavior.ExecuteScalar;
                    if (!cmdType.HasFlag(SqlCommandType.Select))
                    {
                        statementAttr.Execute = ExecuteBehavior.Execute;
                    }
                }
                else
                {
                    var isQueryEnumerable = typeof(IEnumerable).IsAssignableFrom(returnType);
                    if (isQueryEnumerable)
                    {
                        statementAttr.Execute = ExecuteBehavior.Query;
                    }
                    else
                    {
                        statementAttr.Execute = ExecuteBehavior.QuerySingle;
                    }
                }
            }
            return(statementAttr);
        }
Esempio n. 11
0
        public T CreateInstance <T>(ISmartSqlMapper smartSqlMapper, string scope = "")
        {
            var interfaceType = typeof(T);

            return((T)CreateInstance(interfaceType, smartSqlMapper, scope));
        }
Esempio n. 12
0
        private void BuildMethod(Type interfaceType, TypeBuilder typeBuilder, MethodInfo methodInfo, FieldBuilder sqlMapperField, ISmartSqlMapper smartSqlMapper, string scope)
        {
            var methodParams = methodInfo.GetParameters();
            var paramTypes   = methodParams.Select(m => m.ParameterType).ToArray();

            if (paramTypes.Any(p => p.IsGenericParameter))
            {
                _logger.LogError("SmartSql.DyRepository method parameters do not support generic parameters for the time being!");
                throw new SmartSqlException("SmartSql.DyRepository method parameters do not support generic parameters for the time being!");
            }
            var returnType = methodInfo.ReturnType;

            var implMehtod = typeBuilder.DefineMethod(methodInfo.Name
                                                      , MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final
                                                      , returnType, paramTypes);

            var isTaskReturnType = _taskType.IsAssignableFrom(returnType);

            if (methodInfo.IsGenericMethod)
            {
                var genericArgs       = methodInfo.GetGenericArguments();
                var gArgNames         = genericArgs.Select(gArg => gArg.Name).ToArray();
                var defineGenericArgs = implMehtod.DefineGenericParameters(gArgNames);
                for (int i = 0; i < gArgNames.Length; i++)
                {
                    var genericArg       = genericArgs[i];
                    var defineGenericArg = defineGenericArgs[i];
                    defineGenericArg.SetGenericParameterAttributes(genericArg.GenericParameterAttributes);
                }
            }

            StatementAttribute statementAttr = PreStatement(interfaceType, scope, methodInfo, returnType, isTaskReturnType, smartSqlMapper);
            var ilGenerator = implMehtod.GetILGenerator();

            ilGenerator.DeclareLocal(_reqContextType);
            ilGenerator.DeclareLocal(_dbParametersType);
            if (statementAttr.Execute == ExecuteBehavior.FillMultiple)
            {
                ilGenerator.DeclareLocal(_multipleResultType);
                ilGenerator.Emit(OpCodes.Newobj, _multipleResultImplCtor);
                ilGenerator.Emit(OpCodes.Stloc_2);
            }
            if (paramTypes.Length == 1 && paramTypes.First() == _reqContextType)
            {
                ilGenerator.Emit(OpCodes.Ldarg_1);
                ilGenerator.Emit(OpCodes.Stloc_0);
            }
            else
            {
                EmitNewRequestContext(ilGenerator);
                SetCmdTypeAndSourceChoice(statementAttr, ilGenerator);

                if (String.IsNullOrEmpty(statementAttr.Sql))
                {
                    EmitSetScope(ilGenerator, statementAttr.Scope);
                    EmitSetSqlId(ilGenerator, statementAttr);
                }
                else
                {
                    EmitSetRealSql(ilGenerator, statementAttr);
                }
                if (paramTypes.Length == 1 && !IsSimpleParam(paramTypes.First()))
                {
                    ilGenerator.Emit(OpCodes.Ldloc_0);
                    ilGenerator.Emit(OpCodes.Ldarg_1);
                    ilGenerator.Emit(OpCodes.Call, _set_RequestMethod);
                }
                else if (paramTypes.Length > 0)
                {
                    bool ignoreParameterCase = smartSqlMapper.SmartSqlOptions.SmartSqlContext.IgnoreParameterCase;
                    ilGenerator.Emit(ignoreParameterCase ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                    ilGenerator.Emit(OpCodes.Newobj, _dbParametersCtor);
                    ilGenerator.Emit(OpCodes.Stloc_1);
                    for (int i = 0; i < methodParams.Length; i++)
                    {
                        int    argIndex     = i + 1;
                        var    reqParam     = methodParams[i];
                        string reqParamName = reqParam.Name;
                        var    paramAttr    = reqParam.GetCustomAttribute <ParamAttribute>();
                        if (paramAttr != null && !String.IsNullOrEmpty(paramAttr.Name))
                        {
                            reqParamName = paramAttr.Name;
                        }
                        ilGenerator.Emit(OpCodes.Ldloc_1);             //[dic]
                        ilGenerator.Emit(OpCodes.Ldstr, reqParamName); //[dic][param-name]
                        EmitUtils.LoadArg(ilGenerator, argIndex);
                        if (reqParam.ParameterType.IsValueType)
                        {
                            ilGenerator.Emit(OpCodes.Box, reqParam.ParameterType);
                        }
                        ilGenerator.Emit(OpCodes.Call, _addDbParamMehtod);//[empty]
                    }
                    ilGenerator.Emit(OpCodes.Ldloc_0);
                    ilGenerator.Emit(OpCodes.Ldloc_1);
                    ilGenerator.Emit(OpCodes.Call, _set_RequestMethod);
                }
            }

            MethodInfo executeMethod = null;

            executeMethod = PreExecuteMethod(statementAttr, returnType, isTaskReturnType);
            ilGenerator.Emit(OpCodes.Ldarg_0);               // [this]
            ilGenerator.Emit(OpCodes.Ldfld, sqlMapperField); //[this][sqlMapper]
            ilGenerator.Emit(OpCodes.Ldloc_0);               //[sqlMapper][requestContext]
            if (statementAttr.Execute == ExecuteBehavior.FillMultiple)
            {
                var returnGenericTypeArguments = returnType.GenericTypeArguments;
                foreach (var typeArg in returnGenericTypeArguments)
                {
                    bool isEnum           = _enumerableType.IsAssignableFrom(typeArg);
                    var  addTypeMapMethod = isEnum ? _multipleResult_AddTypeMap : _multipleResult_AddSingleTypeMap;
                    var  realRetType      = isEnum ? typeArg.GenericTypeArguments[0] : typeArg;
                    addTypeMapMethod = addTypeMapMethod.MakeGenericMethod(realRetType);
                    ilGenerator.Emit(OpCodes.Ldloc_2);
                    ilGenerator.Emit(OpCodes.Call, addTypeMapMethod);
                    ilGenerator.Emit(OpCodes.Pop);
                }
                ilGenerator.Emit(OpCodes.Ldloc_2);
            }
            ilGenerator.Emit(OpCodes.Call, executeMethod);
            if (returnType == _voidType)
            {
                ilGenerator.Emit(OpCodes.Pop);
            }
            if (statementAttr.Execute == ExecuteBehavior.FillMultiple)
            {
                ilGenerator.Emit(OpCodes.Pop);
                QueryMultipleToValueTuple(methodInfo, returnType, ilGenerator);
            }
            ilGenerator.Emit(OpCodes.Ret);

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"RepositoryBuilder.BuildMethod:{methodInfo.Name}->Statement:[Scope:{statementAttr.Scope},Id:{statementAttr.Id},Execute:{statementAttr.Execute},Sql:{statementAttr.Sql},IsAsync:{isTaskReturnType}]");
            }
        }
Esempio n. 13
0
        public override SmartSqlMapConfig Load(string path, ISmartSqlMapper smartSqlMapper)
        {
            _logger.LogDebug($"NativeConfigLoader Load: { _smartSqlOptions.SqlMapperPath} Starting");

            var config = new SmartSqlMapConfig()
            {
                Path               = _smartSqlOptions.SqlMapperPath,
                SmartSqlMapper     = smartSqlMapper,
                SmartSqlMaps       = new List <SmartSqlMap>(),
                SmartSqlMapSources = new List <SmartSqlMapSource>()
                {
                    new SmartSqlMapSource()
                    {
                        Path = _smartSqlOptions.SqlMapperPath,
                        Type = SmartSqlMapSource.ResourceType.Directory
                    }
                },
                Database = new Database()
                {
                    DbProvider = new DbProvider()
                    {
                        ParameterPrefix = _smartSqlOptions.ParameterPrefix,
                        Name            = _smartSqlOptions.DbProviderFactory.GetType().Name,
                        Type            = _smartSqlOptions.DbProviderFactory.GetType().AssemblyQualifiedName
                    },
                    WriteDataSource = new WriteDataSource()
                    {
                        ConnectionString = _smartSqlOptions.ConnectionString,
                        Name             = _smartSqlOptions.LoggingName
                    },
                    ReadDataSources = new List <ReadDataSource>()
                    {
                        new ReadDataSource()
                        {
                            ConnectionString = _smartSqlOptions.ConnectionString,
                            Name             = _smartSqlOptions.LoggingName,
                            Weight           = 1,
                        }
                    },
                },
                Settings = new Settings()
                {
                    ParameterPrefix   = _smartSqlOptions.ParameterPrefix,
                    IsWatchConfigFile = true
                },
            };

            if (_smartSqlOptions.UseManifestResource)
            {
                foreach (var sourceName in Assembly.GetExecutingAssembly().GetManifestResourceNames())
                {
                    LoadManifestSmartSqlMap(config, sourceName);
                }
            }
            else
            {
                foreach (var sqlmapSource in config.SmartSqlMapSources)
                {
                    switch (sqlmapSource.Type)
                    {
                    case SmartSqlMapSource.ResourceType.File:
                    {
                        LoadSmartSqlMap(config, sqlmapSource.Path);
                        break;
                    }

                    case SmartSqlMapSource.ResourceType.Directory:
                    {
                        var childSqlmapSources = Directory.EnumerateFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, sqlmapSource.Path), "*.xml");
                        foreach (var childSqlmapSource in childSqlmapSources)
                        {
                            LoadSmartSqlMap(config, childSqlmapSource);
                        }
                        break;
                    }

                    default:
                    {
                        _logger.LogDebug($"LocalFileConfigLoader unknow SmartSqlMapSource.ResourceType:{sqlmapSource.Type}.");
                        break;
                    }
                    }
                }
            }
            _logger.LogDebug($"LocalFileConfigLoader Load: { _smartSqlOptions.SqlMapperPath} End");
            smartSqlMapper.LoadConfig(config);

            if (config.Settings.IsWatchConfigFile)
            {
                _logger.LogDebug($"LocalFileConfigLoader Load Add WatchConfig: { _smartSqlOptions.SqlMapperPath} Starting.");
                WatchConfig(smartSqlMapper);
                _logger.LogDebug($"LocalFileConfigLoader Load Add WatchConfig: { _smartSqlOptions.SqlMapperPath} End.");
            }
            return(config);
        }
Esempio n. 14
0
        /// <summary>
        /// 监控配置文件-热更新
        /// </summary>
        /// <param name="smartSqlMapper"></param>
        /// <param name="config"></param>
        private void WatchConfig(ISmartSqlMapper smartSqlMapper)
        {
            var config = smartSqlMapper.SqlMapConfig;

            #region SmartSqlMapConfig File Watch

            _logger.LogDebug($"LocalFileConfigLoader Watch SmartSqlMapConfig: {config.Path} .");
            var cofigFileInfo = FileLoader.GetInfo(config.Path);
            FileWatcherLoader.Instance.Watch(cofigFileInfo, () =>
            {
                Thread.Sleep(DELAYED_LOAD_FILE);
                lock (this)
                {
                    try
                    {
                        _logger.LogDebug($"LocalFileConfigLoader Changed ReloadConfig: {config.Path} Starting");
                        var newConfig = Load(config.Path, smartSqlMapper);
                        _logger.LogDebug($"LocalFileConfigLoader Changed ReloadConfig: {config.Path} End");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(new EventId(ex.HResult), ex, ex.Message);
                    }
                }
            });

            #endregion SmartSqlMapConfig File Watch

            #region SmartSqlMaps File Watch

            foreach (var sqlmap in config.SmartSqlMaps)
            {
                #region SqlMap File Watch

                _logger.LogDebug($"LocalFileConfigLoader Watch SmartSqlMap: {sqlmap.Path} .");
                var sqlMapFileInfo = FileLoader.GetInfo(sqlmap.Path);
                FileWatcherLoader.Instance.Watch(sqlMapFileInfo, () =>
                {
                    Thread.Sleep(DELAYED_LOAD_FILE);
                    lock (this)
                    {
                        try
                        {
                            _logger.LogDebug($"LocalFileConfigLoader Changed Reload SmartSqlMap: {sqlmap.Path} Starting");
                            var sqlmapStream  = LoadConfigStream(sqlmap.Path);
                            var newSqlmap     = LoadSmartSqlMap(sqlmapStream, config);
                            sqlmap.Scope      = newSqlmap.Scope;
                            sqlmap.Statements = newSqlmap.Statements;
                            sqlmap.Caches     = newSqlmap.Caches;
                            config.ResetMappedStatements();
                            smartSqlMapper.CacheManager.ResetMappedCaches();
                            _logger.LogDebug($"LocalFileConfigLoader Changed Reload SmartSqlMap: {sqlmap.Path} End");
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(new EventId(ex.HResult), ex, ex.Message);
                        }
                    }
                });

                #endregion SqlMap File Watch
            }

            #endregion SmartSqlMaps File Watch
        }
Esempio n. 15
0
 public AbstractBatchInsert(ISmartSqlMapper sqlMapper)
 {
     SqlMapper      = sqlMapper;
     ColumnMappings = new Dictionary <String, ColumnMapping>(StringComparer.CurrentCulture);
 }
Esempio n. 16
0
 public CacheManager(ILoggerFactory loggerFactory, ISmartSqlMapper smartSqlMapper)
 {
     _logger        = loggerFactory.CreateLogger <CacheManager>();
     SmartSqlMapper = smartSqlMapper;
 }
Esempio n. 17
0
 public DataAccess(ISmartSqlMapper sqlMapper)
 {
     SqlMapper = sqlMapper;
     InitScope();
 }
Esempio n. 18
0
 public CacheManager(ISmartSqlMapper smartSqlMapper)
 {
     SmartSqlMapper = smartSqlMapper;
 }
Esempio n. 19
0
 public DataAccessGeneric(ISmartSqlMapper smartSqlMapper) : base(smartSqlMapper)
 {
 }
Esempio n. 20
0
 public TestDataAccess(ISmartSqlMapper smartSqlMapper) : base(smartSqlMapper)
 {
 }
Esempio n. 21
0
        internal SqlCommandType Analyse(ISmartSqlMapper smartSqlMapper, string scope, string id)
        {
            string realSql = BuildStatementFullSql(smartSqlMapper, scope, id);

            return(Analyse(realSql));
        }
Esempio n. 22
0
 public SqlServer()
 {
     _sqlMapper = MapperContainer.Instance.GetSqlMapper("SmartSqlMapConfig.xml");
 }
Esempio n. 23
0
 public TestBase()
 {
     SqlMapper = new SmartSqlMapper();
 }
Esempio n. 24
0
 public SmartSqlMapConfigWatcher(ISmartSqlMapper smartSqlMapper, ZooKeeperConfigLoader configLoader)
 {
     SmartSqlMapper = smartSqlMapper;
     ConfigLoader   = configLoader;
 }
Esempio n. 25
0
 public SqlBuilder(ISmartSqlMapper smartSqlMapper)
 {
     SmartSqlMapper = smartSqlMapper;
 }
Esempio n. 26
0
 public SmartSqlMapConfigWatcher(ILoggerFactory loggerFactory, ISmartSqlMapper smartSqlMapper, ZooKeeperConfigLoader configLoader)
 {
     _logger        = loggerFactory.CreateLogger <SmartSqlMapConfigWatcher>();
     SmartSqlMapper = smartSqlMapper;
     ConfigLoader   = configLoader;
 }