Пример #1
0
        private string[] ListPrimaryKeys(IManagedConnection con, DiscoveredTable table)
        {
            string query = $@"SELECT               
            pg_attribute.attname, 
            format_type(pg_attribute.atttypid, pg_attribute.atttypmod) 
            FROM pg_index, pg_class, pg_attribute 
            WHERE 
            pg_class.oid = '{table.GetFullyQualifiedName()}'::regclass AND 
                indrelid = pg_class.oid AND  
            pg_attribute.attrelid = pg_class.oid AND 
            pg_attribute.attnum = any(pg_index.indkey)
            AND indisprimary";

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

            using (DbCommand cmd = table.GetCommand(query, con.Connection))
            {
                cmd.Transaction = con.Transaction;

                using (DbDataReader r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        toReturn.Add((string)r["attname"]);
                    }

                    r.Close();
                }
            }

            return(toReturn.ToArray());
        }
Пример #2
0
        /// <summary>
        /// Overload of basic Init which takes a IServiceProvider and initializes
        /// what it can of the container with elements provided by IServcieProvider
        ///
        /// Today this is only the IManagedProvider if available but this function
        /// could be modified to init other things provided by the ServiceProvider
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="site"></param>
        public virtual void Init(XmlDocument doc, IServiceProvider site)
        {
            if (site != null)
            {
                //see if service provider supports INodeInformation interface from the object explorer
                try
                {
                    //NOTE: we're trying to forcefully set connection information on the data container.
                    //If this code doesn't execute, then dc.Init call below will result in CDataContainer
                    //initializing its ConnectionInfo member with a new object contructed off the parameters
                    //in the XML doc [server name, user name etc]
                    IManagedConnection managedConnection = site.GetService(typeof(IManagedConnection)) as IManagedConnection;
                    if (managedConnection != null)
                    {
                        this.SetManagedConnection(managedConnection);
                    }
                }
                catch (Exception ex)
                {
                    // keep the exception flowing
                    throw ex;
                }
            }

            this.Document = doc;
            LoadData();

            // finish the initialization
            this.Init(doc);
        }
Пример #3
0
        /// <summary>
        /// Inserts the values specified into the database table and returns the last autonum identity generated (or 0 if none present)
        /// </summary>
        /// <param name="toInsert"></param>
        /// <param name="culture"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public int Insert(Dictionary <DiscoveredColumn, object> toInsert, CultureInfo culture, IManagedTransaction transaction = null)
        {
            var syntaxHelper = GetQuerySyntaxHelper();
            var server       = Database.Server;

            var _parameterNames = syntaxHelper.GetParameterNamesFor(toInsert.Keys.ToArray(), c => c.GetRuntimeName());

            using (IManagedConnection connection = Database.Server.GetManagedConnection(transaction))
            {
                string sql =
                    string.Format("INSERT INTO {0}({1}) VALUES ({2})",
                                  GetFullyQualifiedName(),
                                  string.Join(",", toInsert.Keys.Select(c => syntaxHelper.EnsureWrapped(c.GetRuntimeName()))),
                                  string.Join(",", toInsert.Keys.Select(c => _parameterNames[c]))
                                  );

                using (var cmd = server.Helper.GetCommand(sql, connection.Connection, connection.Transaction))
                {
                    foreach (KeyValuePair <DiscoveredColumn, object> kvp in toInsert)
                    {
                        var parameter = server.Helper.GetParameter(_parameterNames[kvp.Key]);

                        var p = GetQuerySyntaxHelper().GetParameter(parameter, kvp.Key, kvp.Value, culture);
                        cmd.Parameters.Add(p);
                    }

                    int result = Helper.ExecuteInsertReturningIdentity(this, cmd, connection.ManagedTransaction);

                    return(result);
                }
            }
        }
Пример #4
0
        public static QueryPlan ExplainQuery(this IManagedConnection runner, NpgsqlCommand cmd, Action <IConfigureExplainExpressions> configureExplain = null)
        {
            var serializer = new JsonNetSerializer();

            var config = new ConfigureExplainExpressions();

            configureExplain?.Invoke(config);

            cmd.CommandText = string.Concat($"explain ({config} format json) ", cmd.CommandText);
            return(runner.Execute(cmd, c =>
            {
                using (var reader = cmd.ExecuteReader())
                {
                    var queryPlans = reader.Read() ? serializer.FromJson <QueryPlanContainer[]>(reader.GetTextReader(0)) : null;
                    var planToReturn = queryPlans?[0].Plan;
                    if (planToReturn != null)
                    {
                        planToReturn.PlanningTime = queryPlans[0].PlanningTime;
                        planToReturn.ExecutionTime = queryPlans[0].ExecutionTime;
                        planToReturn.Command = cmd;
                    }
                    return planToReturn;
                }
            }));
        }
Пример #5
0
 /// <summary>
 /// Creates and runs an ALTER TABLE SQL statement that adds a new column to the table
 /// </summary>
 /// <param name="name">The unqualified name for the new column e.g. "MyCol2"</param>
 /// <param name="databaseType">The proprietary SQL data type for the new column</param>
 /// <param name="allowNulls">True to allow null</param>
 /// <param name="timeoutInSeconds">The length of time to wait in seconds before giving up (See <see cref="DbCommand.CommandTimeout"/>)</param>
 public void AddColumn(string name, string databaseType, bool allowNulls, int timeoutInSeconds)
 {
     using (IManagedConnection connection = Database.Server.GetManagedConnection())
     {
         Helper.AddColumn(this, connection.Connection, name, databaseType, allowNulls, timeoutInSeconds);
     }
 }
Пример #6
0
        /// <summary>
        /// Creates a new DocumentStore with the supplied StoreOptions
        /// </summary>
        /// <param name="options"></param>
        public DocumentStore(StoreOptions options)
        {
            _options           = options;
            _connectionFactory = options.ConnectionFactory();
            _runner            = new ManagedConnection(_connectionFactory, CommandRunnerMode.ReadOnly);

            _logger = options.Logger();

            var creation = options.AutoCreateSchemaObjects
                ? (IDocumentSchemaCreation) new DevelopmentSchemaCreation(_connectionFactory, _logger)
                : new ProductionSchemaCreation();

            Schema = new DocumentSchema(_options, _connectionFactory, creation);

            Schema.Alter(options.Schema);

            _serializer = options.Serializer();

            var cleaner = new DocumentCleaner(_connectionFactory, Schema);

            Advanced = new AdvancedOptions(cleaner, options);

            Diagnostics = new Diagnostics(Schema, new MartenQueryExecutor(_runner, Schema, _serializer, _parser, new NulloIdentityMap(_serializer)));

            EventStore = new EventStoreAdmin(_connectionFactory, _options, creation, _serializer);
        }
Пример #7
0
        public static IList <string> GetStringList(this IManagedConnection runner, string sql, params object[] parameters)
        {
            var list = new List <string>();

            runner.Execute(cmd =>
            {
                cmd.WithText(sql);
                parameters.Each(x =>
                {
                    var param       = cmd.AddParameter(x);
                    cmd.CommandText = cmd.CommandText.UseParameter(param);
                });

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(reader.GetString(0));
                    }

                    reader.Close();
                }
            });

            return(list);
        }
        internal static async Task StreamMany(this IManagedConnection connection, NpgsqlCommand command, Stream stream, CancellationToken token)
        {
            using (var reader = (NpgsqlDataReader)await connection.ExecuteReaderAsync(command, token))
            {
                var ordinal = reader.FieldCount == 1 ? 0 : reader.GetOrdinal("data");

                await stream.WriteBytes(LeftBracket, token);

                if (await reader.ReadAsync(token))
                {
                    var source = await reader.GetStreamAsync(ordinal, token);

                    await source.CopyStreamSkippingSOHAsync(stream, token);
                }

                while (await reader.ReadAsync(token))
                {
                    await stream.WriteBytes(Comma, token);

                    var source = await reader.GetStreamAsync(ordinal, token);

                    await source.CopyStreamSkippingSOHAsync(stream, token);
                }

                await stream.WriteBytes(RightBracket, token);
            }
        }
Пример #9
0
        private async Task <HighWaterStatistics> loadCurrentStatistics(IManagedConnection conn, CancellationToken token)
        {
            var statistics = new HighWaterStatistics();

            using var reader = await conn.ExecuteReaderAsync(_stateDetection, token);

            if (await reader.ReadAsync(token))
            {
                statistics.HighestSequence = await reader.GetFieldValueAsync <long>(0, token);
            }

            await reader.NextResultAsync(token);

            if (!await reader.ReadAsync(token))
            {
                return(statistics);
            }

            statistics.LastMark = statistics.SafeStartMark = await reader.GetFieldValueAsync <long>(0, token);

            statistics.LastUpdated = await reader.GetFieldValueAsync <DateTimeOffset>(1, token);

            statistics.Timestamp = await reader.GetFieldValueAsync <DateTimeOffset>(2, token);

            return(statistics);
        }
Пример #10
0
        private async Task <long> findCurrentMark(HighWaterStatistics statistics, IManagedConnection conn, CancellationToken token)
        {
            // look for the current mark
            _start.Value     = statistics.SafeStartMark;
            using var reader = await conn.ExecuteReaderAsync(_gapDetection, token);

            // If there is a row, this tells us the first sequence gap
            if (await reader.ReadAsync(token))
            {
                return(await reader.GetFieldValueAsync <long>(0, token));
            }

            // use the latest sequence in the event table
            await reader.NextResultAsync(token);

            if (!await reader.ReadAsync(token))
            {
                return(statistics.CurrentMark);
            }

            if (!(await reader.IsDBNullAsync(0, token)))
            {
                return(await reader.GetFieldValueAsync <long>(0, token));
            }

            // This happens when the agent is restarted with persisted
            // state, and has no previous current mark.
            if (statistics.CurrentMark == 0 && statistics.LastMark > 0)
            {
                return(statistics.LastMark);
            }

            return(statistics.CurrentMark);
        }
Пример #11
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }

            if (this.managedConnection != null)
            {
                try
                {
                    if (disposing)
                    {
                        this.managedConnection.Close();
                    }
                    this.managedConnection = null;
                }
                catch (Exception)
                {
                }
            }
        }
Пример #12
0
 internal static T?LoadOne <T>(this IManagedConnection connection, NpgsqlCommand command, ISelector <T> selector)
 {
     using (var reader = connection.ExecuteReader(command))
     {
         if (!reader.Read())
         {
             return(default);
Пример #13
0
 /// <summary>
 /// Creates and runs an ALTER TABLE SQL statement to drop the given column from the table
 /// </summary>
 /// <param name="column">The column to drop</param>
 public void DropColumn(DiscoveredColumn column)
 {
     using (IManagedConnection connection = Database.Server.GetManagedConnection())
     {
         Helper.DropColumn(connection.Connection, column);
     }
 }
Пример #14
0
 public BatchedQuery(DocumentStore store, IManagedConnection runner, IIdentityMap identityMap, QuerySession parent)
 {
     _store       = store;
     _runner      = runner;
     _identityMap = identityMap;
     _parent      = parent;
 }
Пример #15
0
        private string[] ListPrimaryKeys(IManagedConnection con, DiscoveredTable table)
        {
            List <string> toReturn = new List <string>();

            string query = String.Format(@"SELECT i.name AS IndexName, 
OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName, 
c.is_identity
FROM sys.indexes AS i 
INNER JOIN sys.index_columns AS ic 
INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id 
ON i.OBJECT_ID = ic.OBJECT_ID 
AND i.index_id = ic.index_id 
WHERE (i.is_primary_key = 1) AND ic.OBJECT_ID = OBJECT_ID('{0}')
ORDER BY OBJECT_NAME(ic.OBJECT_ID), ic.key_ordinal", GetObjectName(table));

            using (DbCommand cmd = table.GetCommand(query, con.Connection))
            {
                cmd.Transaction = con.Transaction;
                using (DbDataReader r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        toReturn.Add((string)r["ColumnName"]);
                    }

                    r.Close();
                }
            }


            return(toReturn.ToArray());
        }
Пример #16
0
        public IManagedConnection GetConnection()
        {
            //any existing ongoing connection found on this Thread
            IManagedConnection  ongoingConnection  = null;
            IManagedTransaction ongoingTransaction = null;

            GetOngoingActivitiesFromThreadsDictionary(out ongoingConnection, out ongoingTransaction);

            //if we are in the middle of doing stuff we can just reuse the ongoing one
            if (ongoingConnection != null && ongoingConnection.Connection.State == ConnectionState.Open)//as long as it hasn't timed out or been disposed etc
            {
                if (ongoingConnection.CloseOnDispose)
                {
                    var clone = ongoingConnection.Clone();
                    clone.CloseOnDispose = false;
                    return(clone);
                }
                else
                {
                    return(ongoingConnection);
                }
            }

            ongoingConnection = DiscoveredServer.GetManagedConnection(ongoingTransaction);

            //record as the active connection on this thread
            ongoingConnections[Thread.CurrentThread] = ongoingConnection;

            return(ongoingConnection);
        }
Пример #17
0
 public void AddConnection(IManagedConnection connection)
 {
     if (!_connectionReferences.TryAdd(connection.Id, new ConnectionReference(connection)))
     {
         throw new ArgumentException(nameof(connection));
     }
 }
Пример #18
0
        public void RemoveSchemaObjects(IManagedConnection connection)
        {
            var signature = allArgs().Select(x => "JSONB").Join(", ");
            var dropSql   = $"DROP FUNCTION IF EXISTS {Function.QualifiedName}({signature})";

            connection.Execute(cmd => cmd.Sql(dropSql).ExecuteNonQuery());
        }
Пример #19
0
        /// <summary>
        /// Get a SMO Server object that is connected to the connection
        /// </summary>
        /// <param name="ci">Conenction info</param>
        /// <returns>Smo Server object for the connection</returns>
        public static Microsoft.SqlServer.Management.Smo.Server GetSmoServer(IManagedConnection mc)
        {
            SqlOlapConnectionInfoBase ci = mc.Connection;

            if (ci == null)
            {
                throw new ArgumentNullException("ci");
            }

            SMO.Server server = null;

            // see what type of connection we have been passed
            SqlConnectionInfoWithConnection ciWithCon = ci as SqlConnectionInfoWithConnection;

            if (ciWithCon != null)
            {
                server = new SMO.Server(ciWithCon.ServerConnection);
            }
            else
            {
                SqlConnectionInfo sqlCi = ci as SqlConnectionInfo;
                if (sqlCi != null)
                {
                    server = new SMO.Server(new ServerConnection(sqlCi));
                }
            }

            if (server == null)
            {
                throw new InvalidOperationException();
            }
            return(server);
        }
Пример #20
0
        private void GetOngoingActivitiesFromThreadsDictionary(out IManagedConnection ongoingConnection, out IManagedTransaction ongoingTransaction)
        {
            lock (ongoingConnectionsLock)
            {
                //see if Thread dictionary has it
                if (ongoingConnections.ContainsKey(Thread.CurrentThread))
                {
                    ongoingConnection = ongoingConnections[Thread.CurrentThread];
                }
                else
                {
                    ongoingConnections.Add(Thread.CurrentThread, null);
                    ongoingConnection = null;
                }


                //see if Thread dictionary has it
                if (ongoingTransactions.ContainsKey(Thread.CurrentThread))
                {
                    ongoingTransaction = ongoingTransactions[Thread.CurrentThread];
                }
                else
                {
                    ongoingTransactions.Add(Thread.CurrentThread, null);
                    ongoingTransaction = null;
                }
            }
        }
Пример #21
0
 public MartenQueryExecutor(IManagedConnection runner, DocumentStore store, IIdentityMap identityMap, ITenant tenant)
 {
     IdentityMap = identityMap;
     Tenant      = tenant;
     Connection  = runner;
     Store       = store;
 }
Пример #22
0
        public QuerySession(DocumentStore store, SessionOptions sessionOptions, IManagedConnection database,
                            ITenant tenant)
        {
            DocumentStore = store;

            SessionOptions = sessionOptions;

            Listeners.AddRange(store.Options.Listeners);
            if (sessionOptions != null)
            {
                if (sessionOptions.Timeout.HasValue && sessionOptions.Timeout.Value < 0)
                {
                    throw new ArgumentOutOfRangeException("CommandTimeout can't be less than zero");
                }

                Listeners.AddRange(sessionOptions.Listeners);
            }

            _providers = tenant.Providers ?? throw new ArgumentNullException(nameof(ITenant.Providers));

            Database   = database;
            Serializer = store.Serializer;
            Tenant     = tenant;
            Options    = store.Options;
        }
Пример #23
0
        /// <include file='../../CommonMethods.doc.xml' path='Methods/Method[@name="GetCommand"]'/>
        public DbCommand GetCommand(string sql, IManagedConnection managedConnection)
        {
            var cmd = Helper.GetCommand(sql, managedConnection.Connection);

            cmd.Transaction = managedConnection.Transaction;
            return(cmd);
        }
Пример #24
0
 public EventStore(IManagedConnection connection, IDocumentSchema schema, ISerializer serializer, IDocumentSchemaCreation creation)
 {
     _connection = connection;
     _schema     = schema;
     _serializer = serializer;
     _creation   = creation;
 }
Пример #25
0
        /// <summary>
        /// Creates a new object for bulk inserting records into the table.  You should use a using block since <see cref="IBulkCopy"/> is <see cref="IDisposable"/>.
        /// Depending on implementation, records may not be committed to the server until the <see cref="IBulkCopy"/> is disposed.
        /// </summary>
        /// <param name="transaction">Optional - records inserted should form part of the supplied ongoing transaction</param>
        /// <returns></returns>
        public IBulkCopy BeginBulkInsert(CultureInfo culture, IManagedTransaction transaction = null)
        {
            Database.Server.EnableAsync();
            IManagedConnection connection = Database.Server.GetManagedConnection(transaction);

            return(Helper.BeginBulkInsert(this, connection, culture));
        }
Пример #26
0
 public MicrosoftSQLBulkCopy(DiscoveredTable targetTable, IManagedConnection connection, CultureInfo culture) : base(targetTable, connection, culture)
 {
     _bulkcopy = new SqlBulkCopy((SqlConnection)connection.Connection, SqlBulkCopyOptions.KeepIdentity, (SqlTransaction)connection.Transaction)
     {
         BulkCopyTimeout      = 50000,
         DestinationTableName = targetTable.GetFullyQualifiedName()
     };
 }
Пример #27
0
        public void RemoveSchemaObjects(IManagedConnection connection)
        {
            _hasCheckedSchema = false;

            connection.Execute($"DROP TABLE IF EXISTS {_mapping.Table} CASCADE;");

            RemoveUpsertFunction(connection);
        }
Пример #28
0
        /// <summary>
        ///     Only for testing scenarios
        /// </summary>
        /// <param name="connection"></param>
        public void RemoveUpsertFunction(IManagedConnection connection)
        {
            var dropTargets = DocumentCleaner.DropFunctionSql.ToFormat(_mapping.UpsertFunction.Name, _mapping.UpsertFunction.Schema);

            var drops = connection.GetStringList(dropTargets);

            drops.Each(drop => connection.Execute(drop));
        }
Пример #29
0
        public UpdateBatch(StoreOptions options, ISerializer serializer, IManagedConnection connection)
        {
            _options = options;
            _serializer = serializer;

            _commands.Push(new BatchCommand(serializer));
            Connection = connection;
        }
Пример #30
0
 public QuerySession(IDocumentSchema schema, ISerializer serializer, IManagedConnection connection, IQueryParser parser, IIdentityMap identityMap)
 {
     _schema      = schema;
     _serializer  = serializer;
     _connection  = connection;
     _parser      = parser;
     _identityMap = identityMap;
 }
Пример #31
0
 /// <summary>
 /// Issues a database command to rename the table on the database server.
 /// </summary>
 /// <param name="newName"></param>
 public void Rename(string newName)
 {
     using (IManagedConnection connection = Database.Server.GetManagedConnection())
     {
         Helper.RenameTable(this, newName, connection);
         _table = newName;
     }
 }
Пример #32
0
        public UpdateBatch(StoreOptions options, ISerializer serializer, IManagedConnection connection, VersionTracker versions)
        {
            if (versions == null) throw new ArgumentNullException(nameof(versions));

            _options = options;
            _serializer = serializer;
            Versions = versions;

            _commands.Push(new BatchCommand(serializer));
            Connection = connection;
        }
Пример #33
0
 public void RemoveSchemaObjects(IManagedConnection connection)
 {
 }
Пример #34
0
 public void RemoveSchemaObjects(IManagedConnection connection)
 {
     connection.Execute(cmd => cmd.Sql(_dropSql).ExecuteNonQuery());
 }
Пример #35
0
 public void RemoveSchemaObjects(IManagedConnection connection)
 {
     var signature = allArgs().Select(x => "JSONB").Join(", ");
     var dropSql = $"DROP FUNCTION IF EXISTS {Function.QualifiedName}({signature})";
     connection.Execute(cmd => cmd.Sql(dropSql).ExecuteNonQuery());
 }
Пример #36
0
 public void RemoveSchemaObjects(IManagedConnection connection)
 {
     var sql = "drop table if exists " + Table.QualifiedName;
     connection.Execute(cmd => cmd.Sql(sql).ExecuteNonQuery());
 }
        public void RemoveSchemaObjects(IManagedConnection connection)
        {
            var sql = $"drop table if exists {_parent.DatabaseSchemaName}.mt_streams cascade;drop table if exists {_parent.DatabaseSchemaName}.mt_events cascade;";

            connection.Execute(cmd => cmd.Sql(sql).ExecuteNonQuery());
        }