Migration files usually live undermigrate/migrations.
You can either create these files manually, or usefrizzante generate migrationwhich will create a migration file using the local date, time and timezone.
Each migration file has a-- migrate: upand a-- migrate: downsections, which are executed respectively when a migration runs forwards and backwards.
-- migration: down
drop table if exists sessions;
drop table if exists todos;
-- migration: up
create table if not exists sessions(
id varchar(36) primary key,
created_at datetime not null,
updated_at datetime not null,
roles varchar(256) not null default 'user',
user_id varchar(256) not null default 'guest',
error text not null default ''
);
create table if not exists todos(
id varchar(36) primary key,
session_id varchar(36) not null,
description varchar(256) not null default '',
checked int not null default 0,
foreign key (session_id) references sessions(id)
);
Note
The order in which these sections are defined is irrelevant.
You can automate initialization and migration of your database by defining a./migrateprogram at the root of your project.
package main
import (
"database/sql"
"embed"
"log"
"main/lib/databases"
)
//go:embed migrations
var efs embed.FS
func main() {
// no need to close database connection,
// this program runs once and dies immediately
var err error
var database *sql.DB
if database, _, err = databases.Connect(); err != nil {
log.Fatal(err)
}
if err = databases.Migrate(databases.MigrateOptions{
Efs: efs,
Database: database,
Offset: "first",
Target: "last",
}); err != nil {
log.Fatal(err)
}
}
Note
Functiondatabases.Connect()will initialize asource.sqlitedatabase file if it doesn't already exist.
Future database solutions will probably not have this feature, this is something that can generally be done
only with sqlite.
Note
Note that this program embeds the migration files.
This will run all migrations from thefirstone to thelastone.
You can also specify a range by indicating the migration names.
package main
import (
"database/sql"
"embed"
"log"
"main/lib/databases"
)
//go:embed migrations
var efs embed.FS
func main() {
// no need to close database connection,
// this program runs once and dies immediately
var err error
var database *sql.DB
if database, _, err = databases.Connect(); err != nil {
log.Fatal(err)
}
if err = databases.Migrate(databases.MigrateOptions{
Efs: efs,
Database: database,
Offset: "2025_01_01T09_16_00+02_00",
Target: "2026_07_17T09_54_35+02_00",
}); err != nil {
log.Fatal(err)
}
}
Caution
File extension and parent directory path must be excluded.