Java Code Examples for com.j256.ormlite.misc.SqlExceptionUtil

The following examples show how to use com.j256.ormlite.misc.SqlExceptionUtil. These examples are extracted from open source projects. 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 Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: ISC License 6 votes vote down vote up
@Override
public void commit(Savepoint savepoint) throws SQLException {
	try {
		db.setTransactionSuccessful();
		db.endTransaction();
		if (savepoint == null) {
			logger.trace("{}: transaction is successfully ended", this);
		} else {
			logger.trace("{}: transaction {} is successfully ended", this, savepoint.getSavepointName());
		}
	} catch (android.database.SQLException e) {
		if (savepoint == null) {
			throw SqlExceptionUtil.create("problems committing transaction", e);
		} else {
			throw SqlExceptionUtil.create("problems committing transaction " + savepoint.getSavepointName(), e);
		}
	}
}
 
Example 2
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: 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 3
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: 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 4
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: 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 5
Source Project: ormlite-android   Source File: AndroidCompiledStatement.java    License: ISC License 6 votes vote down vote up
/***
 * This is mostly an internal class but is exposed for those people who need access to the Cursor itself.
 * 
 * <p>
 * NOTE: This is not thread safe. Not sure if we need it, but keep that in mind.
 * </p>
 */
public Cursor getCursor() throws SQLException {
	if (cursor == null) {
		String finalSql = null;
		try {
			if (max == null) {
				finalSql = sql;
			} else {
				finalSql = sql + " LIMIT " + max;
			}
			if (cancelQueriesEnabled) {
				cancellationHook = apiCompatibility.createCancellationHook();
			}
			cursor = apiCompatibility.rawQuery(db, finalSql, getStringArray(), cancellationHook);
			cursor.moveToFirst();
			logger.trace("{}: started rawQuery cursor for: {}", this, finalSql);
		} catch (android.database.SQLException e) {
			throw SqlExceptionUtil.create("Problems executing Android query: " + finalSql, e);
		}
	}

	return cursor;
}
 
Example 6
Source Project: ormlite-core   Source File: MappedDeleteCollection.java    License: ISC License 6 votes vote down vote up
private static <T, ID> int updateRows(DatabaseConnection databaseConnection, Class<T> clazz,
		MappedDeleteCollection<T, ID> deleteCollection, Object[] args, ObjectCache objectCache)
		throws SQLException {
	try {
		int rowC = databaseConnection.delete(deleteCollection.statement, args, deleteCollection.argFieldTypes);
		if (rowC > 0 && objectCache != null) {
			for (Object id : args) {
				objectCache.remove(clazz, id);
			}
		}
		logger.debug("delete-collection with statement '{}' and {} args, changed {} rows",
				deleteCollection.statement, args.length, rowC);
		if (args.length > 0) {
			// need to do the (Object) cast to force args to be a single object
			logger.trace("delete-collection arguments: {}", (Object) args);
		}
		return rowC;
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Unable to run delete collection stmt: " + deleteCollection.statement, e);
	}
}
 
Example 7
Source Project: ormlite-core   Source File: MappedDelete.java    License: ISC License 6 votes vote down vote up
/**
 * Delete the object from the database.
 */
public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
	try {
		Object[] args = getFieldObjects(data);
		int rowC = databaseConnection.delete(statement, args, argFieldTypes);
		logger.debug("delete 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("delete arguments: {}", (Object) args);
		}
		if (rowC > 0 && objectCache != null) {
			Object id = idField.extractJavaFieldToSqlArgValue(data);
			objectCache.remove(clazz, id);
		}
		return rowC;
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Unable to run delete stmt on object " + data + ": " + statement, e);
	}
}
 
Example 8
Source Project: ormlite-core   Source File: MappedDelete.java    License: ISC License 6 votes vote down vote up
/**
 * Delete the object from the database.
 */
public int deleteById(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException {
	try {
		Object[] args = new Object[] { convertIdToFieldObject(id) };
		int rowC = databaseConnection.delete(statement, args, argFieldTypes);
		logger.debug("delete 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("delete arguments: {}", (Object) args);
		}
		if (rowC > 0 && objectCache != null) {
			objectCache.remove(clazz, id);
		}
		return rowC;
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Unable to run deleteById stmt on id " + id + ": " + statement, e);
	}
}
 
Example 9
Source Project: ormlite-core   Source File: DatabaseTableConfigLoader.java    License: ISC License 6 votes vote down vote up
/**
 * Read all of the fields information from the configuration file.
 */
private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {
	List<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();
	while (true) {
		String line;
		try {
			line = reader.readLine();
		} catch (IOException e) {
			throw SqlExceptionUtil.create("Could not read next field from config file", e);
		}
		if (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {
			break;
		}
		DatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);
		if (fieldConfig == null) {
			break;
		}
		fields.add(fieldConfig);
	}
	config.setFieldConfigs(fields);
}
 
Example 10
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 11
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 12
Source Project: ormlite-jdbc   Source File: DerbyEmbeddedDatabaseType.java    License: 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 13
Source Project: ormlite-jdbc   Source File: DerbyEmbeddedDatabaseType.java    License: 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 14
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: 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 15
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: 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 16
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: ISC License 5 votes vote down vote up
@Override
public long queryForLong(String statement) throws SQLException {
	SQLiteStatement stmt = null;
	try {
		stmt = db.compileStatement(statement);
		long result = stmt.simpleQueryForLong();
		logger.trace("{}: query for long simple query returned {}: {}", this, result, statement);
		return result;
	} catch (android.database.SQLException e) {
		throw SqlExceptionUtil.create("queryForLong from database failed: " + statement, e);
	} finally {
		closeQuietly(stmt);
	}
}
 
Example 17
Source Project: ormlite-android   Source File: AndroidDatabaseConnection.java    License: ISC License 5 votes vote down vote up
@Override
public boolean isClosed() throws SQLException {
	try {
		boolean isOpen = db.isOpen();
		logger.trace("{}: db {} isOpen returned {}", this, db, isOpen);
		return !isOpen;
	} catch (android.database.SQLException e) {
		throw SqlExceptionUtil.create("problems detecting if the database is closed", e);
	}
}
 
Example 18
Source Project: ormlite-android   Source File: AndroidConnectionSource.java    License: 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 19
Source Project: ormlite-core   Source File: MappedUpdateId.java    License: 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 20
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public GenericRawResults<String[]> queryRaw(String query, String... arguments) throws SQLException {
	checkForInitialized();
	try {
		return statementExecutor.queryRaw(connectionSource, query, arguments, objectCache);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not perform raw query for " + query, e);
	}
}
 
Example 21
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public <GR> GenericRawResults<GR> queryRaw(String query, RawRowMapper<GR> mapper, String... arguments)
		throws SQLException {
	checkForInitialized();
	try {
		return statementExecutor.queryRaw(connectionSource, query, mapper, arguments, objectCache);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not perform raw query for " + query, e);
	}
}
 
Example 22
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public <UO> GenericRawResults<UO> queryRaw(String query, DataType[] columnTypes, RawRowObjectMapper<UO> mapper,
		String... arguments) throws SQLException {
	checkForInitialized();
	try {
		return statementExecutor.queryRaw(connectionSource, query, columnTypes, mapper, arguments, objectCache);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not perform raw query for " + query, e);
	}
}
 
Example 23
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: 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 24
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public <UO> GenericRawResults<UO> queryRaw(String query, DatabaseResultsMapper<UO> mapper, String... arguments)
		throws SQLException {
	checkForInitialized();
	try {
		return statementExecutor.queryRaw(connectionSource, query, mapper, arguments, objectCache);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not perform raw query for " + query, e);
	}
}
 
Example 25
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public long queryRawValue(String query, String... arguments) throws SQLException {
	checkForInitialized();
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	try {
		return statementExecutor.queryForLong(connection, query, arguments);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not perform raw value query for " + query, e);
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example 26
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public int executeRaw(String statement, String... arguments) throws SQLException {
	checkForInitialized();
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		return statementExecutor.executeRaw(connection, statement, arguments);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not run raw execute statement " + statement, e);
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example 27
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public int executeRawNoArgs(String statement) throws SQLException {
	checkForInitialized();
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		return statementExecutor.executeRawNoArgs(connection, statement);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not run raw execute statement " + statement, e);
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example 28
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public int updateRaw(String statement, String... arguments) throws SQLException {
	checkForInitialized();
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName());
	try {
		return statementExecutor.updateRaw(connection, statement, arguments);
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not run raw update statement " + statement, e);
	} finally {
		connectionSource.releaseConnection(connection);
	}
}
 
Example 29
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
@Override
public T createObjectInstance() throws SQLException {
	try {
		T instance;
		if (objectFactory == null) {
			instance = constructor.newInstance();
		} else {
			instance = objectFactory.createObject(constructor, dataClass);
		}
		wireNewInstance(instance);
		return instance;
	} catch (Exception e) {
		throw SqlExceptionUtil.create("Could not create object for " + constructor.getDeclaringClass(), e);
	}
}
 
Example 30
Source Project: ormlite-core   Source File: BaseDaoImpl.java    License: ISC License 5 votes vote down vote up
/**
 * NOTE: package perms to removed synthetic accessor
 */
CloseableIterator<T> createIterator(PreparedQuery<T> preparedQuery, int resultFlags) throws SQLException {
	try {
		SelectIterator<T, ID> iterator =
				statementExecutor.buildIterator(this, connectionSource, preparedQuery, objectCache, resultFlags);
		return iterator;
	} catch (SQLException e) {
		throw SqlExceptionUtil.create("Could not build prepared-query iterator for " + dataClass, e);
	}
}