Esempio n. 1
0
        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;
        }