Java源码示例:com.j256.ormlite.support.DatabaseResults

示例1
@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;
	}
}
 
示例2
@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);
	}
}
 
示例3
/**
 * 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");
	}
}
 
示例4
/**
 * 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");
	}
}
 
示例5
/**
 * 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");
	}
}
 
示例6
@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);
	}
}
 
示例7
@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);
}
 
示例8
@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);
	}
}
 
示例9
@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);
	}
}
 
示例10
@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);
}
 
示例11
@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();
	}
}
 
示例12
@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);
}
 
示例13
@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);
	}
}
 
示例14
@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);
}
 
示例15
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;
}
 
示例16
@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);
}
 
示例17
@Override
public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
	Timestamp timestamp = results.getTimestamp(columnPos);
	if (timestamp == null || ZERO_TIMESTAMP.after(timestamp)) {
		return null;
	} else {
		return timestamp.getTime();
	}
}
 
示例18
@Test(expected = SQLException.class)
public void testResultToSqlArg() throws Exception {
	DatabaseResults results = createMock(DatabaseResults.class);
	int col = 21;
	long value = 2094234324L;
	expect(results.getLong(col)).andReturn(value);
	replay(results);
	DateTimeType.getSingleton().resultToJava(null, results, col);
}
 
示例19
@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;
}
 
示例20
private String[] getColumnNames(DatabaseResults results) throws SQLException {
	if (columnNames != null) {
		return columnNames;
	}
	columnNames = results.getColumnNames();
	return columnNames;
}
 
示例21
private String[] getColumnNames(DatabaseResults results) throws SQLException {
	if (columnNames != null) {
		return columnNames;
	}
	columnNames = results.getColumnNames();
	return columnNames;
}
 
示例22
@Override
public Object[] mapRow(DatabaseResults results) throws SQLException {
	int columnN = results.getColumnCount();
	Object[] result = new Object[columnN];
	for (int colC = 0; colC < columnN; colC++) {
		DataType dataType;
		if (colC >= columnTypes.length) {
			dataType = DataType.STRING;
		} else {
			dataType = columnTypes[colC];
		}
		result[colC] = dataType.getDataPersister().resultToJava(null, results, colC);
	}
	return result;
}
 
示例23
/**
 * @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);
	}
}
 
示例24
/**
 * 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;
}
 
示例25
@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);
}
 
示例26
@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);
	}
}
 
示例27
@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);
}
 
示例28
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;
}
 
示例29
@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);
}
 
示例30
@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);
	}
}