Exemplo n.º 1
0
 public TableOptions GenerateDiferences(TableOptions CamposOrigen, TableOptions CamposDestino)
 {
     foreach (TableOption node in CamposDestino)
     {
         if (!CamposOrigen.Find(node.Name))
         {
             node.Status = Database.ObjectStatusType.CreateStatus;
             //Si el estado de la tabla era el original, lo cambia, sino deja el actual estado.
             if (CamposOrigen.Parent.Status == Database.ObjectStatusType.OriginalStatus)
                 CamposOrigen.Parent.Status = Database.ObjectStatusType.AlterStatus;
             CamposOrigen.Add(node);
         }
     }
     foreach (TableOption node in CamposOrigen)
     {
         if (!CamposDestino.Find(node.Name))
         {
             node.Status = Database.ObjectStatusType.DropStatus;
             //Si el estado de la tabla era el original, lo cambia, sino deja el actual estado.
             if (CamposOrigen.Parent.Status == Database.ObjectStatusType.OriginalStatus)
                 CamposOrigen.Parent.Status = Database.ObjectStatusType.AlterStatus;
         }
     }
     return CamposOrigen;
 }
Exemplo n.º 2
0
 public override StringBuilder BuildObjectName(StringBuilder sb, SqlObjectName name, ConvertType objectType, bool escape, TableOptions tableOptions)
 {
     return(escape ? Convert(sb, name.Name, objectType) : sb.Append(name.Name));
 }
Exemplo n.º 3
0
 public static TempTable <T> CreateLocalTable <T>(this IDataContext db, string?tableName = null, TableOptions tableOptions = TableOptions.NotSet)
 {
     try
     {
         return(CreateTable <T>(db, tableName, tableOptions));
     }
     catch
     {
         ClearDataContext(db);
         db.DropTable <T>(tableName, throwExceptionIfNotExists: false);
         return(CreateTable <T>(db, tableName, tableOptions));
     }
 }
Exemplo n.º 4
0
 public FirebirdTempTable(IDataContext db, string?tableName = null, string?databaseName = null, string?schemaName = null, TableOptions tableOptions = TableOptions.NotSet)
     : base(db, tableName, databaseName, schemaName, tableOptions: tableOptions)
 {
 }
Exemplo n.º 5
0
        public override StringBuilder BuildTableName(StringBuilder sb, string?server, string?database, string?schema, string table, TableOptions tableOptions)
        {
            if (database != null && database.Length == 0)
            {
                database = null;
            }
            if (schema != null && schema.Length == 0)
            {
                schema = null;
            }

            // "db..table" syntax not supported and postgresql doesn't support database name, if it is not current database
            // so we can clear database name to avoid error from server
            if (database != null && schema == null)
            {
                database = null;
            }

            return(base.BuildTableName(sb, null, database, schema, table, tableOptions));
        }
 public DescribeTableResponse(TableMeta tableMeta, ReservedThroughputDetails reservedThroughputDetails, TableOptions tableOptions)
 {
     TableMeta = tableMeta;
     ReservedThroughputDetails = reservedThroughputDetails;
     TableOptions = tableOptions;
 }
Exemplo n.º 7
0
        public void checkPureMetadata(string TableName = null, string KeyspaceName = null, TableOptions tableOptions = null)
        {
            Dictionary <string, ColumnTypeCode> columns = new Dictionary
                                                          <string, ColumnTypeCode>()
            {
                { "q0uuid", ColumnTypeCode.Uuid },
                { "q1timestamp", ColumnTypeCode.Timestamp },
                { "q2double", ColumnTypeCode.Double },
                { "q3int32", ColumnTypeCode.Int },
                { "q4int64", ColumnTypeCode.Bigint },
                { "q5float", ColumnTypeCode.Float },
                { "q6inet", ColumnTypeCode.Inet },
                { "q7boolean", ColumnTypeCode.Boolean },
                { "q8inet", ColumnTypeCode.Inet },
                { "q9blob", ColumnTypeCode.Blob },
                { "q10varint", ColumnTypeCode.Varint },
                { "q11decimal", ColumnTypeCode.Decimal },
                { "q12list", ColumnTypeCode.List },
                { "q13set", ColumnTypeCode.Set },
                { "q14map", ColumnTypeCode.Map }
                //{"q12counter", Metadata.ColumnTypeCode.Counter}, A table that contains a counter can only contain counters
            };

            string        tablename = TableName ?? "table" + Guid.NewGuid().ToString("N");
            StringBuilder sb        = new StringBuilder(@"CREATE TABLE " + tablename + " (");

            foreach (var col in columns)
            {
                sb.Append(col.Key + " " + col.Value.ToString() +
                          (((col.Value == ColumnTypeCode.List) ||
                            (col.Value == ColumnTypeCode.Set) ||
                            (col.Value == ColumnTypeCode.Map))
                               ? "<int" + (col.Value == ColumnTypeCode.Map ? ",varchar>" : ">")
                               : "") + ", ");
            }

            sb.Append("PRIMARY KEY(");
            int rowKeys = Randomm.Instance.Next(1, columns.Count - 3);

            for (int i = 0; i < rowKeys; i++)
            {
                sb.Append(columns.Keys.Where(key => key.StartsWith("q" + i.ToString())).First() +
                          ((i == rowKeys - 1) ? "" : ", "));
            }
            var opt = tableOptions != null ? " WITH " + tableOptions.ToString() : "";

            sb.Append("))" + opt + ";");

            Session.WaitForSchemaAgreement(
                QueryTools.ExecuteSyncNonQuery(Session, sb.ToString())

                );

            var table = this.Cluster.Metadata.GetTable(KeyspaceName ?? Keyspace, tablename);

            foreach (var metaCol in table.TableColumns)
            {
                Assert.True(columns.Keys.Contains(metaCol.Name));
                Assert.True(metaCol.TypeCode ==
                            columns.Where(tpc => tpc.Key == metaCol.Name).First().Value);
                Assert.True(metaCol.Table == tablename);
                Assert.True(metaCol.Keyspace == (KeyspaceName ?? Keyspace));
            }
            if (tableOptions != null)
            {
                Assert.True(tableOptions.Equals(table.Options));
            }
        }
Exemplo n.º 8
0
        private void SetOptions(JSONNode optionsNode)
        {
            List<Option> options = new List<Option>(optionsNode.Count);
            Dictionary<string, List<object>> tableOptions = new Dictionary<string, List<object>>();
            IEnumerable<JSONNode> optionsEnumerable = optionsNode.Childs;
            IEnumerator<JSONNode> optionsEnumerator = optionsEnumerable.GetEnumerator();
            while (optionsEnumerator.MoveNext())
            {
                JSONNode optionNode = optionsEnumerator.Current;
                options.Add(new Option(optionNode["value"], optionNode["label"]));
            }

            if (GetElementType() == XsollaFormElement.TYPE_TABLE)
            {
                this.tableOptions = new TableOptions();
                this.tableOptions.Parse(optionsNode);
            }
            this.options = options;
        }
Exemplo n.º 9
0
        public override StringBuilder BuildObjectName(StringBuilder sb, SqlObjectName name, ConvertType objectType, bool escape, TableOptions tableOptions)
        {
            var databaseName = name.Database;

            // remove database name, which could be inherited from non-temporary table mapping
            // except explicit use of tempdb, needed in some cases at least for sql server 2014
            if ((name.Name.StartsWith("#") || tableOptions.IsTemporaryOptionSet()) && databaseName != "tempdb")
            {
                databaseName = "tempdb";
            }

            if (name.Server != null && (databaseName == null || name.Schema == null))
            {
                // all components required for linked-server syntax by SQL server
                throw new LinqToDBException("You must specify both schema and database names explicitly for linked server query");
            }

            if (name.Server != null)
            {
                (escape ? Convert(sb, name.Server, ConvertType.NameToServer) : sb.Append(name.Server))
                .Append('.');
            }

            if (databaseName != null)
            {
                (escape ? Convert(sb, databaseName, ConvertType.NameToDatabase) : sb.Append(databaseName))
                .Append('.');
            }

            if (name.Schema != null)
            {
                (escape ? Convert(sb, name.Schema, ConvertType.NameToSchema) : sb.Append(name.Schema)).Append('.');
            }
            else if (databaseName != null)
            {
                sb.Append('.');
            }

            var tableName = GetTablePhysicalName(name.Name, tableOptions);

            return(escape ? Convert(sb, tableName, objectType) : sb.Append(tableName));
        }
 public RethinkDbTriggerBinding(ParameterInfo parameter, Task <IConnection> rethinkDbConnectionTask, TableOptions rethinkDbTableOptions, bool includeTypes)
 {
     _parameter = parameter;
     _rethinkDbConnectionTask = rethinkDbConnectionTask;
     _rethinkDbTableOptions   = rethinkDbTableOptions;
     _rethinkDbTable          = Driver.RethinkDB.R.Db(_rethinkDbTableOptions.DatabaseName).Table(_rethinkDbTableOptions.TableName);
     _includeTypes            = includeTypes;
 }
Exemplo n.º 11
0
        private void CheckMetadata(string tableName = null, string keyspaceName = null, TableOptions tableOptions = null)
        {
            var clusterInfo = TestUtils.CcmSetup(2);

            try
            {
                Session = clusterInfo.Session;
                Cluster = clusterInfo.Cluster;
                Session.CreateKeyspaceIfNotExists(Keyspace);
                Session.ChangeKeyspace(Keyspace);

                CheckPureMetadata(tableName, keyspaceName, tableOptions);
            }
            finally
            {
                TestUtils.CcmRemove(clusterInfo);
            }
        }
Exemplo n.º 12
0
        public override StringBuilder BuildObjectName(StringBuilder sb, SqlObjectName name, ConvertType objectType, bool escape, TableOptions tableOptions)
        {
            if (name.Database != null)
            {
                (escape ? Convert(sb, name.Database, ConvertType.NameToDatabase) : sb.Append(name.Database))
                .Append('.');
            }

            return(escape ? Convert(sb, name.Name, objectType) : sb.Append(name.Name));
        }
Exemplo n.º 13
0
 /// <summary>
 /// Returns a query result in a table format, synchronously only, with TABLE output format.
 /// </summary>
 /// <param name="filename">File or table name defined in Linkar Schemas. Table notation is: MainTable[.MVTable[.SVTable]]</param>
 /// <param name="selectClause">Statement fragment specifies the selection condition. For example WITH CUSTOMER = '1'</param>
 /// <param name="dictClause">Space-delimited list of dictionaries to read. If this list is not set, all fields are returned. For example CUSTOMER DATE ITEM. In NONE mode you may use the format LKFLDx where x is the attribute number.</param>
 /// <param name="sortClause">Statement fragment specifies the selection order. If there is a selection rule Linkar will execute a SSELECT, otherwise Linkar will execute a SELECT. For example BY CUSTOMER</param>
 /// <param name="tableOptions">Detailed options to be used, including: rowHeaders, rowProperties, onlyVisibe, usePropertyNames, repeatValues, applyConversion, applyFormat, calculated, pagination, regPage, numPage.</param>
 /// <param name="customVars">Free text sent to the database allows management of additional behaviours in SUB.LK.MAIN.CONTROL.CUSTOM, which is called when this parameter is set.</param>
 /// <param name="receiveTimeout">Maximum time in seconds that the client will wait for a response from the server. Default = 0 to wait indefinitely.</param>
 /// <returns>The results of the operation.</returns>
 /// <example>
 /// <code lang="CS">
 /// using Linkar;
 /// using Linkar.Functions.Persistent.TABLE;
 ///
 /// class Test
 ///     {
 ///         public string MyGetTable()
 ///         {
 ///             string result = "";
 ///             try
 ///             {
 ///                 CredentialOptions credentials = new CredentialOptions("127.0.0.1", "EPNAME", 11300, "admin", "admin");
 ///                 LinkarClient client = new LinkarClient();
 ///                 client.Login(credentials);
 ///                 TableOptions options = new TableOptions(RowHeaders.TYPE.MAINLABEL, false, false, false, false, false, false, false);
 ///                 result = client.GetTable("LK.CUSTOMERS", options);
 ///                 client.Logout();
 ///             }
 ///             catch (Exception ex)
 ///             {
 ///                 string error = ex.Message;
 ///                 // Do something
 ///             }
 ///             return result;
 ///         }
 ///     }
 /// </code>
 /// <code lang="VB">
 /// Imports Linkar
 /// Imports Linkar.Functions.Persistent.TABLE
 ///
 /// Class Test
 ///
 ///     Public Function MyGetTable() As String
 ///         Dim result As String = ""
 ///
 ///         Try
 ///             Dim credentials As CredentialOptions = New CredentialOptions("127.0.0.1", "EPNAME", 11300, "admin", "admin")
 ///
 ///             Dim client As LinkarClient = New LinkarClient()
 ///
 ///             client.Login(credentials)
 ///             Dim options As TableOptions = New TableOptions(RowHeaders.TYPE.MAINLABEL, False, False, False, False, False, False, False);
 ///         result = client.GetTable("LK.CUSTOMERS",options)
 ///             client.Logout()
 ///         Catch ex As Exception
 ///             Dim[error] As String = ex.Message
 ///             ' Do something
 ///
 ///         End Try
 ///
 ///         Return result
 ///   End Function
 /// End Class
 /// </code>
 /// </example>
 /// <remarks>
 /// TABLE output format uses the defined control characters in <see href="http://kosday.com/Manuals/en_web_linkar/lk_schemas_ep_parameters.html">EntryPoints Parameters</see> Table Row Separator and Column Row Separator.
 /// <para>By default:
 /// <list type="bullet">
 /// <item>TAB char (9) for columns.</item>
 /// <item>VT char (11) for rows.</item>
 /// </list>
 /// </para>
 /// </remarks>
 public string GetTable(string filename, string selectClause = "", string dictClause = "", string sortClause = "", TableOptions tableOptions = null, string customVars = "", int receiveTimeout = 0)
 {
     return(this._LinkarClt.GetTable(filename, selectClause, dictClause, sortClause, tableOptions, customVars, receiveTimeout));
 }
Exemplo n.º 14
0
        public MarkdownFormat(
            EmphasisStyle boldStyle           = EmphasisStyle.Asterisk,
            EmphasisStyle italicStyle         = EmphasisStyle.Asterisk,
            BulletListStyle bulletListStyle   = BulletListStyle.Asterisk,
            OrderedListStyle orderedListStyle = OrderedListStyle.Dot,
            HeadingStyle headingStyle         = HeadingStyle.NumberSign,
            HeadingOptions headingOptions     = HeadingOptions.EmptyLineBeforeAndAfter,
            TableOptions tableOptions         = TableOptions.FormatHeader
            | TableOptions.OuterDelimiter
            | TableOptions.Padding
            | TableOptions.EmptyLineBeforeAndAfter,
            CodeFenceStyle codeFenceStyle                   = CodeFenceStyle.Backtick,
            CodeBlockOptions codeBlockOptions               = CodeBlockOptions.EmptyLineBeforeAndAfter,
            CharEntityFormat charEntityFormat               = CharEntityFormat.Hexadecimal,
            HorizontalRuleFormat?horizontalRuleFormat       = null,
            AngleBracketEscapeStyle angleBracketEscapeStyle = AngleBracketEscapeStyle.Backslash)
        {
            BoldStyle        = boldStyle;
            ItalicStyle      = italicStyle;
            BulletListStyle  = bulletListStyle;
            OrderedListStyle = orderedListStyle;
            HeadingStyle     = headingStyle;
            HeadingOptions   = headingOptions;
            TableOptions     = tableOptions;
            CodeFenceStyle   = codeFenceStyle;
            CodeBlockOptions = codeBlockOptions;
            CharEntityFormat = charEntityFormat;

            if (BulletListStyle == BulletListStyle.Asterisk)
            {
                BulletItemStart = "* ";
            }
            else if (BulletListStyle == BulletListStyle.Plus)
            {
                BulletItemStart = "+ ";
            }
            else if (BulletListStyle == BulletListStyle.Minus)
            {
                BulletItemStart = "- ";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(BulletListStyle));
            }

            if (BoldStyle == EmphasisStyle.Asterisk)
            {
                BoldDelimiter = "**";
            }
            else if (BoldStyle == EmphasisStyle.Underscore)
            {
                BoldDelimiter = "__";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(BoldStyle));
            }

            if (ItalicStyle == EmphasisStyle.Asterisk)
            {
                ItalicDelimiter = "*";
            }
            else if (ItalicStyle == EmphasisStyle.Underscore)
            {
                ItalicDelimiter = "_";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(ItalicStyle));
            }

            if (OrderedListStyle == OrderedListStyle.Dot)
            {
                OrderedItemStart = ". ";
            }
            else if (OrderedListStyle == OrderedListStyle.Parenthesis)
            {
                OrderedItemStart = ") ";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(OrderedListStyle));
            }

            if (HeadingStyle == HeadingStyle.NumberSign)
            {
                HeadingStart = "#";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(HeadingStyle));
            }

            if (CodeFenceStyle == CodeFenceStyle.Backtick)
            {
                CodeFence = "```";
            }
            else if (CodeFenceStyle == CodeFenceStyle.Tilde)
            {
                CodeFence = "~~~";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(CodeFenceStyle));
            }

            if (horizontalRuleFormat != null)
            {
                Error.ThrowOnInvalidHorizontalRuleFormat(horizontalRuleFormat.Value);

                HorizontalRuleFormat = horizontalRuleFormat.Value;
            }
            else
            {
                HorizontalRuleFormat = HorizontalRuleFormat.Default;
            }

            if (HorizontalRuleStyle == HorizontalRuleStyle.Hyphen)
            {
                HorizontalRuleText = "-";
            }
            else if (HorizontalRuleStyle == HorizontalRuleStyle.Underscore)
            {
                HorizontalRuleText = "_";
            }
            else if (HorizontalRuleStyle == HorizontalRuleStyle.Asterisk)
            {
                HorizontalRuleText = "*";
            }
            else
            {
                throw new InvalidOperationException(ErrorMessages.UnknownEnumValue(HorizontalRuleStyle));
            }

            AngleBracketEscapeStyle = angleBracketEscapeStyle;
        }
Exemplo n.º 15
0
            static Query <int> CreateQuery(
                IDataContext dataContext,
                string?tableName,
                string?serverName,
                string?databaseName,
                string?schemaName,
                TableOptions tableOptions,
                Type type)
            {
                var sqlTable = new SqlTable(dataContext.MappingSchema, type);

                if (tableName != null)
                {
                    sqlTable.PhysicalName = tableName;
                }
                if (serverName != null)
                {
                    sqlTable.Server = serverName;
                }
                if (databaseName != null)
                {
                    sqlTable.Database = databaseName;
                }
                if (schemaName != null)
                {
                    sqlTable.Schema = schemaName;
                }
                if (tableOptions.IsSet())
                {
                    sqlTable.TableOptions = tableOptions;
                }

                var deleteStatement = new SqlDeleteStatement();

                deleteStatement.SelectQuery.From.Table(sqlTable);

                var ei = new Query <int>(dataContext, null)
                {
                    Queries = { new QueryInfo {
                                    Statement = deleteStatement,
                                } }
                };

                var keys = sqlTable.GetKeys(true).Cast <SqlField>().ToList();

                if (keys.Count == 0)
                {
                    throw new LinqException($"Table '{sqlTable.Name}' does not have primary key.");
                }

                foreach (var field in keys)
                {
                    var param = GetParameter(type, dataContext, field);

                    ei.Queries[0].Parameters.Add(param);

                    deleteStatement.SelectQuery.Where.Field(field).Equal.Expr(param.SqlParameter);

                    if (field.CanBeNull)
                    {
                        deleteStatement.IsParameterDependent = true;
                    }
                }

                SetNonQueryQuery(ei);

                return(ei);
            }
Exemplo n.º 16
0
        private void CheckPureMetadata(Cluster cluster, ISession session, string tableName, string keyspaceName, TableOptions tableOptions = null)
        {
            // build create table cql
            tableName = TestUtils.GetUniqueTableName().ToLower();
            var columns = new Dictionary
                <string, ColumnTypeCode>
            {
                {"q0uuid", ColumnTypeCode.Uuid},
                {"q1timestamp", ColumnTypeCode.Timestamp},
                {"q2double", ColumnTypeCode.Double},
                {"q3int32", ColumnTypeCode.Int},
                {"q4int64", ColumnTypeCode.Bigint},
                {"q5float", ColumnTypeCode.Float},
                {"q6inet", ColumnTypeCode.Inet},
                {"q7boolean", ColumnTypeCode.Boolean},
                {"q8inet", ColumnTypeCode.Inet},
                {"q9blob", ColumnTypeCode.Blob},
                {"q10varint", ColumnTypeCode.Varint},
                {"q11decimal", ColumnTypeCode.Decimal},
                {"q12list", ColumnTypeCode.List},
                {"q13set", ColumnTypeCode.Set},
                {"q14map", ColumnTypeCode.Map}
                //{"q12counter", Metadata.ColumnTypeCode.Counter}, A table that contains a counter can only contain counters
            };

            var stringBuilder = new StringBuilder(@"CREATE TABLE " + tableName + " (");

            foreach (KeyValuePair<string, ColumnTypeCode> col in columns)
                stringBuilder.Append(col.Key + " " + col.Value +
                          (((col.Value == ColumnTypeCode.List) ||
                            (col.Value == ColumnTypeCode.Set) ||
                            (col.Value == ColumnTypeCode.Map))
                              ? "<int" + (col.Value == ColumnTypeCode.Map ? ",varchar>" : ">")
                              : "") + ", ");

            stringBuilder.Append("PRIMARY KEY(");
            int rowKeys = Randomm.Instance.Next(1, columns.Count - 3);
            for (int i = 0; i < rowKeys; i++)
                stringBuilder.Append(columns.Keys.First(key => key.StartsWith("q" + i.ToString(CultureInfo.InvariantCulture))) + ((i == rowKeys - 1) ? "" : ", "));
            string opt = tableOptions != null ? " WITH " + tableOptions : "";
            stringBuilder.Append("))" + opt + ";");

            QueryTools.ExecuteSyncNonQuery(session, stringBuilder.ToString());
            TestUtils.WaitForSchemaAgreement(session.Cluster);

            var table = cluster.Metadata.GetTable(keyspaceName, tableName);
            Assert.AreEqual(tableName, table.Name);
            foreach (var metaCol in table.TableColumns)
            {
                Assert.True(columns.Keys.Contains(metaCol.Name));
                Assert.True(metaCol.TypeCode == columns.First(tpc => tpc.Key == metaCol.Name).Value);
                Assert.True(metaCol.Table == tableName);
                Assert.True(metaCol.Keyspace == (keyspaceName));
            }

            if (tableOptions != null)
            {
                Assert.AreEqual(tableOptions.Comment, table.Options.Comment);
                Assert.AreEqual(tableOptions.ReadRepairChance, table.Options.ReadRepairChance);
                Assert.AreEqual(tableOptions.LocalReadRepairChance, table.Options.LocalReadRepairChance);
                Assert.AreEqual(tableOptions.ReplicateOnWrite, table.Options.replicateOnWrite);
                Assert.AreEqual(tableOptions.GcGraceSeconds, table.Options.GcGraceSeconds);
                Assert.AreEqual(tableOptions.bfFpChance, table.Options.bfFpChance);
                if (tableOptions.Caching == "ALL")
                {
                    //The string returned can be more complete than the provided
                    Assert.That(table.Options.Caching == "ALL" || table.Options.Caching.Contains("ALL"), "Caching returned does not match");
                }
                else
                {
                    Assert.AreEqual(tableOptions.Caching, table.Options.Caching);
                }
                Assert.AreEqual(tableOptions.CompactionOptions, table.Options.CompactionOptions);
                Assert.AreEqual(tableOptions.CompressionParams, table.Options.CompressionParams);
            }
        }
Exemplo n.º 17
0
 public Table(TableOptions options)
 {
     Options = options ?? throw new ArgumentNullException("options");
     Rows    = new List <object[]>();
     Columns = new List <object>(options.Columns);
 }
Exemplo n.º 18
0
        public void checkMetadata(string TableName = null, string KeyspaceName = null, TableOptions tableOptions = null)
        {
            CCMCluster = CCMBridge.CCMCluster.Create(2, Cluster.Builder());
            try
            {
                Session = CCMCluster.Session;
                Cluster = CCMCluster.Cluster;
                Session.CreateKeyspaceIfNotExists(Keyspace);
                Session.ChangeKeyspace(Keyspace);

                checkPureMetadata(TableName, KeyspaceName, tableOptions);
            }
            finally
            {
                CCMCluster.Discard();
            }
        }
        /// <summary>
        /// Returns a query result in a table format, synchronously only, with TABLE output format.
        /// </summary>
        /// <param name="filename">File or table name defined in Linkar Schemas. Table notation is: MainTable[.MVTable[.SVTable]]</param>
        /// <param name="selectClause">Statement fragment specifies the selection condition. For example WITH CUSTOMER = '1'</param>
        /// <param name="dictClause">Space-delimited list of dictionaries to read. If this list is not set, all fields are returned. For example CUSTOMER DATE ITEM. In NONE mode you may use the format LKFLDx where x is the attribute number.</param>
        /// <param name="sortClause">Statement fragment specifies the selection order. If there is a selection rule Linkar will execute a SSELECT, otherwise Linkar will execute a SELECT. For example BY CUSTOMER</param>
        /// <param name="tableOptions">Detailed options to be used, including: rowHeaders, rowProperties, onlyVisibe, usePropertyNames, repeatValues, applyConversion, applyFormat, calculated, pagination, regPage, numPage.</param>
        /// <param name="customVars">Free text sent to the database allows management of additional behaviours in SUB.LK.MAIN.CONTROL.CUSTOM, which is called when this parameter is set.</param>
        /// <param name="receiveTimeout">Maximum time in seconds that the client will wait for a response from the server. Default = 0 to wait indefinitely.</param>
        /// <returns>The results of the operation.</returns>
        /// <example>
        /// <code lang="CS">
        /// using Linkar;
        /// using Linkar.Functions.Persistent.TABLE;
        ///
        /// class Test
        ///     {
        ///         public string MyGetTable()
        ///         {
        ///             string result = "";
        ///             try
        ///             {
        ///                 CredentialOptions credentials = new CredentialOptions("127.0.0.1", "EPNAME", 11300, "admin", "admin");
        ///                 LinkarClient client = new LinkarClient();
        ///                 client.Login(credentials);
        ///                 TableOptions options = new TableOptions(RowHeaders.TYPE.MAINLABEL, false, false, false, false, false, false, false);
        ///                 result = client.GetTableAsync("LK.CUSTOMERS", options).Result;
        ///                 client.Logout();
        ///             }
        ///             catch (Exception ex)
        ///             {
        ///                 string error = ex.Message;
        ///                 // Do something
        ///             }
        ///             return result;
        ///         }
        ///     }
        /// </code>
        /// <code lang="VB">
        /// Imports Linkar
        /// Imports Linkar.Functions.Persistent.TABLE
        ///
        /// Class Test
        ///
        ///     Public Function MyGetTable() As String
        ///         Dim result As String = ""
        ///
        ///         Try
        ///             Dim credentials As CredentialOptions = New CredentialOptions("127.0.0.1", "EPNAME", 11300, "admin", "admin")
        ///
        ///             Dim client As LinkarClient = New LinkarClient()
        ///
        ///             client.Login(credentials)
        ///             Dim options As TableOptions = New TableOptions(RowHeaders.TYPE.MAINLABEL, False, False, False, False, False, False, False);
        ///         result = client.GetTableAsync("LK.CUSTOMERS",options).Result
        ///             client.Logout()
        ///         Catch ex As Exception
        ///             Dim[error] As String = ex.Message
        ///             ' Do something
        ///
        ///         End Try
        ///
        ///         Return result
        ///   End Function
        /// End Class
        /// </code>
        /// </example>
        /// <remarks>
        /// TABLE output format uses the defined control characters in <see href="http://kosday.com/Manuals/en_web_linkar/lk_schemas_ep_parameters.html">EntryPoints Parameters</see> Table Row Separator and Column Row Separator.
        /// <para>By default:
        /// <list type="bullet">
        /// <item>TAB char (9) for columns.</item>
        /// <item>VT char (11) for rows.</item>
        /// </list>
        /// </para>
        /// </remarks>
        public Task <string> GetTableAsync(string filename, string selectClause = "", string dictClause = "", string sortClause = "", TableOptions tableOptions = null, string customVars = "", int receiveTimeout = 0)
        {
            var task = new Task <string>(() =>
            {
                return(this.GetTable(filename, selectClause, dictClause, sortClause, tableOptions, customVars, receiveTimeout));
            });

            task.Start();
            return(task);
        }
Exemplo n.º 20
0
 public static TempTable <T> CreateLocalTable <T>(this IDataContext db, string?tableName = null, TableOptions tableOptions = TableOptions.NotSet)
     where T : notnull
 {
     try
     {
         if ((tableOptions & TableOptions.CheckExistence) == TableOptions.CheckExistence)
         {
             db.DropTable <T>(tableName, tableOptions: tableOptions);
         }
         return(CreateTable <T>(db, tableName, tableOptions));
     }
     catch
     {
         ClearDataContext(db);
         db.DropTable <T>(tableName, throwExceptionIfNotExists: false);
         return(CreateTable <T>(db, tableName, tableOptions));
     }
 }
            public static ITable <T> Query(
                IDataContext dataContext,
                string?tableName,
                string?serverName,
                string?databaseName,
                string?schemaName,
                string?statementHeader,
                string?statementFooter,
                DefaultNullable defaultNullable,
                TableOptions tableOptions)
            {
                var sqlTable    = new SqlTable <T>(dataContext.MappingSchema);
                var createTable = new SqlCreateTableStatement(sqlTable);

                if (tableName != null)
                {
                    sqlTable.PhysicalName = tableName;
                }
                if (serverName != null)
                {
                    sqlTable.Server = serverName;
                }
                if (databaseName != null)
                {
                    sqlTable.Database = databaseName;
                }
                if (schemaName != null)
                {
                    sqlTable.Schema = schemaName;
                }
                if (tableOptions.IsSet())
                {
                    sqlTable.TableOptions = tableOptions;
                }

                createTable.StatementHeader = statementHeader;
                createTable.StatementFooter = statementFooter;
                createTable.DefaultNullable = defaultNullable;

                var query = new Query <int>(dataContext, null)
                {
                    Queries = { new QueryInfo {
                                    Statement = createTable,
                                } }
                };

                SetNonQueryQuery(query);

                query.GetElement(dataContext, Expression.Constant(null), null, null);

                ITable <T> table = new Table <T>(dataContext);

                if (sqlTable.PhysicalName != null)
                {
                    table = table.TableName(sqlTable.PhysicalName);
                }
                if (sqlTable.Server != null)
                {
                    table = table.ServerName(sqlTable.Server);
                }
                if (sqlTable.Database != null)
                {
                    table = table.DatabaseName(sqlTable.Database);
                }
                if (sqlTable.Schema != null)
                {
                    table = table.SchemaName(sqlTable.Schema);
                }
                if (sqlTable.TableOptions.IsSet())
                {
                    table = table.TableOptions(sqlTable.TableOptions);
                }

                return(table);
            }
        public static EntityTypeBuilder ToTable(this EntityTypeBuilder entityTypeBuilder, TableOptions options, string defaultSchema)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var schema = string.IsNullOrWhiteSpace(options.Schema) ? defaultSchema : options.Schema;

            if (string.IsNullOrWhiteSpace(options.Name))
            {
                throw new Exception("Table name cannot be null or empty.");
            }

            if (string.IsNullOrWhiteSpace(schema))
            {
                entityTypeBuilder.ToTable(options.Name);
            }
            else
            {
                entityTypeBuilder.ToTable(options.Name, schema);
            }

            return(entityTypeBuilder);
        }
        /// <summary>
        /// Creates Update Replication Triggers based on rules table
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="file"></param>
        /// <param name="TableName"></param>
        /// <param name="TriggerName"></param>
        /// <param name="ExcludeFields"></param>
        private string ReplicateCreateTriggerUpdate(FbConnection conn, FbTransaction tran, bool generateOnly,
                                                    string tableName, string triggerName, string excludeFields, string localIDColumn, TableOptions options)
        {
            string Result = String.Empty;

            if (!excludeFields.EndsWith(":"))
            {
                excludeFields += ":";
            }

            int    i          = 0;
            string Indexes    = "";
            string updateHash = "NEW.REPLICATE$HASH = HASH(";
            string SQL        = String.Format("select rc.RDB$RELATION_NAME, ris.rdb$field_name from rdb$relation_constraints rc " +
                                              "join rdb$index_segments ris on ris.rdb$index_name = rc.rdb$index_name where rc.rdb$relation_name = '{0}' " +
                                              "and rc.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'", tableName);
            FbDataReader rdr = null;
            FbCommand    cmd = new FbCommand(SQL, conn, tran);

            try
            {
                rdr = cmd.ExecuteReader();
                bool First = true;

                while (rdr.Read())
                {
                    if (First)
                    {
                        Indexes += String.Format("'{0}', OLD.{0}", rdr.GetString(1).Trim());
                        First    = false;
                    }
                    else
                    {
                        Indexes += String.Format(", '{0}', OLD.{0}", rdr.GetString(1).Trim());
                    }

                    i++;
                }
            }
            finally
            {
                CloseAndDispose(ref cmd, ref rdr);
            }

            if (String.IsNullOrEmpty(Indexes))
            {
                return(String.Empty);
            }

            excludeFields += ":REPLICATE$HASH:";

            Result += "SET TERM ^ ;\r\n";
            Result += String.Format("CREATE OR ALTER TRIGGER REPLICATE${0}_U FOR {1} ACTIVE\r\n", triggerName, tableName);
            Result += "BEFORE UPDATE POSITION 32767\r\n";
            Result += "AS\r\n";
            Result += "  DECLARE VARIABLE vOperationLogID BIGINT;\r\n";
            Result += "  DECLARE VARIABLE vHASH BIGINT;\r\n";
            Result += "BEGIN\r\n";
            //Result += ReplicateCreateAnyRecordChangedTest(conn, tran, tableName, excludeFields, 3));

            while (i < 3)
            {
                Indexes += ", NULL, NULL";
                i++;
            }

            Result += String.Format("    EXECUTE PROCEDURE REPLICATE$OPERATIONLOG_INSERT ('{0}', 'UPDATE', {1}) " +
                                    "RETURNING_VALUES :vOperationLogID;\r\n", tableName, Indexes);
            Result += "\r\n";

            SQL = String.Format("select f.rdb$field_name, CASE flds.RDB$FIELD_TYPE WHEN 261 THEN 50000 ELSE " +
                                "flds.RDB$CHARACTER_LENGTH END from rdb$relation_fields f join rdb$relations r on f.rdb$relation_name = " +
                                "r.rdb$relation_name and r.rdb$view_blr is null and (r.rdb$system_flag is null or r.rdb$system_flag = 0) " +
                                "join rdb$fields flds on flds.RDB$FIELD_NAME = f.RDB$FIELD_SOURCE WHERE f.RDB$RELATION_NAME = '{0}' " +
                                "order by 1, f.rdb$field_position;", tableName);
            cmd = new FbCommand(SQL, conn, tran);
            try
            {
                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    int Length = rdr.IsDBNull(1) ? 0 : rdr.GetInt32(1);

                    if (!excludeFields.Contains(String.Format("{0}:", rdr.GetString(0).Trim())))
                    {
                        if (updateHash.Length < 30)
                        {
                            updateHash += String.Format("COALESCE(NEW.{0}, '')", rdr.GetString(0).Trim());
                        }
                        else
                        {
                            updateHash += String.Format(" || COALESCE(NEW.{0}, '')", rdr.GetString(0).Trim());
                        }

#if LogRowData
                        if (options.HasFlag(TableOptions.LogRowData))
                        {
#endif
                        Result += String.Format("    IF ((OLD.{0} IS DISTINCT FROM NEW.{0})) THEN\r\n", rdr.GetString(0).Trim());
                        Result += "    INSERT INTO REPLICATE$COLUMNLOG (ID, OPERATIONLOG_ID, COLUMN_NAME, OLD_VALUE, " +
                                  "NEW_VALUE, OLD_VALUE_BLOB, NEW_VALUE_BLOB)\r\n";

                        if (Length < 301)
                        {
                            Result += String.Format("    VALUES (GEN_ID(REPLICATE$COLUMNLOG_ID, 1), :vOperationLogID, " +
                                                    "'{0}', OLD.{0}, NEW.{0}, NULL, NULL);\r\n", rdr.GetString(0).Trim());
                        }
                        else
                        {
                            Result += String.Format("    VALUES (GEN_ID(REPLICATE$COLUMNLOG_ID, 1), :vOperationLogID, " +
                                                    "'{0}', NULL, NULL, OLD.{0}, NEW.{0});\r\n", rdr.GetString(0).Trim());
                        }

                        Result += "\r\n";
#if LogRowData
                    }
#endif
                    }
                }
            }
            finally
            {
                CloseAndDispose(ref cmd, ref rdr);
            }

            //Result += "   END");
            Result += "\r\n";
            Result += String.Format("   {0});\r\n", updateHash);
            Result += "END^\r\n";
            Result += "SET TERM ; ^\r\n";
            Result += "\r\n";
            Result += "\r\n";

            if (IncludeTrigger(conn, generateOnly, String.Format("{0}_U", triggerName), Result))
            {
                return(Result);
            }
            else
            {
                return(String.Empty);
            }
        }
Exemplo n.º 24
0
 public override StringBuilder BuildTableName(StringBuilder sb, string?server, string?database, string?schema, string table, TableOptions tableOptions)
 {
     return(sb.Append(table));
 }
Exemplo n.º 25
0
        // https://www.ibm.com/support/knowledgecenter/en/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_1652.htm
        public override StringBuilder BuildTableName(StringBuilder sb, string?server, string?database, string?schema, string table, TableOptions tableOptions)
        {
            if (server != null && server.Length == 0)
            {
                server = null;
            }
            if (database != null && database.Length == 0)
            {
                database = null;
            }
            if (schema != null && schema.Length == 0)
            {
                schema = null;
            }

            if (server != null && database == null)
            {
                throw new LinqToDBException("You must specify database for linked server query");
            }

            if (database != null)
            {
                sb.Append(database);
            }

            if (server != null)
            {
                sb.Append('@').Append(server);
            }

            if (database != null)
            {
                sb.Append(':');
            }

            if (schema != null)
            {
                sb.Append(schema).Append('.');
            }

            return(sb.Append(table));
        }
Exemplo n.º 26
0
 static TempTable <T> CreateTable <T>(IDataContext db, string?tableName, TableOptions tableOptions = TableOptions.NotSet) =>
 db.CreateSqlProvider() is FirebirdSqlBuilder ?
 new FirebirdTempTable <T>(db, tableName, tableOptions: tableOptions) :
 new         TempTable <T>(db, tableName, tableOptions: tableOptions);
Exemplo n.º 27
0
 public static ITable <T> TableOptions <T>(this ITable <T> table, [SqlQueryDependent] TableOptions options)
     where T : notnull
 {
     return(((ITableMutable <T>)table).ChangeTableOptions(options));
 }
Exemplo n.º 28
0
        private void CheckPureMetadata(Cluster cluster, ISession session, string tableName, string keyspaceName, TableOptions tableOptions = null)
        {
            // build create table cql
            tableName = TestUtils.GetUniqueTableName().ToLower();
            var columns = new Dictionary
                          <string, ColumnTypeCode>
            {
                { "q0uuid", ColumnTypeCode.Uuid },
                { "q1timestamp", ColumnTypeCode.Timestamp },
                { "q2double", ColumnTypeCode.Double },
                { "q3int32", ColumnTypeCode.Int },
                { "q4int64", ColumnTypeCode.Bigint },
                { "q5float", ColumnTypeCode.Float },
                { "q6inet", ColumnTypeCode.Inet },
                { "q7boolean", ColumnTypeCode.Boolean },
                { "q8inet", ColumnTypeCode.Inet },
                { "q9blob", ColumnTypeCode.Blob },
                { "q10varint", ColumnTypeCode.Varint },
                { "q11decimal", ColumnTypeCode.Decimal },
                { "q12list", ColumnTypeCode.List },
                { "q13set", ColumnTypeCode.Set },
                { "q14map", ColumnTypeCode.Map }
                //{"q12counter", Metadata.ColumnTypeCode.Counter}, A table that contains a counter can only contain counters
            };

            var stringBuilder = new StringBuilder(@"CREATE TABLE " + tableName + " (");

            foreach (KeyValuePair <string, ColumnTypeCode> col in columns)
            {
                stringBuilder.Append(col.Key + " " + col.Value +
                                     (((col.Value == ColumnTypeCode.List) ||
                                       (col.Value == ColumnTypeCode.Set) ||
                                       (col.Value == ColumnTypeCode.Map))
                              ? "<int" + (col.Value == ColumnTypeCode.Map ? ",varchar>" : ">")
                              : "") + ", ");
            }

            stringBuilder.Append("PRIMARY KEY(");
            int rowKeys = Randomm.Instance.Next(1, columns.Count - 3);

            for (int i = 0; i < rowKeys; i++)
            {
                stringBuilder.Append(columns.Keys.First(key => key.StartsWith("q" + i.ToString(CultureInfo.InvariantCulture))) + ((i == rowKeys - 1) ? "" : ", "));
            }
            string opt = tableOptions != null ? " WITH " + tableOptions : "";

            stringBuilder.Append("))" + opt + ";");

            QueryTools.ExecuteSyncNonQuery(session, stringBuilder.ToString());
            TestUtils.WaitForSchemaAgreement(session.Cluster);

            var table = cluster.Metadata.GetTable(keyspaceName, tableName);

            Assert.AreEqual(tableName, table.Name);
            foreach (var metaCol in table.TableColumns)
            {
                Assert.True(columns.Keys.Contains(metaCol.Name));
                Assert.True(metaCol.TypeCode == columns.First(tpc => tpc.Key == metaCol.Name).Value);
                Assert.True(metaCol.Table == tableName);
                Assert.True(metaCol.Keyspace == (keyspaceName));
            }

            if (tableOptions != null)
            {
                Assert.AreEqual(tableOptions.Comment, table.Options.Comment);
                Assert.AreEqual(tableOptions.ReadRepairChance, table.Options.ReadRepairChance);
                Assert.AreEqual(tableOptions.LocalReadRepairChance, table.Options.LocalReadRepairChance);
                Assert.AreEqual(tableOptions.ReplicateOnWrite, table.Options.replicateOnWrite);
                Assert.AreEqual(tableOptions.GcGraceSeconds, table.Options.GcGraceSeconds);
                Assert.AreEqual(tableOptions.bfFpChance, table.Options.bfFpChance);
                if (tableOptions.Caching == "ALL")
                {
                    //The string returned can be more complete than the provided
                    Assert.That(table.Options.Caching == "ALL" || table.Options.Caching.Contains("ALL"), "Caching returned does not match");
                }
                else
                {
                    Assert.AreEqual(tableOptions.Caching, table.Options.Caching);
                }
                Assert.AreEqual(tableOptions.CompactionOptions, table.Options.CompactionOptions);
                Assert.AreEqual(tableOptions.CompressionParams, table.Options.CompressionParams);
            }
        }
Exemplo n.º 29
0
        public override StringBuilder BuildTableName(StringBuilder sb, string?server, string?database, string?schema, string table, TableOptions tableOptions)
        {
            if (database != null && database.Length == 0)
            {
                database = null;
            }

            if (database != null)
            {
                sb.Append(database).Append('.');
            }

            return(sb.Append(table));
        }
Exemplo n.º 30
0
        public override StringBuilder BuildTableName(StringBuilder sb, string?server, string?database, string?schema, string table, TableOptions tableOptions)
        {
            if (database != null && database.Length == 0)
            {
                database = null;
            }
            if (schema != null && schema.Length == 0)
            {
                schema = null;
            }

            // "db..table" syntax not supported
            if (database != null && schema == null)
            {
                throw new LinqToDBException("DB2 requires schema name if database name provided.");
            }

            return(base.BuildTableName(sb, null, database, schema, table, tableOptions));
        }
        private void GenerateDataTableButton_Click(object sender, RoutedEventArgs e)
        {
            FormatOptions presetFormatOptions = new FormatOptions
            {
                PreserveNewLines = this.TryGetArgumentValue <bool>("PreserveNewLines"),
                CSVParsing       = this.TryGetArgumentValue <bool>("CSVParse"),
                PreserveStrings  = this.TryGetArgumentValue <bool>("PreserveStrings"),
                ColumnSeparators = this.GetSeparatorsFromArgumentValue("ColumnSeparators"),
                NewLineSeparator = this.GetSeparatorsFromArgumentValue("NewLineSeparator")
            };

            try
            {
                char[] trimChars = new char[((!((base.ModelItem.Properties["ColumnSizes"].ComputedValue as InArgument <IEnumerable <int> >).Expression is VisualBasicValue <IEnumerable <int> >) ?
                                              null : ((base.ModelItem.Properties["ColumnSizes"].ComputedValue as InArgument <IEnumerable <int> >).Expression as VisualBasicValue <IEnumerable <int> >).ExpressionText) == null) ? 0 : 1];
                trimChars[0] = '{';
                char[] chArray2 = new char[] { '}' };
                string str2     = (!((base.ModelItem.Properties["ColumnSizes"].ComputedValue as InArgument <IEnumerable <int> >).Expression is VisualBasicValue <IEnumerable <int> >) ?
                                   null : ((base.ModelItem.Properties["ColumnSizes"].ComputedValue as InArgument <IEnumerable <int> >).Expression as VisualBasicValue <IEnumerable <int> >).ExpressionText).TrimStart(trimChars).TrimEnd(chArray2);
                presetFormatOptions.ColumnSizes = new IntCollectionToStringConverter().ConvertBack(str2, null, ",", null) as IEnumerable <int>;
            }
            catch (Exception exception1)
            {
                Trace.TraceError(exception1.Message);
            }
            TableOptions presetTableOptions = new TableOptions
            {
                UseColumnHeader = (bool)base.ModelItem.Properties["UseColumnHeader"].Value.GetCurrentValue(),
                UseRowHeader    = (bool)base.ModelItem.Properties["UseRowHeader"].Value.GetCurrentValue(),
                AutoDetectTypes = (bool)base.ModelItem.Properties["AutoDetectTypes"].Value.GetCurrentValue()
            };
            string inputText = this.TryGetArgumentValue <string>("InputString") ?? this.sampleInput;
            GenerateDataTableDialog dialog = new GenerateDataTableDialog(presetFormatOptions, presetTableOptions, inputText);
            bool?nullable = dialog.ShowDialog();
            bool flag     = true;

            if ((nullable.GetValueOrDefault() == flag) ? nullable.HasValue : false)
            {
                Func <string, string> func = delegate(string s)
                {
                    if (s != Environment.NewLine)
                    {
                        return("string.Format(\"" + s.Replace(Environment.NewLine, "{0}") + "\", Environment.NewLine)");
                    }
                    return("Environment.NewLine");
                };
                if (!string.IsNullOrEmpty(dialog.FormatOptions.ColumnSeparators))
                {
                    if (dialog.FormatOptions.ColumnSeparators.Contains(Environment.NewLine))
                    {
                        base.ModelItem.Properties["ColumnSeparators"].SetValue(new InArgument <string>(new VisualBasicValue <string>(func(dialog.FormatOptions.ColumnSeparators))));
                    }
                    else
                    {
                        base.ModelItem.Properties["ColumnSeparators"].SetValue(new InArgument <string>(dialog.FormatOptions.ColumnSeparators));
                    }
                }
                else
                {
                    base.ModelItem.Properties["ColumnSeparators"].SetValue(null);
                }
                if (!string.IsNullOrEmpty(dialog.FormatOptions.NewLineSeparator))
                {
                    if (dialog.FormatOptions.NewLineSeparator.Contains(Environment.NewLine))
                    {
                        base.ModelItem.Properties["NewLineSeparator"].SetValue(new InArgument <string>(new VisualBasicValue <string>(func(dialog.FormatOptions.NewLineSeparator))));
                    }
                    else
                    {
                        base.ModelItem.Properties["NewLineSeparator"].SetValue(new InArgument <string>(dialog.FormatOptions.NewLineSeparator));
                    }
                }
                else
                {
                    base.ModelItem.Properties["NewLineSeparator"].SetValue(null);
                }
                if ((dialog.FormatOptions.ColumnSizes != null) && dialog.FormatOptions.ColumnSizes.Any <int>())
                {
                    string expressionText = $"{{ {new IntCollectionToStringConverter().Convert(dialog.FormatOptions.ColumnSizes, null, ",", null) as string} }}";
                    InArgument <IEnumerable <int> > argument = new InArgument <IEnumerable <int> >
                    {
                        Expression = new VisualBasicValue <IEnumerable <int> >(expressionText)
                    };
                    base.ModelItem.Properties["ColumnSizes"].SetValue(argument);
                }
                else
                {
                    base.ModelItem.Properties["ColumnSizes"].SetValue(null);
                }
                base.ModelItem.Properties["PreserveNewLines"].SetValue(dialog.FormatOptions.PreserveNewLines);
                base.ModelItem.Properties["CSVParse"].SetValue(new InArgument <bool>(dialog.FormatOptions.CSVParsing));
                base.ModelItem.Properties["PreserveStrings"].SetValue(dialog.FormatOptions.PreserveStrings);
                base.ModelItem.Properties["UseColumnHeader"].SetValue(dialog.TableOptions.UseColumnHeader);
                base.ModelItem.Properties["UseRowHeader"].SetValue(dialog.TableOptions.UseRowHeader);
                base.ModelItem.Properties["AutoDetectTypes"].SetValue(dialog.TableOptions.AutoDetectTypes);
                this.sampleInput = dialog.InputText;
            }
        }
Exemplo n.º 32
0
            static Query <int> CreateQuery(
                IDataContext dataContext,
                EntityDescriptor descriptor,
                T obj,
                InsertOrUpdateColumnFilter <T>?columnFilter,
                string?tableName,
                string?serverName,
                string?databaseName,
                string?schemaName,
                TableOptions tableOptions,
                Type type)
            {
                var fieldDic = new Dictionary <SqlField, ParameterAccessor>();
                var sqlTable = new SqlTable(dataContext.MappingSchema, type);

                if (tableName != null)
                {
                    sqlTable.PhysicalName = tableName;
                }
                if (serverName != null)
                {
                    sqlTable.Server = serverName;
                }
                if (databaseName != null)
                {
                    sqlTable.Database = databaseName;
                }
                if (schemaName != null)
                {
                    sqlTable.Schema = schemaName;
                }
                if (tableOptions.IsSet())
                {
                    sqlTable.TableOptions = tableOptions;
                }

                var sqlQuery = new SelectQuery();

                ParameterAccessor?param = null;

                var insertOrUpdateStatement = new SqlInsertOrUpdateStatement(sqlQuery);

                insertOrUpdateStatement.Insert.Into  = sqlTable;
                insertOrUpdateStatement.Update.Table = sqlTable;

                sqlQuery.From.Table(sqlTable);

                var ei = new Query <int>(dataContext, null)
                {
                    Queries = { new QueryInfo {
                                    Statement = insertOrUpdateStatement,
                                } }
                };

                var supported = ei.SqlProviderFlags.IsInsertOrUpdateSupported && ei.SqlProviderFlags.CanCombineParameters;

                // Insert.
                //
                foreach (var field in sqlTable.Fields)
                {
                    if (field.IsInsertable && !field.ColumnDescriptor.ShouldSkip(obj !, descriptor, SkipModification.Insert))
                    {
                        if (columnFilter == null || columnFilter(obj, field.ColumnDescriptor, true))
                        {
                            if (!supported || !fieldDic.TryGetValue(field, out param))
                            {
                                param = GetParameter(type, dataContext, field);
                                ei.Queries[0].AddParameterAccessor(param);

                                if (supported)
                                {
                                    fieldDic.Add(field, param);
                                }
                            }

                            insertOrUpdateStatement.Insert.Items.Add(new SqlSetExpression(field, param.SqlParameter));
                        }
                    }
Exemplo n.º 33
0
            public static async Task <ITable <T> > QueryAsync(
                IDataContext dataContext,
                string?tableName,
                string?serverName,
                string?databaseName,
                string?schemaName,
                string?statementHeader,
                string?statementFooter,
                DefaultNullable defaultNullable,
                TableOptions tableOptions,
                CancellationToken token)
            {
                var sqlTable    = new SqlTable <T>(dataContext.MappingSchema);
                var createTable = new SqlCreateTableStatement(sqlTable);

                if (tableName != null)
                {
                    sqlTable.PhysicalName = tableName;
                }
                if (serverName != null)
                {
                    sqlTable.Server = serverName;
                }
                if (databaseName != null)
                {
                    sqlTable.Database = databaseName;
                }
                if (schemaName != null)
                {
                    sqlTable.Schema = schemaName;
                }
                if (tableOptions.IsSet())
                {
                    sqlTable.TableOptions = tableOptions;
                }

                createTable.StatementHeader = statementHeader;
                createTable.StatementFooter = statementFooter;
                createTable.DefaultNullable = defaultNullable;

                var query = new Query <int>(dataContext, null)
                {
                    Queries = { new QueryInfo {
                                    Statement = createTable,
                                } }
                };

                SetNonQueryQuery(query);

                await query.GetElementAsync(dataContext, ExpressionInstances.UntypedNull, null, null, token).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);

                ITable <T> table = new Table <T>(dataContext);

                if (sqlTable.PhysicalName != null)
                {
                    table = table.TableName(sqlTable.PhysicalName);
                }
                if (sqlTable.Server != null)
                {
                    table = table.ServerName(sqlTable.Server);
                }
                if (sqlTable.Database != null)
                {
                    table = table.DatabaseName(sqlTable.Database);
                }
                if (sqlTable.Schema != null)
                {
                    table = table.SchemaName(sqlTable.Schema);
                }
                if (sqlTable.TableOptions.IsSet())
                {
                    table = table.TableOptions(sqlTable.TableOptions);
                }

                return(table);
            }
Exemplo n.º 34
0
        private void CheckMetadata(string tableName, string keyspaceName, TableOptions tableOptions = null)
        {
            ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(DefaultNodeCount);
            var cluster = testCluster.Cluster;
            var session = testCluster.Session;

            session.CreateKeyspaceIfNotExists(keyspaceName);
            session.ChangeKeyspace(keyspaceName);

            CheckPureMetadata(cluster, session, tableName, keyspaceName, tableOptions);
        }
Exemplo n.º 35
0
        private void CheckMetadata(string tableName = null, string keyspaceName = null, TableOptions tableOptions = null)
        {
            var clusterInfo = TestUtils.CcmSetup(2);
            try
            {
                Session = clusterInfo.Session;
                Cluster = clusterInfo.Cluster;
                Session.CreateKeyspaceIfNotExists(Keyspace);
                Session.ChangeKeyspace(Keyspace);

                CheckPureMetadata(tableName, keyspaceName, tableOptions);
            }
            finally
            {
                TestUtils.CcmRemove(clusterInfo);
            }
        }