Migrations are files that provide syntax for generating Data Definition Language for the ROM::SQL adapter. They are generated by the Hanami command line, and may be written in Ruby syntax (provided by the Sequel library), or plain SQL.
Migration filenames are defined in snake case and prefaced by a numeric timestamp of when they were created. This allows for roughly sequential execution without the likelihood of collisions from sequential integers when multiple people are creating them at the same time.
SQL migrations may be generated by passing the --sql option to the generator:
$ bundle exec hanami generate migration add_published_at_to_posts --sql
They are located in the config/db/migrate directory.
$ tree config/db/migrate
config/db/migrate
├── 20240717170227_create_posts.rb
└── 20240717170318_add_published_at_to_posts.sql
Direction
Migration files are bi-directional, they define schema changes forward and backward, or up and down in Sequel’s syntax. This is important, in case your migration changes cause a problem you will want to roll them back as quickly as possible, and requiring a fresh migration to do this may take too much time.
ROM::SQL.migration do
change do
create_table :users do
primary_key :id
foreign_key :account_id, :accounts, on_delete: :cascade, null: false
column :given_name, String, null: false
column :family_name, String, null: false
column :email, "citext", null: false
end
end
end
In the example above, we used the change method to define our migration. This is written in the style of an up migration, and the down version is inferred by Sequel.
Sometimes, this cannot be automatically inferred. You will need to provide explicit up and down definitions in this case.
ROM::SQL.migration do
up do
alter_table :users do
add_unique_constraint [:email], name: :users_email_uniq
end
end
down do
alter_table :users do
drop_constraint :users_email_uniq
end
end
end
SQL migrations use a special comment parser to divide the file into up and down sections. Parsed comments always begin with a -- @migrate stanza. Normal comments pass through untouched.
SQL migrations are always bi-directional, because there is no translation step. They always begin with an up section, but down is optional.
-- @migrate up
-- @migrate begin
users ADD CONSTRAINT users_email_uniq UNIQUE (email);
-- @migrate end
-- @migrate down
-- @migrate begin
users DROP CONSTRAINT users_email_uniq;
-- @migrate end
Warning
Order is significant. If down comes first, or up is missing, it will raise ROM::SQL::SQLParseError.
Transactions
The majority of migrations are run within a transaction, so that DDL errors trigger a rollback and don’t leave you in a partial state. But certain operations don’t support running inside a transaction.
Within a migration block, no_transaction tells the migrator to run the migration without first starting a transaction.
ROM::SQL.migration do
no_transaction
up do
alter_table :users do
add_index :email, concurrently: true
end
end
down do
alter_table :users do
drop_index :email, concurrently: true
end
end
end
In SQL, this is done by adding a pragma to the top of the file.
-- @migrate transaction=false
-- @migrate up
-- @migrate begin
email ON users (email);
-- @migrate end
-- @migrate down
-- @migrate begin
users CONCURRENTLY email;
-- @migrate end
Syntax
Sequel migration syntax provides some flexibility in how you may choose to represent your table columns.
create_table :users do
# column method, explicit SQL type
column :email, "varchar(255)", null: false
# column method, inferred SQL type: varchar(255)
column :email, String, null: false
# helper method, no inference, SQL type: text
text :email, null: false
# Ruby type method, inferred SQL type: varchar(255)
String :email, null: false
end
Sequel also provides Ruby syntax for defining logical pieces, such as constraints
create_table :users do
primary_key :id
column :name, String, null: false
constraint(:name_min_length) { char_length(name) > 2 }
end
Read more at Sequel: Schema modification methods
A disadvantage of the Ruby syntax is that the more complicated schema changes tend to stray from how the SQL would be written, which makes it unintuitive. This is the main reason why Hanami supports SQL syntax: as an escape-hatch for complicated schema that is difficult to express in Ruby.
-- @migrate up
-- @migrate begin
BEFORE INSERT OR UPDATE ON public.posts
FOR EACH ROW
WHEN (
OLD.title IS DISTINCT FROM NEW.title OR
OLD.content IS DISTINCT FROM NEW.content
)
EXECUTE PROCEDURE tsvector_update_trigger(search_tsvector, 'pg_catalog.english', title, content)
-- @migrate end
-- @migrate down
-- @migrate begin
posts_tsvector_update ON public.posts
-- @migrate end
In this example, we’re storing vector information for PostgreSQL’s text search in a column, automatically built by a trigger.
Statement Splitting
SQL migrations support multiple strategies for splitting statements. What we have shown so far is the default approach of sending the entire begin-end section as a single statement.
Using the split=semicolon setting, each semicolon marks the transition to a new statement. Using split=line splits statements on the newline character. Each of these migration directions will produce three separate statements:
-- @migrate up
-- @migrate begin split=semicolon
(
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
author_id bigint NOT NULL REFERENCES authors (id) ON DELETE CASCADE,
title text NOT NULL,
published_at date NOT NULL DEFAULT CURRENT_DATE,
search_tsvector tsvector GENERATED ALWAYS AS (
to_tsvector('english', title)
) STORED
);
ON books USING GIN (search_tsvector);
ON books (published_at);
-- @migrate end
-- @migrate down
-- @migrate begin split=line
books_published_at_idx
books_search_idx
books
-- @migrate end
Semicolons are harmless in split=line, but they are optional in that case.
Warning
If you are using dollar-quoted strings ($$ or $tag$) in your SQL, split=semicolon will not account for this if you have semicolons inside the quoted section. You must use the default strategy, which sends the entire section as one statement.
Each migration direction may have multiple begin-end sections, each with their own split strategy.
-- @migrate up
-- @migrate begin split=semicolon
authors ADD COLUMN search_tsvector tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(full_name, ''))) STORED;
books ADD COLUMN search_tsvector tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(title, ''))) STORED;
-- @migrate end
-- @migrate begin
(p_query text)
RETURNS TABLE (
book_id bigint,
title text,
author_name text,
rank real
)
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_tsquery tsquery := websearch_to_tsquery('english', p_query);
BEGIN
RETURN QUERY
SELECT
b.id,
b.title,
a.name,
ts_rank(b.search_tsvector || a.search_tsvector, v_tsquery) AS rank
FROM books b
JOIN authors a ON a.id = b.author_id
WHERE (b.search_tsvector || a.search_tsvector) @@ v_tsquery
ORDER BY rank DESC;
END;
$$;
-- @migrate end
-- @migrate down
-- @migrate begin split=line
search_books(text)
books DROP COLUMN search_tsvector
authors DROP COLUMN search_tsvector
-- @migrate end
Environment Variables
If you need to inject data into your migration template, you can use ENV substitution. This is enabled using the env pragma.
-- @migrate env=true
-- @migrate up
-- @migrate begin
CREATE ROLE hanami LOGIN PASSWORD '${DBPASSWD}' CREATEDB;
-- @migrate end
-- @migrate down
-- @migrate begin
DROP ROLE hanami;
-- @end
This will replace the exact string ${DBPASSWD} with the contents of ENV["DBPASSWD"] at runtime. You are responsible for ensuring that it is quoted correctly.
Warning
This will raise ROM::SQL::SQLEnvError if the environment variable is not set.
Database Structure
When adding migrations to your project, it’s useful to maintain a record of what the current state of your database structure was at the time.
This serves three purposes:
- Spot-check your schema changes to ensure you’re doing what you intended
- Provide a simple way to connect the structure of your database to a specific code change
- A blank-slate for setting up a development or test database without running all migrations sequentially
Hanami provides this in the form of config/db/structure.sql. The choice of using plain SQL to reflect your DB structure gives you maximum flexibility in using the most powerful features of your database.