# TypeORM ArangoDB

> [!IMPORTANT]
> This repository is an ArangoDB-maintained fork of
> [TypeORM](https://github.com/typeorm/typeorm) that adds native ArangoDB
> support. It is not the upstream TypeORM distribution.

> [!WARNING]
> This fork and its ArangoDB support are a work in progress. It is not
> production-ready, APIs and behavior may change without notice, and no
> compatibility or support guarantees are provided yet.

The public snapshot npm package is `@arangodb/typeorm-arangodb`. Install it under
the compatibility name `typeorm` so existing imports and integrations keep
working:

```shell
pnpm add "typeorm@npm:@arangodb/typeorm-arangodb@0.0.2-SNAPSHOT"
pnpm add "arangojs@^10.3.1" reflect-metadata
```

See the [ArangoDB driver guide](#arangodb-driver-guide) for usage and
the supported feature set. TypeORM API names remain unchanged for compatibility.

## ArangoDB driver guide

TypeORM supports ArangoDB document collections through
[`arangojs`](https://arangodb.github.io/arangojs/). The integration provides
TypeORM entity persistence for documents and an explicit native AQL escape
hatch. It does not expose ArangoDB graph APIs or translate SQL APIs to AQL.

### Installation

Install the public work-in-progress snapshot under the compatibility name
`typeorm` together with the optional native client:

```shell
pnpm add "typeorm@npm:@arangodb/typeorm-arangodb@0.0.2-SNAPSHOT"
pnpm add "arangojs@^10.3.1" reflect-metadata
```

The npm alias keeps existing `typeorm` imports and integrations working while
the package itself is published as `@arangodb/typeorm-arangodb`.

### Supported versions and deployments

The supported compatibility matrix is:

- Node.js 22 or 24 LTS
- `arangojs` 10.3.x
- ArangoDB 3.12.x in a single-server deployment

Development and CI use `arangojs` 10.3.1 and a pinned ArangoDB 3.12 image.
Node.js 20 is supported by TypeORM generally, but is not part of the ArangoDB
driver compatibility claim. Cluster, coordinator, failover, and multi-server
load-balancing behavior have not been validated. An array of equivalent
single-server endpoints is supported as native client configuration, but does
not imply cluster support.

The ArangoDB client is server-only. Browser builds replace the driver, query
runner, manager, and repository modules with TypeORM's disabled-driver
placeholder.

### Data source configuration

```typescript
import { DataSource } from "typeorm"

export const dataSource = new DataSource({
    type: "arangodb",
    url: "http://localhost:8529",
    database: "application",
    auth: {
        username: "root",
        password: "password",
    },
    synchronize: true,
    migrationsTransactionMode: "none",
    entities: [Product],
    migrations: [CreateProductCategoryIndex],
})
```

ArangoDB-specific options are:

- `url`: one server URL or an array of equivalent endpoints.
- `database`: the required database name.
- `auth`: the basic-auth or bearer-token form accepted by `arangojs`.
- `driver`: an injected `arangojs` module, primarily for controlled runtimes
  and tests. TypeORM loads the installed peer by default.
- `extra`: native `arangojs` client options such as pool size, load-balancing
  strategy, custom fetch, HTTPS/TLS, and agent settings.

The dedicated `url`, `database`, and `auth` values take precedence over any
overlapping native settings. Initialization verifies the selected database
with `Database.version()`. Destroying the data source closes the native
client's connection pool. Native connection and authorization diagnostics are
preserved when initialization fails.

### Entity mapping and document identity

Every ArangoDB entity must declare exactly one primary column. It must be a
non-generated string mapped to ArangoDB's `_key` field:

```typescript
import { Column, Entity, PrimaryColumn } from "typeorm"

@Entity("products")
export class Product {
    @PrimaryColumn("string", { name: "_key" })
    id!: string

    @Column("string")
    name!: string

    @Column("string")
    category!: string
}
```

The entity property may have any name; only its database name must be `_key`.
A caller may provide the property value, or omit it from an `insert` partial
and let ArangoDB generate an opaque string key. TypeORM maps a generated key
back to the entity property.

Embedded objects, recursive embedded objects, and embedded arrays are stored
as nested document values. Column database names and value transformers are
applied at persistence and hydration boundaries. Create, update, and delete
date columns, entity listeners, and subscribers participate in the supported
common persistence lifecycle.

Relations are rejected. Joins, relation cascades, foreign keys, edge
collections, and graph semantics are not inferred from document fields.

### Repository and EntityManager APIs

Use the ArangoDB-specific accessor when native methods are required:

```typescript
await dataSource.initialize()

const products = dataSource.getArangoRepository(Product)

const inserted = await products.insert({
    name: "Desk",
    category: "office",
})
const id = inserted.identifiers[0].id

const product = await products.findOneBy({ id })
await products.update(id, { name: "Standing desk" })
await products.delete(id)

// Truncates only the products collection; it does not drop the collection.
await products.clear()

await dataSource.destroy()
```

`dataSource.getRepository(Product)` returns the same cached
`ArangoRepository` specialization. The matching manager is available through
`dataSource.arangoManager`. The repository methods below are also available on
`ArangoEntityManager`; manager calls additionally receive the entity target.

### Persistence API

The supported persistence surface includes primitive mutations and TypeORM's
entity-aware lifecycle. These examples use the `products` repository from the
preceding section.

#### `insert`

Available on `ArangoRepository` and `ArangoEntityManager`. Performs the
supported primitive insert mutation for one or more document partials. Its
`InsertResult` preserves native write metadata in `raw`.

```typescript
const result = await products.insert({
    name: "Desk",
    category: "office",
})
```

#### `update`

Available on `ArangoRepository` and `ArangoEntityManager`. Performs the
supported primitive update mutation. Its `UpdateResult` preserves native write
metadata in `raw`, and its `affected` value comes from ArangoDB cursor write
statistics.

```typescript
const result = await products.update(id, { name: "Standing desk" })
```

#### `delete`

Available on `ArangoRepository` and `ArangoEntityManager`. Performs the
supported primitive delete mutation. Its `DeleteResult` preserves native write
metadata in `raw`, and its `affected` value comes from ArangoDB cursor write
statistics.

```typescript
const result = await products.delete(id)
```

#### `clear`

Available on `ArangoRepository` and `ArangoEntityManager`. Truncates the
selected entity collection without dropping it or changing unrelated
collections.

```typescript
await products.clear()
```

#### `save`

Available on `ArangoRepository` and `ArangoEntityManager`. Persists entities
through TypeORM's supported entity-aware lifecycle, inserting new entities and
updating existing ones.

```typescript
const product = await products.save({
    name: "Desk",
    category: "office",
})
```

#### `preload`

Available on `ArangoRepository` and `ArangoEntityManager`. Loads an existing
document and merges the supplied values into an entity without saving it. It
returns `undefined` when the document does not exist.

```typescript
const product = await products.preload({ id, name: "Standing desk" })
```

#### `remove`

Available on `ArangoRepository` and `ArangoEntityManager`. Removes entities
through TypeORM's supported entity-aware lifecycle.

```typescript
const product = await products.findOneBy({ id })
if (product) await products.remove(product)
```

#### `softRemove`

Available on `ArangoRepository` and `ArangoEntityManager`. Soft-removes
entities by recording their delete date through TypeORM's supported
entity-aware lifecycle.

```typescript
const product = await products.findOneBy({ id })
if (product) await products.softRemove(product)
```

#### `recover`

Available on `ArangoRepository` and `ArangoEntityManager`. Recovers
soft-removed entities through TypeORM's supported entity-aware lifecycle.

```typescript
const product = await products.findOne({
    where: { id },
    withDeleted: true,
})
if (product) await products.recover(product)
```

### Query API and supported find options

Generated AQL binds collection names and all caller-provided values. Supported
criteria include direct equality and these TypeORM find operators:

- `Equal`, `Not`, `LessThan`, `LessThanOrEqual`, `MoreThan`, and
  `MoreThanOrEqual`;
- `Between`, `In`, and `IsNull`;
- `And` and `Or`, including an array of `where` objects as OR branches.

Criteria may address mapped properties inside non-array embedded objects;
filtering through embedded arrays is not supported. Unsupported operators and
option combinations fail before native query execution.

#### `find`

Available on `ArangoRepository` and `ArangoEntityManager`. Supports `where`,
`select`, `order`, `skip`, `take`, and `withDeleted`.

```typescript
const officeProducts = await products.find({
    where: { category: "office" },
    order: { name: "ASC" },
})
```

#### `findBy`

Available on `ArangoRepository` and `ArangoEntityManager`. Finds entities using
the supported document criteria.

```typescript
const officeProducts = await products.findBy({ category: "office" })
```

#### `findOne`

Available on `ArangoRepository` and `ArangoEntityManager`. Requires non-empty
criteria and does not support pagination.

```typescript
const product = await products.findOne({ where: { id } })
```

#### `findOneBy`

Available on `ArangoRepository` and `ArangoEntityManager`. Finds one entity
using the supported document criteria.

```typescript
const product = await products.findOneBy({ id })
```

#### `findByIds`

Available on `ArangoRepository` and `ArangoEntityManager`. Finds entities by
their document identities.

```typescript
const selected = await products.findByIds(["desk-1", "chair-1"])
```

#### `findAndCount`

Available on `ArangoRepository` and `ArangoEntityManager`. Supports `where`,
`select`, `order`, `skip`, `take`, and `withDeleted`, and returns the matching
entities with their total count.

```typescript
const [officeProducts, total] = await products.findAndCount({
    where: { category: "office" },
    take: 10,
})
```

#### `findAndCountBy`

Available on `ArangoRepository` and `ArangoEntityManager`. Finds and counts
entities using the supported document criteria.

```typescript
const [officeProducts, total] = await products.findAndCountBy({
    category: "office",
})
```

### Cursor API

#### `createEntityCursor`

For incremental entity consumption, `createEntityCursor()` returns an
`ArangoEntityCursor`. The method is available on `ArangoRepository` and
`ArangoEntityManager` and accepts the supported find options.

```typescript
const cursor = await products.createEntityCursor({
    where: { category: "office" },
})
```

#### `next`

Available on `ArangoEntityCursor`. Consumes the next document and returns its
hydrated entity. The entity receives load events exactly once.

```typescript
const cursor = await products.createEntityCursor()
const product = await cursor.next()
```

#### `all`

Available on `ArangoEntityCursor`. Consumes all remaining documents and
returns hydrated entities. Each entity receives load events exactly once.

```typescript
const cursor = await products.createEntityCursor()
const productsPage = await cursor.all()
```

#### `[Symbol.asyncIterator]`

`ArangoEntityCursor` supports async iteration. Each iterated document is
hydrated and receives load events exactly once.

```typescript
const cursor = await products.createEntityCursor()
for await (const product of cursor) {
    console.log(product.name)
}
```

#### `kill`

Available on `ArangoEntityCursor`. Kills the underlying cursor when consumption
stops early.

```typescript
const cursor = await products.createEntityCursor()
await cursor.next()
await cursor.kill()
```

### Native collections and AQL

The native methods are available on `ArangoRepository` and
`ArangoEntityManager`; the query runner also provides collection-name-based
native access.

#### `getNativeCollection`

Returns the typed `arangojs` document collection for an entity.

```typescript
const collection = products.getNativeCollection()
```

#### `queryAql`

Accepts either an `arangojs` tagged AQL query or an AQL string with a separate
bind-variable object:

```typescript
import { aql } from "arangojs"

const products = dataSource.getArangoRepository(Product)
const collection = products.getNativeCollection()

const cursor = await products.queryAql<Product>(aql`
    FOR product IN ${collection}
        FILTER product.category == ${"office"}
        SORT product.name
        RETURN product
`)

try {
    for await (const document of cursor) {
        console.log(document._key, document.name)
    }
} finally {
    await cursor.kill()
}
```

`queryAql()` returns the unconsumed native `arangojs` cursor. Callers own cursor
consumption and should kill a cursor when stopping early. The native cursor
returns documents rather than hydrated entities; use repository find methods
or `createEntityCursor()` when entity transformation and load events are
required.

`Repository.query()`, `DataSource.query()`, SQL `QueryBuilder`, and SQL
parameter APIs are not AQL aliases and fail explicitly.

### Schema synchronization

With `synchronize: true`, TypeORM creates missing document collections and
leaves existing collections and documents unchanged. Repeated synchronization
is idempotent for the supported index mappings:

- ordinary and unique `@Index` metadata maps to persistent indexes;
- `sparse` and `background` persistent-index options are supported;
- `expireAfterSeconds` maps a single, non-unique, non-sparse field to a TTL
  index.

Spatial, full-text, partial/filtered, concurrent, explicitly typed, deferrable,
and invalid TTL definitions fail explicitly. TypeORM does not emulate those
semantics.

`repository.clear()` truncates one selected collection and preserves unrelated
collections. `dataSource.dropDatabase()` has a deliberately narrower meaning
for ArangoDB: it drops every non-system collection in the configured ordinary
database but preserves the physical database. It rejects `_system` before
mutation and propagates native permission failures.

### Migrations

ArangoDB migrations use TypeORM's migration executor and store history in the
configured migrations collection. They are intentionally non-transactional:
set `migrationsTransactionMode: "none"`, and do not set a migration's
`transaction` property to `true`.

Migration methods receive the ArangoDB query runner at runtime. Public
manager APIs can be used without importing an internal driver class:

```typescript
import type {
    ArangoEntityManager,
    MigrationInterface,
    QueryRunner,
} from "typeorm"

export class CreateProductCategoryIndex1735689600000 implements MigrationInterface {
    async up(queryRunner: QueryRunner): Promise<void> {
        const manager = queryRunner.manager as ArangoEntityManager
        const cursor = await manager.queryAql(
            `INSERT { _key: @key, appliedAt: DATE_NOW() }
             INTO @@collection
             OPTIONS { overwriteMode: "ignore" }`,
            {
                "@collection": "products",
                key: "bootstrap",
            },
        )
        await cursor.all()
    }

    async down(queryRunner: QueryRunner): Promise<void> {
        const manager = queryRunner.manager as ArangoEntityManager
        const cursor = await manager.queryAql("REMOVE @key IN @@collection", {
            "@collection": "products",
            key: "bootstrap",
        })
        await cursor.all()
    }
}
```

Migration ordering uses TypeORM migration timestamps; execution history also
uses a stable monotonically increasing execution id so repeated timestamps can
be reverted deterministically. Migration and native AQL failures retain native
ArangoDB diagnostics.

### Unsupported capabilities

The ArangoDB driver does not support:

- SQL queries, SQL `QueryBuilder`, SQL schema operations, or SQL replication;
- TypeORM transactions or transactional migrations;
- relations, joins, relation cascades, foreign keys, tree repositories, or
  relational constraints;
- graph traversal, graph management, edge-collection modeling, or
  graph-specific repositories;
- query-result caching, locking, relation loading options, and unsupported
  find operators;
- spatial, full-text, and other index semantics not listed above;
- cluster, coordinator, or failover compatibility claims.

Use the documented repository/manager operations or explicit bound
`queryAql()` calls. Unsupported TypeORM entry points fail instead of silently
changing semantics.
