com.j256.ormlite.support.DatabaseConnection Java Examples

The following examples show how to use com.j256.ormlite.support.DatabaseConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SerializableTypeTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testSerializableInvalidResult() throws Exception {
	Class<LocalByteArray> clazz = LocalByteArray.class;
	Dao<LocalByteArray, Object> dao = createDao(clazz, true);
	LocalByteArray foo = new LocalByteArray();
	foo.byteField = new byte[] { 1, 2, 3, 4, 5 };
	assertEquals(1, dao.create(foo));
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(TABLE_NAME);
	CompiledStatement stmt = null;
	try {
		stmt = conn.compileStatement("select * from " + TABLE_NAME, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, true);
		DatabaseResults results = stmt.runQuery(null);
		assertTrue(results.next());
		FieldType fieldType = FieldType.createFieldType(databaseType, TABLE_NAME,
				LocalSerializable.class.getDeclaredField(SERIALIZABLE_COLUMN), LocalSerializable.class);
		DataType.SERIALIZABLE.getDataPersister().resultToJava(fieldType, results, results.findColumn(BYTE_COLUMN));
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example #2
Source File: MemoryDBFixture.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void memorySetUp() throws SQLException, CyclicGroupError, CryptoError, MitroServletException {
  // Create a fake SecretsBundle
  TwoFactorSigningService.initialize(SecretsBundle.generateForTest());
  groupToPrivateKeyMap = Maps.newHashMap();
  JdbcConnectionSource connectionSource = new JdbcConnectionSource(DATABASE_URL);
  connectionSource.getReadWriteConnection().executeStatement(
      "DROP ALL OBJECTS", DatabaseConnection.DEFAULT_RESULT_FLAGS);
  managerFactory = new ManagerFactory(DATABASE_URL, new Manager.Pool(),
      ManagerFactory.IDLE_TXN_POLL_SECONDS, TimeUnit.SECONDS, ConnectionMode.READ_WRITE);
  manager = managerFactory.newManager();
  testIdentityKey = keyFactory.generate();
  testIdentity = createIdentity("[email protected]", testIdentityKey);
  testIdentityLoginToken = GetMyPrivateKey.makeLoginTokenString(testIdentity, null, null);
  testIdentityLoginTokenSignature = testIdentityKey.sign(testIdentityLoginToken);

  testIdentity2 = createIdentity("[email protected]", null);
     
  testGroup = createGroupContainingIdentity(testIdentity);
  manager.commitTransaction();

  // remove the audit log that commit writes so that tests start with an empty log
  connectionSource.getReadWriteConnection().executeStatement(
      "DELETE FROM audit;", DatabaseConnection.DEFAULT_RESULT_FLAGS);
  connectionSource.getReadWriteConnection().commit(null);
}
 
Example #3
Source File: BaseDaoImpl.java    From ormlite-core with ISC License 6 votes vote down vote up
@Override
public int update(T data) throws SQLException {
	checkForInitialized();
	// ignore updating a null object
	if (data == null) {
		return 0;
	}
	if (data instanceof BaseDaoEnabled) {
		@SuppressWarnings("unchecked")
		BaseDaoEnabled<T, ID> daoEnabled = (BaseDaoEnabled<T, ID>) data;
		daoEnabled.setDao(this);
	}
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		return statementExecutor.update(connection, data, objectCache);
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example #4
Source File: H2DatabaseTypeTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testRemotePort() throws Exception {
	File dbDir = new File(DB_DIRECTORY);
	TestUtils.deleteDirectory(dbDir);
	dbDir.mkdirs();
	// bad port
	int notTheRightPort = 12345;
	closeConnectionSource();
	// try to disable the retry feature which delays this test failure
	System.setProperty("h2.socketConnectRetry", "0");
	String dbUrl = "jdbc:h2:tcp://localhost:" + notTheRightPort + "/" + dbDir.getPath() + "/" + DATABASE_NAME;
	connectionSource = new JdbcConnectionSource(dbUrl);
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(null);
	try {
		DatabaseTypeUtils.createDatabaseType(dbUrl);
	} finally {
		connectionSource.releaseConnection(conn);
	}
}
 
Example #5
Source File: JdbcPooledConnectionSourceTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testConnectionRollback() throws Exception {
	JdbcPooledConnectionSource pooled = new JdbcPooledConnectionSource(DEFAULT_DATABASE_URL);
	Dao<Foo, Integer> dao = null;
	DatabaseConnection conn = null;
	try {
		TableUtils.createTable(pooled, Foo.class);
		dao = DaoManager.createDao(pooled, Foo.class);
		conn = dao.startThreadConnection();
		dao.setAutoCommit(conn, false);
		Foo foo = new Foo();
		assertEquals(1, dao.create(foo));
		assertNotNull(dao.queryForId(foo.id));
		dao.endThreadConnection(conn);
		assertNull(dao.queryForId(foo.id));
	} finally {
		TableUtils.dropTable(pooled, Foo.class, true);
		if (dao != null) {
			dao.endThreadConnection(conn);
		}
		pooled.close();
	}
}
 
Example #6
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a long from a raw query with String[] arguments.
 */
public long queryForLong(DatabaseConnection databaseConnection, String query, String[] arguments)
		throws SQLException {
	logger.debug("executing raw query for long: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	CompiledStatement compiledStatement = null;
	DatabaseResults results = null;
	try {
		compiledStatement = databaseConnection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		results = compiledStatement.runQuery(null);
		if (results.first()) {
			return results.getLong(0);
		} else {
			throw new SQLException("No result found in queryForLong: " + query);
		}
	} finally {
		IOUtils.closeThrowSqlException(results, "results");
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example #7
Source File: ApsTableUtils.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static <T, ID> int doCreateTable(ConnectionSource connectionSource, TableInfo<T, ID> tableInfo,
		boolean ifNotExists) throws SQLException {
	DatabaseType databaseType = connectionSource.getDatabaseType();
	logger.debug("creating table '{}'", tableInfo.getTableName());
	List<String> statements = new ArrayList<String>();
	List<String> queriesAfter = new ArrayList<String>();
	addCreateTableStatements(databaseType, tableInfo, statements, queriesAfter, ifNotExists);
	DatabaseConnection connection = connectionSource.getReadWriteConnection();
	try {
		int stmtC =
				doStatements(connection, "create", statements, false, databaseType.isCreateTableReturnsNegative(),
						databaseType.isCreateTableReturnsZero());
		stmtC += doCreateTestQueries(connection, databaseType, queriesAfter);
		return stmtC;
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example #8
Source File: JdbcPooledConnectionSourceTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testAuthTestConnectionExpired() throws Exception {
	JdbcPooledConnectionSource pooled = new JdbcPooledConnectionSource(DEFAULT_DATABASE_URL);
	long delay = 100;
	pooled.setCheckConnectionsEveryMillis(delay);
	pooled.setMaxConnectionAgeMillis(delay);
	String pingStatement = pooled.getDatabaseType().getPingStatement();
	try {
		DatabaseConnection conn1 = pooled.getReadWriteConnection(null);
		conn1.queryForLong(pingStatement);
		pooled.releaseConnection(conn1);
		// make it test ok once
		Thread.sleep(delay * 2);
		DatabaseConnection conn2 = pooled.getReadWriteConnection(null);
		assertNotSame(conn1, conn2);
		conn2.queryForLong(pingStatement);
		pooled.releaseConnection(conn2);
	} finally {
		pooled.close();
	}
}
 
Example #9
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testUpdateThrow() throws Exception {
	TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(databaseType, Foo.class);
	DatabaseConnection connection = createMock(DatabaseConnection.class);
	@SuppressWarnings("unchecked")
	PreparedUpdate<Foo> update = createMock(PreparedUpdate.class);
	CompiledStatement compiledStmt = createMock(CompiledStatement.class);
	expect(update.compile(connection, StatementType.UPDATE)).andReturn(compiledStmt);
	expect(compiledStmt.runUpdate()).andThrow(new SQLException("expected"));
	compiledStmt.close();
	StatementExecutor<Foo, String> statementExec =
			new StatementExecutor<Foo, String>(databaseType, tableInfo, null);
	replay(connection, compiledStmt, update);
	try {
		statementExec.update(connection, update);
		fail("should have thrown");
	} catch (SQLException e) {
		// expected
	}
	verify(connection, compiledStmt, update);
}
 
Example #10
Source File: JdbcPooledConnectionSourceTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testTestConnectionThatWasClosed() throws Exception {
	JdbcPooledConnectionSource pooled = new JdbcPooledConnectionSource(DEFAULT_DATABASE_URL);
	String pingStatement = pooled.getDatabaseType().getPingStatement();
	try {
		DatabaseConnection conn1 = pooled.getReadWriteConnection(null);
		conn1.queryForLong(pingStatement);
		pooled.releaseConnection(conn1);
		// close it behind the pool's back, bad dog
		conn1.close();
		DatabaseConnection conn2 = pooled.getReadWriteConnection(null);
		assertSame(conn1, conn2);
		conn2.queryForLong(pingStatement);
	} finally {
		pooled.close();
	}
}
 
Example #11
Source File: TransactionManagerTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testTransactionManagerAutoCommitSupported() throws Exception {
	ConnectionSource connectionSource = createMock(ConnectionSource.class);
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(conn.isAutoCommitSupported()).andReturn(true);
	expect(conn.isAutoCommit()).andReturn(false);
	Savepoint savePoint = createMock(Savepoint.class);
	expect(savePoint.getSavepointName()).andReturn("name").anyTimes();
	expect(conn.setSavePoint(isA(String.class))).andReturn(savePoint);
	conn.commit(savePoint);
	expect(connectionSource.getDatabaseType()).andReturn(databaseType);
	expect(connectionSource.getReadWriteConnection(null)).andReturn(conn);
	expect(connectionSource.saveSpecialConnection(conn)).andReturn(true);
	connectionSource.clearSpecialConnection(conn);
	connectionSource.releaseConnection(conn);
	replay(connectionSource, conn, savePoint);
	TransactionManager tm = new TransactionManager(connectionSource);
	tm.callInTransaction(new Callable<Void>() {
		@Override
		public Void call() {
			return null;
		}
	});
	verify(connectionSource, conn, savePoint);
}
 
Example #12
Source File: JdbcPooledConnectionSourceTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testTransaction() throws Exception {
	JdbcPooledConnectionSource pooled = new JdbcPooledConnectionSource(DEFAULT_DATABASE_URL);
	try {
		DatabaseConnection conn1 = pooled.getReadOnlyConnection(null);
		DatabaseConnection conn2 = pooled.getReadWriteConnection(null);
		pooled.saveSpecialConnection(conn2);
		DatabaseConnection conn3 = pooled.getReadWriteConnection(null);
		assertSame(conn2, conn3);
		pooled.releaseConnection(conn3);
		pooled.releaseConnection(conn1);
		DatabaseConnection conn4 = pooled.getReadWriteConnection(null);
		assertSame(conn2, conn4);
		pooled.releaseConnection(conn4);
		pooled.clearSpecialConnection(conn2);
		DatabaseConnection conn5 = pooled.getReadWriteConnection(null);
		assertSame(conn1, conn5);
		conn1.close();
		conn2.close();
		conn3.close();
		conn4.close();
		conn5.close();
	} finally {
		pooled.close();
	}
}
 
Example #13
Source File: JdbcDatabaseConnectionTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testIdColumnChangedFromStringToNumber() throws Exception {
	// NOTE: trying to get the database to return a string as a result but could not figure it out
	DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(FOOSTRING_TABLE_NAME);
	try {
		createDao(FooString.class, true);
		GeneratedKeyHolder keyHolder = createMock(GeneratedKeyHolder.class);
		expect(keyHolder.getColumnName()).andReturn("id");
		keyHolder.addKey(or(eq(0), eq(0L))); // Depends on driver
		replay(keyHolder);
		StringBuilder sb = new StringBuilder();
		sb.append("insert into foostring (");
		databaseType.appendEscapedEntityName(sb, "id");
		sb.append(", ");
		databaseType.appendEscapedEntityName(sb, "stuff");
		sb.append(") values ('12', 'zipper')");
		databaseConnection.insert(sb.toString(), new Object[0], new FieldType[0], keyHolder);
		verify(keyHolder);
	} finally {
		connectionSource.releaseConnection(databaseConnection);
	}
}
 
Example #14
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
public boolean ifExists(DatabaseConnection connection, ID id) throws SQLException {
	if (ifExistsQuery == null) {
		QueryBuilder<T, ID> qb = new QueryBuilder<T, ID>(databaseType, tableInfo, dao);
		qb.selectRaw("COUNT(*)");
		/*
		 * NOTE: bit of a hack here because the select arg is never used but it _can't_ be a constant because we set
		 * field-name and field-type on it.
		 */
		qb.where().eq(tableInfo.getIdField().getColumnName(), new SelectArg());
		ifExistsQuery = qb.prepareStatementString();
		ifExistsFieldTypes = new FieldType[] { tableInfo.getIdField() };
	}
	Object idSqlArg = tableInfo.getIdField().convertJavaFieldToSqlArgValue(id);
	long count = connection.queryForLong(ifExistsQuery, new Object[] { idSqlArg }, ifExistsFieldTypes);
	logger.debug("query of '{}' returned {}", ifExistsQuery, count);
	return (count != 0);
}
 
Example #15
Source File: SelectIterator.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * If the statement parameter is null then this won't log information
 */
public SelectIterator(Class<?> dataClass, Dao<T, ID> classDao, GenericRowMapper<T> rowMapper,
		ConnectionSource connectionSource, DatabaseConnection connection, CompiledStatement compiledStmt,
		String statement, ObjectCache objectCache) throws SQLException {
	this.dataClass = dataClass;
	this.classDao = classDao;
	this.rowMapper = rowMapper;
	this.connectionSource = connectionSource;
	this.connection = connection;
	this.compiledStmt = compiledStmt;
	this.results = compiledStmt.runQuery(objectCache);
	this.statement = statement;
	if (statement != null) {
		logger.debug("starting iterator @{} for '{}'", hashCode(), statement);
	}
}
 
Example #16
Source File: JdbcDatabaseConnectionTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testQueryKeyHolderNoKeys() throws Exception {
	DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(FOO_TABLE_NAME);
	try {
		createDao(Foo.class, true);
		GeneratedKeyHolder keyHolder = createMock(GeneratedKeyHolder.class);
		expect(keyHolder.getColumnName()).andReturn("id");
		keyHolder.addKey(or(eq(0), eq(0L))); // Depends on driver
		replay(keyHolder);
		StringBuilder sb = new StringBuilder();
		sb.append("insert into foo (");
		databaseType.appendEscapedEntityName(sb, "id");
		sb.append(") values (2)");
		databaseConnection.insert(sb.toString(), new Object[0], new FieldType[0], keyHolder);
		verify(keyHolder);
	} finally {
		connectionSource.releaseConnection(databaseConnection);
	}
}
 
Example #17
Source File: JdbcDatabaseConnectionTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testQueryForLong() throws Exception {
	DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(FOO_TABLE_NAME);
	try {
		Dao<Foo, Object> dao = createDao(Foo.class, true);
		Foo foo = new Foo();
		long id = 21321321L;
		foo.id = id;
		assertEquals(1, dao.create(foo));

		StringBuilder sb = new StringBuilder();
		sb.append("select ");
		databaseType.appendEscapedEntityName(sb, "id");
		sb.append(" from foo");
		assertEquals(id, databaseConnection.queryForLong(sb.toString()));
	} finally {
		connectionSource.releaseConnection(databaseConnection);
	}
}
 
Example #18
Source File: SchemaUtils.java    From ormlite-core with ISC License 6 votes vote down vote up
private static <T, ID> int doCreateSchema(ConnectionSource connectionSource, String schemaName,
                                          boolean ifNotExists) throws SQLException {
    DatabaseType databaseType = connectionSource.getDatabaseType();
    List<String> statements = new ArrayList<String>();
    List<String> queriesAfter = new ArrayList<String>();
    addCreateSchemaStatements(databaseType, schemaName, statements, queriesAfter, ifNotExists, true);
    DatabaseConnection connection = connectionSource.getReadWriteConnection(schemaName);
    try {
        int stmtC = doStatements(connection, "create", statements, false,
                databaseType.isCreateSchemaReturnsNegative(), databaseType.isCreateSchemaReturnsZero());
        stmtC += doCreateTestQueries(connection, databaseType, queriesAfter);
        return stmtC;
    } finally {
        connectionSource.releaseConnection(connection);
    }
}
 
Example #19
Source File: MappedCreateTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testGeneratedId() throws Exception {
	TableInfo<GeneratedId, Integer> tableInfo =
			new TableInfo<GeneratedId, Integer>(databaseType, GeneratedId.class);
	Dao<GeneratedId, Integer> dao = createDao(GeneratedId.class, false);
	StatementExecutor<GeneratedId, Integer> se =
			new StatementExecutor<GeneratedId, Integer>(databaseType, tableInfo, dao);
	DatabaseConnection databaseConnection = createMock(DatabaseConnection.class);
	databaseConnection.insert(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			isA(GeneratedKeyHolder.class));
	expectLastCall().andAnswer(new IAnswer<Object>() {
		@Override
		public Integer answer() throws Throwable {
			GeneratedKeyHolder keyHolder = (GeneratedKeyHolder) (getCurrentArguments()[3]);
			keyHolder.addKey(2);
			return 1;
		}
	});
	replay(databaseConnection);
	GeneratedId genIdSeq = new GeneratedId();
	se.create(databaseConnection, genIdSeq, null);
	verify(databaseConnection);
}
 
Example #20
Source File: TransactionManagerTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testTransactionManager() throws Exception {
	ConnectionSource connectionSource = createMock(ConnectionSource.class);
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(conn.isAutoCommitSupported()).andReturn(false);
	Savepoint savePoint = createMock(Savepoint.class);
	expect(savePoint.getSavepointName()).andReturn("name").anyTimes();
	expect(conn.setSavePoint(isA(String.class))).andReturn(savePoint);
	conn.commit(savePoint);
	expect(connectionSource.getDatabaseType()).andReturn(databaseType);
	expect(connectionSource.getReadWriteConnection(null)).andReturn(conn);
	expect(connectionSource.saveSpecialConnection(conn)).andReturn(true);
	connectionSource.clearSpecialConnection(conn);
	connectionSource.releaseConnection(conn);
	replay(connectionSource, conn, savePoint);
	TransactionManager tm = new TransactionManager(connectionSource);
	tm.callInTransaction(new Callable<Void>() {
		@Override
		public Void call() {
			return null;
		}
	});
	verify(connectionSource, conn, savePoint);
}
 
Example #21
Source File: JdbcConnectionSource.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
/**
 * Make a connection to the database.
 * 
 * @param logger
 *            This is here so we can use the right logger associated with the sub-class.
 */
@SuppressWarnings("resource")
protected DatabaseConnection makeConnection(Logger logger) throws SQLException {
	Properties properties = new Properties();
	if (username != null) {
		properties.setProperty("user", username);
	}
	if (password != null) {
		properties.setProperty("password", password);
	}
	DatabaseConnection connection = new JdbcDatabaseConnection(DriverManager.getConnection(url, properties));
	// by default auto-commit is set to true
	connection.setAutoCommit(true);
	if (connectionProxyFactory != null) {
		connection = connectionProxyFactory.createProxy(connection);
	}
	logger.debug("opened connection to {} got #{}", url, connection.hashCode());
	return connection;
}
 
Example #22
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a results object associated with an internal iterator is mapped by the user's rowMapper.
 */
public <UO> GenericRawResults<UO> queryRaw(ConnectionSource connectionSource, String query,
		DatabaseResultsMapper<UO> mapper, String[] arguments, ObjectCache objectCache) throws SQLException {
	logger.debug("executing raw query for: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		RawResultsImpl<UO> rawResults = new RawResultsImpl<UO>(connectionSource, connection, query, Object[].class,
				compiledStatement, new UserDatabaseResultsMapper<UO>(mapper), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example #23
Source File: MappedCreateTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test(expected = SQLException.class)
public void testSequenceZero() throws Exception {
	DatabaseConnection databaseConnection = createMock(DatabaseConnection.class);
	expect(databaseConnection.queryForLong(isA(String.class))).andReturn(0L);
	replay(databaseConnection);
	NeedsSequenceDatabaseType needsSequence = new NeedsSequenceDatabaseType();
	Dao<GeneratedIdSequence, Integer> dao = createDao(GeneratedIdSequence.class, false);
	MappedCreate<GeneratedIdSequence, Integer> mappedCreate = MappedCreate.build(dao,
			new TableInfo<GeneratedIdSequence, Integer>(databaseType, GeneratedIdSequence.class));
	mappedCreate.insert(needsSequence, databaseConnection, new GeneratedIdSequence(), null);
	verify(databaseConnection);
}
 
Example #24
Source File: BaseDaoImpl.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public int delete(PreparedDelete<T> preparedDelete) throws SQLException {
	checkForInitialized();
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		return statementExecutor.delete(connection, preparedDelete);
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example #25
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testCallBatchTasksAutoCommitFalse() throws Exception {
	TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(databaseType, Foo.class);

	ConnectionSource connectionSource = createMock(ConnectionSource.class);
	DatabaseConnection connection = createMock(DatabaseConnection.class);
	expect(connectionSource.isSingleConnection("foo")).andReturn(false);
	expect(connectionSource.getReadWriteConnection("foo")).andReturn(connection);
	expect(connectionSource.saveSpecialConnection(connection)).andReturn(false);
	connectionSource.clearSpecialConnection(connection);
	connectionSource.releaseConnection(connection);

	expect(connection.isAutoCommitSupported()).andReturn(true);
	expect(connection.isAutoCommit()).andReturn(false);
	StatementExecutor<Foo, String> statementExec =
			new StatementExecutor<Foo, String>(databaseType, tableInfo, null);
	replay(connectionSource, connection);
	final AtomicBoolean called = new AtomicBoolean(false);
	statementExec.callBatchTasks(connectionSource, new Callable<Void>() {
		@Override
		public Void call() {
			called.set(true);
			return null;
		}
	});
	assertTrue(called.get());
	verify(connectionSource, connection);
}
 
Example #26
Source File: RuntimeExceptionDao.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * @see Dao#commit(DatabaseConnection)
 */
@Override
public void commit(DatabaseConnection connection) {
	try {
		dao.commit(connection);
	} catch (SQLException e) {
		logMessage(e, "commit(" + connection + ") threw exception");
		throw new RuntimeException(e);
	}
}
 
Example #27
Source File: JdbcDatabaseConnectionTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Test(expected = SQLException.class)
public void testQueryForLongNoResult() throws Exception {
	DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(FOO_TABLE_NAME);
	try {
		createDao(Foo.class, true);

		StringBuilder sb = new StringBuilder();
		sb.append("select ");
		databaseType.appendEscapedEntityName(sb, "id");
		sb.append(" from foo");
		databaseConnection.queryForLong(sb.toString());
	} finally {
		connectionSource.releaseConnection(databaseConnection);
	}
}
 
Example #28
Source File: BaseDaoImplTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test(expected = SQLException.class)
public void testUpdateRawThrow() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo = new Foo();
	assertEquals(1, dao.create(foo));
	DatabaseConnection conn = connectionSource.getReadWriteConnection(FOO_TABLE_NAME);
	try {
		conn.close();
		dao.updateRaw("DELETE FROM FOO");
	} finally {
		connectionSource.releaseConnection(conn);
	}
}
 
Example #29
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public DatabaseConnection getReadOnlyConnection(String tableName) throws SQLException {
	DatabaseConnection conn = getSavedConnection();
	if (conn == null) {
		return connectionSource.getReadOnlyConnection(tableName);
	} else {
		return conn;
	}
}
 
Example #30
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testCallBatchTasksAutoCommitTrueSynchronized() throws Exception {
	TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(databaseType, Foo.class);

	ConnectionSource connectionSource = createMock(ConnectionSource.class);
	DatabaseConnection connection = createMock(DatabaseConnection.class);
	expect(connectionSource.isSingleConnection("foo")).andReturn(true);
	expect(connectionSource.getReadWriteConnection("foo")).andReturn(connection);
	expect(connectionSource.saveSpecialConnection(connection)).andReturn(false);
	connectionSource.clearSpecialConnection(connection);
	connectionSource.releaseConnection(connection);

	expect(connection.isAutoCommitSupported()).andReturn(true);
	expect(connection.isAutoCommit()).andReturn(true);
	connection.setAutoCommit(false);
	connection.setAutoCommit(true);
	StatementExecutor<Foo, String> statementExec =
			new StatementExecutor<Foo, String>(databaseType, tableInfo, null);
	replay(connectionSource, connection);
	final AtomicBoolean called = new AtomicBoolean(false);
	statementExec.callBatchTasks(connectionSource, new Callable<Void>() {
		@Override
		public Void call() {
			called.set(true);
			return null;
		}
	});
	assertTrue(called.get());
	verify(connectionSource, connection);
}