← Project templates

DATA · IN THE APP NOW

SQLite app

A task list stored in SQLite through database/sql. The database file lives under /sandbox, so it is still there the next time the program runs.

Offline: bundled gopherforge.app/sqlite driver, data kept with the project

Open it in the browser Playground →

What it is

On iPhone and iPad the program imports the app's bundled gopherforge.app/sqlite driver. It registers as sqlite with database/sql and runs statements in the system SQLite of the device, so the template builds and runs offline.

Databases written under /sandbox are kept with the project. Open Project > Databases to browse tasks.db: its tables, schema and rows, a SQL console for your own statements, and import and export through Files.

store.go runs numbered migrations in transactions and records progress in PRAGMA user_version. Each test opens its own in-memory database; one checks that adding the same title twice returns the same id, another that a STRICT table rejects text in an INTEGER column.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
sqlite-app/
├── vendor/
│   ├── gopherforge.app/sqlite/
│   │   ├── README.md
│   │   ├── host_other.go
│   │   └── sqlite.go
│   └── modules.txt
├── go.mod
├── main.go
├── store.go
└── store_test.go

The code

main.go

go
import (
	"database/sql"
	"fmt"
	"log"

	// GopherForge's driver: SQLite on this device, registered as "sqlite".
	// On a server, import _ "modernc.org/sqlite" instead and point dsn at a
	// real path; the driver name and the _pragma parameters stay the same.
	_ "gopherforge.app/sqlite"
)

// Files under /sandbox are kept with the project between runs. Open
// Project > Databases to browse tasks.db, or to run your own SQL against it.
const dsn = "/sandbox/tasks.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(3000)"

store.go

go
// migrations run in order; PRAGMA user_version remembers how many have run.
var migrations = []string{
	`CREATE TABLE tasks (
		id    INTEGER PRIMARY KEY,
		title TEXT    NOT NULL UNIQUE,
		done  INTEGER NOT NULL DEFAULT 0 CHECK (done IN (0, 1))
	) STRICT`,
	`CREATE TABLE runs (
		id INTEGER PRIMARY KEY,
		at TEXT NOT NULL DEFAULT (datetime('now'))
	) STRICT`,
}

store.go

go
func Open(db *sql.DB) (*Store, error) {
	var version int
	if err := db.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil {
		return nil, err
	}
	for version < len(migrations) {
		tx, err := db.Begin()
		if err != nil {
			return nil, err
		}
		if _, err := tx.Exec(migrations[version]); err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("migration %d: %w", version+1, err)
		}
		version++
		// PRAGMA takes no parameters, so the number is formatted in.
		if _, err := tx.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, version)); err != nil {
			tx.Rollback()
			return nil, err
		}
		if err := tx.Commit(); err != nil {
			return nil, err
		}
	}
	return &Store{db: db}, nil
}

store.go

go
// Add inserts a task, or returns the existing one with the same title:
// an UPSERT with RETURNING, both SQLite 3.35+.
func (s *Store) Add(title string) (int64, error) {
	var id int64
	err := s.db.QueryRow(`
		INSERT INTO tasks (title) VALUES (?)
		ON CONFLICT (title) DO UPDATE SET title = excluded.title
		RETURNING id`, title).Scan(&id)
	return id, err
}

store_test.go

go
func TestStrictTableRejectsWrongTypes(t *testing.T) {
	store := newStore(t)
	if _, err := store.db.Exec(`INSERT INTO tasks (title, done) VALUES ('x', 'yes')`); err == nil {
		t.Fatal("a STRICT table accepted text in an INTEGER column")
	}
}

What you learn

  • Open a database with sql.Open and a DSN that sets pragmas such as foreign_keys and busy_timeout.
  • Keep a single writer explicit with db.SetMaxOpenConns(1).
  • Run numbered migrations in transactions and track them with PRAGMA user_version.
  • Let SQLite enforce column types with STRICT tables and CHECK constraints.
  • Write an idempotent insert with ON CONFLICT DO UPDATE and RETURNING.
  • Give every test a fresh :memory: database and close it with t.Cleanup.

Run it on a server

As the comment in main.go says, import modernc.org/sqlite instead of the bundled driver, in main.go and store_test.go. It is a pure-Go SQLite that also registers as sqlite and accepts the same _pragma options. Remove the vendored driver, and point dsn at a writable path, since /sandbox exists only in the app.

go
import _ "modernc.org/sqlite"

const dsn = "tasks.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(3000)"
bash
rm -rf vendor
go mod edit -droprequire gopherforge.app/sqlite
go get modernc.org/sqlite
go mod tidy
go test ./...
go run .

Related: SQLite course · Around Go: SQL services · SQL transactions: every participating call uses the transaction