docs: separate driver-specific documentation (#11581)

This commit is contained in:
Lucian Mocanu 2025-07-28 10:28:51 +02:00 committed by GitHub
parent d57fe3bd85
commit 23fcde24ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
42 changed files with 1578 additions and 2674 deletions

View File

@ -1,5 +1,5 @@
{
"[json][jsonc][javascript][markdown][typescript][yaml]": {
"[css][javascript][json][jsonc][markdown][typescript][typescriptreact][yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.formatOnSave": true,

View File

@ -1,34 +1,31 @@
<div align="center">
<a href="http://typeorm.io/">
<img src="https://github.com/typeorm/typeorm/raw/master/resources/logo_big.png" width="492" height="228">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/typeorm/typeorm/raw/master/resources/typeorm-logo-colored-light.png">
<source media="(prefers-color-scheme: light)" srcset="https://github.com/typeorm/typeorm/raw/master/resources/typeorm-logo-colored-dark.png">
<img height="80" width="auto" alt="TypeORM Logo" src="https://github.com/typeorm/typeorm/raw/master/resources/typeorm-logo-colored-dark.png">
</picture>
</a>
<br>
<br>
<a href="https://app.circleci.com/pipelines/github/typeorm/typeorm">
<img src="https://circleci.com/gh/typeorm/typeorm/tree/master.svg?style=shield">
</a>
<a href="https://badge.fury.io/js/typeorm">
<img src="https://badge.fury.io/js/typeorm.svg">
</a>
<a href="https://david-dm.org/typeorm/typeorm">
<img src="https://david-dm.org/typeorm/typeorm.svg">
</a>
<a href="https://gitter.im/typeorm/typeorm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge">
<img src="https://badges.gitter.im/typeorm/typeorm.svg">
</a>
<a href="https://www.npmjs.com/package/typeorm"><img src="https://img.shields.io/npm/v/typeorm" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/package/typeorm"><img src="https://img.shields.io/npm/dm/typeorm" alt="NPM Downloads" /></a>
<a href="https://github.com/typeorm/typeorm/actions/workflows/commit-validation.yml?query=branch%3Amaster"><img src="https://github.com/typeorm/typeorm/actions/workflows/commit-validation.yml/badge.svg?branch=master" alt="Commit Validation"/></a>
<a href="https://coveralls.io/github/typeorm/typeorm?branch=master"><img src="https://coveralls.io/repos/github/typeorm/typeorm/badge.svg?branch=master" alt="Coverage Status" /></a>
<a href=""><img src="https://img.shields.io/badge/License-MIT-teal.svg" alt="MIT License" /></a>
<br>
<br>
</div>
TypeORM 是一个 [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) 框架,它可以运行在 NodeJS、Browser、Cordova、PhoneGap、Ionic、React Native、Expo 和 Electron 平台上,可以与 TypeScript 和 JavaScript (ES2021)一起使用。 它的目标是始终支持最新的 JavaScript 特性并提供额外的特性以帮助你开发任何使用数据库的(不管是只有几张表的小型应用还是拥有多数据库的大型企业应用)应用程序。
TypeORM 是一个 [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) 框架,它可以运行在 NodeJS、Browser、Cordova、Ionic、React Native、Expo 和 Electron 平台上,可以与 TypeScript 和 JavaScript (ES2021)一起使用。 它的目标是始终支持最新的 JavaScript 特性并提供额外的特性以帮助你开发任何使用数据库的(不管是只有几张表的小型应用还是拥有多数据库的大型企业应用)应用程序。
不同于现有的所有其他 JavaScript ORM 框架TypeORM 支持 [Data Mapper](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) 和 [Active Record](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) 模式,这意味着你可以以最高效的方式编写高质量的、松耦合的、可扩展的、可维护的应用程序。
不同于现有的所有其他 JavaScript ORM 框架TypeORM 支持 [Active Record](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) 和 [Data Mapper](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) 模式,这意味着你可以以最高效的方式编写高质量的、松耦合的、可扩展的、可维护的应用程序。
TypeORM 参考了很多其他优秀 ORM 的实现, 比如 [Hibernate](http://hibernate.org/orm/), [Doctrine](http://www.doctrine-project.org/) 和 [Entity Framework](https://www.asp.net/entity-framework)。
TypeORM 的一些特性:
- 同时支持 [DataMapper](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) 和 [ActiveRecord](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) (随你选择)
- 同时支持 [Active Record](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) 和 [Data Mapper](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) (随你选择)
- 实体和列
- 数据库特性列类型
- 实体管理
@ -149,11 +146,11 @@ await timber.remove()
1. 通过 `npm` 安装:
`npm install typeorm --save`
`npm install typeorm`
2. 你还需要安装 `reflect-metadata`:
`npm install reflect-metadata --save`
`npm install reflect-metadata`
并且需要在应用程序的全局位置导入(例如在`app.ts`中)
@ -161,52 +158,54 @@ await timber.remove()
3. 你可能还需要安装 node typings(以此来使用 Node 的智能提示):
`npm install @types/node --save`
`npm install @types/node --save-dev`
4. 安装数据库驱动:
- **MySQL** 或者 **MariaDB**
`npm install mysql --save` (也可以安装 `mysql2`)
`npm install mysql` (也可以安装 `mysql2`)
- **PostgreSQL**
`npm install pg --save`
`npm install pg`
- **SQLite**
`npm install sqlite3 --save`
`npm install sqlite3`
- **Better SQLite**
`npm install better-sqlite3`
- **Microsoft SQL Server**
`npm install mssql --save`
`npm install mssql`
- **sql.js**
`npm install sql.js --save`
`npm install sql.js`
- **Oracle**
`npm install oracledb --save`
`npm install oracledb`
根据你使用的数据库,仅安装其中*一个*即可。
要使 Oracle 驱动程序正常工作,需要按照其[站点](https://github.com/oracle/node-oracledb)中的安装说明进行操作。
- **SAP Hana**
`npm i @sap/hana-client`
- **MongoDB** (试验性)
`npm install mongodb --save`
`npm install mongodb`
- **NativeScript**, **react-native** 和 **Cordova**
- **NativeScript**, **React Native**, **Cordova** 和 **Expo**
查看 [支持的平台](/supported-platforms.md)
- **SAP Hana**
```
npm i @sap/hana-client
```
##### TypeScript 配置
### TypeScript 配置
此外,请确保你使用的 TypeScript 编译器版本是**3.3**或更高版本,并且已经在 `tsconfig.json` 中启用了以下设置:
@ -215,8 +214,6 @@ await timber.remove()
"experimentalDecorators": true,
```
除此之外,你可能还需要在编译器选项的 `lib` 中启用 `es6`,或者安装 `es6-shim``@types`
## 快速开始
快速上手 TypeORM 的方法是使用其 CLI 命令生成启动项目。
@ -224,13 +221,13 @@ await timber.remove()
首先全局安装 TypeORM:
```
```shell
npm install typeorm -g
```
然后转到要创建新项目的目录并运行命令:
```
```shell
typeorm init --name MyProject --database mysql
```
@ -259,9 +256,9 @@ MyProject
接下来安装项目依赖项:
```sh
$ cd MyProject
$ npm install
```shell
cd MyProject
npm install
```
在安装过程中,编辑 `ormconfig.json` 文件并在其中编辑自己的数据库连接配置选项:
@ -286,8 +283,8 @@ $ npm install
完成配置并安装所有 node modules 后,即可运行应用程序:
```sh
$ npm start
```shell
npm start
```
至此你的应用程序应该成功运行并将新用户插入数据库。你可以继续使用此项目并集成所需的其他模块并创建更多实体。
@ -323,7 +320,7 @@ export class Photo {
让我们将 `Photo` 模型作为一个实体
```ts
```typescript
import { Entity } from "typeorm"
@Entity()
@ -344,7 +341,7 @@ export class Photo {
要添加数据库列,你只需要将要生成的实体属性加上 `@Column` 装饰器。
```ts
```typescript
import { Entity, Column } from "typeorm"
@Entity()
@ -378,7 +375,7 @@ export class Photo {
每个**必须**至少有一个主键列。这是必须的,你无法避免。要使列成为主键,你需要使用 `@PrimaryColumn` 装饰器。
```ts
```typescript
import { Entity, Column, PrimaryColumn } from "typeorm"
@Entity()
@ -464,7 +461,7 @@ export class Photo {
}
```
列类型是特定于数据库的。你可以设置数据库支持的任何列类型。有关支持的列类型的更多信息,请参见[此处](./docs/docs/Entity/1-entities.md#column-types)。
列类型是特定于数据库的。你可以设置数据库支持的任何列类型。有关支持的列类型的更多信息,请参见[此处](./docs/docs/entity/1-entities.md#column-types)。
### 创建数据库的连接
@ -530,7 +527,7 @@ createConnection({
现在可以启动 `app.ts`,启动后可以发现数据库自动被初始化,并且 Photo 这个表也会创建出来。
```bash
```text
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
@ -613,7 +610,7 @@ createConnection(/*...*/)
`savedPhotos` 是一个 Photo 对象数组,其中包含从数据库加载的数据。
了解更多有关 [EntityManager](./docs/docs/Working%20with%20Entity%20Manager/2-working-with-repository.md) 的信息。
了解更多有关 [EntityManager](./docs/docs/working-with-entity-manager/2-working-with-repository.md) 的信息。
### 使用 Repositories
@ -643,7 +640,7 @@ createConnection(/*...*/)
.catch((error) => console.log(error))
```
了解更多有关 [Repository](./docs/docs/Working%20with%20Entity%20Manager/2-working-with-repository.md) 的信息。
了解更多有关 [Repository](./docs/docs/working-with-entity-manager/2-working-with-repository.md) 的信息。
### 从数据库加载
@ -769,7 +766,7 @@ export class PhotoMetadata {
如果运行该应用程序,你将看到一个新生成的表,它将包含一个带有外键的列:
```bash
```text
+-------------+--------------+----------------------------+
| photo_metadata |
+-------------+--------------+----------------------------+
@ -888,7 +885,7 @@ createConnection(/*...*/)
.catch((error) => console.log(error))
```
photos 包含来自数据库的 photos 数组,每个 photo 包含其 photo metadata。详细了解本文档中的[Find 选项](./docs/docs/Working%20with%20Entity%20Manager/3-find-options.md)。
photos 包含来自数据库的 photos 数组,每个 photo 包含其 photo metadata。详细了解本文档中的[Find 选项](./docs/docs/working-with-entity-manager/3-find-options.md)。
使用 find 选项很简单,但是如果你需要更复杂的查询,则应该使用 `QueryBuilder``QueryBuilder` 使用更优雅的方式执行更复杂的查询:
@ -1008,7 +1005,7 @@ export class Photo {
在多对一/一对多的关系中,拥有方总是多对一的。这意味着使用`@ManyToOne`的类将存储相关对象的 id。
运行应用程序后ORM 将创建`author`表:
```bash
```text
+-------------+--------------+----------------------------+
| author |
+-------------+--------------+----------------------------+
@ -1019,7 +1016,7 @@ export class Photo {
它还将修改`photo`表,添加新的`author`列并为其创建外键:
```bash
```text
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
@ -1074,7 +1071,7 @@ export class Photo {
运行后ORM 将创建**album_photos_photo_albums**\_联结表。
```bash
```text
+-------------+--------------+----------------------------+
| album_photos_photo_albums |
+-------------+--------------+----------------------------+
@ -1161,7 +1158,7 @@ let photos = await connection
此查询选择所有 published 的 name 等于"My"或"Mishka"的 photos。它将从结果中的第 5 个(分页偏移)开始,并且仅选择 10 个结果(分页限制)。得到的结果将按 ID 降序排序。photo 的 albums 将被 left-joined其元数据将被 inner joined。
由于 QueryBuilder 的自由度更高,因此在项目中可能会大量的使用它。
更多关于 QueryBuilder 的信息,[可查看](./docs/docs/Query%20Builder/1-select-query-builder.md)。
更多关于 QueryBuilder 的信息,[可查看](./docs/docs/query-builder/1-select-query-builder.md)。
## 示例
@ -1176,7 +1173,7 @@ let photos = await connection
- [Example how to use Express and TypeORM](https://github.com/typeorm/typescript-express-example)
- [Example how to use Koa and TypeORM](https://github.com/typeorm/typescript-koa-example)
- [Example how to use TypeORM with MongoDB](https://github.com/typeorm/mongo-typescript-example)
- [Example how to use TypeORM in a Cordova/PhoneGap app](https://github.com/typeorm/cordova-example)
- [Example how to use TypeORM in a Cordova app](https://github.com/typeorm/cordova-example)
- [Example how to use TypeORM with an Ionic app](https://github.com/typeorm/ionic-example)
- [Example how to use TypeORM with React Native](https://github.com/typeorm/react-native-example)
- [Example how to use TypeORM with Electron using JavaScript](https://github.com/typeorm/electron-javascript-example)

1125
README.md

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,31 @@
<div align="center"> <a href="http://typeorm.io/"> <img src="https://github.com/typeorm/typeorm/raw/master/resources/logo_big.png" width="492" height="228"> </a> <br> <br> <a href="https://app.circleci.com/pipelines/github/typeorm/typeorm"> <img src="https://circleci.com/gh/typeorm/typeorm/tree/master.svg?style=shield"> </a> <a href="https://badge.fury.io/js/typeorm"> <img src="https://badge.fury.io/js/typeorm.svg"> </a> <a href="https://codecov.io/gh/typeorm/typeorm"> <img src="https://img.shields.io/codecov/c/github/typeorm/typeorm.svg" alt="Codecov"> </a> <img src="https://img.shields.io/badge/chat-on%20slack-blue.svg"> </a> <br> <br>
<div align="center">
<a href="http://typeorm.io/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/typeorm/typeorm/raw/master/resources/typeorm-logo-colored-light.png">
<source media="(prefers-color-scheme: light)" srcset="https://github.com/typeorm/typeorm/raw/master/resources/typeorm-logo-colored-dark.png">
<img height="80" width="auto" alt="TypeORM Logo" src="https://github.com/typeorm/typeorm/raw/master/resources/typeorm-logo-colored-dark.png">
</picture>
</a>
<br>
<br>
<a href="https://www.npmjs.com/package/typeorm"><img src="https://img.shields.io/npm/v/typeorm" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/package/typeorm"><img src="https://img.shields.io/npm/dm/typeorm" alt="NPM Downloads" /></a>
<a href="https://github.com/typeorm/typeorm/actions/workflows/commit-validation.yml?query=branch%3Amaster"><img src="https://github.com/typeorm/typeorm/actions/workflows/commit-validation.yml/badge.svg?branch=master" alt="Commit Validation"/></a>
<a href="https://coveralls.io/github/typeorm/typeorm?branch=master"><img src="https://coveralls.io/repos/github/typeorm/typeorm/badge.svg?branch=master" alt="Coverage Status" /></a>
<a href=""><img src="https://img.shields.io/badge/License-MIT-teal.svg" alt="MIT License" /></a>
<br>
<br>
</div>
TypeORM은 NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo 및 Electron 플랫폼에서 실행할 수 있는 [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)이며 TypeScript 및 JavaScript(ES2021)와 함께 사용할 수 있다. TypeORM의 목표는 항상 최신 JavaScript 기능을 지원하고 몇 개의 테이블이 있는 작은 응용 프로그램에서 여러 데이터베이스가 있는 대규모 엔터프라이즈 응용 프로그램에 이르기까지 데이터베이스를 사용하는 모든 종류의 응용 프로그램을 개발하는 데 도움이 되는 추가 기능을 제공하는 것이다.
TypeORM은 NodeJS, Browser, Cordova, Ionic, React Native, NativeScript, Expo 및 Electron 플랫폼에서 실행할 수 있는 [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)이며 TypeScript 및 JavaScript(ES2021)와 함께 사용할 수 있다. TypeORM의 목표는 항상 최신 JavaScript 기능을 지원하고 몇 개의 테이블이 있는 작은 응용 프로그램에서 여러 데이터베이스가 있는 대규모 엔터프라이즈 응용 프로그램에 이르기까지 데이터베이스를 사용하는 모든 종류의 응용 프로그램을 개발하는 데 도움이 되는 추가 기능을 제공하는 것이다.
TypeORM은 현재 존재하는 다른 모든 JavaScript ORM과 달리 [Active Record](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) 및 [Data Mapper](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) 패턴을 모두 지원한다. 즉, 고품질의 느슨하게 결합된 확장 가능하고 유지 관리 가능한 애플리케이션을 가장 생산적인 방식으로 작성할 수 있다.
TypeORM은 현재 존재하는 다른 모든 JavaScript ORM과 달리 [Active Record](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) 및 [Data Mapper](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) 패턴을 모두 지원한다. 즉, 고품질의 느슨하게 결합된 확장 가능하고 유지 관리 가능한 애플리케이션을 가장 생산적인 방식으로 작성할 수 있다.
TypeORM은 [Hibernate](http://hibernate.org/orm/), [Doctrine](http://www.doctrine-project.org/) 및 [Entity Framework](https://www.asp.net/entity-framework)와 같은 다른 ORM의 영향을 많이 받는다.
## 특징
- [DataMapper](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern)와 [ActiveRecord](./docs/docs/Guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern)을 모두 지원.
- [DataMapper](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern)와 [ActiveRecord](./docs/docs/guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern)을 모두 지원.
- 항목 및 열.
- 데이터베이스 별 열 유형.
- 엔터티 관리자.
@ -130,11 +146,11 @@ await timber.remove()
1. npm 패키지를 설치한다:
`npm install typeorm --save`
`npm install typeorm`
2. `reflect-metadata` 심(shim)을 설치한다:
`npm install reflect-metadata --save`
`npm install reflect-metadata`
그리고 그것을 app (예: `app.ts`)의 전역 위치에 불러와야 한다:
@ -148,47 +164,47 @@ await timber.remove()
- **MySQL** 또는 **MariaDB**의 경우
`npm install mysql --save` (you can install `mysql2` instead as well)
`npm install mysql` / `npm install mysql2`
- for **PostgreSQL**또는 **CockroachDB**의 경우
`npm install pg --save`
`npm install pg`
- **SQLite**의 경우
`npm install sqlite3 --save`
`npm install sqlite3`
- **Better SQLite**의 경우
`npm install better-sqlite3`
- **Microsoft SQL Server**의 경우
`npm install mssql --save`
`npm install mssql`
- **sql.js**의 경우
`npm install sql.js --save`
`npm install sql.js`
- **Oracle**의 경우
`npm install oracledb --save`
`npm install oracledb`
Oracle 드라이버를 작동시키려면 [해당](https://github.com/oracle/node-oracledb) 사이트의 설치 지침을 따라야 한다.
- **SAP Hana**의 경우
```
npm i @sap/hana-client
```
`npm i @sap/hana-client`
- **MongoDB** (experimental)의 경우
`npm install mongodb@^5.2.0 --save`
`npm install mongodb`
- **NativeScript**, **react-native**, **Cordova**의 경우
- **NativeScript**, **React Native**, **Cordova**, **Expo**의 경우
[지원되는 플랫폼 문서](./docs/docs/Help/2-supported-platforms.md) 확인
[지원되는 플랫폼 문서](./docs/docs/help/2-supported-platforms.md) 확인
사용하는 데이터베이스에 따라*하나*만 설치
##### TypeScript 환경 설정
### TypeScript 환경 설정
또한 TypeScript 버전 **3.3** 이상을 사용 중이어야 하고, `tsconfig.json`에서 다음 설정을 사용 가능하게 했는지 확인해야 한다:
@ -197,8 +213,6 @@ await timber.remove()
"experimentalDecorators": true,
```
컴파일러 옵션의 `lib` 섹션에서 `es6`을 사용 설정하거나, `@types`에서 `es6-shim`을 설치해야 할 수도 있다.
## 빠른 시작
TypeORM을 시작하는 가장 빠른 방법은 CLI 명령을 사용하여 시작 프로젝트를 생성하는 것이다. 빠른 시작은 NodeJS 애플리케이션에서 TypeORM을 사용하는 경우에만 동작한다. 다른 플랫폼을 사용하는 경우 [단계별 가이드](#step-by-step-guide)에 따라 진행해야 한다.
@ -219,7 +233,7 @@ typeorm init --name MyProject --database mysql
이 명령은 `MyProject` 디렉토리에 다음의 파일들이 있는 새 프로젝트를 생성한다:
```
```text
MyProject
├── src // place of your TypeScript code
│ ├── entity // place where your entities (database models) are stored
@ -237,7 +251,7 @@ MyProject
다음 단계는 새 프로젝트 종속성을 설치하는 것이다:
```
```shell
cd MyProject
npm install
```
@ -264,7 +278,7 @@ npm install
설정을 마치고 모든 node 모듈이 설치되면 애플리케이션을 실행할 수 있다:
```
```shell
npm start
```
@ -441,7 +455,7 @@ export class Photo {
}
```
열 타입은 데이터베이스에 따라 다르다. 데이터베이스가 지원하는 모든 열 타입을 설정할 수 있다. 지원 되는 열 타입에 대한 자세한 정보는 [여기](./docs/docs/Entity/1-entities.md#column-types)에서 찾을 수 있다.
열 타입은 데이터베이스에 따라 다르다. 데이터베이스가 지원하는 모든 열 타입을 설정할 수 있다. 지원 되는 열 타입에 대한 자세한 정보는 [여기](./docs/docs/entity/1-entities.md#column-types)에서 찾을 수 있다.
### 데이터 베이스에 대한 연결 생성
@ -504,7 +518,7 @@ createConnection({
이제 `index.ts`를 실행하면 데이터베이스와의 연결이 초기화되고 photo에 대한 데이터베이스 테이블이 생성된다.
```shell
```text
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
@ -585,7 +599,7 @@ createConnection(/*...*/)
`savedPhotos`는 데이터베이스에서 로드된 데이터가 있는 Photo 객체의 배열이다.
[여기](./docs/docs/Working%20with%20Entity%20Manager/2-working-with-repository.md)에서 엔터티 매니저에 대해 자세히 알 수 있다.
[여기](./docs/docs/working-with-entity-manager/2-working-with-repository.md)에서 엔터티 매니저에 대해 자세히 알 수 있다.
### 리포지토리 사용
@ -615,7 +629,7 @@ createConnection(/*...*/)
.catch((error) => console.log(error))
```
[여기](./docs/docs/Working%20with%20Entity%20Manager/2-working-with-repository.md)에서 리포지토리에 대해 자세히 알 수 있다.
[여기](./docs/docs/working-with-entity-manager/2-working-with-repository.md)에서 리포지토리에 대해 자세히 알 수 있다.
### 데이터베이스에서 로드
@ -739,7 +753,7 @@ export class PhotoMetadata {
앱을 실행하면 새로 생성된 테이블이 표시되며 여기에는 photo 관계에 대한 외래 키가 있는 열이 포함된다:
```shell
```text
+-------------+--------------+----------------------------+
| photo_metadata |
+-------------+--------------+----------------------------+
@ -858,7 +872,7 @@ createConnection(/*...*/)
.catch((error) => console.log(error))
```
여기에서 photos에는 데이터베이스의 photo 배열이 포함되고 각 photo에는 photo metadata가 포함된다. [이 문서](./docs/docs/Working%20with%20Entity%20Manager/3-find-options.md)에서 찾기 옵션에 대해 자세히 알아볼 수 있다.
여기에서 photos에는 데이터베이스의 photo 배열이 포함되고 각 photo에는 photo metadata가 포함된다. [이 문서](./docs/docs/working-with-entity-manager/3-find-options.md)에서 찾기 옵션에 대해 자세히 알아볼 수 있다.
Using find options is good and dead 찾기 옵션을 사용하는 것은 훌륭하고 간단하지만 더 복잡한 쿼리가 필요한 경우에는 `QueryBuilder`를 대신 사용해야 한다. `QueryBuilder`를 사용하면 보다 복잡한 쿼리를 우아한 방식으로 사용할 수 있다.
@ -980,7 +994,7 @@ N:1/1:N 관계에서 소유자측은 항상 다대일(ManyToOne)이다. 즉 `@Ma
애플리케이션을 실행한 후, ORM은 `author` 테이블을 생성한다:
```shell
```text
+-------------+--------------+----------------------------+
| author |
+-------------+--------------+----------------------------+
@ -991,7 +1005,7 @@ N:1/1:N 관계에서 소유자측은 항상 다대일(ManyToOne)이다. 즉 `@Ma
또한 새 `author` 열을 추가하고 이에 대한 외래 키를 생성하여 `photo` 테이블을 수정한다:
```shell
```text
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
@ -1046,7 +1060,7 @@ export class Photo {
애플리케이션을 실행한 후, ORM은 **album_photos_photo_albums**라는 *접합 테이블(junction table)*을 생성한다.:
```shell
```text
+-------------+--------------+----------------------------+
| album_photos_photo_albums |
+-------------+--------------+----------------------------+
@ -1134,7 +1148,7 @@ let photos = await connection
이 쿼리는 이름이 "My" 또는 "Mishka"인 게시된 모든 photo를 선택한다. 위치 5(pagination 오프셋)에서 결과를 선택하고 10개 결과(pagination 제한)만 선택한다. 선택 결과는 id의 내림차순으로 정렬된다. photo의 album들은 결합된 상태로 유지되고 해당 metadata는 내부 결합(inner join)된다.
애플리케이션에서 쿼리 빌더를 많이 사용할 것이다. [여기](./docs/docs/Query%20Builder/1-select-query-builder.md)에서 쿼리 빌더에 대해 자세히 알 수 있다.
애플리케이션에서 쿼리 빌더를 많이 사용할 것이다. [여기](./docs/docs/query-builder/1-select-query-builder.md)에서 쿼리 빌더에 대해 자세히 알 수 있다.
## 샘플들
@ -1150,7 +1164,7 @@ clone하여 시작할 수 있는 몇 가지 리포지토리가 있다:
- [Express 및 TypeORM 사용 방법의 예시](https://github.com/typeorm/typescript-express-example)
- [Koa 및 TypeORM 사용 예시](https://github.com/typeorm/typescript-koa-example)
- [MongoDB에서 TypeORM을 사용하는 방법의 예시](https://github.com/typeorm/mongo-typescript-example)
- [Cordova/PhoneGap 앱에서 TypeORM을 사용하는 방법의 예시](https://github.com/typeorm/cordova-example)
- [Cordova 앱에서 TypeORM을 사용하는 방법의 예시](https://github.com/typeorm/cordova-example)
- [Ionic 앱에서 TypeORM을 사용하는 방법의 예시](https://github.com/typeorm/ionic-example)
- [React Native에서 TypeORM을 사용하는 방법의 예시](https://github.com/typeorm/react-native-example)
- [Nativescript-Vue와 함께 TypeORM을 사용하는 방법의 예시](https://github.com/typeorm/nativescript-vue-typeorm-sample)

View File

@ -76,9 +76,8 @@ Here we setup two options:
Once you setup the connection options you can create a new migration using CLI:
```
```shell
typeorm migration:create ./path-to-migrations-dir/PostRefactoring
```
Here, `PostRefactoring` is the name of the migration - you can specify any name you want.
@ -131,25 +130,25 @@ export class PostRefactoringTIMESTAMP implements MigrationInterface {
Once you have a migration to run on production, you can run them using a CLI command:
```
```shell
typeorm migration:run -- -d path-to-datasource-config
```
**`typeorm migration:create` and `typeorm migration:generate` will create `.ts` files, unless you use the `o` flag (see more in [Generating migrations](#generating-migrations)). The `migration:run` and `migration:revert` commands only work on `.js` files. Thus the typescript files need to be compiled before running the commands.** Alternatively you can use `ts-node` in conjunction with `typeorm` to run `.ts` migration files.
**`typeorm migration:create` and `typeorm migration:generate` will create `.ts` files, unless you use the `o` flag (see more in [Generating migrations](#generating-migrations)). The `migration:run` and `migration:revert` commands only work on `.js` files. Thus the typescript files need to be compiled before running the commands.** Alternatively, you can use `ts-node` with `typeorm` to run `.ts` migration files.
Example with `ts-node`:
```
```shell
npx typeorm-ts-node-commonjs migration:run -- -d path-to-datasource-config
```
Example with `ts-node` in ESM projects:
```
```shell
npx typeorm-ts-node-esm migration:run -- -d path-to-datasource-config
```
```
```shell
npx typeorm-ts-node-esm migration:generate ./src/migrations/update-post-table -d ./src/data-source.ts
```
@ -159,7 +158,7 @@ That's all! Now you have your database schema up-to-date.
If for some reason you want to revert the changes, you can run:
```
```shell
typeorm migration:revert -- -d path-to-datasource-config
```
@ -173,14 +172,14 @@ to the migrations table without running it. This is useful for migrations create
have already been made to the database or when migrations have been run externally
(e.g. by another tool or application), and you still would like to keep a consistent migration history.
```
typeorm migration:run --fake
```shell
typeorm migration:run -d path-to-datasource-config --fake
```
This is also possible with rollbacks.
```
typeorm migration:revert --fake
```shell
typeorm migration:revert -d path-to-datasource-config --fake
```
### Transaction modes
@ -216,13 +215,13 @@ TypeORM is able to automatically generate migration files with schema changes yo
Let's say you have a `Post` entity with a `title` column, and you have changed the name `title` to `name`.
You can run following command:
```
```shell
typeorm migration:generate PostRefactoring -d path-to-datasource-config
```
If you encounter any error, it require you have the path to migration name and data source. You can try this option
```
```shell
typeorm migration:generate -d <path/to/datasource> path/to/migrations/<migration-name>
```
@ -246,7 +245,7 @@ export class PostRefactoringTIMESTAMP implements MigrationInterface {
}
```
Alternatively you can also output your migrations as Javascript files using the `o` (alias for `--outputJs`) flag. This is useful for Javascript only projects in which TypeScript additional packages are not installed. This command, will generate a new migration file `{TIMESTAMP}-PostRefactoring.js` with the following content:
Alternatively, you can also output your migrations as Javascript files using the `o` (alias for `--outputJs`) flag. This is useful for Javascript only projects in which TypeScript additional packages are not installed. This command, will generate a new migration file `{TIMESTAMP}-PostRefactoring.js` with the following content:
```javascript
/**
@ -270,8 +269,8 @@ module.exports = class PostRefactoringTIMESTAMP {
)
}
}
```
By default, it generates CommonJS JavaScript code with the `o` (alias for `--outputJs`) flag, but you can also generate ESM code with the `esm` flag. This is useful for Javascript projects that use ESM:
```javascript
@ -279,7 +278,6 @@ By default, it generates CommonJS JavaScript code with the `o` (alias for `--out
* @typedef {import('typeorm').MigrationInterface} MigrationInterface
*/
/**
* @class
* @implements {MigrationInterface}
@ -332,7 +330,7 @@ The rule of thumb for generating migrations is that you generate them after **ea
If you need to run/revert/generate/show your migrations use the `-d` (alias for `--dataSource`) and pass the path to the file where your DataSource instance is defined as an argument
```
```shell
typeorm -d <your-data-source-path> migration:{run|revert}
```
@ -340,7 +338,7 @@ typeorm -d <your-data-source-path> migration:{run|revert}
If you need to specify a timestamp for the migration name, use the `-t` (alias for `--timestamp`) and pass the timestamp (should be a non-negative number)
```
```shell
typeorm -t <specific-timestamp> migration:{create|generate}
```

View File

@ -17,13 +17,13 @@ You may setup ts-node in your project to ease the operation as follows:
Install ts-node:
```
```shell
npm install ts-node --save-dev
```
Add typeorm command under scripts section in package.json
```
```json
"scripts": {
...
"typeorm": "typeorm-ts-node-commonjs"
@ -32,7 +32,7 @@ Add typeorm command under scripts section in package.json
For ESM projects add this instead:
```
```json
"scripts": {
...
"typeorm": "typeorm-ts-node-esm"
@ -43,7 +43,7 @@ If you want to load more modules like [module-alias](https://github.com/ilearnio
Then you may run the command like this:
```
```shell
npm run typeorm migration:run -- -d path-to-datasource-config
```
@ -55,7 +55,7 @@ To reduce verbosity of the documentation, the following sections are using a glo
You can create a new project with everything already setup:
```
```shell
typeorm init
```
@ -74,31 +74,31 @@ After that, you can run your application by running `npm start`.
All files are generated in the current directory.
If you want to generate them in a special directory you can use `--name`:
```
```shell
typeorm init --name my-project
```
To specify a specific database you use you can use `--database`:
```
```shell
typeorm init --database mssql
```
To generate an ESM base project you can use `--module esm`:
```
```shell
typeorm init --name my-project --module esm
```
You can also generate a base project with Express:
```
```shell
typeorm init --name my-project --express
```
If you are using docker you can generate a `docker-compose.yml` file using:
```
```shell
typeorm init --docker
```
@ -108,7 +108,7 @@ typeorm init --docker
You can create a new entity using CLI:
```
```shell
typeorm entity:create path-to-entity-dir/entity
```
@ -118,7 +118,7 @@ Learn more about [entities](../entity/1-entities.md).
You can create a new subscriber using CLI:
```
```shell
typeorm subscriber:create path-to-subscriber-dir/subscriber
```
@ -128,7 +128,7 @@ Learn more about [Subscribers](./4-listeners-and-subscribers.md).
You can create a new migration using CLI:
```
```shell
typeorm migration:create path-to-migrations-dir/migrationName
```
@ -141,7 +141,7 @@ and writes all sql queries that must be executed to update the database.
If no there were no changes generated, the command will exit with code 1.
```
```shell
typeorm migration:generate path/to/Migration -d path/to/datasource
```
@ -155,7 +155,7 @@ Learn more about [Migrations](./1-migrations.md).
To execute all pending migrations use following command:
```
```shell
typeorm migration:run -- -d path-to-datasource-config
```
@ -165,7 +165,7 @@ Learn more about [Migrations](./1-migrations.md).
To revert the most recently executed migration use the following command:
```
```shell
typeorm migration:revert -- -d path-to-datasource-config
```
@ -177,7 +177,7 @@ Learn more about [Migrations](./1-migrations.md).
To show all migrations and whether they've been run or not use following command:
```
```shell
typeorm migration:show -- -d path-to-datasource-config
```
@ -189,7 +189,7 @@ typeorm migration:show -- -d path-to-datasource-config
To synchronize a database schema use:
```
```shell
typeorm schema:sync
```
@ -201,7 +201,7 @@ Check which sql queries it will run before running on production.
To check what sql queries `schema:sync` is going to run use:
```
```shell
typeorm schema:log
```
@ -209,7 +209,7 @@ typeorm schema:log
To completely drop a database schema use:
```
```shell
typeorm schema:drop -- -d path-to-datasource-config
```
@ -219,7 +219,7 @@ Be careful with this command on production since it completely removes data from
You can execute any SQL query you want directly in the database using:
```
```shell
typeorm query "SELECT * FROM USERS"
```
@ -228,7 +228,7 @@ typeorm query "SELECT * FROM USERS"
If you are using `QueryBuilder` caching, sometimes you may want to clear everything stored in the cache.
You can do it using the following command:
```
```shell
typeorm cache:clear
```
@ -236,6 +236,6 @@ typeorm cache:clear
You can check what typeorm version you have installed (both local and global) by running:
```
```shell
typeorm version
```

View File

@ -32,13 +32,12 @@ const AppDataSource = new DataSource({
database: "test",
})
AppDataSource.initialize()
.then(() => {
console.log("Data Source has been initialized!")
})
.catch((err) => {
console.error("Error during Data Source initialization", err)
})
try {
await AppDataSource.initialize()
console.log("Data Source has been initialized!")
} catch (error) {
console.error("Error during Data Source initialization", error)
}
```
It's a good idea to make `AppDataSource` globally available by `export`-ing it since you'll use this instance across your application.

View File

@ -84,484 +84,6 @@ Different RDBMS-es have their own specific options.
- `isolateWhereStatements` - Enables where statement isolation, wrapping each where clause in brackets automatically.
eg. `.where("user.firstName = :search OR user.lastName = :search")` becomes `WHERE (user.firstName = ? OR user.lastName = ?)` instead of `WHERE user.firstName = ? OR user.lastName = ?`
## `mysql` / `mariadb` data source options
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. Default mysql port is `3306`.
- `username` - Database username.
- `password` - Database password.
- `database` - Database name.
- `charset` - The charset for the connection. This is called "collation" in the SQL-level of MySQL
(like utf8_general_ci). If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used. (Default: `UTF8_GENERAL_CI`).
- `timezone` - the timezone configured on the MySQL server. This is used to typecast server date/time
values to JavaScript Date object and vice versa. This can be `local`, `Z`, or an offset in the form
`+HH:MM` or `-HH:MM`. (Default: `local`)
- `connectTimeout` - The milliseconds before a timeout occurs during the initial connection to the MySQL server.
(Default: `10000`)
- `acquireTimeout` - The milliseconds before a timeout occurs during the initial connection to the MySql server. It differs from `connectTimeout` as it governs the TCP connection timeout where as connectTimeout does not. (default: `10000`)
- `insecureAuth` - Allow connecting to MySQL instances that ask for the old (insecure) authentication method.
(Default: `false`)
- `supportBigNumbers` - When dealing with big numbers (`BIGINT` and `DECIMAL` columns) in the database,
you should enable this option (Default: `true`)
- `bigNumberStrings` - Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers
(`BIGINT` and `DECIMAL` columns) to be always returned as JavaScript String objects (Default: `true`).
Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String
objects only when they cannot be accurately represented with
[JavaScript Number objects](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
(which happens when they exceed the `[-2^53, +2^53]` range), otherwise they will be returned as
Number objects. This option is ignored if `supportBigNumbers` is disabled.
- `dateStrings` - Force date types (`TIMESTAMP`, `DATETIME`, `DATE`) to be returned as strings rather than
inflated into JavaScript Date objects. Can be true/false or an array of type names to keep as strings.
(Default: `false`)
- `debug` - Prints protocol details to stdout. Can be true/false or an array of packet type names that
should be printed. (Default: `false`)
- `trace` - Generates stack traces on Error to include call site of library entrance ("long stack traces").
Slight performance penalty for most calls. (Default: `true`)
- `multipleStatements` - Allow multiple mysql statements per query. Be careful with this, it could increase the scope
of SQL injection attacks. (Default: `false`)
- `legacySpatialSupport` - Use spatial functions like GeomFromText and AsText which are removed in MySQL 8. (Default: true)
- `flags` - List of connection flags to use other than the default ones. It is also possible to blacklist default ones.
For more information, check [Connection Flags](https://github.com/mysqljs/mysql#connection-flags).
- `ssl` - object with SSL parameters or a string containing the name of the SSL profile.
See [SSL options](https://github.com/mysqljs/mysql#ssl-options).
- `enableQueryTimeout` - If a value is specified for maxQueryExecutionTime, in addition to generating a warning log when a
query exceeds this time limit,
the specified maxQueryExecutionTime value is also used as the timeout for the query.
For more information, check https://github.com/mysqljs/mysql?tab=readme-ov-file#timeouts
## `postgres` / `cockroachdb` data source options
PostgreSQL and CockroachDB are supported as TypeORM drivers. Databases that are PostgreSQL-compatible can also be used with TypeORM via the `postgres` data source option.
To use YugabyteDB, refer to [their ORM docs](https://docs.yugabyte.com/stable/drivers-orms/nodejs/typeorm/) to get started. Note that because some postgres features are [not supported](https://docs.yugabyte.com/stable/develop/postgresql-compatibility/#unsupported-postgresql-features) by YugabyteDB, some TypeORM functionality may be limited.
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. The default Postgres port is `5432`.
- `username` - Database username.
- `password` - Database password.
- `database` - Database name.
- `schema` - Schema name. Default is "public".
- `connectTimeoutMS` - The milliseconds before a timeout occurs during the initial connection to the postgres server. If `undefined`, or set to `0`, there is no timeout. Defaults to `undefined`.
- `ssl` - Object with ssl parameters. See [TLS/SSL](https://node-postgres.com/features/ssl).
- `uuidExtension` - The Postgres extension to use when generating UUIDs. Defaults to `uuid-ossp`. Can be changed to `pgcrypto` if the `uuid-ossp` extension is unavailable.
- `poolErrorHandler` - A function that get's called when underlying pool emits `'error'` event. Takes a single parameter (error instance) and defaults to logging with `warn` level.
- `maxTransactionRetries` - A maximum number of transaction retries in case of 40001 error. Defaults to 5.
- `logNotifications` - A boolean to determine whether postgres server [notice messages](https://www.postgresql.org/docs/current/plpgsql-errors-and-messages.html) and [notification events](https://www.postgresql.org/docs/current/sql-notify.html) should be included in client's logs with `info` level (default: `false`).
- `installExtensions` - A boolean to control whether to install necessary postgres extensions automatically or not (default: `true`)
- `applicationName` - A string visible in statistics and logs to help referencing an application to a connection (default: `undefined`)
- `parseInt8` - A boolean to enable parsing 64-bit integers (int8) as JavaScript integers.
By default int8 (bigint) values are returned as strings to avoid overflows.
JavaScript doesn't have support for 64-bit integers, the maximum safe integer in js is: Number.MAX_SAFE_INTEGER (`+2^53`). Be careful when enabling `parseInt8`.
Note: This option is ignored if the undelying driver does not support it.
## `sqlite` data source options
- `database` - Database path. For example "mydb.sql"
## `better-sqlite3` data source options
- `database` - Database path. For example "mydb.sql"
- `statementCacheSize` - Cache size of sqlite statement to speed up queries (default 100).
- `prepareDatabase` - Function to run before a database is used in typeorm. You can access original better-sqlite3 Database object here.
- `nativeBinding` - Relative or absolute path to the native addon (better_sqlite3.node).
## `capacitor` data source options
- `database` - Database name (capacitor-sqlite will add the suffix `SQLite.db`)
- `driver` - The capacitor-sqlite instance. For example, `new SQLiteConnection(CapacitorSQLite)`.
- `mode` - Set the mode for database encryption: "no-encryption" | "encryption" | "secret" | "newsecret"
- `version` - Database version
- `journalMode` - The SQLite journal mode (optional)
## `cordova` data source options
- `database` - Database name
- `location` - Where to save the database. See [cordova-sqlite-storage](https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database) for options.
## `react-native` data source options
- `database` - Database name
- `location` - Where to save the database. See [react-native-sqlite-storage](https://github.com/andpor/react-native-sqlite-storage#opening-a-database) for options.
## `nativescript` data source options
- `database` - Database name
## `mssql` data source options
Based on [tedious](https://tediousjs.github.io/node-mssql/) MSSQL implementation. See [SqlServerConnectionOptions.ts](https://github.com/typeorm/typeorm/tree/master/src/driver/sqlserver/SqlServerConnectionOptions.ts) for details on exposed attributes.
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. Default mssql port is `1433`.
- `username` - Database username.
- `password` - Database password.
- `database` - Database name.
- `schema` - Schema name. Default is "public".
- `domain` - Once you set domain, the driver will connect to SQL Server using domain login.
- `connectionTimeout` - Connection timeout in ms (default: `15000`).
- `requestTimeout` - Request timeout in ms (default: `15000`). NOTE: msnodesqlv8 driver doesn't support
timeouts < 1 second.
- `stream` - Stream recordsets/rows instead of returning them all at once as an argument of callback (default: `false`).
You can also enable streaming for each request independently (`request.stream = true`). Always set to `true` if you plan to
work with a large amount of rows.
- `pool.max` - The maximum number of connections there can be in the pool (default: `10`).
- `pool.min` - The minimum of connections there can be in the pool (default: `0`).
- `pool.maxWaitingClients` - maximum number of queued requests allowed, additional acquire calls will be callback with
an err in a future cycle of the event loop.
- `pool.acquireTimeoutMillis` - max milliseconds an `acquire` call will wait for a resource before timing out.
(default no limit), if supplied should non-zero positive integer.
- `pool.fifo` - if true the oldest resources will be first to be allocated. If false the most recently released resources
will be the first to be allocated. This in effect turns the pool's behaviour from a queue into a stack. boolean,
(default `true`).
- `pool.priorityRange` - int between 1 and x - if set, borrowers can specify their relative priority in the queue if no
resources are available. see example. (default `1`).
- `pool.evictionRunIntervalMillis` - How often to run eviction checks. Default: `0` (does not run).
- `pool.numTestsPerRun` - Number of resources to check each eviction run. Default: `3`.
- `pool.softIdleTimeoutMillis` - amount of time an object may sit idle in the pool before it is eligible for eviction by
the idle object evictor (if any), with the extra condition that at least "min idle" object instances remain in the pool.
Default `-1` (nothing can get evicted).
- `pool.idleTimeoutMillis` - the minimum amount of time that an object may sit idle in the pool before it is eligible for
eviction due to idle time. Supersedes `softIdleTimeoutMillis`. Default: `30000`.
- `pool.errorHandler` - A function that gets called when the underlying pool emits `'error'` event. Takes a single parameter (error instance) and defaults to logging with `warn` level.
- `options.fallbackToDefaultDb` - By default, if the database requestion by `options.database` cannot be accessed, the connection
will fail with an error. However, if `options.fallbackToDefaultDb` is set to `true`, then the user's default database will
be used instead (Default: `false`).
- `options.instanceName` - The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable. Mutually exclusive with `port`. (no default).
- `options.enableAnsiNullDefault` - If true, SET ANSI_NULL_DFLT_ON ON will be set in the initial sql. This means new
columns will be nullable by default. See the [T-SQL documentation](https://msdn.microsoft.com/en-us/library/ms187375.aspx)
for more details. (Default: `true`).
- `options.cancelTimeout` - The number of milliseconds before the cancel (abort) of a request is considered failed (default: `5000`).
- `options.packetSize` - The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default: `4096`).
- `options.useUTC` - A boolean determining whether to pass time values in UTC or local time. (default: `false`).
- `options.abortTransactionOnError` - A boolean determining whether to rollback a transaction automatically if any
error is encountered during the given transaction's execution. This sets the value for `SET XACT_ABORT` during the
initial SQL phase of a connection ([documentation](http://msdn.microsoft.com/en-us/library/ms188792.aspx)).
- `options.localAddress` - A string indicating which network interface (ip address) to use when connecting to SQL Server.
- `options.useColumnNames` - A boolean determining whether to return rows as arrays or key-value collections. (default: `false`).
- `options.camelCaseColumns` - A boolean, controlling whether the column names returned will have the first letter
converted to lower case (`true`) or not. This value is ignored if you provide a `columnNameReplacer`. (default: `false`).
- `options.isolationLevel` - The default isolation level that transactions will be run with. The isolation levels are
available from `require('tedious').ISOLATION_LEVEL`.
- `READ_UNCOMMITTED`
- `READ_COMMITTED`
- `REPEATABLE_READ`
- `SERIALIZABLE`
- `SNAPSHOT`
(default: `READ_COMMITTED`)
- `options.connectionIsolationLevel` - The default isolation level for new connections. All out-of-transaction queries
are executed with this setting. The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
- `READ_UNCOMMITTED`
- `READ_COMMITTED`
- `REPEATABLE_READ`
- `SERIALIZABLE`
- `SNAPSHOT`
(default: `READ_COMMITTED`)
- `options.readOnlyIntent` - A boolean, determining whether the connection will request read-only access from a
SQL Server Availability Group. For more information, see here. (default: `false`).
- `options.encrypt` - A boolean determining whether or not the connection will be encrypted. Set to true if you're
on Windows Azure. (default: `true`).
- `options.cryptoCredentialsDetails` - When encryption is used, an object may be supplied that will be used for the
first argument when calling [tls.createSecurePair](http://nodejs.org/docs/latest/api/tls.html#tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized)
(default: `{}`).
- `options.rowCollectionOnDone` - A boolean, that when true will expose received rows in Requests' `done*` events.
See done, [doneInProc](http://tediousjs.github.io/tedious/api-request.html#event_doneInProc)
and [doneProc](http://tediousjs.github.io/tedious/api-request.html#event_doneProc). (default: `false`)
Caution: If many rows are received, enabling this option could result in excessive memory usage.
- `options.rowCollectionOnRequestCompletion` - A boolean, that when true will expose received rows
in Requests' completion callback. See [new Request](http://tediousjs.github.io/tedious/api-request.html#function_newRequest). (default: `false`)
Caution: If many rows are received, enabling this option could result in excessive memory usage.
- `options.tdsVersion` - The version of TDS to use. If the server doesn't support the specified version, a negotiated version
is used instead. The versions are available from `require('tedious').TDS_VERSION`.
- `7_1`
- `7_2`
- `7_3_A`
- `7_3_B`
- `7_4`
(default: `7_4`)
- `options.appName` - Application name used for identifying a specific application in profiling, logging or tracing tools of SQL Server. (default: `node-mssql`)
- `options.trustServerCertificate` - A boolean, controlling whether encryption occurs if there is no verifiable server certificate. (default: `false`)
- `options.debug.packet` - A boolean, controlling whether `debug` events will be emitted with text describing packet
details (default: `false`).
- `options.debug.data` - A boolean, controlling whether `debug` events will be emitted with text describing packet data
details (default: `false`).
- `options.debug.payload` - A boolean, controlling whether `debug` events will be emitted with text describing packet
payload details (default: `false`).
- `options.debug.token` - A boolean, controlling whether `debug` events will be emitted with text describing token stream
tokens (default: `false`).
## `mongodb` data source options
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. Default mongodb port is `27017`.
- `username` - Database username (replacement for `auth.user`).
- `password` - Database password (replacement for `auth.password`).
- `database` - Database name.
- `poolSize` - Set the maximum pool size for each individual server or proxy connection.
- `ssl` - Use ssl connection (needs to have a mongod server with ssl support). Default: `false`.
- `sslValidate` - Validate mongod server certificate against ca (needs to have a mongod server with ssl support,
2.4 or higher). Default: `true`.
- `sslCA` - Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support,
2.4 or higher).
- `sslCert` - String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl
support, 2.4 or higher)
- `sslKey` - String or buffer containing the certificate private key we wish to present (needs to have a mongod server
with ssl support, 2.4 or higher).
- `sslPass` - String or buffer containing the certificate password (needs to have a mongod server with ssl support,
2.4 or higher).
- `autoReconnect` - Reconnect on error. Default: `true`.
- `noDelay` - TCP Socket NoDelay option. Default: `true`.
- `keepAlive` - The number of milliseconds to wait before initiating keepAlive on the TCP socket. Default: `30000`.
- `connectTimeoutMS` - TCP Connection timeout setting. Default: `30000`.
- `socketTimeoutMS` - TCP Socket timeout setting. Default: `360000`.
- `reconnectTries` - Server attempt to reconnect #times. Default: `30`.
- `reconnectInterval` - Server will wait #milliseconds between retries. Default: `1000`.
- `ha` - Turn on high availability monitoring. Default: `true`.
- `haInterval` - Time between each replicaset status check. Default: `10000,5000`.
- `replicaSet` - The name of the replicaset to connect to.
- `acceptableLatencyMS` - Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence,
ex: range of 1 to (1 + 15) ms). Default: `15`.
- `secondaryAcceptableLatencyMS` - Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency
fence, ex: range of 1 to (1 + 15) ms). Default: `15`.
- `connectWithNoPrimary` - Sets if the driver should connect even if no primary is available. Default: `false`.
- `authSource` - If the database authentication is dependent on another databaseName.
- `w` - The write concern.
- `wtimeout` - The write concern timeout value.
- `j` - Specify a journal write concern. Default: `false`.
- `forceServerObjectId` - Force server to assign \_id values instead of driver. Default: `false`.
- `serializeFunctions` - Serialize functions on any object. Default: `false`.
- `ignoreUndefined` - Specify if the BSON serializer should ignore undefined fields. Default: `false`.
- `raw` - Return document results as raw BSON buffers. Default: `false`.
- `promoteLongs` - Promotes Long values to number if they fit inside the 53 bits resolution. Default: `true`.
- `promoteBuffers` - Promotes Binary BSON values to native Node Buffers. Default: `false`.
- `promoteValues` - Promotes BSON values to native types where possible, set to false to only receive wrapper types.
Default: `true`.
- `domainsEnabled` - Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
Default: `false`.
- `bufferMaxEntries` - Sets a cap on how many operations the driver will buffer up before giving up on getting a
working connection, default is -1 which is unlimited.
- `readPreference` - The preferred read preference.
- `ReadPreference.PRIMARY`
- `ReadPreference.PRIMARY_PREFERRED`
- `ReadPreference.SECONDARY`
- `ReadPreference.SECONDARY_PREFERRED`
- `ReadPreference.NEAREST`
- `pkFactory` - A primary key factory object for generation of custom \_id keys.
- `promiseLibrary` - A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible.
- `readConcern` - Specify a read concern for the collection. (only MongoDB 3.2 or higher supported).
- `maxStalenessSeconds` - Specify a maxStalenessSeconds value for secondary reads, minimum is 90 seconds.
- `appname` - The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this
value in the server log upon establishing each connection. It is also recorded in the slow query log and profile
collections
- `loggerLevel` - Specify the log level used by the driver logger (`error/warn/info/debug`).
- `logger` - Specify a customer logger mechanism, that can be used to log using your app-level logger.
- `authMechanism` - Sets the authentication mechanism that MongoDB will use to authenticate the connection.
- `directConnection` - Specifies whether to force dispatch all operations to the specified host.
## `sql.js` data source options
- `database`: The raw UInt8Array database that should be imported.
- `sqlJsConfig`: Optional initialize config for sql.js.
- `autoSave`: Whether or not autoSave should be disabled. If set to true the database will be saved to the given file location (Node.js) or LocalStorage element (browser) when a change happens and `location` is specified. Otherwise `autoSaveCallback` can be used.
- `autoSaveCallback`: A function that get's called when changes to the database are made and `autoSave` is enabled. The function gets a `UInt8Array` that represents the database.
- `location`: The file location to load and save the database to.
- `useLocalForage`: Enables the usage of the localforage library (https://github.com/localForage/localForage) to save & load the database asynchronously from the indexedDB instead of using the synchrony local storage methods in a browser environment. The localforage node module needs to be added to your project and the localforage.js should be imported in your page.
## `expo` data source options
- `database` - Name of the database. For example, "mydb".
- `driver` - The Expo SQLite module. For example, `require('expo-sqlite')`.
## `oracle` data source options
The following TNS connection string will be used in the next explanations:
```bash
(DESCRIPTION=
(ADDRESS=(PROTOCOL=tcp)(HOST=sales-server)(PORT=1521))
(CONNECT_DATA=
(SID=sales)
(SERVICE_NAME=sales.us.example.com)
(INSTANCE_NAME=sales))
(SERVER=shared)))
)
```
- `sid` - The System Identifier (SID) identifies a specific database instance. For example, "sales".
- `serviceName` - The Service Name is an identifier of a database service. For example, `sales.us.example.com`.
## `sap` data source options
- `host` - The hostname of the SAP HANA server. For example, `"localhost"`.
- `port` - The port number of the SAP HANA server. For example, `30015`.
- `username` - The username to connect to the SAP HANA server. For example, `"SYSTEM"`.
- `password` - The password to connect to the SAP HANA server. For example, `"password"`.
- `database` - The name of the database to connect to. For example, `"HXE"`.
- `encrypt` - Whether to encrypt the connection. For example, `true`.
- `sslValidateCertificate` - Whether to validate the SSL certificate. For example, `true`.
- `key`, `cert` and `ca` - Private key, public certificate and certificate authority for the encrypted connection.
- `pool` — Connection pool configuration object:
- `maxConnectedOrPooled` (number) — Max active or idle connections in the pool (default: 10).
- `maxPooledIdleTime` (seconds) — Time before an idle connection is closed (default: 30).
- `pingCheck` (boolean) — Whether to validate connections before use (default: false).
- `poolCapacity` (number) — Maximum number of connections to be kept available (default: no limit).
See the official documentation of SAP HANA Client for more details as well as the `extra` properties: [Node.js Connection Properties](https://help.sap.com/docs/SAP_HANA_CLIENT/f1b440ded6144a54ada97ff95dac7adf/4fe9978ebac44f35b9369ef5a4a26f4c.html).
## Data Source Options example
Here is a small example of data source options for mysql:

View File

@ -1,7 +1,7 @@
# DataSource API
- `options` - Options used to create this dataSource.
Learn more about [DataSourceOptions](./2-data-source-options.md).
Learn more about [Data Source Options](./2-data-source-options.md).
```typescript
const dataSourceOptions: DataSourceOptions = dataSource.options
@ -29,7 +29,7 @@ const users = await manager.find()
```
- `mongoManager` - `MongoEntityManager` used to work with entities for mongodb data source.
For more information about MongoEntityManager see [MongoDB](../guides/2-mongodb.md) documentation.
For more information about MongoEntityManager see [MongoDB](../drivers/mongodb.md) documentation.
```typescript
const manager: MongoEntityManager = dataSource.mongoManager
@ -114,7 +114,7 @@ const categories = await repository.findTrees()
- `getMongoRepository` - Gets `MongoRepository` of the given entity.
This repository is used for entities in MongoDB dataSource.
Learn more about [MongoDB support](../guides/2-mongodb.md).
Learn more about [MongoDB support](../drivers/mongodb.md).
```typescript
const repository = dataSource.getMongoRepository(User)

View File

@ -0,0 +1,38 @@
# Google Spanner
## Installation
```shell
npm install @google-cloud/spanner
```
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options.
Provide authentication credentials to your application code
by setting the environment variable `GOOGLE_APPLICATION_CREDENTIALS`:
```shell
# Linux/macOS
export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"
# Windows
set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
# Replace KEY_PATH with the path of the JSON file that contains your service account key.
```
To use Spanner with the emulator you should set `SPANNER_EMULATOR_HOST` environment variable:
```shell
# Linux/macOS
export SPANNER_EMULATOR_HOST=localhost:9010
# Windows
set SPANNER_EMULATOR_HOST=localhost:9010
```
## Column Types
`bool`, `int64`, `float64`, `numeric`, `string`, `json`, `bytes`, `date`, `timestamp`, `array`

View File

@ -0,0 +1,166 @@
# Microsoft SQLServer
## Installation
```shell
npm install mssql
```
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options.
Based on [tedious](https://tediousjs.github.io/node-mssql/) MSSQL implementation. See [SqlServerConnectionOptions.ts](https://github.com/typeorm/typeorm/tree/master/src/driver/sqlserver/SqlServerConnectionOptions.ts) for details on exposed attributes.
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. Default mssql port is `1433`.
- `username` - Database username.
- `password` - Database password.
- `database` - Database name.
- `schema` - Schema name. Default is "dbo".
- `domain` - Once you set domain, the driver will connect to SQL Server using domain login.
- `connectionTimeout` - Connection timeout in ms (default: `15000`).
- `requestTimeout` - Request timeout in ms (default: `15000`). NOTE: msnodesqlv8 driver doesn't support
timeouts < 1 second.
- `stream` - Stream record sets/rows instead of returning them all at once as an argument of callback (default: `false`).
You can also enable streaming for each request independently (`request.stream = true`). Always set to `true` if you plan to
work with a large number of rows.
- `pool.max` - The maximum number of connections there can be in the pool (default: `10`).
- `pool.min` - The minimum of connections there can be in the pool (default: `0`).
- `pool.maxWaitingClients` - maximum number of queued requests allowed, additional acquire calls will be called back with
an error in a future cycle of the event loop.
- `pool.acquireTimeoutMillis` - max milliseconds an `acquire` call will wait for a resource before timing out.
(default no limit), if supplied should non-zero positive integer.
- `pool.fifo` - if true the oldest resources will be first to be allocated. If false, the most recently released resources
will be the first to be allocated. This, in effect, turns the pool's behaviour from a queue into a stack. boolean,
(default `true`).
- `pool.priorityRange` - int between 1 and x - if set, borrowers can specify their relative priority in the queue if no
resources are available. see example. (default `1`).
- `pool.evictionRunIntervalMillis` - How often to run eviction checks. Default: `0` (does not run).
- `pool.numTestsPerRun` - Number of resources to check each eviction run. Default: `3`.
- `pool.softIdleTimeoutMillis` - amount of time an object may sit idle in the pool before it is eligible for eviction by
the idle object evictor (if any), with the extra condition that at least "min idle" object instances remain in the pool.
Default `-1` (nothing can get evicted).
- `pool.idleTimeoutMillis` - the minimum amount of time that an object may sit idle in the pool before it is eligible for
eviction due to idle time. Supersedes `softIdleTimeoutMillis`. Default: `30000`.
- `pool.errorHandler` - A function that gets called when the underlying pool emits `'error'` event. Takes a single parameter (error instance) and defaults to logging with `warn` level.
- `options.fallbackToDefaultDb` - By default, if the database requested by `options.database` cannot be accessed, the connection will fail with an error. However, if `options.fallbackToDefaultDb` is set to `true`, then the user's default database will be used instead (Default: `false`).
- `options.instanceName` - The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable. Mutually exclusive with `port`. (no default).
- `options.enableAnsiNullDefault` - If true, `SET ANSI_NULL_DFLT_ON ON` will be set in the initial SQL. This means new
columns will be nullable by default. See the [T-SQL documentation](https://msdn.microsoft.com/en-us/library/ms187375.aspx)
for more details. (Default: `true`).
- `options.cancelTimeout` - The number of milliseconds before the cancel (abort) of a request is considered failed (default: `5000`).
- `options.packetSize` - The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default: `4096`).
- `options.useUTC` - A boolean determining whether to pass time values in UTC or local time. (default: `false`).
- `options.abortTransactionOnError` - A boolean determining whether to roll back a transaction automatically if any
error is encountered during the given transaction's execution. This sets the value for `SET XACT_ABORT` during the
initial SQL phase of a connection ([documentation](http://msdn.microsoft.com/en-us/library/ms188792.aspx)).
- `options.localAddress` - A string indicating which network interface (ip address) to use when connecting to SQL Server.
- `options.useColumnNames` - A boolean determining whether to return rows as arrays or key-value collections. (default: `false`).
- `options.camelCaseColumns` - A boolean, controlling whether the column names returned will have the first letter
converted to lower case (`true`) or not. This value is ignored if you provide a `columnNameReplacer`. (default: `false`).
- `options.isolationLevel` - The default isolation level that transactions will be run with. The isolation levels are
available from `require('tedious').ISOLATION_LEVEL`.
- `READ_UNCOMMITTED`
- `READ_COMMITTED`
- `REPEATABLE_READ`
- `SERIALIZABLE`
- `SNAPSHOT`
(default: `READ_COMMITTED`)
- `options.connectionIsolationLevel` - The default isolation level for new connections. All out-of-transaction queries
are executed with this setting. The isolation levels are available from `require('tedious').ISOLATION_LEVEL`.
- `READ_UNCOMMITTED`
- `READ_COMMITTED`
- `REPEATABLE_READ`
- `SERIALIZABLE`
- `SNAPSHOT`
(default: `READ_COMMITTED`)
- `options.readOnlyIntent` - A boolean, determining whether the connection will request read-only access from a
SQL Server Availability Group. For more information, see here. (default: `false`).
- `options.encrypt` - A boolean determining whether the connection will be encrypted. Set to true if you're on Windows Azure. (default: `true`).
- `options.cryptoCredentialsDetails` - When encryption is used, an object may be supplied that will be used for the
first argument when calling [tls.createSecurePair](http://nodejs.org/docs/latest/api/tls.html#tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized)
(default: `{}`).
- `options.rowCollectionOnDone` - A boolean, that when true will expose received rows in Requests' `done*` events.
See done, [doneInProc](http://tediousjs.github.io/tedious/api-request.html#event_doneInProc)
and [doneProc](http://tediousjs.github.io/tedious/api-request.html#event_doneProc). (default: `false`)
Caution: If many rows are received, enabling this option could result in excessive memory usage.
- `options.rowCollectionOnRequestCompletion` - A boolean, that when true will expose received rows
in Requests' completion callback. See [new Request](http://tediousjs.github.io/tedious/api-request.html#function_newRequest). (default: `false`)
Caution: If many rows are received, enabling this option could result in excessive memory usage.
- `options.tdsVersion` - The version of TDS to use. If the server doesn't support the specified version, a negotiated version
is used instead. The versions are available from `require('tedious').TDS_VERSION`.
- `7_1`
- `7_2`
- `7_3_A`
- `7_3_B`
- `7_4`
(default: `7_4`)
- `options.appName` - Application name used for identifying a specific application in profiling, logging or tracing tools of SQL Server. (default: `node-mssql`)
- `options.trustServerCertificate` - A boolean, controlling whether encryption occurs if there is no verifiable server certificate. (default: `false`)
- `options.debug.packet` - A boolean, controlling whether `debug` events will be emitted with text describing packet
details (default: `false`).
- `options.debug.data` - A boolean, controlling whether `debug` events will be emitted with text describing packet data
details (default: `false`).
- `options.debug.payload` - A boolean, controlling whether `debug` events will be emitted with text describing packet
payload details (default: `false`).
- `options.debug.token` - A boolean, controlling whether `debug` events will be emitted with text describing token stream
tokens (default: `false`).
## Column Types
`int`, `bigint`, `bit`, `decimal`, `money`, `numeric`, `smallint`, `smallmoney`, `tinyint`, `float`, `real`, `date`, `datetime2`, `datetime`, `datetimeoffset`, `smalldatetime`, `time`, `char`, `varchar`, `text`, `nchar`, `nvarchar`, `ntext`, `binary`, `image`, `varbinary`, `hierarchyid`, `sql_variant`, `timestamp`, `uniqueidentifier`, `xml`, `geometry`, `geography`, `rowversion`

View File

@ -6,6 +6,89 @@ TypeORM has basic MongoDB support.
Most of TypeORM functionality is RDBMS-specific,
this page contains all MongoDB-specific functionality documentation.
## Installation
```shell
npm install mongodb
```
## Data Source Options
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. Default mongodb port is `27017`.
- `username` - Database username (replacement for `auth.user`).
- `password` - Database password (replacement for `auth.password`).
- `database` - Database name.
- `poolSize` - Set the maximum pool size for each server or proxy connection.
- `tls` - Use a TLS/SSL connection (needs a mongod server with ssl support, 2.4 or higher). Default: `false`.
- `tlsAllowInvalidCertificates` - Specifies whether the driver generates an error when the server's TLS certificate is invalid. Default: `false`.
- `tlsCAFile` - Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority.
- `tlsCertificateKeyFile` - Specifies the location of a local .pem file that contains the client's TLS/SSL certificate and key.
- `tlsCertificateKeyFilePassword` - Specifies the password to decrypt the `tlsCertificateKeyFile`.
- `keepAlive` - The number of milliseconds to wait before initiating keepAlive on the TCP socket. Default: `30000`.
- `connectTimeoutMS` - TCP Connection timeout setting. Default: `30000`.
- `socketTimeoutMS` - TCP Socket timeout setting. Default: `360000`.
- `replicaSet` - The name of the replica set to connect to.
- `authSource` - If the database authentication is dependent on another databaseName.
- `writeConcern` - The write concern.
- `forceServerObjectId` - Force server to assign \_id values instead of driver. Default: `false`.
- `serializeFunctions` - Serialize functions on any object. Default: `false`.
- `ignoreUndefined` - Specify if the BSON serializer should ignore undefined fields. Default: `false`.
- `raw` - Return document results as raw BSON buffers. Default: `false`.
- `promoteLongs` - Promotes Long values to number if they fit inside the 53-bit resolution. Default: `true`.
- `promoteBuffers` - Promotes Binary BSON values to native Node Buffers. Default: `false`.
- `promoteValues` - Promotes BSON values to native types where possible, set to false to only receive wrapper types.
Default: `true`.
- `readPreference` - The preferred read preference.
- `ReadPreference.PRIMARY`
- `ReadPreference.PRIMARY_PREFERRED`
- `ReadPreference.SECONDARY`
- `ReadPreference.SECONDARY_PREFERRED`
- `ReadPreference.NEAREST`
- `pkFactory` - A primary key factory object for generation of custom \_id keys.
- `readConcern` - Specify a read concern for the collection. (only MongoDB 3.2 or higher supported).
- `maxStalenessSeconds` - Specify a maxStalenessSeconds value for secondary reads, minimum is 90 seconds.
- `appName` - The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this
value in the server log upon establishing each connection. It is also recorded in the slow query log and profile
collections
- `authMechanism` - Sets the authentication mechanism that MongoDB will use to authenticate the connection.
- `directConnection` - Specifies whether to force-dispatch all operations to the specified host.
Additional options can be added to the `extra` object and will be passed directly to the client library. See more in `mongodb`'s documentation for [Connection Options](https://mongodb-node.netlify.app/docs/drivers/node/current/connect/connection-options/).
## Defining entities and columns
Defining entities and columns is almost the same as in relational databases,
@ -45,8 +128,7 @@ const myDataSource = new DataSource({
## Defining subdocuments (embed documents)
Since MongoDB stores objects and objects inside objects (or documents inside documents)
you can do the same in TypeORM:
Since MongoDB stores objects and objects inside objects (or documents inside documents), you can do the same in TypeORM:
```typescript
import { Entity, ObjectId, ObjectIdColumn, Column } from "typeorm"
@ -127,7 +209,7 @@ const manager = getMongoManager()
await manager.save(user)
```
Following document will be saved in the database:
The following document will be saved in the database:
```json
{
@ -256,146 +338,145 @@ const users = await myDataSource.getMongoRepository(User).find({
})
```
Both `MongoEntityManager` and `MongoRepository` contain lot of useful MongoDB-specific methods:
Both `MongoEntityManager` and `MongoRepository` contain a lot of useful MongoDB-specific methods:
#### `createCursor`
### `createCursor`
Creates a cursor for a query that can be used to iterate over results from MongoDB.
Create a cursor for a query that can be used to iterate over results from MongoDB.
#### `createEntityCursor`
### `createEntityCursor`
Creates a cursor for a query that can be used to iterate over results from MongoDB.
Create a cursor for a query that can be used to iterate over results from MongoDB.
This returns a modified version of the cursor that transforms each result into Entity models.
#### `aggregate`
### `aggregate`
Execute an aggregation framework pipeline against the collection.
#### `bulkWrite`
### `bulkWrite`
Perform a bulkWrite operation without a fluent API.
#### `count`
### `count`
Count number of matching documents in the db to a query.
Count the number of matching documents in the db to a query.
#### `countDocuments`
### `countDocuments`
Count number of matching documents in the db to a query.
Count the number of matching documents in the db to a query.
#### `createCollectionIndex`
### `createCollectionIndex`
Creates an index on the db and collection.
Create an index on the db and collection.
#### `createCollectionIndexes`
### `createCollectionIndexes`
Creates multiple indexes in the collection, this method is only supported in MongoDB 2.6 or higher.
Earlier version of MongoDB will throw a command not supported error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.
Create multiple indexes in the collection, this method is only supported in MongoDB 2.6 or higher. Earlier versions of MongoDB will throw a "command not supported" error. Index specifications are defined at [createIndexes](http://docs.mongodb.org/manual/reference/command/createIndexes/).
#### `deleteMany`
### `deleteMany`
Delete multiple documents on MongoDB.
#### `deleteOne`
### `deleteOne`
Delete a document on MongoDB.
#### `distinct`
### `distinct`
The distinct command returns a list of distinct values for the given key across a collection.
#### `dropCollectionIndex`
### `dropCollectionIndex`
Drops an index from this collection.
#### `dropCollectionIndexes`
### `dropCollectionIndexes`
Drops all indexes from the collection.
#### `findOneAndDelete`
### `findOneAndDelete`
Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
#### `findOneAndReplace`
### `findOneAndReplace`
Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
#### `findOneAndUpdate`
### `findOneAndUpdate`
Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
#### `geoHaystackSearch`
### `geoHaystackSearch`
Execute a geo search using a geo haystack index on a collection.
#### `geoNear`
### `geoNear`
Execute the geoNear command to search for items in the collection.
#### `group`
### `group`
Run a group command across a collection.
#### `collectionIndexes`
### `collectionIndexes`
Retrieve all the indexes on the collection.
Retrieve all the indexes of the collection.
#### `collectionIndexExists`
### `collectionIndexExists`
Retrieve if an index exists on the collection
#### `collectionIndexInformation`
### `collectionIndexInformation`
Retrieves this collections index info.
Retrieve this collection's index info.
#### `initializeOrderedBulkOp`
### `initializeOrderedBulkOp`
Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
Initiate an In order bulk write operation; operations will be serially executed in the order they are added, creating a new operation for each switch in types.
#### `initializeUnorderedBulkOp`
### `initializeUnorderedBulkOp`
Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
#### `insertMany`
### `insertMany`
Inserts an array of documents into MongoDB.
Insert an array of documents into MongoDB.
#### `insertOne`
### `insertOne`
Inserts a single document into MongoDB.
Insert a single document into MongoDB.
#### `isCapped`
### `isCapped`
Returns if the collection is a capped collection.
Return if the collection is a capped collection.
#### `listCollectionIndexes`
### `listCollectionIndexes`
Get the list of all indexes information for the collection.
#### `parallelCollectionScan`
### `parallelCollectionScan`
Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are no ordering guarantees for returned results
Return N number of parallel cursors for a collection allowing parallel reading of the entire collection. There are no ordering guarantees for returned results
#### `reIndex`
### `reIndex`
Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
#### `rename`
### `rename`
Changes the name of an existing collection.
Change the name of an existing collection.
#### `replaceOne`
### `replaceOne`
Replace a document on MongoDB.
#### `stats`
### `stats`
Get all the collection statistics.
#### `updateMany`
### `updateMany`
Updates multiple documents within the collection based on the filter.
Update multiple documents within the collection based on the filter.
#### `updateOne`
### `updateOne`
Updates a single document within the collection based on the filter.
Update a single document within the collection based on the filter.

141
docs/docs/drivers/mysql.md Normal file
View File

@ -0,0 +1,141 @@
# MySQL / MariaDB
MySQL, MariaDB and Amazon Aurora MySQL are supported as TypeORM drivers.
## Installation
Either `mysql` or `mysql2` are required to connect to a MySQL/MariaDB data source. Only `mysql2` can connect to MySQL 8.0 or later and is recommended because it is still maintained. See more about [mysql2](https://sidorares.github.io/node-mysql2/docs/history-and-why-mysq2).
```shell
npm install mysql
```
or:
```shell
npm install mysql2
```
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options. You can use the data source types `mysql`, `mariadb` and `aurora-mysql` to connect to the respective databases.
- `connectorPackage` - The database client, either `mysql` or `mysql2`. If the specified client cannot be loaded, it will fall back to the alternative. (Current default: `mysql`)
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. Default mysql port is `3306`.
- `username` - Database username.
- `password` - Database password.
- `database` - Database name.
- `charset` - The charset for the connection. This is called "collation" in the SQL-level of MySQL
(like utf8_general_ci). If an SQL-level charset is specified (like utf8mb4), then the default collation for that charset is used. (Default: `UTF8_GENERAL_CI`).
- `timezone` - the timezone configured on the MySQL server. This is used to typecast server date/time
values to JavaScript Date object and vice versa. This can be `local`, `Z`, or an offset in the form
`+HH:MM` or `-HH:MM`. (Default: `local`)
- `connectTimeout` - The milliseconds before a timeout occurs during the initial connection to the MySQL server.
(Default: `10000`)
- `acquireTimeout` - The milliseconds before a timeout occurs during the initial connection to the MySQL server. It differs from `connectTimeout` as it governs the TCP connection timeout whereas connectTimeout does not. (default: `10000`)
- `insecureAuth` - Allow connecting to MySQL instances that ask for the old (insecure) authentication method.
(Default: `false`)
- `supportBigNumbers` - When dealing with big numbers (`BIGINT` and `DECIMAL` columns) in the database,
you should enable this option (Default: `true`)
- `bigNumberStrings` - Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers
(`BIGINT` and `DECIMAL` columns) to be always returned as JavaScript String objects (Default: `true`).
Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String
objects only when they cannot be accurately represented with
[JavaScript Number objects](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
(which happens when they exceed the `[-2^53, +2^53]` range), otherwise they will be returned as
Number objects. This option is ignored if `supportBigNumbers` is disabled.
- `dateStrings` - Force date types (`TIMESTAMP`, `DATETIME`, `DATE`) to be returned as strings rather than
inflated into JavaScript Date objects. Can be true/false or an array of type names to keep as strings.
(Default: `false`)
- `debug` - Prints protocol details to stdout. Can be true/false or an array of packet type names that
should be printed. (Default: `false`)
- `trace` - Generates stack traces on Error to include call site of library entrance ("long stack traces").
Slight performance penalty for most calls. (Default: `true`)
- `multipleStatements` - Allow multiple mysql statements per query. Be careful with this, it could increase the scope
of SQL injection attacks. (Default: `false`)
- `legacySpatialSupport` - Use legacy spatial functions like `GeomFromText` and `AsText` which have been replaced by the standard-compliant `ST_GeomFromText` or `ST_AsText` in MySQL 8.0. (Current default: true)
- `flags` - List of connection flags to use other than the default ones. It is also possible to blacklist default ones.
For more information, check [Connection Flags](https://github.com/mysqljs/mysql#connection-flags).
- `ssl` - object with SSL parameters or a string containing the name of the SSL profile.
See [SSL options](https://github.com/mysqljs/mysql#ssl-options).
- `enableQueryTimeout` - If a value is specified for maxQueryExecutionTime, in addition to generating a warning log when a query exceeds this time limit, the specified maxQueryExecutionTime value is also used as the timeout for the query. For more information, check [mysql timeouts](https://github.com/mysqljs/mysql#timeouts).
Additional options can be added to the `extra` object and will be passed directly to the client library. See more in the [mysql connection options](https://github.com/mysqljs/mysql#connection-options) or the [mysql2 documentation](https://sidorares.github.io/node-mysql2/docs).
## Column Types
`bit`, `int`, `integer`, `tinyint`, `smallint`, `mediumint`, `bigint`, `float`, `double`, `double precision`, `dec`, `decimal`, `numeric`, `fixed`, `bool`, `boolean`, `date`, `datetime`, `timestamp`, `time`, `year`, `char`, `nchar`, `national char`, `varchar`, `nvarchar`, `national varchar`, `text`, `tinytext`, `mediumtext`, `blob`, `longtext`, `tinyblob`, `mediumblob`, `longblob`, `enum`, `set`, `json`, `binary`, `varbinary`, `geometry`, `point`, `linestring`, `polygon`, `multipoint`, `multilinestring`, `multipolygon`, `geometrycollection`, `uuid`, `inet4`, `inet6`
> Note: `uuid`, `inet4`, and `inet6` are only available for MariaDB and for the respective versions that made them available.
### `enum` column type
See [enum column type](../entity/1-entities.md#enum-column-type).
### `set` column type
`set` column type is supported by `mariadb` and `mysql`. There are various possible column definitions:
Using TypeScript enums:
```typescript
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: UserRole,
default: [UserRole.GHOST, UserRole.EDITOR],
})
roles: UserRole[]
}
```
Using an array with `set` values:
```typescript
export type UserRoleType = "admin" | "editor" | "ghost"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: ["admin", "editor", "ghost"],
default: ["ghost", "editor"],
})
roles: UserRoleType[]
}
```

View File

@ -0,0 +1,21 @@
# Oracle
## Installation
```shell
npm install oracledb
```
By default, the [oracledb](https://github.com/oracle/node-oracledb) uses the "thin mode" to connect. To enable the "thick mode", you need to follow the installation instructions from
their [user guide](https://node-oracledb.readthedocs.io/en/latest/user_guide/installation.html).
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options.
- `sid` - The System Identifier (SID) identifies a specific database instance. For example, "sales".
- `serviceName` - The Service Name is an identifier of a database service. For example, `sales.us.example.com`.
## Column Types
`char`, `nchar`, `nvarchar2`, `varchar2`, `long`, `raw`, `long raw`, `number`, `numeric`, `float`, `dec`, `decimal`, `integer`, `int`, `smallint`, `real`, `double precision`, `date`, `timestamp`, `timestamp with time zone`, `timestamp with local time zone`, `interval year to month`, `interval day to second`, `bfile`, `blob`, `clob`, `nclob`, `rowid`, `urowid`

View File

@ -0,0 +1,166 @@
# Postgres / CockroachDB
PostgreSQL, CockroachDB and Amazon Aurora Postgres are supported as TypeORM drivers.
Databases that are PostgreSQL-compatible can also be used with TypeORM via the `postgres` data source type.
To use YugabyteDB, refer to [their ORM docs](https://docs.yugabyte.com/stable/drivers-orms/nodejs/typeorm/) to get started. Note that because some Postgres features are [not supported](https://docs.yugabyte.com/stable/develop/postgresql-compatibility/#unsupported-postgresql-features) by YugabyteDB, some TypeORM functionality may be limited.
## Installation
```shell
npm install pg
```
For streaming support:
```shell
npm install pg-query-stream
```
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options. You can use the data source type `postgres`, `cockroachdb` or `aurora-postgres` to connect to the respective databases.
- `url` - Connection url where the connection is performed. Please note that other data source options will override parameters set from url.
- `host` - Database host.
- `port` - Database host port. The default Postgres port is `5432`.
- `username` - Database username.
- `password` - Database password.
- `database` - Database name.
- `schema` - Schema name. Default is "public".
- `connectTimeoutMS` - The milliseconds before a timeout occurs during the initial connection to the postgres server. If `undefined`, or set to `0`, there is no timeout. Defaults to `undefined`.
- `ssl` - Object with ssl parameters. See [TLS/SSL](https://node-postgres.com/features/ssl).
- `uuidExtension` - The Postgres extension to use when generating UUIDs. Defaults to `uuid-ossp`. It can be changed to `pgcrypto` if the `uuid-ossp` extension is unavailable.
- `poolErrorHandler` - A function that gets called when the underlying pool emits `'error'` event. Takes a single parameter (error instance) and defaults to logging with `warn` level.
- `maxTransactionRetries` - A maximum number of transaction retries in case of a 40001 error. Defaults to 5.
- `logNotifications` - A boolean to determine whether postgres server [notice messages](https://www.postgresql.org/docs/current/plpgsql-errors-and-messages.html) and [notification events](https://www.postgresql.org/docs/current/sql-notify.html) should be included in client's logs with `info` level (default: `false`).
- `installExtensions` - A boolean to control whether to install necessary postgres extensions automatically or not (default: `true`)
- `applicationName` - A string visible in statistics and logs to help referencing an application to a connection (default: `undefined`)
- `parseInt8` - A boolean to enable parsing 64-bit integers (int8) as JavaScript numbers. By default, `int8` (bigint) values are returned as strings to avoid overflows. JavaScript numbers are IEEE-754 and lose precision over the maximum safe integer (`Number.MAX_SAFE_INTEGER = +2^53`). If you require the full 64-bit range consider working with the returned strings or converting them to native `bigint` instead of using this option.
Additional options can be added to the `extra` object and will be passed directly to the client library. See more in `pg`'s documentation for [Pool](https://node-postgres.com/apis/pool#new-pool) and [Client](https://node-postgres.com/apis/client#new-client).
## Column Types
### Column types for `postgres`
`int`, `int2`, `int4`, `int8`, `smallint`, `integer`, `bigint`, `decimal`, `numeric`, `real`, `float`, `float4`, `float8`, `double precision`, `money`, `character varying`, `varchar`, `character`, `char`, `text`, `citext`, `hstore`, `bytea`, `bit`, `varbit`, `bit varying`, `timetz`, `timestamptz`, `timestamp`, `timestamp without time zone`, `timestamp with time zone`, `date`, `time`, `time without time zone`, `time with time zone`, `interval`, `bool`, `boolean`, `enum`, `point`, `line`, `lseg`, `box`, `path`, `polygon`, `circle`, `cidr`, `inet`, `macaddr`, `macaddr8`, `tsvector`, `tsquery`, `uuid`, `xml`, `json`, `jsonb`, `int4range`, `int8range`, `numrange`, `tsrange`, `tstzrange`, `daterange`, `int4multirange`, `int8multirange`, `nummultirange`, `tsmultirange`, `tstzmultirange`, `multidaterange`, `geometry`, `geography`, `cube`, `ltree`
### Column types for `cockroachdb`
`array`, `bool`, `boolean`, `bytes`, `bytea`, `blob`, `date`, `numeric`, `decimal`, `dec`, `float`, `float4`, `float8`, `double precision`, `real`, `inet`, `int`, `integer`, `int2`, `int8`, `int64`, `smallint`, `bigint`, `interval`, `string`, `character varying`, `character`, `char`, `char varying`, `varchar`, `text`, `time`, `time without time zone`, `timestamp`, `timestamptz`, `timestamp without time zone`, `timestamp with time zone`, `json`, `jsonb`, `uuid`
Note: CockroachDB returns all numeric data types as `string`. However, if you omit the column type and define your property as `number` ORM will `parseInt` string into number.
### Spatial columns
TypeORM's PostgreSQL and CockroachDB support uses [GeoJSON](http://geojson.org/) as an interchange format, so geometry columns should be tagged either as `object` or `Geometry` (or subclasses, e.g. `Point`) after importing [`geojson` types](https://www.npmjs.com/package/@types/geojson) or using the TypeORM built-in GeoJSON types:
```typescript
import {
Entity,
PrimaryColumn,
Column,
Point,
LineString,
MultiPoint
} from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("geometry")
point: Point
@Column("geometry")
linestring: LineString
@Column("geometry", {
spatialFeatureType: "MultiPoint",
srid: 4326,
})
multiPointWithSRID: MultiPoint
}
...
const thing = new Thing()
thing.point = {
type: "Point",
coordinates: [116.443987, 39.920843],
}
thing.linestring = {
type: "LineString",
coordinates: [
[-87.623177, 41.881832],
[-90.199402, 38.627003],
[-82.446732, 38.413651],
[-87.623177, 41.881832],
],
}
thing.multiPointWithSRID = {
type: "MultiPoint",
coordinates: [
[100.0, 0.0],
[101.0, 1.0],
],
}
```
TypeORM tries to do the right thing, but it's not always possible to determine
when a value being inserted or the result of a PostGIS function should be
treated as a geometry. As a result, you may find yourself writing code similar
to the following, where values are converted into PostGIS `geometry`s from
GeoJSON and into GeoJSON as `json`:
```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()
```

44
docs/docs/drivers/sap.md Normal file
View File

@ -0,0 +1,44 @@
# SAP HANA
## Installation
TypeORM relies on `@sap/hana-client` for establishing the database connection:
```shell
npm install @sap/hana-client
```
If you are using TypeORM 0.3.25 or earlier, `hdb-pool` is also required for managing the pool.
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options.
- `host` - The hostname of the SAP HANA server. For example, `"localhost"`.
- `port` - The port number of the SAP HANA server. For example, `30015`.
- `username` - The username to connect to the SAP HANA server. For example, `"SYSTEM"`.
- `password` - The password to connect to the SAP HANA server. For example, `"password"`.
- `database` - The name of the database to connect to. For example, `"HXE"`.
- `encrypt` - Whether to encrypt the connection. For example, `true`.
- `sslValidateCertificate` - Whether to validate the SSL certificate. For example, `true`.
- `key`, `cert` and `ca` - Private key, public certificate and certificate authority for the encrypted connection.
- `pool` — Connection pool configuration object:
- `maxConnectedOrPooled` (number) — Max active or idle connections in the pool (default: 10).
- `maxPooledIdleTime` (seconds) — Time before an idle connection is closed (default: 30).
- `pingCheck` (boolean) — Whether to validate connections before use (default: false).
- `poolCapacity` (number) — Maximum number of connections to be kept available (default: no limit).
See the official documentation of SAP HANA Client for more details as well as the `extra` properties: [Node.js Connection Properties](https://help.sap.com/docs/SAP_HANA_CLIENT/f1b440ded6144a54ada97ff95dac7adf/4fe9978ebac44f35b9369ef5a4a26f4c.html).
## Column Types
SAP HANA 2.0 and SAP HANA Cloud support slightly different data types. Check the SAP Help pages for more information:
- [SAP HANA 2.0 Data Types](https://help.sap.com/docs/SAP_HANA_PLATFORM/4fe29514fd584807ac9f2a04f6754767/20a1569875191014b507cf392724b7eb.html?locale=en-US)
- [SAP HANA Cloud Data Types](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-sql-reference-guide/data-types)
TypeORM's `SapDriver` supports `tinyint`, `smallint`, `integer`, `bigint`, `smalldecimal`, `decimal`, `real`, `double`, `date`, `time`, `seconddate`, `timestamp`, `boolean`, `char`, `nchar`, `varchar`, `nvarchar`, `text`, `alphanum`, `shorttext`, `array`, `varbinary`, `blob`, `clob`, `nclob`, `st_geometry`, `st_point`, `real_vector` and `half_vector`. Some of these data types have been deprecated or removed in SAP HANA Cloud, and will be converted to the closest available alternative when connected to a Cloud database.
### Vector Types
The `real_vector` and `half_vector` data types were introduced in SAP HANA Cloud (2024Q1 and 2025Q2 respectively), and require a supported version of `@sap/hana-client` as well. By default, the client will return a `Buffer` in the `fvecs`/`hvecs` format, which is more efficient. It is possible to let the driver convert the values to a `number[]` by adding `{ extra: { vectorOutputType: "Array" } }` to the connection options. Check the SAP HANA Client documentation for more information about [REAL_VECTOR](https://help.sap.com/docs/SAP_HANA_CLIENT/f1b440ded6144a54ada97ff95dac7adf/0d197e4389c64e6b9cf90f6f698f62fe.html) or [HALF_VECTOR](https://help.sap.com/docs/SAP_HANA_CLIENT/f1b440ded6144a54ada97ff95dac7adf/8bb854b4ce4a4299bed27c365b717e91.html).

View File

@ -0,0 +1,78 @@
# SQLite
## Installation
- for **SQLite**:
```shell
npm install sqlite3
```
- for **Better SQLite**:
```shell
npm install better-sqlite3
```
- for **sql.js**:
```shell
npm install sql.js
```
- for **Capacitor**, **Cordova**, **Expo**, **NativeScript** and **React Native**, check the [supported platforms](../help/2-supported-platforms.md).
## Data Source Options
See [Data Source Options](../data-source/2-data-source-options.md) for the common data source options.
### `sqlite` data source options
- `database` - Database path. For example, "mydb.sql"
### `better-sqlite3` data source options
- `database` - Database path. For example, "mydb.sql"
- `statementCacheSize` - Cache size of the SQLite statement to speed up queries (default 100).
- `prepareDatabase` - Function to run before a database is used in typeorm. You can access the original better-sqlite3 Database object here.
- `nativeBinding` - Relative or absolute path to the native addon (better_sqlite3.node).
### `sql.js` data source options
- `database`: The raw UInt8Array database that should be imported.
- `sqlJsConfig`: Optional initialize config for sql.js.
- `autoSave`: Enable automatic persistence of database changes, requires either `location` or `autoSaveCallback`. When set to `true`, every change is saved to the file system (Node.js) or to `localStorage`/`indexedDB` (browser) if `location` is specified, or the `autoSaveCallback` is invoked otherwise.
- `autoSaveCallback`: A function that gets called when changes to the database are made and `autoSave` is enabled. The function gets a `UInt8Array` that represents the database.
- `location`: The file location to load and save the database to.
- `useLocalForage`: Enables the usage of the [localforage library](https://github.com/localForage/localForage) to save and load the database asynchronously from the indexedDB instead of using the synchrony local storage methods in a browser environment. The localforage node module needs to be added to your project, and the localforage.js should be imported in your page.
### `capacitor` data source options
- `database` - Database name (capacitor-sqlite will add the suffix `SQLite.db`)
- `driver` - The capacitor-sqlite instance. For example, `new SQLiteConnection(CapacitorSQLite)`.
- `mode` - Set the mode for database encryption: "no-encryption" | "encryption" | "secret" | "newsecret"
- `version` - Database version
- `journalMode` - The SQLite journal mode (optional)
### `cordova` data source options
- `database` - Database name
- `location` - Where to save the database. See [cordova-sqlite-storage](https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database) for options.
### `expo` data source options
- `database` - Name of the database. For example, "mydb".
- `driver` - The Expo SQLite module. For example, `require('expo-sqlite')`.
### `nativescript` data source options
- `database` - Database name
### `react-native` data source options
- `database` - Database name
- `location` - Where to save the database. See [react-native-sqlite-storage](https://github.com/andpor/react-native-sqlite-storage#opening-a-database) for options.
## Column Types
`int`, `int2`, `int8`, `integer`, `tinyint`, `smallint`, `mediumint`, `bigint`, `decimal`, `numeric`, `float`, `double`, `real`, `double precision`, `datetime`, `varying character`, `character`, `native character`, `varchar`, `nchar`, `nvarchar2`, `unsigned big int`, `boolean`, `blob`, `text`, `clob`, `date`

View File

@ -180,137 +180,6 @@ There are several special column types with additional functionality available:
each time you call `save` of entity manager or repository.
You don't need to set this column - it will be automatically set.
### Spatial columns
MS SQL, MySQL, MariaDB, PostgreSQL and CockroachDB all support spatial columns. TypeORM's
support for each varies slightly between databases, particularly as the column
names vary between databases.
MS SQL and MySQL / MariaDB's TypeORM support exposes (and expects) geometries to
be provided as [well-known text
(WKT)](https://en.wikipedia.org/wiki/Well-known_text), so geometry columns
should be tagged with the `string` type.
```typescript
import { Entity, PrimaryColumn, Column } from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("point")
point: string
@Column("linestring")
linestring: string
}
...
const thing = new Thing()
thing.point = "POINT(1 1)"
thing.linestring = "LINESTRING(0 0,1 1,2 2)"
```
TypeORM's PostgreSQL and CockroachDB support uses [GeoJSON](http://geojson.org/) as an
interchange format, so geometry columns should be tagged either as `object` or
`Geometry` (or subclasses, e.g. `Point`) after importing [`geojson`
types](https://www.npmjs.com/package/@types/geojson) or using TypeORM built in [GeoJSON types](../../../src/driver/types/GeoJsonTypes.ts).
```typescript
import {
Entity,
PrimaryColumn,
Column,
Point,
LineString,
MultiPoint
} from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("geometry")
point: Point
@Column("geometry")
linestring: LineString
@Column("geometry", {
spatialFeatureType: "MultiPoint",
srid: 4326,
})
multiPointWithSRID: MultiPoint
}
...
const thing = new Thing()
thing.point = {
type: "Point",
coordinates: [116.443987, 39.920843],
}
thing.linestring = {
type: "LineString",
coordinates: [
[-87.623177, 41.881832],
[-90.199402, 38.627003],
[-82.446732, 38.413651],
[-87.623177, 41.881832],
],
}
thing.multiPointWithSRID = {
type: "MultiPoint",
coordinates: [
[100.0, 0.0],
[101.0, 1.0],
],
}
```
TypeORM tries to do the right thing, but it's not always possible to determine
when a value being inserted or the result of a PostGIS function should be
treated as a geometry. As a result, you may find yourself writing code similar
to the following, where values are converted into PostGIS `geometry`s from
GeoJSON and into GeoJSON as `json`:
```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()
```
## Column types
TypeORM supports all of the most commonly used database-supported column types.
@ -344,76 +213,6 @@ or
> Note about `bigint` type: `bigint` column type, used in SQL databases, doesn't fit into the regular `number` type and maps property to a `string` instead.
### Column types for `mysql` / `mariadb`
`bit`, `int`, `integer`, `tinyint`, `smallint`, `mediumint`, `bigint`, `float`, `double`,
`double precision`, `dec`, `decimal`, `numeric`, `fixed`, `bool`, `boolean`, `date`, `datetime`,
`timestamp`, `time`, `year`, `char`, `nchar`, `national char`, `varchar`, `nvarchar`, `national varchar`,
`text`, `tinytext`, `mediumtext`, `blob`, `longtext`, `tinyblob`, `mediumblob`, `longblob`, `enum`, `set`,
`json`, `binary`, `varbinary`, `geometry`, `point`, `linestring`, `polygon`, `multipoint`, `multilinestring`,
`multipolygon`, `geometrycollection`, `uuid`, `inet4`, `inet6`
> Note: UUID, INET4, and INET6 are only available for mariadb and for respective versions that made them available.
### Column types for `postgres`
`int`, `int2`, `int4`, `int8`, `smallint`, `integer`, `bigint`, `decimal`, `numeric`, `real`,
`float`, `float4`, `float8`, `double precision`, `money`, `character varying`, `varchar`,
`character`, `char`, `text`, `citext`, `hstore`, `bytea`, `bit`, `varbit`, `bit varying`,
`timetz`, `timestamptz`, `timestamp`, `timestamp without time zone`, `timestamp with time zone`,
`date`, `time`, `time without time zone`, `time with time zone`, `interval`, `bool`, `boolean`,
`enum`, `point`, `line`, `lseg`, `box`, `path`, `polygon`, `circle`, `cidr`, `inet`, `macaddr`, `macaddr8`,
`tsvector`, `tsquery`, `uuid`, `xml`, `json`, `jsonb`, `int4range`, `int8range`, `numrange`,
`tsrange`, `tstzrange`, `daterange`, `int4multirange`, `int8multirange`, `nummultirange`,
`tsmultirange`, `tstzmultirange`, `multidaterange`, `geometry`, `geography`, `cube`, `ltree`
### Column types for `cockroachdb`
`array`, `bool`, `boolean`, `bytes`, `bytea`, `blob`, `date`, `numeric`, `decimal`, `dec`, `float`,
`float4`, `float8`, `double precision`, `real`, `inet`, `int`, `integer`, `int2`, `int8`, `int64`,
`smallint`, `bigint`, `interval`, `string`, `character varying`, `character`, `char`, `char varying`,
`varchar`, `text`, `time`, `time without time zone`, `timestamp`, `timestamptz`, `timestamp without time zone`,
`timestamp with time zone`, `json`, `jsonb`, `uuid`
> Note: CockroachDB returns all numeric data types as `string`. However if you omit column type and define your property as
> `number` ORM will `parseInt` string into number.
### Column types for `sqlite` / `cordova` / `react-native` / `expo`
`int`, `int2`, `int8`, `integer`, `tinyint`, `smallint`, `mediumint`, `bigint`, `decimal`,
`numeric`, `float`, `double`, `real`, `double precision`, `datetime`, `varying character`,
`character`, `native character`, `varchar`, `nchar`, `nvarchar2`, `unsigned big int`, `boolean`,
`blob`, `text`, `clob`, `date`
### Column types for `mssql`
`int`, `bigint`, `bit`, `decimal`, `money`, `numeric`, `smallint`, `smallmoney`, `tinyint`, `float`,
`real`, `date`, `datetime2`, `datetime`, `datetimeoffset`, `smalldatetime`, `time`, `char`, `varchar`,
`text`, `nchar`, `nvarchar`, `ntext`, `binary`, `image`, `varbinary`, `hierarchyid`, `sql_variant`,
`timestamp`, `uniqueidentifier`, `xml`, `geometry`, `geography`, `rowversion`
### Column types for `oracle`
`char`, `nchar`, `nvarchar2`, `varchar2`, `long`, `raw`, `long raw`, `number`, `numeric`, `float`, `dec`,
`decimal`, `integer`, `int`, `smallint`, `real`, `double precision`, `date`, `timestamp`, `timestamp with time zone`,
`timestamp with local time zone`, `interval year to month`, `interval day to second`, `bfile`, `blob`, `clob`,
`nclob`, `rowid`, `urowid`
### Column types for `sap`
SAP HANA 2.0 and SAP HANA Cloud support slightly different data types. Check the SAP Help pages for more information:
- [SAP HANA 2.0 Data Types](https://help.sap.com/docs/SAP_HANA_PLATFORM/4fe29514fd584807ac9f2a04f6754767/20a1569875191014b507cf392724b7eb.html?locale=en-US)
- [SAP HANA Cloud Data Types](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-sql-reference-guide/data-types)
TypeORM's `SapDriver` supports `tinyint`, `smallint`, `integer`, `bigint`, `smalldecimal`, `decimal`, `real`, `double`, `date`, `time`, `seconddate`, `timestamp`, `boolean`, `char`, `nchar`, `varchar`, `nvarchar`, `text`, `alphanum`, `shorttext`, `array`, `varbinary`, `blob`, `clob`, `nclob`, `st_geometry`, `st_point`, `real_vector` and `half_vector`. Some of these data types have been deprecated or removed in SAP HANA Cloud, and will be converted to the closest available alternative when connected to a Cloud database.
The `real_vector` and `half_vector` data types were introduced in SAP HANA Cloud (2024Q1 and 2025Q2 respectively), and require a supported version of `@sap/hana-client` as well. By default, the client will return a `Buffer` in the `fvecs`/`hvecs` format, which is more efficient. It is possible to let the driver convert the values to a `number[]` by adding `{ extra: { vectorOutputType: "Array" } }` to the connection options. Check the SAP HANA Client documentation for more information about [REAL_VECTOR](https://help.sap.com/docs/SAP_HANA_CLIENT/f1b440ded6144a54ada97ff95dac7adf/0d197e4389c64e6b9cf90f6f698f62fe.html) or [HALF_VECTOR](https://help.sap.com/docs/SAP_HANA_CLIENT/f1b440ded6144a54ada97ff95dac7adf/8bb854b4ce4a4299bed27c365b717e91.html).
### Column types for `spanner`
`bool`, `int64`, `float64`, `numeric`, `string`, `json`, `bytes`, `date`, `timestamp`, `array`
### `enum` column type
`enum` column type is supported by `postgres` and `mysql`. There are various possible column definitions:
@ -463,53 +262,6 @@ export class User {
}
```
### `set` column type
`set` column type is supported by `mariadb` and `mysql`. There are various possible column definitions:
Using typescript enums:
```typescript
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: UserRole,
default: [UserRole.GHOST, UserRole.EDITOR],
})
roles: UserRole[]
}
```
Using array with `set` values:
```typescript
export type UserRoleType = "admin" | "editor" | "ghost",
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
type: "set",
enum: ["admin", "editor", "ghost"],
default: ["ghost", "editor"]
})
roles: UserRoleType[]
}
```
### `simple-array` column type
There is a special column type called `simple-array` which can store primitive array values in a single string column.
@ -586,6 +338,38 @@ Besides "uuid" there is also "increment", "identity" (Postgres 10+ only) and "ro
on some database platforms with this type of generation (for example some databases can only have one increment column,
or some of them require increment to be a primary key).
### Spatial columns
Microsoft SQLServer, MySQL/MariaDB, PostgreSQL/CockroachDB and SAP HANA all support spatial columns. TypeORM's support for each varies slightly between databases, particularly as the column names vary between databases.
MS SQL, MySQL/MariaDB and SAP HANA use geometries in the [well-known text
(WKT)](https://en.wikipedia.org/wiki/Well-known_text) format, so geometry columns
should be tagged with the `string` type.
```typescript
import { Entity, PrimaryColumn, Column } from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("point")
point: string
@Column("linestring")
linestring: string
}
...
const thing = new Thing()
thing.point = "POINT(1 1)"
thing.linestring = "LINESTRING(0 0,1 1,2 2)"
```
For Postgres/CockroachDB, see [Postgis Data Types](../drivers/postgres.md#spatial-columns)
## Column options
Column options defines additional options for your entity columns.

View File

@ -285,13 +285,13 @@ const postCategory = await dataSource.manager.findOneBy(PostCategory, { id: 1 })
the result in `postCategories` will be:
```
```javascript
[ PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' },
PostCategory { id: 2, name: 'About Boeing', categoryName: 'Airplanes' } ]
```
and in `postCategory`:
```
```javascript
PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' }
```

View File

@ -1,7 +1,7 @@
# Getting Started
TypeORM is an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)
that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms
that can run in Node.js, Browser, Cordova, Ionic, React Native, NativeScript, Expo, and Electron platforms
and can be used with TypeScript and JavaScript (ES2021).
Its goal is to always support the latest JavaScript features and provide additional features
@ -9,6 +9,8 @@ that help you to develop any kind of application that uses databases - from
small applications with a few tables to large-scale enterprise applications
with multiple databases.
TypeORM supports more databases than any other JS/TS ORM: [Google Spanner](./drivers/google-spanner.md), [Microsoft SqlServer](./drivers/microsoft-sqlserver.md), [MongoDB](./drivers/mongodb.md), [MySQL/MariaDB](./drivers/mysql.md), [Oracle](./drivers/oracle.md), [Postgres](./drivers/postgres.md), [SAP HANA](./drivers/sap.md) and [SQLite](./drivers/sqlite.md), as well we derived databases and different drivers.
TypeORM supports both [Active Record](./guides/1-active-record-data-mapper.md#what-is-the-active-record-pattern) and [Data Mapper](./guides/1-active-record-data-mapper.md#what-is-the-data-mapper-pattern) patterns,
unlike all other JavaScript ORMs currently in existence,
which means you can write high-quality, loosely coupled, scalable,
@ -27,7 +29,7 @@ TypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate
- Clean object-relational model.
- Associations (relations).
- Eager and lazy relations.
- Uni-directional, bi-directional, and self-referenced relations.
- Unidirectional, bidirectional, and self-referenced relations.
- Supports multiple inheritance patterns.
- Cascades.
- Indices.
@ -49,7 +51,7 @@ TypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate
- Schema declaration in models or separate configuration files.
- Supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js.
- Supports MongoDB NoSQL database.
- Works in NodeJS / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
- Works in Node.js / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
- TypeScript and JavaScript support.
- ESM and CommonJS support.
- Produced code is performant, flexible, clean, and maintainable.
@ -58,7 +60,7 @@ TypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate
And more...
With TypeORM your models look like this:
With TypeORM, your models look like this:
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@ -148,11 +150,11 @@ await timber.remove()
1. Install the npm package:
`npm install typeorm --save`
`npm install typeorm`
2. You need to install `reflect-metadata` shim:
`npm install reflect-metadata --save`
`npm install reflect-metadata`
and import it somewhere in the global place of your app (for example in `app.ts`):
@ -162,77 +164,9 @@ await timber.remove()
`npm install @types/node --save-dev`
4. Install a database driver:
4. Install a database driver: see the documentation for each particular driver: [mongodb](./drivers/mongodb.md#installation), [mssql](./drivers/microsoft-sqlserver.md#installation), [mysql/mariadb](./drivers/mysql.md#installation), [oracle](./drivers/oracle.md#installation), [postgres](./drivers/postgres.md#installation), [sap](./drivers/sap.md#installation), [spanner](./drivers/google-spanner.md#installation), [sqlite](./drivers/sqlite.md#installation).
- for **MySQL** or **MariaDB**
`npm install mysql --save` (you can install `mysql2` instead as well)
- for **PostgreSQL** or **CockroachDB**
`npm install pg --save`
- for **SQLite**
`npm install sqlite3 --save`
- for **Microsoft SQL Server**
`npm install mssql --save`
- for **sql.js**
`npm install sql.js --save`
- for **Oracle**
`npm install oracledb --save`
To make the Oracle driver work, you need to follow the installation instructions from
[their](https://github.com/oracle/node-oracledb) site.
- for **SAP Hana**
`npm install @sap/hana-client --save`
- for **Google Cloud Spanner**
`npm install @google-cloud/spanner --save`
Provide authentication credentials to your application code
by setting the environment variable `GOOGLE_APPLICATION_CREDENTIALS`:
```shell
# Linux/macOS
export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"
# Windows
set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
# Replace KEY_PATH with the path of the JSON file that contains your service account key.
```
To use Spanner with the emulator you should set `SPANNER_EMULATOR_HOST` environment variable:
```shell
# Linux/macOS
export SPANNER_EMULATOR_HOST=localhost:9010
# Windows
set SPANNER_EMULATOR_HOST=localhost:9010
```
- for **MongoDB** (experimental)
`npm install mongodb@^5.2.0 --save`
- for **NativeScript**, **react-native** and **Cordova**
Check [documentation of supported platforms](./help/2-supported-platforms.md)
Install only _one_ of them, depending on which database you use.
##### TypeScript configuration
### TypeScript configuration
Also, make sure you are using TypeScript version **4.5** or higher,
and you have enabled the following settings in `tsconfig.json`:
@ -242,12 +176,10 @@ and you have enabled the following settings in `tsconfig.json`:
"experimentalDecorators": true,
```
You may also need to enable `es6` in the `lib` section of compiler options, or install `es6-shim` from `@types`.
## Quick Start
The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project.
Quick start works only if you are using TypeORM in a NodeJS application.
Quick start works only if you are using TypeORM in a Node.js application.
If you are using other platforms, proceed to the [step-by-step guide](#step-by-step-guide).
To create a new project using CLI, run the following command:
@ -262,7 +194,7 @@ Database can be one of the following values: `mysql`, `mariadb`, `postgres`, `co
This command will generate a new project in the `MyProject` directory with the following files:
```
```text
MyProject
├── src // place of your TypeScript code
│ ├── entity // place where your entities (database models) are stored
@ -328,7 +260,7 @@ creating more entities.
## Step-by-Step Guide
What are you expecting from ORM?
First of all, you are expecting it will create database tables for you
First, you are expecting it will create database tables for you
and find / insert / update / delete your data without the pain of
having to write lots of hardly maintainable SQL queries.
This guide will show you how to set up TypeORM from scratch and make it do what you are expecting from an ORM.
@ -381,13 +313,13 @@ export class Photo {
}
```
Now, a database table will be created for the `Photo` entity and we'll be able to work with it anywhere in our app.
Now, a database table will be created for the `Photo` entity, and we'll be able to work with it anywhere in our app.
We have created a database table, however, what table can exist without columns?
Let's create a few columns in our database table.
### Adding table columns
To add database columns, you simply need to decorate an entity's properties you want to make into a column
To add database columns, you need to decorate an entity's properties you want to make into a column
with a `@Column` decorator.
```typescript
@ -426,7 +358,7 @@ Each database table must have a column with a primary key.
### Creating a primary column
Each entity **must** have at least one primary key column.
This is a requirement and you can't avoid it.
This is a requirement, and you can't avoid it.
To make a column a primary key, you need to use the `@PrimaryColumn` decorator.
```typescript
@ -488,8 +420,8 @@ export class Photo {
Next, let's fix our data types. By default, the string is mapped to a varchar(255)-like type (depending on the database type).
The number is mapped to an integer-like type (depending on the database type).
We don't want all our columns to be limited varchars or integers.
Let's setup the correct data types:
We don't want all our columns to be limited to varchars or integers.
Let's set up the correct data types:
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"
@ -546,15 +478,15 @@ const AppDataSource = new DataSource({
// 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))
try {
await AppDataSource.initialize()
} catch (error) {
console.log(error)
}
```
We are using Postgres in this example, but you can use any other supported database.
To use another database, simply change the `type` in the options to the database type you are using:
To use another database, change the `type` in the options to the database type you are using:
`mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `oracle`, `sap`, `spanner`, `cordova`, `nativescript`, `react-native`,
`expo`, or `mongodb`.
Also make sure to use your own host, port, username, password, and database settings.
@ -568,7 +500,7 @@ Setting `synchronize` makes sure your entities will be synced with the database,
Now if you run your `index.ts`, a connection with the database will be initialized and a database table for your photos will be created.
```shell
```text
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
@ -600,7 +532,7 @@ await AppDataSource.manager.save(photo)
console.log("Photo has been saved. Photo id is", photo.id)
```
Once your entity is saved it will get a newly generated id.
Once your entity is saved, it will get a newly generated id.
`save` method returns an instance of the same object you pass to it.
It's not a new copy of the object, it modifies its "id" and returns it.
@ -608,7 +540,7 @@ It's not a new copy of the object, it modifies its "id" and returns it.
We just created a new photo and saved it in the database.
We used `EntityManager` to save it.
Using entity manager you can manipulate any entity in your app.
Using entity manager, you can manipulate any entity in your app.
For example, let's load our saved entity:
```typescript
@ -621,7 +553,7 @@ console.log("All photos from the db: ", savedPhotos)
`savedPhotos` will be an array of Photo objects with the data loaded from the database.
Learn more about EntityManager [here](./working-with-entity-manager/1-working-with-entity-manager.md).
Learn more about [EntityManager](./working-with-entity-manager/1-working-with-entity-manager.md).
### Using Repositories
@ -686,7 +618,7 @@ console.log("Photos count: ", photosCount)
### Updating in the database
Now let's load a single photo from the database, update it and save it:
Now let's load a single photo from the database, update it, and save it:
```typescript
import { Photo } from "./entity/Photo"
@ -762,12 +694,12 @@ export class PhotoMetadata {
Here, we are using a new decorator called `@OneToOne`. It allows us to create a one-to-one relationship between two entities. We also add a `@JoinColumn` decorator, which indicates that this side of the relationship will own the relationship.
Relations can be unidirectional or bidirectional.
Only one side of relational can be owning.
Only one side of the relation can be the owner.
Using `@JoinColumn` decorator is required on the owner side of the relationship.
If 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:
```shell
```text
+-------------+--------------+----------------------------+
| photo_metadata |
+-------------+--------------+----------------------------+
@ -783,13 +715,13 @@ If you run the app, you'll see a newly generated table, and it will contain a co
### Save a one-to-one relation
Now let's save a photo, and its metadata and attach them to each other.
Now let's save a photo and its metadata and attach them to each other.
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
// create a photo
// Create a photo
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
@ -797,7 +729,7 @@ photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true
// create a photo metadata
// Create a photo metadata
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
@ -806,17 +738,17 @@ metadata.comment = "cybershoot"
metadata.orientation = "portrait"
metadata.photo = photo // this way we connect them
// get entity repositories
// Get entity repositories
const photoRepository = AppDataSource.getRepository(Photo)
const metadataRepository = AppDataSource.getRepository(PhotoMetadata)
// first we should save a photo
// First we should save a photo
await photoRepository.save(photo)
// photo is saved. Now we need to save a photo metadata
// The Photo is saved. Now we need to save a photo metadata
await metadataRepository.save(metadata)
// done
// Done
console.log(
"Metadata is saved, and the relation between metadata and photo is created in the database too",
)
@ -828,7 +760,7 @@ Relations can be unidirectional or bidirectional.
Currently, our relation between PhotoMetadata and Photo is unidirectional.
The owner of the relation is PhotoMetadata, and Photo doesn't know anything about PhotoMetadata.
This makes it complicated to access PhotoMetadata from the Photo side.
To fix this issue we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional.
To fix this issue, we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional.
Let's modify our entities:
```typescript
@ -866,7 +798,7 @@ export class Photo {
`photo => photo.metadata` is a function that returns the name of the inverse side of the relation.
Here we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class.
Instead of passing a function that returns a property of the photo, you could alternatively simply pass a string to `@OneToOne` decorator, like `"metadata"`.
Instead of passing a function that returns a property of the photo, you could alternatively spass a string to `@OneToOne` decorator, like `"metadata"`.
But we used this function-typed approach to make our refactoring easier.
Note that we should use the `@JoinColumn` decorator only on one side of a relation.
@ -942,7 +874,7 @@ Here, photos will contain an array of photos from the database, and each photo w
Learn more about Find Options in [this documentation](./working-with-entity-manager/3-find-options.md).
Using find options is good and dead simple, but if you need a more complex query, you should use `QueryBuilder` instead.
`QueryBuilder` allows more complex queries to be used in an elegant way:
`QueryBuilder` allows more complex queries to be used elegantly:
```typescript
import { Photo } from "./entity/Photo"
@ -1063,7 +995,7 @@ It means that the class that uses `@ManyToOne` will store the id of the related
After you run the application, the ORM will create the `author` table:
```shell
```text
+-------------+--------------+----------------------------+
| author |
+-------------+--------------+----------------------------+
@ -1074,7 +1006,7 @@ After you run the application, the ORM will create the `author` table:
It will also modify the `photo` table, adding a new `author` column and creating a foreign key for it:
```shell
```text
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
@ -1129,9 +1061,9 @@ export class Photo {
}
```
After you run the application, the ORM will create a **album_photos_photo_albums** _junction table_:
After you run the application, the ORM will create an **album_photos_photo_albums** _junction table_:
```shell
```text
+-------------+--------------+----------------------------+
| album_photos_photo_albums |
+-------------+--------------+----------------------------+
@ -1140,7 +1072,7 @@ After you run the application, the ORM will create a **album_photos_photo_albums
+-------------+--------------+----------------------------+
```
Don't forget to register the `Album` class with your connection in the ORM:
Remember to register the `Album` class with your connection in the ORM:
```typescript
const options: DataSourceOptions = {
@ -1209,7 +1141,7 @@ You can use QueryBuilder to build SQL queries of almost any complexity. For exam
```typescript
const photos = await AppDataSource.getRepository(Photo)
.createQueryBuilder("photo") // first argument is an alias. Alias is what you are selecting - photos. You must specify it.
.createQueryBuilder("photo") // First argument is an alias. Alias is what you are selecting - photos. You must specify it.
.innerJoinAndSelect("photo.metadata", "metadata")
.leftJoinAndSelect("photo.albums", "album")
.where("photo.isPublished = true")
@ -1225,7 +1157,7 @@ This query selects all published photos with "My" or "Mishka" names.
It will select results from position 5 (pagination offset)
and will select only 10 results (pagination limit).
The selection result will be ordered by id in descending order.
The photo albums will be left joined and their metadata will be inner joined.
The photo albums will be left joined and their metadata will be inner-joined.
You'll use the query builder in your application a lot.
Learn more about QueryBuilder [here](./query-builder/1-select-query-builder.md).
@ -1244,7 +1176,7 @@ There are a few repositories that you can clone and start with:
- [Example how to use Express and TypeORM](https://github.com/typeorm/typescript-express-example)
- [Example how to use Koa and TypeORM](https://github.com/typeorm/typescript-koa-example)
- [Example how to use TypeORM with MongoDB](https://github.com/typeorm/mongo-typescript-example)
- [Example how to use TypeORM in a Cordova/PhoneGap app](https://github.com/typeorm/cordova-example)
- [Example how to use TypeORM in a Cordova app](https://github.com/typeorm/cordova-example)
- [Example how to use TypeORM with an Ionic app](https://github.com/typeorm/ionic-example)
- [Example how to use TypeORM with React Native](https://github.com/typeorm/react-native-example)
- [Example how to use TypeORM with Nativescript-Vue](https://github.com/typeorm/nativescript-vue-typeorm-sample)
@ -1262,7 +1194,7 @@ There are several extensions that simplify working with TypeORM and integrating
- Fixtures loader - [typeorm-fixtures-cli](https://github.com/RobinCK/typeorm-fixtures)
- ER Diagram generator - [typeorm-uml](https://github.com/eugene-manuilov/typeorm-uml/)
- another ER Diagram generator - [erdia](https://www.npmjs.com/package/erdia/)
- Create, drop & seed database - [typeorm-extension](https://github.com/tada5hi/typeorm-extension)
- Create, drop and seed database - [typeorm-extension](https://github.com/tada5hi/typeorm-extension)
- Automatically update `data-source.ts` after generating migrations/entities - [typeorm-codebase-sync](https://www.npmjs.com/package/typeorm-codebase-sync)
- Easy manipulation of `relations` objects - [typeorm-relations](https://npmjs.com/package/typeorm-relations)
- Automatically generate `relations` based on a GraphQL query - [typeorm-relations-graphql](https://npmjs.com/package/typeorm-relations-graphql)
@ -1277,7 +1209,7 @@ This project exists thanks to all the people who contribute:
## Sponsors
Open source is hard and time-consuming. If you want to invest in 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)
Open source is hard and time-consuming. If you want to invest in 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)
<a href="https://opencollective.com/typeorm" target="_blank"><img src="https://opencollective.com/typeorm/tiers/sponsor.svg?width=890"/></a>

View File

@ -8,13 +8,13 @@ within web api.
First, create a directory called "user":
```
```shell
mkdir user
```
Then switch to the directory and create a new project:
```
```shell
cd user
npm init
```
@ -23,7 +23,7 @@ Finish the init process by filling in all required application information.
Now we need to install and setup a TypeScript compiler. Lets install it first:
```
```shell
npm i typescript --save-dev
```
@ -45,7 +45,7 @@ compile and run. Create it using your favorite editor and put the following conf
Now let's create a main application endpoint - `app.ts` inside the `src` directory:
```
```shell
mkdir src
cd src
touch app.ts
@ -60,14 +60,14 @@ console.log("Application is up and running")
Now it's time to run our application.
To run it, you need to compile your typescript project first:
```
```shell
tsc
```
Once you compile it, you should have a `src/app.js` file generated.
You can run it using:
```
```shell
node src/app.js
```
@ -80,8 +80,9 @@ Alternatively, you can set up watcher or install [ts-node](https://github.com/Ty
Let's add Express to our application. First, let's install the packages we need:
```
npm i express @types/express --save
```shell
npm install express
npm install @types/express --save-dev
```
- `express` is the express engine itself. It allows us to create a web api
@ -135,14 +136,13 @@ Setup process for other drivers is similar.
Let's install the required packages first:
```
npm i typeorm mysql reflect-metadata --save
```shell
npm install typeorm reflect-metadata mysql
```
- `typeorm` is the typeorm package itself
- `mysql` is the underlying database driver.
If you are using a different database system, you must install the appropriate package
- `reflect-metadata` is required to make decorators to work properly
- `reflect-metadata` is required to make decorators to work properly. Remember to import it before your TypeORM code.
- `mysql` is the underlying database driver. If you are using a different database system, you must install the appropriate package
Let's create `app-data-source.ts` where we set up initial database connection options:
@ -186,20 +186,20 @@ export class User {
Let's change `src/app.ts` to establish database connection and start using `myDataSource`:
```typescript
import "reflect-metadata"
import * as express from "express"
import { Request, Response } from "express"
import { User } from "./entity/User"
import { myDataSource } from "./app-data-source.ts"
// establish database connection
myDataSource
.initialize()
.then(() => {
console.log("Data Source has been initialized!")
})
.catch((err) => {
console.error("Error during Data Source initialization:", err)
})
try {
await myDataSource.initialize()
console.log("Data Source has been initialized!")
} catch (error) {
console.error("Error during Data Source initialization:", error)
}
// create and setup express app
const app = express()

View File

@ -14,25 +14,29 @@ const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
Parameters are automatically escaped and formatted according to your database type:
- **PostgreSQL, CockroachDB, Aurora PostgreSQL, MariaDB**: Uses `$1`, `$2`, etc.
- **PostgreSQL**, **CockroachDB**, **Aurora PostgreSQL** uses `$1`, `$2`, etc.:
```typescript
// Query becomes: SELECT * FROM users WHERE name = $1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```
- **MySQL, SQLite, Aurora MySQL**: Uses `?`
- **MySQL**, **MariaDB**, **Aurora MySQL**, **SAP**, **SQLite** use `?`:
```typescript
// Query becomes: SELECT * FROM users WHERE name = ?
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```
- **Oracle**: Uses `:1`, `:2`, etc.
- **Oracle** uses `:1`, `:2`, etc.:
```typescript
// Query becomes: SELECT * FROM users WHERE name = :1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
```
- **MSSQL**: Uses `@1`, `@2`, etc.
- **MSSQL** uses `@1`, `@2`, etc.:
```typescript
// Query becomes: SELECT * FROM users WHERE name = @1
const users = await dataSource.sql`SELECT * FROM users WHERE name = ${"John"}`
@ -81,9 +85,9 @@ const rawData = await dataSource.sql`
## Features
- **SQL Injection Prevention**: Parameters are properly escaped
- **Database Agnostic**: Parameter formatting is handled based on your database type
- **Readable Queries**: Template literals can make queries more readable than parameter arrays
- **SQL Injection Prevention**: Parameters are properly escaped
- **Database Agnostic**: Parameter formatting is handled based on your database type
- **Readable Queries**: Template literals can make queries more readable than parameter arrays
## Comparison with Query Method
@ -91,10 +95,10 @@ The traditional `query` method requires manual parameter placeholder handling:
```typescript
// Traditional query method
await dataSource.query(
"SELECT * FROM users WHERE name = $1 AND age > $2",
["John", 30]
)
await dataSource.query("SELECT * FROM users WHERE name = $1 AND age > $2", [
"John",
30,
])
// SQL tag alternative
await dataSource.sql`SELECT * FROM users WHERE name = ${"John"} AND age > ${30}`

View File

@ -21,7 +21,7 @@ There are two ways that help you achieve this:
- Use command line tools and run schema sync manually in the command line:
```
```shell
typeorm schema:sync
```
@ -135,7 +135,7 @@ That's why when you remove and move entities with `outDir` enabled, it's strongl
You can prevent compiling files each time using [ts-node](https://github.com/TypeStrong/ts-node).
If you are using ts-node, you can specify `ts` entities inside data source options:
```
```javascript
{
entities: ["src/entity/*.ts"],
subscribers: ["src/subscriber/*.ts"]
@ -148,13 +148,13 @@ make sure to use the `outDir` compiler option to prevent
Also, if you want to use the ts-node CLI, you can execute TypeORM the following way:
```
```shell
npx typeorm-ts-node-commonjs schema:sync
```
For ESM projects use this instead:
```
```shell
npx typeorm-ts-node-esm schema:sync
```
@ -162,7 +162,7 @@ npx typeorm-ts-node-esm schema:sync
Webpack produces warnings due to what it views as missing require statements -- require statements for all drivers supported by TypeORM. To suppress these warnings for unused drivers, you will need to edit your webpack config file.
```js
```javascript
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
module.exports = {
@ -180,7 +180,7 @@ module.exports = {
By default Webpack tries to bundle everything into one file. This can be problematic when your project has migration files which are meant to be executed after bundled code is deployed to production. To make sure all your migrations can be recognized and executed by TypeORM, you may need to use "Object Syntax" for the `entry` configuration for the migration files only.
```js
```javascript
const glob = require("glob")
const path = require("path")
@ -212,7 +212,7 @@ module.exports = {
Also, since Webpack 4, when using `mode: 'production'`, files are optimized by default which includes mangling your code in order to minimize file sizes. This breaks the migrations because TypeORM relies on their names to determine which has already been executed. You may disable minimization completely by adding:
```js
```javascript
module.exports = {
// ... other Webpack configurations here
optimization: {
@ -223,7 +223,7 @@ module.exports = {
Alternatively, if you are using the `UglifyJsPlugin`, you can tell it to not change class or function names like so:
```js
```javascript
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
module.exports = {
@ -243,7 +243,7 @@ module.exports = {
Lastly, make sure in your data source options, the transpiled migration files are included:
```js
```javascript
// TypeORM Configurations
module.exports = {
// ...
@ -264,7 +264,7 @@ On production builds, files are [optimized by default](https://vite.dev/config/b
You have 3 options to mitigate this. The 3 options are shown belown as diff to this basic "vite.config.ts"
```ts
```typescript
import legacy from "@vitejs/plugin-legacy"
import vue from "@vitejs/plugin-vue"
import path from "path"

View File

@ -2,13 +2,13 @@
## NodeJS
TypeORM was tested on Node.js version 14 and above.
TypeORM is compatible with Node.js 16+ and currently each commit is tested on Node.js 18 and 20.
## Browser
You can use [sql.js](https://sql.js.org) in the browser.
#### Webpack configuration
### Webpack configuration
In the `browser` folder the package also includes a version compiled as a ES2015 module. If you want to use a different loader this is the point to start. Prior to TypeORM 0.1.7, the package is setup in a way that loaders like webpack will automatically use the `browser` folder. With 0.1.7 this was dropped to support Webpack usage in Node.js projects. This means, that the `NormalModuleReplacementPlugin` has to be used to insure that the correct version is loaded for browser projects. The configuration in your webpack config file, for this plugin looks like this:
@ -26,7 +26,7 @@ plugins: [
and make sure [sql-wasm.wasm file](https://github.com/sql-js/sql.js/blob/master/README.md#downloadingusing) exists in your public path.
#### Example of configuration
### Example of configuration
```typescript
new DataSource({
@ -36,7 +36,7 @@ new DataSource({
})
```
#### Don't forget to include reflect-metadata
### Don't forget to include reflect-metadata
In your main html page, you need to include reflect-metadata:
@ -44,16 +44,16 @@ In your main html page, you need to include reflect-metadata:
<script src="./node_modules/reflect-metadata/Reflect.js"></script>
```
## Cordova / PhoneGap / Ionic apps
## Capacitor
TypeORM is able to run on Cordova, PhoneGap, Ionic apps using the
See [Using TypeORM with the Capacitor driver type](https://github.com/capacitor-community/sqlite/blob/master/docs/TypeORM-Usage-From-5.6.0.md) in the official Capacitor docs.
## Cordova / Ionic apps
TypeORM is able to run on Cordova/Ionic apps using the
[cordova-sqlite-storage](https://github.com/litehelpers/Cordova-sqlite-storage) plugin
You have the option to choose between module loaders just like in browser package.
For an example how to use TypeORM in Cordova see [typeorm/cordova-example](https://github.com/typeorm/cordova-example) and for Ionic see [typeorm/ionic-example](https://github.com/typeorm/ionic-example). **Important**: For use with Ionic, a custom webpack config file is needed! Please checkout the example to see the needed changes. Note that there is currently no support for transactions when using the [cordova-sqlite-storage](https://github.com/litehelpers/Cordova-sqlite-storage) plugin. See https://github.com/storesafe/cordova-sqlite-storage#other-limitations for more information.
## React Native
TypeORM is able to run on React Native apps using the [react-native-sqlite-storage](https://github.com/andpor/react-native-sqlite-storage) plugin. For an example see [typeorm/react-native-example](https://github.com/typeorm/react-native-example).
For an example how to use TypeORM in Cordova see [typeorm/cordova-example](https://github.com/typeorm/cordova-example) and for Ionic see [typeorm/ionic-example](https://github.com/typeorm/ionic-example). **Important**: For use with Ionic, a custom webpack config file is needed! Please checkout the example to see the needed changes. Note that there is currently no support for transactions when using the [cordova-sqlite-storage](https://github.com/litehelpers/Cordova-sqlite-storage) plugin. See [Cordova SQLite limitations](https://github.com/storesafe/cordova-sqlite-storage#other-limitations) for more information.
## Expo
@ -87,3 +87,7 @@ which will **NOT** run as it is. It has to be bundled.
Please use the `tns run --bundle` method_
Checkout example [here](https://github.com/championswimmer/nativescript-vue-typeorm-sample)!
## React Native
TypeORM is able to run on React Native apps using the [react-native-sqlite-storage](https://github.com/andpor/react-native-sqlite-storage) plugin. For an example see [typeorm/react-native-example](https://github.com/typeorm/react-native-example).

View File

@ -258,7 +258,7 @@ export class User {
}
```
Learn more about [MongoDB](../guides/2-mongodb.md).
Learn more about [MongoDB](../drivers/mongodb.md).
#### `@CreateDateColumn`

View File

@ -1,18 +1,18 @@
# Support
### Found a bug or want to propose a new feature?
## Found a bug or want to propose a new feature?
If you found a bug, issue, or you just want to propose a new feature, create [an issue on GitHub](https://github.com/typeorm/typeorm/issues).
### Have a question?
## Have a question?
If you have a question, you can ask it on [StackOverflow](https://stackoverflow.com/questions/tagged/typeorm) or other community support channels.
### Want community support?
## Want community support?
If you want community support, or simply want to chat with friendly TypeORM enthusiasts and users, you can do it on [Discord](https://discord.gg/cC9hkmUgNa).
### Want professional commercial support?
## Want professional commercial support?
The TypeORM core team is always ready to provide professional commercial support.
We are ready to work with any team in any part of the world.

View File

@ -29,7 +29,7 @@ WHERE user.id = 1
and returns you an instance of `User`:
```
```javascript
User {
id: 1,
firstName: "Timber",
@ -41,26 +41,26 @@ User {
When using the `QueryBuilder`, you need to provide unique parameters in your `WHERE` expressions. **This will not work**:
```TypeScript
```typescript
const result = await dataSource
.getRepository(User)
.createQueryBuilder('user')
.leftJoinAndSelect('user.linkedSheep', 'linkedSheep')
.leftJoinAndSelect('user.linkedCow', 'linkedCow')
.where('user.linkedSheep = :id', { id: sheepId })
.andWhere('user.linkedCow = :id', { id: cowId });
.createQueryBuilder("user")
.leftJoinAndSelect("user.linkedSheep", "linkedSheep")
.leftJoinAndSelect("user.linkedCow", "linkedCow")
.where("user.linkedSheep = :id", { id: sheepId })
.andWhere("user.linkedCow = :id", { id: cowId })
```
... but this will:
```TypeScript
```typescript
const result = await dataSource
.getRepository(User)
.createQueryBuilder('user')
.leftJoinAndSelect('user.linkedSheep', 'linkedSheep')
.leftJoinAndSelect('user.linkedCow', 'linkedCow')
.where('user.linkedSheep = :sheepId', { sheepId })
.andWhere('user.linkedCow = :cowId', { cowId });
.createQueryBuilder("user")
.leftJoinAndSelect("user.linkedSheep", "linkedSheep")
.leftJoinAndSelect("user.linkedCow", "linkedCow")
.where("user.linkedSheep = :sheepId", { sheepId })
.andWhere("user.linkedCow = :cowId", { cowId })
```
Note that we uniquely named `:sheepId` and `:cowId` instead of using `:id` twice for different parameters.
@ -893,7 +893,7 @@ Using `take` and `skip` will prevent those issues.
QueryBuilder supports both optimistic and pessimistic locking.
#### Lock modes
### Lock modes
Support of lock modes, and SQL statements they translate to, are listed in the table below (blank cell denotes unsupported). When specified lock mode is not supported, a `LockNotSupportedOnGivenDriverError` error will be thrown.
@ -951,7 +951,7 @@ const users = await dataSource
Optimistic locking works in conjunction with both `@Version` and `@UpdatedDate` decorators.
#### Lock tables
### Lock tables
You can also lock tables using the following method:

View File

@ -18,7 +18,7 @@ await dataSource
This is the most efficient way in terms of performance to insert rows into your database.
You can also perform bulk insertions this way.
### Raw SQL support
## Raw SQL support
In some cases when you need to execute SQL queries you need to use function style value:
@ -34,9 +34,9 @@ await dataSource
.execute()
```
This syntax doesn't escape your values, you need to handle escape on your own.
> Warning: When using raw SQL, ensure that values are properly sanitized to prevent SQL injection.
### Update values ON CONFLICT
## Update values ON CONFLICT
If the values you are trying to insert conflict due to existing data the `orUpdate` function can be used to update specific values on the conflicted target.
@ -50,14 +50,11 @@ await dataSource
lastName: "Saw",
externalId: "abc123",
})
.orUpdate(
["firstName", "lastName"],
["externalId"],
)
.orUpdate(["firstName", "lastName"], ["externalId"])
.execute()
```
### Update values ON CONFLICT with condition (Postgres, Oracle, MSSQL, SAP HANA)
## Update values ON CONFLICT with condition (Postgres, Oracle, MSSQL, SAP HANA)
```typescript
await dataSource
@ -69,22 +66,17 @@ await dataSource
lastName: "Saw",
externalId: "abc123",
})
.orUpdate(
["firstName", "lastName"],
["externalId"],
{
overwriteCondition: {
where: {
firstName: Equal("Phantom"),
}
.orUpdate(["firstName", "lastName"], ["externalId"], {
overwriteCondition: {
where: {
firstName: Equal("Phantom"),
},
}
)
},
})
.execute()
```
### IGNORE error (MySQL) or DO NOTHING (Postgres, Oracle, MSSQL, SAP HANA) during insert
## IGNORE error (MySQL) or DO NOTHING (Postgres, Oracle, MSSQL, SAP HANA) during insert
If the values you are trying to insert conflict due to existing data or containing invalid data, the `orIgnore` function can be used to suppress errors and insert only rows that contain valid data.
@ -102,7 +94,7 @@ await dataSource
.execute()
```
### Skip data update if values have not changed (Postgres, Oracle, MSSQL, SAP HANA)
## Skip data update if values have not changed (Postgres, Oracle, MSSQL, SAP HANA)
```typescript
await dataSource
@ -114,17 +106,13 @@ await dataSource
lastName: "Saw",
externalId: "abc123",
})
.orUpdate(
["firstName", "lastName"],
["externalId"],
{
skipUpdateIfNoValuesChanged: true,
}
)
.orUpdate(["firstName", "lastName"], ["externalId"], {
skipUpdateIfNoValuesChanged: true,
})
.execute()
```
### Use partial index (Postgres)
## Use partial index (Postgres)
```typescript
await dataSource
@ -136,13 +124,9 @@ await dataSource
lastName: "Saw",
externalId: "abc123",
})
.orUpdate(
["firstName", "lastName"],
["externalId"],
{
skipUpdateIfNoValuesChanged: true,
indexPredicate: "date > 2020-01-01"
}
)
.orUpdate(["firstName", "lastName"], ["externalId"], {
skipUpdateIfNoValuesChanged: true,
indexPredicate: "date > 2020-01-01",
})
.execute()
```

View File

@ -14,7 +14,7 @@ await dataSource
This is the most efficient way in terms of performance to update entities in your database.
### Raw SQL support
## Raw SQL support
In some cases when you need to execute SQL queries you need to use function style value:
@ -31,4 +31,4 @@ await dataSource
.execute()
```
This syntax doesn't escape your values, you need to handle escape on your own.
> Warning: When using raw SQL, ensure that values are properly sanitized to prevent SQL injection.

View File

@ -1,6 +1,6 @@
# Delete using Query Builder
### `Delete`
## `Delete`
You can create `DELETE` queries using `QueryBuilder`.
Examples:
@ -16,7 +16,7 @@ await myDataSource
This is the most efficient way in terms of performance to delete entities from your database.
### `Soft-Delete`
## `Soft-Delete`
Applying Soft Delete to QueryBuilder
@ -35,7 +35,7 @@ await myDataSource
.execute()
```
### `Restore-Soft-Delete`
## `Restore-Soft-Delete`
Alternatively, You can recover the soft deleted rows by using the `restore()` method:

View File

@ -3,7 +3,7 @@
## What is a QueryRunner?
Each new `QueryRunner` instance takes a single connection from connection pool, if RDBMS supports connection pooling.
For databases not supporting connection pools, it uses the same connection across data source.
For databases not supporting connection pools, it uses the same connection across the entire data source.
## Creating a new `QueryRunner` instance
@ -15,23 +15,23 @@ const queryRunner = dataSource.createQueryRunner()
## Using `QueryRunner`
After you create a new instance of `QueryRunner` use `connect` method to actually obtain a connection from the connection pool:
After you create a new instance of `QueryRunner` use `connect` method to actually get a connection from the connection pool:
```typescript
const queryRunner = dataSource.createQueryRunner()
await queryRunner.connect()
```
**Important**: make sure to release it when it is not needed anymore to make it available to the connection pool again:
**Important**: make sure to release it when it is not necessary anymore to make it available to the connection pool again:
```typescript
await queryRunner.release()
```
After connection is released it is not possible to use the query runner methods.
After connection is released, it is not possible to use the query runner methods.
`QueryRunner` has bunch of methods you can use, it also has its own `EntityManager` instance,
which you can use through `manager` property in order to run `EntityManager` methods on a particular database connection
`QueryRunner` has a bunch of methods you can use, it also has its own `EntityManager` instance,
which you can use through `manager` property to run `EntityManager` methods on a particular database connection
used by `QueryRunner` instance:
```typescript
@ -43,6 +43,6 @@ await queryRunner.connect()
// use this particular connection to execute queries
const users = await queryRunner.manager.find(User)
// don't forget to release connection after you are done using it
// remember to release connection after you are done using it
await queryRunner.release()
```

View File

@ -2,7 +2,7 @@
## Basic options
All repository and manager ` .find*` methods accept special options you can use to query data you need without using `QueryBuilder`:
All repository and manager `.find*` methods accept special options you can use to query data you need without using `QueryBuilder`:
- `select` - indicates which properties of the main object must be selected

View File

@ -370,7 +370,7 @@ const categoryRepository = manager.getTreeRepository(Category)
```
- `getMongoRepository` - Gets `MongoRepository` to perform operations on a specific entity.
Learn more about [MongoDB](../guides/2-mongodb.md).
Learn more about [MongoDB](../drivers/mongodb.md).
```typescript
const userRepository = manager.getMongoRepository(User)

View File

@ -75,9 +75,9 @@ repository.merge(user, { firstName: "Timber" }, { lastName: "Saw" }) // same as
- `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. <br></br>
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.
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.
```typescript
const partialUser = {
@ -143,7 +143,7 @@ await repository.update(1, { firstName: "Rizzrak" })
// executes UPDATE user SET firstName = Rizzrak WHERE id = 1
```
- `updateAll` - Updates *all* entities of target type (without WHERE clause). Sets fields from supplied partial entity.
- `updateAll` - Updates _all_ entities of target type (without WHERE clause). Sets fields from supplied partial entity.
```typescript
await repository.updateAll({ category: "ADULT" })
@ -224,7 +224,7 @@ await repository.delete([1, 2, 3])
await repository.delete({ firstName: "Timber" })
```
- `deleteAll` - Deletes *all* entities of target type (without WHERE clause).
- `deleteAll` - Deletes _all_ entities of target type (without WHERE clause).
```typescript
await repository.deleteAll()
@ -482,4 +482,4 @@ For `TreeRepository` API refer to [the Tree Entities documentation](../entity/4-
## `MongoRepository` API
For `MongoRepository` API refer to [the MongoDB documentation](../guides/2-mongodb.md).
For `MongoRepository` API refer to [the MongoDB documentation](../drivers/mongodb.md).

743
docs/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -51,6 +51,11 @@ const sidebars: SidebarsConfig = {
items: [{ type: "autogenerated", dirName: "query-builder" }],
},
"query-runner",
{
type: "category",
label: "Drivers",
items: [{ type: "autogenerated", dirName: "drivers" }],
},
{
type: "category",
label: "Guides",

View File

@ -310,8 +310,8 @@ function PlatformsSection() {
Works Everywhere
</Heading>
<p className={styles.platformsDescription}>
TypeORM runs in NodeJS, Browser, Cordova, PhoneGap, Ionic,
React Native, NativeScript, Expo, and Electron platforms.
TypeORM runs in NodeJS, Browser, Cordova, Ionic, React
Native, NativeScript, Expo, and Electron platforms.
</p>
<div className={styles.platformsIcons}>
<span>🖥 NodeJS</span>
@ -337,7 +337,10 @@ function CallToAction() {
</p>
<div className={styles.ctaButtons}>
<Link
className={clsx("button button--secondary button--lg margin-right--md", styles.noHorizontalMarginTablet)}
className={clsx(
"button button--secondary button--lg margin-right--md",
styles.noHorizontalMarginTablet,
)}
to="/docs/getting-started"
>
Read the Docs
@ -361,7 +364,7 @@ export default function Home(): ReactNode {
return (
<Layout
title={`${siteConfig.title} - ${siteConfig.tagline}`}
description="TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript."
description="TypeORM is an ORM that can run in NodeJS, Browser, Cordova, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript."
>
<HomepageHeader />
<main>

View File

@ -242,9 +242,9 @@ export class RedisQueryResultCache implements QueryResultCache {
} else {
return PlatformTools.load(this.clientType)
}
} catch (e) {
} catch {
throw new TypeORMError(
`Cannot use cache because ${this.clientType} is not installed. Please run "npm i ${this.clientType} --save".`,
`Cannot use cache because ${this.clientType} is not installed. Please run "npm i ${this.clientType}".`,
)
}
}

View File

@ -995,10 +995,10 @@ export class CockroachDriver implements Driver {
loadStreamDependency() {
try {
return PlatformTools.load("pg-query-stream")
} catch (e) {
} catch {
// todo: better error for browser env
throw new TypeORMError(
`To use streams you should install pg-query-stream package. Please run npm i pg-query-stream --save command.`,
`To use streams you should install pg-query-stream package. Please run "npm i pg-query-stream".`,
)
}
}

View File

@ -213,14 +213,14 @@ export interface MongoConnectionOptions extends BaseDataSourceOptions {
/**
* @deprecated A boolean to enable or disables TLS/SSL for the connection.
* (The ssl option is equivalent to the tls option.)
* (The ssl option is equivalent to the {@link tls} option.)
*/
readonly ssl?: boolean
/**
* @deprecated SSL Root Certificate file path.
*
* Will be removed in the next major version. Please use tlsCAFile instead.
* Will be removed in the next major version. Please use {@link tlsCAFile} instead.
*/
readonly sslCA?: string
@ -234,28 +234,28 @@ export interface MongoConnectionOptions extends BaseDataSourceOptions {
/**
* @deprecated SSL Certificate file path.
*
* Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
* Will be removed in the next major version. Please use {@link tlsCertificateKeyFile} instead.
*/
readonly sslCert?: string
/**
* @deprecated SSL Key file file path.
*
* Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
* Will be removed in the next major version. Please use {@link tlsCertificateKeyFile} instead.
*/
readonly sslKey?: string
/**
* @deprecated SSL Certificate pass phrase.
*
* Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
* Will be removed in the next major version. Please use {@link tlsCertificateKeyFilePassword} instead.
*/
readonly sslPass?: string
/**
* @deprecated Validate mongod server certificate against Certificate Authority
*
* Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
* Will be removed in the next major version. Please use {@link tlsAllowInvalidCertificates} instead.
*/
readonly sslValidate?: boolean
@ -280,14 +280,14 @@ export interface MongoConnectionOptions extends BaseDataSourceOptions {
readonly tlsCertificateKeyFile?: string
/**
* Specifies the password to de-crypt the tlsCertificateKeyFile.
* Specifies the password to de-crypt the {@link tlsCertificateKeyFile}.
*/
readonly tlsCertificateKeyFilePassword?: string
/**
* @deprecated The write concern w value
*
* Please use the `writeConcern` option instead
* Please use the {@link writeConcern} option instead
*/
readonly w?: string | number
@ -300,7 +300,7 @@ export interface MongoConnectionOptions extends BaseDataSourceOptions {
/**
* @deprecated The write concern timeout
*
* Please use the `writeConcern` option instead
* Please use the {@link writeConcern} option instead
*/
readonly wtimeoutMS?: number
}

View File

@ -1411,10 +1411,10 @@ export class PostgresDriver implements Driver {
loadStreamDependency() {
try {
return PlatformTools.load("pg-query-stream")
} catch (e) {
} catch {
// todo: better error for browser env
throw new TypeORMError(
`To use streams you should install pg-query-stream package. Please run npm i pg-query-stream --save command.`,
`To use streams you should install pg-query-stream package. Please run "npm i pg-query-stream".`,
)
}
}

View File

@ -6,8 +6,7 @@ import { TypeORMError } from "./TypeORMError"
export class DriverPackageNotInstalledError extends TypeORMError {
constructor(driverName: string, packageName: string) {
super(
`${driverName} package has not been found installed. ` +
`Try to install it: npm install ${packageName} --save`,
`${driverName} package has not been found installed. Please run "npm install ${packageName}".`,
)
}
}