{"analyzedAt":"2022-07-13T08:58:13.489Z","collected":{"metadata":{"name":"@erpairforce/typeorm","scope":"erpairforce","version":"0.2.40","description":"Data-Mapper ORM for TypeScript, ES7, ES6, ES5. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB databases. Pulled from https://github.com/typeorm/typeorm ad upgraded SAP Hana-Client","date":"2021-07-01T20:52:47.220Z","author":{"name":"ERP Airforce","email":"fme-support@erp.ngo"},"publisher":{"username":"erpairforce","email":"francois.maass@erp.ngo"},"maintainers":[{"username":"erpairforce","email":"francois.maass@erp.ngo"}],"repository":{"type":"git","url":"git+https://github.com/typeorm/typeorm.git"},"links":{"npm":"https://www.npmjs.com/package/%40erpairforce%2Ftypeorm","homepage":"https://github.com/typeorm/typeorm#readme","repository":"https://github.com/typeorm/typeorm","bugs":"https://github.com/typeorm/typeorm/issues"},"license":"MIT","dependencies":{"@sap/hana-client":"^2.8.22","@sqltools/formatter":"^1.2.2","app-root-path":"^3.0.0","buffer":"^6.0.3","chalk":"^4.1.0","cli-highlight":"^2.1.11","debug":"^4.3.1","dotenv":"^8.2.0","glob":"^7.1.6","hdb-pool":"^0.1.6","js-yaml":"^4.0.0","mkdirp":"^1.0.4","reflect-metadata":"^0.1.13","sha.js":"^2.4.11","tslib":"^2.1.0","xml2js":"^0.4.23","yargonaut":"^1.1.4","yargs":"^16.2.0","zen-observable-ts":"^1.0.0"},"devDependencies":{"@types/app-root-path":"^1.2.4","@types/chai":"^4.2.15","@types/chai-as-promised":"^7.1.3","@types/debug":"^4.1.5","@types/dotenv":"^8.2.0","@types/js-yaml":"^4.0.0","@types/mkdirp":"^1.0.1","@types/mocha":"^8.2.1","@types/node":"^14.14.31","@types/rimraf":"^3.0.0","@types/sha.js":"^2.4.0","@types/sinon":"^9.0.10","@types/source-map-support":"^0.5.3","@types/xml2js":"^0.4.8","@types/yargs":"^16.0.0","@typescript-eslint/eslint-plugin":"^4.15.2","@typescript-eslint/parser":"^4.15.2","better-sqlite3":"^7.1.2","chai":"^4.3.0","chai-as-promised":"^7.1.1","class-transformer":"^0.4.0","conventional-changelog-angular":"^5.0.12","conventional-changelog-cli":"^2.1.1","del":"^6.0.0","eslint":"^7.20.0","gulp":"^4.0.2","gulp-eslint":"^6.0.0","gulp-istanbul":"^1.1.3","gulp-mocha":"^8.0.0","gulp-rename":"^2.0.0","gulp-replace":"^1.0.0","gulp-shell":"^0.8.0","gulp-sourcemaps":"^3.0.0","gulp-typescript":"^6.0.0-alpha.1","gulpclass":"^0.2.0","husky":"^5.1.1","lint-staged":"^10.5.4","mocha":"^8.3.0","mongodb":"^3.6.4","mssql":"^6.3.1","mysql":"^2.18.1","mysql2":"^2.2.5","oracledb":"^5.1.0","pg":"^8.5.1","pg-query-stream":"^4.0.0","redis":"^3.1.1","remap-istanbul":"^0.13.0","rimraf":"^3.0.2","sinon":"^9.2.4","sinon-chai":"^3.5.0","source-map-support":"^0.5.19","sql.js":"^1.4.0","sqlite3":"^5.0.2","ts-node":"^9.1.1","typeorm-aurora-data-api-driver":"^2.0.0","typescript":"^4.2.2"},"peerDependencies":{"@sap/hana-client":"*","better-sqlite3":"*","hdb-pool":"*","ioredis":"*","mongodb":"*","mssql":"*","mysql2":"*","oracledb":"*","pg":"*","pg-native":"*","pg-query-stream":"*","redis":"*","sql.js":"*","sqlite3":"*","typeorm-aurora-data-api-driver":"*"},"releases":[{"from":"2022-06-13T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":0},{"from":"2022-04-14T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":0},{"from":"2022-01-14T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":1},{"from":"2021-07-13T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":1},{"from":"2020-07-13T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":8}],"hasTestScript":true,"readme":"<div align=\"center\">\n  <a href=\"http://typeorm.io/\">\n    <img src=\"https://github.com/typeorm/typeorm/raw/master/resources/logo_big.png\" width=\"492\" height=\"228\">\n  </a>\n  <br>\n  <br>\n\t<a href=\"https://app.circleci.com/pipelines/github/typeorm/typeorm\">\n\t\t<img src=\"https://circleci.com/gh/typeorm/typeorm/tree/master.svg?style=shield\">\n\t</a>\n\t<a href=\"https://badge.fury.io/js/typeorm\">\n\t\t<img src=\"https://badge.fury.io/js/typeorm.svg\">\n\t</a>\n\t<a href=\"https://david-dm.org/typeorm/typeorm\">\n\t\t<img src=\"https://david-dm.org/typeorm/typeorm.svg\">\n\t</a>\n    <a href=\"https://codecov.io/gh/typeorm/typeorm\">\n        <img alt=\"Codecov\" src=\"https://img.shields.io/codecov/c/github/typeorm/typeorm.svg\">\n    </a>\n\t<a href=\"https://join.slack.com/t/typeorm/shared_invite/zt-gej3gc00-hR~L~DqGUJ7qOpGy4SSq3g\">\n\t\t<img src=\"https://img.shields.io/badge/chat-on%20slack-blue.svg\">\n\t</a>\n  <br>\n  <br>\n</div>\n\nTypeORM is an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)\nthat can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms\nand can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8).\nIts goal is to always support the latest JavaScript features and provide additional features\nthat help you to develop any kind of application that uses databases - from\nsmall applications with a few tables to large scale enterprise applications\nwith multiple databases.\n\nTypeORM supports both [Active Record](./docs/active-record-data-mapper.md#what-is-the-active-record-pattern) and [Data Mapper](./docs/active-record-data-mapper.md#what-is-the-data-mapper-pattern) patterns,\nunlike all other JavaScript ORMs currently in existence,\nwhich means you can write high quality, loosely coupled, scalable,\nmaintainable applications the most productive way.\n\nTypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate.org/orm/),\n [Doctrine](http://www.doctrine-project.org/) and [Entity Framework](https://www.asp.net/entity-framework).\n\n## Features\n\n* supports both [DataMapper](./docs/active-record-data-mapper.md#what-is-the-data-mapper-pattern) and [ActiveRecord](./docs/active-record-data-mapper.md#what-is-the-active-record-pattern) (your choice)\n* entities and columns\n* database-specific column types\n* entity manager\n* repositories and custom repositories\n* clean object relational model\n* associations (relations)\n* eager and lazy relations\n* uni-directional, bi-directional and self-referenced relations\n* supports multiple inheritance patterns\n* cascades\n* indices\n* transactions\n* migrations and automatic migrations generation\n* connection pooling\n* replication\n* using multiple database connections\n* working with multiple databases types\n* cross-database and cross-schema queries\n* elegant-syntax, flexible and powerful QueryBuilder\n* left and inner joins\n* proper pagination for queries using joins\n* query caching\n* streaming raw results\n* logging\n* listeners and subscribers (hooks)\n* supports closure table pattern\n* schema declaration in models or separate configuration files\n* connection configuration in json / xml / yml / env formats\n* supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js\n* supports MongoDB NoSQL database\n* works in NodeJS / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms\n* TypeScript and JavaScript support\n* produced code is performant, flexible, clean and maintainable\n* follows all possible best practices\n* CLI\n\nAnd more...\n\nWith TypeORM your models look like this:\n\n```javascript\nimport { Entity, PrimaryGeneratedColumn, Column } from \"typeorm\";\n\n@Entity()\nexport class User {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    firstName: string;\n\n    @Column()\n    lastName: string;\n\n    @Column()\n    age: number;\n\n}\n```\n\nAnd your domain logic looks like this:\n\n```javascript\nconst repository = connection.getRepository(User);\n\nconst user = new User();\nuser.firstName = \"Timber\";\nuser.lastName = \"Saw\";\nuser.age = 25;\nawait repository.save(user);\n\nconst allUsers = await repository.find();\nconst firstUser = await repository.findOne(1); // find by id\nconst timber = await repository.findOne({ firstName: \"Timber\", lastName: \"Saw\" });\n\nawait repository.remove(timber);\n```\n\nAlternatively, if you prefer to use the `ActiveRecord` implementation, you can use it as well:\n\n```javascript\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from \"typeorm\";\n\n@Entity()\nexport class User extends BaseEntity {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    firstName: string;\n\n    @Column()\n    lastName: string;\n\n    @Column()\n    age: number;\n\n}\n```\n\nAnd your domain logic will look this way:\n\n```javascript\nconst user = new User();\nuser.firstName = \"Timber\";\nuser.lastName = \"Saw\";\nuser.age = 25;\nawait user.save();\n\nconst allUsers = await User.find();\nconst firstUser = await User.findOne(1);\nconst timber = await User.findOne({ firstName: \"Timber\", lastName: \"Saw\" });\n\nawait timber.remove();\n```\n\n## Installation\n\n\n1. Install the npm package:\n\n    `npm install typeorm --save`\n\n2. You need to install `reflect-metadata` shim:\n\n    `npm install reflect-metadata --save`\n\n    and import it somewhere in the global place of your app (for example in `app.ts`):\n\n    `import \"reflect-metadata\";`\n\n3. You may need to install node typings:\n\n    `npm install @types/node --save-dev`\n\n4. Install a database driver:\n\n    * for **MySQL** or **MariaDB**\n\n        `npm install mysql --save` (you can install `mysql2` instead as well)\n\n    * for **PostgreSQL** or **CockroachDB**\n\n        `npm install pg --save`\n\n    * for **SQLite**\n\n        `npm install sqlite3 --save`\n\n    * for **Microsoft SQL Server**\n\n        `npm install mssql --save`\n\n    * for **sql.js**\n\n        `npm install sql.js --save`\n\n    * for **Oracle**\n\n        `npm install oracledb --save`\n\n        To make the Oracle driver work, you need to follow the installation instructions from\n        [their](https://github.com/oracle/node-oracledb) site.\n\n    * for **SAP Hana**\n\n        ```\n        npm i @sap/hana-client\n\t\tnpm i hdb-pool\n        ```\n\n        *SAP Hana support made possible by sponsorship of [Neptune Software](https://www.neptune-software.com/).*\n\n    * for **MongoDB** (experimental)\n\n        `npm install mongodb --save`\n\n    * for **NativeScript**, **react-native** and **Cordova**\n\n        Check [documentation of supported platforms](./docs/supported-platforms.md)\n\n    Install only *one* of them, depending on which database you use.\n\n\n##### TypeScript configuration\n\nAlso, make sure you are using TypeScript version **3.3** or higher,\nand you have enabled the following settings in `tsconfig.json`:\n\n```json\n\"emitDecoratorMetadata\": true,\n\"experimentalDecorators\": true,\n```\n\nYou may also need to enable `es6` in the `lib` section of compiler options, or install `es6-shim` from `@types`.\n\n## Quick Start\n\nThe quickest way to get started with TypeORM is to use its CLI commands to generate a starter project.\nQuick start works only if you are using TypeORM in a NodeJS application.\nIf you are using other platforms, proceed to the [step-by-step guide](#step-by-step-guide).\n\nFirst, install TypeORM globally:\n\n```\nnpm install typeorm -g\n```\n\nThen go to the directory where you want to create a new project and run the command:\n\n```\ntypeorm init --name MyProject --database mysql\n```\n\nWhere `name` is the name of your project and `database` is the database you'll use.\nDatabase can be one of the following values: `mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `oracle`, `mongodb`,\n`cordova`, `react-native`, `expo`, `nativescript`.\n\nThis command will generate a new project in the `MyProject` directory with the following files:\n\n```\nMyProject\n├── src              // place of your TypeScript code\n│   ├── entity       // place where your entities (database models) are stored\n│   │   └── User.ts  // sample entity\n│   ├── migration    // place where your migrations are stored\n│   └── index.ts     // start point of your application\n├── .gitignore       // standard gitignore file\n├── ormconfig.json   // ORM and database connection configuration\n├── package.json     // node module dependencies\n├── README.md        // simple readme file\n└── tsconfig.json    // TypeScript compiler options\n```\n\n> You can also run `typeorm init` on an existing node project, but be careful - it may override some files you already have.\n\nThe next step is to install new project dependencies:\n\n```\ncd MyProject\nnpm install\n```\n\nWhile installation is in progress, edit the `ormconfig.json` file and put your own database connection configuration options in there:\n\n```json\n{\n   \"type\": \"mysql\",\n   \"host\": \"localhost\",\n   \"port\": 3306,\n   \"username\": \"test\",\n   \"password\": \"test\",\n   \"database\": \"test\",\n   \"synchronize\": true,\n   \"logging\": false,\n   \"entities\": [\n      \"src/entity/**/*.ts\"\n   ],\n   \"migrations\": [\n      \"src/migration/**/*.ts\"\n   ],\n   \"subscribers\": [\n      \"src/subscriber/**/*.ts\"\n   ]\n}\n```\n\nParticularly, most of the time you'll only need to configure\n`host`, `username`, `password`, `database` and maybe `port` options.\n\nOnce you finish with configuration and all node modules are installed, you can run your application:\n\n```\nnpm start\n```\n\nThat's it, your application should successfully run and insert a new user into the database.\nYou can continue to work with this project and integrate other modules you need and start\ncreating more entities.\n\n> You can generate an even more advanced project with express installed by running\n`typeorm init --name MyProject --database mysql --express` command.\n\n> You can generate docker-compose file by running\n`typeorm init --name MyProject --database postgres --docker` command.\n\n## Step-by-Step Guide\n\nWhat are you expecting from ORM?\nFirst of all, you are expecting it will create database tables for you\nand find / insert / update / delete your data without the pain of\nhaving to write lots of hardly maintainable SQL queries.\nThis guide will show you how to setup TypeORM from scratch and make it do what you are expecting from an ORM.\n\n### Create a model\n\nWorking with a database starts from creating tables.\nHow do you tell TypeORM to create a database table?\nThe answer is - through the models.\nYour models in your app are your database tables.\n\nFor example, you have a `Photo` model:\n\n```javascript\nexport class Photo {\n    id: number;\n    name: string;\n    description: string;\n    filename: string;\n    views: number;\n    isPublished: boolean;\n}\n```\n\nAnd you want to store photos in your database.\nTo store things in the database, first you need a database table,\nand database tables are created from your models.\nNot all models, but only those you define as *entities*.\n\n### Create an entity\n\n*Entity* is your model decorated by an `@Entity` decorator.\nA database table will be created for such models.\nYou work with entities everywhere with TypeORM.\nYou can load/insert/update/remove and perform other operations with them.\n\nLet's make our `Photo` model as an entity:\n\n```javascript\nimport { Entity } from \"typeorm\";\n\n@Entity()\nexport class Photo {\n    id: number;\n    name: string;\n    description: string;\n    filename: string;\n    views: number;\n    isPublished: boolean;\n}\n```\n\nNow, a database table will be created for the `Photo` entity and we'll be able to work with it anywhere in our app.\nWe have created a database table, however what table can exist without columns?\nLet's create a few columns in our database table.\n\n### Adding table columns\n\nTo add database columns, you simply need to decorate an entity's properties you want to make into a column\nwith a `@Column` decorator.\n\n```javascript\nimport { Entity, Column } from \"typeorm\";\n\n@Entity()\nexport class Photo {\n\n    @Column()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @Column()\n    description: string;\n\n    @Column()\n    filename: string;\n\n    @Column()\n    views: number;\n\n    @Column()\n    isPublished: boolean;\n}\n```\n\nNow `id`, `name`, `description`, `filename`, `views` and `isPublished` columns will be added to the `photo` table.\nColumn types in the database are inferred from the property types you used, e.g.\n`number` will be converted into `integer`, `string` into `varchar`, `boolean` into `bool`, etc.\nBut you can use any column type your database supports by explicitly specifying a column type into the `@Column` decorator.\n\nWe generated a database table with columns, but there is one thing left.\nEach database table must have a column with a primary key.\n\n### Creating a primary column\n\nEach entity **must** have at least one primary key column.\nThis is a requirement and you can't avoid it.\nTo make a column a primary key, you need to use `@PrimaryColumn` decorator.\n\n```javascript\nimport { Entity, Column, PrimaryColumn } from \"typeorm\";\n\n@Entity()\nexport class Photo {\n\n    @PrimaryColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @Column()\n    description: string;\n\n    @Column()\n    filename: string;\n\n    @Column()\n    views: number;\n\n    @Column()\n    isPublished: boolean;\n}\n```\n\n### Creating an auto generated column\n\nNow, let's say you want your id column to be auto-generated (this is known as auto-increment / sequence / serial / generated identity column).\nTo do that, you need to change the `@PrimaryColumn` decorator to a `@PrimaryGeneratedColumn` decorator:\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn } from \"typeorm\";\n\n@Entity()\nexport class Photo {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @Column()\n    description: string;\n\n    @Column()\n    filename: string;\n\n    @Column()\n    views: number;\n\n    @Column()\n    isPublished: boolean;\n}\n```\n\n### Column data types\n\nNext, let's fix our data types. By default, string is mapped to a varchar(255)-like type (depending on the database type).\nNumber is mapped to a integer-like type (depending on the database type).\nWe don't want all our columns to be limited varchars or integers.\nLet's setup correct data types:\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn } from \"typeorm\";\n\n@Entity()\nexport class Photo {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column({\n        length: 100\n    })\n    name: string;\n\n    @Column(\"text\")\n    description: string;\n\n    @Column()\n    filename: string;\n\n    @Column(\"double\")\n    views: number;\n\n    @Column()\n    isPublished: boolean;\n}\n```\n\nColumn types are database-specific.\nYou can set any column type your database supports.\nMore information on supported column types can be found [here](./docs/entities.md#column-types).\n\n### Creating a connection to the database\n\nNow, when our entity is created, let's create an `index.ts` (or `app.ts` whatever you call it) file and set up our connection there:\n\n```javascript\nimport \"reflect-metadata\";\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection({\n    type: \"mysql\",\n    host: \"localhost\",\n    port: 3306,\n    username: \"root\",\n    password: \"admin\",\n    database: \"test\",\n    entities: [\n        Photo\n    ],\n    synchronize: true,\n    logging: false\n}).then(connection => {\n    // here you can start to work with your entities\n}).catch(error => console.log(error));\n```\n\nWe are using MySQL in this example, but you can use any other supported database.\nTo use another database, simply change the `type` in the options to the database type you are using:\n`mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `oracle`, `cordova`, `nativescript`, `react-native`,\n`expo`, or `mongodb`.\nAlso make sure to use your own host, port, username, password and database settings.\n\nWe added our Photo entity to the list of entities for this connection.\nEach entity you are using in your connection must be listed there.\n\nSetting `synchronize` makes sure your entities will be synced with the database, every time you run the application.\n\n### Loading all entities from the directory\n\nLater, when we create more entities we need to add them to the entities in our configuration.\nThis is not very convenient, so instead we can set up the whole directory, from where all entities will be connected and used in our connection:\n\n```javascript\nimport { createConnection } from \"typeorm\";\n\ncreateConnection({\n    type: \"mysql\",\n    host: \"localhost\",\n    port: 3306,\n    username: \"root\",\n    password: \"admin\",\n    database: \"test\",\n    entities: [\n        __dirname + \"/entity/*.js\"\n    ],\n    synchronize: true,\n}).then(connection => {\n    // here you can start to work with your entities\n}).catch(error => console.log(error));\n```\n\nBut be careful with this approach.\nIf you are using `ts-node` then you need to specify paths to `.ts` files instead.\nIf you are using `outDir` then you'll need to specify paths to `.js` files inside outDir directory.\nIf you are using `outDir` and when you remove or rename your entities make sure to clear `outDir` directory\nand re-compile your project again, because when you remove your source `.ts` files their compiled `.js` versions\naren't removed from output directory and still are loaded by TypeORM because they are present in the `outDir` directory.\n\n### Running the application\n\nNow if you run your `index.ts`, a connection with database will be initialized and a database table for your photos will be created.\n\n\n```shell\n+-------------+--------------+----------------------------+\n|                         photo                           |\n+-------------+--------------+----------------------------+\n| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |\n| name        | varchar(100) |                            |\n| description | text         |                            |\n| filename    | varchar(255) |                            |\n| views       | int(11)      |                            |\n| isPublished | boolean      |                            |\n+-------------+--------------+----------------------------+\n```\n\n### Creating and inserting a photo into the database\n\nNow let's create a new photo to save it in the database:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(connection => {\n\n    let photo = new Photo();\n    photo.name = \"Me and Bears\";\n    photo.description = \"I am near polar bears\";\n    photo.filename = \"photo-with-bears.jpg\";\n    photo.views = 1;\n    photo.isPublished = true;\n\n    return connection.manager\n            .save(photo)\n            .then(photo => {\n                console.log(\"Photo has been saved. Photo id is\", photo.id);\n            });\n\n}).catch(error => console.log(error));\n```\n\nOnce your entity is saved it will get a newly generated id.\n`save` method returns an instance of the same object you pass to it.\nIt's not a new copy of the object, it modifies its \"id\" and returns it.\n\n### Using async/await syntax\n\nLet's take advantage of the latest ES8 (ES2017) features and use async/await syntax instead:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    let photo = new Photo();\n    photo.name = \"Me and Bears\";\n    photo.description = \"I am near polar bears\";\n    photo.filename = \"photo-with-bears.jpg\";\n    photo.views = 1;\n    photo.isPublished = true;\n\n    await connection.manager.save(photo);\n    console.log(\"Photo has been saved\");\n\n}).catch(error => console.log(error));\n```\n\n### Using Entity Manager\n\nWe just created a new photo and saved it in the database.\nWe used `EntityManager` to save it.\nUsing entity manager you can manipulate any entity in your app.\nFor example, let's load our saved entity:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    /*...*/\n    let savedPhotos = await connection.manager.find(Photo);\n    console.log(\"All photos from the db: \", savedPhotos);\n\n}).catch(error => console.log(error));\n```\n\n`savedPhotos` will be an array of Photo objects with the data loaded from the database.\n\nLearn more about EntityManager [here](./docs/working-with-entity-manager.md).\n\n### Using Repositories\n\nNow let's refactor our code and use `Repository` instead of `EntityManager`.\nEach entity has its own repository which handles all operations with its entity.\nWhen you deal with entities a lot, Repositories are more convenient to use than EntityManagers:\n\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    let photo = new Photo();\n    photo.name = \"Me and Bears\";\n    photo.description = \"I am near polar bears\";\n    photo.filename = \"photo-with-bears.jpg\";\n    photo.views = 1;\n    photo.isPublished = true;\n\n    let photoRepository = connection.getRepository(Photo);\n\n    await photoRepository.save(photo);\n    console.log(\"Photo has been saved\");\n\n    let savedPhotos = await photoRepository.find();\n    console.log(\"All photos from the db: \", savedPhotos);\n\n}).catch(error => console.log(error));\n```\n\nLearn more about Repository [here](./docs/working-with-repository.md).\n\n### Loading from the database\n\nLet's try more load operations using the Repository:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    /*...*/\n    let allPhotos = await photoRepository.find();\n    console.log(\"All photos from the db: \", allPhotos);\n\n    let firstPhoto = await photoRepository.findOne(1);\n    console.log(\"First photo from the db: \", firstPhoto);\n\n    let meAndBearsPhoto = await photoRepository.findOne({ name: \"Me and Bears\" });\n    console.log(\"Me and Bears photo from the db: \", meAndBearsPhoto);\n\n    let allViewedPhotos = await photoRepository.find({ views: 1 });\n    console.log(\"All viewed photos: \", allViewedPhotos);\n\n    let allPublishedPhotos = await photoRepository.find({ isPublished: true });\n    console.log(\"All published photos: \", allPublishedPhotos);\n\n    let [allPhotos, photosCount] = await photoRepository.findAndCount();\n    console.log(\"All photos: \", allPhotos);\n    console.log(\"Photos count: \", photosCount);\n\n}).catch(error => console.log(error));\n```\n\n### Updating in the database\n\nNow let's load a single photo from the database, update it and save it:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    /*...*/\n    let photoToUpdate = await photoRepository.findOne(1);\n    photoToUpdate.name = \"Me, my friends and polar bears\";\n    await photoRepository.save(photoToUpdate);\n\n}).catch(error => console.log(error));\n```\n\nNow photo with `id = 1` will be updated in the database.\n\n### Removing from the database\n\nNow let's remove our photo from the database:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    /*...*/\n    let photoToRemove = await photoRepository.findOne(1);\n    await photoRepository.remove(photoToRemove);\n\n}).catch(error => console.log(error));\n```\n\nNow photo with `id = 1` will be removed from the database.\n\n### Creating a one-to-one relation\n\nLet's create a one-to-one relation with another class.\nLet's create a new class in `PhotoMetadata.ts`. This PhotoMetadata class is supposed to contain our photo's additional meta-information:\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn } from \"typeorm\";\nimport { Photo } from \"./Photo\";\n\n@Entity()\nexport class PhotoMetadata {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column(\"int\")\n    height: number;\n\n    @Column(\"int\")\n    width: number;\n\n    @Column()\n    orientation: string;\n\n    @Column()\n    compressed: boolean;\n\n    @Column()\n    comment: string;\n\n    @OneToOne(type => Photo)\n    @JoinColumn()\n    photo: Photo;\n}\n```\n\nHere, we are using a new decorator called `@OneToOne`. It allows us to create a one-to-one relationship between two entities.\n`type => Photo` is a function that returns the class of the entity with which we want to make our relationship.\nWe are forced to use a function that returns a class, instead of using the class directly, because of the language specifics.\nWe can also write it as `() => Photo`, but we use `type => Photo` as a convention to increase code readability.\nThe type variable itself does not contain anything.\n\nWe also add a `@JoinColumn` decorator, which indicates that this side of the relationship will own the relationship.\nRelations can be unidirectional or bidirectional.\nOnly one side of relational can be owning.\nUsing `@JoinColumn` decorator is required on the owner side of the relationship.\n\nIf you run the app, you'll see a newly generated table, and it will contain a column with a foreign key for the photo relation:\n\n```shell\n+-------------+--------------+----------------------------+\n|                     photo_metadata                      |\n+-------------+--------------+----------------------------+\n| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |\n| height      | int(11)      |                            |\n| width       | int(11)      |                            |\n| comment     | varchar(255) |                            |\n| compressed  | boolean      |                            |\n| orientation | varchar(255) |                            |\n| photoId     | int(11)      | FOREIGN KEY                |\n+-------------+--------------+----------------------------+\n```\n\n### Save a one-to-one relation\n\nNow let's save a photo, its metadata and attach them to each other.\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\nimport { PhotoMetadata } from \"./entity/PhotoMetadata\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    // create a photo\n    let photo = new Photo();\n    photo.name = \"Me and Bears\";\n    photo.description = \"I am near polar bears\";\n    photo.filename = \"photo-with-bears.jpg\";\n    photo.isPublished = true;\n\n    // create a photo metadata\n    let metadata = new PhotoMetadata();\n    metadata.height = 640;\n    metadata.width = 480;\n    metadata.compressed = true;\n    metadata.comment = \"cybershoot\";\n    metadata.orientation = \"portrait\";\n    metadata.photo = photo; // this way we connect them\n\n    // get entity repositories\n    let photoRepository = connection.getRepository(Photo);\n    let metadataRepository = connection.getRepository(PhotoMetadata);\n\n    // first we should save a photo\n    await photoRepository.save(photo);\n\n    // photo is saved. Now we need to save a photo metadata\n    await metadataRepository.save(metadata);\n\n    // done\n    console.log(\"Metadata is saved, and relation between metadata and photo is created in the database too\");\n\n}).catch(error => console.log(error));\n```\n\n### Inverse side of the relationship\n\nRelations can be unidirectional or bidirectional.\nCurrently, our relation between PhotoMetadata and Photo is unidirectional.\nThe owner of the relation is PhotoMetadata, and Photo doesn't know anything about PhotoMetadata.\nThis makes it complicated to access PhotoMetadata from the Photo side.\nTo fix this issue we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional.\nLet's modify our entities:\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn } from \"typeorm\";\nimport { Photo } from \"./Photo\";\n\n@Entity()\nexport class PhotoMetadata {\n\n    /* ... other columns */\n\n    @OneToOne(type => Photo, photo => photo.metadata)\n    @JoinColumn()\n    photo: Photo;\n}\n```\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn, OneToOne } from \"typeorm\";\nimport { PhotoMetadata } from \"./PhotoMetadata\";\n\n@Entity()\nexport class Photo {\n\n    /* ... other columns */\n\n    @OneToOne(type => PhotoMetadata, photoMetadata => photoMetadata.photo)\n    metadata: PhotoMetadata;\n}\n```\n\n`photo => photo.metadata` is a function that returns the name of the inverse side of the relation.\nHere we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class.\nInstead of passing a function that returns a property of the photo, you could alternatively simply pass a string to `@OneToOne` decorator, like `\"metadata\"`.\nBut we used this function-typed approach to make our refactoring easier.\n\nNote that we should use `@JoinColumn` decorator only on one side of a relation.\nWhichever side you put this decorator on will be the owning side of the relationship.\nThe owning side of a relationship contains a column with a foreign key in the database.\n\n### Loading objects with their relations\n\nNow let's load our photo and its photo metadata in a single query.\nThere are two ways to do it - using `find*` methods or using `QueryBuilder` functionality.\nLet's use `find*` methods first.\n`find*` methods allow you to specify an object with the `FindOneOptions` / `FindManyOptions` interface.\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\nimport { PhotoMetadata } from \"./entity/PhotoMetadata\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    /*...*/\n    let photoRepository = connection.getRepository(Photo);\n    let photos = await photoRepository.find({ relations: [\"metadata\"] });\n\n}).catch(error => console.log(error));\n```\n\nHere, photos will contain an array of photos from the database, and each photo will contain its photo metadata.\nLearn more about Find Options in [this documentation](./docs/find-options.md).\n\nUsing find options is good and dead simple, but if you need a more complex query, you should use `QueryBuilder` instead.\n`QueryBuilder` allows more complex queries to be used in an elegant way:\n\n```javascript\nimport { createConnection } from \"typeorm\";\nimport { Photo } from \"./entity/Photo\";\nimport { PhotoMetadata } from \"./entity/PhotoMetadata\";\n\ncreateConnection(/*...*/).then(async connection => {\n\n    /*...*/\n    let photos = await connection\n            .getRepository(Photo)\n            .createQueryBuilder(\"photo\")\n            .innerJoinAndSelect(\"photo.metadata\", \"metadata\")\n            .getMany();\n\n\n}).catch(error => console.log(error));\n```\n\n`QueryBuilder` allows creation and execution of SQL queries of almost any complexity.\nWhen you work with `QueryBuilder`, think like you are creating an SQL query.\nIn this example, \"photo\" and \"metadata\" are aliases applied to selected photos.\nYou use aliases to access columns and properties of the selected data.\n\n### Using cascades to automatically save related objects\n\nWe can setup cascade options in our relations, in the cases when we want our related object to be saved whenever the other object is saved.\nLet's change our photo's `@OneToOne` decorator a bit:\n\n```javascript\nexport class Photo {\n    /// ... other columns\n\n    @OneToOne(type => PhotoMetadata, metadata => metadata.photo, {\n        cascade: true,\n    })\n    metadata: PhotoMetadata;\n}\n```\n\nUsing `cascade` allows us not to separately save photo and separately save metadata objects now.\nNow we can simply save a photo object, and the metadata object will be saved automatically because of cascade options.\n\n```javascript\ncreateConnection(options).then(async connection => {\n\n    // create photo object\n    let photo = new Photo();\n    photo.name = \"Me and Bears\";\n    photo.description = \"I am near polar bears\";\n    photo.filename = \"photo-with-bears.jpg\";\n    photo.isPublished = true;\n\n    // create photo metadata object\n    let metadata = new PhotoMetadata();\n    metadata.height = 640;\n    metadata.width = 480;\n    metadata.compressed = true;\n    metadata.comment = \"cybershoot\";\n    metadata.orientation = \"portrait\";\n\n    photo.metadata = metadata; // this way we connect them\n\n    // get repository\n    let photoRepository = connection.getRepository(Photo);\n\n    // saving a photo also save the metadata\n    await photoRepository.save(photo);\n\n    console.log(\"Photo is saved, photo metadata is saved too.\")\n\n}).catch(error => console.log(error));\n```\n\nNotice that we now set the photo's `metadata` property, instead of the metadata's `photo` property as before. The `cascade` feature only works if you connect the photo to its metadata from the photo's side. If you set the metadata's side, the metadata would not be saved automatically.\n\n### Creating a many-to-one / one-to-many relation\n\nLet's create a many-to-one / one-to-many relation.\nLet's say a photo has one author, and each author can have many photos.\nFirst, let's create an `Author` class:\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn, OneToMany, JoinColumn } from \"typeorm\";\nimport { Photo } from \"./Photo\";\n\n@Entity()\nexport class Author {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @OneToMany(type => Photo, photo => photo.author) // note: we will create author property in the Photo class below\n    photos: Photo[];\n}\n```\n\n`Author` contains an inverse side of a relation.\n`OneToMany` is always an inverse side of relation, and it can't exist without `ManyToOne` on the other side of the relation.\n\nNow let's add the owner side of the relation into the Photo entity:\n\n```javascript\nimport { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from \"typeorm\";\nimport { PhotoMetadata } from \"./PhotoMetadata\";\nimport { Author } from \"./Author\";\n\n@Entity()\nexport class Photo {\n\n    /* ... other columns */\n\n    @ManyToOne(type => Author, author => author.photos)\n    author: Author;\n}\n```\n\nIn many-to-one / one-to-many relation, the owner side is always many-to-one.\nIt means that the class that uses `@ManyToOne` will store the id of the related object.\n\nAfter you run the application, the ORM will create the `author` table:\n\n\n```shell\n+-------------+--------------+----------------------------+\n|                          author                         |\n+-------------+--------------+----------------------------+\n| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |\n| name        | varchar(255) |                            |\n+-------------+--------------+----------------------------+\n```\n\nIt will also modify the `photo` table, adding a new `author` column and creating a foreign key for it:\n\n```shell\n+-------------+--------------+----------------------------+\n|                         photo                           |\n+-------------+--------------+----------------------------+\n| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |\n| name        | varchar(255) |                            |\n| description | varchar(255) |                            |\n| filename    | varchar(255) |                            |\n| isPublished | boolean      |                            |\n| authorId    | int(11)      | FOREIGN KEY                |\n+-------------+--------------+----------------------------+\n```\n\n### Creating a many-to-many relation\n\nLet's create a many-to-many relation.\nLet's say a photo can be in many albums, and each album can contain many photos.\nLet's create an `Album` class:\n\n```javascript\nimport { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from \"typeorm\";\n\n@Entity()\nexport class Album {\n\n    @PrimaryGeneratedColumn()\n    id: number;\n\n    @Column()\n    name: string;\n\n    @ManyToMany(type => Photo, photo => photo.albums)\n    @JoinTable()\n    photos: Photo[];\n}\n```\n\n`@JoinTable` is required to specify that this is the owner side of the relationship.\n\nNow let's add the inverse side of our relation to the `Photo` class:\n\n```javascript\nexport class Photo {\n    /// ... other columns\n\n    @ManyToMany(type => Album, album => album.photos)\n    albums: Album[];\n}\n```\n\nAfter you run the application, the ORM will create a **album_photos_photo_albums** *junction table*:\n\n```shell\n+-------------+--------------+----------------------------+\n|                album_photos_photo_albums                |\n+-------------+--------------+----------------------------+\n| album_id    | int(11)      | PRIMARY KEY FOREIGN KEY    |\n| photo_id    | int(11)      | PRIMARY KEY FOREIGN KEY    |\n+-------------+--------------+----------------------------+\n```\n\nDon't forget to register the `Album` class with your connection in the ORM:\n\n```javascript\nconst options: ConnectionOptions = {\n    // ... other options\n    entities: [Photo, PhotoMetadata, Author, Album]\n};\n```\n\nNow let's insert albums and photos to our database:\n\n```javascript\nlet connection = await createConnection(options);\n\n// create a few albums\nlet album1 = new Album();\nalbum1.name = \"Bears\";\nawait connection.manager.save(album1);\n\nlet album2 = new Album();\nalbum2.name = \"Me\";\nawait connection.manager.save(album2);\n\n// create a few photos\nlet photo = new Photo();\nphoto.name = \"Me and Bears\";\nphoto.description = \"I am near polar bears\";\nphoto.filename = \"photo-with-bears.jpg\";\nphoto.views = 1\nphoto.isPublished = true\nphoto.albums = [album1, album2];\nawait connection.manager.save(photo);\n\n// now our photo is saved and albums are attached to it\n// now lets load them:\nconst loadedPhoto = await connection\n    .getRepository(Photo)\n    .findOne(1, { relations: [\"albums\"] });\n```\n\n`loadedPhoto` will be equal to:\n\n```javascript\n{\n    id: 1,\n    name: \"Me and Bears\",\n    description: \"I am near polar bears\",\n    filename: \"photo-with-bears.jpg\",\n    albums: [{\n        id: 1,\n        name: \"Bears\"\n    }, {\n        id: 2,\n        name: \"Me\"\n    }]\n}\n```\n\n### Using QueryBuilder\n\nYou can use QueryBuilder to build SQL queries of almost any complexity. For example, you can do this:\n\n```javascript\nlet photos = await connection\n    .getRepository(Photo)\n    .createQueryBuilder(\"photo\") // first argument is an alias. Alias is what you are selecting - photos. You must specify it.\n    .innerJoinAndSelect(\"photo.metadata\", \"metadata\")\n    .leftJoinAndSelect(\"photo.albums\", \"album\")\n    .where(\"photo.isPublished = true\")\n    .andWhere(\"(photo.name = :photoName OR photo.name = :bearName)\")\n    .orderBy(\"photo.id\", \"DESC\")\n    .skip(5)\n    .take(10)\n    .setParameters({ photoName: \"My\", bearName: \"Mishka\" })\n    .getMany();\n```\n\nThis query selects all published photos with \"My\" or \"Mishka\" names.\nIt will select results from position 5 (pagination offset),\nand will select only 10 results (pagination limit).\nThe selection result will be ordered by id in descending order.\nThe photo's albums will be left-joined and their metadata will be inner joined.\n\nYou'll use the query builder in your application a lot.\nLearn more about QueryBuilder [here](./docs/select-query-builder.md).\n\n## Samples\n\nTake a look at the samples in [sample](https://github.com/typeorm/typeorm/tree/master/sample) for examples of usage.\n\nThere are a few repositories which you can clone and start with:\n\n* [Example how to use TypeORM with TypeScript](https://github.com/typeorm/typescript-example)\n* [Example how to use TypeORM with JavaScript](https://github.com/typeorm/javascript-example)\n* [Example how to use TypeORM with JavaScript and Babel](https://github.com/typeorm/babel-example)\n* [Example how to use TypeORM with TypeScript and SystemJS in Browser](https://github.com/typeorm/browser-example)\n* [Example how to use Express and TypeORM](https://github.com/typeorm/typescript-express-example)\n* [Example how to use Koa and TypeORM](https://github.com/typeorm/typescript-koa-example)\n* [Example how to use TypeORM with MongoDB](https://github.com/typeorm/mongo-typescript-example)\n* [Example how to use TypeORM in a Cordova/PhoneGap app](https://github.com/typeorm/cordova-example)\n* [Example how to use TypeORM with an Ionic app](https://github.com/typeorm/ionic-example)\n* [Example how to use TypeORM with React Native](https://github.com/typeorm/react-native-example)\n* [Example how to use TypeORM with Nativescript-Vue](https://github.com/typeorm/nativescript-vue-typeorm-sample)\n* [Example how to use TypeORM with Nativescript-Angular](https://github.com/betov18x/nativescript-angular-typeorm-example)\n* [Example how to use TypeORM with Electron using JavaScript](https://github.com/typeorm/electron-javascript-example)\n* [Example how to use TypeORM with Electron using TypeScript](https://github.com/typeorm/electron-typescript-example)\n\n## Extensions\n\nThere are several extensions that simplify working with TypeORM and integrating it with other modules:\n\n* [TypeORM + GraphQL framework](http://vesper-framework.com)\n* [TypeORM integration](https://github.com/typeorm/typeorm-typedi-extensions) with [TypeDI](https://github.com/pleerock/typedi)\n* [TypeORM integration](https://github.com/typeorm/typeorm-routing-controllers-extensions) with [routing-controllers](https://github.com/pleerock/routing-controllers)\n* Models generation from existing database - [typeorm-model-generator](https://github.com/Kononnable/typeorm-model-generator)\n* Fixtures loader - [typeorm-fixtures-cli](https://github.com/RobinCK/typeorm-fixtures)\n* ER Diagram generator - [typeorm-uml](https://github.com/eugene-manuilov/typeorm-uml/)\n\n## Contributing\n\nLearn about contribution [here](https://github.com/typeorm/typeorm/blob/master/CONTRIBUTING.md) and how to setup your development environment [here](https://github.com/typeorm/typeorm/blob/master/DEVELOPER.md).\n\nThis project exists thanks to all the people who contribute:\n\n<a href=\"https://github.com/typeorm/typeorm/graphs/contributors\"><img src=\"https://opencollective.com/typeorm/contributors.svg?width=890&showBtn=false\" /></a>\n\n## Sponsors\n\nOpen source is hard and time-consuming. If you want to invest into TypeORM's future you can become a sponsor and allow our core team to spend more time on TypeORM's improvements and new features. [Become a sponsor](https://opencollective.com/typeorm)\n\n<a href=\"https://opencollective.com/typeorm\" target=\"_blank\"><img src=\"https://opencollective.com/typeorm/tiers/sponsor.svg?width=890\"></a>\n\n## Gold Sponsors\n\nBecome a gold sponsor and get a premium technical support from our core contributors. [Become a gold sponsor](https://opencollective.com/typeorm)\n\n<a href=\"https://opencollective.com/typeorm\" target=\"_blank\"><img src=\"https://opencollective.com/typeorm/tiers/gold-sponsor.svg?width=890\"></a>"},"npm":{"downloads":[{"from":"2022-07-12T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":0},{"from":"2022-07-06T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":0},{"from":"2022-06-13T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":7},{"from":"2022-04-14T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":47},{"from":"2022-01-14T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":156},{"from":"2021-07-13T00:00:00.000Z","to":"2022-07-13T00:00:00.000Z","count":331}],"starsCount":0}},"evaluation":{"quality":{"carefulness":0.165,"tests":0,"health":0,"branding":0},"popularity":{"communityInterest":0,"downloadsCount":15.666666666666666,"downloadsAcceleration":-0.17842465753424658,"dependentsCount":0},"maintenance":{"releasesFrequency":0.3729452054794521,"commitsFrequency":0,"openIssues":0,"issuesDistribution":0}},"score":{"final":0.14172710991241394,"detail":{"quality":0.10511502143193392,"popularity":0.0040971109842176875,"maintenance":0.31073889896673595}}}