ORM::ActiveRecord

Every page of the ORM::ActiveRecord manual, in reading order.

  • Overview ORM::ActiveRecord is an object-relational mapping module for Raku supporting PostgreSQL, MySQL, and SQLite. The manual covers models, queries, validations, and migrations.
  • Conventions Naming conventions for ORM::ActiveRecord methods, such as -bang suffixes and is- predicates, with reference tables mapping common operations to their method names.
  • Adapters Configuring PostgreSQL, MySQL, and SQLite through DATABASE_URL or config/application.json, with connects-to, multiple databases, pooling, query cache, and advisory locks.
  • Migrations Writing migrations with change or up and down methods: tables, columns, indexes, foreign keys, constraints, PostgreSQL enums, reversibility, and the active-record command.
  • Generators The active-record generate and destroy commands for scaffolding models, migrations, scopes, and validators, with name:type field specs.
  • Database tasks The active-record db:* tasks for creating, dropping, migrating, and seeding databases, checking migration status, preparing the test database, and dumping and loading the schema.
  • Runtime tasks The active-record runtime subcommands: console for a Raku REPL, runner for scripts or inline code, dbconsole for a database client, and notes and stats for the source tree.
  • Info Model associations: has-one, has-many, belongs-to, through and polymorphic associations, scopes, inverse-of, dependent, counter cache, touch, autosave, and strict loading.
  • Attribute types Per-attribute types with cast, deserialize, and serialize hooks: custom types, serialized columns, store accessors, defaults, overriding column types, and virtual attributes.
  • Enums Declaring enums that map a column's stored integer or string values to symbolic names, with predicates, bang setters, class scopes, and state machines.
  • Normalization Declaring attribute normalizers with normalizes, which transform values before validation and save, across multiple attributes and in query lookups.
  • Serialization Record identity and serialization methods: to-param, to-key, cache keys, serializable-hash, as-json, to-json, inspect, attribute-for-inspect, and filter-attribute.
  • Inheritance Single-table inheritance: storing a class hierarchy in one table with a type column, how subclass reads behave, and inheritance-column, abstract-class, and sti-name.
  • Finders Class-level finders: find, find-by, first, last, take, sole, find-sole-by, find-or-create-by, find-or-initialize-by, create-with, pick, exists, and composite primary keys.
  • Relations Lazy, chainable relations built with where, order, limit, offset, and select, the methods that run them, plus none, pluck, ids, count, exists, and eager loading.
  • Queries Relation filtering methods: where shorthands, LIKE predicates, where.not, JSON predicates, where.missing, where.associated, excluding, or, and, merge, rewhere, and unscope.
  • Joins Adding SQL JOIN clauses with joins and left-outer-joins by association name, nested associations, or raw SQL, plus filtering on joined tables, references, and distinct.
  • Aggregation Set-shaping relation methods: distinct, sum, average, minimum, maximum, calculate, count, group and having, pluck of SQL expressions, from, readonly, and extending.
  • Batching Iterating large tables in primary-key order with find-each, find-in-batches, and in-batches, each with a configurable batch size and any chained where filter.
  • Async queries The -async variants of read methods, such as load-async, count-async, and pluck-async, which run a query on a worker thread and return a Raku Promise.
  • Raw SQL & CTEs Raw SQL and Common Table Expressions with find-by-sql, select-all, with, and with-recursive, plus annotate, optimizer-hints, and to-sql.
  • Inspection Methods for inspecting a relation without running it: to-sql, explain, relation predicates, and cache-key, cache-version, and cache-key-with-version.
  • Persistence Saving, updating, and destroying records with quiet and -bang variants, plus dirty tracking, targeted writes, bulk operations such as upsert-all, and automatic timestamps.
  • Callbacks Model life cycle callbacks for save, create, update, destroy, validation, find, and touch, with around callbacks, :if and :unless conditions, halting, and observers.
  • Transactions Transactions with DB.shared.transaction: rollback with X::Rollback, nested savepoints, isolation levels, transactional callbacks, optimistic and pessimistic locking, and write guards.
  • Soft deletes Soft deletes with soft-deletes: discard and undiscard through a timestamp column, the kept, discarded, and with-discarded scopes, bulk operations, and discard callbacks.
  • Data Built-in model validations: acceptance, confirmation, exclusion, format, inclusion, length, numericality, comparison, presence, uniqueness, and validates associated.
  • Conditionals Running validations conditionally with if, unless, and on, including create and update contexts, custom contexts, sticky context, and re-running validations.
  • Options Options shared by every validator: allow-nil, allow-blank, strict, and as, plus case-sensitive and conditions for uniqueness validations.
  • Messages & locales Validation message templates: the tokens substituted into messages, per-locale message registration, lookup order, and switching locale for a block.
  • Tokens & secure data Password and token helpers: has-secure-password with authenticate, has-secure-token, signed ids, and purpose tokens from generates-token-for that self-invalidate.
  • Encryption Encrypting column values at rest with encrypts, covering encryption keys, deterministic versus random encryption, key rotation, and backfilling existing rows.
  • Through associations A walkthrough of :through associations using users, subscriptions, and magazines: setup, reading through the join model, eager loading, and has-one :through.
  • Polymorphic associations Polymorphic belongs-to associations that point at more than one parent type: setup, assigning different parent types, the inverse collection, optional parents, and eager loading.
  • Single-table inheritance A walkthrough of single-table inheritance with a vehicles table: setup, saving and reading back subclasses, changing a row's class, and tuning the type column and names.
  • Custom validators Writing custom validators as a class with a validate method attached through validates-with, or as inline per-attribute checks with validates-each.
  • Transactions and savepoints A walkthrough of transactions: committing a block, rolling back, nested savepoints with :requires-new, isolation levels, and after-commit and after-rollback callbacks.
  • Eager loading Avoiding N+1 queries with preload, eager-load, and includes, covering how each one fetches associations, loading several associations, and nested eager loading.
  • Errors Typed exceptions such as X::RecordNotFound, X::RecordInvalid, and X::ReadOnlyRecord, and the per-record errors collection for adding, reading, and merging validation errors.
  • Reflection Class-level introspection of associations, columns, primary keys, and enums, with reflect-on-association, column-names, and build-stubbed for stubbed records.
  • Logging Logging through Log::Async: the default stdout handler, ERROR-level file logging with ORM_LOG_FILE, structured configuration, and SQL logs with timing and bound values.
  • Instrumentation Subscribing to query, model load, and transaction events with Notifications, logging queries with timing through LogSubscriber, and tagging SQL with QueryLogs.
  • Tests Running the ORM::ActiveRecord test suite: prove6 tests and behave specs against PostgreSQL, MySQL, or SQLite, parallel spec runs, and adapter-aware test skipping.
  • Test helpers Test helpers in ORM::ActiveRecord::Testing: transactional tests rolled back at teardown, YAML fixtures with interpolation and references, and a database cleaner.