### Start TypeORM Application Source: https://github.com/n8n-io/typeorm/blob/master/README.md Once dependencies are installed and the data source is configured, run this command to start your TypeORM application. ```shell npm start ``` -------------------------------- ### Start Docker Compose for Databases Source: https://github.com/n8n-io/typeorm/blob/master/DEVELOPER.md Run this command in the project root to start all necessary database images using Docker Compose. This avoids the need to install DBMS locally. ```shell docker-compose up ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/n8n-io/typeorm/blob/master/README.md After generating the project, navigate to the project directory and install the necessary Node.js dependencies using npm. ```shell cd MyProject npm install ``` -------------------------------- ### Install Express Source: https://github.com/n8n-io/typeorm/blob/master/docs/example-with-express.md Installs the Express framework and its type definitions for TypeScript. ```bash npm i express @types/express --save ``` -------------------------------- ### Install SQLite driver Source: https://github.com/n8n-io/typeorm/blob/master/README.md Installs the SQLite database driver for TypeORM. ```bash npm install sqlite3 --save ``` -------------------------------- ### MySQL Data Source Options Example Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-options.md Example configuration for a MySQL data source, including connection details, logging, synchronization, and entity/subscriber/migration paths. ```typescript { host: "localhost", port: 3306, username: "test", password: "test", database: "test", logging: true, synchronize: true, entities: [ "entity/*.js" ], subscribers: [ "subscriber/*.js" ], entitySchemas: [ "schema/*.json" ], migrations: [ "migration/*.js" ] } ``` -------------------------------- ### Install TypeORM and MySQL Driver Source: https://github.com/n8n-io/typeorm/blob/master/docs/example-with-express.md Install the necessary packages for TypeORM, the MySQL driver, and reflect-metadata for decorator support. ```bash npm i typeorm mysql reflect-metadata --save ``` -------------------------------- ### Setting up Sequelize Data Source Source: https://github.com/n8n-io/typeorm/blob/master/docs/sequelize-migration.md Demonstrates how to initialize a data source using Sequelize. Requires Sequelize to be installed. ```javascript const sequelize = new Sequelize("database", "username", "password", { host: "localhost", dialect: "mysql", }) sequelize .authenticate() .then(() => { console.log("Data Source has been initialized successfully.") }) .catch((err) => { console.error("Error during Data Source initialization:", err) }) ``` -------------------------------- ### Complete Find Options Example Source: https://github.com/n8n-io/typeorm/blob/master/docs/find-options.md A comprehensive example showcasing various find options: select, relations, where, order, skip, take, and cache. ```typescript userRepository.find({ select: { firstName: true, lastName: true, }, relations: { profile: true, photos: true, videos: true, }, where: { firstName: "Timber", lastName: "Saw", profile: { userName: "tshaw", }, }, order: { name: "ASC", id: "DESC", }, skip: 5, take: 10, cache: true, }) ``` -------------------------------- ### Install NPM Dependencies Source: https://github.com/n8n-io/typeorm/blob/master/DEVELOPER.md Install all necessary Node.js dependencies for TypeORM development. This command should be run after cloning the repository. ```shell npm install ``` -------------------------------- ### Initialize TypeScript Project Source: https://github.com/n8n-io/typeorm/blob/master/docs/example-with-express.md Basic commands to create a new Node.js project, install TypeScript, and configure the tsconfig.json file. ```bash mkdir user cd user npm init npm i typescript --save-dev ``` -------------------------------- ### Install MySQL/MariaDB driver Source: https://github.com/n8n-io/typeorm/blob/master/README.md Installs the MySQL database driver for TypeORM. You can use 'mysql' or 'mysql2'. ```bash npm install mysql --save ``` -------------------------------- ### Setting up TypeORM Data Source Source: https://github.com/n8n-io/typeorm/blob/master/docs/sequelize-migration.md Illustrates TypeORM's approach to initializing a data source. Requires TypeORM and its relevant driver to be installed. ```typescript import { DataSource } from "typeorm" const dataSource = new DataSource({ type: "mysql", host: "localhost", username: "username", password: "password", }) dataSource .initialize() .then(() => { console.log("Data Source has been initialized successfully.") }) .catch((err) => { console.error("Error during Data Source initialization:", err) }) ``` -------------------------------- ### Browser DataSource Configuration Source: https://github.com/n8n-io/typeorm/blob/master/docs/supported-platforms.md Example of configuring a DataSource for browser environments using sql.js. ```typescript new DataSource({ type: "sqljs", entities: [Photo], synchronize: true, }) ``` -------------------------------- ### Express Application Setup with Routes Source: https://github.com/n8n-io/typeorm/blob/master/docs/example-with-express.md Sets up an Express application, defines middleware, and registers basic CRUD routes for users. ```typescript import * as express from "express" import { Request, Response } from "express" // create and setup express app const app = express() app.use(express.json()) // register routes app.get("/users", function (req: Request, res: Response) { // here we will have logic to return all users }) app.get("/users/:id", function (req: Request, res: Response) { // here we will have logic to return user by id }) app.post("/users", function (req: Request, res: Response) { // here we will have logic to save a user }) app.put("/users/:id", function (req: Request, res: Response) { // here we will have logic to update a user by a given user id }) app.delete("/users/:id", function (req: Request, res: Response) { // here we will have logic to delete a user by a given user id }) // start express server app.listen(3000) ``` -------------------------------- ### Install PostgreSQL driver Source: https://github.com/n8n-io/typeorm/blob/master/README.md Installs the PostgreSQL database driver for TypeORM. This driver is also used for CockroachDB. ```bash npm install pg --save ``` -------------------------------- ### Install reflect-metadata shim Source: https://github.com/n8n-io/typeorm/blob/master/README.md Installs the reflect-metadata package, which is required for TypeORM decorators. Import it globally in your application's entry point. ```bash npm install reflect-metadata --save ``` -------------------------------- ### Basic Application Endpoint Source: https://github.com/n8n-io/typeorm/blob/master/docs/example-with-express.md A simple 'app.ts' file with a console log to verify the application setup. ```typescript console.log("Application is up and running") ``` -------------------------------- ### Install Node.js typings Source: https://github.com/n8n-io/typeorm/blob/master/README.md Installs TypeScript typings for Node.js, which may be required for certain Node.js APIs used with TypeORM. ```bash npm install @types/node --save-dev ``` -------------------------------- ### Install TypeORM npm package Source: https://github.com/n8n-io/typeorm/blob/master/README.md Installs the TypeORM npm package. Use '--save' to add it to your project's dependencies. ```bash npm install typeorm --save ``` -------------------------------- ### Initialize Database Connection and Create Table Source: https://github.com/n8n-io/typeorm/blob/master/README.md Running the application initializes the database connection and creates tables based on your entities. This example shows the resulting table structure for 'photo'. ```shell +-------------+--------------+----------------------------+ | photo | +-------------+--------------+----------------------------+ | id | int(11) | PRIMARY KEY AUTO_INCREMENT | | name | varchar(100) | | | description | text | | | filename | varchar(255) | | | views | int(11) | | | isPublished | boolean | | +-------------+--------------+----------------------------+ ``` -------------------------------- ### Accessing and Using a User Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/working-with-repository.md Demonstrates how to get a repository for a specific entity (User) and perform operations like finding a record, updating it, and saving changes. ```typescript import { User } from "./entity/User" const userRepository = dataSource.getRepository(User) const user = await userRepository.findOneBy({ id: 1, }) user.name = "Umed" await userRepository.save(user) ``` -------------------------------- ### Populate and Query View Data Source: https://github.com/n8n-io/typeorm/blob/master/docs/view-entities.md Example of populating the Category and Post tables, then querying the aggregated data from the PostCategory view. ```typescript import { Category } from "./entity/Category" import { Post } from "./entity/Post" import { PostCategory } from "./entity/PostCategory" const category1 = new Category() category1.name = "Cars" await dataSource.manager.save(category1) const category2 = new Category() category2.name = "Airplanes" await dataSource.manager.save(category2) const post1 = new Post() post1.name = "About BMW" post1.categoryId = category1.id await dataSource.manager.save(post1) const post2 = new Post() post2.name = "About Boeing" post2.categoryId = category2.id await dataSource.manager.save(post2) const postCategories = await dataSource.manager.find(PostCategory) const postCategory = await dataSource.manager.findOneBy(PostCategory, { id: 1 }) ``` -------------------------------- ### IORedis Cluster Cache Options Source: https://github.com/n8n-io/typeorm/blob/master/docs/caching.md Example of configuring IORedis cluster cache, showing how to pass options directly to the cluster constructor. ```typescript { ... cache: { type: "ioredis/cluster", ``` -------------------------------- ### InsertQueryBuilder Example Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use InsertQueryBuilder to construct and execute INSERT queries for multiple entities. ```typescript await dataSource .createQueryBuilder() .insert() .into(User) .values([ { firstName: "Timber", lastName: "Saw" }, { firstName: "Phantom", lastName: "Lancer" }, ]) .execute() ``` -------------------------------- ### Example Post Entity Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Defines a simple Post entity with id, title, and text fields. ```typescript import { Entity, Column, PrimaryGeneratedColumn } from "typeorm" @Entity() export class Post { @PrimaryGeneratedColumn() id: number @Column() title: string @Column() text: string } ``` -------------------------------- ### Commit Message Example: Implement New Feature Source: https://github.com/n8n-io/typeorm/blob/master/CONTRIBUTING.md Use this format to introduce new features. The 'feat' type signifies a new feature. ```git feat: implement new magic decorator This new feature change bahviour of typeorm to allow use new magic decorator... Closes: #22222 ``` -------------------------------- ### Pagination with Order, Skip, and Take for MSSQL Source: https://github.com/n8n-io/typeorm/blob/master/docs/find-options.md When using `take` or `limit` with MSSQL, an `order` clause is required to avoid errors. This example demonstrates combining `order`, `skip`, and `take` for paginated queries. ```typescript userRepository.find({ order: { columnName: "ASC", }, skip: 0, take: 10, }) ``` ```sql SELECT * FROM "user" ORDER BY "columnName" ASC LIMIT 10 OFFSET 0 ``` -------------------------------- ### Commit Message Example: Documentation Update Source: https://github.com/n8n-io/typeorm/blob/master/CONTRIBUTING.md Use the 'docs' type for documentation-only changes. ```git docs: update supported mssql column types ``` -------------------------------- ### UpdateQueryBuilder Example Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use UpdateQueryBuilder to construct and execute UPDATE queries, specifying the entity, values, and conditions. ```typescript await dataSource .createQueryBuilder() .update(User) .set({ firstName: "Timber", lastName: "Saw" }) .where("id = :id", { id: 1 }) .execute() ``` -------------------------------- ### Get First 10 Users with Photos Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use `take(10)` to retrieve the first 10 records. This is useful for implementing pagination or limiting results. ```typescript const users = await dataSource .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect("user.photos", "photo") .take(10) .getMany() ``` -------------------------------- ### Query and Insert Data using Schemas Source: https://github.com/n8n-io/typeorm/blob/master/docs/separating-entity-definition.md Example of how to use defined entity schemas with TypeORM repositories to fetch and save data. ```typescript // request data const categoryRepository = dataSource.getRepository(CategoryEntity) const category = await categoryRepository.findOneBy({ id: 1, }) // category is properly typed! // insert a new category into the database const categoryDTO = { // note that the ID is autogenerated; see the schema above name: "new category", } const newCategory = await categoryRepository.save(categoryDTO) ``` -------------------------------- ### Defining a Sequelize Model Source: https://github.com/n8n-io/typeorm/blob/master/docs/sequelize-migration.md Example of defining a 'project' model in Sequelize, including its fields and data types. ```javascript module.exports = function (sequelize, DataTypes) { const Project = sequelize.define("project", { title: DataTypes.STRING, description: DataTypes.TEXT, }) return Project } ``` -------------------------------- ### QueryRunner: Get All Database Names Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Retrieves a list of all available database names, including system databases. Useful for database introspection. ```typescript getDatabases(): Promise ``` -------------------------------- ### Get Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a `Repository` to perform operations on a specific entity. ```APIDOC ## getRepository ### Description Gets `Repository` to perform operations on a specific entity. Learn more about [Repositories](working-with-repository.md). ### Method `getRepository` ### Parameters - `entity` (object | string): The entity for which to get the repository. ### Request Example ```typescript const userRepository = manager.getRepository(User) ``` ``` -------------------------------- ### Get Tree Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a `TreeRepository` to perform operations on a specific entity. ```APIDOC ## getTreeRepository ### Description Gets `TreeRepository` to perform operations on a specific entity. Learn more about [Repositories](working-with-repository.md). ### Method `getTreeRepository` ### Parameters - `entity` (object | string): The entity for which to get the tree repository. ### Request Example ```typescript const categoryRepository = manager.getTreeRepository(Category) ``` ``` -------------------------------- ### Create Distribution Package Source: https://github.com/n8n-io/typeorm/blob/master/RELEASE.md Run this command to create the distribution package for publishing. ```bash npm run package ``` -------------------------------- ### Get Repository with EntityManager Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a `Repository` instance for performing operations on a specific entity. ```typescript const userRepository = manager.getRepository(User) ``` -------------------------------- ### Get Mongo Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a `MongoRepository` to perform operations on a specific entity. Learn more about MongoDB. ```APIDOC ## getMongoRepository ### Description Gets `MongoRepository` to perform operations on a specific entity. Learn more about [MongoDB](./mongodb.md). ### Method `getMongoRepository` ### Parameters - `entity` (object | string): The entity for which to get the mongo repository. ### Request Example ```typescript const userRepository = manager.getMongoRepository(User) ``` ``` -------------------------------- ### Querying Spatial Data with TypeORM Source: https://github.com/n8n-io/typeorm/blob/master/docs/entities.md Examples demonstrating how to use TypeORM's query builder to perform spatial operations, including converting GeoJSON to PostGIS geometries and vice versa. ```typescript import { Point } from "typeorm" const origin: Point = { type: "Point", coordinates: [0, 0], } await dataSource.manager .createQueryBuilder(Thing, "thing") // convert stringified GeoJSON into a geometry with an SRID that matches the // table specification .where( "ST_Distance(geom, ST_SetSRID(ST_GeomFromGeoJSON(:origin), ST_SRID(geom))) > 0", ) .orderBy( "ST_Distance(geom, ST_SetSRID(ST_GeomFromGeoJSON(:origin), ST_SRID(geom)))", "ASC", ) .setParameters({ // stringify GeoJSON origin: JSON.stringify(origin), }) .getMany() await dataSource.manager .createQueryBuilder(Thing, "thing") // convert geometry result into GeoJSON, treated as JSON (so that TypeORM // will know to deserialize it) .select("ST_AsGeoJSON(ST_Buffer(geom, 0.1))::json geom") .from("thing") .getMany() ``` -------------------------------- ### Run All Tests Source: https://github.com/n8n-io/typeorm/blob/master/DEVELOPER.md Execute all tests in the project after setting up the environment configuration. ```shell npm test ``` -------------------------------- ### Get Mongo Repository with EntityManager Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a `MongoRepository` instance for performing operations on a specific entity in a MongoDB database. ```typescript const userRepository = manager.getMongoRepository(User) ``` -------------------------------- ### Create and Initialize MySQL DataSource Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source.md Instantiate a DataSource for MySQL, configure connection details, and initialize the connection. This is typically done once on application bootstrap. ```typescript import { DataSource } from "typeorm" const AppDataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "test", password: "test", database: "test", }) AppDataSource.initialize() .then(() => { console.log("Data Source has been initialized!") }) .catch((err) => { console.error("Error during Data Source initialization", err) }) ``` -------------------------------- ### Create and Initialize DataSource in TypeORM Source: https://github.com/n8n-io/typeorm/blob/master/README.md Set up a DataSource instance to connect to a database. Configure connection details, entities, and synchronization options. Ensure 'reflect-metadata' is imported. ```typescript import "reflect-metadata" import { DataSource } from "typeorm" import { Photo } from "./entity/Photo" const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "root", password: "admin", database: "test", entities: [Photo], synchronize: true, logging: false, }) // to initialize the initial connection with the database, register all entities // and "synchronize" database schema, call "initialize()" method of a newly created database // once in your application bootstrap AppDataSource.initialize() .then(() => { // here you can start to work with your database }) .catch((error) => console.log(error)) ``` -------------------------------- ### Get Custom Repository with Transaction Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a custom repository instance used within a transaction. Learn more about Custom Repositories. ```APIDOC ## withRepository ### Description Gets custom repository instance used in a transaction. Learn more about [Custom repositories](custom-repository.md). ### Method `withRepository` ### Parameters - `repository` (object): The custom repository to get. ### Request Example ```typescript const myUserRepository = manager.withRepository(UserRepository) ``` ``` -------------------------------- ### Get Tree Repository with EntityManager Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a `TreeRepository` instance for performing operations on a specific entity, typically for hierarchical data. ```typescript const categoryRepository = manager.getTreeRepository(Category) ``` -------------------------------- ### SQL Table Structure for User and Photo Entities Source: https://github.com/n8n-io/typeorm/blob/master/docs/many-to-one-one-to-many-relations.md Illustrates the resulting SQL table structures for the `photo` and `user` entities, including primary keys, columns, and foreign key constraints. ```shell +-------------+--------------+----------------------------+ | photo | +-------------+--------------+----------------------------+ | id | int(11) | PRIMARY KEY AUTO_INCREMENT | | url | varchar(255) | | | userId | int(11) | FOREIGN KEY | +-------------+--------------+----------------------------+ +-------------+--------------+----------------------------+ | user | +-------------+--------------+----------------------------+ | id | int(11) | PRIMARY KEY AUTO_INCREMENT | | name | varchar(255) | | +-------------+--------------+----------------------------+ ``` -------------------------------- ### Get Custom Repository with EntityManager Source: https://github.com/n8n-io/typeorm/blob/master/docs/entity-manager-api.md Gets a custom repository instance, often used within transactions. Refer to Custom repositories documentation for more details. ```typescript const myUserRepository = manager.withRepository(UserRepository) ``` -------------------------------- ### Build TypeORM Distribution Package as TGZ Source: https://github.com/n8n-io/typeorm/blob/master/DEVELOPER.md Generate a distribution package of TypeORM as a .tgz file in the 'build' directory. This tarball can be installed in your project using 'npm install'. ```shell npm run pack ``` -------------------------------- ### Load Photos with Various Criteria using Repository Source: https://github.com/n8n-io/typeorm/blob/master/README.md Demonstrates multiple ways to load Photo entities using the Repository, including finding all, finding one by criteria, finding multiple by criteria, and finding with a count. ```typescript import { Photo } from "./entity/Photo" import { AppDataSource } from "./index" const photoRepository = AppDataSource.getRepository(Photo) const allPhotos = await photoRepository.find() console.log("All photos from the db: ", allPhotos) const firstPhoto = await photoRepository.findOneBy({ id: 1, }) console.log("First photo from the db: ", firstPhoto) const meAndBearsPhoto = await photoRepository.findOneBy({ name: "Me and Bears", }) console.log("Me and Bears photo from the db: ", meAndBearsPhoto) const allViewedPhotos = await photoRepository.findBy({ views: 1 }) console.log("All viewed photos: ", allViewedPhotos) const allPublishedPhotos = await photoRepository.findBy({ isPublished: true }) console.log("All published photos: ", allPublishedPhotos) const [photos, photosCount] = await photoRepository.findAndCount() console.log("All photos: ", photos) console.log("Photos count: ", photosCount) ``` -------------------------------- ### Save User and Associated Photos (Method 2) Source: https://github.com/n8n-io/typeorm/blob/master/docs/many-to-one-one-to-many-relations.md Demonstrates saving a user and its associated photos by first saving the user, then creating photos and assigning the user to them before saving the photos. ```typescript const user = new User() user.name = "Leo" await dataSource.manager.save(user) const photo1 = new Photo() photo1.url = "me.jpg" photo1.user = user await dataSource.manager.save(photo1) const photo2 = new Photo() photo2.url = "me-and-bears.jpg" photo2.user = user await dataSource.manager.save(photo2) ``` -------------------------------- ### getId Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Gets the primary column property values of the given entity. ```APIDOC ## `getId` Gets the primary column property values of the given entity. If entity has composite primary keys then the returned value will be an object with names and values of primary columns. ### Method ```typescript repository.getId(entity: object): any ``` ### Parameters - **entity** (object) - Required - The entity to get the ID from. ### Request Example ```typescript const userId = repository.getId(user) // userId === 1 ``` ``` -------------------------------- ### RelationQueryBuilder Example Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use RelationQueryBuilder for relation-specific operations, such as loading related entities. ```typescript await dataSource .createQueryBuilder() .relation(User,"photos") .of(id) .loadMany(); ``` -------------------------------- ### Initialize New TypeORM Project with CLI Source: https://github.com/n8n-io/typeorm/blob/master/README.md Use this command to generate a new TypeORM project. Specify the project name and the desired database type. This command is intended for NodeJS applications. ```shell npx typeorm init --name MyProject --database postgres ``` -------------------------------- ### Generate TypeORM Project with Express Source: https://github.com/n8n-io/typeorm/blob/master/README.md Initialize a TypeORM project with Express framework pre-installed by adding the `--express` flag to the init command. ```shell npx typeorm init --name MyProject --database mysql --express ``` -------------------------------- ### Access Underlying Database Driver Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Get the underlying database driver used by this DataSource. ```typescript const driver: Driver = dataSource.driver ``` -------------------------------- ### Save User and Associated Photos (Method 1) Source: https://github.com/n8n-io/typeorm/blob/master/docs/many-to-one-one-to-many-relations.md Demonstrates saving a user and its associated photos by first saving the photos and then assigning them to the user before saving the user. ```typescript const photo1 = new Photo() photo1.url = "me.jpg" await dataSource.manager.save(photo1) const photo2 = new Photo() photo2.url = "me-and-bears.jpg" await dataSource.manager.save(photo2) const user = new User() user.name = "John" user.photos = [photo1, photo2] await dataSource.manager.save(user) ``` -------------------------------- ### Create New Migration using CLI Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Command to generate a new migration file with the specified name. ```bash typeorm migration:create ./path-to-migrations-dir/PostRefactoring ``` -------------------------------- ### Access Model Properties in Sequelize Source: https://github.com/n8n-io/typeorm/blob/master/docs/sequelize-migration.md Use the `get()` method to access model properties in Sequelize. ```typescript console.log(employee.get("name")) ``` -------------------------------- ### DeleteQueryBuilder Example Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use DeleteQueryBuilder to construct and execute DELETE queries, specifying the entity and conditions. ```typescript await dataSource .createQueryBuilder() .delete() .from(User) .where("id = :id", { id: 1 }) .execute() ``` -------------------------------- ### create Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Creates a new instance of an entity, optionally initializing it with given properties. ```APIDOC ## `create` Creates a new instance of an entity. Optionally accepts an object literal with entity properties which will be written into the newly created entity object. ### Method ```typescript repository.create(entityLike?: DeepPartial): T ``` ### Parameters - **entityLike** (DeepPartial) - Optional - An object with properties to initialize the new entity. ### Request Example ```typescript const user = repository.create() // same as const user = new User(); const user = repository.create({ id: 1, firstName: "Timber", lastName: "Saw", }) // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw"; ``` ``` -------------------------------- ### Initialize DataSource Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Initializes the DataSource and opens a connection pool to the database. ```typescript await dataSource.initialize() ``` -------------------------------- ### Define and Use a Basic Custom Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/custom-repository.md Assign a repository instance to a globally exported variable for app-wide access. This is a common practice for simple repository usage. ```typescript export const UserRepository = dataSource.getRepository(User) export class UserController { users() { return UserRepository.find() } } ``` -------------------------------- ### Configure Read/Write Replication Source: https://github.com/n8n-io/typeorm/blob/master/docs/multiple-data-sources.md Set up replication options for a data source to enable read/write splitting. Queries will be distributed between master and slave instances. ```typescript const datasource = new DataSource({ type: "mysql", logging: true, replication: { master: { host: "server1", port: 3306, username: "test", password: "test", database: "test" }, slaves: [ { host: "server2", port: 3306, username: "test", password: "test", database: "test" }, { host: "server3", port: 3306, username: "test", password: "test", database: "test" } ] } }); ``` -------------------------------- ### Create, Insert, and Load Photos using Repository Source: https://github.com/n8n-io/typeorm/blob/master/README.md Refactors the creation and saving of a Photo entity to use the Repository pattern. It also demonstrates loading all saved photos using the repository's 'find' method. ```typescript import { Photo } from "./entity/Photo" import { AppDataSource } from "./index" const photo = new Photo() photo.name = "Me and Bears" photo.description = "I am near polar bears" photo.filename = "photo-with-bears.jpg" photo.views = 1 photo.isPublished = true const photoRepository = AppDataSource.getRepository(Photo) await photoRepository.save(photo) console.log("Photo has been saved") const savedPhotos = await photoRepository.find() console.log("All photos from the db: ", savedPhotos) ``` -------------------------------- ### Get Single Entity or Fail using getOneOrFail Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Retrieve a single entity, throwing an EntityNotFoundError if no result is found. ```typescript const timber = await dataSource .getRepository(User) .createQueryBuilder("user") .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" }) .getOneOrFail() ``` -------------------------------- ### Create and Use QueryRunner Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Instantiate a query runner to manage a single database connection. Remember to connect before use and release when finished. ```typescript const queryRunner = dataSource.createQueryRunner() // you can use its methods only after you call connect // which performs real database connection await queryRunner.connect() // .. now you can work with query runner and call its methods // very important - don't forget to release query runner once you finished working with it await queryRunner.release() ``` -------------------------------- ### Get Repository for Entity Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Retrieves the Repository for a given entity. Can also specify a table name. Learn more about Repositories. ```typescript const repository = dataSource.getRepository(User) // now you can call repository methods, for example find: const users = await repository.find() ``` -------------------------------- ### PostgreSQL Data Source Options Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-options.md Configure connection details, SSL, extensions, and transaction retries for PostgreSQL. Options like `url`, `host`, `port`, `username`, `password`, `database`, `schema`, `connectTimeoutMS`, `ssl`, `uuidExtension`, `poolErrorHandler`, `maxTransactionRetries`, `logNotifications`, `installExtensions`, `applicationName`, and `parseInt8` are available. -------------------------------- ### Get Generated SQL Query Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use `getSql` to retrieve the SQL query string generated by the QueryBuilder for debugging or inspection. ```typescript const sql = createQueryBuilder("user") .where("user.firstName = :firstName", { firstName: "Timber" }) .orWhere("user.lastName = :lastName", { lastName: "Saw" }) .getSql() ``` -------------------------------- ### Access Repository Target Entity Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Get the target entity class managed by this repository. This is used in transactional instances of EntityManager. ```typescript const target = repository.target ``` -------------------------------- ### Access Repository Query Runner Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Get the query runner instance used by the EntityManager. This is typically used in transactional contexts. ```typescript const queryRunner = repository.queryRunner ``` -------------------------------- ### Basic User Selection with QueryBuilder Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Demonstrates how to select a single user by ID using the QueryBuilder. It shows the SQL query generated and the resulting entity. ```typescript const firstUser = await dataSource .getRepository(User) .createQueryBuilder("user") .where("user.id = :id", { id: 1 }) .getOne() ``` ```sql SELECT user.id as userId, user.firstName as userFirstName, user.lastName as userLastName FROM users user WHERE user.id = 1 ``` ```javascript User { id: 1, firstName: "Timber", lastName: "Saw" } ``` -------------------------------- ### Basic Find Options with Lock Source: https://github.com/n8n-io/typeorm/blob/master/docs/find-options.md Demonstrates basic find options including a lock mode. Refer to lock modes documentation for more details. ```typescript userRepository.find({ where: { id: 1, }, lock: { mode: "optimistic", version: 1 }, }) ``` -------------------------------- ### Get Tree Repository for Entity Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Retrieves the TreeRepository for a given entity. Can also specify a table name. Learn more about Repositories. ```typescript const repository = dataSource.getTreeRepository(Category) // now you can call tree repository methods, for example findTrees: const categories = await repository.findTrees() ``` -------------------------------- ### Generate TypeORM Project with Docker Support Source: https://github.com/n8n-io/typeorm/blob/master/README.md To include a docker-compose file for easier containerized deployment, use the `--docker` flag when initializing your TypeORM project. ```shell npx typeorm init --name MyProject --database postgres --docker ``` -------------------------------- ### Get Entity Metadata Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Retrieves the EntityMetadata for a given entity. Can also specify a table name. Learn more about Entity Metadata. ```typescript const userMetadata = dataSource.getMetadata(User) // now you can get any information about User entity ``` -------------------------------- ### Defining Another Sequelize Model Source: https://github.com/n8n-io/typeorm/blob/master/docs/sequelize-migration.md Example of defining a 'task' model in Sequelize, including string, text, and date fields. ```javascript module.exports = function (sequelize, DataTypes) { const Task = sequelize.define("task", { title: DataTypes.STRING, description: DataTypes.TEXT, deadline: DataTypes.DATE, }) return Task } ``` -------------------------------- ### QueryRunner: Create Database Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Creates a new database with the specified name. Optionally skips creation if the database already exists. ```typescript createDatabase(database: string, ifNotExist?: boolean): Promise ``` -------------------------------- ### Load Relations from Both Sides with QueryBuilder Source: https://github.com/n8n-io/typeorm/blob/master/docs/many-to-many-relations.md Demonstrates loading relations from the `Category` side using `QueryBuilder` in a bidirectional many-to-many setup. ```typescript const categoriesWithQuestions = await dataSource .getRepository(Category) .createQueryBuilder("category") .leftJoinAndSelect("category.questions", "question") .getMany() ``` -------------------------------- ### Table and Index Creation/Dropping Methods Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Methods for creating and dropping tables and indexes. ```APIDOC ## `createTable(table: Table, ifNotExist?: boolean, columns?: TableColumn[], indices?: TableIndex[])` ### Description Creates a new table. Optionally, it can create the table only if it does not exist, and can also create initial columns and indices. ### Parameters - `table` (Table) - The Table object representing the table to create. - `ifNotExist` (boolean) - Optional. If true, skips creation if the table already exists. - `columns` (TableColumn[]) - Optional. An array of TableColumn objects for initial columns. - `indices` (TableIndex[]) - Optional. An array of TableIndex objects for initial indices. ### Method `createTable(table: Table, ifNotExist?: boolean, columns?: TableColumn[], indices?: TableIndex[]): Promise` ## `dropTable(table: Table|string, ifExist?: boolean, dropEnlistedColumns?: boolean)` ### Description Drops a table. Optionally, it can drop the table only if it exists, and can also drop columns that were previously enlisted. ### Parameters - `table` (Table|string) - The Table object or name of the table to drop. - `ifExist` (boolean) - Optional. If true, skips deletion if the table was not found. - `dropEnlistedColumns` (boolean) - Optional. If true, drops columns that were previously enlisted. ### Method `dropTable(table: Table|string, ifExist?: boolean, dropEnlistedColumns?: boolean): Promise` ## `createIndex(index: TableIndex)` ### Description Creates a new index on a table. ### Parameters - `index` (TableIndex) - The TableIndex object representing the index to create. ### Method `createIndex(index: TableIndex): Promise` ## `dropIndex(index: TableIndex|string)` ### Description Drops an index from a table. ### Parameters - `index` (TableIndex|string) - The TableIndex object or name of the index to drop. ### Method `dropIndex(index: TableIndex|string): Promise` ``` -------------------------------- ### Create a new QueryRunner instance Source: https://github.com/n8n-io/typeorm/blob/master/docs/query-runner.md Instantiate a new QueryRunner using the `createQueryRunner` method on your DataSource. This prepares a query runner but does not yet acquire a connection. ```typescript const queryRunner = dataSource.createQueryRunner() ``` -------------------------------- ### Get Memorized SQL Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Retrieves the SQL statements stored in memory, including both `upQueries` and `downQueries`. Parameters in the SQL are already replaced. ```typescript getMemorySql(): SqlInMemory ``` -------------------------------- ### Stream Raw Result Data Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use `stream` to get a stream of raw data. Entity transformation must be handled manually. ```typescript const stream = await dataSource .getRepository(User) .createQueryBuilder("user") .where("user.id = :id", { id: 1 }) .stream() ``` -------------------------------- ### preload Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Creates a new entity from a plain object, loading it from the database if it exists and updating its properties. ```APIDOC ## `preload` Creates a new entity from the given plain javascript object. If the entity already exists in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object, and returns the new entity. The new entity is actually an entity loaded from the database with all properties replaced from the new object.
Note that given entity-like object must have an entity id / primary key to find entity by. Returns undefined if entity with given id was not found. ### Method ```typescript repository.preload(entityLike: DeepPartial): Promise ``` ### Parameters - **entityLike** (DeepPartial) - Required - An object with properties to preload the entity. ### Request Example ```typescript const partialUser = { id: 1, firstName: "Rizzrak", profile: { id: 1, }, } const user = await repository.preload(partialUser) // user will contain all missing data from partialUser with partialUser property values: // { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } } ``` ``` -------------------------------- ### Get Count using getCount Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Retrieve the total number of rows matching the query criteria using getCount, returning a number. ```typescript const count = await dataSource .getRepository(User) .createQueryBuilder("user") .where("user.name = :name", { name: "Timber" }) .getCount() ``` -------------------------------- ### Create ormconfig.json Source: https://github.com/n8n-io/typeorm/blob/master/DEVELOPER.md Create an initial ormconfig.json file by copying the distribution file. This configuration file is used by TypeORM to connect to databases. ```shell cp ormconfig.json.dist ormconfig.json ``` -------------------------------- ### Get Entity ID Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Retrieve the primary column property values for a given entity. For composite primary keys, this returns an object. ```typescript const userId = repository.getId(user) // userId === 1 ``` -------------------------------- ### Database Schema for One-to-One Relation Source: https://github.com/n8n-io/typeorm/blob/master/docs/one-to-one-relations.md Illustrates the resulting database table structures for the User and Profile entities after defining a one-to-one relationship with @JoinColumn on the User side. ```shell +-------------+--------------+----------------------------+ | profile | +-------------+--------------+----------------------------+ | id | int(11) | PRIMARY KEY AUTO_INCREMENT | | gender | varchar(255) | | | photo | varchar(255) | | +-------------+--------------+----------------------------+ +-------------+--------------+----------------------------+ | user | +-------------+--------------+----------------------------+ | id | int(11) | PRIMARY KEY AUTO_INCREMENT | | name | varchar(255) | | | profileId | int(11) | FOREIGN KEY | +-------------+--------------+----------------------------+ ``` -------------------------------- ### Create and Save New Model in TypeORM (Repository Pattern) Source: https://github.com/n8n-io/typeorm/blob/master/docs/sequelize-migration.md Instantiate a new model, set its properties, and save it using the repository in TypeORM. ```typescript const employee = new Employee() // you can use constructor parameters as well employee.name = "John Doe" employee.title = "senior engineer" await dataSource.getRepository(Employee).save(employee) ``` -------------------------------- ### Run Migrations Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Runs all pending database migrations. ```typescript await dataSource.runMigrations() ``` -------------------------------- ### Get Memory SQL Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Retrieves the SQL statements stored in memory, with parameters already replaced. Returns an object containing `upQueries` and `downQueries`. ```APIDOC ## getMemorySql ### Description Gets the SQL statements stored in memory. ### Returns - `SqlInMemory` - An object containing `upQueries` and `downQueries` arrays of SQL statements. ``` -------------------------------- ### Create Multiple Data Sources Source: https://github.com/n8n-io/typeorm/blob/master/docs/multiple-data-sources.md Instantiate multiple DataSource objects to connect to different databases. Ensure each DataSource is configured with its specific connection details. ```typescript import { DataSource } from "typeorm" const db1DataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "admin", database: "db1", entities: [__dirname + "/entity/*{.js,.ts}"], synchronize: true, }) const db2DataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "admin", database: "db2", entities: [__dirname + "/entity/*{.js,.ts}"], synchronize: true, }) ``` -------------------------------- ### Find and Count Entities with Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Use `findAndCount` to retrieve entities matching specific criteria and get the total count, ignoring pagination. ```typescript const [timbers, timbersCount] = await repository.findAndCount({ where: { firstName: "Timber", }, }) ``` -------------------------------- ### Configure TypeORM Data Source Source: https://github.com/n8n-io/typeorm/blob/master/docs/example-with-express.md Set up the TypeORM DataSource with connection details and entity configurations for a MySQL database. ```typescript import { DataSource } from "typeorm" export const myDataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "test", password: "test", database: "test", entities: ["src/entity/*.js"], logging: true, synchronize: true, }) ``` -------------------------------- ### Print Generated SQL and Get Entities Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use `printSql` to log the generated SQL statement to the console while executing the query and fetching entities. ```typescript const users = await createQueryBuilder("user") .where("user.firstName = :firstName", { firstName: "Timber" }) .orWhere("user.lastName = :lastName", { lastName: "Saw" }) .printSql() .getMany() ``` -------------------------------- ### TypeORM Migration with QueryRunner API Source: https://github.com/n8n-io/typeorm/blob/master/docs/migrations.md Demonstrates creating and modifying database schema using the QueryRunner API within a TypeORM migration. Includes creating tables, indexes, columns, and foreign keys, as well as their corresponding down methods for rollback. ```typescript import { MigrationInterface, QueryRunner, Table, TableIndex, TableColumn, TableForeignKey, } from "typeorm" export class QuestionRefactoringTIMESTAMP implements MigrationInterface { async up(queryRunner: QueryRunner): Promise { await queryRunner.createTable( new Table({ name: "question", columns: [ { name: "id", type: "int", isPrimary: true, }, { name: "name", type: "varchar", }, ], }), true, ) await queryRunner.createIndex( "question", new TableIndex({ name: "IDX_QUESTION_NAME", columnNames: ["name"], }), ) await queryRunner.createTable( new Table({ name: "answer", columns: [ { name: "id", type: "int", isPrimary: true, }, { name: "name", type: "varchar", }, { name: "created_at", type: "timestamp", default: "now()", }, ], }), true, ) await queryRunner.addColumn( "answer", new TableColumn({ name: "questionId", type: "int", }), ) await queryRunner.createForeignKey( "answer", new TableForeignKey({ columnNames: ["questionId"], referencedColumnNames: ["id"], referencedTableName: "question", onDelete: "CASCADE", }), ) } async down(queryRunner: QueryRunner): Promise { const table = await queryRunner.getTable("answer") const foreignKey = table.foreignKeys.find( (fk) => fk.columnNames.indexOf("questionId") !== -1, ) await queryRunner.dropForeignKey("answer", foreignKey) await queryRunner.dropColumn("answer", "questionId") await queryRunner.dropTable("answer") await queryRunner.dropIndex("question", "IDX_QUESTION_NAME") await queryRunner.dropTable("question") } } ``` -------------------------------- ### Get Raw Data using getRawMany Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Retrieve multiple raw data results, useful for aggregated data across multiple groups. ```typescript const photosSums = await dataSource .getRepository(User) .createQueryBuilder("user") .select("user.id") .addSelect("SUM(user.photosCount)", "sum") .groupBy("user.id") .getRawMany() ``` -------------------------------- ### DataSource Initialization and Destruction Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Methods for initializing the DataSource connection and destroying it when no longer needed. ```APIDOC ## DataSource Initialization and Destruction ### Description Methods to manage the lifecycle of the DataSource, including establishing a connection and closing it. ### Methods - **initialize()** - Initializes data source and opens connection pool to the database. - **destroy()** - Destroys the DataSource and closes all database connections. Usually, you call this method when your application is shutting down. ``` -------------------------------- ### User Domain Logic with Repository Pattern Source: https://github.com/n8n-io/typeorm/blob/master/README.md Demonstrates creating, saving, finding, and removing User entities using the TypeORM repository pattern. Requires a configured DataSource (MyDataSource) and the User entity. ```typescript const userRepository = MyDataSource.getRepository(User) const user = new User() user.firstName = "Timber" user.lastName = "Saw" user.age = 25 await userRepository.save(user) const allUsers = await userRepository.find() const firstUser = await userRepository.findOneBy({ id: 1, }) // find by id const timber = await userRepository.findOneBy({ firstName: "Timber", lastName: "Saw", }) // find by firstName and lastName await userRepository.remove(timber) ``` -------------------------------- ### Get Single Entity using getOne Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Retrieve a single entity from the database using the getOne method, suitable for fetching by ID or name. ```typescript const timber = await dataSource .getRepository(User) .createQueryBuilder("user") .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" }) .getOne() ``` -------------------------------- ### Get Mongo Repository for Entity Source: https://github.com/n8n-io/typeorm/blob/master/docs/data-source-api.md Retrieves the MongoRepository for a given entity, used for entities in a MongoDB data source. Learn more about MongoDB support. ```typescript const repository = dataSource.getMongoRepository(User) // now you can call mongodb-specific repository methods, for example createEntityCursor: const categoryCursor = repository.createEntityCursor() const category1 = await categoryCursor.next() const category2 = await categoryCursor.next() ``` -------------------------------- ### Create Query Builder Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Instantiate a QueryBuilder to construct SQL queries. Learn more about QueryBuilder. ```typescript const users = await repository .createQueryBuilder("user") .where("user.name = :name", { name: "John" }) .getMany() ``` -------------------------------- ### Find and Count Entities by Criteria with Repository Source: https://github.com/n8n-io/typeorm/blob/master/docs/repository-api.md Use `findAndCountBy` for a concise way to find entities matching `FindOptionsWhere` and get their count, ignoring pagination. ```typescript const [timbers, timbersCount] = await repository.findAndCountBy({ firstName: "Timber", }) ``` -------------------------------- ### Enable All Logging Types Source: https://github.com/n8n-io/typeorm/blob/master/docs/logging.md A shorthand to enable all available logging types by setting `logging` to the string "all". ```typescript { host: "localhost", ... logging: "all" } ``` -------------------------------- ### Get Users Skipping First 10 Source: https://github.com/n8n-io/typeorm/blob/master/docs/select-query-builder.md Use `skip(10)` to exclude the first 10 records from the result set. This is commonly used for pagination. ```typescript const users = await dataSource .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect("user.photos", "photo") .skip(10) .getMany() ```