
Red
Experimental migrations: manage versioned schema and data changes with red migration. The API and migration formats may change. See basic usage. Read the migration workflow or follow the Docker workshop.
Take a look at our Documentation: https://fco.github.io/Red/
Red - A WiP ORM for Raku
RECENT HIGHLIGHTS
PostgreSQL users: the Pg driver is no longer bundled with Red. Install the separate Red::Driver::Pg distribution when installing or upgrading:
zef install Red::Driver::Pg
Other recent highlights include:
Queries: opt-in RakuAST compilation, compiled regex filters translated to SQL, and isolated SQL plan caching. See compiled regex filters.
Schema: named, composite and partial indexes, CHECK and PostgreSQL EXCLUDE constraints, and native range/regex helpers. See indexes and constraints and PostgreSQL ranges.
Transactions: nested savepoints and explicit guards with asynchronous work. See transactions and savepoints.
Models and relationships: creation through empty scalar relationships, stable has-one, .^refresh and is handling, plus dirty tracking for in-place collection mutations. See relationship creation, refresh and is handling.
Results and JSON: chainable scalar/container projections, SQL tail/reverse, ResultSeq products and expanded JSON operations.
Performance and reliability: faster hydration and projections, safer concurrent query/class initialization, and fixes for generated getters and formatter handling.
See Changes for the complete list.
EXPERIMENTAL MIGRATIONS
Configure your existing Red models and database in red.rakuconf at the project root. For example, with a model available as lib/MyApp/Task.rakumod:
use lib 'lib';
use Red:api<2>;
use Red::Migration::Configuration;
config {
.models = ['MyApp::Task'];
.drivers = ['SQLite'];
.directory = 'migrations';
.connections = %(
default => { database 'SQLite', :database<development.sqlite> },
);
}
Application queries also use .connections<default> automatically, and schema() returns the configured models:
use lib 'lib';
use Red:api<2>;
use MyApp::Task;
say schema().models.keys;
MyApp::Task.^create(:title<Example>);
Run from the directory containing red.rakuconf. Loading a schema does not open the database; lazy connections are reused per thread on first database use. Explicit $*RED-DB and red-defaults take precedence. Tests can replace the configuration with set-config from Red::Migration::Configuration. Supplying models explicitly to schema(...) keeps the existing behavior.
Run these commands from the project root:
red migration prepare initial # Generate SQL and schema snapshots; do not change the database.
red migration apply --test # Validate the history in a disposable database.
red migration apply # Apply pending versions to the configured default connection.
red migration status # Show database initialization and migration states.
red migration init-tests # Create t/migrations.rakutest for your project's test suite.
Review the generated SQL before applying it and commit the migrations/ directory. After changing your models, run red migration prepare change-name, validate and apply again. Preparation compares models with the last prepared snapshot, initially an empty schema; it does not automatically adopt an existing database. PostgreSQL and MySQL are also supported through their separate driver distributions.
For changes requiring data preparation, use red migration create change-name, edit the generated migration.raku, then run red migration prepare change-name. Data updates and final constraints execute synchronously during apply. Rollback uses red migration rollback when the version has an available inverse; it cannot automatically recover overwritten data. Supported changes vary by driver, and SQLite table reconstruction requires manual SQL.
See the migration workflow for data transformations, production connections, rollback, driver backfill and parallel histories, or follow the Docker workshop for a guided deployment exercise.
INSTALL
Install with (you need rakudo 2018.12-94-g495ac7c00 or newer):
zef install Red
PostgreSQL support is provided by a separate distribution. Install it only if you use PostgreSQL:
zef install Red::Driver::Pg
SYNOPSIS
use Red:api<2>;
model Person {...}
model Post is rw {
has Int $.id is serial;
has Int $!author-id is referencing( *.id, :model<Person> );
has Str $.title is column{ :unique };
has Str $.body is column;
has Person $.author is relationship{ .author-id };
has Bool $.deleted is column = False;
has DateTime $.created is column .= now;
has Set $.tags is column{
:type<string>,
:deflate{ .keys.join: "," },
:inflate{ set(.split: ",") }
} = set();
method delete { $!deleted = True; self.^save }
}
model Person is rw {
has Int $.id is serial;
has Str $.name is column;
has Post @.posts is relationship{ .author-id };
method active-posts { @!posts.grep: not *.deleted }
}
my $*RED-DB = database "SQLite";
Person.^create-table;
-- Equivalent to the following query:
CREATE TABLE person(
id integer NOT NULL primary key
AUTOINCREMENT,
name varchar(255) NOT NULL
)
Post.^create-table;
-- Equivalent to the following query:
CREATE TABLE post(
id integer NOT NULL primary key AUTOINCREMENT,
author_id integer NULL references person(id),
title varchar(255) NOT NULL,
body varchar(255) NOT NULL,
deleted integer NOT NULL,
created varchar(32) NOT NULL,
tags varchar(255) NOT NULL,
UNIQUE (title)
)
my Post $post1 = Post.^load: :42id;
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
post.id = 42
my Post $post1 = Post.^load: 42;
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
post.id = 42
my Post $post1 = Post.^load: :title("my title");
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
post.title = 'my title'
my $person = Person.^create: :name<Fernando>;
-- Equivalent to the following query:
INSERT INTO person(
name
)
VALUES(
?
) RETURNING *
-- BIND: ["Fernando"]
RETURNS:
Person.new(name => "Fernando")
say $person.posts;
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
post.author_id = ?
-- BIND: [1]
say Person.new(:2id)
.active-posts
.grep: { .created > DateTime.now }
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
(
post.author_id = ?
AND (
post.deleted == 0
OR post.deleted IS NULL
)
)
AND post.created > '2019-04-02T22:55:13Z'
-- BIND: [2]
my $now = DateTime.now;
say Person.new(:3id)
.active-posts
.grep: { .created > $now }
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
(
post.author_id = ?
AND (
post.deleted == 0
OR post.deleted IS NULL
)
)
AND post.created > ?
-- BIND: [
-- 3,
-- "2019-04-02T22:55:13Z"
-- ]
Person.^create:
:name<Fernando>,
:posts[
{
:title("My new post"),
:body("A long post")
},
]
;
-- Equivalent to the following query:
INSERT INTO person(
name
)
VALUES(
?
) RETURNING *
-- BIND: ["Fernando"]
INSERT INTO post(
created,
title,
author_id,
tags,
deleted,
body
)
VALUES(
?,
?,
?,
?,
?,
?
) RETURNING *
-- BIND: [
-- "2019-04-02T22:55:13.658596+01:00",
-- "My new post",
-- 1,
-- "",
-- Bool::False,
-- "A long post"
-- ]
my $post = Post.^load: :title("My new post");
-- Equivalent to the following query:
SELECT
post.id,
post.author_id as "author-id",
post.title,
post.body,
post.deleted,
post.created,
post.tags
FROM
post
WHERE
post.title = 'My new post'
-- BIND: []
RETURNS:
Post.new(
title => "My new post",
body => "A long post",
deleted => 0,
created => DateTime.new(
2019,
4,
2,
23,
7,
46.677388,
:timezone(3600)
),
tags => Set.new("")
)
say $post.body;
PRINTS:
A long post
my $author = $post.author;
RETURNS:
Person.new(name => "Fernando")
$author.name = "John Doe";
$author.^save;
-- Equivalent to the following query:
UPDATE person SET
name = 'John Doe'
WHERE id = 1
$author.posts.create:
:title("Second post"),
:body("Another long post");
-- Equivalent to the following query:
INSERT INTO post(
title,
body,
created,
tags,
deleted,
author_id
)
VALUES(
?,
?,
?,
?,
?,
?
) RETURNING *
-- BIND: [
-- "Second post",
-- "Another long post",
-- "2019-04-02T23:28:09.346442+01:00",
-- "",
-- Bool::False,
-- 1
-- ]
$author.posts.elems;
-- Equivalent to the following query:
SELECT
count(*) as "data_1"
FROM
post
WHERE
post.author_id = ?
-- BIND: [1]
RETURNS:
2
DESCRIPTION
Red is a WiP ORM for Raku.
traits
is column
is column{}
is id
is id{}
is serial
is referencing{}
is relationship{}
is table<>
is nullable
is handling
is serial and is column{ :type<serial> } both declare a non-null generated primary key. serial is a portable Red type: each driver chooses its equivalent integer type and identifier generator, including on engines without a native SERIAL type.
features:
relationships
Red will infer relationship data if you use type constraints on your properties.
# Single file e.g. Schema.pm6
model Related { ... }
# belongs to
model MyModel {
has Int $.id is serial;
has Int $!related-id is referencing( *.id, :model<Related> );
has Related $.related is relationship{ .related-id };
}
# has one/has many
model Related {
has Int $.id is serial;
has MyModel @.my-models is relationship{ .related-id };
}
If you want to put your schema into multiple files, you can create an "indirect" relationship, and Red will look up the related models as necessary.
# MyModel.pm6
model MyModel {
has Int $.id is serial;
has Int $!related-id is referencing(:model<Related>, :column<id>);
has $.related is relationship({ .related-id }, :model<Related>);
}
# Related.pm6
model Related {
has Int $.id is serial;
has @.my-models is relationship({ .related-id }, :model<MyModel>);
}
If Red can’t find where your model is defined you can override where it looks with require:
has Int $!related-id is referencing(:model<Related>, :column<id>,
:require<MyApp::Schema::Related>);
creating through a scalar relationship
An empty scalar relationship returns an undefined, false type object carrying the relationship's creation context, rather than Nil. Call .^create on that object to create the related row and fill the foreign key automatically:
my $parent = $child.parent.^create(:name<parent>);
# For a relationship declared with :has-one:
my $profile = $account.profile.^create(:description<profile>);
For a belongs-to relationship, Red saves the foreign key on the existing source row. For :has-one