com.j256.ormlite.field.FieldType Java Examples

The following examples show how to use com.j256.ormlite.field.FieldType. 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: MappedDeleteCollection.java    From ormlite-core with ISC License 6 votes vote down vote up
private static void appendWhereIds(DatabaseType databaseType, FieldType idField, StringBuilder sb, int numDatas,
		FieldType[] fieldTypes) {
	sb.append("WHERE ");
	databaseType.appendEscapedEntityName(sb, idField.getColumnName());
	sb.append(" IN (");
	boolean first = true;
	for (int i = 0; i < numDatas; i++) {
		if (first) {
			first = false;
		} else {
			sb.append(',');
		}
		sb.append('?');
		if (fieldTypes != null) {
			fieldTypes[i] = idField;
		}
	}
	sb.append(") ");
}
 
Example #2
Source File: PostgresDatabaseTypeTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testGeneratedIdSequenceAutoName() throws Exception {
	if (connectionSource == null) {
		return;
	}
	TableInfo<GeneratedIdSequenceAutoName, Integer> tableInfo =
			new TableInfo<GeneratedIdSequenceAutoName, Integer>(databaseType, GeneratedIdSequenceAutoName.class);
	assertEquals(2, tableInfo.getFieldTypes().length);
	FieldType idField = tableInfo.getFieldTypes()[0];
	StringBuilder sb = new StringBuilder();
	List<String> additionalArgs = new ArrayList<String>();
	List<String> statementsBefore = new ArrayList<String>();
	List<String> queriesAfter = new ArrayList<String>();
	databaseType.appendColumnArg(null, sb, idField, additionalArgs, statementsBefore, null, queriesAfter);
	databaseType.addPrimaryKeySql(new FieldType[] { idField }, additionalArgs, statementsBefore, null,
			queriesAfter);
	String seqName = databaseType
			.generateIdSequenceName(GeneratedIdSequenceAutoName.class.getSimpleName().toLowerCase(), idField);
	assertTrue(sb.toString().contains(" DEFAULT NEXTVAL('\"" + seqName + "\"')"));
	assertEquals(1, statementsBefore.size());
	assertTrue(statementsBefore.get(0).contains(seqName));
	assertEquals(1, additionalArgs.size());
	assertTrue(additionalArgs.get(0).contains("PRIMARY KEY"));
	assertEquals(0, queriesAfter.size());
}
 
Example #3
Source File: MappedCreateTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Test
public void testGeneratedIdSequence() throws Exception {
	DatabaseType databaseType = new NeedsSequenceDatabaseType();
	connectionSource.setDatabaseType(databaseType);
	TableInfo<GeneratedId, Integer> tableInfo =
			new TableInfo<GeneratedId, Integer>(databaseType, GeneratedId.class);
	Dao<GeneratedId, Integer> dao = createDao(GeneratedId.class, false);
	StatementExecutor<GeneratedId, Integer> se =
			new StatementExecutor<GeneratedId, Integer>(databaseType, tableInfo, dao);
	DatabaseConnection databaseConnection = createMock(DatabaseConnection.class);
	expect(databaseConnection.queryForLong(isA(String.class))).andReturn(1L);
	expect(databaseConnection.insert(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			(GeneratedKeyHolder) isNull())).andReturn(1);

	replay(databaseConnection);
	GeneratedId genIdSeq = new GeneratedId();
	se.create(databaseConnection, genIdSeq, null);
	verify(databaseConnection);
}
 
Example #4
Source File: SqliteAndroidDatabaseType.java    From ormlite-android with ISC License 6 votes vote down vote up
@Override
public DataPersister getDataPersister(DataPersister defaultPersister, FieldType fieldType) {
	if (defaultPersister == null) {
		return super.getDataPersister(defaultPersister, fieldType);
	}
	// we are only overriding certain types
	switch (defaultPersister.getSqlType()) {
		case DATE:
			/*
			 * We need to map the dates into their string equivalents because of mapping issues with Sqlite's
			 * default date string formats.
			 */
			if (defaultPersister instanceof TimeStampType) {
				return TimeStampStringType.getSingleton();
			} else if (defaultPersister instanceof SqlDateType) {
				return SqlDateStringType.getSingleton();
			} else {
				return DateStringType.getSingleton();
			}
		default:
			return super.getDataPersister(defaultPersister, fieldType);
	}
}
 
Example #5
Source File: BaseDaoImpl.java    From ormlite-core with ISC License 6 votes vote down vote up
private <FT> ForeignCollection<FT> makeEmptyForeignCollection(T parent, String fieldName) throws SQLException {
	checkForInitialized();
	ID id;
	if (parent == null) {
		id = null;
	} else {
		id = extractId(parent);
	}
	for (FieldType fieldType : tableInfo.getFieldTypes()) {
		if (fieldType.getColumnName().equals(fieldName)) {
			@SuppressWarnings("unchecked")
			ForeignCollection<FT> collection = (ForeignCollection<FT>) fieldType.buildForeignCollection(parent, id);
			if (parent != null) {
				fieldType.assignField(connectionSource, parent, collection, true, null);
			}
			return collection;
		}
	}
	throw new IllegalArgumentException("Could not find a field named " + fieldName);
}
 
Example #6
Source File: HsqldbDatabaseTypeTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testBadGeneratedId() throws Exception {
	Field field = GeneratedId.class.getField("id");
	DatabaseType databaseType = createMock(DatabaseType.class);
	expect(databaseType.isIdSequenceNeeded()).andReturn(false);
	DataPersister dataPersister = createMock(DataPersister.class);
	expect(databaseType.getDataPersister(isA(DataPersister.class), isA(FieldType.class))).andReturn(dataPersister);
	expect(databaseType.getFieldConverter(isA(DataPersister.class), isA(FieldType.class))).andReturn(dataPersister);
	expect(databaseType.isEntityNamesMustBeUpCase()).andReturn(true);
	expect(databaseType.upCaseEntityName("id")).andReturn("ID");
	replay(databaseType);
	connectionSource.setDatabaseType(databaseType);
	try {
		FieldType fieldType = FieldType.createFieldType(databaseType, "foo", field, GeneratedId.class);
		verify(databaseType);
		StringBuilder sb = new StringBuilder();
		List<String> statementsBefore = new ArrayList<String>();
		databaseType.appendColumnArg(null, sb, fieldType, null, statementsBefore, null, null);
	} finally {
		connectionSource.setDatabaseType(databaseType);
	}
}
 
Example #7
Source File: BaseCoreStmtTest.java    From ormlite-core with ISC License 6 votes vote down vote up
@Override
@Before
public void before() throws Exception {
	super.before();

	Field field = Foo.class.getDeclaredField("stringField");
	assertEquals(String.class, field.getType());
	stringFieldType = FieldType.createFieldType(databaseType, "BaseFoo", field, Foo.class);
	stringFieldType.configDaoInformation(connectionSource, Foo.class);
	field = Foo.class.getDeclaredField("val");
	assertEquals(int.class, field.getType());
	numberFieldType = FieldType.createFieldType(databaseType, "BaseFoo", field, Foo.class);
	numberFieldType.configDaoInformation(connectionSource, Foo.class);
	field = Foreign.class.getDeclaredField("foo");
	assertEquals(Foo.class, field.getType());
	foreignFieldType = FieldType.createFieldType(databaseType, "BaseFoo", field, Foreign.class);
	foreignFieldType.configDaoInformation(connectionSource, Foreign.class);

	baseFooTableInfo = new TableInfo<Foo, Integer>(databaseType, Foo.class);
	baseSchemaFooTableInfo = new TableInfo<SchemaFoo, Integer>(databaseType, SchemaFoo.class);
}
 
Example #8
Source File: OracleDatabaseType.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Override
public FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType) {
	switch (dataPersister.getSqlType()) {
		case BOOLEAN:
			/*
			 * Booleans in Oracle are stored as the character '1' or '0'. You can change the characters by
			 * specifying a format string. It must be a string with 2 characters. The first character is the value
			 * for TRUE, the second is FALSE. See {@link BooleanCharType}.
			 * 
			 * You can also specify the format as "integer" to use an integer column type and the value 1 (really
			 * non-0) for true and 0 for false. See {@link BooleanIntegerType}.
			 */
			if (BOOLEAN_INTEGER_FORMAT.equalsIgnoreCase(fieldType.getFormat())) {
				return DataType.BOOLEAN_INTEGER.getDataPersister();
			} else {
				return DataType.BOOLEAN_CHAR.getDataPersister();
			}
		default:
			return super.getFieldConverter(dataPersister, fieldType);
	}
}
 
Example #9
Source File: DatePersister.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) {
	Object defaultValue = null;
	if (DateConverter.DATETIME_FORMAT.equals(defaultStr)) {
		defaultValue = javaToSqlArg(null, new Date());
	}
	return defaultValue;
}
 
Example #10
Source File: BaseSqliteDatabaseType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
protected void appendLongType(StringBuilder sb, FieldType fieldType, int fieldWidth) {
	/*
	 * This is unfortunate. SQLIte requires that a generated-id have the string "INTEGER PRIMARY KEY AUTOINCREMENT"
	 * even though the maximum generated value is 64-bit. See configureGeneratedId below.
	 */
	if (fieldType.getSqlType() == SqlType.LONG && fieldType.isGeneratedId()) {
		sb.append("INTEGER");
	} else {
		sb.append("BIGINT");
	}
}
 
Example #11
Source File: H2DatabaseConnection.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public long queryForLong(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException {
	// don't care about the object cache here
	Object result = queryForOne(statement, args, argFieldTypes, longWrapper, null);
	if (result == null) {
		throw new SQLException("No results returned in query-for-long: " + statement);
	} else if (result == MORE_THAN_ONE) {
		throw new SQLException("More than 1 result returned in query-for-long: " + statement);
	} else {
		return (Long) result;
	}
}
 
Example #12
Source File: DatePersister.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos)
		throws SQLException {
	Object javaDate = null;
	if (sqlArg != null && sqlArg instanceof String) {
		try {
			javaDate = dateConverter.dateValue((String) sqlArg);
		} catch (Exception e) {
			throw new SQLException(
					"Failed to parse date string: " + sqlArg, e);
		}
	}
	return javaDate;
}
 
Example #13
Source File: DatabaseConnectionProxy.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public int insert(String statement, Object[] args, FieldType[] argfieldTypes, GeneratedKeyHolder keyHolder)
		throws SQLException {
	if (proxy == null) {
		return 0;
	} else {
		return proxy.insert(statement, args, argfieldTypes, keyHolder);
	}
}
 
Example #14
Source File: BigDecimalNumericType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
	try {
		return new BigDecimal(defaultStr);
	} catch (IllegalArgumentException e) {
		throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default BigDecimal string '"
				+ defaultStr + "'", e);
	}
}
 
Example #15
Source File: MyDatePersister.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
	if (sqlArg == null) {
		return null;
	} else {
		return new Date((Long) sqlArg);
	}
}
 
Example #16
Source File: MappedCreateTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test(expected = SQLException.class)
public void testArgumentHolderNotSet() throws Exception {
	TableInfo<Foo, Integer> tableInfo = new TableInfo<Foo, Integer>(databaseType, Foo.class);
	Dao<Foo, Integer> dao = createDao(Foo.class, false);
	MappedCreate<Foo, Integer> mappedCreate = MappedCreate.build(dao, tableInfo);
	DatabaseConnection conn = createMock(DatabaseConnection.class);
	expect(conn.insert(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			isA(GeneratedKeyHolder.class))).andReturn(1);
	replay(conn);
	mappedCreate.insert(databaseType, conn, new Foo(), null);
}
 
Example #17
Source File: TimeStampTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
	this.defaultStr = defaultStr;
	if ("CURRENT_TIMESTAMP()".equals(defaultStr)) {
		return defaultStr;
	} else {
		return super.parseDefaultString(fieldType, defaultStr);
	}
}
 
Example #18
Source File: EnumStringType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
	if (fieldType == null) {
		return sqlArg;
	}
	String value = (String) sqlArg;
	@SuppressWarnings("unchecked")
	Map<String, Enum<?>> enumStringMap = (Map<String, Enum<?>>) fieldType.getDataTypeConfigObj();
	if (enumStringMap == null) {
		return enumVal(fieldType, value, null, fieldType.getUnknownEnumVal());
	} else {
		return enumVal(fieldType, value, enumStringMap.get(value), fieldType.getUnknownEnumVal());
	}
}
 
Example #19
Source File: EnumStringType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object makeConfigObject(FieldType fieldType) throws SQLException {
	Map<String, Enum<?>> enumStringMap = new HashMap<String, Enum<?>>();
	Enum<?>[] constants = (Enum<?>[]) fieldType.getType().getEnumConstants();
	if (constants == null) {
		throw new SQLException(
				"Could not get enum-constants for field " + fieldType + ", not an enum or maybe generic?");
	}
	for (Enum<?> enumVal : constants) {
		enumStringMap.put(getEnumName(enumVal), enumVal);
	}
	return enumStringMap;
}
 
Example #20
Source File: DatabaseTableConfigTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testFieldConfigConstructor() throws SQLException {
	List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>();
	fieldConfigs.add(new DatabaseFieldConfig("stuff", null, DataType.UNKNOWN, "", 0, true, false, false, null,
			false, null, false, null, false, null, false, null, null, false,
			DatabaseFieldConfig.NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED, 0));
	DatabaseTableConfig<DatabaseTableAnno> dbTableConf =
			new DatabaseTableConfig<DatabaseTableAnno>(databaseType, DatabaseTableAnno.class, fieldConfigs);
	assertEquals(DatabaseTableAnno.class, dbTableConf.getDataClass());
	assertEquals(TABLE_NAME, dbTableConf.getTableName());
	dbTableConf.extractFieldTypes(databaseType);
	FieldType[] fieldTypes = dbTableConf.getFieldTypes(databaseType);
	assertEquals(1, fieldTypes.length);
	assertEquals("stuff", fieldTypes[0].getColumnName());
}
 
Example #21
Source File: MysqlDatabaseType.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType,
		List<String> statementsBefore, List<String> statementsAfter, List<String> additionalArgs,
		List<String> queriesAfter) {
	sb.append("AUTO_INCREMENT ");
	configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter);
}
 
Example #22
Source File: AndroidDatabaseConnection.java    From ormlite-android with ISC License 5 votes vote down vote up
@Override
public CompiledStatement compileStatement(String statement, StatementType type, FieldType[] argFieldTypes,
		int resultFlags, boolean cacheStore) {
	// resultFlags argument is not used in Android-land since the {@link Cursor} is bi-directional.
	CompiledStatement stmt = new AndroidCompiledStatement(statement, db, type, cancelQueriesEnabled, cacheStore);
	logger.trace("{}: compiled statement got {}: {}", this, stmt, statement);
	return stmt;
}
 
Example #23
Source File: NetezzaDatabaseType.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public void dropColumnArg(FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter) {
	if (fieldType.isGeneratedIdSequence()) {
		StringBuilder sb = new StringBuilder(64);
		sb.append("DROP SEQUENCE ");
		appendEscapedEntityName(sb, fieldType.getGeneratedIdSequence());
		statementsAfter.add(sb.toString());
	}
}
 
Example #24
Source File: SqlServerDatabaseType.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public FieldConverter getFieldConverter(DataPersister dataType, FieldType fieldType) {
	// we are only overriding certain types
	switch (dataType.getSqlType()) {
		case BOOLEAN:
			return booleanConverter;
		case BYTE:
			return byteConverter;
		default:
			return super.getFieldConverter(dataType, fieldType);
	}
}
 
Example #25
Source File: BaseDatabaseType.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Output the SQL type for a Java String.
 */
protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) {
	if (isVarcharFieldWidthSupported()) {
		sb.append("VARCHAR(").append(fieldWidth).append(')');
	} else {
		sb.append("VARCHAR");
	}
}
 
Example #26
Source File: ReflectionDatabaseConnectionProxyFactoryTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public int insert(String statement, Object[] args, FieldType[] argfieldTypes, GeneratedKeyHolder keyHolder)
		throws SQLException {
	// change the first argument which should be the 'val' field
	args[0] = (Integer) args[0] + VALUE_INCREMENT;
	insertCount++;
	return super.insert(statement, args, argfieldTypes, keyHolder);
}
 
Example #27
Source File: MappedRefresh.java    From ormlite-core with ISC License 5 votes vote down vote up
public static <T, ID> MappedRefresh<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo) throws SQLException {
	FieldType idField = tableInfo.getIdField();
	if (idField == null) {
		throw new SQLException(
				"Cannot refresh " + tableInfo.getDataClass() + " because it doesn't have an id field");
	}
	DatabaseType databaseType = dao.getConnectionSource().getDatabaseType();
	String statement = buildStatement(databaseType, tableInfo, idField);
	return new MappedRefresh<T, ID>(dao, tableInfo, statement, new FieldType[] { tableInfo.getIdField() },
			tableInfo.getFieldTypes());
}
 
Example #28
Source File: NullArgHolderTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testStuff() {
	NullArgHolder holder = new NullArgHolder();
	assertEquals("null-holder", holder.getColumnName());
	holder.setMetaInfo((String) null);
	holder.setMetaInfo((FieldType) null);
}
 
Example #29
Source File: PostgresDatabaseType.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public void dropColumnArg(FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter) {
	if (fieldType.isGeneratedIdSequence()) {
		StringBuilder sb = new StringBuilder(64);
		sb.append("DROP SEQUENCE ");
		appendEscapedEntityName(sb, fieldType.getGeneratedIdSequence());
		statementsAfter.add(sb.toString());
	}
}
 
Example #30
Source File: Db2DatabaseTypeTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Test
public void testByte() throws Exception {
	TableInfo<AllTypes, Void> tableInfo = new TableInfo<AllTypes, Void>(databaseType, AllTypes.class);
	assertEquals(9, tableInfo.getFieldTypes().length);
	FieldType byteField = tableInfo.getFieldTypes()[3];
	assertEquals("byteField", byteField.getColumnName());
	StringBuilder sb = new StringBuilder();
	List<String> additionalArgs = new ArrayList<String>();
	List<String> statementsBefore = new ArrayList<String>();
	databaseType.appendColumnArg(null, sb, byteField, additionalArgs, statementsBefore, null, null);
	assertTrue(sb.toString().contains("SMALLINT"));
}