com.j256.ormlite.support.CompiledStatement Java Examples

The following examples show how to use com.j256.ormlite.support.CompiledStatement. 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: 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,
		RawRowMapper<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 UserRawRowMapper<UO>(rowMapper, this), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example #2
Source File: TableUtils.java    From ormlite-core with ISC License 6 votes vote down vote up
private static <T> int clearTable(ConnectionSource connectionSource, String schemaName, String tableName) throws SQLException {
	DatabaseType databaseType = connectionSource.getDatabaseType();
	StringBuilder sb = new StringBuilder(48);
	if (databaseType.isTruncateSupported()) {
		sb.append("TRUNCATE TABLE ");
	} else {
		sb.append("DELETE FROM ");
	}
	if (schemaName != null && schemaName.length() > 0){
		databaseType.appendEscapedEntityName(sb, schemaName);
		sb.append('.');
	}
	databaseType.appendEscapedEntityName(sb, tableName);
	String statement = sb.toString();
	logger.info("clearing table '{}' with '{}", tableName, statement);
	CompiledStatement compiledStmt = null;
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableName);
	try {
		compiledStmt = connection.compileStatement(statement, StatementType.EXECUTE, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		return compiledStmt.runExecute();
	} finally {
		IOUtils.closeThrowSqlException(compiledStmt, "compiled statement");
		connectionSource.releaseConnection(connection);
	}
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return true if it worked else false.
 */
public int executeRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {
	logger.debug("running raw execute statement: {}", statement);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("execute arguments: {}", (Object) arguments);
	}
	CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.EXECUTE,
			noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
	try {
		assignStatementArguments(compiledStatement, arguments);
		return compiledStatement.runExecute();
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example #10
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return the number of rows affected.
 */
public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {
	logger.debug("running raw update statement: {}", statement);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("update arguments: {}", (Object) arguments);
	}
	CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes,
			DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
	try {
		assignStatementArguments(compiledStatement, arguments);
		return compiledStatement.runUpdate();
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Create and return an {@link SelectIterator} for the class using a prepared statement.
 */
public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,
		PreparedStmt<T> preparedStmt, ObjectCache objectCache, int resultFlags) throws SQLException {
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = preparedStmt.compile(connection, StatementType.SELECT, resultFlags);
		SelectIterator<T, ID> iterator = new SelectIterator<T, ID>(tableInfo.getDataClass(), classDao, preparedStmt,
				connectionSource, connection, compiledStatement, preparedStmt.getStatement(), objectCache);
		connection = null;
		compiledStatement = null;
		return iterator;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example #16
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 #17
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a long value from a prepared query.
 */
public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException {
	CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG);
	DatabaseResults results = null;
	try {
		results = compiledStatement.runQuery(null);
		if (results.first()) {
			return results.getLong(0);
		} else {
			throw new SQLException("No result found in queryForLong: " + preparedStmt.getStatement());
		}
	} finally {
		IOUtils.closeThrowSqlException(results, "results");
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example #18
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return the first object that matches the {@link PreparedStmt} or null if none.
 */
public T queryForFirst(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt, ObjectCache objectCache)
		throws SQLException {
	CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT);
	DatabaseResults results = null;
	try {
		compiledStatement.setMaxRows(1);
		results = compiledStatement.runQuery(objectCache);
		if (results.first()) {
			logger.debug("query-for-first of '{}' returned at least 1 result", preparedStmt.getStatement());
			return preparedStmt.mapRow(results);
		} else {
			logger.debug("query-for-first of '{}' returned 0 results", preparedStmt.getStatement());
			return null;
		}
	} finally {
		IOUtils.closeThrowSqlException(results, "results");
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: WrappedDatabaseConnection.java    From ormlite-core with ISC License 6 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// System.err.println("Running method on Connection." + method.getName());
	try {
		Object obj = method.invoke(connection, args);
		if (method.getName().equals("compileStatement") && obj instanceof CompiledStatement) {
			WrappedCompiledStatement wrappedStatement = new WrappedCompiledStatement((CompiledStatement) obj);
			wrappedStatements.add(wrappedStatement);
			obj = wrappedStatement.getPreparedStatement();
		}
		return obj;
	} catch (InvocationTargetException e) {
		// pass on the exception
		throw e.getTargetException();
	}
}
 
Example #24
Source File: MappedPreparedQueryTest.java    From ormlite-core with ISC License 6 votes vote down vote up
private void checkResults(List<LocalFoo> foos, MappedPreparedStmt<LocalFoo, Integer> preparedQuery, int expectedNum)
		throws SQLException {
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(TABLE_NAME);
	CompiledStatement stmt = null;
	try {
		stmt = preparedQuery.compile(conn, StatementType.SELECT);
		DatabaseResults results = stmt.runQuery(null);
		int fooC = 0;
		while (results.next()) {
			LocalFoo foo2 = preparedQuery.mapRow(results);
			assertEquals(foos.get(fooC).id, foo2.id);
			fooC++;
		}
		assertEquals(expectedNum, fooC);
	} finally {
		IOUtils.closeThrowSqlException(stmt, "compiled statement");
		connectionSource.releaseConnection(conn);
	}
}
 
Example #25
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 #26
Source File: H2DatabaseConnection.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public CompiledStatement compileStatement(String statement, StatementType type, FieldType[] argFieldTypes,
		int resultFlags, boolean cacheStore) throws SQLException {
	PreparedStatement stmt;
	if (resultFlags == DatabaseConnection.DEFAULT_RESULT_FLAGS) {
		stmt = connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
	} else {
		stmt = connection.prepareStatement(statement, resultFlags, ResultSet.CONCUR_READ_ONLY);
	}
	return new H2CompiledStatement(stmt, cacheStore);
}
 
Example #27
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 #28
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 #29
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 #30
Source File: MappedPreparedStmt.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public CompiledStatement compile(DatabaseConnection databaseConnection, StatementType type, int resultFlags)
		throws SQLException {
	if (this.type != type) {
		throw new SQLException("Could not compile this " + this.type + " statement since the caller is expecting a "
				+ type + " statement.  Check your QueryBuilder methods.");
	}
	CompiledStatement stmt =
			databaseConnection.compileStatement(statement, type, argFieldTypes, resultFlags, cacheStore);
	// this may return null if the stmt had to be closed
	return assignStatementArguments(stmt);
}