Java Code Examples for io.debezium.relational.ColumnEditor

Following code examples demonstrate how to use io.debezium.relational.ColumnEditorfrom debezium. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use io.debezium.relational.ColumnEditorand various code implementation of this class.

    public ColumnDefinitionParserListener(TableEditor tableEditor, ColumnEditor columnEditor, DataTypeResolver dataTypeResolver, MySqlValueConverters converters) {
        this.tableEditor = tableEditor;
        this.columnEditor = columnEditor;
        this.dataTypeResolver = dataTypeResolver;
        this.converters = converters;
    } 


    private void convertDefaultValueToSchemaType(ColumnEditor columnEditor) {
        final Column column = columnEditor.create();
        if (converters != null && columnEditor.defaultValue() != null) {
            Object defaultValue = columnEditor.defaultValue();
            final SchemaBuilder schemaBuilder = converters.schemaBuilder(column);
            if (schemaBuilder == null) {
                return;
            }
            final Schema schema = schemaBuilder.build();
            final Field field = new Field(column.name(), -1, schema);
            final ValueConverter valueConverter = converters.converter(column, field);
            if (defaultValue instanceof String) {
                defaultValue = defaultValuePreConverter.convert(column, (String)defaultValue);
            }
            defaultValue = valueConverter.convert(defaultValue);
            columnEditor.defaultValue(defaultValue);
        }
    } 

    public void enterDefaultValue(DefaultValueContext ctx) {
        String sign = "";
        if (ctx.NULL_LITERAL() != null) {
            return;
        }
        if (ctx.unaryOperator() != null) {
            sign = ctx.unaryOperator().getText();
        }
        if (ctx.constant() != null) {
            if (ctx.constant().stringLiteral() != null) {
                columnEditor.defaultValue(sign + unquote(ctx.constant().stringLiteral().getText()));
            }
            else if (ctx.constant().decimalLiteral() != null) {
                columnEditor.defaultValue(sign + ctx.constant().decimalLiteral().getText());
            }
            else if (ctx.constant().BIT_STRING() != null) {
                columnEditor.defaultValue(unquoteBinary(ctx.constant().BIT_STRING().getText()));
            }
            else if (ctx.constant().booleanLiteral() != null) {
                columnEditor.defaultValue(ctx.constant().booleanLiteral().getText());
            }
            else if (ctx.constant().REAL_LITERAL() != null) {
                columnEditor.defaultValue(ctx.constant().REAL_LITERAL().getText());
            }
        }
        else if (ctx.timeDefinition() != null) {
            if (ctx.timeDefinition().CURRENT_TIMESTAMP() != null || ctx.timeDefinition().NOW() != null) {
                columnEditor.defaultValue("1970-01-01 00:00:00");
            }
            else {
                columnEditor.defaultValue(ctx.timeDefinition().getText());
            }
        }
        convertDefaultValueToSchemaType(columnEditor);
        super.enterDefaultValue(ctx);
    } 

    public Table getTableSchemaFromChangeTable(ChangeTable changeTable) throws SQLException {
        final DatabaseMetaData metadata = connection().getMetaData();
        final TableId changeTableId = changeTable.getChangeTableId();

        List<ColumnEditor> columnEditors = new ArrayList<>();
        try (ResultSet rs = metadata.getColumns(realDatabaseName, changeTableId.schema(), changeTableId.table(), null)) {
            while (rs.next()) {
                readTableColumn(rs, changeTableId, null).ifPresent(columnEditors::add);
            }
        }

        final List<Column> columns = columnEditors.subList(CHANGE_TABLE_DATA_COLUMN_OFFSET, columnEditors.size() - 1).stream()
                .map(c -> c.position(c.position() - CHANGE_TABLE_DATA_COLUMN_OFFSET).create())
                .collect(Collectors.toList());

        final List<String> pkColumnNames = new ArrayList<>();
        prepareQuery(GET_LIST_OF_KEY_COLUMNS, ps -> ps.setInt(1, changeTable.getChangeTableObjectId()), rs -> {
            while (rs.next()) {
                pkColumnNames.add(rs.getString(2));
            }
        });
        Collections.sort(columns);
        return Table.editor()
            .tableId(changeTable.getSourceTableId())
            .addColumns(columns)
            .setPrimaryKeyNames(pkColumnNames)
            .create();
    } 

        private static Table fromDocument(TableId id, Document document) {
            TableEditor editor = Table.editor()
                .tableId(id)
                .setDefaultCharsetName(document.getString("defaultCharsetName"));

            document.getArray("columns")
                .streamValues()
                .map(Value::asDocument)
                .map(v -> {
                    ColumnEditor columnEditor = Column.editor()
                        .name(v.getString("name"))
                        .jdbcType(v.getInteger("jdbcType"));

                        Integer nativeType = v.getInteger("nativeType");
                        if (nativeType != null) {
                            columnEditor.nativeType(nativeType);
                        }

                       columnEditor.type(v.getString("typeName"), v.getString("typeExpression"))
                           .charsetName(v.getString("charsetName"));

                       Integer length = v.getInteger("length");
                       if (length != null) {
                           columnEditor.length(length);
                       }

                       Integer scale = v.getInteger("scale");
                       if (scale != null) {
                           columnEditor.scale(scale);
                       }

                       columnEditor.position(v.getInteger("position"))
                           .optional(v.getBoolean("optional"))
                           .autoIncremented(v.getBoolean("autoIncremented"))
                           .generated(v.getBoolean("generated"));

                    return columnEditor.create();
                })
                .forEach(editor::addColumn);

            editor.setPrimaryKeyNames(document.getArray("primaryKeyColumnNames")
                .streamValues()
                .map(Value::asString)
                .collect(Collectors.toList()));

            return editor.create();
        } 

        private void setScale(Precision_partContext precisionPart, ColumnEditor columnEditor) {
            if (precisionPart.numeric().size() > 1) {
                columnEditor.scale(Integer.valueOf(precisionPart.numeric(1).getText()));
            }
            else if (precisionPart.numeric_negative() != null) {
                columnEditor.scale(Integer.valueOf(precisionPart.numeric_negative().getText()));
            }
            else {
                columnEditor.scale(0);
            }
        } 

    public void enterAlterByChangeDefault(MySqlParser.AlterByChangeDefaultContext ctx) {
        parserCtx.runIfNotNull(() -> {
            String columnName = parserCtx.parseName(ctx.uid());
            Column column = tableEditor.columnWithName(columnName);
            if (column != null) {
                ColumnEditor columnEditor = column.edit();
                columnEditor.generated(ctx.DROP() != null);
            }
        }, tableEditor);
        super.enterAlterByChangeDefault(ctx);
    } 

    public void enterAlterByAddColumn(MySqlParser.AlterByAddColumnContext ctx) {
        parserCtx.runIfNotNull(() -> {
            String columnName = parserCtx.parseName(ctx.uid(0));
            ColumnEditor columnEditor = Column.editor().name(columnName);
            columnDefinitionListener = new ColumnDefinitionParserListener(tableEditor, columnEditor, parserCtx.dataTypeResolver());
            listeners.add(columnDefinitionListener);
        }, tableEditor);
        super.exitAlterByAddColumn(ctx);
    } 

    public void exitAlterByAddColumns(MySqlParser.AlterByAddColumnsContext ctx) {
        parserCtx.runIfNotNull(() -> {
            columnEditors.forEach(columnEditor -> tableEditor.addColumn(columnEditor.create()));
        }, tableEditor, columnEditors);
        super.exitAlterByAddColumns(ctx);
    } 

    public void enterColumnDeclaration(MySqlParser.ColumnDeclarationContext ctx) {
        parser.runIfNotNull(() -> {
            String columnName = parser.parseName(ctx.uid());
            ColumnEditor columnEditor = Column.editor().name(columnName);
            if (columnDefinitionListener == null) {
                columnDefinitionListener = new ColumnDefinitionParserListener(tableEditor, columnEditor, parser.dataTypeResolver(), parser.getConverters());
                listeners.add(columnDefinitionListener);
            } else {
                columnDefinitionListener.setColumnEditor(columnEditor);
            }
        }, tableEditor);
        super.enterColumnDeclaration(ctx);
    } 

    protected Column createColumnFromConstant(String columnName, String constantValue) {
        ColumnEditor column = Column.editor().name(columnName);
        try {
            if (constantValue.startsWith("'") || constantValue.startsWith("\"")) {
                column.type("CHAR");
                column.jdbcType(Types.CHAR);
                column.length(constantValue.length() - 2);
            }
            else if (constantValue.equalsIgnoreCase("TRUE") || constantValue.equalsIgnoreCase("FALSE")) {
                column.type("BOOLEAN");
                column.jdbcType(Types.BOOLEAN);
            }
            else {
                setTypeInfoForConstant(constantValue, column);
            }
        }
        catch (Throwable t) {
            logger.debug("Unable to create an artificial column for the constant: " + constantValue);
        }
        return column.create();
    } 

    protected void setTypeInfoForConstant(String constantValue, ColumnEditor column) {
        try {
            Integer.parseInt(constantValue);
            column.type("INTEGER");
            column.jdbcType(Types.INTEGER);
        }
        catch (NumberFormatException e) {
        }
        try {
            Long.parseLong(constantValue);
            column.type("BIGINT");
            column.jdbcType(Types.BIGINT);
        }
        catch (NumberFormatException e) {
        }
        try {
            Float.parseFloat(constantValue);
            column.type("FLOAT");
            column.jdbcType(Types.FLOAT);
        }
        catch (NumberFormatException e) {
        }
        try {
            Double.parseDouble(constantValue);
            column.type("DOUBLE");
            column.jdbcType(Types.DOUBLE);
            int precision = 0;
            int scale = 0;
            boolean foundDecimalPoint = false;
            for (int i = 0; i < constantValue.length(); i++) {
                char c = constantValue.charAt(i);
                if (c == '+' || c == '-') {
                    continue;
                }
                else if (c == '.') {
                    foundDecimalPoint = true;
                }
                else if (Character.isDigit(c)) {
                    if (foundDecimalPoint)
                        ++scale;
                    else
                        ++precision;
                }
                else {
                    break;
                }
            }
            column.length(precision);
            column.scale(scale);
        }
        catch (NumberFormatException e) {
        }
        try {
            BigDecimal decimal = new BigDecimal(constantValue);
            column.type("DECIMAL");
            column.jdbcType(Types.DECIMAL);
            column.length(decimal.precision());
            column.scale(decimal.precision());
        }
        catch (NumberFormatException e) {
        }
    } 

Advertisement
Javadoc
An editor for Column instances. @author Randall Hauch
Advertisement