# Active Record > A Rails-inspired Active Record for Cloudflare Workers, on D1 or Postgres. Active Record is `@forestfuture/active-record` on npm, a Rails-inspired Active Record for Cloudflare Workers, with an adapter for each database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres. Install its agent skill, with the rules for writing Active Record code, using `npx skills add forestfuture/active-record`. Every behavior the tests prove is in the [behavior contract](https://github.com/forestfuture/active-record/blob/main/docs/contract.md). The installed package ships this guide for its own version at `node_modules/@forestfuture/active-record/llms-full.txt`. ## Docs - [Active Record for Cloudflare Workers](https://active-record.forestfuture.dev/): Active Record for Cloudflare Workers: typed Models, validations, callbacks, associations, and composable queries, on D1 or Postgres through Hyperdrive. ## Introduction - [Getting started](https://active-record.forestfuture.dev/getting-started): Get started with Active Record on Cloudflare D1: install it, generate two related Models and their tables, add validations, and use them in a Worker. - [Coming from Rails](https://active-record.forestfuture.dev/coming-from-rails): Active Record for Cloudflare Workers compared with Rails’ Active Record: what carries over, and what differs, from camelCase attributes to OrThrow methods. - [AI agents](https://active-record.forestfuture.dev/ai-agents): Give coding agents Active Record’s guide and rules: llms.txt, llms-full.txt, every page as Markdown, the agent skill, and a pointer in AGENTS.md or CLAUDE.md. ## Basics - [Models](https://active-record.forestfuture.dev/models): Define Active Record Models on ApplicationRecord, with attributes from your migrations, overrides, table names, building records, permit, ids, and timestamps. - [Attribute types](https://active-record.forestfuture.dev/attribute-types): Active Record attribute types, from string, decimal, and datetime to json and binary, how each is stored on D1 and Postgres, and how values are cast. - [Enums](https://active-record.forestfuture.dev/enums): Active Record enums: declare an attribute’s names as a list or with stored values, use their predicates, setters, and scopes, and read enums from CHECKs. - [Change tracking](https://active-record.forestfuture.dev/change-tracking): Track Active Record changes: changed, attributeWas, and isAttributeChanged before a save, savedChangeTo after it, and restoreAttributes to undo unsaved changes. - [Serialization](https://active-record.forestfuture.dev/serialization): Serialize Active Record records with toJSON and Response.json, hide attributes from responses, filter secrets from logs, and print records and Relations. - [Passwords and tokens](https://active-record.forestfuture.dev/passwords-and-tokens): Keep Active Record passwords as salted digests with securePassword, check them with authenticate or authenticateBy, reset them with a signed token, and make random tokens, signed ids, and tokens for a purpose. - [Querying](https://active-record.forestfuture.dev/querying): Build Active Record queries as lazy Relations, and run them with find, findBy, first, count, pluck, and exists, with links to conditions, joins, and paging. - [Conditions](https://active-record.forestfuture.dev/conditions): Filter Active Record queries with where, whereNot, or, comparisons like gte and between, sql fragments, rewhere, unscope, and excluding, on D1 or Postgres. - [Ordering and pagination](https://active-record.forestfuture.dev/ordering-and-pagination): Sort Active Record queries with order, reorder, and inOrderOf, place NULLs the same on D1 and Postgres, and paginate with a page total or without a count. - [Calculations](https://active-record.forestfuture.dev/calculations): Count, sum, average, minimum, and maximum in Active Record without loading records, per group with group and having, and exact money sums on D1. - [Scopes](https://active-record.forestfuture.dev/scopes): Define named scopes on Active Record Models, call them on any Relation, narrow every query with a default scope, and leave it out with unscoped(). - [Joins](https://active-record.forestfuture.dev/joins): Join Active Record associations with joins and leftJoins, get each record once with distinct, and filter or sort by a joined Model’s attributes with merge. - [Batch iteration](https://active-record.forestfuture.dev/batch-iteration): Work through large tables with Active Record’s findEach, findInBatches, and inBatches, a batch of records at a time, within D1’s per-invocation query limit. - [Raw statements](https://active-record.forestfuture.dev/raw-statements): Send your own SQL beside Active Record: typeForAttribute’s serialize, deserialize, and cast convert values the way an attribute stores them, on D1 or Postgres. - [Persistence](https://active-record.forestfuture.dev/persistence): Save, create, update, and destroy Active Record records, catch RecordInvalid from the OrThrow variants, findOrCreateBy, increment, touch, and reload. - [Validations](https://active-record.forestfuture.dev/validations): Validate Active Record records before saving: presence, length, format, uniqueness, numericality, and more, with contexts, custom rules, and error messages. - [Callbacks](https://active-record.forestfuture.dev/callbacks): Run code at points in an Active Record record’s lifecycle: before validation, around a save, after commit, and abort() to stop a save or destroy. - [Associations](https://active-record.forestfuture.dev/associations): Connect Active Record Models with belongsTo, hasMany, and hasOne: reading and setting records, polymorphic associations, foreign keys, scopes, and dependents. - [Preloading](https://active-record.forestfuture.dev/preloading): Preload (eager load) Active Record associations with includes: one query per association, the whole tree in one D1 round trip, nested and polymorphic includes. - [Autosaving](https://active-record.forestfuture.dev/autosaving): Autosave Active Record associations: create records through a hasMany, save a graph with its owner in one batch, save changed records, and markForDestruction. - [Counter caches](https://active-record.forestfuture.dev/counter-caches): Active Record counter caches: keep a hasMany’s count on its owner with counterCache, read it with size(), reset it with resetCounters, and backfill one. - [Touching](https://active-record.forestfuture.dev/touching): Touch Active Record associations: set updatedAt on the record a belongsTo or hasOne reaches, name other attributes, and turn touches off with noTouching. - [Through associations](https://active-record.forestfuture.dev/through-associations): Many-to-many associations in Active Record: hasMany and hasOne through a join Model, with source, preloading, push, build, create, and removing join records. - [Bulk writes and batches](https://active-record.forestfuture.dev/batches): Write many rows in one SQL statement with insertAll, upsert, updateAll, and deleteAll, and send writes in an atomic batch on D1 or one Postgres transaction. - [Connections](https://active-record.forestfuture.dev/connecting): How Active Record queries find their database: the Model’s binding, withDatabase for one request, connect(env.DB), and why new User() throws NoDatabase. - [Command line](https://active-record.forestfuture.dev/command-line): The active-record command: initialize a project, generate the schema from your migrations, write migrations and Models, open a console, and apply migrations. - [Errors](https://active-record.forestfuture.dev/errors): Every error Active Record throws, from RecordNotFound and RecordInvalid to constraint errors, how to catch them with ActiveRecordError, and when each is thrown. ## Adapters - [D1](https://active-record.forestfuture.dev/d1): Use Active Record on Cloudflare D1: install the adapter, bind a database, read replicas with Sessions, one round trip per page, and what differs on D1. - [PostgreSQL](https://active-record.forestfuture.dev/postgresql): Use Active Record on Postgres: install pg, connect through Hyperdrive or a Pool, and what works differently from D1, from transactions to sorting. ## How To - [Generators](https://active-record.forestfuture.dev/generators): Generate a table’s migration and its Active Record Model from a short description, write columns and references, and keep the generated schema current. - [Console](https://active-record.forestfuture.dev/console): Open an Active Record console on your local or remote database with your Models loaded, to try queries and fix records by hand, and see where its history lives. - [Schema changes](https://active-record.forestfuture.dev/change-a-table): Change a D1 or Postgres table with Active Record migrations: add, rename, and remove columns, deploy them in the right order, and change a column’s type. - [Existing databases](https://active-record.forestfuture.dev/adopt-a-database): Use Active Record with an existing D1 database managed by Drizzle or Prisma, or with no migrations at all, and fix columns of the wrong type with overrides. - [Shared behavior](https://active-record.forestfuture.dev/shared-behavior): Share methods, callbacks, and scopes across every Active Record Model by writing them once on your app’s ApplicationRecord base class. - [Custom types](https://active-record.forestfuture.dev/custom-types): Define a custom Active Record attribute type, such as money in cents or a list of sizes, stored in its column as a built-in type, and use it on any Model. - [Untrusted input](https://active-record.forestfuture.dev/untrusted-input): Handle untrusted input with Active Record: permit only the fields you want, return a 400 for values that can’t be cast, and check values before querying. - [Logging](https://active-record.forestfuture.dev/logging): Log the SQL your Cloudflare Worker sends with an Active Record onQuery listener: every query app-wide, one request’s queries, Workers Logs, and Server-Timing. - [Read replicas](https://active-record.forestfuture.dev/read-your-own-writes): Keep each user’s reads at least as new as their own writes with D1 read replication, using an Active Record Session for each request and a bookmark cookie. - [Testing](https://active-record.forestfuture.dev/testing): Test Active Record Models and your Cloudflare Worker against a real D1 database with Vitest and Miniflare, with your migrations applied to each test database. - [Multiple databases](https://active-record.forestfuture.dev/several-databases): Use several databases from one Cloudflare Worker with Active Record, on D1, Postgres, or both: a schema and base class for each, Sessions, and tests. - [Moving to Postgres](https://active-record.forestfuture.dev/move-to-postgres): Move an Active Record app from Cloudflare D1 to Postgres with Hyperdrive: rewrite the migrations, regenerate the schema, copy the data, and keep your Models. - [Upgrading](https://active-record.forestfuture.dev/upgrading): Upgrade an Active Record app one release at a time, from d1-record 0.5 to Active Record 0.8, with the code and schema changes each release needs. ## Background - [Database resolution](https://active-record.forestfuture.dev/query-databases): How an Active Record query finds its database in a Cloudflare Worker: the Model’s binding, the request’s database, or one you pass explicitly. - [Schema and ApplicationRecord](https://active-record.forestfuture.dev/schema): Why Active Record generates a Model’s attributes from your migrations when you run active-record schema, and how the generated schema compares to Rails’. - [Security](https://active-record.forestfuture.dev/security): What Active Record protects against, from SQL injection to prototype pollution, what it leaves to your app, the tests behind each guarantee, and its reviews. ## Agent skills - [active-record](https://active-record.forestfuture.dev/.well-known/agent-skills/active-record/SKILL.md): Active Record (`@forestfuture/active-record`, with its D1 and PostgreSQL adapters as its `/d1` and `/postgresql` entries), a Rails-style Active Record for Cloudflare Workers. Use when writing code with the package, or deciding how to model D1 or Postgres data in a Worker. ## Agent resources - [llms-full.txt](https://active-record.forestfuture.dev/llms-full.txt): The full Markdown of every page in one file. - [Page Markdown](https://active-record.forestfuture.dev/index.md): Append `.md` to any page URL to fetch that page as raw Markdown. - [JSON API](https://active-record.forestfuture.dev/api/docs/pages.json): Page index of the JSON docs API; each entry links the page's JSON and Markdown forms. Described by the OpenAPI document at https://active-record.forestfuture.dev/openapi.json. - [Agent skills](https://active-record.forestfuture.dev/.well-known/agent-skills/index.json): Agent Skills discovery index of the skills this site publishes. - [API catalog](https://active-record.forestfuture.dev/.well-known/api-catalog): RFC 9727 linkset of the APIs documented here. - [AI catalog](https://active-record.forestfuture.dev/.well-known/ai-catalog.json): ARD manifest of the agent-facing resources on this site (MCP server, skills, APIs). - [agent-readability.json](https://active-record.forestfuture.dev/agent-readability.json): Manifest of every agent-facing artifact on this site. - [Sitemap](https://active-record.forestfuture.dev/sitemap.xml): Every indexable page URL with its last-modified date.