Socket
Socket
Sign inDemoInstall

caixie-orm

Package Overview
Dependencies
0
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    caixie-orm

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.


Version published
Weekly downloads
189
increased by18.13%
Maintainers
1
Created
Weekly downloads
 

Changelog

Source

4.0.0 (2020-09-08)

Bug Fixes

  • cli: custom tsconfig gets wrong path (#597) (3cdb5dd)
  • core: add RequestContext.createAsync() for Koa (ae3bc0f), closes #709
  • core: allow date to be used as primary key (#609) (d421be8)
  • core: allow having same property name as entity name (6b9d4cd), closes #655
  • core: allow hiding PKs in toObject() (0a920dd), closes #644
  • core: allow populating FK as PK in toJSON() (e05d780)
  • core: do not cascade merge new entities (2b0f208)
  • core: do not lookup in identity map with non-PK conditions (4fb0e52), closes #625
  • core: do not merge entity instances in em.create() (50aaef8)
  • core: fix em.create() with deeply nested data (#683) (a302473), closes #678
  • core: fix default value for cache.enabled (9be725f)
  • core: fix extracting PK out of reference wrapper (db037dc), closes #589
  • core: map values from returning clause via hydrator (c5384b4), closes #725
  • core: mark all properties as populated for new entities (5f7fb8f), closes #784
  • core: reset collections when assigning to those not initialized (e19a6b4)
  • core: support comments in tsconfig.json (6506695), closes #730
  • core: support nullable bigints (3bb2a2d), closes #631
  • core: support self referencing with Reference wrapper (fd1e158), closes #610
  • core: throw when trying to call em.remove(..., null) (77c52dd)
  • mapping: support mixed M:N with composite PK on one side only (a951918)
  • mariadb: enable bigNumberStrings toggle (ee90c64), closes #578
  • mongo: add support for $re operator in mongo (13fe6e5), closes #613
  • postgres: time column type should be a string (#774) (237ddbf)
  • query-builder: make sure $or and $and combined works correctly (c8d3a34), closes #792
  • query-builder: make sure we use the right alias in complex $and queries (522787e), closes #786
  • query-builder: use correct operators in complex and/or conditions (#803) (aca0e10)
  • schema: do not create indexes for each composite PK (91b38cb), closes #760
  • postgres: keep bigint/numeric types as string (014f3b5), closes #324
  • sql: pivot joining of m:n when no target entity needed directly (2b0bb72), closes #549
  • sql: pivot joining of m:n when target entity is null (3b05a59), closes #548
  • sql: rework implicit m:n pivot joining (7928c50)
  • sql: support composite keys in EntityCaseNamingStrategy (8d07727)
  • sql: use composite FKs instead in schema generator (f5c2302)
  • utils: ts-node check now runs in a webpack environment (#657) (4384019)

Features

  • core: add driver.nativeInsertMany() method (#688) (78b2341), closes #442
  • core: add em.begin/commit/rollback methods (#717) (5414c52)
  • core: add EntityRepositoryType symbol (#698) (ffae0a8), closes #696
  • core: add expr helper to allow custom expressions in EM API (39ced1b), closes #802
  • core: add property serializers (3d94b93), closes #809
  • core: add support for entity and property comment (#668) (c01b338)
  • core: add support for filters/scopes (#663) (c1025b9), closes #385
  • core: add support for flush events (#642) (1f12aff), closes #637
  • core: add support for ordering by NULLS (#677) (74ee0cb), closes #675
  • core: allow persisting 1:m collections (#686) (379b289), closes #467
  • core: allow using knex.raw in query params (e6b9f0e), closes #802
  • core: allow using destructing assignments in entity ctors (06a5490), closes #781
  • core: execute hooks via EventManager (#623) (6a7f627), closes #622
  • core: expose populate parameter in wrap(e).init() (d33432a), closes #814
  • core: readonly entity (#738) (7581592)
  • core: refactor internal dependencies to support Yarn PnP (#645) (7e21bb8)
  • core: refactor merging to allow querying by custom type (#800) (bfbc5f8), closes #739
  • core: support globs in entities (#618) (ee81b61), closes #605
  • core: type safe references (#691) (77d64ba), closes #214
  • core: use custom errors for failHandler and metadata (6db22af), closes #611
  • migrations: add Migration.execute() method (5c1f60a), closes #770
  • migrations: add support for initial migrations (#818) (26b2228), closes #772
  • migrations: allow specifying list of migrations (#741) (5a0f2a6), closes #705
  • migrations: allow using knex in migrations (fc2fbaa), closes #799
  • postgres: add $ilike, $overlap, $contains, $contained (3c59885), closes #641
  • query-builder: allow ordering by custom expressions (e4674c7), closes #707
  • query-builder: make sure we do not prefix virtual props (fd0766c), closes #734
  • cli: allow the use of TS path mapping (#554) (2444192)
  • core: accept references in collection add/remove/set methods (26d132f)
  • core: add connect: boolean param to MikroORM.init() (43a9ce9)
  • core: add having to FindOptions (952fd2f)
  • core: add custom types for array, blob and json (#559) (7703cc5), closes #476
  • core: add pagination support (QueryFlag.PAGINATE) (#544) (d43241e)
  • core: add support for alternative loading strategies (#556) (0b89d4a), closes #440
  • core: add support for event subscribers (#614) (1281356), closes #516
  • core: add support for lazy scalar properties (#585) (cd8c683), closes #427
  • core: add support for Node.js 14 (#522) (2093af8)
  • core: add support for single table inheritance (#503) (8c45339), closes #33
  • core: allow adding items to not initialized collections (#489) (8be8a4d)
  • core: allow adding items to not initialized collections (#489) (ca5eb64)
  • core: do not cache metadata for other than ts-morph provider (#569) (49fb4eb)
  • core: pass entity as parameter in onCreate and onUpdate (#564) (3044a19)
  • core: split project into multiple packages (#475) (636e861)
  • core: use custom exceptions for driver related errors (#539) (2c30679)
  • discovery: use both entity name and path as key in Metadat… (#488) (72f0aca)
  • mapping: add support for embeddables (#514) (0fa06b1)
  • migrations: support custom migration names (8ea71b6), closes #449
  • mongo: add getCollection() method to MongoEntityManager (79a9a7d)
  • mongo: allow creating any kind of index in mongo (8fbe48a)
  • mongo: allow using different primary key types than ObjectId (#568) (e523794), closes #349
  • postgres: use jsonb column type by default (b6c0578)
  • sql: add execute() method to SqlEntityManager (e389d40)
  • sql: add groupBy to FindOptions (2f6687a)
  • sql: add qb.raw() to allow using raw snippets in QB (c09a5b6), closes #598
  • sql: add support for computed properties via @Formula() (#553) (68b9336)
  • sql: add support for sub-queries (#525) (e07f8ad)
  • sql: allow delete queries with auto-joining via sub-queries (#538) (e44bc56), closes #492
  • sql: allow update queries with auto-joining via sub-queries (#537) (cff9a3a), closes #319
  • sql: ensure correct table order in schema generator (#617) (b3949cf)
  • sql: initialize query builder in select mode (#565) (3e3abe7)
  • ts-morph: add ORM version to cache invalidation logic (f28119a)
  • ts-morph: infer nullability from property types (4c45e00)
  • ts-morph: use .d.ts files for ts-morph discovery (#616) (54ce064)

Performance Improvements

  • cli: transpile only when using ts-node in CLI (f739f39)
  • core: do not generate sql when logging disabled (f232bb3), closes #732
  • core: implement bulk deletes (#757) (d83f648), closes #732
  • core: improve performance of QB a bit (efc044f), closes #732
  • core: improve speed of inserting new items (bfeb2e3), closes #732
  • core: optimize QB for simple cases (99cfca7), closes #732
  • core: reduce usage of wrap helper internally (66ffc3b), closes #732
  • core: simplify MetadataStorage.find() method (9abbe03), closes #732
  • core: use actual Map for identity maps (3645a20), closes #732
  • core: use Set instead of array for cycle lookups (dff0c9d), closes #732
  • core: use Set instead of array for stacks in UoW (12ba811), closes #732

BREAKING CHANGES

Please see the upgrading guide.

Readme

Source

MikroORM

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.

Heavily inspired by Doctrine and Nextras Orm.

NPM version NPM dev version Chat on slack Downloads Coverage Status Maintainability Build Status

🤔 Unit of What?

You might be asking: What the hell is Unit of Work and why should I care about it?

Unit of Work maintains a list of objects (entities) affected by a business transaction and coordinates the writing out of changes. (Martin Fowler)

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)

So what benefits does it bring to us?

Implicit Transactions

First and most important implication of having Unit of Work is that it allows handling transactions automatically.

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.

You can also control the transaction boundaries manually via em.transactional(cb).

const user = await em.findOneOrFail(User, 1);
user.email = 'foo@bar.com';
const car = new Car();
user.cars.add(car);

// 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();

ChangeSet based persistence

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:

@Entity()
export class User {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  @OneToOne()
  address?: Address;

  @ManyToMany()
  cars = new Collection<Car>(this);

  constructor(name: string) {
    this.name = name;
  }

}

Now to create new instance of the User entity, we are forced to provide the name:

const user = new User('John Doe'); // name is required to create new user instance
user.address = new Address('10 Downing Street'); // address is optional

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.

const user = await em.findOneOrFail(User, 1, ['cars', 'address']);
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);

// now we can flush all changes done to managed entities
await em.flush();

em.flush() will then execute these queries from the example above:

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 = true where id = 1;
update car set for_sale = true where id = 2;
update car set for_sale = true where id = 3;
insert into car (brand, owner) values ('VW', 1);
commit;

Only One Instance of Entity

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).

📖 Documentation

MikroORM v4 documentation, included in this repo in the root directory, is built with Jekyll and publicly hosted on GitHub Pages at https://mikro-orm.io.

There is also auto-generated CHANGELOG.md file based on commit messages (via semantic-release).

You can browse MikroORM v3 docs at https://mikro-orm.io/docs/3.6/installation.

To upgrade to v4, please see the upgrading guide.

✨ Core Features

📦 Example Integrations

You can find example integrations for some popular frameworks in the mikro-orm-examples repository:

TypeScript Examples

JavaScript Examples

Articles

  • Introducing MikroORM, TypeScript data-mapper ORM with Identity Map
  • Handling transactions and concurrency in MikroORM
  • MikroORM 3: Knex.js, CLI, Schema Updates, Entity Generator and more…

🚀 Quick Start

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.

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/sqlite      # for sqlite

or

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/sqlite      # for sqlite

Next you will need to enable support for decorators as well as esModuleInterop in tsconfig.json via:

"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,

Then call MikroORM.init as part of bootstrapping your app:

const orm = await MikroORM.init({
  entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
  dbName: 'my-db-name',
  type: 'mongo',
  clientUrl: '...', // defaults to 'mongodb://localhost:27017' for mongodb driver
});
console.log(orm.em); // access EntityManager via `em` property

There are more ways to configure your entities, take a look at installation page.

Read more about all the possible configuration options in Advanced Configuration section.

Then you will need to fork entity manager for each request so their identity maps will not collide. To do so, use the RequestContext helper:

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.

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

@Entity()
export class MongoBook {

  @PrimaryKey()
  _id: ObjectID;

  @SerializedPrimaryKey()
  id: string;

  @Property()
  title: string;

  @ManyToOne()
  author: Author;

  @ManyToMany()
  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

@Entity()
export class SqlBook {

  @PrimaryKey()
  id: number;

}

Or if you want to use UUID primary keys:

./entities/UuidBook.ts

import { v4 } from 'uuid';

@Entity()
export class UuidBook {

  @PrimaryKey()
  uuid = v4();

}

More information can be found in defining entities section in docs.

When you have your entities defined, you can start using ORM either via EntityManager or via EntityRepositorys.

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.

// 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 orm.em.persistAndFlush([book1, book2, book3]);

To fetch entities from database you can use find() and findOne() of EntityManager:

const authors = orm.em.find(Author, {});

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:

const booksRepository = orm.em.getRepository(Book);

// with sorting, limit and offset parameters, populating author references
const books = await booksRepository.find({ author: '...' }, ['author'], { title: QueryOrder.DESC }, 2, 1);

// or with options object
const books = await booksRepository.find({ author: '...' }, { 
  populate: ['author'],
  limit: 1,
  offset: 2,
  orderBy: { title: QueryOrder.DESC },
});

console.log(books); // Book[]

Take a look at docs about working with EntityManager or using EntityRepository instead.

🤝 Contributing

Contributions, issues and feature requests are welcome. Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.

Authors

👤 Martin Adámek

See also the list of contributors who participated in this project.

Show Your Support

Please ⭐️ this repository if this project helped you!

📝 License

Copyright © 2018 Martin Adámek.

This project is licensed under the MIT License - see the LICENSE file for details.

Keywords

FAQs

Last updated on 12 Mar 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc