com.j256.ormlite.misc.SqlExceptionUtil Java Examples

The following examples show how to use com.j256.ormlite.misc.SqlExceptionUtil. 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: DatabaseTableConfigLoader.java    From ormlite-core with 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 #2
Source File: MappedDelete.java    From ormlite-core with 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 #3
Source File: MappedDelete.java    From ormlite-core with 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 #4
Source File: MappedDeleteCollection.java    From ormlite-core with 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 #5
Source File: AndroidCompiledStatement.java    From ormlite-android with 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 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 #7
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 #8
Source File: AndroidDatabaseConnection.java    From ormlite-android with 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 #9
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 #10
Source File: DateLongType.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 date-long value: "
				+ defaultStr, e);
	}
}
 
Example #11
Source File: BigDecimalStringType.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).toString();
	} catch (IllegalArgumentException e) {
		throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default BigDecimal string '"
				+ defaultStr + "'", e);
	}
}
 
Example #12
Source File: BigDecimalStringType.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 BigDecimal((String) sqlArg);
	} catch (IllegalArgumentException e) {
		throw SqlExceptionUtil.create("Problems with column " + columnPos + " parsing BigDecimal string '" + sqlArg
				+ "'", e);
	}
}
 
Example #13
Source File: StringBytesType.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
	if (defaultStr == null) {
		return null;
	} else {
		try {
			return defaultStr.getBytes(getCharsetName(fieldType));
		} catch (UnsupportedEncodingException e) {
			throw SqlExceptionUtil.create("Could not convert default string: " + defaultStr, e);
		}
	}
}
 
Example #14
Source File: StringBytesType.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 {
	byte[] bytes = (byte[]) sqlArg;
	String charsetName = getCharsetName(fieldType);
	try {
		// NOTE: I can't use new String(bytes, Charset) because it was introduced in 1.6.
		return new String(bytes, charsetName);
	} catch (UnsupportedEncodingException e) {
		throw SqlExceptionUtil.create("Could not convert string with charset name: " + charsetName, e);
	}
}
 
Example #15
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 #16
Source File: BigIntegerType.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 BigInteger(defaultStr).toString();
	} catch (IllegalArgumentException e) {
		throw SqlExceptionUtil.create(
				"Problems with field " + fieldType + " parsing default BigInteger string '" + defaultStr + "'", e);
	}
}
 
Example #17
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 #18
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 #19
Source File: DateStringType.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 {
	String value = (String) sqlArg;
	DateStringFormatConfig formatConfig = convertDateStringConfig(fieldType, defaultDateFormatConfig);
	try {
		return parseDateString(formatConfig, value);
	} catch (ParseException e) {
		throw SqlExceptionUtil.create("Problems with column " + columnPos + " parsing date-string '" + value
				+ "' using '" + formatConfig + "'", e);
	}
}
 
Example #20
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 #21
Source File: DateTimeType.java    From ormlite-core with ISC License 5 votes vote down vote up
private Object createInstance(Long sqlArg) throws SQLException {
	try {
		if (millisConstructor == null) {
			Class<?> clazz = getDateTimeClass();
			millisConstructor = clazz.getConstructor(long.class);
		}
		return millisConstructor.newInstance(sqlArg);
	} catch (Exception e) {
		throw SqlExceptionUtil.create("Could not use reflection to construct a Joda DateTime", e);
	}
}
 
Example #22
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 #23
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 #24
Source File: BaseDaoImpl.java    From ormlite-core with 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);
	}
}
 
Example #25
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 #26
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 #27
Source File: ByteArrayType.java    From ormlite-core with ISC License 5 votes vote down vote up
private Object getBytesImpl(FieldType fieldType, String stringValue) throws SQLException {
	if (fieldType == null || fieldType.getFormat() == null) {
		return stringValue.getBytes();
	} else {
		try {
			return stringValue.getBytes(fieldType.getFormat());
		} catch (UnsupportedEncodingException e) {
			throw SqlExceptionUtil.create("Could not convert default string: " + stringValue, e);
		}
	}
}
 
Example #28
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 #29
Source File: DatabaseFieldConfigLoader.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Write the configuration to a buffered writer.
 */
public static void write(BufferedWriter writer, DatabaseFieldConfig config, String tableName) throws SQLException {
	try {
		writeConfig(writer, config, tableName);
	} catch (IOException e) {
		throw SqlExceptionUtil.create("Could not write config to writer", e);
	}
}
 
Example #30
Source File: SchemaUtils.java    From ormlite-core with ISC License 5 votes vote down vote up
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, StatementType.EXECUTE, noFieldTypes,
                    DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
            rowC = compiledStmt.runExecute();
            logger.info("executed {} schema statement changed {} rows: {}", label, rowC, statement);
        } catch (SQLException e) {
            if (ignoreErrors) {
                logger.info("ignoring {} error '{}' for statement: {}", label, e, statement);
            } else {
                throw SqlExceptionUtil.create("SQL statement failed: " + statement, e);
            }
        } finally {
            IOUtils.closeThrowSqlException(compiledStmt, "compiled statement");
        }
        // 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;
}