Build() public static méthode

public static Build ( IParseTree tree ) : SqlExpression
tree IParseTree
Résultat Deveel.Data.Sql.Expressions.SqlExpression
Exemple #1
0
        public static SqlStatement Statement(PlSqlParser.AssignmentStatementContext context)
        {
            SqlExpression varRef;

            if (context.general_element() != null)
            {
                var element = ElementNode.Form(context.general_element());
                if (element.Argument != null &&
                    element.Argument.Length > 0)
                {
                    throw new ParseCanceledException("Invalid assignment: cannot assign a function");
                }

                var name = element.Id;
                if (name.Parent != null)
                {
                    throw new ParseCanceledException("Invalid assignment.");
                }

                varRef = SqlExpression.VariableReference(name.ToString());
            }
            else if (context.bind_variable() != null)
            {
                var varName = Name.Variable(context.bind_variable());
                varRef = SqlExpression.VariableReference(varName);
            }
            else
            {
                throw new ParseCanceledException("Invalid assignment syntax");
            }

            var valueExp = Expression.Build(context.expression());

            return(new AssignVariableStatement(varRef, valueExp));
        }
        public override SqlStatement VisitVariableDeclaration(PlSqlParser.VariableDeclarationContext context)
        {
            var name = Name.Simple(context.variable_name());
            var type = SqlTypeParser.Parse(context.datatype());

            bool notNull  = context.NOT() != null && context.NULL() != null;
            bool constant = context.CONSTANT() != null;

            if (constant)
            {
                notNull = true;
            }

            SqlExpression defaultValue = null;

            if (context.defaultValuePart() != null)
            {
                defaultValue = Expression.Build(context.defaultValuePart().expression());
            }

            return(new DeclareVariableStatement(name, type)
            {
                DefaultExpression = defaultValue,
                IsNotNull = notNull,
                IsConstant = constant
            });
        }
        public override SqlExpression VisitTrimFunction(PlSqlParser.TrimFunctionContext context)
        {
            var arg1 = Expression.Build(context.concatenationWrapper());
            var part = "both";

            if (context.LEADING() != null)
            {
                part = "leading";
            }
            else if (context.TRAILING() != null)
            {
                part = "trailing";
            }
            else if (context.BOTH() != null)
            {
                part = "both";
            }

            var toTrim = " ";

            if (context.quoted_string() != null)
            {
                toTrim = InputString.AsNotQuoted(context.quoted_string());
            }

            var arg2 = SqlExpression.Constant(part);
            var arg3 = SqlExpression.Constant(toTrim);

            return(SqlExpression.FunctionCall("SQL_TRIM", new SqlExpression[] { arg1, arg2, arg3 }));
        }
Exemple #4
0
            public static SelectColumn BuildColumn(PlSqlParser.SelectedElementContext context)
            {
                string alias = null;

                if (context.column_alias() != null &&
                    !context.column_alias().IsEmpty)
                {
                    alias = Name.Simple(context.column_alias());
                }

                SelectColumn column;

                if (context.expression() != null &&
                    !context.expression().IsEmpty)
                {
                    column = new SelectColumn(Expression.Build(context.expression()), alias);
                }
                else if (context.selectedColumn() != null &&
                         !context.selectedColumn().IsEmpty)
                {
                    bool       glob = context.selectedColumn().glob != null;
                    ObjectName name = Name.Select(context.selectedColumn().objectName(), glob);

                    var exp = SqlExpression.Reference(name);
                    column = new SelectColumn(exp, alias);
                }
                else
                {
                    throw new ParseCanceledException();
                }

                return(column);
            }
        public override SqlStatement VisitLoopStatement(PlSqlParser.LoopStatementContext context)
        {
            LoopStatement loop;

            if (context.WHILE() != null)
            {
                var condition = Expression.Build(context.condition());
                loop = new WhileLoopStatement(condition);
            }
            else if (context.FOR() != null)
            {
                var param = context.cursorLoopParam();
                if (param.lowerBound() != null &&
                    param.upperBound() != null)
                {
                    var lower     = Expression.Build(param.lowerBound());
                    var upper     = Expression.Build(param.upperBound());
                    var indexName = Name.Simple(param.id());

                    var reverse = param.REVERSE() != null;
                    loop = new ForLoopStatement(indexName, lower, upper)
                    {
                        Reverse = reverse
                    };
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else
            {
                loop = new LoopStatement();
            }

            if (context.labelDeclaration() != null)
            {
                var labelName = Name.Simple(context.labelDeclaration().id());
                loop.Label = labelName;
            }

            var seqOfStatements = context.seqOfStatements();

            if (seqOfStatements != null)
            {
                var statements = seqOfStatements.statement().Select(Visit);
                foreach (var statement in statements)
                {
                    loop.Statements.Add(statement);
                }
            }

            return(loop);
        }
        public override SqlStatement VisitInsertStatement(PlSqlParser.InsertStatementContext context)
        {
            var singleTableInsert = context.singleTableInsert();
            var insertInto        = singleTableInsert.insertIntoClause();

            if (insertInto != null)
            {
                var tableName   = Name.Object(insertInto.objectName());
                var columnNames = new string[0];

                if (insertInto.columnName() != null)
                {
                    columnNames = insertInto.columnName().Select(Name.Simple).ToArray();
                }

                if (singleTableInsert.valuesClause() != null)
                {
                    var values = new List <SqlExpression[]>();
                    foreach (var listContext in singleTableInsert.valuesClause().expression_list())
                    {
                        var array = listContext.expression().Select(Expression.Build).ToArray();
                        values.Add(array);
                    }

                    return(new InsertStatement(tableName, columnNames, values));
                }

                if (singleTableInsert.subquery() != null)
                {
                    var query = Subquery.Form(singleTableInsert.subquery());
                    return(new InsertSelectStatement(tableName, columnNames, query));
                }
            }
            else if (singleTableInsert.insertSetClause() != null)
            {
                var tableName = Name.Object(singleTableInsert.insertSetClause().objectName());

                var columns = new List <string>();
                var values  = new List <SqlExpression>();

                foreach (var assignmentContext in singleTableInsert.insertSetClause().insertAssignment())
                {
                    var columnName = Name.Simple(assignmentContext.columnName());
                    var value      = Expression.Build(assignmentContext.expression());

                    columns.Add(columnName);
                    values.Add(value);
                }

                return(new InsertStatement(tableName, columns.ToArray(), new[] { values.ToArray() }));
            }

            return(base.VisitInsertStatement(context));
        }
        public override SqlStatement VisitReturnStatement(PlSqlParser.ReturnStatementContext context)
        {
            var           returnContext    = context.condition();
            SqlExpression returnExpression = null;

            if (returnContext != null)
            {
                returnExpression = Expression.Build(returnContext);
            }

            return(new ReturnStatement(returnExpression));
        }
Exemple #8
0
        public static UpdateStatement Build(PlSqlParser.UpdateStatementContext context)
        {
            var tableName   = Name.Object(context.objectName());
            var setClause   = context.updateSetClause();
            var limitClause = context.updateLimitClause();

            if (setClause != null)
            {
                var assignments = new List <SqlColumnAssignment>();
                var whereClause = context.whereClause();
                int limit       = -1;

                if (limitClause != null)
                {
                    limit = Number.PositiveInteger(limitClause.numeric()) ?? -1;
                }

                SqlExpression whereExpression = null;
                if (whereClause != null)
                {
                    whereExpression = Expression.Build(whereClause.conditionWrapper());
                }

                if (setClause.VALUE() != null)
                {
                    var columnName = Name.Simple(setClause.columnName());
                    var value      = Expression.Build(setClause.expression());

                    assignments.Add(new SqlColumnAssignment(columnName, value));
                }
                else
                {
                    var pairs = setClause.columnBasedUpdateClause().Select(x => new {
                        columnName = Name.Simple(x.columnName()),
                        value      = Expression.Build(x.expression())
                    });

                    assignments = pairs.Select(x => new SqlColumnAssignment(x.columnName, x.value)).ToList();
                }

                return(new UpdateStatement(tableName, whereExpression, assignments)
                {
                    Limit = limit
                });
            }
            if (context.updateFromClause() != null)
            {
                var query = Subquery.Form(context.updateFromClause().subquery());
            }

            throw new NotSupportedException();
        }
Exemple #9
0
        private static LoopControlStatement Build(LoopControlType controlType, PlSqlParser.LabelNameContext labelContext, PlSqlParser.ConditionContext conditionContext)
        {
            string        label          = null;
            SqlExpression whenExpression = null;

            if (labelContext != null)
            {
                label = Name.Simple(labelContext);
            }

            if (conditionContext != null)
            {
                whenExpression = Expression.Build(conditionContext.expression());
            }

            return(new LoopControlStatement(controlType, label, whenExpression));
        }
        public override SqlStatement VisitIfStatement(PlSqlParser.IfStatementContext context)
        {
            var conditions = new List <ConditionPart> {
                new ConditionPart {
                    Condition  = Expression.Build(context.condition()),
                    Statements = context.seqOfStatements().statement().Select(Visit).ToArray()
                }
            };

            foreach (var partContext in context.elsifPart())
            {
                conditions.Add(new ConditionPart {
                    Condition  = Expression.Build(partContext.condition()),
                    Statements = partContext.seqOfStatements().statement().Select(Visit).ToArray()
                });
            }

            if (context.elsePart() != null)
            {
                var statements = context.elsePart().seqOfStatements().statement().Select(Visit).ToArray();
                conditions.Add(new ConditionPart {
                    Condition  = SqlExpression.Constant(true),
                    Statements = statements
                });
            }

            ConditionStatement conditional = null;

            for (int i = conditions.Count - 1; i >= 0; i--)
            {
                var current = conditions[i];

                var condition = new ConditionStatement(current.Condition, current.Statements);

                if (conditional != null)
                {
                    conditional = new ConditionStatement(current.Condition, current.Statements, new SqlStatement[] { conditional });
                }
                else
                {
                    conditional = condition;
                }
            }

            return(conditional);
        }
            public static IAlterTableAction Build(PlSqlParser.AlterTableActionContext context)
            {
                if (context.addColumnAction() != null)
                {
                    var column = TableColumn.Form(context.addColumnAction().tableColumn(), new List <ColumnConstraint>());
                    return(new AddColumnAction(column));
                }
                if (context.addConstraintAction() != null)
                {
                    var constraint = TableConstraint.Form(context.addConstraintAction().tableConstraint());
                    return(new AddConstraintAction(constraint));
                }

                if (context.dropColumnAction() != null)
                {
                    var columnName = context.dropColumnAction().id().GetText();
                    return(new DropColumnAction(columnName));
                }

                if (context.dropConstraintAction() != null)
                {
                    var constraintName = context.dropConstraintAction().id().GetText();
                    return(new DropConstraintAction(constraintName));
                }

                if (context.dropPrimaryKeyAction() != null)
                {
                    return(new DropPrimaryKeyAction());
                }

                if (context.dropDefaultAction() != null)
                {
                    var columnName = Name.Simple(context.dropDefaultAction().columnName());
                    return(new DropDefaultAction(columnName));
                }

                if (context.setDefaultAction() != null)
                {
                    var columnName   = Name.Simple(context.setDefaultAction().columnName());
                    var defaultValue = Expression.Build(context.setDefaultAction().expressionWrapper());
                    return(new SetDefaultAction(columnName, defaultValue));
                }

                throw new ParseCanceledException("The ALTER TABLE action is not supported");
            }
Exemple #12
0
        public static CreateViewStatement Create(PlSqlParser.CreateViewStatementContext context)
        {
            var orReplace = context.OR() != null && context.REPLACE() != null;

            var viewName = Name.Object(context.objectName());
            var query    = (SqlQueryExpression)Expression.Build(context.subquery());

            string[] columnNames = null;
            if (context.columnList() != null)
            {
                columnNames = context.columnList().columnName().Select(Name.Simple).ToArray();
            }

            return(new CreateViewStatement(viewName, columnNames, query)
            {
                ReplaceIfExists = orReplace
            });
        }
        public override SqlStatement VisitSimpleCaseStatement(PlSqlParser.SimpleCaseStatementContext context)
        {
            var exp = Expression.Build(context.atom());

            var switches = new List <CaseSwitch>();

            foreach (var partContext in context.simpleCaseWhenPart())
            {
                var otherExp = Expression.Build(partContext.expressionWrapper());
                switches.Add(new CaseSwitch {
                    Condition        = SqlExpression.Equal(exp, otherExp),
                    ReturnStatements = partContext.seqOfStatements().statement().Select(Visit).ToArray()
                });
            }

            if (context.caseElsePart() != null)
            {
                var returnstatements = context.caseElsePart().seqOfStatements().statement().Select(Visit).ToArray();
                switches.Add(new CaseSwitch {
                    Condition        = SqlExpression.Constant(true),
                    ReturnStatements = returnstatements
                });
            }

            ConditionStatement conditional = null;

            for (int i = switches.Count - 1; i >= 0; i--)
            {
                var current = switches[i];

                var condition = new ConditionStatement(current.Condition, current.ReturnStatements);

                if (conditional != null)
                {
                    conditional = new ConditionStatement(current.Condition, current.ReturnStatements, new SqlStatement[] { conditional });
                }
                else
                {
                    conditional = condition;
                }
            }

            return(conditional);
        }
        public static RoutineParameter Routine(PlSqlParser.ParameterContext context)
        {
            var paramName = Name.Simple(context.parameter_name());
            var paramType = SqlTypeParser.Parse(context.datatype());

            var paramDir = ParameterDirection.Input;

            if (context.IN() != null)
            {
                if (context.OUT() != null)
                {
                    paramDir = ParameterDirection.InputOutput;
                }
                else
                {
                    paramDir = ParameterDirection.Input;
                }
            }
            else if (context.OUT() != null)
            {
                paramDir = ParameterDirection.Output;
            }
            else if (context.INOUT() != null)
            {
                paramDir = ParameterDirection.InputOutput;
            }

            SqlExpression defaultValue = null;
            var           defaultPart  = context.defaultValuePart();

            if (defaultPart != null)
            {
                defaultValue = Expression.Build(defaultPart.expression());
            }

            // TODO: Support default in RoutineParameter
            return(new RoutineParameter(paramName, paramType, paramDir));
        }
Exemple #15
0
        public static SqlStatement Build(PlSqlParser.SelectStatementContext context)
        {
            IntoClause into;
            var        query = Subquery.Form(context.subquery(), out into);

            if (into != null)
            {
                SqlExpression reference;
                if (into.TableName != null)
                {
                    reference = SqlExpression.Reference(into.TableName);
                }
                else
                {
                    var vars = into.Variables;
                    reference = SqlExpression.Tuple(vars.Select(SqlExpression.VariableReference).Cast <SqlExpression>().ToArray());
                }

                return(new SelectIntoStatement(query, reference));
            }

            var statement = new SelectStatement(query);

            var orderBy   = context.orderByClause();
            var forUpdate = context.forUpdateClause();

            if (orderBy != null)
            {
                var sortColumns = orderBy.orderByElements().orderByElement().Select(x => {
                    bool asc = x.DESC() == null;
                    var exp  = Expression.Build(x.expression());
                    return(new SortColumn(exp, asc));
                });

                statement.OrderBy = sortColumns;
            }

            statement.ForUpdate = forUpdate != null;

            var limit = context.queryLimitClause();

            if (limit != null)
            {
                var n1 = Number.PositiveInteger(limit.n1);
                var n2 = Number.PositiveInteger(limit.n2);

                if (n1 == null)
                {
                    throw new ParseCanceledException("Invalid LIMIT clause");
                }

                if (n2 != null)
                {
                    statement.Limit = new QueryLimit(n1.Value, n2.Value);
                }
                else
                {
                    statement.Limit = new QueryLimit(n1.Value);
                }
            }

            return(statement);
        }
        public static SqlTableConstraint Form(PlSqlParser.TableConstraintContext context)
        {
            string constraintName = Name.Simple(context.id());

            ConstraintType type;

            string[] columns  = null;
            string   refTable = null;

            string[]         refColumns = null;
            SqlExpression    checkExp   = null;
            ForeignKeyAction?onDelete   = null;
            ForeignKeyAction?onUpdate   = null;

            if (context.primaryKeyConstraint() != null)
            {
                type = ConstraintType.PrimaryKey;

                columns = context.primaryKeyConstraint().columnList().columnName().Select(Name.Simple).ToArray();
            }
            else if (context.uniqueKeyConstraint() != null)
            {
                type    = ConstraintType.Unique;
                columns = context.uniqueKeyConstraint().columnList().columnName().Select(Name.Simple).ToArray();
            }
            else if (context.checkConstraint() != null)
            {
                type     = ConstraintType.Check;
                checkExp = Expression.Build(context.checkConstraint().expression());
            }
            else if (context.foreignKeyConstraint() != null)
            {
                type       = ConstraintType.ForeignKey;
                columns    = context.foreignKeyConstraint().columns.columnName().Select(Name.Simple).ToArray();
                refColumns = context.foreignKeyConstraint().refColumns.columnName().Select(Name.Simple).ToArray();
                refTable   = Name.Object(context.foreignKeyConstraint().objectName()).ToString();
                var refActions = context.foreignKeyConstraint().referentialAction();
                if (refActions != null && refActions.Length > 0)
                {
                    foreach (var action in refActions)
                    {
                        if (action.onDelete() != null)
                        {
                            var actionType = GetForeignKeyAction(action.onDelete().referentialActionType().GetText());
                            onDelete = actionType;
                        }
                        else if (action.onUpdate() != null)
                        {
                            var actionType = GetForeignKeyAction(action.onUpdate().referentialActionType().GetText());
                            onUpdate = actionType;
                        }
                    }
                }
            }
            else
            {
                throw new ParseCanceledException("Invalid ");
            }

            var constraint = new SqlTableConstraint(constraintName, type, columns);

            if (type == ConstraintType.ForeignKey)
            {
                constraint.ReferenceTable   = refTable;
                constraint.ReferenceColumns = refColumns;
                constraint.OnUpdate         = onUpdate ?? ForeignKeyAction.NoAction;
                constraint.OnDelete         = onDelete ?? ForeignKeyAction.NoAction;
            }
            else if (type == ConstraintType.Check)
            {
                constraint.CheckExpression = checkExp;
            }

            return(constraint);
        }
        public static SqlTableColumn Form(PlSqlParser.TableColumnContext context, List <ColumnConstraint> constraints)
        {
            var columnName = Name.Simple(context.columnName());
            var columnType = SqlTypeParser.Parse(context.datatype());

            if (columnType == null)
            {
                throw new ParseCanceledException("No type was found for table.");
            }

            SqlExpression defaultExpression = null;
            bool          identity          = false;
            bool          nullable          = true;
            string        indexType         = null;

            if (context.IDENTITY() != null)
            {
                if (!(columnType is NumericType))
                {
                    throw new InvalidOperationException("Cannot have an identity column that has not a numeric type");
                }

                identity = true;
            }
            else
            {
                var columnConstraints = context.columnConstraint();
                if (columnConstraints != null &&
                    columnConstraints.Length > 0)
                {
                    foreach (var constraintContext in columnConstraints)
                    {
                        if (constraintContext.PRIMARY() != null)
                        {
                            constraints.Add(new ColumnConstraint {
                                ColumnName = columnName,
                                Type       = ConstraintType.PrimaryKey
                            });
                        }
                        else if (constraintContext.UNIQUE() != null)
                        {
                            constraints.Add(new ColumnConstraint {
                                Type       = ConstraintType.Unique,
                                ColumnName = columnName
                            });
                        }
                        else if (constraintContext.NOT() != null &&
                                 constraintContext.NULL() != null)
                        {
                            nullable = false;
                        }
                    }
                }

                if (context.defaultValuePart() != null)
                {
                    defaultExpression = Expression.Build(context.defaultValuePart().expression());
                }

                if (context.columnIndex() != null)
                {
                    var columnIndex = context.columnIndex();
                    if (columnIndex.BLIST() != null)
                    {
                        indexType = DefaultIndexTypes.InsertSearch;
                    }
                    else if (columnIndex.NONE() != null)
                    {
                        indexType = DefaultIndexTypes.BlindSearch;
                    }
                    else if (columnIndex.id() != null)
                    {
                        indexType = Name.Simple(columnIndex.id());
                    }
                    else if (columnIndex.CHAR_STRING() != null)
                    {
                        indexType = InputString.AsNotQuoted(columnIndex.CHAR_STRING());
                    }
                }
            }

            return(new SqlTableColumn(columnName, columnType)
            {
                IsNotNull = !nullable,
                IsIdentity = identity,
                DefaultExpression = defaultExpression,
                IndexType = indexType
            });
        }