com.j256.ormlite.support.DatabaseResults Java Examples

The following examples show how to use com.j256.ormlite.support.DatabaseResults. 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: H2DatabaseConnection.java    From ormlite-core with ISC License 6 votes vote down vote up
@Override
public <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes,
		GenericRowMapper<T> rowMapper, ObjectCache objectCache) throws SQLException {
	PreparedStatement stmt =
			connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
	if (args != null) {
		statementSetArgs(stmt, args, argFieldTypes);
	}
	DatabaseResults results = new H2DatabaseResults(stmt.executeQuery(), objectCache, true);
	if (!results.next()) {
		// no results at all
		IOUtils.closeThrowSqlException(results, "results");
		return null;
	}
	T first = rowMapper.mapRow(results);
	if (results.next()) {
		return MORE_THAN_ONE;
	} else {
		return first;
	}
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #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: 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 #11
Source File: BaseMappedQueryTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testMappedQuery() throws Exception {
	Field field = Foo.class.getDeclaredField(Foo.ID_COLUMN_NAME);
	String tableName = "basefoo";
	Dao<Foo, Integer> dao = createDao(Foo.class, false);
	FieldType[] resultFieldTypes =
			new FieldType[] { FieldType.createFieldType(databaseType, tableName, field, Foo.class) };
	BaseMappedQuery<Foo, Integer> baseMappedQuery = new BaseMappedQuery<Foo, Integer>(dao, baseFooTableInfo,
			"select * from " + tableName, new FieldType[0], resultFieldTypes) {
	};
	DatabaseResults results = createMock(DatabaseResults.class);
	int colN = 1;
	expect(results.getObjectCacheForRetrieve()).andReturn(null);
	expect(results.getObjectCacheForStore()).andReturn(null);
	expect(results.findColumn(Foo.ID_COLUMN_NAME)).andReturn(colN);
	int id = 63365;
	expect(results.getInt(colN)).andReturn(id);
	replay(results);
	Foo baseFoo = baseMappedQuery.mapRow(results);
	assertNotNull(baseFoo);
	assertEquals(id, baseFoo.id);
	verify(results);
}
 
Example #12
Source File: FieldTypeTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testSerializableNull() throws Exception {
	Field[] fields = SerializableField.class.getDeclaredFields();
	assertTrue(fields.length >= 1);
	Field field = fields[0];
	FieldType fieldType = FieldType.createFieldType(databaseType, SerializableField.class.getSimpleName(), field,
			SerializableField.class);
	DatabaseResults results = createMock(DatabaseResults.class);
	int fieldNum = 1;
	expect(results.findColumn(field.getName())).andReturn(fieldNum);
	expect(results.getTimestamp(fieldNum)).andReturn(null);
	expect(results.wasNull(fieldNum)).andReturn(true);
	replay(results);
	assertNull(fieldType.resultToJava(results, new HashMap<String, Integer>()));
	verify(results);
}
 
Example #13
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 #14
Source File: StatementExecutor.java    From ormlite-core with ISC License 5 votes vote down vote up
private String[] getColumnNames(DatabaseResults results) throws SQLException {
	if (columnNames != null) {
		return columnNames;
	}
	columnNames = results.getColumnNames();
	return columnNames;
}
 
Example #15
Source File: StatementExecutor.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public String[] mapRow(DatabaseResults results) throws SQLException {
	int columnN = results.getColumnCount();
	String[] result = new String[columnN];
	for (int colC = 0; colC < columnN; colC++) {
		result[colC] = results.getString(colC);
	}
	return result;
}
 
Example #16
Source File: BaseDaoImplTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Foo mapRow(DatabaseResults databaseResults) throws SQLException {
	Foo foo = new Foo();
	String[] columnNames = databaseResults.getColumnNames();
	for (int i = 0; i < columnNames.length; i++) {
		if (columnNames[i].equalsIgnoreCase(Foo.ID_COLUMN_NAME)) {
			foo.id = databaseResults.getInt(i);
		} else if (columnNames[i].equalsIgnoreCase(Foo.VAL_COLUMN_NAME)) {
			foo.val = databaseResults.getInt(i);
		} else if (columnNames[i].equalsIgnoreCase(Foo.STRING_COLUMN_NAME)) {
			foo.stringField = databaseResults.getString(i);
		}
	}
	return foo;
}
 
Example #17
Source File: SelectIteratorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testIteratorGetRawResults() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	assertEquals(1, dao.create(foo1));

	assertEquals(1, dao.queryForAll().size());

	@SuppressWarnings("unchecked")
	SelectIterator<Foo, String> iterator = (SelectIterator<Foo, String>) dao.iterator();
	DatabaseResults results = iterator.getRawResults();
	assertTrue(results.next());
	iterator.close();
}
 
Example #18
Source File: RuntimeExceptionDao.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * @see Dao#mapSelectStarRow(DatabaseResults)
 */
@Override
public T mapSelectStarRow(DatabaseResults results) {
	try {
		return dao.mapSelectStarRow(results);
	} catch (SQLException e) {
		logMessage(e, "mapSelectStarRow threw exception on results");
		throw new RuntimeException(e);
	}
}
 
Example #19
Source File: FieldTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testForeignAutoRefresh() throws Exception {
	Field field = ForeignAutoRefresh.class.getDeclaredField("foreign");
	ConnectionSource connectionSource = createMock(ConnectionSource.class);
	DatabaseConnection connection = createMock(DatabaseConnection.class);
	expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes();
	expect(connectionSource.getReadOnlyConnection("ForeignAutoRefresh")).andReturn(connection);
	ForeignForeign foreignForeign = new ForeignForeign();
	String stuff = "21312j3213";
	int id = 4123123;
	foreignForeign.id = id;
	foreignForeign.stuff = stuff;
	expect(connection.queryForOne(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			isA(GenericRowMapper.class), (ObjectCache) isNull())).andReturn(foreignForeign);
	connectionSource.releaseConnection(connection);
	DatabaseResults results = createMock(DatabaseResults.class);
	ForeignAutoRefresh foreign = new ForeignAutoRefresh();
	replay(results, connectionSource, connection);
	FieldType fieldType = FieldType.createFieldType(databaseType, ForeignAutoRefresh.class.getSimpleName(), field,
			ForeignAutoRefresh.class);
	fieldType.configDaoInformation(connectionSource, ForeignAutoRefresh.class);
	assertNull(foreign.foreign);
	fieldType.assignField(connectionSource, foreign, id, false, null);
	assertNotNull(foreign.foreign);
	assertEquals(id, foreign.foreign.id);
	assertEquals(stuff, foreign.foreign.stuff);
	verify(results, connectionSource, connection);
}
 
Example #20
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 #21
Source File: BaseMappedQueryTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testMappedQueryCached() throws Exception {
	Field field = Foo.class.getDeclaredField(Foo.ID_COLUMN_NAME);
	String tableName = "basefoo";
	FieldType[] resultFieldTypes =
			new FieldType[] { FieldType.createFieldType(databaseType, tableName, field, Foo.class) };
	Dao<Foo, Integer> dao = createDao(Foo.class, false);
	BaseMappedQuery<Foo, Integer> baseMappedQuery = new BaseMappedQuery<Foo, Integer>(dao, baseFooTableInfo,
			"select * from " + tableName, new FieldType[0], resultFieldTypes) {
	};
	DatabaseResults results = createMock(DatabaseResults.class);
	int colN = 1;
	ObjectCache objectCache = createMock(ObjectCache.class);
	expect(results.getObjectCacheForRetrieve()).andReturn(objectCache);
	int id = 63365;
	expect(results.getInt(colN)).andReturn(id);
	expect(objectCache.get(Foo.class, id)).andReturn(null);
	objectCache.put(eq(Foo.class), eq(id), isA(Foo.class));
	expect(results.getObjectCacheForStore()).andReturn(objectCache);
	expect(results.findColumn(Foo.ID_COLUMN_NAME)).andReturn(colN);
	expect(results.getInt(colN)).andReturn(id);

	replay(results, objectCache);
	Foo baseFoo = baseMappedQuery.mapRow(results);
	assertNotNull(baseFoo);
	assertEquals(id, baseFoo.id);
	verify(results, objectCache);
}
 
Example #22
Source File: FieldType.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Get the result object from the results. A call through to {@link FieldConverter#resultToJava}.
 */
public <T> T resultToJava(DatabaseResults results, Map<String, Integer> columnPositions) throws SQLException {
	Integer dbColumnPos = columnPositions.get(columnName);
	if (dbColumnPos == null) {
		dbColumnPos = results.findColumn(columnName);
		columnPositions.put(columnName, dbColumnPos);
	}

	/*
	 * Subtle problem here. If the field is a foreign-field and/or a primitive and the value was null then we get 0
	 * from results.getInt() which mirrors the ResultSet. We have to specifically test to see if we have a null
	 * result with results.wasNull(...) afterwards so we return a null value to not create the sub-object or turn a
	 * Integer field into 0 instead of null.
	 * 
	 * But this presents a limitation. Sometimes people want to convert a result field value that is stored in the
	 * database as null into a non-null value when it comes out of the database. There is no way to do that because
	 * of the results.wasNull(...) checks after the fact then override the non-null value from the converter.
	 */
	@SuppressWarnings("unchecked")
	T converted = (T) fieldConverter.resultToJava(this, results, dbColumnPos);
	if (fieldConfig.isForeign()) {
		/*
		 * If your foreign field is a primitive and the value was null then this would return 0 from
		 * results.getInt(). We have to specifically test to see if we have a foreign field so if it is null we
		 * return a null value to not create the sub-object.
		 */
		if (results.wasNull(dbColumnPos)) {
			return null;
		}
	} else if (dataPersister.isPrimitive()) {
		if (fieldConfig.isThrowIfNull() && results.wasNull(dbColumnPos)) {
			throw new SQLException(
					"Results value for primitive field '" + field.getName() + "' was an invalid null value");
		}
	} else if (!fieldConverter.isStreamType() && results.wasNull(dbColumnPos)) {
		// we can't check if we have a null if this is a stream type
		return null;
	}
	return converted;
}
 
Example #23
Source File: JdbcCompiledStatement.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public DatabaseResults runQuery(ObjectCache objectCache) throws SQLException {
	if (!type.isOkForQuery()) {
		throw new IllegalArgumentException("Cannot call query on a " + type + " statement");
	}
	return new JdbcDatabaseResults(preparedStatement, preparedStatement.executeQuery(), objectCache, cacheStore);
}
 
Example #24
Source File: SchemaUtils.java    From ormlite-core with ISC License 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 schema
    for (String query : queriesAfter) {
        CompiledStatement compiledStmt = null;
        try {
            compiledStmt = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
                    DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
            // 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.info("executing create schema 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 schema after-query failed: " + query, e);
        } finally {
            // result set is closed by the statement being closed
            IOUtils.closeThrowSqlException(compiledStmt, "compiled statement");
        }
        stmtC++;
    }
    return stmtC;
}
 
Example #25
Source File: BaseCoreDatabaseTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testBooleanConverterResultToJava() throws Exception {
	DatabaseResults results = createMock(DatabaseResults.class);
	boolean first = Boolean.TRUE;
	boolean second = Boolean.FALSE;
	expect(results.getByte(1)).andReturn((byte) 1);
	expect(results.getByte(2)).andReturn((byte) 0);
	replay(results);
	FieldType fieldType = FieldType.createFieldType(databaseType, "foo", ManyFields.class.getDeclaredField("bool"),
			ManyFields.class);
	assertEquals(first, booleanFieldConverter.resultToJava(fieldType, results, 1));
	assertEquals(second, booleanFieldConverter.resultToJava(fieldType, results, 2));
	verify(results);
}
 
Example #26
Source File: BaseFieldConverter.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object resultToJava(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
	Object value = resultToSqlArg(fieldType, results, columnPos);
	if (value == null) {
		return null;
	} else {
		return sqlArgToJava(fieldType, value, columnPos);
	}
}
 
Example #27
Source File: FieldTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testInvalidFieldType() throws Exception {
	Field[] fields = InvalidType.class.getDeclaredFields();
	assertTrue(fields.length >= 1);
	Field field = fields[0];
	FieldType fieldType =
			FieldType.createFieldType(databaseType, InvalidType.class.getSimpleName(), field, InvalidType.class);
	DatabaseResults results = createMock(DatabaseResults.class);
	int fieldNum = 1;
	expect(results.findColumn(field.getName())).andReturn(fieldNum);
	expect(results.wasNull(fieldNum)).andReturn(true);
	replay(results);
	assertNull(fieldType.resultToJava(results, new HashMap<String, Integer>()));
	verify(results);
}
 
Example #28
Source File: RxBaseDaoImpl.java    From AndroidStarter with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<DataType> rxMapSelectStarRow(final DatabaseResults results) {
    final Func0<Observable<DataType>> loFunc = () -> {
        try {
            return Observable.just(mapSelectStarRow(results));
        } catch (SQLException e) {
            return Observable.error(e);
        }
    };
    return Observable.defer(loFunc);
}
 
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 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 #30
Source File: RawRowMapperTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testRawResultsMapper() throws Exception {
	Dao<Foo, Object> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	foo1.val = 12321;
	assertEquals(1, dao.create(foo1));
	Foo foo2 = new Foo();
	foo2.val = 754282321;
	assertEquals(1, dao.create(foo2));

	QueryBuilder<Foo, Object> qb = dao.queryBuilder();
	qb.selectColumns(Foo.ID_COLUMN_NAME, Foo.VAL_COLUMN_NAME);
	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		DatabaseResults results = iterator.getRawResults();
		for (int count = 0; results.next(); count++) {
			Foo foo = dao.mapSelectStarRow(results);
			switch (count) {
				case 0 :
					assertEquals(foo1.id, foo.id);
					assertEquals(foo1.val, foo.val);
					break;
				case 1 :
					assertEquals(foo2.id, foo.id);
					assertEquals(foo2.val, foo.val);
					break;
				default :
					fail("Unknown entry in list");
			}
		}
	} finally {
		iterator.close();
	}
}