# Arbor > Arbor: an Active Record ORM for TypeScript on Cloudflare D1 and PostgreSQL, built for Cloudflare Workers. Arbor ORM is `@forestfuture/arbor` on npm, an Active Record ORM for TypeScript on Cloudflare D1 and PostgreSQL, built for Cloudflare Workers, with an adapter for each database inside it: `@forestfuture/arbor/d1` for D1, and `@forestfuture/arbor/postgresql` for Postgres. Install its agent skill, with the rules for writing Arbor code, using `npx skills add forestfuture/arbor`. Every behavior the tests prove is in the [behavior contract](https://github.com/forestfuture/arbor/blob/main/docs/contract.md). The installed package ships this guide for its own version at `node_modules/@forestfuture/arbor/llms-full.txt`. ## Docs - [An Active Record ORM for TypeScript on Cloudflare D1 and PostgreSQL](https://arbor.forestfuture.dev/): Arbor, an Active Record ORM for TypeScript on Cloudflare Workers: typed Models, validations, callbacks, associations, and composable queries, on D1 or Postgres through Hyperdrive. ## Introduction - [Getting started](https://arbor.forestfuture.dev/getting-started): Get started with Arbor on Cloudflare D1: install it, generate two related Models and their tables, add validations, and use them in a Worker. - [Coming from Rails](https://arbor.forestfuture.dev/coming-from-rails): Arbor compared with Rails’ Active Record: what carries over, and what differs, from camelCase attributes to OrThrow methods. - [AI agents](https://arbor.forestfuture.dev/ai-agents): Give coding agents Arbor’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://arbor.forestfuture.dev/models): Define Arbor Models on ApplicationRecord, with attributes from your migrations, overrides, table names, building records, permit, ids, and timestamps. - [Attribute types](https://arbor.forestfuture.dev/attribute-types): Arbor 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://arbor.forestfuture.dev/enums): Arbor 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://arbor.forestfuture.dev/change-tracking): Track Arbor changes: changed, attributeWas, and isAttributeChanged before a save, savedChangeTo after it, and restoreAttributes to undo unsaved changes. - [Serialization](https://arbor.forestfuture.dev/serialization): Serialize Arbor records with toJSON and Response.json, hide attributes from responses, filter secrets from logs, and print records and Relations. - [Passwords and tokens](https://arbor.forestfuture.dev/passwords-and-tokens): Keep Arbor 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://arbor.forestfuture.dev/querying): Build Arbor queries as lazy Relations, and run them with find, findBy, first, count, pluck, and exists, with links to conditions, joins, and paging. - [Conditions](https://arbor.forestfuture.dev/conditions): Filter Arbor queries with where, whereNot, or, comparisons like gte and between, sql fragments, rewhere, unscope, and excluding, on D1 or Postgres. - [Ordering and pagination](https://arbor.forestfuture.dev/ordering-and-pagination): Sort Arbor 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://arbor.forestfuture.dev/calculations): Count, sum, average, minimum, and maximum in Arbor without loading records, per group with group and having, and exact money sums on D1. - [Scopes](https://arbor.forestfuture.dev/scopes): Define named scopes on Arbor Models, call them on any Relation, narrow every query with a default scope, and leave it out with unscoped(). - [Joins](https://arbor.forestfuture.dev/joins): Join Arbor 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://arbor.forestfuture.dev/batch-iteration): Work through large tables with Arbor’s findEach, findInBatches, and inBatches, a batch of records at a time, within D1’s per-invocation query limit. - [Raw statements](https://arbor.forestfuture.dev/raw-statements): Send your own SQL beside Arbor: typeForAttribute’s serialize, deserialize, and cast convert values the way an attribute stores them, on D1 or Postgres. - [Persistence](https://arbor.forestfuture.dev/persistence): Save, create, update, and destroy Arbor records, catch RecordInvalid from the OrThrow variants, findOrCreateBy, increment, touch, and reload. - [Validations](https://arbor.forestfuture.dev/validations): Validate Arbor records before saving: presence, length, format, uniqueness, numericality, and more, with contexts, custom rules, and error messages. - [Callbacks](https://arbor.forestfuture.dev/callbacks): Run code at points in an Arbor record’s lifecycle: before validation, around a save, after commit, and abort() to stop a save or destroy. - [Associations](https://arbor.forestfuture.dev/associations): Connect Arbor Models with belongsTo, hasMany, and hasOne: reading and setting records, polymorphic associations, foreign keys, scopes, and dependents. - [Preloading](https://arbor.forestfuture.dev/preloading): Preload (eager load) Arbor associations with includes: one query per association, the whole tree in one D1 round trip, nested and polymorphic includes. - [Autosaving](https://arbor.forestfuture.dev/autosaving): Autosave Arbor associations: create records through a hasMany, save a graph with its owner in one batch, save changed records, and markForDestruction. - [Counter caches](https://arbor.forestfuture.dev/counter-caches): Arbor 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://arbor.forestfuture.dev/touching): Touch Arbor associations: set updatedAt on the record a belongsTo or hasOne reaches, name other attributes, and turn touches off with noTouching. - [Optimistic locking](https://arbor.forestfuture.dev/optimistic-locking): Optimistic locking in Arbor: a lock_version column checked by every save, destroy, and touch, StaleRecord for a stale copy, version fields in forms, and retrying with reload. - [Read-only records](https://arbor.forestfuture.dev/read-only): Read-only records and attributes in Arbor: readonly() Relations, markReadonly(), ReadonlyRecord for a refused save or destroy, and readonly attributes set only on create. - [Through associations](https://arbor.forestfuture.dev/through-associations): Many-to-many associations in Arbor: hasMany and hasOne through a join Model, with source, preloading, push, build, create, and removing join records. - [Bulk writes and batches](https://arbor.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://arbor.forestfuture.dev/connecting): How Arbor queries find their database: the Model’s binding, withDatabase for one request, its cache of identical reads, connect(env.DB), and NoDatabase. - [Command line](https://arbor.forestfuture.dev/command-line): The arbor command: initialize a project, generate the schema from your migrations, write migrations and Models, open a console, and apply migrations. - [Errors](https://arbor.forestfuture.dev/errors): Every error Arbor throws, from RecordNotFound and RecordInvalid to constraint errors, how to catch them with ArborError, and when each is thrown. ## Adapters - [D1](https://arbor.forestfuture.dev/d1): Use Arbor 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://arbor.forestfuture.dev/postgresql): Use Arbor on Postgres: install pg, connect through Hyperdrive or a Pool, and what works differently from D1, from transactions to sorting. ## How To - [Generators](https://arbor.forestfuture.dev/generators): Generate a table’s migration and its Arbor Model from a short description, write columns and references, and keep the generated schema current. - [Console](https://arbor.forestfuture.dev/console): Open an Arbor 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://arbor.forestfuture.dev/change-a-table): Change a D1 or Postgres table with Arbor migrations: add, rename, and remove columns, deploy them in the right order, and change a column’s type. - [Existing databases](https://arbor.forestfuture.dev/adopt-a-database): Use Arbor 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://arbor.forestfuture.dev/shared-behavior): Share methods, callbacks, and scopes across every Arbor Model by writing them once on your app’s ApplicationRecord base class. - [Custom types](https://arbor.forestfuture.dev/custom-types): Define a custom Arbor 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://arbor.forestfuture.dev/untrusted-input): Handle untrusted input with Arbor: permit only the fields you want, return a 400 for values that can’t be cast, and check values before querying. - [Logging](https://arbor.forestfuture.dev/logging): Log the SQL your Cloudflare Worker sends with an Arbor onQuery listener: every query app-wide, one request’s queries, Workers Logs, and Server-Timing. - [Read replicas](https://arbor.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 Arbor Session for each request and a bookmark cookie. - [Testing](https://arbor.forestfuture.dev/testing): Test Arbor 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://arbor.forestfuture.dev/several-databases): Use several databases from one Cloudflare Worker with Arbor, on D1, Postgres, or both: a schema and base class for each, Sessions, and tests. - [Moving to Postgres](https://arbor.forestfuture.dev/move-to-postgres): Move an Arbor app from Cloudflare D1 to Postgres with Hyperdrive: rewrite the migrations, regenerate the schema, copy the data, and keep your Models. - [Upgrading](https://arbor.forestfuture.dev/upgrading): Upgrade an Arbor app one release at a time, from 0.10 to 0.12: the rename to Arbor in 0.11, then uuid attributes on Postgres in 0.12. ## Background - [Database resolution](https://arbor.forestfuture.dev/query-databases): How an Arbor 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://arbor.forestfuture.dev/schema): Why Arbor generates a Model’s attributes from your migrations when you run arbor schema, and how the generated schema compares to Rails’. - [Security](https://arbor.forestfuture.dev/security): What Arbor protects against, from SQL injection to prototype pollution, what it leaves to your app, the tests behind each guarantee, and its reviews. ## Agent skills - [arbor](https://arbor.forestfuture.dev/.well-known/agent-skills/arbor/SKILL.md): Arbor ORM (`@forestfuture/arbor`, with its D1 and PostgreSQL adapters as its `/d1` and `/postgresql` entries), an Active Record ORM for TypeScript on 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://arbor.forestfuture.dev/llms-full.txt): The full Markdown of every page in one file. - [Page Markdown](https://arbor.forestfuture.dev/index.md): Append `.md` to any page URL to fetch that page as raw Markdown. - [JSON API](https://arbor.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://arbor.forestfuture.dev/openapi.json. - [Agent skills](https://arbor.forestfuture.dev/.well-known/agent-skills/index.json): Agent Skills discovery index of the skills this site publishes. - [API catalog](https://arbor.forestfuture.dev/.well-known/api-catalog): RFC 9727 linkset of the APIs documented here. - [AI catalog](https://arbor.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://arbor.forestfuture.dev/agent-readability.json): Manifest of every agent-facing artifact on this site. - [Sitemap](https://arbor.forestfuture.dev/sitemap.xml): Every indexable page URL with its last-modified date.