Strata (models)
Strata is Rocks’ object-relational mapper. Each model is a class that inherits from
Strata::Record and maps to a database table. Strata is built on Entity Framework Core,
so you get its database providers and its query translation, without its fondness for
the word “Async”.
Models
Section titled “Models”class Post < Strata::Record @[Required] @[Length(max: 120)] property title: String
property body: String property published: Bool = false
@[HasMany(Comment)] getter comments: Strata::Relation[Comment]
def excerpt: String body.length > 100 ? body.substring(0, 100) + "…" : body endendBy convention, Post maps to the posts table, title to the title column, and
every model gets id, created_at and updated_at. Override the conventions with
@[Table("...")] and @[Column("...")] when your schema predates your good taste.
Queries
Section titled “Queries”Queries are built by chaining, and only run when you ask for results:
recent = Post.where(published: true).order(:created_at, :desc).limit(10)
recent.all # Array[Post]recent.first # Post?recent.count # Intrecent.any? # BoolColumn names are checked against the model at compile time.
Post.where(pubilshed: true) doesn’t compile, saving you from a query that would
politely return nothing forever.
Finding one record
Section titled “Finding one record”Post.find(42) # Post? (nil if there's no such post)Post.find!(42) # Post, or raises RecordNotFoundExceptionSaving
Section titled “Saving”post = Post.new(title: "Hello", body: "First!")post.save # Bool: false if validation failedpost.save! # Void, or raises RecordInvalidException
post.errors # Array[ValidationError], for the false caseValidations are attributes on properties: @[Required], @[Length(min:, max:)],
@[Format(/regex/)], @[Unique] and @[Range(min:, max:)].
Associations
Section titled “Associations”| Attribute | Means |
|---|---|
@[HasMany(Comment)] |
This record has many comments |
@[HasOne(Profile)] |
This record has one profile |
@[BelongsTo(Post)] |
This record has a post_id and a post |
post.comments.where(approved: true).countcomment.post.titleMigrations
Section titled “Migrations”Migrations change your schema gradually, one layer at a time. Like erosion, but on purpose.
rocks generate migration CreatePostsclass CreatePosts < Strata::Migration def up create_table :posts do string :title, null: false text :body boolean :published, default: false timestamps end end
def down drop_table :posts endendrocks db migrate # apply pending migrationsrocks db rollback # undo the last onecreate_table’s block is a receiver block
whose self is a Strata::TableBuilder, so column types are methods and misspelling
string is a compile error.