Search in sources :

Example 1 with ExtendedSqlException

use of com.developmentontheedge.dbms.ExtendedSqlException in project be5 by DevelopmentOnTheEdge.

the class TableDef method isSafeTypeUpdate.

private boolean isSafeTypeUpdate(ColumnDef oldColumn, ColumnDef column, DbmsTypeManager typeManager, SqlExecutor sql) throws ExtendedSqlException {
    SqlColumnType oldType = oldColumn.getType();
    SqlColumnType type = column.getType();
    if (typeManager.getTypeClause(oldType).equals(typeManager.getTypeClause(type)))
        return true;
    // Enlarging VARCHAR column
    if (oldType.getTypeName().equals(TYPE_VARCHAR) && type.getTypeName().equals(TYPE_VARCHAR)) {
        if (type.getSize() >= oldType.getSize())
            return true;
        return sql != null && !sql.hasResult("sql.select.longer", typeManager.normalizeIdentifier(getEntityName()), typeManager.normalizeIdentifier(oldColumn.getName()), type.getSize());
    }
    // Enlarging DECIMAL column
    if (oldType.getTypeName().equals(TYPE_DECIMAL) && type.getTypeName().equals(TYPE_DECIMAL)) {
        if (type.getSize() >= oldType.getSize() && type.getPrecision() >= oldType.getPrecision())
            return true;
    }
    // Adding new variants for ENUM column
    if ((oldType.getTypeName().equals(TYPE_ENUM) || oldType.getTypeName().equals(TYPE_BOOL) || oldType.getTypeName().equals(TYPE_VARCHAR)) && (type.getTypeName().equals(TYPE_ENUM) || type.getTypeName().equals(TYPE_BOOL))) {
        List<String> newValues = Arrays.asList(type.getEnumValues());
        if (!oldType.getTypeName().equals(TYPE_VARCHAR) && newValues.containsAll(Arrays.asList(oldType.getEnumValues())))
            return true;
        return sql != null && !sql.hasResult("sql.select.not.in.range", typeManager.normalizeIdentifier(getEntityName()), typeManager.normalizeIdentifier(oldColumn.getName()), MetadataUtils.toInClause(newValues));
    }
    // Changing ENUM to varchar
    if ((oldType.getTypeName().equals(TYPE_ENUM) || oldType.getTypeName().equals(TYPE_BOOL)) && type.getTypeName().equals(TYPE_VARCHAR)) {
        int len = 0;
        for (String value : oldType.getEnumValues()) {
            len = Math.max(len, value.length());
        }
        if (type.getSize() >= len)
            return true;
        return sql != null && !sql.hasResult("sql.select.longer", typeManager.normalizeIdentifier(getEntityName()), typeManager.normalizeIdentifier(oldColumn.getName()), type.getSize());
    }
    // Changing ENUM to char
    if (oldType.getTypeName().equals(TYPE_ENUM) && type.getTypeName().equals(TYPE_CHAR)) {
        return StreamEx.of(oldType.getEnumValues()).map(String::length).distinct().collect(MoreCollectors.onlyOne()).filter(len -> type.getSize() == len).isPresent();
    }
    return false;
}
Also used : DbmsTypeManager(com.developmentontheedge.be5.metadata.sql.type.DbmsTypeManager) Arrays(java.util.Arrays) BeCaseInsensitiveCollection(com.developmentontheedge.be5.metadata.model.base.BeCaseInsensitiveCollection) SqlExecutor(com.developmentontheedge.dbms.SqlExecutor) Iterator(java.util.Iterator) BeVectorCollection(com.developmentontheedge.be5.metadata.model.base.BeVectorCollection) MoreCollectors(one.util.streamex.MoreCollectors) ProjectElementException(com.developmentontheedge.be5.metadata.exception.ProjectElementException) Set(java.util.Set) MetadataUtils(com.developmentontheedge.be5.metadata.MetadataUtils) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) Rdbms(com.developmentontheedge.be5.metadata.sql.Rdbms) ArrayList(java.util.ArrayList) BeModelElement(com.developmentontheedge.be5.metadata.model.base.BeModelElement) List(java.util.List) Strings2(com.developmentontheedge.be5.metadata.util.Strings2) PropertyName(com.developmentontheedge.beans.annot.PropertyName) StreamEx(one.util.streamex.StreamEx) SqlColumnType(com.developmentontheedge.be5.metadata.model.SqlColumnType) Map(java.util.Map) ExtendedSqlException(com.developmentontheedge.dbms.ExtendedSqlException) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) SqlColumnType(com.developmentontheedge.be5.metadata.model.SqlColumnType)

Example 2 with ExtendedSqlException

use of com.developmentontheedge.dbms.ExtendedSqlException in project be5 by DevelopmentOnTheEdge.

the class AppSync method execute.

// /////////////////////////////////////////////////////////////////
@Override
public void execute() throws MojoFailureException {
    init();
    PrintStream ps = null;
    try {
        if (logPath != null) {
            logPath.mkdirs();
            ps = new PrintStream(new File(logPath, be5Project.getName() + "_sync_ddl.sql"), "UTF-8");
        }
        sqlExecutor = new BeSqlExecutor(connector, ps);
        if (be5Project.getDebugStream() != null) {
            be5Project.getDebugStream().println("Modules and extras for " + be5Project.getName() + ":");
            be5Project.allModules().map(m -> "- " + m.getName() + ": " + (m.getExtras() == null ? "" : String.join(", ", m.getExtras()))).forEach(be5Project.getDebugStream()::println);
        }
        readSchema();
        createEntities();
        String ddlString = getDdlStatements(false);
        ddlString = MultiSqlParser.normalize(be5Project.getDatabaseSystem().getType(), ddlString);
        if (ddlString.isEmpty()) {
            getLog().info("Database scheme is up-to-date");
            return;
        }
        if (forceUpdate) {
            sqlExecutor.startSection("Sync schema");
            logger.setOperationName("[>] Schema");
            sqlExecutor.executeMultiple(ddlString);
            sqlExecutor.startSection(null);
        } else {
            System.err.println("The following statements should be executed to update database scheme:");
            System.err.println(ddlString);
            System.err.println("Use -DBE5_FORCE_UPDATE=true, for apply");
        }
        checkSynchronizationStatus();
        logger.setOperationName("Finished");
    } catch (// ReadException | ProjectLoadException | SQLException e )
    FreemarkerSqlException | ExtendedSqlException | SQLException e) {
        if (debug)
            throw new MojoFailureException("Synchronisation error: " + e.getMessage(), e);
        throw new MojoFailureException("Synchronisation error: " + e.getMessage());
    } catch (IOException | ProcessInterruptedException e) {
        throw new MojoFailureException("Synchronisation error: " + e.getMessage(), e);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new MojoFailureException("Synchronisation error: " + t.getMessage(), t);
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}
Also used : FreemarkerSqlException(com.developmentontheedge.be5.metadata.exception.FreemarkerSqlException) Arrays(java.util.Arrays) ViewDef(com.developmentontheedge.be5.metadata.model.ViewDef) NullLogger(com.developmentontheedge.be5.metadata.util.NullLogger) HashMap(java.util.HashMap) BeSqlExecutor(com.developmentontheedge.be5.metadata.sql.BeSqlExecutor) Parameter(org.apache.maven.plugins.annotations.Parameter) MultiSqlParser(com.developmentontheedge.dbms.MultiSqlParser) Rdbms(com.developmentontheedge.be5.metadata.sql.Rdbms) ArrayList(java.util.ArrayList) Entity(com.developmentontheedge.be5.metadata.model.Entity) DefaultTypeManager(com.developmentontheedge.be5.metadata.sql.type.DefaultTypeManager) Mojo(org.apache.maven.plugins.annotations.Mojo) SQLException(java.sql.SQLException) IndexDef(com.developmentontheedge.be5.metadata.model.IndexDef) DatabaseUtils(com.developmentontheedge.be5.metadata.sql.DatabaseUtils) ResultSet(java.sql.ResultSet) Locale(java.util.Locale) Map(java.util.Map) ExtendedSqlException(com.developmentontheedge.dbms.ExtendedSqlException) DdlElement(com.developmentontheedge.be5.metadata.model.DdlElement) Module(com.developmentontheedge.be5.metadata.model.Module) TableDef(com.developmentontheedge.be5.metadata.model.TableDef) DataElementUtils(com.developmentontheedge.be5.metadata.model.DataElementUtils) ProcessController(com.developmentontheedge.be5.metadata.util.ProcessController) PrintStream(java.io.PrintStream) DbmsTypeManager(com.developmentontheedge.be5.metadata.sql.type.DbmsTypeManager) ProcessInterruptedException(com.developmentontheedge.be5.metadata.exception.ProcessInterruptedException) IndexColumnDef(com.developmentontheedge.be5.metadata.model.IndexColumnDef) IOException(java.io.IOException) File(java.io.File) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SqlColumnInfo(com.developmentontheedge.be5.metadata.sql.pojo.SqlColumnInfo) List(java.util.List) ColumnDef(com.developmentontheedge.be5.metadata.model.ColumnDef) IndexInfo(com.developmentontheedge.be5.metadata.sql.pojo.IndexInfo) SqlColumnType(com.developmentontheedge.be5.metadata.model.SqlColumnType) DbmsType(com.developmentontheedge.dbms.DbmsType) IntStreamEx(one.util.streamex.IntStreamEx) Pattern(java.util.regex.Pattern) Project(com.developmentontheedge.be5.metadata.model.Project) Collections(java.util.Collections) EntityType(com.developmentontheedge.be5.metadata.model.EntityType) DbmsSchemaReader(com.developmentontheedge.be5.metadata.sql.schema.DbmsSchemaReader) FreemarkerSqlException(com.developmentontheedge.be5.metadata.exception.FreemarkerSqlException) PrintStream(java.io.PrintStream) SQLException(java.sql.SQLException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) ExtendedSqlException(com.developmentontheedge.dbms.ExtendedSqlException) BeSqlExecutor(com.developmentontheedge.be5.metadata.sql.BeSqlExecutor) File(java.io.File) ProcessInterruptedException(com.developmentontheedge.be5.metadata.exception.ProcessInterruptedException)

Example 3 with ExtendedSqlException

use of com.developmentontheedge.dbms.ExtendedSqlException in project be5 by DevelopmentOnTheEdge.

the class AppTools method execute.

@Override
public void execute() throws MojoFailureException {
    init();
    BeConnectionProfile prof = be5Project.getConnectionProfile();
    if (prof == null) {
        throw new MojoFailureException("Connection profile is required for SQL console");
    }
    try {
        getLog().info("Welcome to FTL/SQL console!");
        BeSqlExecutor sql = new BeSqlExecutor(connector) {

            @Override
            public void executeSingle(String statement) throws ExtendedSqlException {
                ResultSet rs = null;
                try {
                    rs = connector.executeQuery(statement);
                    format(rs, System.err, 20);
                } catch (SQLException e) {
                    throw new ExtendedSqlException(connector, statement, e);
                } finally {
                    connector.close(rs);
                }
            }
        };
        FreemarkerScript fs = new FreemarkerScript("SQL", be5Project.getApplication().getFreemarkerScripts());
        DataElementUtils.save(fs);
        ProcessController log = new NullLogger();
        while (true) {
            getLog().info("Enter FTL/SQL (use 'quit' to exit):");
            String line = new BufferedReader(new InputStreamReader(inputStream)).readLine();
            if (line == null) {
                break;
            }
            line = line.trim();
            if (line.equals("quit")) {
                break;
            }
            fs.setSource(line);
            ParseResult result = fs.getResult();
            if (result.getResult() != null) {
                getLog().info("SQL> " + result.getResult());
            } else {
                getLog().info("ERROR> " + result.getError());
                continue;
            }
            try {
                sql.executeScript(fs, log);
            } catch (Exception e) {
                getLog().info("ERROR> " + e.getMessage());
            }
        }
    } catch (Exception e) {
        throw new MojoFailureException("Console error: " + e.getMessage(), e);
    }
}
Also used : ParseResult(com.developmentontheedge.be5.metadata.model.ParseResult) SQLException(java.sql.SQLException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ExtendedSqlException(com.developmentontheedge.dbms.ExtendedSqlException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SQLException(java.sql.SQLException) ExtendedSqlException(com.developmentontheedge.dbms.ExtendedSqlException) BeSqlExecutor(com.developmentontheedge.be5.metadata.sql.BeSqlExecutor) NullLogger(com.developmentontheedge.be5.metadata.util.NullLogger) BeConnectionProfile(com.developmentontheedge.be5.metadata.model.BeConnectionProfile) ProcessController(com.developmentontheedge.be5.metadata.util.ProcessController) ResultSet(java.sql.ResultSet) FreemarkerScript(com.developmentontheedge.be5.metadata.model.FreemarkerScript)

Example 4 with ExtendedSqlException

use of com.developmentontheedge.dbms.ExtendedSqlException in project be5 by DevelopmentOnTheEdge.

the class FreemarkerSqlHandler method endStatement.

@Override
public void endStatement(String statement) {
    List<Position> positions = calculatePosition();
    if (debug) {
        for (Position position : positions) {
            sqlExecutor.comment("At " + position, false);
        }
    }
    List<String> newIncludeChain = getIncludeChain(positions);
    if (!newIncludeChain.equals(includeChain)) {
        int i = 0;
        while (newIncludeChain.size() > i && includeChain.size() > i && newIncludeChain.get(i).equals(includeChain.get(i))) {
            i++;
        }
        for (int j = includeChain.size() - 1; j >= i; j--) {
            sqlExecutor.comment("End of included " + includeChain.get(j), false);
        }
        for (int j = i; j < newIncludeChain.size(); j++) {
            if (log != null) {
                StringBuilder sb = new StringBuilder("[>]   ");
                for (int k = 0; k < j; k++) sb.append("  ");
                sb.append(newIncludeChain.get(j));
                log.setOperationName(sb.toString());
            }
            sqlExecutor.comment("Start of included " + newIncludeChain.get(j));
        }
    }
    includeChain = newIncludeChain;
    try {
        sqlExecutor.executeSingle(statement);
    } catch (ExtendedSqlException e) {
        if (!debug) {
            for (Position position : positions) {
                sqlExecutor.comment("At " + position, false);
            }
        }
        throw new FreemarkerSqlException(e, positions.toArray(new Position[positions.size()]));
    }
}
Also used : FreemarkerSqlException(com.developmentontheedge.be5.metadata.exception.FreemarkerSqlException) ExtendedSqlException(com.developmentontheedge.dbms.ExtendedSqlException)

Aggregations

ExtendedSqlException (com.developmentontheedge.dbms.ExtendedSqlException)4 FreemarkerSqlException (com.developmentontheedge.be5.metadata.exception.FreemarkerSqlException)2 SqlColumnType (com.developmentontheedge.be5.metadata.model.SqlColumnType)2 BeSqlExecutor (com.developmentontheedge.be5.metadata.sql.BeSqlExecutor)2 Rdbms (com.developmentontheedge.be5.metadata.sql.Rdbms)2 DbmsTypeManager (com.developmentontheedge.be5.metadata.sql.type.DbmsTypeManager)2 NullLogger (com.developmentontheedge.be5.metadata.util.NullLogger)2 ProcessController (com.developmentontheedge.be5.metadata.util.ProcessController)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 MojoFailureException (org.apache.maven.plugin.MojoFailureException)2 MetadataUtils (com.developmentontheedge.be5.metadata.MetadataUtils)1 ProcessInterruptedException (com.developmentontheedge.be5.metadata.exception.ProcessInterruptedException)1 ProjectElementException (com.developmentontheedge.be5.metadata.exception.ProjectElementException)1 BeConnectionProfile (com.developmentontheedge.be5.metadata.model.BeConnectionProfile)1 ColumnDef (com.developmentontheedge.be5.metadata.model.ColumnDef)1