You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

@mikro-orm/migrations

Package Overview
Dependencies
Maintainers
1
Versions
4149
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mikro-orm/migrations - npm Package Compare versions

Comparing version
7.0.2-dev.11
to
7.0.2-dev.12
+3
-3
package.json
{
"name": "@mikro-orm/migrations",
"version": "7.0.2-dev.11",
"version": "7.0.2-dev.12",
"description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",

@@ -50,3 +50,3 @@ "keywords": [

"dependencies": {
"@mikro-orm/sql": "7.0.2-dev.11"
"@mikro-orm/sql": "7.0.2-dev.12"
},

@@ -57,3 +57,3 @@ "devDependencies": {

"peerDependencies": {
"@mikro-orm/core": "7.0.2-dev.11"
"@mikro-orm/core": "7.0.2-dev.12"
},

@@ -60,0 +60,0 @@ "engines": {

+127
-293

@@ -5,3 +5,3 @@ <h1 align="center">

TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL, SQLite (including libSQL), MSSQL and Oracle databases.
TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL, SQLite (including libSQL), MSSQL and Oracle databases.

@@ -17,140 +17,170 @@ > Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).

## 🤔 Unit of What?
## Quick Start
You might be asking: _What the hell is Unit of Work and why should I care about it?_
Install a driver package for your database:
> Unit of Work maintains a list of objects (_entities_) affected by a business transaction
> and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
```sh
npm install @mikro-orm/postgresql # PostgreSQL
npm install @mikro-orm/mysql # MySQL
npm install @mikro-orm/mariadb # MariaDB
npm install @mikro-orm/sqlite # SQLite
npm install @mikro-orm/libsql # libSQL / Turso
npm install @mikro-orm/mongodb # MongoDB
npm install @mikro-orm/mssql # MS SQL Server
npm install @mikro-orm/oracledb # Oracle
```
> Identity Map ensures that each object (_entity_) gets loaded only once by keeping every
> loaded object in a map. Looks up objects using the map when referring to them.
> [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/identityMap.html)
> If you use additional packages like `@mikro-orm/cli`, `@mikro-orm/migrations`, or `@mikro-orm/entity-generator`, install `@mikro-orm/core` explicitly as well. See the [quick start guide](https://mikro-orm.io/docs/quick-start) for details.
So what benefits does it bring to us?
### Define Entities
### Implicit Transactions
The recommended way to define entities is using [`defineEntity`](https://mikro-orm.io/docs/define-entity) with `setClass`:
First and most important implication of having Unit of Work is that it allows handling transactions automatically.
```typescript
import { defineEntity, p, MikroORM } from '@mikro-orm/postgresql';
When you call `em.flush()`, all computed changes are queried inside a database transaction (if supported by given driver). This means that you can control the boundaries of transactions simply by calling `em.persistLater()` and once all your changes are ready, calling `flush()` will run them inside a transaction.
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
name: p.string(),
email: p.string(),
born: p.datetime().nullable(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
> You can also control the transaction boundaries manually via `em.transactional(cb)`.
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);
```typescript
const user = await em.findOneOrFail(User, 1);
user.email = 'foo@bar.com';
const car = new Car();
user.cars.add(car);
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
title: p.string(),
author: () => p.manyToOne(Author).inversedBy('books'),
},
});
// thanks to bi-directional cascading we only need to persist user entity
// flushing will create a transaction, insert new car and update user with new email
// as user entity is managed, calling flush() is enough
await em.flush();
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
```
### ChangeSet based persistence
You can also define entities using [decorators](https://mikro-orm.io/docs/defining-entities) or [`EntitySchema`](https://mikro-orm.io/docs/entity-schema). See the [defining entities guide](https://mikro-orm.io/docs/defining-entities) for all options.
MikroORM allows you to implement your domain/business logic directly in the entities. To maintain always valid entities, you can use constructors to mark required properties. Let's define the `User` entity used in previous example:
### Initialize and Use
```typescript
@Entity()
export class User {
import { MikroORM, RequestContext } from '@mikro-orm/postgresql';
@PrimaryKey()
id!: number;
const orm = await MikroORM.init({
entities: [Author, Book],
dbName: 'my-db',
});
@Property()
name!: string;
// Create new entities
const author = orm.em.create(Author, {
name: 'Jon Snow',
email: 'snow@wall.st',
});
const book = orm.em.create(Book, {
title: 'My Life on The Wall',
author,
});
@OneToOne(() => Address)
address?: Address;
// Flush persists all tracked changes in a single transaction
await orm.em.flush();
```
@ManyToMany(() => Car)
cars = new Collection<Car>(this);
### Querying
constructor(name: string) {
this.name = name;
}
```typescript
// Find with relations
const authors = await orm.em.findAll(Author, {
populate: ['books'],
orderBy: { name: 'asc' },
});
}
// Type-safe QueryBuilder
const qb = orm.em.createQueryBuilder(Author);
const result = await qb
.select('*')
.where({ books: { title: { $like: '%Wall%' } } })
.getResult();
```
Now to create new instance of the `User` entity, we are forced to provide the `name`:
### Request Context
In web applications, use `RequestContext` to isolate the identity map per request:
```typescript
const user = new User('John Doe'); // name is required to create new user instance
user.address = new Address('10 Downing Street'); // address is optional
const app = express();
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
```
Once your entities are loaded, make a number of synchronous actions on your entities,
then call `em.flush()`. This will trigger computing of change sets. Only entities
(and properties) that were changed will generate database queries, if there are no changes,
no transaction will be started.
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
## Unit of Work
> Unit of Work maintains a list of objects (_entities_) affected by a business transaction
> and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
When you call `em.flush()`, all computed changes are queried inside a database transaction. This means you can control transaction boundaries simply by making changes to your entities and calling `flush()` when ready.
```typescript
const user = await em.findOneOrFail(User, 1, {
populate: ['cars', 'address.city'],
const author = await em.findOneOrFail(Author, 1, {
populate: ['books'],
});
user.title = 'Mr.';
user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
const car = new Car('VW');
user.cars.add(car);
author.name = 'Jon Snow II';
author.books.getItems().forEach(book => book.title += ' (2nd ed.)');
author.books.add(orm.em.create(Book, { title: 'New Book', author }));
// now we can flush all changes done to managed entities
// Flush computes change sets and executes them in a single transaction
await em.flush();
```
`em.flush()` will then execute these queries from the example above:
The above flush will execute:
```sql
begin;
update "user" set "title" = 'Mr.' where "id" = 1;
update "user_address" set "street" = '10 Downing Street' where "id" = 123;
update "car"
set "for_sale" = case
when ("id" = 1) then true
when ("id" = 2) then true
when ("id" = 3) then true
else "for_sale" end
where "id" in (1, 2, 3)
insert into "car" ("brand", "owner") values ('VW', 1);
update "author" set "name" = 'Jon Snow II' where "id" = 1;
update "book"
set "title" = case
when ("id" = 1) then 'My Life on The Wall (2nd ed.)'
when ("id" = 2) then 'Another Book (2nd ed.)'
else "title" end
where "id" in (1, 2);
insert into "book" ("title", "author_id") values ('New Book', 1);
commit;
```
### Identity Map
## Core Features
Thanks to Identity Map, you will always have only one instance of given entity in one context. This allows for some optimizations (skipping loading of already loaded entities), as well as comparison by identity (`ent1 === ent2`).
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities) — decorators, `EntitySchema`, or `defineEntity`
- [Identity Map](https://mikro-orm.io/docs/identity-map) and [Unit of Work](https://mikro-orm.io/docs/unit-of-work) — automatic change tracking
- [Entity References](https://mikro-orm.io/docs/entity-references) and [Collections](https://mikro-orm.io/docs/collections)
- [QueryBuilder](https://mikro-orm.io/docs/query-builder) and [Kysely Integration](https://mikro-orm.io/docs/kysely)
- [Transactions](https://mikro-orm.io/docs/transactions) and [Cascading](https://mikro-orm.io/docs/cascading)
- [Populating Relations](https://mikro-orm.io/docs/populating-relations) and [Loading Strategies](https://mikro-orm.io/docs/loading-strategies)
- [Filters](https://mikro-orm.io/docs/filters) and [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
- [Schema Generator](https://mikro-orm.io/docs/schema-generator) and [Migrations](https://mikro-orm.io/docs/migrations)
- [Entity Generator](https://mikro-orm.io/docs/entity-generator) and [Seeding](https://mikro-orm.io/docs/seeding)
- [Embeddables](https://mikro-orm.io/docs/embeddables), [Custom Types](https://mikro-orm.io/docs/custom-types), and [Serialization](https://mikro-orm.io/docs/serializing)
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
- [Entity Constructors](https://mikro-orm.io/docs/entity-constructors) and [Property Validation](https://mikro-orm.io/docs/property-validation)
- [Modelling Relationships](https://mikro-orm.io/docs/relationships) and [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
## 📖 Documentation
## Documentation
MikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
## ✨ Core Features
## Example Integrations
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities)
- [Identity Map](https://mikro-orm.io/docs/identity-map)
- [Entity References](https://mikro-orm.io/docs/entity-references)
- [Using Entity Constructors](https://mikro-orm.io/docs/entity-constructors)
- [Modelling Relationships](https://mikro-orm.io/docs/relationships)
- [Collections](https://mikro-orm.io/docs/collections)
- [Unit of Work](https://mikro-orm.io/docs/unit-of-work)
- [Transactions](https://mikro-orm.io/docs/transactions)
- [Cascading persist and remove](https://mikro-orm.io/docs/cascading)
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
- [Filters](https://mikro-orm.io/docs/filters)
- [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
- [Populating relations](https://mikro-orm.io/docs/populating-relations)
- [Property Validation](https://mikro-orm.io/docs/property-validation)
- [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
- [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
- [Schema Generator](https://mikro-orm.io/docs/schema-generator)
- [Entity Generator](https://mikro-orm.io/docs/entity-generator)
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
## 📦 Example Integrations
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
### TypeScript Examples

@@ -170,204 +200,8 @@

### JavaScript Examples
### JavaScript Examples
- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
## 🚀 Quick Start
## Contributing
First install the module via `yarn` or `npm` and do not forget to install the database driver as well:
> Since v4, you should install the driver package, but not the db connector itself, e.g. install `@mikro-orm/sqlite`, but not `sqlite3` as that is already included in the driver package.
```sh
yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo
yarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
yarn add @mikro-orm/core @mikro-orm/mssql # for mssql
yarn add @mikro-orm/core @mikro-orm/oracledb # for oracle
yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
```
or
```sh
npm i -s @mikro-orm/core @mikro-orm/mongodb # for mongo
npm i -s @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
npm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql
npm i -s @mikro-orm/core @mikro-orm/mssql # for mssql
npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
npm i -s @mikro-orm/core @mikro-orm/libsql # for libsql
```
Next, if you want to use decorators for your entity definition, you will need to enable support for [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) as well as `esModuleInterop` in `tsconfig.json` via:
```json
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
```
Alternatively, you can use [`EntitySchema`](https://mikro-orm.io/docs/entity-schema).
Then call `MikroORM.init` as part of bootstrapping your app:
> To access driver specific methods like `em.createQueryBuilder()` we need to specify the driver type when calling `MikroORM.init()`. Alternatively we can cast the `orm.em` to `EntityManager` exported from the driver package:
>
> ```ts
> import { EntityManager } from '@mikro-orm/postgresql';
> const em = orm.em as EntityManager;
> const qb = em.createQueryBuilder(...);
> ```
```typescript
import type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package
const orm = await MikroORM.init<PostgreSqlDriver>({
entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
dbName: 'my-db-name',
type: 'postgresql',
});
console.log(orm.em); // access EntityManager via `em` property
```
There are more ways to configure your entities, take a look at [installation page](https://mikro-orm.io/docs/installation/).
> Read more about all the possible configuration options in [Advanced Configuration](https://mikro-orm.io/docs/configuration) section.
Then you will need to fork entity manager for each request so their [identity maps](https://mikro-orm.io/docs/identity-map/) will not collide. To do so, use the `RequestContext` helper:
```typescript
const app = express();
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
```
> You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like `queryParser` or `bodyParser`, so definitely register the context after them.
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
Now you can start defining your entities (in one of the `entities` folders). This is how simple entity can look like in mongo driver:
**`./entities/MongoBook.ts`**
```typescript
@Entity()
export class MongoBook {
@PrimaryKey()
_id: ObjectID;
@SerializedPrimaryKey()
id: string;
@Property()
title: string;
@ManyToOne(() => Author)
author: Author;
@ManyToMany(() => BookTag)
tags = new Collection<BookTag>(this);
constructor(title: string, author: Author) {
this.title = title;
this.author = author;
}
}
```
For SQL drivers, you can use `id: number` PK:
**`./entities/SqlBook.ts`**
```typescript
@Entity()
export class SqlBook {
@PrimaryKey()
id: number;
}
```
Or if you want to use UUID primary keys:
**`./entities/UuidBook.ts`**
```typescript
import { randomUUID } from 'node:crypto';
@Entity()
export class UuidBook {
@PrimaryKey()
uuid = randomUUID();
}
```
More information can be found in [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.
When you have your entities defined, you can start using ORM either via `EntityManager` or via `EntityRepository`s.
To save entity state to database, you need to persist it. Persist takes care or deciding whether to use `insert` or `update` and computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade persisted automatically.
```typescript
// use constructors in your entities for required parameters
const author = new Author('Jon Snow', 'snow@wall.st');
author.born = new Date();
const publisher = new Publisher('7K publisher');
const book1 = new Book('My Life on The Wall, part 1', author);
book1.publisher = publisher;
const book2 = new Book('My Life on The Wall, part 2', author);
book2.publisher = publisher;
const book3 = new Book('My Life on The Wall, part 3', author);
book3.publisher = publisher;
// just persist books, author and publisher will be automatically cascade persisted
await em.persistAndFlush([book1, book2, book3]);
```
To fetch entities from database you can use `find()` and `findOne()` of `EntityManager`:
```typescript
const authors = em.find(Author, {}, { populate: ['books'] });
for (const author of authors) {
console.log(author); // instance of Author entity
console.log(author.name); // Jon Snow
for (const book of author.books) { // iterating books collection
console.log(book); // instance of Book entity
console.log(book.title); // My Life on The Wall, part 1/2/3
}
}
```
More convenient way of fetching entities from database is by using `EntityRepository`, that carries the entity name, so you do not have to pass it to every `find` and `findOne` calls:
```typescript
const booksRepository = em.getRepository(Book);
const books = await booksRepository.find({ author: '...' }, {
populate: ['author'],
limit: 1,
offset: 2,
orderBy: { title: QueryOrder.DESC },
});
console.log(books); // Loaded<Book, 'author'>[]
```
Take a look at docs about [working with `EntityManager`](https://mikro-orm.io/docs/entity-manager/) or [using `EntityRepository` instead](https://mikro-orm.io/docs/repositories/).
## 🤝 Contributing
Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.

@@ -377,3 +211,3 @@

👤 **Martin Adámek**
**Martin Adámek**

@@ -387,10 +221,10 @@ - Twitter: [@B4nan](https://twitter.com/B4nan)

Please ⭐️ this repository if this project helped you!
Please star this repository if this project helped you!
> If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
## 📝 License
## License
Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
Copyright © 2018-present [Martin Adámek](https://github.com/b4nan).
This project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.