Search in sources :

Example 6 with DbException

use of com.wplatform.ddal.message.DbException in project jdbc-shards by wplatform.

the class MergeExecutor method executeUpdate.

@Override
public int executeUpdate() {
    Column[] columns = prepared.getColumns();
    TableMate table = castTableMate(prepared.getTable());
    ArrayList<Expression[]> list = prepared.getList();
    table.check();
    int count;
    session.getUser().checkRight(table, Right.INSERT);
    session.getUser().checkRight(table, Right.UPDATE);
    prepared.setCurrentRowNumber(0);
    if (list.size() > 0) {
        count = 0;
        for (int x = 0, size = list.size(); x < size; x++) {
            prepared.setCurrentRowNumber(x + 1);
            Expression[] expr = list.get(x);
            Row newRow = table.getTemplateRow();
            for (int i = 0, len = columns.length; i < len; i++) {
                Column c = columns[i];
                int index = c.getColumnId();
                Expression e = expr[i];
                if (e != null) {
                    // e can be null (DEFAULT)
                    try {
                        Value v = c.convert(e.getValue(session));
                        newRow.setValue(index, v);
                    } catch (DbException ex) {
                        throw prepared.setRow(ex, count, Prepared.getSQL(expr));
                    }
                }
            }
            merge(newRow);
            count++;
        }
    } else {
        Query query = prepared.getQuery();
        ResultInterface rows = query.query(0);
        count = 0;
        while (rows.next()) {
            count++;
            Value[] r = rows.currentRow();
            Row newRow = table.getTemplateRow();
            prepared.setCurrentRowNumber(count);
            for (int j = 0; j < columns.length; j++) {
                Column c = columns[j];
                int index = c.getColumnId();
                try {
                    Value v = c.convert(r[j]);
                    newRow.setValue(index, v);
                } catch (DbException ex) {
                    throw prepared.setRow(ex, count, Prepared.getSQL(r));
                }
            }
            merge(newRow);
        }
        rows.close();
    }
    return count;
}
Also used : ResultInterface(com.wplatform.ddal.result.ResultInterface) Query(com.wplatform.ddal.command.dml.Query) DbException(com.wplatform.ddal.message.DbException) Column(com.wplatform.ddal.dbobject.table.Column) Expression(com.wplatform.ddal.command.expression.Expression) Value(com.wplatform.ddal.value.Value) TableMate(com.wplatform.ddal.dbobject.table.TableMate) Row(com.wplatform.ddal.result.Row) SearchRow(com.wplatform.ddal.result.SearchRow)

Example 7 with DbException

use of com.wplatform.ddal.message.DbException in project jdbc-shards by wplatform.

the class CreateTableExecutor method executeUpdate.

@Override
public int executeUpdate() {
    String tableName = prepared.getTableName();
    TableMate tableMate = getTableMate(tableName);
    if (tableMate == null) {
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
    }
    if (!tableMate.isInited()) {
        if (prepared.isIfNotExists()) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, tableName);
    }
    Query query = prepared.getQuery();
    if (query != null) {
        query.prepare();
        if (prepared.getColumnCount() == 0) {
            generateColumnsFromQuery();
        } else if (prepared.getColumnCount() != query.getColumnCount()) {
            throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
        }
    }
    ArrayList<Sequence> sequences = New.arrayList();
    for (Column c : tableMate.getColumns()) {
        if (c.isAutoIncrement()) {
            c.convertAutoIncrementToSequence(session, database.getSchema(session.getCurrentSchemaName()), tableMate.getId(), prepared.isTemporary());
        }
        Sequence seq = c.getSequence();
        if (seq != null) {
            sequences.add(seq);
        }
    }
    try {
        for (Column c : tableMate.getColumns()) {
            c.prepareExpression(session);
        }
        for (Sequence sequence : sequences) {
            tableMate.addSequence(sequence);
        }
        for (DefineCommand command : prepared.getConstraintCommands()) {
            if (command.getType() == CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL) {
                AlterTableAddConstraint stmt = (AlterTableAddConstraint) command;
                String refTableName = stmt.getRefTableName();
                TableMate refTable = getTableMate(refTableName);
                if (refTable != null && refTable.getPartitionNode().length > 1) {
                    TableNode[] tableNodes = tableMate.getPartitionNode();
                    TableNode[] refTableNodes = refTable.getPartitionNode();
                    Map<TableNode, TableNode> symmetryRelation = getSymmetryRelation(tableNodes, refTableNodes);
                    if (symmetryRelation == null) {
                        throw DbException.get(ErrorCode.CHECK_CONSTRAINT_INVALID, "Create foreign key for table,the original table and the reference table should be symmetrical.");
                    }
                }
            }
        }
        TableNode[] nodes = tableMate.getPartitionNode();
        execute(nodes);
        if (query != null) {
            Insert insert = new Insert(session);
            insert.setSortedInsertMode(prepared.isSortedInsertMode());
            insert.setQuery(query);
            insert.setTable(tableMate);
            insert.setInsertFromSelect(true);
            insert.prepare();
            insert.update();
        }
    } catch (DbException e) {
        throw e;
    }
    tableMate.loadMataData(session);
    return 0;
}
Also used : AlterTableAddConstraint(com.wplatform.ddal.command.ddl.AlterTableAddConstraint) Query(com.wplatform.ddal.command.dml.Query) Sequence(com.wplatform.ddal.dbobject.schema.Sequence) Insert(com.wplatform.ddal.command.dml.Insert) DefineCommand(com.wplatform.ddal.command.ddl.DefineCommand) DbException(com.wplatform.ddal.message.DbException) IndexColumn(com.wplatform.ddal.dbobject.table.IndexColumn) Column(com.wplatform.ddal.dbobject.table.Column) TableNode(com.wplatform.ddal.dispatch.rule.TableNode) TableMate(com.wplatform.ddal.dbobject.table.TableMate)

Example 8 with DbException

use of com.wplatform.ddal.message.DbException in project jdbc-shards by wplatform.

the class TableView method initColumnsAndTables.

private void initColumnsAndTables(Session session) {
    Column[] cols;
    //removeViewFromTables();
    try {
        Query query = compileViewQuery(session, querySQL);
        this.querySQL = query.getPlanSQL();
        tables = New.arrayList(query.getTables());
        ArrayList<Expression> expressions = query.getExpressions();
        ArrayList<Column> list = New.arrayList();
        for (int i = 0, count = query.getColumnCount(); i < count; i++) {
            Expression expr = expressions.get(i);
            String name = null;
            if (columnNames != null && columnNames.length > i) {
                name = columnNames[i];
            }
            if (name == null) {
                name = expr.getAlias();
            }
            int type = expr.getType();
            long precision = expr.getPrecision();
            int scale = expr.getScale();
            int displaySize = expr.getDisplaySize();
            Column col = new Column(name, type, precision, scale, displaySize);
            col.setTable(this, i);
            // Fetch check constraint from view column source
            ExpressionColumn fromColumn = null;
            if (expr instanceof ExpressionColumn) {
                fromColumn = (ExpressionColumn) expr;
            } else if (expr instanceof Alias) {
                Expression aliasExpr = expr.getNonAliasExpression();
                if (aliasExpr instanceof ExpressionColumn) {
                    fromColumn = (ExpressionColumn) aliasExpr;
                }
            }
            if (fromColumn != null) {
                Expression checkExpression = fromColumn.getColumn().getCheckConstraint(session, name);
                if (checkExpression != null) {
                    col.addCheckConstraint(session, checkExpression);
                }
            }
            list.add(col);
        }
        cols = new Column[list.size()];
        list.toArray(cols);
        createException = null;
        viewQuery = query;
    } catch (DbException e) {
        e.addSQL(querySQL);
        createException = e;
        // if it can't be compiled, then it's a 'zero column table'
        // this avoids problems when creating the view when opening the
        // database
        tables = New.arrayList();
        cols = new Column[0];
        if (recursive && columnNames != null) {
            cols = new Column[columnNames.length];
            for (int i = 0; i < columnNames.length; i++) {
                cols[i] = new Column(columnNames[i], Value.STRING);
            }
            //index.setRecursive(true);
            createException = null;
        }
    }
    setColumns(cols);
    if (getId() != 0) {
    //addViewToTables();
    }
}
Also used : Query(com.wplatform.ddal.command.dml.Query) DbException(com.wplatform.ddal.message.DbException)

Example 9 with DbException

use of com.wplatform.ddal.message.DbException in project jdbc-shards by wplatform.

the class TableMate method loadMataData.

public void loadMataData(Session session) {
    TableNode[] nodes = getPartitionNode();
    if (nodes == null || nodes.length < 1) {
        throw new IllegalStateException();
    }
    TableNode matadataNode = nodes[0];
    String tableName = matadataNode.getCompositeObjectName();
    String shardName = matadataNode.getShardName();
    try {
        trace.debug("Try to load {0} metadata from table {1}.{2}", getName(), shardName, tableName);
        readMataData(session, matadataNode);
        trace.debug("Load the {0} metadata success.", getName());
        initException = null;
    } catch (DbException e) {
        trace.debug("Fail to load {0} metadata from table {1}.{2}. error: {3}", getName(), shardName, tableName, e.getCause().getMessage());
        initException = e;
        Column[] cols = {};
        setColumns(cols);
        scanIndex = new IndexMate(this, 0, null, IndexColumn.wrap(cols), IndexType.createNonUnique());
        indexes.add(scanIndex);
    }
}
Also used : TableNode(com.wplatform.ddal.dispatch.rule.TableNode) IndexMate(com.wplatform.ddal.dbobject.index.IndexMate) DbException(com.wplatform.ddal.message.DbException)

Example 10 with DbException

use of com.wplatform.ddal.message.DbException in project jdbc-shards by wplatform.

the class TableMate method readMataData.

/**
     * @param session
     */
public void readMataData(Session session, TableNode matadataNode) {
    for (int retry = 0; ; retry++) {
        try {
            Connection conn = null;
            String tableName = matadataNode.getCompositeObjectName();
            String shardName = matadataNode.getShardName();
            try {
                DataSourceRepository dsRepository = session.getDataSourceRepository();
                DataSource dataSource = dsRepository.getDataSourceByShardName(shardName);
                Optional optional = Optional.build().shardName(shardName).readOnly(false);
                conn = session.applyConnection(dataSource, optional);
                tableName = database.identifier(tableName);
                tryReadMetaData(conn, tableName);
                return;
            } catch (Exception e) {
                throw DbException.convert(e);
            } finally {
                JdbcUtils.closeSilently(conn);
            }
        } catch (DbException e) {
            if (retry >= MAX_RETRY) {
                throw e;
            }
        }
    }
}
Also used : DataSourceRepository(com.wplatform.ddal.shards.DataSourceRepository) Optional(com.wplatform.ddal.excutor.Optional) Connection(java.sql.Connection) SQLException(java.sql.SQLException) DbException(com.wplatform.ddal.message.DbException) DataSource(javax.sql.DataSource) DbException(com.wplatform.ddal.message.DbException)

Aggregations

DbException (com.wplatform.ddal.message.DbException)14 TableMate (com.wplatform.ddal.dbobject.table.TableMate)8 Column (com.wplatform.ddal.dbobject.table.Column)7 Value (com.wplatform.ddal.value.Value)6 Query (com.wplatform.ddal.command.dml.Query)5 Row (com.wplatform.ddal.result.Row)5 SearchRow (com.wplatform.ddal.result.SearchRow)5 Expression (com.wplatform.ddal.command.expression.Expression)4 ResultInterface (com.wplatform.ddal.result.ResultInterface)3 SQLException (java.sql.SQLException)3 TableNode (com.wplatform.ddal.dispatch.rule.TableNode)2 Database (com.wplatform.ddal.engine.Database)2 Prepared (com.wplatform.ddal.command.Prepared)1 AlterTableAddConstraint (com.wplatform.ddal.command.ddl.AlterTableAddConstraint)1 DefineCommand (com.wplatform.ddal.command.ddl.DefineCommand)1 Insert (com.wplatform.ddal.command.dml.Insert)1 Parameter (com.wplatform.ddal.command.expression.Parameter)1 IndexMate (com.wplatform.ddal.dbobject.index.IndexMate)1 Sequence (com.wplatform.ddal.dbobject.schema.Sequence)1 IndexColumn (com.wplatform.ddal.dbobject.table.IndexColumn)1