Java Code Examples for com.j256.ormlite.support.ConnectionSource#releaseConnection()

The following examples show how to use com.j256.ormlite.support.ConnectionSource#releaseConnection() . 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: 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 2
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 that returns String[] results.
 */
public GenericRawResults<String[]> queryRaw(ConnectionSource connectionSource, String query, 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);
		GenericRawResults<String[]> rawResults = new RawResultsImpl<String[]>(connectionSource, connection, query,
				String[].class, compiledStatement, this, objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 3
Source File: TransactionManagerTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testTransactionManagerTableName() 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(FOO_TABLE_NAME)).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(FOO_TABLE_NAME, new Callable<Void>() {
		@Override
		public Void call() {
			return null;
		}
	});
	verify(connectionSource, conn, savePoint);
}
 
Example 4
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, DataType[] columnTypes,
		RawRowObjectMapper<UO> rowMapper, 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, String[].class,
				compiledStatement, new UserRawRowObjectMapper<UO>(rowMapper, columnTypes), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 5
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 that returns Object[] results.
 */
public GenericRawResults<Object[]> queryRaw(ConnectionSource connectionSource, String query, DataType[] columnTypes,
		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<Object[]> rawResults = new RawResultsImpl<Object[]>(connectionSource, connection, query,
				Object[].class, compiledStatement, new ObjectArrayRowMapper(columnTypes), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 6
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 7
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
private <CT> CT doCallBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		/*
		 * We are using a thread-local boolean to detect whether we are in the middle of running a number of
		 * changes. This disables the dao change notification for every batched call.
		 */
		localIsInBatchMode.set(true);
		/*
		 * We need to save the connection because we are going to be disabling auto-commit on it and we don't want
		 * pooled connection factories to give us another connection where auto-commit might still be enabled.
		 */
		boolean saved = connectionSource.saveSpecialConnection(connection);
		return doCallBatchTasks(connection, saved, callable);
	} finally {
		// even if the save-special returned false, we need to clear it to decrement the usage counter
		connectionSource.clearSpecialConnection(connection);
		connectionSource.releaseConnection(connection);
		localIsInBatchMode.set(false);
		if (dao != null) {
			// only at the end is the DAO notified of changes
			dao.notifyChanges();
		}
	}
}
 
Example 8
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 9
Source File: SelectIteratorTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testNextThrow() throws Exception {
	ConnectionSource cs = createMock(ConnectionSource.class);
	cs.releaseConnection(null);
	CompiledStatement stmt = createMock(CompiledStatement.class);
	DatabaseResults results = createMock(DatabaseResults.class);
	expect(stmt.runQuery(null)).andReturn(results);
	expect(results.first()).andThrow(new SQLException("some result problem"));
	@SuppressWarnings("unchecked")
	GenericRowMapper<Foo> mapper = (GenericRowMapper<Foo>) createMock(GenericRowMapper.class);
	stmt.close();
	replay(stmt, mapper, cs, results);
	SelectIterator<Foo, Integer> iterator =
			new SelectIterator<Foo, Integer>(Foo.class, null, mapper, cs, null, stmt, "statement", null);
	try {
		iterator.hasNext();
	} finally {
		iterator.close();
	}
	verify(stmt, mapper, cs, results);
}
 
Example 10
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 11
Source File: TableUtils.java    From ormlite-core with ISC License 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();
	List<String> statements = new ArrayList<String>();
	List<String> queriesAfter = new ArrayList<String>();
	addCreateTableStatements(databaseType, tableInfo, statements, queriesAfter, ifNotExists, true);
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		int stmtC = doStatements(connection, "create", statements, false,
				databaseType.isCreateTableReturnsNegative(), databaseType.isCreateTableReturnsZero());
		stmtC += doCreateTestQueries(connection, databaseType, queriesAfter);
		return stmtC;
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example 12
Source File: TransactionManagerTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testTransactionManagerSavePointNull() throws Exception {
	ConnectionSource connectionSource = createMock(ConnectionSource.class);
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(conn.isAutoCommitSupported()).andReturn(false);
	expect(conn.setSavePoint(isA(String.class))).andReturn(null);
	conn.commit(null);
	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);
	TransactionManager tm = new TransactionManager(connectionSource);
	tm.callInTransaction(new Callable<Void>() {
		@Override
		public Void call() {
			return null;
		}
	});
	verify(connectionSource, conn);
}
 
Example 13
Source File: TransactionManagerTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testTransactionManagerRollback() 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.rollback(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);
	try {
		tm.callInTransaction(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				throw new SQLException("you better roll back!!");
			}
		});
		fail("expected an exception");
	} catch (SQLException e) {
		// expected
	}
	verify(connectionSource, conn, savePoint);
}
 
Example 14
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testCallBatchTasksNoAutoCommit() 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(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 15
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);
}
 
Example 16
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testCallBatchTasksAutoCommitTrue() 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(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);
}
 
Example 17
Source File: TableUtilsTest.java    From ormlite-core with ISC License 4 votes vote down vote up
@Test
public void testUniqueIndex() throws Exception {
	final ConnectionSource connectionSource = createMock(ConnectionSource.class);
	expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes();
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(connectionSource.getReadWriteConnection("uniqueindex")).andReturn(conn);
	final CompiledStatement stmt = createMock(CompiledStatement.class);
	expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(FieldType[].class), anyInt(),
			anyBoolean())).andAnswer(new IAnswer<CompiledStatement>() {
				private int stmtC = 0;

				@Override
				public CompiledStatement answer() {
					Object[] args = EasyMock.getCurrentArguments();
					assertNotNull(args);
					assertEquals("was expecting a call with 5 args", 5, args.length);
					if (stmtC == 0) {
						assertEquals("CREATE TABLE `uniqueindex` (`stuff` VARCHAR(255) ) ", args[0]);
					} else if (stmtC == 1) {
						assertEquals("CREATE UNIQUE INDEX `uniqueindex_stuff_idx` ON `uniqueindex` ( `stuff` )",
								args[0]);
					} else if (stmtC == 2) {
						assertEquals("DROP INDEX `uniqueindex_stuff_idx`", args[0]);
					} else if (stmtC == 3) {
						assertEquals("DROP TABLE `uniqueindex` ", args[0]);
					} else {
						fail("Should only be called 4 times");
					}
					stmtC++;
					assertEquals(StatementType.EXECUTE, args[1]);
					assertEquals(0, ((FieldType[]) args[2]).length);
					return stmt;
				}
			}).anyTimes();
	expect(stmt.runExecute()).andReturn(0).anyTimes();
	connectionSource.releaseConnection(conn);
	expect(connectionSource.getReadWriteConnection("uniqueindex")).andReturn(conn);
	connectionSource.releaseConnection(conn);
	expectLastCall().anyTimes();
	stmt.close();
	expectLastCall().anyTimes();
	replay(connectionSource, conn, stmt);
	TableUtils.createTable(connectionSource, UniqueIndex.class);
	TableUtils.dropTable(connectionSource, UniqueIndex.class, false);
	verify(connectionSource, conn, stmt);
}
 
Example 18
Source File: TableUtilsTest.java    From ormlite-core with ISC License 4 votes vote down vote up
@Test
public void testIndex() throws Exception {
	final ConnectionSource connectionSource = createMock(ConnectionSource.class);
	expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes();
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(connectionSource.getReadWriteConnection("index")).andReturn(conn);
	final CompiledStatement stmt = createMock(CompiledStatement.class);
	expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(FieldType[].class), anyInt(),
			anyBoolean())).andAnswer(new IAnswer<CompiledStatement>() {
				private int stmtC = 0;

				@Override
				public CompiledStatement answer() {
					Object[] args = EasyMock.getCurrentArguments();
					assertNotNull(args);
					assertEquals("was expecting a call with 5 args", 5, args.length);
					if (stmtC == 0) {
						assertEquals("CREATE TABLE `index` (`stuff` VARCHAR(255) ) ", args[0]);
					} else if (stmtC == 1) {
						assertEquals("CREATE INDEX `index_stuff_idx` ON `index` ( `stuff` )", args[0]);
					} else if (stmtC == 2) {
						assertEquals("DROP INDEX `index_stuff_idx`", args[0]);
					} else if (stmtC == 3) {
						assertEquals("DROP TABLE `index` ", args[0]);
					} else {
						fail("Should only be called 4 times");
					}
					stmtC++;
					assertEquals(StatementType.EXECUTE, args[1]);
					assertEquals(0, ((FieldType[]) args[2]).length);
					return stmt;
				}
			}).anyTimes();
	expect(stmt.runExecute()).andReturn(0).anyTimes();
	connectionSource.releaseConnection(conn);
	expect(connectionSource.getReadWriteConnection("index")).andReturn(conn);
	connectionSource.releaseConnection(conn);
	expectLastCall().anyTimes();
	stmt.close();
	expectLastCall().anyTimes();
	replay(connectionSource, conn, stmt);
	TableUtils.createTable(connectionSource, Index.class);
	TableUtils.dropTable(connectionSource, Index.class, true);
	verify(connectionSource, conn, stmt);
}
 
Example 19
Source File: TableUtilsTest.java    From ormlite-core with ISC License 4 votes vote down vote up
@Test
public void testComboIndex() throws Exception {
	final ConnectionSource connectionSource = createMock(ConnectionSource.class);
	expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes();
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(connectionSource.getReadWriteConnection("comboindex")).andReturn(conn);
	final CompiledStatement stmt = createMock(CompiledStatement.class);
	expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(FieldType[].class), anyInt(),
			anyBoolean())).andAnswer(new IAnswer<CompiledStatement>() {
				private int stmtC = 0;

				@Override
				public CompiledStatement answer() {
					Object[] args = EasyMock.getCurrentArguments();
					assertNotNull(args);
					assertEquals("was expecting a call with 5 args", 5, args.length);
					if (stmtC == 0) {
						assertEquals("CREATE TABLE `comboindex` (`stuff` VARCHAR(255) , `junk` BIGINT ) ", args[0]);
					} else if (stmtC == 1) {
						assertEquals(
								"CREATE INDEX `" + ComboIndex.INDEX_NAME + "` ON `comboindex` ( `stuff`, `junk` )",
								args[0]);
					} else if (stmtC == 2) {
						assertEquals("DROP INDEX `" + ComboIndex.INDEX_NAME + "`", args[0]);
					} else if (stmtC == 3) {
						assertEquals("DROP TABLE `comboindex` ", args[0]);
					} else {
						fail("Should only be called 4 times");
					}
					stmtC++;
					assertEquals(StatementType.EXECUTE, args[1]);
					assertEquals(0, ((FieldType[]) args[2]).length);
					return stmt;
				}
			}).anyTimes();
	expect(stmt.runExecute()).andReturn(0).anyTimes();
	connectionSource.releaseConnection(conn);
	expect(connectionSource.getReadWriteConnection("comboindex")).andReturn(conn);
	connectionSource.releaseConnection(conn);
	expectLastCall().anyTimes();
	stmt.close();
	expectLastCall().anyTimes();
	replay(connectionSource, conn, stmt);
	TableUtils.createTable(connectionSource, ComboIndex.class);
	TableUtils.dropTable(connectionSource, ComboIndex.class, false);
	verify(connectionSource, conn, stmt);
}
 
Example 20
Source File: FieldType.java    From ormlite-core with ISC License 4 votes vote down vote up
private Object createForeignObject(ConnectionSource connectionSource, Object val, ObjectCache objectCache)
		throws SQLException {

	// try to stop the level counters objects from being created
	LevelCounters levelCounters = threadLevelCounters.get();
	if (levelCounters == null) {
		// only create a shell if we are not in auto-refresh mode
		if (!fieldConfig.isForeignAutoRefresh()) {
			return createForeignShell(connectionSource, val, objectCache);
		}
		levelCounters = new LevelCounters();
		threadLevelCounters.set(levelCounters);
	}

	// we record the current auto-refresh level which will be used along the way
	if (levelCounters.autoRefreshLevel == 0) {
		// if we aren't in an auto-refresh loop then don't _start_ an new loop if auto-refresh is not configured
		if (!fieldConfig.isForeignAutoRefresh()) {
			return createForeignShell(connectionSource, val, objectCache);
		}
		levelCounters.autoRefreshLevelMax = fieldConfig.getMaxForeignAutoRefreshLevel();
	}
	// if we have recursed the proper number of times, return a shell with just the id set
	if (levelCounters.autoRefreshLevel >= levelCounters.autoRefreshLevelMax) {
		return createForeignShell(connectionSource, val, objectCache);
	}

	/*
	 * We may not have a mapped query for id because we aren't auto-refreshing ourselves. But a parent class may be
	 * auto-refreshing us with a level > 1 so we may need to build our query-for-id optimization on the fly here.
	 */
	if (mappedQueryForForeignField == null) {
		@SuppressWarnings("unchecked")
		Dao<Object, Object> castDao = (Dao<Object, Object>) foreignDao;
		MappedQueryForFieldEq<Object, Object> castMappedQueryForId =
				MappedQueryForFieldEq.build(castDao, castDao.getTableInfo(), foreignIdField);
		mappedQueryForForeignField = castMappedQueryForId;
	}
	levelCounters.autoRefreshLevel++;
	try {
		DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(tableName);
		try {
			// recurse and get the sub-object
			@SuppressWarnings("unchecked")
			MappedQueryForFieldEq<Object, Object> castMappedQueryForForeignField =
					(MappedQueryForFieldEq<Object, Object>) mappedQueryForForeignField;
			return castMappedQueryForForeignField.execute(databaseConnection, val, objectCache);
		} finally {
			connectionSource.releaseConnection(databaseConnection);
		}
	} finally {
		levelCounters.autoRefreshLevel--;
		if (levelCounters.autoRefreshLevel <= 0) {
			threadLevelCounters.remove();
		}
	}
}