Java Code Examples for com.j256.ormlite.support.CompiledStatement#close()

The following examples show how to use com.j256.ormlite.support.CompiledStatement#close() . 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: EnumStringTypeTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testEnumStringResultsNoFieldType() throws Exception {
	Dao<LocalEnumString, Object> dao = createDao(LocalEnumString.class, true);
	OurEnum val = OurEnum.SECOND;
	LocalEnumString foo = new LocalEnumString();
	foo.ourEnum = val;
	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());
		assertEquals(val.toString(), DataType.ENUM_STRING.getDataPersister().resultToJava(null, results,
				results.findColumn(ENUM_COLUMN)));
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 2
Source File: SelectIteratorTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testHasNextThrow() 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 database problem"));
	stmt.close();
	replay(stmt, results, cs);
	SelectIterator<Foo, Integer> iterator =
			new SelectIterator<Foo, Integer>(Foo.class, null, null, cs, null, stmt, "statement", null);
	try {
		iterator.hasNext();
	} finally {
		iterator.close();
	}
}
 
Example 3
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 4
Source File: EnumIntegerTypeTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testEnumIntResultsNoFieldType() throws Exception {
	Class<LocalEnumInt> clazz = LocalEnumInt.class;
	Dao<LocalEnumInt, Object> dao = createDao(clazz, true);
	OurEnum val = OurEnum.SECOND;
	LocalEnumInt foo = new LocalEnumInt();
	foo.ourEnum = val;
	assertEquals(1, dao.create(foo));
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(FOO_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());
		assertEquals(val.ordinal(), DataType.ENUM_INTEGER.getDataPersister().resultToJava(null, results,
				results.findColumn(ENUM_COLUMN)));
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 5
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 6
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testDeleteThrow() throws Exception {
	TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(databaseType, Foo.class);
	DatabaseConnection connection = createMock(DatabaseConnection.class);
	@SuppressWarnings("unchecked")
	PreparedDelete<Foo> delete = createMock(PreparedDelete.class);
	CompiledStatement compiledStmt = createMock(CompiledStatement.class);
	expect(delete.compile(connection, StatementType.DELETE)).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, delete);
	try {
		statementExec.delete(connection, delete);
		fail("should have thrown");
	} catch (SQLException e) {
		// expected
	}
	verify(connection, compiledStmt, delete);
}
 
Example 7
Source File: SerializableTypeTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testSerializableNoValue() throws Exception {
	Class<LocalSerializable> clazz = LocalSerializable.class;
	Dao<LocalSerializable, Object> dao = createDao(clazz, true);
	LocalSerializable foo = new LocalSerializable();
	foo.serializable = null;
	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,
				clazz.getDeclaredField(SERIALIZABLE_COLUMN), clazz);
		assertNull(DataType.SERIALIZABLE.getDataPersister().resultToJava(fieldType, results,
				results.findColumn(SERIALIZABLE_COLUMN)));
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 8
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 9
Source File: DateStringTypeTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testDateStringResultInvalid() throws Exception {
	Class<LocalString> clazz = LocalString.class;
	Dao<LocalString, Object> dao = createDao(clazz, true);
	LocalString foo = new LocalString();
	foo.string = "not a date format";
	assertEquals(1, dao.create(foo));
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(FOO_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());
		int colNum = results.findColumn(STRING_COLUMN);
		DataType.DATE_STRING.getDataPersister().resultToJava(null, results, colNum);
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 10
Source File: TableUtilsTest.java    From ormlite-core with ISC License 5 votes vote down vote up
private void testStatement(String tableName, ConnectionSource connectionSource, DatabaseType databaseType,
		String statement, String queryAfter, int rowN, boolean throwExecute, Callable<Integer> callable)
		throws Exception {
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	CompiledStatement stmt = createMock(CompiledStatement.class);
	DatabaseResults results = null;
	final AtomicInteger rowC = new AtomicInteger(1);
	if (throwExecute) {
		expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(FieldType[].class), anyInt(),
				anyBoolean())).andThrow(new SQLException("you asked us to!!"));
	} else {
		expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(FieldType[].class), anyInt(),
				anyBoolean())).andReturn(stmt);
		expect(stmt.runExecute()).andReturn(rowN);
		stmt.close();
		if (queryAfter != null) {
			expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(FieldType[].class),
					anyInt(), anyBoolean())).andReturn(stmt);
			results = createMock(DatabaseResults.class);
			expect(results.first()).andReturn(false);
			expect(stmt.runQuery(null)).andReturn(results);
			stmt.close();
			replay(results);
			rowC.incrementAndGet();
		}
	}
	expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes();
	expect(connectionSource.getReadWriteConnection(tableName)).andReturn(conn);
	connectionSource.releaseConnection(conn);
	replay(connectionSource, conn, stmt);
	// we have to store the value since we count the number of rows in the rowC while call() is happening
	assertEquals((Integer) rowC.get(), callable.call());
	verify(connectionSource, conn, stmt);
	if (queryAfter != null) {
		verify(results);
	}
}
 
Example 11
Source File: ApsTableUtils.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static int doStatements(DatabaseConnection connection, String label, Collection<String> statements,
		boolean ignoreErrors, boolean returnsNegative, boolean expectingZero) throws SQLException {
	int stmtC = 0;
	for (String statement : statements) {
		int rowC = 0;
		CompiledStatement compiledStmt = null;
		try {
			compiledStmt = connection.compileStatement(statement, StatementBuilder.StatementType.EXECUTE, noFieldTypes);
			rowC = compiledStmt.runExecute();
			logger.debug("executed {} table statement changed {} rows: {}", label, rowC, statement);
		} catch (SQLException e) {
			if (ignoreErrors) {
				logger.debug("ignoring {} error '{}' for statement: {}", label, e, statement);
			} else {
				throw SqlExceptionUtil.create("SQL statement failed: " + statement, e);
			}
		} finally {
			if (compiledStmt != null) {
				compiledStmt.close();
			}
		}
		// sanity check
		if (rowC < 0) {
			if (!returnsNegative) {
				throw new SQLException("SQL statement " + statement + " updated " + rowC
						+ " rows, we were expecting >= 0");
			}
		} else if (rowC > 0 && expectingZero) {
			throw new SQLException("SQL statement updated " + rowC + " rows, we were expecting == 0: " + statement);
		}
		stmtC++;
	}
	return stmtC;
}
 
Example 12
Source File: SelectIteratorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testRemoveThrow() throws Exception {
	ConnectionSource cs = createMock(ConnectionSource.class);
	cs.releaseConnection(null);
	CompiledStatement stmt = createMock(CompiledStatement.class);
	DatabaseResults results = createMock(DatabaseResults.class);
	expect(results.first()).andReturn(true);
	expect(stmt.runQuery(null)).andReturn(results);
	@SuppressWarnings("unchecked")
	GenericRowMapper<Foo> mapper = (GenericRowMapper<Foo>) createMock(GenericRowMapper.class);
	Foo foo = new Foo();
	expect(mapper.mapRow(results)).andReturn(foo);
	@SuppressWarnings("unchecked")
	Dao<Foo, Integer> dao = (Dao<Foo, Integer>) createMock(Dao.class);
	expect(dao.delete(foo)).andThrow(new SQLException("some dao problem"));
	stmt.close();
	replay(stmt, dao, results, mapper, cs);
	SelectIterator<Foo, Integer> iterator =
			new SelectIterator<Foo, Integer>(Foo.class, dao, mapper, cs, null, stmt, "statement", null);
	try {
		iterator.hasNext();
		iterator.next();
		iterator.remove();
	} finally {
		iterator.close();
	}
}
 
Example 13
Source File: MappedPreparedQueryTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testMapRow() throws Exception {
	Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, true);
	LocalFoo foo1 = new LocalFoo();
	fooDao.create(foo1);

	TableInfo<LocalFoo, Integer> tableInfo = new TableInfo<LocalFoo, Integer>(databaseType, LocalFoo.class);
	MappedPreparedStmt<LocalFoo, Integer> rowMapper =
			new MappedPreparedStmt<LocalFoo, Integer>(fooDao, tableInfo, null, new FieldType[0],
					tableInfo.getFieldTypes(), new ArgumentHolder[0], null, StatementType.SELECT, false);

	DatabaseConnection conn = connectionSource.getReadOnlyConnection(TABLE_NAME);
	CompiledStatement stmt = null;
	try {
		stmt = conn.compileStatement("select * from " + TABLE_NAME, StatementType.SELECT, new FieldType[0],
				DatabaseConnection.DEFAULT_RESULT_FLAGS, true);

		DatabaseResults results = stmt.runQuery(null);
		while (results.next()) {
			LocalFoo foo2 = rowMapper.mapRow(results);
			assertEquals(foo1.id, foo2.id);
		}
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 14
Source File: ApsTableUtils.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static int doCreateTestQueries(DatabaseConnection connection, DatabaseType databaseType,
		List<String> queriesAfter) throws SQLException {
	int stmtC = 0;
	// now execute any test queries which test the newly created table
	for (String query : queriesAfter) {
		CompiledStatement compiledStmt = null;
		try {
			compiledStmt = connection.compileStatement(query, StatementBuilder.StatementType.SELECT, noFieldTypes);
			// we don't care about an object cache here
			DatabaseResults results = compiledStmt.runQuery(null);
			int rowC = 0;
			// count the results
			for (boolean isThereMore = results.first(); isThereMore; isThereMore = results.next()) {
				rowC++;
			}
			logger.debug("executing create table after-query got {} results: {}", rowC, query);
		} catch (SQLException e) {
			// we do this to make sure that the statement is in the exception
			throw SqlExceptionUtil.create("executing create table after-query failed: " + query, e);
		} finally {
			// result set is closed by the statement being closed
			if (compiledStmt != null) {
				compiledStmt.close();
			}
		}
		stmtC++;
	}
	return stmtC;
}
 
Example 15
Source File: BaseTypeTest.java    From ormlite-core with ISC License 4 votes vote down vote up
protected <T, ID> void testType(Dao<T, ID> dao, T foo, Class<T> clazz, Object javaVal, Object defaultSqlVal,
		Object sqlArg, String defaultValStr, DataType dataType, String columnName, boolean isValidGeneratedType,
		boolean isAppropriateId, boolean isEscapedValue, boolean isPrimitive, boolean isSelectArgRequired,
		boolean isStreamType, boolean isComparable, boolean isConvertableId) throws Exception {
	DataPersister dataPersister = dataType.getDataPersister();
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(TABLE_NAME);
	CompiledStatement stmt = null;
	if (sqlArg != null) {
		assertEquals(defaultSqlVal.getClass(), sqlArg.getClass());
	}
	try {
		stmt = conn.compileStatement("select * from " + TABLE_NAME, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, true);
		DatabaseResults results = stmt.runQuery(null);
		assertTrue(results.next());
		int colNum = results.findColumn(columnName);
		Field field = clazz.getDeclaredField(columnName);
		FieldType fieldType = FieldType.createFieldType(databaseType, TABLE_NAME, field, clazz);
		assertEquals(dataType.getDataPersister(), fieldType.getDataPersister());
		Class<?>[] classes = fieldType.getDataPersister().getAssociatedClasses();
		if (classes.length > 0) {
			assertTrue(classes[0].isAssignableFrom(fieldType.getType()));
		}
		assertTrue(fieldType.getDataPersister().isValidForField(field));
		if (javaVal instanceof byte[]) {
			assertTrue(Arrays.equals((byte[]) javaVal,
					(byte[]) dataPersister.resultToJava(fieldType, results, colNum)));
		} else {
			Map<String, Integer> colMap = new HashMap<String, Integer>();
			colMap.put(columnName, colNum);
			Object result = fieldType.resultToJava(results, colMap);
			assertEquals(javaVal, result);
		}
		if (dataType == DataType.SERIALIZABLE) {
			try {
				dataPersister.parseDefaultString(fieldType, "");
				fail("parseDefaultString should have thrown for " + dataType);
			} catch (SQLException e) {
				// expected
			}
		} else if (defaultValStr != null) {
			Object parsedDefault = dataPersister.parseDefaultString(fieldType, defaultValStr);
			assertEquals(defaultSqlVal.getClass(), parsedDefault.getClass());
			if (dataType == DataType.BYTE_ARRAY || dataType == DataType.STRING_BYTES) {
				assertTrue(Arrays.equals((byte[]) defaultSqlVal, (byte[]) parsedDefault));
			} else {
				assertEquals(defaultSqlVal, parsedDefault);
			}
		}
		if (sqlArg == null) {
			// noop
		} else if (sqlArg instanceof byte[]) {
			assertTrue(Arrays.equals((byte[]) sqlArg, (byte[]) dataPersister.javaToSqlArg(fieldType, javaVal)));
		} else {
			assertEquals(sqlArg, dataPersister.javaToSqlArg(fieldType, javaVal));
		}
		assertEquals(isValidGeneratedType, dataPersister.isValidGeneratedType());
		assertEquals(isAppropriateId, dataPersister.isAppropriateId());
		assertEquals(isEscapedValue, dataPersister.isEscapedValue());
		assertEquals(isEscapedValue, dataPersister.isEscapedDefaultValue());
		assertEquals(isPrimitive, dataPersister.isPrimitive());
		assertEquals(isSelectArgRequired, dataPersister.isArgumentHolderRequired());
		assertEquals(isStreamType, dataPersister.isStreamType());
		assertEquals(isComparable, dataPersister.isComparable());
		if (isConvertableId) {
			assertNotNull(dataPersister.convertIdNumber(10));
		} else {
			assertNull(dataPersister.convertIdNumber(10));
		}
		List<T> list = dao.queryForAll();
		assertEquals(1, list.size());
		assertTrue(dao.objectsEqual(foo, list.get(0)));
		// if we have a value then look for it, floats don't find any results because of rounding issues
		if (javaVal != null && dataPersister.isComparable() && dataType != DataType.FLOAT
				&& dataType != DataType.FLOAT_OBJ) {
			// test for inline arguments
			list = dao.queryForMatching(foo);
			assertEquals(1, list.size());
			assertTrue(dao.objectsEqual(foo, list.get(0)));
			// test for SelectArg arguments
			list = dao.queryForMatchingArgs(foo);
			assertEquals(1, list.size());
			assertTrue(dao.objectsEqual(foo, list.get(0)));
		}
		if (dataType == DataType.STRING_BYTES || dataType == DataType.BYTE_ARRAY
				|| dataType == DataType.SERIALIZABLE) {
			// no converting from string to value
		} else {
			// test string conversion
			String stringVal = results.getString(colNum);
			Object convertedJavaVal = fieldType.convertStringToJavaField(stringVal, 0);
			assertEquals(javaVal, convertedJavaVal);
		}
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 16
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 17
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 18
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);
}