GOTTH+
GitHub

Building

Data: SQLite, Postgres or MySQL

Choosing a database, connecting to it, the migrations that create its tables, and the safe patterns for queries.

Choosing a database

Every project talks to its database through GORM, so models, repositories and queries are the same code whichever database you pick. Choose one with --db when you create the project. Only the connection code, the configuration and the test setup change. With Postgres or MySQL, the generator names the database after the project, with each character that isn't a letter, digit or underscore turned into an underscore, and prints the command that creates it.

--dbDriverConnectionGood for
sqlite (default)glebarez/sqlite, pure Go (or mattn/go-sqlite3 with --sqlite-driver=cgo)DatabasePath, a file. Defaults to app.db.Learning, prototypes and single-server apps. Nothing else to run.
postgresgorm.io/driver/postgres, pure GoDatabaseURL, required. For example postgres://localhost:5432/my_app?sslmode=disableMost production apps, managed cloud databases, and Supabase Auth, which always uses Postgres.
mysqlgorm.io/driver/mysql, pure GoDatabaseURL, required, in go-sql-driver/mysql's DSN format. For example root@tcp(localhost:3306)/my_app?parseTime=true&charset=utf8mb4&loc=UTCTeams and hosts already running MySQL or a MySQL-compatible server.
go run github.com/owenwexler/create-gotth-plus-app@latest my-app --db=postgres
createdb my_app    # Postgres: create the database before the first run

go run github.com/owenwexler/create-gotth-plus-app@latest my-app --db=mysql
mysql -u root -e 'CREATE DATABASE my_app CHARACTER SET utf8mb4'

Connecting

SQLite needs no server. DatabasePath sets the file, and the file is created on first use. In production, put it on a volume that survives redeploys and keep it readable only by the app's user. A new project opens SQLite with GORM's defaults. If reads and writes start waiting on each other, turn on WAL mode and a busy timeout, so a read never blocks a write and a short lock wait is retried instead of failing. With the pure-Go driver, add them to the path in ConnectDb:

dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(ON)", path)

Postgres and MySQL read DatabaseURL, and the app refuses to start without it. Point it at a local server or a cloud database. internal/database opens a pool of up to 25 connections, well below the server's default connection limit so more than one instance fits, and recycles each connection after 30 minutes, or 5 idle, so failovers and server-side timeouts are picked up.

  • Connect over TLS to any server that isn't localhost: sslmode=verify-full on Postgres, tls=true on MySQL.
  • Log in as the app's own user with only the privileges it needs, never as a superuser or root.
  • MySQL needs parseTime=true in the DSN, because the models use time.Time.
  • IDs are stored as a uuid column on Postgres and char(36) on MySQL. SQLite takes the value as it is.

Migrations

A new project creates its tables in development. make seed calls the /seed route, which runs GORM's AutoMigrate for the example model and then loads seedData.json. It is safe to run more than once. The route only exists in development: GoEnv=production unregisters it, so nothing changes the schema in production until you decide how it should.

make seed    # development: create the tables, then load seedData.json

Before the first deploy, add an explicit migration step. Run it before each new server starts, never from inside the server, so a schema change happens once and not on every instance. AutoMigrate creates missing tables, columns and indexes, and can change a column's type, but it never drops or renames a column. Review what it will do, or switch to a versioned migration tool such as goose, golang-migrate or Atlas. All three work with SQLite, Postgres and MySQL.

If AutoMigrate is enough for your schema, a small command is all it takes: a cmd/migrate whose main connects with database.ConnectDb and calls AutoMigrate with every model the app stores, built into the image beside the server and run by each deploy before the new server starts. With sign-in, model.All() already lists every model.

Safe queries

  • Use bound parameters: Where("slug = ?", slug). Never concatenate user input into SQL.
  • Map user-chosen sort columns through an allow-list before they reach Order.
  • Map a form into a DTO, validate it, then copy the allowed fields. Never bind a request straight into a model: that lets a client set its own id or timestamps.
  • Escape LIKE wildcards with escaper.Like, and cap the length of any search. On SQLite and Postgres, add ESCAPE '\' to the query. MySQL already uses \ as its escape character, so MySQL queries need no ESCAPE clause.
  • Paginate every list. repository.Paginate clamps the page size to 100.

Testing

On SQLite, each test opens its own temporary file, so the tests need nothing installed. On Postgres and MySQL, the tests need a running server: internal/database/dbtest creates a fresh database for each test and drops it when the test ends. It uses TestDatabaseURL, or DatabaseURL when that is empty, so that user needs CREATEDB on Postgres, or CREATE and DROP on MySQL. Never point either at a production server.

Concurrent updates

Let the database do the arithmetic. Reading a value, changing it in Go and writing it back loses one of two updates that arrive at the same moment. Use a single UPDATE with gorm.Expr, or an upsert with clause.OnConflict, which all three databases support, then read the result back in the same request rather than trusting the number the client already has.

db.Model(&model.Post{}).Where("id = ?", id).Update("likes", gorm.Expr("likes + ?", 1))

Was this page helpful?

Be the first to answer.