Search code examples
sqlitego-sqlite3

Why is sqlite3 memory database persisted to disk?


In my go program I does this to initialize my sqlite3 schema:

db.MustExec(`ATTACH DATABASE ":memory:" AS "mem"`)
db.MustExec(`CREATE TABLE IF NOT EXISTS "mem.token" (
    "token"  TEXT NOT NULL UNIQUE,
    "expire" INTEGER NOT NULL,
    "login"  TEXT NOT NULL,
    "auth"   INTEGER NOT NULL,
    PRIMARY KEY("token")
) WITHOUT ROWID`)

The problem is, this table is persisted to disk! After quit the program, I use sqlite3 command line tool to open the database file, the mem.token table is still there, if I insert data into it, the data is persisted and available even after I reboot my PC.

How to make a memory table with transient data?


Solution

  • By quoting the database you create with:

    db.MustExec(`CREATE TABLE IF NOT EXISTS "mem.token" (
    

    You're instructing SQLite to create a database called literally mem.token on the current database. If you want to create a database called token on the attached memory database, don't use the quotes:

    db.MustExec(`CREATE TABLE IF NOT EXISTS mem.token (