Skip to content

plainsql generate

Terminal window
plainsql generate

Run this after you change your SQL or your schema. PlainSQL reads plainsql.yaml, connects to the database, checks every query against the schema, and writes the Go code to the output directory. Apply your migrations to the database first.

Terminal window
plainsql generate --config config/plainsql.yaml
plainsql generate --project blog
plainsql generate --project blog --project reporting

By default, PlainSQL generates every project. Repeat --project to pick several. --config reads a different configuration file, and paths in that file are relative to it. The include and mode settings in each queries entry control which SQL files are selected and how they are checked.

With dir: gen/db and two SQL files, the output looks like this:

queries/
posts.sql
users.sql
gen/db/
plainsql.go # Queries, New, interfaces, Store, and transaction helpers
models.go # Shared models and enums
posts.sql.go # SQL, query-specific types, and methods from posts.sql
users.sql.go # SQL, query-specific types, and methods from users.sql

Each .sql file becomes one .sql.go file. The methods and their Params and Row structs stay together in that file. For example, CreatePost and CreatePostParams are both in posts.sql.go. Shared models and enums go in models.go. PlainSQL skips that file when there are none.

Because the SQL file name becomes the Go file name, every selected SQL file in a project needs a unique name. The comparison ignores case and ignores directories. Two files called queries.sql in different directories cause an error.

Generation deletes everything in the output directory and writes the new files. Keep your own code and tests somewhere else.

PlainSQL analyzes and renders every selected project before it writes anything. If any step fails, your existing files stay as they were. Writing happens one directory at a time, so a failure during writing can leave some projects updated and others not.

The same SQL, configuration, and schema always produce the same output. To compare that output with the existing files without writing anything, run plainsql check.