示例#1
0
        public void Setup()
        {
            if (String.IsNullOrEmpty(ConfigPath))
            {
                ConfigPath = Consts.DEFAULT_SMARTSQL_CONFIG_PATH;
            }
            if (String.IsNullOrEmpty(Alias))
            {
                Alias = ConfigPath;
            }
            if (LoggerFactory == null)
            {
                LoggerFactory = NoneLoggerFactory.Instance;
            }

            if (ConfigLoader == null)
            {
                ConfigLoader = new LocalFileConfigLoader(ConfigPath, LoggerFactory);
            }
            var sqlMapConfig = ConfigLoader.Load();

            SmartSqlContext = new SmartSqlContext(LoggerFactory.CreateLogger <SmartSqlContext>(), sqlMapConfig);
            if (DbSessionStore == null)
            {
                DbSessionStore = new DbConnectionSessionStore(LoggerFactory, SmartSqlContext.DbProvider.Factory);
            }
            if (DataSourceFilter == null)
            {
                DataSourceFilter = new DataSourceFilter(LoggerFactory.CreateLogger <DataSourceFilter>(), DbSessionStore, SmartSqlContext);
            }
            if (SqlBuilder == null)
            {
                SqlBuilder = new SqlBuilder(LoggerFactory.CreateLogger <SqlBuilder>());
            }

            if (PreparedCommand == null)
            {
                PreparedCommand = new PreparedCommand(LoggerFactory.CreateLogger <PreparedCommand>(), SmartSqlContext);
            }
            if (CommandExecuter == null)
            {
                CommandExecuter = new CommandExecuter(LoggerFactory.CreateLogger <CommandExecuter>(), PreparedCommand);
            }
            if (DataReaderDeserializerFactory == null)
            {
                DataReaderDeserializerFactory = new EmitDataReaderDeserializerFactory();
            }
            if (CacheManager == null)
            {
                if (SmartSqlContext.IsCacheEnabled)
                {
                    CacheManager = new CacheManager(LoggerFactory.CreateLogger <CacheManager>(), SmartSqlContext, DbSessionStore);
                }
                else
                {
                    CacheManager = new NoneCacheManager();
                }
            }
            ConfigLoader.OnChanged += ConfigLoader_OnChanged;
        }
示例#2
0
 public CommandExecutor(DbCommand command, PreparedCommand prepared, RetryPolicy retryPolicy, TimedSection timedSection, ITransactionDiagnostic transaction, bool allowSynchronousOperations)
 {
     this.command      = command;
     this.prepared     = prepared;
     this.retryPolicy  = retryPolicy;
     this.timedSection = timedSection;
     this.transaction  = transaction;
     this.allowSynchronousOperations = allowSynchronousOperations;
 }
示例#3
0
            public void Execute()
            {
                Writer.Flush();
                Stream.Position = 0;
                Stream.SetLength(Stream.Length - 2);
                IDbCommand com;

                if (UsePrepared)
                {
                    var             name = ActionName.ToString();
                    PreparedCommand preparedCommand;
                    if (!PreparedStatements.TryGetValue(name, out preparedCommand))
                    {
                        var preparedName = "LR-" + PreparedCount++;
                        var rdr          = Stream.GetReader();
                        preparedCommand          = new PreparedCommand(preparedName, rdr.ReadToEnd(), string.Join(",", Types));
                        PreparedStatements[name] = preparedCommand;
                    }
                    Stream.Reset();
                    Writer.Write("EXECUTE \"");
                    Writer.Write(preparedCommand.Name);
                    Writer.Write('"');
                    if (preparedCommand.Types.Length > 0)
                    {
                        Writer.Write(" (");
                        if (WriteValues.Count > 0)
                        {
                            WriteValues[0](Writer);
                        }
                        for (int i = 1; i < WriteValues.Count; i++)
                        {
                            Writer.Write(',');
                            WriteValues[i](Writer);
                        }
                        Writer.Write(")");
                    }
                    Writer.Flush();
                    Stream.Position = 0;
                    com             = PostgresCommandFactory.PreparedCommand(Stream, preparedCommand.Name, preparedCommand.Query, preparedCommand.Types);
                }
                else
                {
                    com = PostgresCommandFactory.NewCommand(Stream);
                }
                Results = new object[ResultActions.Count];
                Query.Execute(
                    com,
                    dr =>
                {
                    for (int i = 0; i < ResultActions.Count; i++)
                    {
                        Results[i] = ResultActions[i](dr, i);
                    }
                });
            }
示例#4
0
    /// <summary>
    /// Attempts to execute the given prepared command.
    /// </summary>
    /// <param name="preparedCommand">The prepared command.</param>
    /// <param name="services">The services available to the invocation.</param>
    /// <param name="ct">The cancellation token for this operation.</param>
    /// <returns>An execution result which may or may not have succeeded.</returns>
    public async Task <Result <IResult> > TryExecuteAsync
    (
        PreparedCommand preparedCommand,
        IServiceProvider services,
        CancellationToken ct = default
    )
    {
        var(boundCommandNode, parameters) = preparedCommand;

        var groupType     = boundCommandNode.Node.GroupType;
        var groupInstance = (CommandGroup)services.GetRequiredService(groupType);

        groupInstance.SetCancellationToken(ct);

        var method = boundCommandNode.Node.CommandMethod;

        try
        {
            IResult result;
            if (method.ReturnType.GetGenericTypeDefinition() == typeof(ValueTask <>))
            {
                var genericUnwrapMethod = GetType()
                                          .GetMethod(nameof(UnwrapCommandValueTask), BindingFlags.NonPublic | BindingFlags.Static)
                                          ?? throw new InvalidOperationException();

                var unwrapMethod = genericUnwrapMethod
                                   .MakeGenericMethod(method.ReturnType.GetGenericArguments().Single());

                var invocationResult = method.Invoke(groupInstance, parameters);
                var unwrapTask       = (Task <IResult>)(unwrapMethod.Invoke
                                                        (
                                                            null, new[] { invocationResult }
                                                        ) ?? throw new InvalidOperationException());

                result = await unwrapTask;
            }
            else
            {
                var invocationResult = (Task)(method.Invoke(groupInstance, parameters)
                                              ?? throw new InvalidOperationException());
                await invocationResult;

                result = (IResult)(invocationResult.GetType().GetProperty(nameof(Task <object> .Result))
                                   ?.GetValue(invocationResult) ?? throw new InvalidOperationException());
            }

            return(Result <IResult> .FromSuccess(result));
        }
        catch (Exception ex)
        {
            return(ex);
        }
    }
        public DapperDataReaderDeserializerFactory_Test()
        {
            _deserializerFactory = new DapperDataReaderDeserializerFactory();

            _sessionStore = new DbConnectionSessionStore(LoggerFactory, DbProviderFactory);
            var _configLoader = new LocalFileConfigLoader(SqlMapConfigFilePath, LoggerFactory);
            var config        = _configLoader.Load();

            _smartSqlContext = new SmartSqlContext(LoggerFactory.CreateLogger <SmartSqlContext>(), config);
            _sqlBuilder      = new SqlBuilder(LoggerFactory.CreateLogger <SqlBuilder>(), _smartSqlContext, _configLoader);
            var _preparedCommand = new PreparedCommand(LoggerFactory.CreateLogger <PreparedCommand>(), _smartSqlContext);

            _commandExecuter = new CommandExecuter(LoggerFactory.CreateLogger <CommandExecuter>(), _preparedCommand);
        }
示例#6
0
        public async Task PrepareCommand_NoArg()
        {
            var preparedCommand = new PreparedCommand(postgres, "SELECT value FROM enumerate_table WHERE value = @value;");
            var command         = preparedCommand.Clone();
            var values          = new HashSet <int>();

            using (var reader = await command.ExecuteReaderAsync())
            {
                await foreach (var row in reader.ToAsyncEnumerable())
                {
                    values.Add(row.GetInt32(0));
                }
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.Contains(i, values);
            }
        }
        public void ShouldCreateDocumentsWithPreparedCommandByPossition()
        {
            var createQuery = new PreparedCommand("insert into Profile set name = ? , surname = ?");
            var values      = new[] {
                new { Name = "Pura", Surname = "Shields" },
                new { Name = "Deedra", Surname = "Bonura" },
                new { Name = "Foster", Surname = "Coppin" },
                new { Name = "Bradly", Surname = "Sanzone" }
            };

            foreach (var item in values)
            {
                var createdDoc = _database.Command(createQuery)
                                 .Run(item.Name, item.Surname).ToSingle();

                Assert.That(createdDoc.ORID, Is.Not.Null);
                Assert.That(createdDoc.GetField <string>("name"), Is.EqualTo(item.Name));
                Assert.That(createdDoc.GetField <string>("surname"), Is.EqualTo(item.Surname));
            }
        }
示例#8
0
        public async Task PrepareCommand_Arg()
        {
            var singleParameters = new Dictionary <string, NpgsqlDbType>()
            {
                { "Value", NpgsqlDbType.Integer }
            };

            var preparedCommand = new PreparedCommand(postgres, "SELECT value FROM enumerate_table WHERE value = @value;", singleParameters);
            var command         = preparedCommand.Clone();
            var values          = new HashSet <int>();

            command.Parameters["value"].Value = 5;

            using (var reader = await command.ExecuteReaderAsync())
            {
                await foreach (var row in reader.ToAsyncEnumerable())
                {
                    values.Add(row.GetInt32(0));
                }
            }

            Assert.Single(values);
            Assert.Contains(values, v => v == 5);
        }
示例#9
0
 public PreparedCommand Command(PreparedCommand command)
 {
     command.SetConnection(GetConnection());
     return(command);
 }