Search in sources :

Example 61 with JDBCSession

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCSession in project dbeaver by serge-rider.

the class GenericTable method loadReferences.

private synchronized List<GenericTableForeignKey> loadReferences(DBRProgressMonitor monitor) throws DBException {
    if (!isPersisted() || !getDataSource().getInfo().supportsReferentialIntegrity()) {
        return new ArrayList<>();
    }
    try (JDBCSession session = DBUtils.openMetaSession(monitor, getDataSource(), "Load table relations")) {
        // Read foreign keys in two passes
        // First read entire resultset to prevent recursive metadata requests
        // some drivers don't like it
        final GenericMetaObject fkObject = getDataSource().getMetaObject(GenericConstants.OBJECT_FOREIGN_KEY);
        final List<ForeignKeyInfo> fkInfos = new ArrayList<>();
        JDBCDatabaseMetaData metaData = session.getMetaData();
        // Load indexes
        try (JDBCResultSet dbResult = metaData.getExportedKeys(getCatalog() == null ? null : getCatalog().getName(), getSchema() == null ? null : getSchema().getName(), getName())) {
            while (dbResult.next()) {
                ForeignKeyInfo fkInfo = new ForeignKeyInfo();
                fkInfo.pkColumnName = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.PKCOLUMN_NAME);
                fkInfo.fkTableCatalog = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.FKTABLE_CAT);
                fkInfo.fkTableSchema = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.FKTABLE_SCHEM);
                fkInfo.fkTableName = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.FKTABLE_NAME);
                fkInfo.fkColumnName = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.FKCOLUMN_NAME);
                fkInfo.keySeq = GenericUtils.safeGetInt(fkObject, dbResult, JDBCConstants.KEY_SEQ);
                fkInfo.updateRuleNum = GenericUtils.safeGetInt(fkObject, dbResult, JDBCConstants.UPDATE_RULE);
                fkInfo.deleteRuleNum = GenericUtils.safeGetInt(fkObject, dbResult, JDBCConstants.DELETE_RULE);
                fkInfo.fkName = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.FK_NAME);
                fkInfo.pkName = GenericUtils.safeGetStringTrimmed(fkObject, dbResult, JDBCConstants.PK_NAME);
                fkInfo.defferabilityNum = GenericUtils.safeGetInt(fkObject, dbResult, JDBCConstants.DEFERRABILITY);
                fkInfos.add(fkInfo);
            }
        }
        List<GenericTableForeignKey> fkList = new ArrayList<>();
        Map<String, GenericTableForeignKey> fkMap = new HashMap<>();
        for (ForeignKeyInfo info : fkInfos) {
            DBSForeignKeyModifyRule deleteRule = JDBCUtils.getCascadeFromNum(info.deleteRuleNum);
            DBSForeignKeyModifyRule updateRule = JDBCUtils.getCascadeFromNum(info.updateRuleNum);
            DBSForeignKeyDefferability defferability;
            switch(info.defferabilityNum) {
                case DatabaseMetaData.importedKeyInitiallyDeferred:
                    defferability = DBSForeignKeyDefferability.INITIALLY_DEFERRED;
                    break;
                case DatabaseMetaData.importedKeyInitiallyImmediate:
                    defferability = DBSForeignKeyDefferability.INITIALLY_IMMEDIATE;
                    break;
                case DatabaseMetaData.importedKeyNotDeferrable:
                    defferability = DBSForeignKeyDefferability.NOT_DEFERRABLE;
                    break;
                default:
                    defferability = DBSForeignKeyDefferability.UNKNOWN;
                    break;
            }
            if (info.fkTableName == null) {
                log.debug("Null FK table name");
                continue;
            }
            //String fkTableFullName = DBUtils.getFullyQualifiedName(getDataSource(), info.fkTableCatalog, info.fkTableSchema, info.fkTableName);
            GenericTable fkTable = getDataSource().findTable(monitor, info.fkTableCatalog, info.fkTableSchema, info.fkTableName);
            if (fkTable == null) {
                log.warn("Can't find FK table " + info.fkTableName);
                continue;
            }
            GenericTableColumn pkColumn = this.getAttribute(monitor, info.pkColumnName);
            if (pkColumn == null) {
                log.warn("Can't find PK column " + info.pkColumnName);
                continue;
            }
            GenericTableColumn fkColumn = fkTable.getAttribute(monitor, info.fkColumnName);
            if (fkColumn == null) {
                log.warn("Can't find FK table " + fkTable.getFullyQualifiedName(DBPEvaluationContext.DDL) + " column " + info.fkColumnName);
                continue;
            }
            // Find PK
            GenericPrimaryKey pk = null;
            if (!CommonUtils.isEmpty(info.pkName)) {
                pk = DBUtils.findObject(this.getConstraints(monitor), info.pkName);
                if (pk == null) {
                    log.debug("Unique key '" + info.pkName + "' not found in table " + this.getFullyQualifiedName(DBPEvaluationContext.DDL));
                }
            }
            if (pk == null) {
                Collection<GenericPrimaryKey> uniqueKeys = this.getConstraints(monitor);
                if (uniqueKeys != null) {
                    for (GenericPrimaryKey pkConstraint : uniqueKeys) {
                        if (pkConstraint.getConstraintType().isUnique() && DBUtils.getConstraintAttribute(monitor, pkConstraint, pkColumn) != null) {
                            pk = pkConstraint;
                            break;
                        }
                    }
                }
            }
            if (pk == null) {
                log.warn("Can't find unique key for table " + this.getFullyQualifiedName(DBPEvaluationContext.DDL) + " column " + pkColumn.getName());
                // Too bad. But we have to create new fake PK for this FK
                //String pkFullName = getFullyQualifiedName() + "." + info.pkName;
                pk = new GenericPrimaryKey(this, info.pkName, null, DBSEntityConstraintType.PRIMARY_KEY, true);
                pk.addColumn(new GenericTableConstraintColumn(pk, pkColumn, info.keySeq));
                // Add this fake constraint to it's owner
                this.addUniqueKey(pk);
            }
            // Find (or create) FK
            GenericTableForeignKey fk;
            if (CommonUtils.isEmpty(info.fkName)) {
                // Make fake FK name
                info.fkName = info.fkTableName.toUpperCase() + "_FK" + info.keySeq;
                fk = DBUtils.findObject(fkTable.getAssociations(monitor), info.fkName);
            } else {
                fk = DBUtils.findObject(fkTable.getAssociations(monitor), info.fkName);
                if (fk == null) {
                    log.warn("Can't find foreign key '" + info.fkName + "' for table " + fkTable.getFullyQualifiedName(DBPEvaluationContext.DDL));
                // No choice, we have to create fake foreign key :(
                }
            }
            if (fk != null && !fkList.contains(fk)) {
                fkList.add(fk);
            }
            if (fk == null) {
                fk = fkMap.get(info.fkName);
                if (fk == null) {
                    fk = new GenericTableForeignKey(fkTable, info.fkName, null, pk, deleteRule, updateRule, defferability, true);
                    fkMap.put(info.fkName, fk);
                    fkList.add(fk);
                }
                GenericTableForeignKeyColumnTable fkColumnInfo = new GenericTableForeignKeyColumnTable(fk, fkColumn, info.keySeq, pkColumn);
                fk.addColumn(fkColumnInfo);
            }
        }
        return fkList;
    } catch (SQLException ex) {
        throw new DBException(ex, getDataSource());
    }
}
Also used : JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBException(org.jkiss.dbeaver.DBException) GenericMetaObject(org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaObject) SQLException(java.sql.SQLException) JDBCDatabaseMetaData(org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData) DBSForeignKeyModifyRule(org.jkiss.dbeaver.model.struct.rdb.DBSForeignKeyModifyRule) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) DBSForeignKeyDefferability(org.jkiss.dbeaver.model.struct.rdb.DBSForeignKeyDefferability)

Example 62 with JDBCSession

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCSession in project dbeaver by serge-rider.

the class ExasolBaseTableToolDialog method executeSQL.

@Override
protected void executeSQL() {
    final String jobName = getShell().getText();
    final SQLScriptProgressListener<ExasolTableBase> scriptListener = getScriptListener();
    final List<ExasolTableBase> objects = getCheckedObjects();
    final Map<ExasolTableBase, List<String>> objectsSQL = new LinkedHashMap<>();
    for (ExasolTableBase object : objects) {
        final List<String> lines = new ArrayList<>();
        generateObjectCommand(lines, object);
        objectsSQL.put(object, lines);
    }
    final DataSourceJob job = new DataSourceJob(jobName, null, getExecutionContext()) {

        public Exception objectProcessingError;

        @SuppressWarnings("rawtypes")
        @Override
        protected IStatus run(final DBRProgressMonitor monitor) {
            final DataSourceJob curJob = this;
            DBeaverUI.asyncExec(new Runnable() {

                @Override
                public void run() {
                    scriptListener.beginScriptProcessing(curJob, objects);
                }
            });
            monitor.beginTask(jobName, objects.size());
            try (DBCSession session = getExecutionContext().openSession(monitor, DBCExecutionPurpose.UTIL, jobName)) {
                for (int i = 0; i < objects.size(); i++) {
                    if (monitor.isCanceled()) {
                        break;
                    }
                    final int objectNumber = i;
                    final ExasolTableBase object = objects.get(i);
                    monitor.subTask("Process " + DBUtils.getObjectFullName(object, DBPEvaluationContext.UI));
                    objectProcessingError = null;
                    DBeaverUI.asyncExec(new Runnable() {

                        @Override
                        public void run() {
                            scriptListener.beginObjectProcessing(object, objectNumber);
                        }
                    });
                    try {
                        final List<String> lines = objectsSQL.get(object);
                        for (String line : lines) {
                            try (final Statement statement = ((JDBCSession) session).getOriginal().createStatement()) {
                                int affectedRows = statement.executeUpdate(line);
                                Integer[] resultSetData = new Integer[] { affectedRows };
                                final LocalResultSet resultSet = new LocalResultSet<>(session, new JDBCStatementImpl<>((JDBCSession) session, statement, true));
                                resultSet.addColumn("ROWS_AFFECTED", DBPDataKind.NUMERIC);
                                resultSet.addRow((Object[]) resultSetData);
                                // Run in sync because we need result set
                                DBeaverUI.syncExec(new Runnable() {

                                    @Override
                                    public void run() {
                                        try {
                                            scriptListener.processObjectResults(object, null, resultSet);
                                        } catch (DBCException e) {
                                            objectProcessingError = e;
                                        }
                                    }
                                });
                                if (objectProcessingError != null) {
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        objectProcessingError = e;
                    } finally {
                        DBeaverUI.asyncExec(new Runnable() {

                            @Override
                            public void run() {
                                scriptListener.endObjectProcessing(object, objectProcessingError);
                            }
                        });
                    }
                    monitor.worked(1);
                }
            } finally {
                monitor.done();
                DBeaverUI.asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        scriptListener.endScriptProcessing();
                    }
                });
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(false);
    job.addJobChangeListener(new JobChangeAdapter() {

        @Override
        public void done(IJobChangeEvent event) {
        }
    });
    job.schedule();
}
Also used : LocalResultSet(org.jkiss.dbeaver.model.impl.local.LocalResultSet) JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) Statement(java.sql.Statement) ExasolTableBase(org.jkiss.dbeaver.ext.exasol.model.ExasolTableBase) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent) DataSourceJob(org.jkiss.dbeaver.runtime.jobs.DataSourceJob) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 63 with JDBCSession

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCSession in project dbeaver by serge-rider.

the class FireBirdUtils method getTriggerSource.

public static String getTriggerSource(DBRProgressMonitor monitor, FireBirdTrigger trigger) throws DBException {
    try (JDBCSession session = DBUtils.openMetaSession(monitor, trigger.getDataSource(), "Load trigger source code")) {
        DatabaseMetaData fbMetaData = session.getOriginal().getMetaData();
        String source = (String) fbMetaData.getClass().getMethod("getTriggerSourceCode", String.class).invoke(fbMetaData, trigger.getName());
        if (CommonUtils.isEmpty(source)) {
            return null;
        }
        return getTriggerSourceWithHeader(monitor, trigger, source);
    } catch (SQLException e) {
        throw new DBException("Can't read source code of trigger '" + trigger.getName() + "'", e);
    } catch (Exception e) {
        log.debug(e);
        return null;
    }
}
Also used : JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBException(org.jkiss.dbeaver.DBException) SQLException(java.sql.SQLException) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) DBException(org.jkiss.dbeaver.DBException)

Example 64 with JDBCSession

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCSession in project dbeaver by serge-rider.

the class FireBirdUtils method getViewSource.

public static String getViewSource(DBRProgressMonitor monitor, GenericTable view) throws DBException {
    try (JDBCSession session = DBUtils.openMetaSession(monitor, view.getDataSource(), "Load view source code")) {
        DatabaseMetaData fbMetaData = session.getOriginal().getMetaData();
        String source = (String) fbMetaData.getClass().getMethod("getViewSourceCode", String.class).invoke(fbMetaData, view.getName());
        if (CommonUtils.isEmpty(source)) {
            return null;
        }
        return getViewSourceWithHeader(monitor, view, source);
    } catch (SQLException e) {
        throw new DBException("Can't read source code of view '" + view.getName() + "'", e);
    } catch (Exception e) {
        log.debug(e);
        return null;
    }
}
Also used : JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBException(org.jkiss.dbeaver.DBException) SQLException(java.sql.SQLException) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) DBException(org.jkiss.dbeaver.DBException)

Example 65 with JDBCSession

use of org.jkiss.dbeaver.model.exec.jdbc.JDBCSession in project dbeaver by serge-rider.

the class FireBirdMetaModel method loadTriggers.

@Override
public List<GenericTrigger> loadTriggers(DBRProgressMonitor monitor, @NotNull GenericStructContainer container, @Nullable GenericTable table) throws DBException {
    try (JDBCSession session = DBUtils.openMetaSession(monitor, container.getDataSource(), "Read triggers")) {
        try (JDBCPreparedStatement dbStat = session.prepareStatement("SELECT RDB$TRIGGER_NAME,RDB$TRIGGER_SEQUENCE,RDB$TRIGGER_TYPE,RDB$DESCRIPTION FROM RDB$TRIGGERS\n" + "WHERE RDB$RELATION_NAME" + (table == null ? " IS NULL" : "=?"))) {
            if (table != null) {
                dbStat.setString(1, table.getName());
            }
            List<GenericTrigger> result = new ArrayList<>();
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                while (dbResult.next()) {
                    String name = JDBCUtils.safeGetString(dbResult, 1);
                    if (name == null) {
                        continue;
                    }
                    name = name.trim();
                    int sequence = JDBCUtils.safeGetInt(dbResult, 2);
                    int type = JDBCUtils.safeGetInt(dbResult, 3);
                    String description = JDBCUtils.safeGetString(dbResult, 4);
                    FireBirdTrigger trigger = new FireBirdTrigger(container, table, name, description, FireBirdTriggerType.getByType(type), sequence);
                    result.add(trigger);
                }
            }
            return result;
        }
    } catch (SQLException e) {
        throw new DBException(e, container.getDataSource());
    }
}
Also used : JDBCPreparedStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement) JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBException(org.jkiss.dbeaver.DBException) SQLException(java.sql.SQLException) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) ArrayList(java.util.ArrayList)

Aggregations

JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)73 SQLException (java.sql.SQLException)67 DBException (org.jkiss.dbeaver.DBException)54 JDBCResultSet (org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)54 JDBCPreparedStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement)46 DBCException (org.jkiss.dbeaver.model.exec.DBCException)16 ArrayList (java.util.ArrayList)15 JDBCStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement)7 NotNull (org.jkiss.code.NotNull)5 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)5 DatabaseMetaData (java.sql.DatabaseMetaData)3 GenericDataSource (org.jkiss.dbeaver.ext.generic.model.GenericDataSource)3 JDBCCallableStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCCallableStatement)3 Matcher (java.util.regex.Matcher)2 DB2XMLString (org.jkiss.dbeaver.ext.db2.info.DB2XMLString)2 GenericMetaObject (org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaObject)2 JDBCDatabaseMetaData (org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData)2 Property (org.jkiss.dbeaver.model.meta.Property)2 DBSObjectType (org.jkiss.dbeaver.model.struct.DBSObjectType)2 DBSProcedureType (org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType)2