The standard librarySlide 74 of 86
74:memory:The standard library

The in-memory trap

An in-memory SQLite database (:memory:) belongs to one connection, not to the program: each connection gets its own empty database, which disappears when the connection closes. connect and pool both open a pool of connections, so queries work one at a time and fail as soon as two overlap. The second query gets a new connection, finds an empty database, and fails with "no such table". Tests that run one query at a time pass, and a server fails as soon as it handles two requests at once.

Use "file::memory:?cache=shared" instead: every connection shares one in-memory database, and the pool can grow with the load. Limiting the pool to one connection with pool(…, 1, 1) also works, but then every query in the program waits its turn. This is how SQLite behaves, not a Hive rule.

A row type
type User { id: Int, name: Str }

query findUser(name: Str): User[dyn] {
	SELECT id, name FROM users WHERE name = {name}
}

proc lookUp(db: hive.sql.SqlConnection, name: Str): Str {
	if hive.sql.run(db, findUser(name)) is Result.Ok(rows) {
		if rows bounds 0 {
			return rows[0].name
		}
	}
	return "?"
}

proc main(): void {
	// A plain ":memory:" would give each of these eight connections a
	// private, empty database of its own. The shared cache is what makes
	// them all the same one.
	opened := hive.sql.pool(hive.sql.DatabaseDriver.SQLite(), "file::memory:?cache=shared", 8, 1)
	if opened is Result.Ok(db) {
		hive.sql.unsafe(db, "CREATE TABLE users (id INTEGER, name TEXT)")
		hive.sql.unsafe(db, "INSERT INTO users (id, name) VALUES (1, 'ada'), (2, 'grace')")

		echo await [lookUp(db, "ada"), lookUp(db, "grace")]
		hive.sql.close(db)
	}
}