com.almworks.sqlite4java.SQLiteException Java Examples

The following examples show how to use com.almworks.sqlite4java.SQLiteException. 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: AttestationServer.java    From AttestationServer with MIT License 6 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, false);

        final SQLiteStatement select = conn.prepare("DELETE from Sessions where userId = ?");
        select.bind(1, account.userId);
        select.step();
        select.dispose();
    } finally {
        conn.dispose();
    }
    clearCookie(exchange);
    exchange.sendResponseHeaders(200, -1);
}
 
Example #2
Source File: SqliteStreamOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public void processTuple(int tableNum, HashMap<String, Object> tuple)
{
  InputSchema inputSchema = inputSchemas.get(tableNum);

  SQLiteStatement insertStatement = insertStatements.get(tableNum);
  try {
    for (Map.Entry<String, Object> entry : tuple.entrySet()) {
      ColumnInfo t = inputSchema.columnInfoMap.get(entry.getKey());
      if (t != null && t.bindIndex != 0) {
        insertStatement.bind(t.bindIndex, entry.getValue().toString());
      }
    }

    insertStatement.step();
    insertStatement.reset();
  } catch (SQLiteException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #3
Source File: AttestationServer.java    From AttestationServer with MIT License 6 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    exchange.getResponseHeaders().set("Content-Type", "image/png");
    exchange.sendResponseHeaders(200, 0);
    try (final OutputStream output = exchange.getResponseBody()) {
        final String contents = "attestation.app " +
            account.userId + " " +
            BaseEncoding.base64().encode(account.subscribeKey) + " " +
            account.verifyInterval;
        createQrCode(contents.getBytes(), output);
    }
}
 
Example #4
Source File: SQLiteWrapper.java    From sync-android with Apache License 2.0 6 votes vote down vote up
@Override
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
    if (values == null || values.size() == 0) {
        throw new IllegalArgumentException("Empty values");
    }

    try {
        String updateQuery = QueryBuilder.buildUpdateQuery(table, values, whereClause, whereArgs);
        Object[] bindArgs = QueryBuilder.buildBindArguments(values, whereArgs);
        this.executeSQLStatement(updateQuery, bindArgs);
        return getConnection().getChanges();
    } catch (SQLiteException e) {
        logger.log(Level.SEVERE, String.format("Error updating: %s, %s, %s, %s", table,
                values, whereClause, Arrays.toString(whereArgs)), e);
        return -1;
    }
}
 
Example #5
Source File: AttestationServer.java    From AttestationServer with MIT License 6 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, false);

        final byte[] subscribeKey = generateRandomToken();

        final SQLiteStatement select = conn.prepare("UPDATE Accounts SET " +
                "subscribeKey = ? WHERE userId = ?");
        select.bind(1, subscribeKey);
        select.bind(2, account.userId);
        select.step();
        select.dispose();
    } finally {
        conn.dispose();
    }
    exchange.sendResponseHeaders(200, -1);
}
 
Example #6
Source File: SQLiteWrapperUtils.java    From sync-android with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to run the query on the db and return the value in the
 * first column of the first row.
 */
public static Long longForQuery(SQLiteConnection conn, String query, Object[] bindArgs)
        throws SQLiteException {
    SQLiteStatement stmt = null;
    try {
        stmt = conn.prepare(query);
        if (bindArgs != null && bindArgs.length > 0) {
            stmt = SQLiteWrapperUtils.bindArguments(stmt, bindArgs);
        }
        if (stmt.step()) {
            return stmt.columnLong(0);
        } else {
            throw new IllegalStateException("query failed to return any result: " + query);
        }
    } finally {
        SQLiteWrapperUtils.disposeQuietly(stmt);
    }
}
 
Example #7
Source File: SQLite3StatementBindInvoker.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Object bind(SQLiteStatement stmt, Class<?> type, int index) {
   try {
      if (type.equals(String.class)) {
         return stmt.columnString(index);
      } else if (type.equals(Integer.class) || type.equals(int.class) ) {
         return stmt.columnInt(index);
      } else if (type.equals(Long.class) || type.equals(long.class)) {
         return stmt.columnLong(index);
      } else if (type.equals(Byte.class) || type.equals(byte.class) ) {
         return (byte)stmt.columnInt(index);
      } else if ( type.equals(Boolean.class) || type.equals(boolean.class) ) {
         return stmt.columnInt(index) != 0;
      } else if (type.equals(Double.class) || type.equals(double.class)) {
         return stmt.columnDouble(index);
      } else if (type.equals(float.class) || type.equals(Float.class)) {
         return (float)stmt.columnDouble(index);
      } else if (type.equals(Serializable.class)) {
         return stmt.columnBlob(index);
      }
   } catch (SQLiteException e) {
      log.error("sql bind invoker could not invoke:" , e);
   }

   return null;
}
 
Example #8
Source File: SQLiteWrapperUtils.java    From sync-android with Apache License 2.0 6 votes vote down vote up
public static SQLiteCursor buildSQLiteCursor(SQLiteConnection conn, String sql, Object[] bindArgs)
        throws SQLiteException {
    SQLiteStatement stmt = null;
    try {
        stmt = bindArguments(conn.prepare(sql), bindArgs);
        List<String> columnNames = null;
        List<Tuple> resultSet = new ArrayList<Tuple>();
        while (!stmt.hasStepped() || stmt.hasRow()) {
            if (!stmt.step()) {
                break;
            }
            if (columnNames == null) {
                columnNames = getColumnNames(stmt);
            }

            Tuple t = getDataRow(stmt);
            logger.finest("Tuple: "+ t.toString());
            resultSet.add(t);
        }
        return new SQLiteCursor(columnNames, resultSet);
    } finally {
        SQLiteWrapperUtils.disposeQuietly(stmt);
    }
}
 
Example #9
Source File: SQLiteWrapperUtils.java    From sync-android with Apache License 2.0 5 votes vote down vote up
static List<String> getColumnNames(SQLiteStatement stmt) throws SQLiteException {
//        Log.v(LOG_TAG, "getColumnNames()");
        List<String> columnNames = new ArrayList<String>();
        int columnCount = stmt.columnCount();
        for (int i = 0; i < columnCount; i++) {
            columnNames.add(i, stmt.getColumnName(i));
        }
//        Log.v(LOG_TAG, "columnNames:" + columnNames);
        return columnNames;
    }
 
Example #10
Source File: SQLiteWrapperUtils.java    From sync-android with Apache License 2.0 5 votes vote down vote up
static List<Integer> getColumnTypes(SQLiteStatement stmt) throws SQLiteException {
//        Log.v(LOG_TAG, "getColumnTypes()");
        List<Integer> columnTypes = new ArrayList<Integer>();
        int columnCount = stmt.columnCount();
        for (int i = 0; i < columnCount; i++) {
            columnTypes.add(i, mapColumnType(stmt.columnType(i)));
        }
//        Log.v(LOG_TAG, "columnTypes:" + columnTypes);
        return columnTypes;
    }
 
Example #11
Source File: SQLiteWrapper.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Override
public int delete(String table, String whereClause, String[] whereArgs) {
    try {
        String sql = new StringBuilder("DELETE FROM \"")
                .append(table)
                .append("\"")
                .append(!Misc.isStringNullOrEmpty(whereClause) ? " WHERE " +
                        whereClause : "")
                .toString();
        this.executeSQLStatement(sql, whereArgs);
        return getConnection().getChanges();
    } catch (SQLiteException e) {
        return 0;
    }
}
 
Example #12
Source File: Db.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private SQLiteConnection createConnection() {
   try {
      SQLiteConnection db = new SQLiteConnection(dbFile);
      db.openV2(
         SQLiteConstants.SQLITE_OPEN_READWRITE |
         SQLiteConstants.SQLITE_OPEN_CREATE |
         SQLiteConstants.SQLITE_OPEN_FULLMUTEX |
         SQLiteConstants.SQLITE_OPEN_PRIVATECACHE
      );
      return db;
   } catch (SQLiteException ex) {
      throw new DbException("could not connect to db", ex);
   }
}
 
Example #13
Source File: SQLiteWrapperUtils.java    From sync-android with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to run the query on the db and return the value in the
 * first column of the first row.
 */
public static int intForQuery(SQLiteConnection conn, String query, Object[] bindArgs) throws SQLiteException {
    SQLiteStatement stmt = null;
    try {
        stmt = bindArguments(conn.prepare(query), bindArgs);
        if (stmt.step()) {
            return stmt.columnInt(0);
        } else {
            throw new IllegalStateException("query failed to return any result: " + query);
        }
    } finally {
        SQLiteWrapperUtils.disposeQuietly(stmt);
    }
}
 
Example #14
Source File: SQLiteWrapper.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Override
public SQLiteCursor rawQuery(String sql, String[] bindArgs) throws SQLException {
    try {
        return SQLiteWrapperUtils.buildSQLiteCursor(getConnection(), sql, bindArgs);
    } catch (SQLiteException e) {
        throw new SQLException(e);
    }
}
 
Example #15
Source File: SQLiteWrapperUtils.java    From sync-android with Apache License 2.0 5 votes vote down vote up
static Tuple getDataRow(SQLiteStatement stmt) throws SQLiteException {
        logger.entering("com.cloudant.sync.internal.sqlite.sqlite4java.SQLiteWrapperUtils","getDataRow",stmt);
        Tuple result = new Tuple(getColumnTypes(stmt));
        for (int i = 0; i < stmt.columnCount(); i++) {
            Integer type = stmt.columnType(i);
//            Log.v(LOG_TAG, "i: " + i + ", type: " + mapColumnType(type) + ", expected type: " + result.getType(i));
            switch (type) {
                case SQLiteConstants.SQLITE_NULL:
                    result.put(i);
                    break;
                case SQLiteConstants.SQLITE_TEXT:
                    result.put(i, stmt.columnString(i));
                    break;
                case SQLiteConstants.SQLITE_INTEGER:
                    result.put(i, stmt.columnLong(i));
                    break;
                case SQLiteConstants.SQLITE_FLOAT:
                    result.put(i, Double.valueOf(stmt.columnDouble(i)).floatValue());
                    break;
                case SQLiteConstants.SQLITE_BLOB:
                    result.put(i, stmt.columnBlob(i));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported data type: " + type);
            }
        }
        return result;
    }
 
Example #16
Source File: SQLiteWrapper.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Override
public void execSQL(String sql, Object[] bindArgs) throws SQLException {
    Misc.checkNotNullOrEmpty(sql.trim(), "Input SQL");
    SQLiteStatement stmt = null;
    try {
        stmt = this.getConnection().prepare(sql);
        stmt = SQLiteWrapperUtils.bindArguments(stmt, bindArgs);
        while (stmt.step()) {
        }
    } catch (SQLiteException e) {
        throw new SQLException(e);
    } finally {
        SQLiteWrapperUtils.disposeQuietly(stmt);
    }
}
 
Example #17
Source File: SQLiteWrapper.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Override
public void execSQL(String sql) throws SQLException {
    Misc.checkNotNullOrEmpty(sql.trim(), "Input SQL");
    try {
        getConnection().exec(sql);
    } catch (SQLiteException e) {
        throw new SQLException(e);
    }
}
 
Example #18
Source File: SQLiteWrapper.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Override
public int getVersion() {
    try {
        return SQLiteWrapperUtils.longForQuery(getConnection(), "PRAGMA user_version;").intValue();
    } catch (SQLiteException e) {
        throw new IllegalStateException("Can not query for the user_version?");
    }
}
 
Example #19
Source File: SqliteStreamOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void endWindow()
{
  try {
    commitStatement.step();
    commitStatement.reset();
    if (bindings != null) {
      for (int i = 0; i < bindings.size(); i++) {
        execStatement.bind(i, bindings.get(i).toString());
      }
    }
    int columnCount = execStatement.columnCount();
    while (execStatement.step()) {
      HashMap<String, Object> resultRow = new HashMap<String, Object>();
      for (int i = 0; i < columnCount; i++) {
        resultRow.put(execStatement.getColumnName(i), execStatement.columnValue(i));
      }
      this.result.emit(resultRow);
    }
    execStatement.reset();

    for (SQLiteStatement st : deleteStatements) {
      st.step();
      st.reset();
    }
  } catch (SQLiteException ex) {
    throw new RuntimeException(ex);
  }
  bindings = null;
}
 
Example #20
Source File: SqliteStreamOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void beginWindow(long windowId)
{
  try {
    beginStatement.step();
    beginStatement.reset();
  } catch (SQLiteException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #21
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final InputStream input = exchange.getRequestBody();

    final ByteArrayOutputStream sample = new ByteArrayOutputStream();
    final byte[] buffer = new byte[4096];
    for (int read = input.read(buffer); read != -1; read = input.read(buffer)) {
        sample.write(buffer, 0, read);

        if (sample.size() > 64 * 1024) {
            exchange.sendResponseHeaders(413, -1);
            return;
        }
    }

    final SQLiteConnection conn = new SQLiteConnection(SAMPLES_DATABASE);
    try {
        open(conn, false);
        final SQLiteStatement insert = conn.prepare("INSERT INTO Samples " +
               "(sample, time) VALUES (?, ?)");
        insert.bind(1, sample.toByteArray());
        insert.bind(2, System.currentTimeMillis());
        insert.step();
        insert.dispose();
    } finally {
        conn.dispose();
    }

    exchange.sendResponseHeaders(200, -1);
}
 
Example #22
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    writeDevicesJson(exchange, account.userId);
}
 
Example #23
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final String requestToken;
    final String fingerprint;
    try (final JsonReader reader = Json.createReader(exchange.getRequestBody())) {
        final JsonObject object = reader.readObject();
        requestToken = object.getString("requestToken");
        fingerprint = object.getString("fingerprint");
    } catch (final ClassCastException | JsonException | NullPointerException e) {
        e.printStackTrace();
        exchange.sendResponseHeaders(400, -1);
        return;
    }

    final Account account = verifySession(exchange, false, requestToken.getBytes(StandardCharsets.UTF_8));
    if (account == null) {
        return;
    }

    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, false);

        final SQLiteStatement update = conn.prepare("UPDATE Devices SET " +
                "deletionTime = ? WHERE userId = ? AND hex(fingerprint) = ?");
        update.bind(1, System.currentTimeMillis());
        update.bind(2, account.userId);
        update.bind(3, fingerprint);
        update.step();
        update.dispose();

        if (conn.getChanges() == 0) {
            exchange.sendResponseHeaders(400, -1);
            return;
        }
    } finally {
        conn.dispose();
    }
    exchange.sendResponseHeaders(200, -1);
}
 
Example #24
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    final JsonObjectBuilder accountJson = Json.createObjectBuilder();
    accountJson.add("username", account.username);
    accountJson.add("verifyInterval", account.verifyInterval);
    accountJson.add("alertDelay", account.alertDelay);

    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, true);
        final SQLiteStatement select = conn.prepare("SELECT address FROM EmailAddresses " +
                "WHERE userId = ?");
        select.bind(1, account.userId);
        if (select.step()) {
            accountJson.add("email", select.columnString(0));
        }
        select.dispose();
    } finally {
        conn.dispose();
    }

    exchange.getResponseHeaders().set("Content-Type", "application/json");
    exchange.sendResponseHeaders(200, 0);
    try (final OutputStream output = exchange.getResponseBody();
            final JsonWriter writer = Json.createWriter(output)) {
        writer.write(accountJson.build());
    }
}
 
Example #25
Source File: MbVectorTilesInputFormat.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
protected long getRecordCount(Configuration conf) throws IOException
{
  String countQuery = "SELECT COUNT(*) FROM tiles WHERE zoom_level=?";
  // Run the count query and grab the result.
  SQLiteConnection conn = null;
  try {
    conn = MbVectorTilesDataProvider.getDbConnection(dbSettings, conf);
    SQLiteStatement stmt = null;
    try {
      stmt = conn.prepare(countQuery, false);
      stmt.bind(1, zoomLevel);
      if (stmt.step()) {
        return stmt.columnLong(0);
      }
      else {
        throw new IOException("Unable to count tiles for zoom " + zoomLevel + " in " + dbSettings.getFilename());
      }
    }
    finally {
      if (stmt != null) {
        stmt.dispose();
      }
    }
  }
  catch (SQLiteException e)
  {
    String msg = "Unable to get the count of records using query: " + countQuery;
    log.error(msg, e);
    throw new IOException(msg, e);
  }
  finally {
    if (conn != null) {
      conn.dispose();
    }
  }
}
 
Example #26
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, true, null);
    if (account == null) {
        return;
    }
    clearCookie(exchange);
    exchange.sendResponseHeaders(200, -1);
}
 
Example #27
Source File: MbVectorTilesRecordReader.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException
{
  if (!(split instanceof MbVectorTilesInputSplit)) {
    throw new IOException("Expected an instance of PgInputSplit");
  }
  offset = ((MbVectorTilesInputSplit) split).getOffset();
  limit = ((MbVectorTilesInputSplit) split).getLimit();
  zoomLevel = ((MbVectorTilesInputSplit) split).getZoomLevel();
  currIndex = (offset < 0) ? 0 : offset - 1;
  try
  {
    conn = MbVectorTilesDataProvider.getDbConnection(dbSettings,
            context.getConfiguration());
    // If the offset is < 0, then there is only one partition, so no need
    // for a limit query.
    String query ="SELECT tile_column, tile_row, tile_data FROM tiles WHERE zoom_level=? order by zoom_level, tile_column, tile_row";
    if (offset >= 0 && limit >= 0) {
      query = query + " LIMIT ? OFFSET ?";
    }
    tileStmt = conn.prepare(query);
    tileStmt.bind(1, zoomLevel);
    if (offset >= 0 && limit >= 0) {
      tileStmt.bind(2, limit);
      tileStmt.bind(3, offset);
    }
  }
  catch (SQLiteException e)
  {
    throw new IOException("Could not open database.", e);
  }
}
 
Example #28
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
private static void changePassword(final long userId, final String currentPassword, final String newPassword)
        throws GeneralSecurityException, SQLiteException {
    validatePassword(currentPassword);
    validatePassword(newPassword);

    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, false);

        conn.exec("BEGIN TRANSACTION");

        final SQLiteStatement select = conn.prepare("SELECT passwordHash, passwordSalt " +
                "FROM Accounts WHERE userId = ?");
        select.bind(1, userId);
        select.step();
        final byte[] currentPasswordHash = select.columnBlob(0);
        final byte[] currentPasswordSalt = select.columnBlob(1);
        select.dispose();
        if (!MessageDigest.isEqual(hash(currentPassword.getBytes(), currentPasswordSalt), currentPasswordHash)) {
            throw new GeneralSecurityException("invalid password");
        }

        final byte[] newPasswordSalt = generateRandomToken();
        final byte[] newPasswordHash = hash(newPassword.getBytes(), newPasswordSalt);

        final SQLiteStatement update = conn.prepare("UPDATE Accounts " +
                "SET passwordHash = ?, passwordSalt = ? WHERE userId = ?");
        update.bind(1, newPasswordHash);
        update.bind(2, newPasswordSalt);
        update.bind(3, userId);
        update.step();
        update.dispose();

        conn.exec("COMMIT TRANSACTION");
    } finally {
        conn.dispose();
    }
}
 
Example #29
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
private static void createAccount(final String username, final String password)
        throws GeneralSecurityException, SQLiteException {
    if (username.length() > 32 || !username.matches("[a-zA-Z0-9]+")) {
        throw new GeneralSecurityException("invalid username");
    }
    validatePassword(password);

    final byte[] passwordSalt = generateRandomToken();
    final byte[] passwordHash = hash(password.getBytes(), passwordSalt);
    final byte[] subscribeKey = generateRandomToken();

    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, false);
        final SQLiteStatement insert = conn.prepare("INSERT INTO Accounts " +
                "(username, passwordHash, passwordSalt, subscribeKey, creationTime, verifyInterval, alertDelay) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)");
        insert.bind(1, username);
        insert.bind(2, passwordHash);
        insert.bind(3, passwordSalt);
        insert.bind(4, subscribeKey);
        insert.bind(5, System.currentTimeMillis());
        insert.bind(6, DEFAULT_VERIFY_INTERVAL);
        insert.bind(7, DEFAULT_ALERT_DELAY);
        insert.step();
        insert.dispose();
    } catch (final SQLiteException e) {
        if (e.getErrorCode() == SQLITE_CONSTRAINT_UNIQUE) {
            throw new UsernameUnavailableException();
        }
        throw e;
    } finally {
        conn.dispose();
    }
}
 
Example #30
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
static void open(final SQLiteConnection conn, final boolean readOnly) throws SQLiteException {
    if (readOnly) {
        conn.openReadonly();
    } else {
        conn.open();
    }
    conn.setBusyTimeout(BUSY_TIMEOUT);
    conn.exec("PRAGMA foreign_keys=ON");
    conn.exec("PRAGMA journal_mode=WAL");
}