+ int version = 0;
+ try (GigiPreparedStatement gigiPreparedStatement = new GigiPreparedStatement("SELECT version FROM \"schemeVersion\" ORDER BY version DESC LIMIT 1;")) {
+ GigiResultSet rs = gigiPreparedStatement.executeQuery();
+ if (rs.next()) {
+ version = rs.getInt(1);
+ }
+ }
+ if (version == CURRENT_SCHEMA_VERSION) {
+ return; // Good to go
+ }
+ if (version > CURRENT_SCHEMA_VERSION) {
+ throw new Error("Invalid database version. Please fix this.");
+ }
+ upgrade(version);
+ }
+
+ private static void upgrade(int version) {
+ try {
+ Statement s = getInstance().c.createStatement();
+ try {
+ while (version < CURRENT_SCHEMA_VERSION) {
+ try (InputStream resourceAsStream = DatabaseConnection.class.getResourceAsStream("upgrade/from_" + version + ".sql")) {
+ if (resourceAsStream == null) {
+ throw new Error("Upgrade script from version " + version + " was not found.");
+ }
+ SQLFileManager.addFile(s, resourceAsStream, ImportType.PRODUCTION);
+ }
+ version++;
+ }
+ s.addBatch("UPDATE \"schemeVersion\" SET version='" + version + "'");
+ System.out.println("UPGRADING Database to version " + version);
+ s.executeBatch();
+ System.out.println("done.");
+ } finally {
+ s.close();
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static final String preprocessQuery(String originalQuery) {
+ originalQuery = originalQuery.replace('`', '"');
+ if (originalQuery.matches("^INSERT INTO [^ ]+ SET .*")) {
+ Pattern p = Pattern.compile("INSERT INTO ([^ ]+) SET (.*)");
+ Matcher m = p.matcher(originalQuery);
+ if (m.matches()) {
+ String replacement = "INSERT INTO " + toIdentifier(m.group(1));
+ String[] parts = m.group(2).split(",");
+ StringJoiner columns = new StringJoiner(", ");
+ StringJoiner values = new StringJoiner(", ");
+ for (int i = 0; i < parts.length; i++) {
+ String[] split = parts[i].split("=", 2);
+ columns.add(toIdentifier(split[0]));
+ values.add(split[1]);
+ }
+ replacement += "(" + columns.toString() + ") VALUES(" + values.toString() + ")";
+ return replacement;
+ }
+ }
+
+ //
+ return originalQuery;