Search in sources :

Example 1 with PgStatement

use of cz.startnet.utils.pgdiff.schema.PgStatement in project pgcodekeeper by pgcodekeeper.

the class AlterOwner method parseObject.

@Override
public void parseObject() {
    if (db.getArguments().isIgnorePrivileges()) {
        return;
    }
    IdentifierContext name = ctx.owner_to().user_name().identifier();
    if (name == null) {
        return;
    }
    PgStatement st = null;
    if (ctx.OPERATOR() != null) {
        Target_operatorContext targetOperCtx = ctx.target_operator();
        Operator_nameContext operNameCtx = targetOperCtx.name;
        IdentifierContext schemaCtx = operNameCtx.schema_name;
        All_simple_opContext nameCtx = operNameCtx.operator;
        List<ParserRuleContext> ids = Arrays.asList(schemaCtx, nameCtx);
        st = getSafe(AbstractSchema::getOperator, getSchemaSafe(ids), parseSignature(nameCtx.getText(), targetOperCtx), nameCtx.getStart());
        setOwner(st, name);
        addObjReference(ids, DbObjType.OPERATOR, ACTION_ALTER);
        return;
    }
    List<IdentifierContext> ids = ctx.name.identifier();
    IdentifierContext nameCtx = QNameParser.getFirstNameCtx(ids);
    DbObjType type = null;
    if (ctx.SCHEMA() != null) {
        st = getSafe(PgDatabase::getSchema, db, nameCtx);
        type = DbObjType.SCHEMA;
    } else if (ctx.FOREIGN() != null && ctx.DATA() != null && ctx.WRAPPER() != null) {
        st = getSafe(PgDatabase::getForeignDW, db, nameCtx);
        type = DbObjType.FOREIGN_DATA_WRAPPER;
    } else if (ctx.SERVER() != null) {
        st = getSafe(PgDatabase::getServer, db, nameCtx);
        type = DbObjType.SERVER;
    } else {
        AbstractSchema schema = getSchemaSafe(ids);
        if (ctx.DOMAIN() != null) {
            st = getSafe(AbstractSchema::getDomain, schema, nameCtx);
            type = DbObjType.DOMAIN;
        } else if (ctx.VIEW() != null) {
            st = getSafe(AbstractSchema::getView, schema, nameCtx);
            type = DbObjType.VIEW;
        } else if (ctx.DICTIONARY() != null) {
            st = getSafe(AbstractSchema::getFtsDictionary, schema, nameCtx);
            type = DbObjType.FTS_DICTIONARY;
        } else if (ctx.CONFIGURATION() != null) {
            st = getSafe(AbstractSchema::getFtsConfiguration, schema, nameCtx);
            type = DbObjType.FTS_CONFIGURATION;
        } else if (ctx.SEQUENCE() != null) {
            st = getSafe(AbstractSchema::getSequence, schema, nameCtx);
            type = DbObjType.SEQUENCE;
        } else if (ctx.TYPE() != null) {
            st = getSafe(AbstractSchema::getType, schema, nameCtx);
            type = DbObjType.TYPE;
        } else if (ctx.PROCEDURE() != null || ctx.FUNCTION() != null || ctx.AGGREGATE() != null) {
            st = getSafe(AbstractSchema::getFunction, schema, parseSignature(nameCtx.getText(), ctx.function_args()), nameCtx.getStart());
            if (ctx.FUNCTION() != null) {
                type = DbObjType.FUNCTION;
            } else if (ctx.PROCEDURE() != null) {
                type = DbObjType.PROCEDURE;
            } else {
                type = DbObjType.AGGREGATE;
            }
        }
    }
    if (type != null) {
        if (type == DbObjType.FUNCTION || type == DbObjType.PROCEDURE || type == DbObjType.AGGREGATE) {
            addObjReference(ids, type, ACTION_ALTER, parseArguments(ctx.function_args()));
        } else {
            addObjReference(ids, type, ACTION_ALTER);
        }
    }
    if (st == null || (type == DbObjType.SCHEMA && ApgdiffConsts.PUBLIC.equals(nameCtx.getText()) && "postgres".equals(name.getText()))) {
        return;
    }
    setOwner(st, name);
}
Also used : ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) PgStatement(cz.startnet.utils.pgdiff.schema.PgStatement) AbstractSchema(cz.startnet.utils.pgdiff.schema.AbstractSchema) DbObjType(ru.taximaxim.codekeeper.apgdiff.model.difftree.DbObjType) Target_operatorContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.Target_operatorContext) Operator_nameContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.Operator_nameContext) PgDatabase(cz.startnet.utils.pgdiff.schema.PgDatabase) IdentifierContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.IdentifierContext) All_simple_opContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.All_simple_opContext) StatementOverride(cz.startnet.utils.pgdiff.schema.StatementOverride)

Example 2 with PgStatement

use of cz.startnet.utils.pgdiff.schema.PgStatement in project pgcodekeeper by pgcodekeeper.

the class AlterTable method parseObject.

@Override
public void parseObject() {
    List<IdentifierContext> ids = ctx.name.identifier();
    AbstractSchema schema = getSchemaSafe(ids);
    IdentifierContext nameCtx = QNameParser.getFirstNameCtx(ids);
    AbstractPgTable tabl = null;
    PgObjLocation loc = addObjReference(ids, DbObjType.TABLE, ACTION_ALTER);
    for (Table_actionContext tablAction : ctx.table_action()) {
        IdentifierContext column = tablAction.column;
        Column_actionContext colAction = tablAction.column_action();
        if (column != null && tablAction.DROP() != null) {
            loc.setWarning(DangerStatement.DROP_COLUMN);
        } else if (colAction != null && colAction.data_type() != null) {
            loc.setWarning(DangerStatement.ALTER_COLUMN);
        }
        if (tablAction.owner_to() != null) {
            IRelation r = getSafe(AbstractSchema::getRelation, schema, nameCtx);
            if (r instanceof PgStatement) {
                fillOwnerTo(tablAction.owner_to().user_name().identifier(), (PgStatement) r);
            }
            continue;
        }
        // everything else requires a real table, so fail immediately
        tabl = (AbstractPgTable) getSafe(AbstractSchema::getTable, schema, nameCtx);
        if (tablAction.tabl_constraint != null) {
            IdentifierContext conNameCtx = tablAction.tabl_constraint.identifier();
            AbstractConstraint con = parseAlterTableConstraint(tablAction, createTableConstraintBlank(tablAction.tabl_constraint), getSchemaNameSafe(ids), nameCtx.getText(), fileName);
            if (!con.getName().isEmpty()) {
                addSafe(tabl, con, Arrays.asList(QNameParser.getSchemaNameCtx(ids), nameCtx, conNameCtx));
            } else {
                doSafe(AbstractPgTable::addConstraint, tabl, con);
            }
        }
        if (tablAction.drop_constraint() != null) {
            addObjReference(Arrays.asList(QNameParser.getSchemaNameCtx(ids), nameCtx, tablAction.drop_constraint().constraint_name), DbObjType.CONSTRAINT, ACTION_DROP);
        }
        if (isRefMode()) {
            continue;
        }
        Table_column_definitionContext def = tablAction.table_column_definition();
        if (def != null) {
            addColumn(def.identifier().getText(), def.data_type(), def.collate_identifier(), def.compression_identifier(), def.constraint_common(), def.define_foreign_options(), tabl);
        }
        if (column != null && colAction != null) {
            PgColumn col;
            if (tabl.getInherits().isEmpty()) {
                col = (PgColumn) getSafe(AbstractTable::getColumn, tabl, column);
            } else {
                String colName = column.getText();
                col = (PgColumn) tabl.getColumn(colName);
                if (col == null) {
                    col = new PgColumn(colName);
                    col.setInherit(true);
                    tabl.addColumn(col);
                }
            }
            parseColumnAction(schema, col, colAction);
        }
        Schema_qualified_nameContext ind = tablAction.index_name;
        if (ind != null) {
            IdentifierContext indexName = QNameParser.getFirstNameCtx(ind.identifier());
            AbstractIndex index = getSafe(AbstractTable::getIndex, tabl, indexName);
            index.setClusterIndex(true);
        }
        if (tablAction.WITHOUT() != null && tablAction.OIDS() != null) {
            tabl.setHasOids(false);
        } else if (tablAction.WITH() != null && tablAction.OIDS() != null) {
            tabl.setHasOids(true);
        }
        if (tablAction.RULE() != null) {
            createRule(tabl, tablAction);
        }
        if (tablAction.SECURITY() != null && tabl instanceof AbstractRegularTable) {
            AbstractRegularTable regTable = (AbstractRegularTable) tabl;
            // since 9.5 PostgreSQL
            if (tablAction.FORCE() != null) {
                regTable.setForceSecurity(tablAction.NO() == null);
            } else {
                regTable.setRowSecurity(tablAction.ENABLE() != null);
            }
        }
    }
}
Also used : Column_actionContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.Column_actionContext) AbstractConstraint(cz.startnet.utils.pgdiff.schema.AbstractConstraint) AbstractRegularTable(cz.startnet.utils.pgdiff.schema.AbstractRegularTable) PgObjLocation(cz.startnet.utils.pgdiff.schema.PgObjLocation) Schema_qualified_nameContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.Schema_qualified_nameContext) PgColumn(cz.startnet.utils.pgdiff.schema.PgColumn) AbstractPgTable(cz.startnet.utils.pgdiff.schema.AbstractPgTable) AbstractTable(cz.startnet.utils.pgdiff.schema.AbstractTable) AbstractSchema(cz.startnet.utils.pgdiff.schema.AbstractSchema) PgStatement(cz.startnet.utils.pgdiff.schema.PgStatement) Table_column_definitionContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.Table_column_definitionContext) IRelation(cz.startnet.utils.pgdiff.schema.IRelation) AbstractIndex(cz.startnet.utils.pgdiff.schema.AbstractIndex) Table_actionContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.Table_actionContext) IdentifierContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.IdentifierContext)

Example 3 with PgStatement

use of cz.startnet.utils.pgdiff.schema.PgStatement in project pgcodekeeper by pgcodekeeper.

the class AbstractAnalysisLauncher method analyzeTableChildVex.

/**
 * Sets up namespace for Constraint/Index expr analysis
 * @return
 */
protected Set<PgObjLocation> analyzeTableChildVex(VexContext ctx, MetaContainer meta) {
    PgStatement table = stmt.getParent();
    String schemaName = table.getParent().getName();
    String rawTableReference = table.getName();
    ValueExprWithNmspc valExptWithNmspc = new ValueExprWithNmspc(meta);
    valExptWithNmspc.addRawTableReference(new GenericColumn(schemaName, rawTableReference, DbObjType.TABLE));
    return analyze(ctx, valExptWithNmspc);
}
Also used : GenericColumn(cz.startnet.utils.pgdiff.schema.GenericColumn) PgStatement(cz.startnet.utils.pgdiff.schema.PgStatement) ValueExprWithNmspc(cz.startnet.utils.pgdiff.parsers.antlr.expr.ValueExprWithNmspc)

Example 4 with PgStatement

use of cz.startnet.utils.pgdiff.schema.PgStatement in project pgcodekeeper by pgcodekeeper.

the class QuickUpdateJob method doRun.

private void doRun() throws IOException, InterruptedException, CoreException, PgCodekeeperUIException, InvocationTargetException {
    boolean isMsSql = OpenProjectUtils.checkMsSql(proj.getProject());
    if (dbinfo.isMsSql() != isMsSql) {
        throw new PgCodekeeperUIException(Messages.QuickUpdate_different_types);
    }
    boolean isSchemaFile = UIProjectLoader.isSchemaFile(file.getProjectRelativePath(), isMsSql);
    IEclipsePreferences projPrefs = proj.getPrefs();
    String timezone = projPrefs.get(PROJ_PREF.TIMEZONE, ApgdiffConsts.UTC);
    PgDatabase dbProjectFragment = UIProjectLoader.buildFiles(Arrays.asList(file), isMsSql, monitor.newChild(1));
    Collection<PgStatement> listPgObjectsFragment = dbProjectFragment.getDescendants().collect(Collectors.toList());
    long schemaCount = dbProjectFragment.getSchemas().size();
    if (schemaCount > 1) {
        // more than 1 schema, shoudln't happen
        throw new PgCodekeeperUIException(Messages.QuickUpdate_multiple_schemas);
    } else if (listPgObjectsFragment.isEmpty() || (schemaCount == listPgObjectsFragment.size() && !isSchemaFile)) {
        // only schema loaded but not a schema file: probably a search_path-only file
        throw new PgCodekeeperUIException(Messages.QuickUpdate_empty_script);
    }
    checkFileModified();
    DbSource dbRemote = DbSource.fromDbInfo(dbinfo, projPrefs.getBoolean(PROJ_PREF.FORCE_UNIX_NEWLINES, true), proj.getProjectCharset(), timezone, proj.getProject());
    DbSource dbProject = DbSource.fromProject(proj);
    TreeDiffer treediffer = new TreeDiffer(dbRemote, dbProject);
    treediffer.run(monitor.newChild(1));
    TreeElement treeFull = treediffer.getDiffTree();
    Collection<TreeElement> checked = setCheckedFromFragment(treeFull, listPgObjectsFragment, dbRemote.getDbObject(), dbProject.getDbObject());
    if (checked.isEmpty()) {
        // $NON-NLS-1$
        Log.log(Log.LOG_INFO, "No object changes found when comparing to DB");
        return;
    }
    Differ differ = new Differ(dbRemote.getDbObject(), dbProject.getDbObject(), treeFull, false, timezone, isMsSql, proj.getProject());
    differ.run(monitor.newChild(1));
    checkFileModified();
    monitor.newChild(1).subTask(Messages.QuickUpdate_updating_db);
    JdbcConnector connector;
    if (isMsSql) {
        connector = new JdbcMsConnector(dbinfo.getDbHost(), dbinfo.getDbPort(), dbinfo.getDbUser(), dbinfo.getDbPass(), dbinfo.getDbName(), dbinfo.getProperties(), dbinfo.isReadOnly(), dbinfo.isWinAuth(), dbinfo.getDomain());
    } else {
        connector = new JdbcConnector(dbinfo.getDbHost(), dbinfo.getDbPort(), dbinfo.getDbUser(), dbinfo.getDbPass(), dbinfo.getDbName(), dbinfo.getProperties(), dbinfo.isReadOnly(), ApgdiffConsts.UTC);
    }
    try {
        ScriptParser parser = new ScriptParser(file.getName(), differ.getDiffDirect(), isMsSql);
        String error = parser.getErrorMessage();
        if (error != null) {
            throw new PgCodekeeperUIException(error);
        }
        if (parser.isDangerDdl(EnumSet.noneOf(DangerStatement.class))) {
            throw new PgCodekeeperUIException(Messages.QuickUpdate_danger);
        }
        new JdbcRunner(monitor).runBatches(connector, parser.batch(), null);
    } catch (SQLException e) {
        throw new PgCodekeeperUIException(Messages.QuickUpdate_migration_failed + e.getLocalizedMessage());
    }
    checkFileModified();
    TreeDiffer treedifferAfter = new TreeDiffer(DbSource.fromDbObject(dbProject), dbRemote);
    treedifferAfter.run(monitor.newChild(1));
    TreeElement treeAfter = treedifferAfter.getDiffTree();
    Collection<TreeElement> checkedAfter = setCheckedFromFragment(treeAfter, listPgObjectsFragment, dbProject.getDbObject(), dbRemote.getDbObject());
    if (checkedAfter.isEmpty()) {
        // success, no export needed, Postgres didn't make any alterations
        return;
    }
    checkFileModified();
    monitor.newChild(1).subTask(Messages.QuickUpdate_updating_project);
    ProjectUpdater updater = new ProjectUpdater(dbRemote.getDbObject(), dbProject.getDbObject(), checkedAfter, proj, false);
    updater.updatePartial();
    file.refreshLocal(IResource.DEPTH_INFINITE, monitor.newChild(1));
}
Also used : IEclipsePreferences(org.eclipse.core.runtime.preferences.IEclipsePreferences) SQLException(java.sql.SQLException) JdbcRunner(cz.startnet.utils.pgdiff.loader.JdbcRunner) ProjectUpdater(ru.taximaxim.codekeeper.ui.fileutils.ProjectUpdater) PgDatabase(cz.startnet.utils.pgdiff.schema.PgDatabase) TreeDiffer(ru.taximaxim.codekeeper.ui.differ.TreeDiffer) TreeElement(ru.taximaxim.codekeeper.apgdiff.model.difftree.TreeElement) JdbcConnector(cz.startnet.utils.pgdiff.loader.JdbcConnector) JdbcMsConnector(cz.startnet.utils.pgdiff.loader.JdbcMsConnector) Differ(ru.taximaxim.codekeeper.ui.differ.Differ) TreeDiffer(ru.taximaxim.codekeeper.ui.differ.TreeDiffer) PgStatement(cz.startnet.utils.pgdiff.schema.PgStatement) PgCodekeeperUIException(ru.taximaxim.codekeeper.ui.PgCodekeeperUIException) ScriptParser(cz.startnet.utils.pgdiff.parsers.antlr.ScriptParser) DangerStatement(cz.startnet.utils.pgdiff.DangerStatement) DbSource(ru.taximaxim.codekeeper.ui.differ.DbSource)

Example 5 with PgStatement

use of cz.startnet.utils.pgdiff.schema.PgStatement in project pgcodekeeper by pgcodekeeper.

the class GrantPrivilege method setColumnPrivilege.

private void setColumnPrivilege(Schema_qualified_nameContext tbl, Map<String, Entry<IdentifierContext, List<String>>> colPrivs, List<String> roles) {
    List<IdentifierContext> ids = tbl.identifier();
    addObjReference(ids, DbObjType.TABLE, state);
    if (isRefMode()) {
        return;
    }
    AbstractSchema schema = getSchemaSafe(ids);
    IdentifierContext firstPart = QNameParser.getFirstNameCtx(ids);
    // привилегии пишем так как получили одной строкой
    PgStatement st = (PgStatement) getSafe(AbstractSchema::getRelation, schema, firstPart);
    for (Entry<String, Entry<IdentifierContext, List<String>>> colPriv : colPrivs.entrySet()) {
        StringBuilder permission = new StringBuilder();
        for (String priv : colPriv.getValue().getValue()) {
            permission.append(priv).append('(').append(colPriv.getValue().getKey().getText()).append("),");
        }
        permission.setLength(permission.length() - 1);
        for (String role : roles) {
            PgPrivilege priv = new PgPrivilege(state, permission.toString(), "TABLE " + st.getQualifiedName(), role, isGO);
            if (DbObjType.TABLE != st.getStatementType()) {
                addPrivilege(st, priv);
            } else {
                IdentifierContext colName = colPriv.getValue().getKey();
                AbstractColumn col = getSafe(AbstractTable::getColumn, (AbstractTable) st, colName);
                addPrivilege(col, priv);
            }
        }
    }
}
Also used : AbstractTable(cz.startnet.utils.pgdiff.schema.AbstractTable) SimpleEntry(java.util.AbstractMap.SimpleEntry) Entry(java.util.Map.Entry) AbstractSchema(cz.startnet.utils.pgdiff.schema.AbstractSchema) PgStatement(cz.startnet.utils.pgdiff.schema.PgStatement) PgPrivilege(cz.startnet.utils.pgdiff.schema.PgPrivilege) AbstractColumn(cz.startnet.utils.pgdiff.schema.AbstractColumn) IdentifierContext(cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.IdentifierContext)

Aggregations

PgStatement (cz.startnet.utils.pgdiff.schema.PgStatement)52 AbstractTable (cz.startnet.utils.pgdiff.schema.AbstractTable)12 HashSet (java.util.HashSet)11 AbstractSchema (cz.startnet.utils.pgdiff.schema.AbstractSchema)10 PgDatabase (cz.startnet.utils.pgdiff.schema.PgDatabase)10 DbObjType (ru.taximaxim.codekeeper.apgdiff.model.difftree.DbObjType)10 TreeElement (ru.taximaxim.codekeeper.apgdiff.model.difftree.TreeElement)10 PgPrivilege (cz.startnet.utils.pgdiff.schema.PgPrivilege)7 StatementOverride (cz.startnet.utils.pgdiff.schema.StatementOverride)7 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Entry (java.util.Map.Entry)7 DefaultEdge (org.jgrapht.graph.DefaultEdge)7 IdentifierContext (cz.startnet.utils.pgdiff.parsers.antlr.SQLParser.IdentifierContext)6 AbstractColumn (cz.startnet.utils.pgdiff.schema.AbstractColumn)6 GenericColumn (cz.startnet.utils.pgdiff.schema.GenericColumn)6 Map (java.util.Map)6 Path (java.nio.file.Path)5 IStructuredSelection (org.eclipse.jface.viewers.IStructuredSelection)5 IdContext (cz.startnet.utils.pgdiff.parsers.antlr.TSQLParser.IdContext)4