Search in sources :

Example 16 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project perun by CESNET.

the class AuthorshipManagerBlImpl method createAuthorship.

// business methods ===================================
@Override
public Authorship createAuthorship(PerunSession sess, Authorship authorship) throws CabinetException, InternalErrorException {
    if (authorshipExists(authorship))
        throw new CabinetException(ErrorCodes.AUTHORSHIP_ALREADY_EXISTS);
    if (authorship.getCreatedDate() == null) {
        authorship.setCreatedDate(new Date());
    }
    if (authorship.getCreatedByUid() == 0) {
        authorship.setCreatedByUid(sess.getPerunPrincipal().getUserId());
    }
    try {
        getAuthorshipManagerDao().createAuthorship(sess, authorship);
    } catch (DataIntegrityViolationException e) {
        throw new CabinetException(ErrorCodes.USER_NOT_EXISTS, e);
    }
    log.debug("{} created.", authorship);
    synchronized (CabinetManagerBlImpl.class) {
        getCabinetManagerBl().updatePriorityCoefficient(sess, authorship.getUserId(), calculateNewRank(authorship.getUserId()));
    }
    synchronized (ThanksManagerBlImpl.class) {
        getCabinetManagerBl().setThanksAttribute(authorship.getUserId());
    }
    // log
    perun.getAuditer().log(sess, "Authorship {} created.", authorship);
    return authorship;
}
Also used : CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException) Date(java.util.Date) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 17 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project spring-framework by spring-projects.

the class SQLExceptionSubclassTranslatorTests method errorCodeTranslation.

@Test
public void errorCodeTranslation() {
    SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
    SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0);
    DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx);
    assertEquals(dataIntegrityViolationEx, divex.getCause());
    SQLException featureNotSupEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0);
    InvalidDataAccessApiUsageException idaex = (InvalidDataAccessApiUsageException) sext.translate("task", "SQL", featureNotSupEx);
    assertEquals(featureNotSupEx, idaex.getCause());
    SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0);
    DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2);
    assertEquals(dataIntegrityViolationEx2, divex2.getCause());
    SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0);
    PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx);
    assertEquals(permissionDeniedEx, pdaex.getCause());
    SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0);
    DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccessResourceEx);
    assertEquals(dataAccessResourceEx, darex.getCause());
    SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0);
    BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2);
    assertEquals("SQL2", bsgex2.getSql());
    assertEquals(badSqlEx2, bsgex2.getSQLException());
    SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0);
    ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx);
    assertEquals(tranRollbackEx, cfex.getCause());
    SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0);
    TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx);
    assertEquals(transientConnEx, tdarex.getCause());
    SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0);
    QueryTimeoutException tdarex2 = (QueryTimeoutException) sext.translate("task", "SQL", transientConnEx2);
    assertEquals(transientConnEx2, tdarex2.getCause());
    SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0);
    RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx);
    assertEquals(recoverableEx, rdaex2.getCause());
    // Test classic error code translation. We should move there next if the exception we pass in is not one
    // of the new sub-classes.
    SQLException sexEct = new SQLException("", "", 1);
    BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct);
    assertEquals("SQL-ECT", bsgEct.getSql());
    assertEquals(sexEct, bsgEct.getSQLException());
    // Test fallback. We assume that no database will ever return this error code,
    // but 07xxx will be bad grammar picked up by the fallback SQLState translator
    SQLException sexFbt = new SQLException("", "07xxx", 666666666);
    BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt);
    assertEquals("SQL-FBT", bsgFbt.getSql());
    assertEquals(sexFbt, bsgFbt.getSQLException());
    // and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator
    SQLException sexFbt2 = new SQLException("", "08xxx", 666666666);
    DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2);
    assertEquals(sexFbt2, darfFbt.getCause());
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) QueryTimeoutException(org.springframework.dao.QueryTimeoutException) TransientDataAccessResourceException(org.springframework.dao.TransientDataAccessResourceException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) PermissionDeniedDataAccessException(org.springframework.dao.PermissionDeniedDataAccessException) RecoverableDataAccessException(org.springframework.dao.RecoverableDataAccessException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Example 18 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project spring-boot by spring-projects.

the class JooqAutoConfigurationTests method jooqWithoutTx.

@Test
public void jooqWithoutTx() throws Exception {
    registerAndRefresh(JooqDataSourceConfiguration.class, JooqAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    assertThat(getBeanNames(PlatformTransactionManager.class)).isEqualTo(NO_BEANS);
    assertThat(getBeanNames(SpringTransactionProvider.class)).isEqualTo(NO_BEANS);
    DSLContext dsl = this.context.getBean(DSLContext.class);
    dsl.execute("create table jooqtest (name varchar(255) primary key);");
    dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "0"));
    dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');"));
    dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1"));
    try {
        dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", "insert into jooqtest (name) values ('foo');"));
        fail("An DataIntegrityViolationException should have been thrown.");
    } catch (DataIntegrityViolationException ex) {
    // Ignore
    }
    dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2"));
}
Also used : DSLContext(org.jooq.DSLContext) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Example 19 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project spring-boot by spring-projects.

the class JooqAutoConfigurationTests method jooqWithTx.

@Test
public void jooqWithTx() throws Exception {
    registerAndRefresh(JooqDataSourceConfiguration.class, PropertyPlaceholderAutoConfiguration.class, TxManagerConfiguration.class, JooqAutoConfiguration.class);
    this.context.getBean(PlatformTransactionManager.class);
    DSLContext dsl = this.context.getBean(DSLContext.class);
    assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.H2);
    dsl.execute("create table jooqtest_tx (name varchar(255) primary key);");
    dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0"));
    dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');"));
    dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1"));
    try {
        dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", "insert into jooqtest (name) values ('foo');"));
        fail("A DataIntegrityViolationException should have been thrown.");
    } catch (DataIntegrityViolationException ex) {
    // Ignore
    }
    dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1"));
}
Also used : DSLContext(org.jooq.DSLContext) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Test(org.junit.Test)

Example 20 with DataIntegrityViolationException

use of org.springframework.dao.DataIntegrityViolationException in project goci by EBISPOT.

the class V1_9_9_010__Association_locus_links_for_single_snp method migrate.

public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
    // get all genes
    IdAndStringRowHandler geneHandler = new IdAndStringRowHandler();
    jdbcTemplate.query(SELECT_GENES, geneHandler);
    final Map<Long, String> geneIdToNameMap = geneHandler.getIdToStringMap();
    // get all snps
    IdAndStringRowHandler snpHandler = new IdAndStringRowHandler();
    jdbcTemplate.query(SELECT_SNPS, snpHandler);
    final Map<Long, String> snpIdToRsIdMap = snpHandler.getIdToStringMap();
    // get all associations and link to gene id
    final Map<Long, Set<Long>> associationIdToGeneIds = new HashMap<>();
    final Map<Long, Long> associationIdToSnpId = new HashMap<>();
    final Map<Long, String> associationIdToRiskAlleleName = new HashMap<>();
    jdbcTemplate.query(SELECT_ASSOCIATIONS_AND_SNPS, (resultSet, i) -> {
        long associationID = resultSet.getLong(1);
        List<String> riskAlleles;
        List<String> geneNames;
        List<String> rsIds;
        String riskAlleleStr = resultSet.getString(2);
        if (riskAlleleStr != null) {
            riskAlleles = split(resultSet.getString(2).trim());
        } else {
            riskAlleles = new ArrayList<>();
        }
        String genesStr = resultSet.getString(3);
        if (genesStr != null) {
            geneNames = split(genesStr.trim());
        } else {
            geneNames = new ArrayList<>();
        }
        String snpsStr = resultSet.getString(4);
        if (snpsStr != null) {
            rsIds = split(snpsStr.trim());
        } else {
            rsIds = new ArrayList<>();
        }
        // in case we need to add new genes
        SimpleJdbcInsert insertGene = new SimpleJdbcInsert(jdbcTemplate).withTableName("GENE").usingColumns("GENE_NAME").usingGeneratedKeyColumns("ID");
        for (String geneName : geneNames) {
            boolean found = false;
            for (long geneID : geneIdToNameMap.keySet()) {
                if (geneIdToNameMap.get(geneID).equals(geneName)) {
                    if (!associationIdToGeneIds.containsKey(associationID)) {
                        associationIdToGeneIds.put(associationID, new HashSet<>());
                    }
                    if (!associationIdToGeneIds.get(associationID).contains(geneID)) {
                        // add the new associated gene
                        associationIdToGeneIds.get(associationID).add(geneID);
                    }
                    found = true;
                    // we break here to handle duplicate entries in the gene table of the database
                    break;
                }
            }
            if (!found) {
                // the GENE with the GENE_NAME in GWASSTUDIESSNP doesn't exist in GWASGENE,
                // so create a new GENE entry
                Map<String, Object> geneArgs = new HashMap<>();
                geneArgs.put("GENE_NAME", geneName);
                long geneID = insertGene.executeAndReturnKey(geneArgs).longValue();
                geneIdToNameMap.put(geneID, geneName);
                if (!associationIdToGeneIds.containsKey(associationID)) {
                    associationIdToGeneIds.put(associationID, new HashSet<>());
                }
                if (!associationIdToGeneIds.get(associationID).contains(geneID)) {
                    // add the new associated gene
                    associationIdToGeneIds.get(associationID).add(geneID);
                }
            }
        }
        // in case we need to add new SNPs
        SimpleJdbcInsert insertSnp = new SimpleJdbcInsert(jdbcTemplate).withTableName("SINGLE_NUCLEOTIDE_POLYMORPHISM").usingColumns("RS_ID").usingGeneratedKeyColumns("ID");
        for (String rsId : rsIds) {
            boolean foundSnp = false;
            for (long snpID : snpIdToRsIdMap.keySet()) {
                if (snpIdToRsIdMap.get(snpID).equals(rsId)) {
                    if (associationIdToSnpId.containsKey(associationID)) {
                        // check for equality of SNP names
                        String rsExisting = snpIdToRsIdMap.get(associationIdToSnpId.get(associationID));
                        String rsNew = snpIdToRsIdMap.get(snpID);
                        if (!rsExisting.equals(rsNew)) {
                            // can't safely ignore, this isn't simply duplicate entries in SNP table
                            throw new RuntimeException("Can't link association '" + associationID + "' to single SNP - " + "more than one connected rsID (" + "existing = " + associationIdToSnpId.get(associationID) + ", " + "new = " + snpID + ")");
                        }
                    } else {
                        if (riskAlleles.size() > 1) {
                            throw new RuntimeException("Single SNP with multiple risk alleles for SNP - " + snpID + " (risk alleles = " + riskAlleles + ")");
                        } else {
                            if (!riskAlleles.isEmpty()) {
                                associationIdToSnpId.put(associationID, snpID);
                                associationIdToRiskAlleleName.put(associationID, riskAlleles.iterator().next());
                            }
                        }
                    }
                    foundSnp = true;
                    // we break here to handle duplicate entries in the snp table of the database
                    break;
                }
            }
            if (!foundSnp) {
                // the SNP with the RS_ID in GWASSTUDIESSNP doesn't exist in GWASSNP,
                // so create a new SINGLE_NUCLEOTIDE_POLYMORPHISM entry
                Map<String, Object> snpArgs = new HashMap<>();
                snpArgs.put("RS_ID", rsId);
                long snpID = insertSnp.executeAndReturnKey(snpArgs).longValue();
                snpIdToRsIdMap.put(snpID, rsId);
                associationIdToSnpId.put(associationID, snpID);
            }
        }
        return null;
    });
    SimpleJdbcInsert insertLocus = new SimpleJdbcInsert(jdbcTemplate).withTableName("LOCUS").usingColumns("HAPLOTYPE_SNP_COUNT", "DESCRIPTION").usingGeneratedKeyColumns("ID");
    SimpleJdbcInsert insertAssociationLocus = new SimpleJdbcInsert(jdbcTemplate).withTableName("ASSOCIATION_LOCUS").usingColumns("ASSOCIATION_ID", "LOCUS_ID");
    SimpleJdbcInsert insertRiskAllele = new SimpleJdbcInsert(jdbcTemplate).withTableName("RISK_ALLELE").usingColumns("RISK_ALLELE_NAME").usingGeneratedKeyColumns("ID");
    SimpleJdbcInsert insertLocusRiskAllele = new SimpleJdbcInsert(jdbcTemplate).withTableName("LOCUS_RISK_ALLELE").usingColumns("LOCUS_ID", "RISK_ALLELE_ID");
    SimpleJdbcInsert insertRiskAlleleSnp = new SimpleJdbcInsert(jdbcTemplate).withTableName("RISK_ALLELE_SNP").usingColumns("RISK_ALLELE_ID", "SNP_ID");
    SimpleJdbcInsert insertAuthorReportedGene = new SimpleJdbcInsert(jdbcTemplate).withTableName("AUTHOR_REPORTED_GENE").usingColumns("LOCUS_ID", "REPORTED_GENE_ID");
    for (Long associationID : associationIdToSnpId.keySet()) {
        // create a single LOCUS and get the locus ID
        Map<String, Object> locusArgs = new HashMap<>();
        locusArgs.put("HAPLOTYPE_SNP_COUNT", null);
        locusArgs.put("DESCRIPTION", "Single variant");
        Number locusID = insertLocus.executeAndReturnKey(locusArgs);
        // now create the ASSOCIATION_LOCUS link
        Map<String, Object> associationLocusArgs = new HashMap<>();
        associationLocusArgs.put("ASSOCIATION_ID", associationID);
        associationLocusArgs.put("LOCUS_ID", locusID);
        insertAssociationLocus.execute(associationLocusArgs);
        // now create a single RISK_ALLELE and get the risk allele ID
        Map<String, Object> riskAlleleArgs = new HashMap<>();
        riskAlleleArgs.put("RISK_ALLELE_NAME", associationIdToRiskAlleleName.get(associationID));
        Number riskAlleleID = insertRiskAllele.executeAndReturnKey(riskAlleleArgs);
        // now create the LOCUS_RISK_ALLELE link
        Map<String, Object> locusRiskAlleleArgs = new HashMap<>();
        locusRiskAlleleArgs.put("LOCUS_ID", locusID.longValue());
        locusRiskAlleleArgs.put("RISK_ALLELE_ID", riskAlleleID.longValue());
        insertLocusRiskAllele.execute(locusRiskAlleleArgs);
        // now create the RISK_ALLELE_SNP link
        Long snpID = associationIdToSnpId.get(associationID);
        try {
            Map<String, Object> riskAlleleSnpArgs = new HashMap<>();
            riskAlleleSnpArgs.put("RISK_ALLELE_ID", riskAlleleID.longValue());
            riskAlleleSnpArgs.put("SNP_ID", snpID);
            insertRiskAlleleSnp.execute(riskAlleleSnpArgs);
        } catch (DataIntegrityViolationException e) {
            throw new RuntimeException("Failed to insert link between snp = " + snpID + " and risk allele = " + riskAlleleID, e);
        }
        // finally create the AUTHOR_REPORTED_GENE link
        if (associationIdToGeneIds.containsKey(associationID)) {
            for (Long geneID : associationIdToGeneIds.get(associationID)) {
                try {
                    Map<String, Object> authorReportedGeneArgs = new HashMap<>();
                    authorReportedGeneArgs.put("LOCUS_ID", locusID.longValue());
                    authorReportedGeneArgs.put("REPORTED_GENE_ID", geneID);
                    insertAuthorReportedGene.execute(authorReportedGeneArgs);
                } catch (DataIntegrityViolationException e) {
                    throw new RuntimeException("Failed to insert link between locus = " + locusID + " and reported gene  = " + geneID, e);
                }
            }
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ResultSet(java.sql.ResultSet) HashMap(java.util.HashMap) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) SimpleJdbcInsert(org.springframework.jdbc.core.simple.SimpleJdbcInsert)

Aggregations

DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)27 Test (org.junit.Test)11 SQLException (java.sql.SQLException)8 HashSet (java.util.HashSet)6 HashMap (java.util.HashMap)5 Set (java.util.Set)5 DataAccessException (org.springframework.dao.DataAccessException)5 SimpleJdbcInsert (org.springframework.jdbc.core.simple.SimpleJdbcInsert)5 ResultSet (java.sql.ResultSet)4 Date (java.util.Date)3 List (java.util.List)3 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)3 BadSqlGrammarException (org.springframework.jdbc.BadSqlGrammarException)3 MongoException (com.mongodb.MongoException)2 CabinetException (cz.metacentrum.perun.cabinet.bl.CabinetException)2 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)2 ConsistencyErrorRuntimeException (cz.metacentrum.perun.core.api.exceptions.rt.ConsistencyErrorRuntimeException)2 InternalErrorRuntimeException (cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException)2 ArrayList (java.util.ArrayList)2 ObjectId (org.bson.types.ObjectId)2