Refine search
@Override public List<String> inTransaction(Handle handle, TransactionStatus status) { return handle.createQuery(reverseFetchQuery) .bind("val", value) .map(StringMapper.FIRST) .list(); } });
@Override public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception { // Check if we already have notifications for that key final Class<T> clazz = (Class<T>) notificationKey.getClass(); final Iterable<NotificationEventWithMetadata<T>> futureNotifications = getFutureNotificationsForAccountInTransaction(entitySqlDaoWrapperFactory, overdueQueue, clazz, context); final boolean shouldInsertNewNotification = cleanupFutureNotificationsFormTransaction(entitySqlDaoWrapperFactory, futureNotifications, futureNotificationTime, overdueQueue); if (shouldInsertNewNotification) { log.debug("Queuing overdue check notification. Account id: {}, timestamp: {}", accountId.toString(), futureNotificationTime.toString()); overdueQueue.recordFutureNotificationFromTransaction(entitySqlDaoWrapperFactory.getHandle().getConnection(), futureNotificationTime, notificationKey, context.getUserToken(), context.getAccountRecordId(), context.getTenantRecordId()); } else { log.debug("Skipping queuing overdue check notification. Account id: {}, timestamp: {}", accountId.toString(), futureNotificationTime.toString()); } return null; } });
private boolean addLock(Handle handle, String entryId, LockType lock) throws JsonProcessingException { final String statement = StringUtils.format( "INSERT INTO %1$s (%2$s_id, lock_payload) VALUES (:entryId, :payload)", lockTable, entryTypeName ); return handle.createStatement(statement) .bind("entryId", entryId) .bind("payload", jsonMapper.writeValueAsBytes(lock)) .execute() == 1; }
@Override public T withHandle(Handle handle) throws Exception { final Connection connection = handle.getConnection(); final boolean readOnly = connection.isReadOnly(); connection.setReadOnly(true); try { return handle.inTransaction(callback); } finally { try { connection.setReadOnly(readOnly); } catch (SQLException e) { // at least try to log it so we don't swallow exceptions LOGGER.error(e, "Unable to reset connection read-only state"); } } } }
/** * @param <ReturnType> object type to return from the transaction * @param requestedRO hint as whether to use the read-only connection * @param entitySqlDaoTransactionWrapper transaction to execute * @return result from the transaction fo type ReturnType */ public <ReturnType> ReturnType execute(final boolean requestedRO, final EntitySqlDaoTransactionWrapper<ReturnType> entitySqlDaoTransactionWrapper) { final String debugInfo = logger.isDebugEnabled() ? getDebugInfo() : null; final Handle handle = dbRouter.getHandle(requestedRO); logger.debug("DBI handle created, transaction: {}", debugInfo); try { final EntitySqlDao<EntityModelDao<Entity>, Entity> entitySqlDao = handle.attach(InitialEntitySqlDao.class); // The transaction isolation level is now set at the pool level: this avoids 3 roundtrips for each transaction // Note that if the pool isn't used (tests or PostgreSQL), the transaction level will depend on the DB configuration //return entitySqlDao.inTransaction(TransactionIsolationLevel.READ_COMMITTED, new JdbiTransaction<ReturnType, EntityModelDao<Entity>, Entity>(handle, entitySqlDaoTransactionWrapper)); logger.debug("Starting transaction {}", debugInfo); final ReturnType returnType = entitySqlDao.inTransaction(new JdbiTransaction<ReturnType, EntityModelDao<Entity>, Entity>(handle, entitySqlDaoTransactionWrapper)); logger.debug("Exiting transaction {}, returning {}", debugInfo, returnType); return returnType; } finally { handle.close(); logger.debug("DBI handle closed, transaction: {}", debugInfo); } }
@Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); dbi = new DBI(ds); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); }
@Override public Void withHandle(final Handle handle) throws Exception { // Note: we always create an accounts table, see MysqlTestingHelper handle.execute("insert into tag_definitions (record_id, id, name, description, is_active, created_date, created_by, updated_date, updated_by, tenant_record_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", tagDefinitionRecordId, tagDefinitionId.toString(), "tagdef", "nothing", true, new Date(), "i", new Date(), "j", 0); return null; } });
@Override public Void inTransaction(final Handle conn, final TransactionStatus status) throws Exception { conn.execute("insert into dummy2 (dummy_id) values ('" + UUID.randomUUID().toString() + "')"); return null; } });
@Test public void testFluentUpdate() throws Exception { DBI dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID()); Handle h = dbi.open(); h.execute("create table something (id int primary key, name varchar(100))"); h.createStatement("insert into something(id, name) values (:id, :name)") .bind("id", 4) .bind("name", "Martin") .execute(); h.close(); }
@Before public void createTestData() throws Exception { Handle handle = dbiProvider.get().open(); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(handle.getConnection())); Liquibase liquibase = new Liquibase("singularity_test.sql", new FileSystemResourceAccessor(), database); liquibase.update((String) null); try { database.close(); } catch (Throwable t) { } handle.close(); }
@Test(groups = "slow") public void testRetrieveAuditsDirectly() throws Exception { addTag(); // Verify we get an audit entry for the tag_history table final Handle handle = dbi.open(); final String tagHistoryString = (String) handle.select("select id from tag_history limit 1").get(0).get("id"); handle.close(); for (final AuditLevel level : AuditLevel.values()) { final List<AuditLog> auditLogs = auditDao.getAuditLogsForId(TableName.TAG_HISTORY, UUID.fromString(tagHistoryString), level, internalCallContext); verifyAuditLogsForTag(auditLogs, level); } }
@Test public void testDefines() throws Exception { handle.attach(Wombat.class).weirdInsert("something", "id", "name", 5, "Bouncer"); handle.attach(Wombat.class).weirdInsert("something", "id", "name", 6, "Bean"); String name = handle.createQuery("select name from something where id = 5") .mapTo(String.class) .first(); assertThat(name, equalTo("Bouncer")); }
@Test public void testDoesNotExist() throws Exception { h.execute("insert into something (id, name) values (1, 'Coda')"); h.registerContainerFactory(new MaybeContainerFactory()); Maybe<String> rs = h.createQuery("select name from something where id = :id") .bind("id", 2) .mapTo(String.class) .first(Maybe.class); assertThat(rs.isKnown(), equalTo(false)); }
@Test public void testRegisterOnDBI() throws Exception { dbi.registerArgumentFactory(new NameAF()); Handle h2 = dbi.open(); h2.createStatement("insert into something (id, name) values (:id, :name)") .bind("id", 7) .bind("name", new Name("Brian", "McCallister")) .execute(); String full_name = h.createQuery("select name from something where id = 7").mapTo(String.class).first(); assertThat(full_name, equalTo("Brian McCallister")); h2.close(); }
@Test @Category(JDBIQuarantineTests.class) // Feature disabled public void testRegisterOnHandle() throws Exception { h.registerArgumentFactory(new NameAF()); h.createStatement("insert into something (id, name) values (:id, :name)") .bind("id", 7) .bind("name", new Name("Brian", "McCallister")) .execute(); String full_name = h.createQuery("select name from something where id = 7").map(StringMapper.FIRST).first(); assertThat(full_name, equalTo("Brian McCallister")); }
@Test public void testRegisterOnHandle() throws Exception { h.registerArgumentFactory(new NameAF()); h.createStatement("insert into something (id, name) values (:id, :name)") .bind("id", 7) .bind("name", new Name("Brian", "McCallister")) .execute(); String full_name = h.createQuery("select name from something where id = 7").mapTo(String.class).first(); assertThat(full_name, equalTo("Brian McCallister")); }
@Test public void testOnList() throws Exception { h.registerContainerFactory(new ImmutableListContainerFactory()); h.execute("insert into something (id, name) values (1, 'Coda')"); h.execute("insert into something (id, name) values (2, 'Brian')"); ImmutableList<String> rs = h.createQuery("select name from something order by id") .map(StringMapper.FIRST) .list(ImmutableList.class); assertThat(rs, equalTo(ImmutableList.of("Coda", "Brian"))); }
@Test public void testBaz() throws Exception { Wombat wombat = handle.attach(Wombat.class); wombat.insert(new Something(7, "Henning")); String name = handle.createQuery("select name from something where id = 7") .map(StringMapper.FIRST) .first(); assertThat(name, equalTo("Henning")); }
public String getUserStripeId(int id) { try (Handle handle = dbi.open()) { return handle .createQuery("SELECT stripe_id FROM web_user WHERE id = :id") .bind("id", id).map(StringMapper.FIRST).first(); } }
@Test public void testJustJdbiTransactions() throws Exception { Handle h1 = dbi.open(); Handle h2 = dbi.open(); h1.execute("insert into something (id, name) values (8, 'Mike')"); h1.begin(); h1.execute("update something set name = 'Miker' where id = 8"); assertEquals("Mike", h2.createQuery("select name from something where id = 8").map(StringMapper.FIRST).first()); h1.commit(); h1.close(); h2.close(); }