backup in memory sqlite db to byte array using jooq Context

坚强是说给别人听的谎言 提交于 2019-12-24 11:45:08

问题


private byte[] inMemSqliteDbBackup() {
    byte[] data = null;
    try (DSLContext dsl = DSL.using("jdbc:sqlite::memory:") {
        ...
        //insert some data 
        dsl.execute("backup to " + data); // backup to byte[], but unsupported , a file is needed 
        dsl.connection(connection -> {
            // or, get underlying connection and open inputstream 
            // but there is no getInputStream in SqliteConnection
        });
    }
    return data;
}

How can we backup in memory sqlite db to byte[] ? I went through SqliteConnection and it does not give an InputStream either.

one option is to not use in memory db by using url as "jdbc:sqlite:/some-location" and then we can use FileUtils.readFileToByteArray(new File(some-location)) , but not sure if we can do the same with in memory sqlite db and still using DSLContext by Jooq.


回答1:


That backup to syntax is not a native SQLite SQL syntax, but offered by the Xerial JDBC driver according to their docs here:

Take a backup of the whole database to backup.db file:

// Create a memory database
Connection conn = DriverManager.getConnection("jdbc:sqlite:");
Statement stmt = conn.createStatement();
// Do some updates
stmt.executeUpdate("create table sample(id, name)");
stmt.executeUpdate("insert into sample values(1, \"leo\")");
stmt.executeUpdate("insert into sample values(2, \"yui\")");
// Dump the database contents to a file
stmt.executeUpdate("backup to backup.db");
Restore the database from a backup file:
// Create a memory database
Connection conn = DriverManager.getConnection("jdbc:sqlite:");
// Restore the database from a backup file
Statement stat = conn.createStatement();
stat.executeUpdate("restore from backup.db");

If you reverse engineer their sources, you can see that the command is intercepted, and translated to this particular method in org.sqlite.core.NativeDB:

native synchronized int backup(byte[] dbNameUtf8, byte[] destFileNameUtf8,
        ProgressObserver observer) throws SQLException;

I.e. it is bound to the SQLite backup API, which can operate only with actual files, not with in-memory data structures.

So, I'm afraid you cannot, with the current versions of SQLite, intercept that backup and send that into a byte[] variable, without an intermediate temporary file being written, regardless if using jOOQ or JDBC or native SQLite directly



来源:https://stackoverflow.com/questions/53102512/backup-in-memory-sqlite-db-to-byte-array-using-jooq-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!