SQLite User Forum

Open database given only file descriptor (vs. filename)?
Login

Open database given only file descriptor (vs. filename)?

(1) By anonymous on 2022-03-18 20:02:06 [link] [source]

On Linux, is it possible to open and access (read-only is fine) a sqlite3 database, if all you have is an already-open file descriptor to the database file? Assume that the database file is too large to copy, and you were in full control of its creation (e.g. so you know there were no open transactions, no usage of WAL mode, or whatever other constraints are useful)

A different way of asking the question might be "is a sqlite database viable as a read-only file format, if all you get is a file descriptor for the database, vs. a filename that you can pass to a typical sqlite open call."

(2) By Larry Brasfield (larrybr) on 2022-03-18 20:23:04 in reply to 1 [source]

There is no API for doing that directly.

You might find that a VFS shim, adapted from one of the VFS implementations published within the extensions directory, gets the job done without too much trouble.

(3) By anonymous on 2022-03-18 22:53:18 in reply to 1 [link] [source]

int sqlite_fdopen(
    int fd,
    sqlite3 **connection)
{
    char uri[48];

    snprintf(uri, sizeof uri, "file:///dev/fd/%d?immutable=1", fd);
    return sqlite3_open_v2(
        uri,
        connection,
        SQLITE_OPEN_READONLY | SQLITE_OPEN_URI,
        NULL);
}

SQLite will then use a duplicate of the original file descriptor, which shouldn't matter much.

(4) By anonymous on 2022-03-19 11:44:19 in reply to 1 [link] [source]

Others have already shown that it's possible; I'll just recommend you to carefully read How to corrupt an SQLite database file, especially parts 1.1 and 2.2 which mention file descriptors. But since you control this file descriptor and can impose any reasonable constraints on it, that shouldn't be a problem.