Java Code Examples for com.j256.ormlite.misc.SqlExceptionUtil#create()

The following examples show how to use com.j256.ormlite.misc.SqlExceptionUtil#create() . 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: AndroidDatabaseConnection.java    From ormlite-android with ISC License 6 votes vote down vote up
@Override
public void rollback(Savepoint savepoint) throws SQLException {
	try {
		// no setTransactionSuccessful() means it is a rollback
		db.endTransaction();
		if (savepoint == null) {
			logger.trace("{}: transaction is ended, unsuccessfully", this);
		} else {
			logger.trace("{}: transaction {} is ended, unsuccessfully", this, savepoint.getSavepointName());
		}
	} catch (android.database.SQLException e) {
		if (savepoint == null) {
			throw SqlExceptionUtil.create("problems rolling back transaction", e);
		} else {
			throw SqlExceptionUtil.create("problems rolling back transaction " + savepoint.getSavepointName(), e);
		}
	}
}
 
Example 2
Source File: AndroidDatabaseConnection.java    From ormlite-android with ISC License 6 votes vote down vote up
@Override
public int insert(String statement, Object[] args, FieldType[] argFieldTypes, GeneratedKeyHolder keyHolder)
		throws SQLException {
	SQLiteStatement stmt = null;
	try {
		stmt = db.compileStatement(statement);
		bindArgs(stmt, args, argFieldTypes);
		long rowId = stmt.executeInsert();
		if (keyHolder != null) {
			keyHolder.addKey(rowId);
		}
		/*
		 * I've decided to not do the CHANGES() statement here like we do down below in UPDATE because we know that
		 * it worked (since it didn't throw) so we know that 1 is right.
		 */
		int result = 1;
		logger.trace("{}: insert statement is compiled and executed, changed {}: {}", this, result, statement);
		return result;
	} catch (android.database.SQLException e) {
		throw SqlExceptionUtil.create("inserting to database failed: " + statement, e);
	} finally {
		closeQuietly(stmt);
	}
}
 
Example 3
Source File: AndroidDatabaseConnection.java    From ormlite-android with ISC License 6 votes vote down vote up
@Override
public long queryForLong(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException {
	Cursor cursor = null;
	AndroidDatabaseResults results = null;
	try {
		cursor = db.rawQuery(statement, toStrings(args));
		results = new AndroidDatabaseResults(cursor, null, false);
		long result;
		if (results.first()) {
			result = results.getLong(0);
		} else {
			result = 0L;
		}
		logger.trace("{}: query for long raw query returned {}: {}", this, result, statement);
		return result;
	} catch (android.database.SQLException e) {
		throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e);
	} finally {
		closeQuietly(cursor);
		IOUtils.closeQuietly(results);
	}
}
 
Example 4
Source File: DateTimeType.java    From ormlite-core with ISC License 5 votes vote down vote up
private Long extractMillis(Object javaObject) throws SQLException {
	try {
		if (getMillisMethod == null) {
			Class<?> clazz = getDateTimeClass();
			getMillisMethod = clazz.getMethod("getMillis");
		}
		if (javaObject == null) {
			return null;
		} else {
			return (Long) getMillisMethod.invoke(javaObject);
		}
	} catch (Exception e) {
		throw SqlExceptionUtil.create("Could not use reflection to get millis from Joda DateTime: " + javaObject, e);
	}
}
 
Example 5
Source File: BigIntegerType.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 {
	try {
		return new BigInteger((String) sqlArg);
	} catch (IllegalArgumentException e) {
		throw SqlExceptionUtil
				.create("Problems with column " + columnPos + " parsing BigInteger string '" + sqlArg + "'", e);
	}
}
 
Example 6
Source File: StringBytesType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object javaToSqlArg(FieldType fieldType, Object javaObject) throws SQLException {
	String string = (String) javaObject;
	String charsetName = getCharsetName(fieldType);
	try {
		// NOTE: I can't use string.getBytes(Charset) because it was introduced in 1.6.
		return string.getBytes(charsetName);
	} catch (UnsupportedEncodingException e) {
		throw SqlExceptionUtil.create("Could not convert string with charset name: " + charsetName, e);
	}
}
 
Example 7
Source File: DateStringType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
	DateStringFormatConfig formatConfig = convertDateStringConfig(fieldType, defaultDateFormatConfig);
	try {
		// we parse to make sure it works and then format it again
		return normalizeDateString(formatConfig, defaultStr);
	} catch (ParseException e) {
		throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default date-string '"
				+ defaultStr + "' using '" + formatConfig + "'", e);
	}
}
 
Example 8
Source File: DatabaseTableConfigLoader.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Write the table configuration to a buffered writer.
 */
public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {
	try {
		writeConfig(writer, config);
	} catch (IOException e) {
		throw SqlExceptionUtil.create("Could not write config to writer", e);
	}
}
 
Example 9
Source File: MappedUpdateId.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Update the id field of the object in the database.
 */
public int execute(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache)
		throws SQLException {
	try {
		// the arguments are the new-id and old-id
		Object[] args = new Object[] { convertIdToFieldObject(newId), extractIdToFieldObject(data) };
		int rowC = databaseConnection.update(statement, args, argFieldTypes);
		if (rowC > 0) {
			if (objectCache != null) {
				Object oldId = idField.extractJavaFieldValue(data);
				T obj = objectCache.updateId(clazz, oldId, newId);
				if (obj != null && obj != data) {
					// if our cached value is not the data that will be updated then we need to update it specially
					idField.assignField(connectionSource, obj, newId, false, objectCache);
				}
			}
			// adjust the object to assign the new id
			idField.assignField(connectionSource, data, newId, false, objectCache);
		}
		logger.debug("updating-id with statement '{}' and {} args, changed {} rows", statement, args.length, rowC);
		if (args.length > 0) {
			// need to do the cast otherwise we only print the first object in args
			logger.trace("updating-id arguments: {}", (Object) args);
		}
		return rowC;
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Unable to run update-id stmt on object " + data + ": " + statement, e);
	}
}
 
Example 10
Source File: AndroidConnectionSource.java    From ormlite-android with ISC License 5 votes vote down vote up
@Override
public DatabaseConnection getReadWriteConnection(String tableName) throws SQLException {
	DatabaseConnection conn = getSavedConnection();
	if (conn != null) {
		return conn;
	}
	if (connection == null) {
		SQLiteDatabase db;
		if (sqliteDatabase == null) {
			try {
				db = helper.getWritableDatabase();
			} catch (android.database.SQLException e) {
				throw SqlExceptionUtil.create("Getting a writable database from helper " + helper + " failed", e);
			}
		} else {
			db = sqliteDatabase;
		}
		connection = new AndroidDatabaseConnection(db, true, cancelQueriesEnabled);
		if (connectionProxyFactory != null) {
			connection = connectionProxyFactory.createProxy(connection);
		}
		logger.trace("created connection {} for db {}, helper {}", connection, db, helper);
	} else {
		logger.trace("{}: returning read-write connection {}, helper {}", this, connection, helper);
	}
	return connection;
}
 
Example 11
Source File: DatabaseFieldConfigLoader.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Load a configuration in from a text file.
 * 
 * @return A config if any of the fields were set otherwise null on EOF.
 */
public static DatabaseFieldConfig fromReader(BufferedReader reader) throws SQLException {
	DatabaseFieldConfig config = new DatabaseFieldConfig();
	boolean anything = false;
	while (true) {
		String line;
		try {
			line = reader.readLine();
		} catch (IOException e) {
			throw SqlExceptionUtil.create("Could not read DatabaseFieldConfig from stream", e);
		}
		if (line == null) {
			break;
		}
		// we do this so we can support multiple class configs per file
		if (line.equals(CONFIG_FILE_END_MARKER)) {
			break;
		}
		// skip empty lines or comments
		if (line.length() == 0 || line.startsWith("#") || line.equals(CONFIG_FILE_START_MARKER)) {
			continue;
		}
		String[] parts = line.split("=", -2);
		if (parts.length != 2) {
			throw new SQLException("DatabaseFieldConfig reading from stream cannot parse line: " + line);
		}
		readField(config, parts[0], parts[1]);
		anything = true;
	}
	// if we got any config lines then we return the config
	if (anything) {
		return config;
	} else {
		// otherwise we return null for none
		return null;
	}
}
 
Example 12
Source File: DateIntegerType.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 Integer.parseInt(defaultStr);
	} catch (NumberFormatException e) {
		throw SqlExceptionUtil.create(
				"Problems with field " + fieldType + " parsing default date-integer value: " + defaultStr, e);
	}
}
 
Example 13
Source File: DateTimeType.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 Long.parseLong(defaultStr);
	} catch (NumberFormatException e) {
		throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default DateTime value: "
				+ defaultStr, e);
	}
}
 
Example 14
Source File: AndroidDatabaseConnection.java    From ormlite-android with ISC License 5 votes vote down vote up
@Override
public Savepoint setSavePoint(String name) throws SQLException {
	try {
		db.beginTransaction();
		logger.trace("{}: save-point set with name {}", this, name);
		return new OurSavePoint(name);
	} catch (android.database.SQLException e) {
		throw SqlExceptionUtil.create("problems beginning transaction " + name, e);
	}
}
 
Example 15
Source File: AndroidDatabaseConnection.java    From ormlite-android with ISC License 5 votes vote down vote up
@Override
public boolean isAutoCommit() throws SQLException {
	try {
		boolean inTransaction = db.inTransaction();
		logger.trace("{}: in transaction is {}", this, inTransaction);
		// You have to explicitly commit your transactions, so this is sort of correct
		return !inTransaction;
	} catch (android.database.SQLException e) {
		throw SqlExceptionUtil.create("problems getting auto-commit from database", e);
	}
}
 
Example 16
Source File: DerbyEmbeddedDatabaseType.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public Object javaToSqlArg(FieldType fieldType, Object javaObject) throws SQLException {
	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	try {
		ObjectOutputStream objOutStream = new ObjectOutputStream(outStream);
		objOutStream.writeObject(javaObject);
	} catch (Exception e) {
		throw SqlExceptionUtil.create("Could not write serialized object to output stream", e);
	}
	return new SerialBlob(outStream.toByteArray());
}
 
Example 17
Source File: DerbyEmbeddedDatabaseType.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
	InputStream stream = (InputStream) sqlArg;
	try {
		ObjectInputStream objInStream = new ObjectInputStream(stream);
		return objInStream.readObject();
	} catch (Exception e) {
		throw SqlExceptionUtil.create("Could not read serialized object from result blob", e);
	} finally {
		IOUtils.closeQuietly(stream);
	}
}
 
Example 18
Source File: BaseDaoImpl.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public GenericRawResults<Object[]> queryRaw(String query, DataType[] columnTypes, String... arguments)
		throws SQLException {
	checkForInitialized();
	try {
		return statementExecutor.queryRaw(connectionSource, query, columnTypes, arguments, objectCache);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not perform raw query for " + query, e);
	}
}
 
Example 19
Source File: DatabaseTableConfigLoader.java    From ormlite-core with ISC License 4 votes vote down vote up
/**
 * Load a table configuration in from a text-file reader.
 * 
 * @return A config if any of the fields were set otherwise null if we reach EOF.
 */
public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException {
	DatabaseTableConfig<T> config = new DatabaseTableConfig<T>();
	boolean anything = false;
	while (true) {
		String line;
		try {
			line = reader.readLine();
		} catch (IOException e) {
			throw SqlExceptionUtil.create("Could not read DatabaseTableConfig from stream", e);
		}
		if (line == null) {
			break;
		}
		// we do this so we can support multiple class configs per file
		if (line.equals(CONFIG_FILE_END_MARKER)) {
			break;
		}
		// we do this so we can support multiple class configs per file
		if (line.equals(CONFIG_FILE_FIELDS_START)) {
			readFields(reader, config);
			continue;
		}
		// skip empty lines or comments
		if (line.length() == 0 || line.startsWith("#") || line.equals(CONFIG_FILE_START_MARKER)) {
			continue;
		}
		String[] parts = line.split("=", -2);
		if (parts.length != 2) {
			throw new SQLException("DatabaseTableConfig reading from stream cannot parse line: " + line);
		}
		readTableField(config, parts[0], parts[1]);
		anything = true;
	}
	// if we got any config lines then we return the config
	if (anything) {
		return config;
	} else {
		// otherwise we return null for none
		return null;
	}
}
 
Example 20
Source File: MappedUpdate.java    From ormlite-core with ISC License 4 votes vote down vote up
/**
 * Update the object in the database.
 */
public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
	try {
		// there is always and id field as an argument so just return 0 lines updated
		if (argFieldTypes.length <= 1) {
			return 0;
		}
		Object[] args = getFieldObjects(data);
		Object newVersion = null;
		if (versionFieldType != null) {
			newVersion = versionFieldType.extractJavaFieldValue(data);
			newVersion = versionFieldType.moveToNextValue(newVersion);
			args[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);
		}
		int rowC = databaseConnection.update(statement, args, argFieldTypes);
		if (rowC > 0) {
			if (newVersion != null) {
				// if we have updated a row then update the version field in our object to the new value
				versionFieldType.assignField(connectionSource, data, newVersion, false, null);
			}
			if (objectCache != null) {
				// if we've changed something then see if we need to update our cache
				Object id = idField.extractJavaFieldValue(data);
				T cachedData = objectCache.get(clazz, id);
				if (cachedData != null && cachedData != data) {
					// copy each field from the updated data into the cached object
					for (FieldType fieldType : tableInfo.getFieldTypes()) {
						if (fieldType != idField) {
							fieldType.assignField(connectionSource, cachedData,
									fieldType.extractJavaFieldValue(data), false, objectCache);
						}
					}
				}
			}
		}
		logger.debug("update data with statement '{}' and {} args, changed {} rows", statement, args.length, rowC);
		if (args.length > 0) {
			// need to do the (Object) cast to force args to be a single object
			logger.trace("update arguments: {}", (Object) args);
		}
		return rowC;
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Unable to run update stmt on object " + data + ": " + statement, e);
	}
}