Example #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlTable"/> class using the
        /// specified table name and alias.
        /// </summary>
        /// <param name="tableName">
        /// The name of the table.
        /// </param>
        /// <param name="alias">
        /// The alias to use for the table.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when the <paramref name="tableName"/> argument is <see langword="null"/>,
        /// an empty string, or a string containing only white-space characters.
        /// </exception>
        public SqlTable(SqlIdentifier tableName, string alias)
            : base(alias)
        {
            if (tableName == null) throw new ArgumentNullException(nameof(tableName));

            TableName = tableName;
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlTable"/> class using the
        /// specified column name and alias.
        /// </summary>
        /// <param name="columnName">
        /// The name of the column.
        /// </param>
        /// <param name="alias">
        /// The alias to use for the column.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when the <paramref name="columnName"/> argument is <see langword="null"/>,
        /// an empty string, or a string containing only white-space characters.
        /// </exception>
        public SqlColumn(SqlIdentifier columnName, string alias)
        {
            if (columnName == null) throw new ArgumentNullException(nameof(columnName));

            ColumnName = columnName;
            Alias = alias;
        }
Example #3
0
        /// <summary>
        /// Applies the specified event store table name to the configuration.
        /// </summary>
        /// <param name="schemaName">The configured event store schema name. The default value is "Events".</param>
        /// <param name="tableName">The configured event store table name. The default value is based on the <see cref="EntityName"/> property.</param>
        /// <returns>The original <see cref="SqlEventStoreConfigurationBuilder">builder</see>.</returns>
        public virtual SqlEventStoreConfigurationBuilder HasTableName(string schemaName, string tableName)
        {
            Arg.NotNullOrEmpty(schemaName, nameof(schemaName));
            Arg.NotNullOrEmpty(tableName, nameof(tableName));
            Contract.Ensures(Contract.Result <SqlEventStoreConfigurationBuilder>() != null);

            TableNameIsOverriden = tableName != TableName.ObjectName;
            TableName            = new SqlIdentifier(schemaName, tableName);
            return(this);
        }
        public override SqlObject VisitPropertyRefScalarExpressionRecursive([NotNull] sqlParser.PropertyRefScalarExpressionRecursiveContext context)
        {
            Contract.Requires(context != null);
            // primary_expression '.' IDENTIFIER

            SqlScalarExpression memberExpression = (SqlScalarExpression)this.Visit(context.primary_expression());
            SqlIdentifier       indentifier      = SqlIdentifier.Create(context.IDENTIFIER().GetText());

            return(SqlPropertyRefScalarExpression.Create(memberExpression, indentifier));
        }
        public void Ctor_WithEscapedIdentifier_SetsSegmentsProperty()
        {
            var identifier = new SqlIdentifier("[Bl[og].\"db\"\"o\".[Us]]ers].[Em\"ail]");

            Assert.NotNull(identifier.Segments);
            Assert.Equal(4, identifier.Segments.Length);
            Assert.Equal("Bl[og", identifier.Segments[0]);
            Assert.Equal("db\"o", identifier.Segments[1]);
            Assert.Equal("Us]ers", identifier.Segments[2]);
            Assert.Equal("Em\"ail", identifier.Segments[3]);
        }
Example #6
0
        private SqlFromClause CreateSubqueryFromClause()
        {
            SqlQuery subquery = this.inputQuery.GetSqlQuery();
            SqlSubqueryCollection          collection = SqlSubqueryCollection.Create(subquery);
            ParameterExpression            inputParam = this.inputQuery.Alias;
            SqlIdentifier                  identifier = SqlIdentifier.Create(inputParam.Name);
            SqlAliasedCollectionExpression colExp     = SqlAliasedCollectionExpression.Create(collection, identifier);
            SqlFromClause                  fromClause = this.CreateFrom(colExp);

            return(fromClause);
        }
Example #7
0
 protected override void WriteName(string name)
 {
     if (SqlIdentifier.NeedToQuote(name))
     {
         sb.Append(SqlIdentifier.QuoteCompoundIdentifier(name));
     }
     else
     {
         sb.Append(name);
     }
 }
Example #8
0
 private static void BuildPrimaryKey(MetaTable table, StringBuilder sb)
 {
     foreach (MetaDataMember mm in table.RowType.IdentityMembers)
     {
         if (sb.Length > 0)
         {
             sb.Append(", ");
         }
         sb.Append(SqlIdentifier.QuoteCompoundIdentifier(mm.MappedName));
     }
 }
Example #9
0
            internal SubscriptionQueueSqlBuilder(SqlIdentifier identifier, SqlIdentifier subscriptionIdentifier)
            {
                var delimitedName  = identifier.Delimit();
                var identifierName = identifier.AsIdentifierName();
                var indexName      = "IX_" + identifier.AsIdentifierName();

#pragma warning disable SA1137 // Elements should have the same indentation

                CreateSchema = Statement(
                    $"IF NOT EXISTS( SELECT * FROM sys.schemas WHERE name = '{identifier.SchemaName}' )",
                    "BEGIN",
                    $"    EXECUTE( 'CREATE SCHEMA {identifier.Delimit( SchemaName )};' );",
                    "END;");

                CreateTable = Statement(
                    $"IF NOT EXISTS( SELECT * FROM sys.tables WHERE schema_id = SCHEMA_ID( '{identifier.SchemaName}' ) AND name = '{identifier.ObjectName}' )",
                    "BEGIN",
                    $"    CREATE TABLE {delimitedName}",
                    "    (",
                    "         SubscriptionId UNIQUEIDENTIFIER NOT NULL",
                    "        ,MessageId UNIQUEIDENTIFIER NOT NULL",
                    "        ,EnqueueTime DATETIME2 NOT NULL",
                    "        ,DequeueAttempts INT NOT NULL DEFAULT(0)",
                    "        ,DueTime DATETIME2 NOT NULL",
                    "        ,Type NVARCHAR(256) NOT NULL",
                    "        ,Revision INT NOT NULL",
                    "        ,Message VARBINARY(MAX) NOT NULL",
                    $"        ,CONSTRAINT PK_{identifierName} PRIMARY KEY NONCLUSTERED ( SubscriptionId, MessageId )",
                    $"        ,CONSTRAINT FK_{identifierName}_{subscriptionIdentifier.AsIdentifierName( ObjectName )} FOREIGN KEY ( SubscriptionId )",
                    $"             REFERENCES {subscriptionIdentifier.Delimit()} ( SubscriptionId ) ON DELETE CASCADE",
                    "    );",
                    "END;");

                CreateIndex = Statement(
                    $"IF NOT EXISTS( SELECT * FROM sys.indexes WHERE name = '{indexName}' )",
                    "BEGIN",
                    $"    CREATE CLUSTERED INDEX {indexName}",
                    $"    ON {delimitedName}( DueTime, DequeueAttempts );",
                    "END;");

                Enqueue = $"INSERT INTO {delimitedName} VALUES( @SubscriptionId, @MessageId, @EnqueueTime, @DequeueAttempts, @DueTime, @Type, @Revision, @Message );";

                Dequeue = Statement(
                    $"DELETE FROM {delimitedName}",
                    "OUTPUT DELETED.MessageId, DELETED.EnqueueTime, DELETED.DequeueAttempts, DELETED.DueTime,",
                    "    DELETED.Type, DELETED.Revision, DELETED.Message",
                    "WHERE MessageId IN (",
                    "    SELECT TOP(1) MessageId",
                    $"    FROM {delimitedName} WITH (XLOCK, ROWLOCK, READPAST)",
                    "    WHERE DueTime <= @DueTime",
                    "    ORDER BY DequeueAttempts );");

#pragma warning restore SA1137 // Elements should have the same indentation
            }
Example #10
0
            internal SubscriptionSqlBuilder(SqlIdentifier identifier, SqlIdentifier messageQueueIdentifier, SqlIdentifier subscriptionQueueIdentifier)
            {
                var delimitedName     = identifier.Delimit();
                var triggerIdentifier = new SqlIdentifier(identifier.SchemaName, "AfterInsertInto" + identifier.AsIdentifierName(ObjectName));

#pragma warning disable SA1137 // Elements should have the same indentation

                CreateSchema = Statement(
                    $"IF NOT EXISTS( SELECT * FROM sys.schemas WHERE name = '{identifier.SchemaName}' )",
                    "BEGIN",
                    $"    EXECUTE( 'CREATE SCHEMA {identifier.Delimit( SchemaName )};' );",
                    "END;");

                CreateTable = Statement(
                    $"IF NOT EXISTS( SELECT * FROM sys.tables WHERE schema_id = SCHEMA_ID( '{identifier.SchemaName}' ) AND name = '{identifier.ObjectName}' )",
                    "BEGIN",
                    $"    CREATE TABLE {delimitedName}",
                    "    (",
                    "         SubscriptionId UNIQUEIDENTIFIER NOT NULL DEFAULT(NEWSEQUENTIALID()) PRIMARY KEY",
                    "        ,CreationTime DATETIME2 NOT NULL DEFAULT(GETUTCDATE())",
                    "    );",
                    "END;");

                CreateTrigger = Statement(
                    $"CREATE OR ALTER TRIGGER {triggerIdentifier.Delimit()} ON {delimitedName} FOR INSERT AS",
                    "BEGIN",
                    "SET NOCOUNT ON;",
                    $"INSERT INTO {subscriptionQueueIdentifier.Delimit()}",
                    "SELECT",
                    "     i.SubscriptionId",
                    "    ,mq.MessageId",
                    "    ,mq.EnqueueTime",
                    "    ,0 -- DequeueAttempts",
                    "    ,mq.DueTime",
                    "    ,mq.Type",
                    "    ,mq.Revision",
                    "    ,mq.Message",
                    "FROM",
                    "    INSERTED i",
                    $"    INNER JOIN {messageQueueIdentifier.Delimit()} mq ON mq.EnqueueTime >= i.CreationTime;",
                    "END;");

                CreateSubscription = Statement(
                    $"MERGE {delimitedName} AS target",
                    "USING ( SELECT @SubscriptionId, @CreationTime ) AS source ( SubscriptionId, CreationTime )",
                    "ON target.SubscriptionId = source.SubscriptionId",
                    "WHEN NOT MATCHED THEN",
                    "    INSERT ( SubscriptionId, CreationTime )",
                    "    VALUES ( source.SubscriptionId, source.CreationTime );");

                DeleteSubscription = $"DELETE FROM {delimitedName} WHERE SubscriptionId = SubscriptionId;";

#pragma warning restore SA1137 // Elements should have the same indentation
            }
Example #11
0
        internal static string GetCreateDatabaseCommand(string catalog, string dataFilename, string logFilename)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("CREATE DATABASE {0}", SqlIdentifier.QuoteIdentifier(catalog));
            if (dataFilename != null)
            {
                sb.AppendFormat(" ON PRIMARY (NAME='{0}', FILENAME='{1}')", Path.GetFileName(dataFilename), dataFilename);
                sb.AppendFormat(" LOG ON (NAME='{0}', FILENAME='{1}')", Path.GetFileName(logFilename), logFilename);
            }
            return(sb.ToString());
        }
Example #12
0
        private static string BuildKey(IEnumerable <MetaDataMember> members)
        {
            StringBuilder sb = new StringBuilder();

            foreach (MetaDataMember mm in members)
            {
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(SqlIdentifier.QuoteCompoundIdentifier(mm.MappedName));
            }
            return(sb.ToString());
        }
        public override bool Visit(SqlIdentifier first, SqlObject secondAsObject)
        {
            if (!(secondAsObject is SqlIdentifier second))
            {
                return(false);
            }

            if (first.Value != second.Value)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Applies the specified entity name to the configuration.
        /// </summary>
        /// <param name="value">The configured entity name. The default value is "Event".</param>
        /// <returns>The original <see cref="SqlEventStoreConfigurationBuilder">builder</see>.</returns>
        public virtual SqlEventStoreConfigurationBuilder HasEntityName(string value)
        {
            Arg.NotNullOrEmpty(value, nameof(value));
            Contract.Ensures(Contract.Result <SqlEventStoreConfigurationBuilder>() != null);

            EntityName = value;

            if (!TableNameIsOverriden)
            {
                TableName = new SqlIdentifier(TableName.SchemaName, value);
            }

            return(this);
        }
Example #15
0
            protected override void WriteName(string name)
            {
                var index      = name.LastIndexOf('.');
                var columnName = index > 0 ? name.Substring(index + 1) : name;

                if (SqlIdentifier.NeedToQuote(columnName))
                {
                    sb.Append(SqlIdentifier.QuoteCompoundIdentifier(columnName));
                }
                else
                {
                    sb.Append(name);
                }
            }
Example #16
0
        private int ProcessExpressionName(int nextToken)
        {
            SqlIdentifier name = CodeObject.Name;

            for (int i = nextToken; i < name.Position.startTokenNumber; i++)
            {
                ProcessTokenEnsuringOneNewLineMinimum(i);
            }

            ProcessTokenRange(name.Position.startTokenNumber, name.Position.endTokenNumber);

            nextToken = name.Position.endTokenNumber;

            return(nextToken);
        }
        public void SqlArrayScalarExpressionTest()
        {
            CosmosObject tag = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["name"] = CosmosString.Create("asdf")
            });

            CosmosObject tags = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["tags"] = CosmosArray.Create(new List <CosmosElement>()
                {
                    tag
                }),
                ["_rid"] = CosmosString.Create("AYIMAMmFOw8YAAAAAAAAAA==")
            });

            CosmosObject tagsWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = tags,
                ["_rid"] = CosmosString.Create("AYIMAMmFOw8YAAAAAAAAAA==")
            });

            // ARRAY(SELECT VALUE t.name FROM t in c.tags)
            SqlArrayScalarExpression arrayScalarExpression = SqlArrayScalarExpression.Create(
                SqlQuery.Create(
                    SqlSelectClause.Create(
                        SqlSelectValueSpec.Create(
                            TestUtils.CreatePathExpression("t", "name"))),
                    SqlFromClause.Create(
                        SqlArrayIteratorCollectionExpression.Create(
                            SqlIdentifier.Create("t"),
                            SqlInputPathCollection.Create(
                                SqlIdentifier.Create("c"),
                                SqlStringPathExpression.Create(
                                    null,
                                    SqlStringLiteral.Create("tags"))))),
                    whereClause: null,
                    groupByClause: null,
                    orderByClause: null,
                    offsetLimitClause: null));

            CosmosArray tagNames = CosmosArray.Create(new List <CosmosElement>()
            {
                CosmosString.Create("asdf")
            });

            AssertEvaluation(tagNames, arrayScalarExpression, tagsWrapped);
        }
Example #18
0
            //internal override SqlRow VisitRow(SqlRow row)
            //{
            //    int num = 0;
            //    int count = row.Columns.Count;
            //    while (num < count)
            //    {
            //        SqlColumn key = row.Columns[num];
            //        if (num > 0)
            //        {
            //            sb.Append(", ");
            //        }

            //        num++;
            //    }
            //    return row;
            //}

            internal override void VisitRowColumn(SqlColumn key)
            {
                Visit(key.Expression);
                string name = key.Name;
                string str2 = InferName(key.Expression, null);

                if (name == null)
                {
                    name = str2;
                }
                if ((name == null) && !names.TryGetValue(key, out name))
                {
                    name       = "C" + names.Count;
                    names[key] = name;
                }

                if (key.Expression != null && key.Expression.NodeType == SqlNodeType.FunctionCall &&
                    ((SqlFunctionCall)key.Expression).Name.StartsWith("GEN_ID"))
                {
                    name = null;
                }

                if (!string.IsNullOrEmpty(str2))
                {
                    str2 = SqlIdentifier.UnquoteIdentifier(str2);
                }

                if (name != str2 && !string.IsNullOrEmpty(name))
                {
                    if (string.IsNullOrEmpty(str2) && key.Expression == null)
                    {
                        this.WriteName(name);
                    }
                    else
                    {
                        sb.Append(" AS ");

                        if (SqlIdentifier.NeedToQuote(name))
                        {
                            WriteName(SqlIdentifier.QuoteIdentifier(name));
                        }
                        else
                        {
                            WriteName(name);
                        }
                    }
                }
            }
Example #19
0
        /// <summary>
        /// Create a FROM clause from a set of FROM parameter bindings.
        /// </summary>
        /// <returns>The created FROM clause.</returns>
        private SqlFromClause CreateFrom(SqlCollectionExpression inputCollectionExpression)
        {
            bool first = true;

            foreach (Binding paramDef in this.fromParameters.GetBindings())
            {
                // If input collection expression is provided, the first binding,
                // which is the input paramter name, should be omitted.
                if (first)
                {
                    first = false;
                    if (inputCollectionExpression != null)
                    {
                        continue;
                    }
                }

                ParameterExpression parameter    = paramDef.Parameter;
                SqlCollection       paramBinding = paramDef.ParameterDefinition;

                SqlIdentifier           identifier = SqlIdentifier.Create(parameter.Name);
                SqlCollectionExpression collExpr;
                if (!paramDef.IsInCollection)
                {
                    SqlCollection collection = paramBinding ?? SqlInputPathCollection.Create(identifier, null);
                    SqlIdentifier alias      = paramBinding == null ? null : identifier;
                    collExpr = SqlAliasedCollectionExpression.Create(collection, alias);
                }
                else
                {
                    collExpr = SqlArrayIteratorCollectionExpression.Create(identifier, paramBinding);
                }

                if (inputCollectionExpression != null)
                {
                    inputCollectionExpression = SqlJoinCollectionExpression.Create(inputCollectionExpression, collExpr);
                }
                else
                {
                    inputCollectionExpression = collExpr;
                }
            }

            SqlFromClause fromClause = SqlFromClause.Create(inputCollectionExpression);

            return(fromClause);
        }
Example #20
0
        /// <summary>
        /// Flatten subqueries into a single query by substituting their expressions in the current query.
        /// </summary>
        /// <returns>A flattened query.</returns>
        public QueryUnderConstruction Flatten()
        {
            // SELECT fo(y) FROM y IN (SELECT fi(x) FROM x WHERE gi(x)) WHERE go(y)
            // is translated by substituting fi(x) for y in the outer query
            // producing
            // SELECT fo(fi(x)) FROM x WHERE gi(x) AND (go(fi(x))
            if (this.inputQuery == null)
            {
                // we are flat already
                if (this.selectClause == null)
                {
                    this.selectClause = new SqlSelectClause(new SqlSelectStarSpec(), this.topSpec);
                }
                else
                {
                    this.selectClause = new SqlSelectClause(this.selectClause.SelectSpec, this.topSpec, this.selectClause.HasDistinct);
                }

                return(this);
            }

            if (this.inputQuery.orderByClause != null && this.orderByClause != null)
            {
                throw new DocumentQueryException("Multiple OrderBy is not supported.");
            }

            var flatInput   = this.inputQuery.Flatten();
            var inputSelect = flatInput.selectClause;
            var inputwhere  = flatInput.whereClause;

            SqlIdentifier          replacement     = new SqlIdentifier(this.InputParameter().Name);
            var                    composedSelect  = Substitute(inputSelect, inputSelect.TopSpec ?? this.topSpec, replacement, this.selectClause);
            var                    composedWhere   = Substitute(inputSelect.SelectSpec, replacement, this.whereClause);
            var                    composedOrderBy = Substitute(inputSelect.SelectSpec, replacement, this.orderByClause);
            var                    and             = QueryUnderConstruction.CombineWithConjunction(inputwhere, composedWhere);
            QueryUnderConstruction result          = new QueryUnderConstruction
            {
                selectClause   = composedSelect,
                whereClause    = and,
                inputQuery     = null,
                fromParameters = flatInput.fromParameters,
                orderByClause  = composedOrderBy ?? this.inputQuery.orderByClause,
            };

            return(result);
        }
        public override SqlObject VisitInputPathCollection([NotNull] sqlParser.InputPathCollectionContext context)
        {
            Contract.Requires(context != null);

            SqlIdentifier     identifier = SqlIdentifier.Create(context.IDENTIFIER().GetText());
            SqlPathExpression pathExpression;

            if (context.path_expression() != null)
            {
                pathExpression = (SqlPathExpression)this.Visit(context.path_expression());
            }
            else
            {
                pathExpression = null;
            }

            return(SqlInputPathCollection.Create(identifier, pathExpression));
        }
        public override SqlObject VisitAliasedCollectionExpression([NotNull] sqlParser.AliasedCollectionExpressionContext context)
        {
            Contract.Requires(context != null);

            SqlCollection sqlCollection = (SqlCollection)this.Visit(context.collection());
            SqlIdentifier alias;

            if (context.IDENTIFIER() != null)
            {
                alias = SqlIdentifier.Create(context.IDENTIFIER().GetText());
            }
            else
            {
                alias = default;
            }

            return(SqlAliasedCollectionExpression.Create(sqlCollection, alias));
        }
        public override SqlObject VisitSelect_item([NotNull] sqlParser.Select_itemContext context)
        {
            Contract.Requires(context != null);

            SqlScalarExpression sqlScalarExpression = (SqlScalarExpression)this.Visit(context.scalar_expression());
            SqlIdentifier       alias;

            if (context.IDENTIFIER() != null)
            {
                alias = SqlIdentifier.Create(context.IDENTIFIER().GetText());
            }
            else
            {
                alias = default;
            }

            return(SqlSelectItem.Create(sqlScalarExpression, alias));
        }
Example #24
0
        public SqlTableDefinitionFormatter(FormatterVisitor visitor, SqlTableDefinition codeObject)
            : base(visitor, codeObject)
        {
            CommaSeparatedListFormatter = new CommaSeparatedListFormatter(visitor, codeObject, true);

            // figure out the size of paddings required to align column definitions in a "columnar" form
            if (FormatOptions.AlignColumnDefinitionsInColumns)
            {
                int range1MaxLength = 0;
                int range2MaxLength = 0;

                foreach (SqlCodeObject child in CodeObject.Children)
                {
                    if (child is SqlColumnDefinition && !(child is SqlComputedColumnDefinition))
                    {
                        SqlIdentifier identifierChild = child.Children.ElementAtOrDefault(0) as SqlIdentifier;

                        if (identifierChild == null)
                        {
                            throw new FormatFailedException("unexpected token at index start Token Index");
                        }

                        string s1 = child.TokenManager.GetText(identifierChild.Position.startTokenNumber, identifierChild.Position.endTokenNumber);
                        range1MaxLength = Math.Max(range1MaxLength, s1.Length);

                        SqlDataTypeSpecification dataTypeChildchild = child.Children.ElementAtOrDefault(1) as SqlDataTypeSpecification;

                        // token "timestamp" should be ignorred
                        if (dataTypeChildchild != null)
                        {
                            string s2 = child.TokenManager.GetText(dataTypeChildchild.Position.startTokenNumber, dataTypeChildchild.Position.endTokenNumber);
                            range2MaxLength = Math.Max(range2MaxLength, s2.Length);
                        }
                    }
                }

                PaddedSpaceSeparatedListFormatter.ColumnSpacingFormatDefinition        d1 = new PaddedSpaceSeparatedListFormatter.ColumnSpacingFormatDefinition(typeof(SqlIdentifier), typeof(SqlDataTypeSpecification), range1MaxLength + 1);
                PaddedSpaceSeparatedListFormatter.ColumnSpacingFormatDefinition        d2 = new PaddedSpaceSeparatedListFormatter.ColumnSpacingFormatDefinition(typeof(SqlDataTypeSpecification), null, range2MaxLength + 1);
                List <PaddedSpaceSeparatedListFormatter.ColumnSpacingFormatDefinition> columnSpacingFormatDefinitions = new List <PaddedSpaceSeparatedListFormatter.ColumnSpacingFormatDefinition>(2);
                columnSpacingFormatDefinitions.Add(d1);
                columnSpacingFormatDefinitions.Add(d2);
                Visitor.Context.CurrentColumnSpacingFormatDefinitions = columnSpacingFormatDefinitions;
            }
        }
Example #25
0
        private static IEnumerable <String> GetCreateForeignKeyCommands(MetaType type)
        {
            string tableName = type.Table.TableName;

            foreach (MetaDataMember mm in type.DataMembers)
            {
                if (mm.IsDeclaredBy(type) && mm.IsAssociation)
                {
                    MetaAssociation assoc = mm.Association;
                    if (assoc.IsForeignKey)
                    {
                        StringBuilder sb         = new StringBuilder();
                        string        thisKey    = BuildKey(assoc.ThisKey);
                        string        otherKey   = BuildKey(assoc.OtherKey);
                        string        otherTable = assoc.OtherType.Table.TableName;
                        string        name;
                        name = mm.MappedName;
                        if (name == mm.Name)
                        {
                            name = String.Format(Globalization.CultureInfo.InvariantCulture, "FK_{0}_{1}", tableName, mm.Name);
                        }
                        string cmd = "ALTER TABLE {0}" + Environment.NewLine + "  ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3}({4})";
                        //In DLinq we put the constraint on the child object (which triggers the behavior when deleted),
                        //but in SQL it is part of the parent constraint (the parent row gets changed / deleted to satisfy the constraint)
                        MetaDataMember otherMember = mm.Association.OtherMember;
                        if (otherMember != null)
                        {
                            string delConstr = otherMember.Association.DeleteRule;
                            if (delConstr != null)
                            {
                                cmd += Environment.NewLine + "  ON DELETE " + delConstr;
                            }
                        }
                        sb.AppendFormat(cmd,
                                        SqlIdentifier.QuoteCompoundIdentifier(tableName),
                                        SqlIdentifier.QuoteIdentifier(name),
                                        SqlIdentifier.QuoteCompoundIdentifier(thisKey),
                                        SqlIdentifier.QuoteCompoundIdentifier(otherTable),
                                        SqlIdentifier.QuoteCompoundIdentifier(otherKey));
                        yield return(sb.ToString());
                    }
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlSagaStorageConfiguration"/> class.
        /// </summary>
        /// <param name="providerFactory">The <see cref="DbProviderFactory">provider factory</see> for underlying database operations.</param>
        /// <param name="connectionString">The database connection string.</param>
        /// <param name="tableName">The saga data table name.</param>
        /// <param name="messageTypeResolver">The <see cref="IMessageTypeResolver">resolver</see> used to resolve message <see cref="Type">types</see>.</param>
        /// <param name="serializerFactory">The <see cref="ISqlMessageSerializerFactory">factory</see> used to create new message serializers.</param>
        public SqlSagaStorageConfiguration(
            DbProviderFactory providerFactory,
            string connectionString,
            SqlIdentifier tableName,
            IMessageTypeResolver messageTypeResolver,
            ISqlMessageSerializerFactory serializerFactory)
        {
            Arg.NotNull(providerFactory, nameof(providerFactory));
            Arg.NotNullOrEmpty(connectionString, nameof(connectionString));
            Arg.NotNull(messageTypeResolver, nameof(messageTypeResolver));
            Arg.NotNull(serializerFactory, nameof(serializerFactory));

            ProviderFactory        = providerFactory;
            this.connectionString  = connectionString;
            this.serializerFactory = serializerFactory;
            TableName           = tableName;
            MessageTypeResolver = messageTypeResolver;
            Sql = new SqlBuilder(tableName);
        }
        public override SqlObject VisitFunctionCallScalarExpression([NotNull] sqlParser.FunctionCallScalarExpressionContext context)
        {
            Contract.Requires(context != null);
            // (K_UDF '.')? IDENTIFIER '(' scalar_expression_list? ')'

            bool          udf                    = context.K_UDF() != null;
            SqlIdentifier identifier             = SqlIdentifier.Create(context.IDENTIFIER().GetText());
            List <SqlScalarExpression> arguments = new List <SqlScalarExpression>();

            if (context.scalar_expression_list() != null)
            {
                foreach (sqlParser.Scalar_expressionContext scalarExpressionContext in context.scalar_expression_list().scalar_expression())
                {
                    arguments.Add((SqlScalarExpression)this.Visit(scalarExpressionContext));
                }
            }

            return(SqlFunctionCallScalarExpression.Create(identifier, udf, arguments.ToImmutableArray()));
        }
        private static SqlScalarExpression GenerateMemberIndexerScalarExpressionFromPath(Path path)
        {
            if (path.Length < 1)
            {
                throw new ArgumentException($"{nameof(path)} is too short.");
            }

            if (!(path.First() is StringPathToken rootToken))
            {
                throw new ArgumentException($"{nameof(path)} did not start with a string.");
            }

            SqlScalarExpression rootExpression = SqlPropertyRefScalarExpression.Create(
                member: null,
                identifier: SqlIdentifier.Create(rootToken.PropertyName));

            foreach (PathToken token in path.Skip(1))
            {
                SqlLiteralScalarExpression memberIndexer;
                switch (token)
                {
                case StringPathToken stringPathToken:
                    memberIndexer = SqlLiteralScalarExpression.Create(
                        SqlStringLiteral.Create(
                            stringPathToken.PropertyName));
                    break;

                case IntegerPathToken integerPathToken:
                    memberIndexer = SqlLiteralScalarExpression.Create(
                        SqlNumberLiteral.Create(
                            integerPathToken.Index));
                    break;

                default:
                    throw new ArgumentException($"Unknown token type: {token.GetType()}; {token}");
                }

                rootExpression = SqlMemberIndexerScalarExpression.Create(rootExpression, memberIndexer);
            }

            return(rootExpression);
        }
Example #29
0
        protected int ProcessColumnList(int nextToken, SqlIdentifierCollection columnList, NormalizeWhitespace normalizer)
        {
            // find where the columns start
            IEnumerator <SqlIdentifier> columnEnum = columnList.GetEnumerator();

            if (columnEnum.MoveNext())
            {
                ProcessAndNormalizeWhitespaceRange(nextToken, columnEnum.Current.Position.startTokenNumber, normalizer);

                ProcessChild(columnEnum.Current);
                SqlIdentifier previousColumn = columnEnum.Current;
                while (columnEnum.MoveNext())
                {
                    CommaSeparatedList.ProcessInterChildRegion(previousColumn, columnEnum.Current);
                    ProcessChild(columnEnum.Current);
                    previousColumn = columnEnum.Current;
                }
                nextToken = previousColumn.Position.endTokenNumber;
            }
            return(nextToken);
        }
Example #30
0
        internal static string GetCreateTableCommand(MetaTable table)
        {
            StringBuilder sb   = new StringBuilder();
            StringBuilder decl = new StringBuilder();

            BuildFieldDeclarations(table, decl);
            sb.AppendFormat("CREATE TABLE {0}", SqlIdentifier.QuoteCompoundIdentifier(table.TableName));
            sb.Append("(");
            sb.Append(decl.ToString());
            decl = new StringBuilder();
            BuildPrimaryKey(table, decl);
            if (decl.Length > 0)
            {
                string name = String.Format(Globalization.CultureInfo.InvariantCulture, "PK_{0}", table.TableName);
                sb.Append(", ");
                sb.AppendLine();
                sb.AppendFormat("  CONSTRAINT {0} PRIMARY KEY ({1})", SqlIdentifier.QuoteIdentifier(name), decl.ToString());
            }
            sb.AppendLine();
            sb.Append("  )");
            return(sb.ToString());
        }
Example #31
0
        /// <summary>
        /// Writes the specified <paramref name="identifier"/> to the output stream.
        /// </summary>
        /// <param name="identifier">
        /// The <see cref="SqlIdentifier"/> to write to the output stream.
        /// </param>
        public void WriteIdentifier(SqlIdentifier identifier)
        {
            EnsureNotDisposed();
            if (identifier == null)
            {
                throw new ArgumentNullException(nameof(identifier));
            }

            for (int index = 0; index < identifier.Segments.Length; index++)
            {
                var segment = identifier.Segments[index];
                if (index > 0)
                {
                    WriteRaw(".");
                    WriteRaw(Dialect.FormatIdentifier(segment));
                }
                else
                {
                    Write(Dialect.FormatIdentifier(segment));
                }
            }
        }
Example #32
0
        public virtual IColumnValue this[SqlIdentifier columnName]
        {
            get
            {
                foreach (IColumnValue Itm in this)
                {
                    if (Itm.ColumnIdentifier.EqualsByName(columnName))
                    {
                        return(Itm);
                    }
                }

                // FIXME: No debería crearlo automáticamente
                // Log.Warn("Dynamically adding column " + columnName + " to a row.");
                var Res = new ColumnValue(columnName);
                this.Add(Res);
                return(Res);
            }
            set
            {
                bool Encontrado = false;
                for (int i = 0; i < this.Count; i++)
                {
                    if (this[i].ColumnIdentifier.EqualsByName(columnName))
                    {
                        ((ColumnValue)(this[i])).Value = value;
                        Encontrado = true;
                        break;
                    }
                }
                if (Encontrado == false)
                {
                    // Si no existe, creo dinámicamente el campo
                    value.ColumnIdentifier = columnName;
                    this.Add(value);
                }
            }
        }
Example #33
0
 /// <summary>
 /// Visits the specified <see cref="SqlIdentifier"/>.
 /// </summary>
 /// <param name="expression">
 /// The expression to visit.
 /// </param>
 public virtual void Visit(SqlIdentifier expression)
 {
 }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlTable"/> class using the
 /// specified table name.
 /// </summary>
 /// <param name="tableName">
 /// The name of the table.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// Thrown when the <paramref name="tableName"/> argument is <see langword="null"/>,
 /// an empty string, or a string containing only white-space characters.
 /// </exception>
 public SqlTable(SqlIdentifier tableName)
     : this(tableName, null)
 {
 }
Example #35
0
 /// <summary> 
 /// Converts the specified column name to a <see cref="SqlColumn"/> when concatenated 
 /// with a <see cref="SqlTable"/>. 
 /// </summary> 
 /// <param name="table"> 
 /// The table used to access the column. 
 /// </param> 
 /// <param name="columnName"> 
 /// The name of the column. 
 /// </param> 
 /// <returns> 
 /// A <see cref="SqlColumn"/> instance representing the specified column in the specified table. 
 /// </returns> 
 public static SqlColumn operator +(SqlTable table, string columnName)
 {
     SqlIdentifier identifier;
     if (table.Alias != null)
     {
         identifier = new SqlIdentifier(new[] { table.Alias, columnName });
     }
     else
     {
         var segments = table.TableName.Segments;
         identifier = new SqlIdentifier(segments.Concat(new[] { columnName }).ToArray());
     }
     return new SqlColumn(identifier, null);
 }
Example #36
0
 public LGExp(string column, object value, bool equal)
 {
     this.column = (SqlIdentifier) column;
     this.value = value;
     this.equal = equal;
 }
Example #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlColumn"/> class using the
 /// specified column name.
 /// </summary>
 /// <param name="columnName">
 /// The name of the column.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// Thrown when the <paramref name="columnName"/> argument is <see langword="null"/>,
 /// an empty string, or a string containing only white-space characters.
 /// </exception>
 public SqlColumn(SqlIdentifier columnName)
     : this(columnName, null)
 {
 }