* added find options and new option relationLoadStrategy * find now returns null instead of undefined; removed primary relations support; bugfixing; added some changes and tests from next branch; * added typename to connection options; added data loader types, lot of deprecations; new es2020 emit by tsc; new custom repositories syntax * applied lint fixing * replaced some instanceof checks * reverting docker compose image versions * optimizing imports * reverting back some instanceof checks to prevent compiler errors * downgrading es compilation version * docs: remove "primary" from relation options (#8619) remove ex-line 26 for being deprecated in 0.3.0: "* `primary: boolean` - Indicates whether this relation's column will be a primary column or not." * Revert "reverting back some instanceof checks to prevent compiler errors" This reverts commit 7bf12a39e2297d097aa2a42989afd0e9e4f49bb0. * Revert "optimizing imports" This reverts commit 7588ac14e4f1bf1a82e3b7883134b9c2c8ae5f3f. * Revert "replaced some instanceof checks" This reverts commit bfa5a2d706f697ed1c1beb38b4455c0d33121e5a. * fixing few comments * removing transaction decorators * this test is invalid - it's not clear why the hell getTreeRepository will throw an error and it's not clear what kind of error its going to throw * addded mixed list support in connection options * trying to fix oracle length issue * lintfix * removed shorten usages * added named entity target support to the connection * fixing entity target support in relation options via entity schema * debugging oracle issue * fixed issue with alias not being shortened in many to many alias cases * some day we'll have a prettier. * fixing oracle tests * fixing oracle failing test * removed "null" support in where expressions; fixed softDelete and restore incorrect usages * renamed FindConditions to FindOptionsWhere * version bump * docs: update loading relation in find method (v 0.3.0) (#8621) * docs: update relation definition method Update the method that allows loading a specific relation inside the find method. This method is found on the one-to-one-relations page. Change `const users = await userRepository.find({ relations: ["profile"] });` to `const users = await userRepository.find({ relations: {profile: true});`. * fix formatting Co-authored-by: Umed Khudoiberdiev <pleerock.me@gmail.com> * docs: change relations option definition (#8620) * docs: change relations option definition change line 139 from `const users = await connection.getRepository(User).find({ relations: ["profile", "photos", "videos"] });` to `const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true] });` to reflect version 0.3.0 changes * docs: change relations option definition Rectified a type on line 139 from: `const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true] });` to `const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true} });` * formatting Co-authored-by: Umed Khudoiberdiev <pleerock.me@gmail.com> * lint * improved find options types * fixed types and removed nonnever because it causes circual issue for some reason * docs: update entitymanager definition (#8623) * docs: update entitymanager definition change the "What is EntityManager?" page to be up-to-date with v 0.3.0 1. line 6 changes from `You can access the entity manager via 'getManager()' or from 'Connection'.` to `You can access the entity manager via DataSource's manager.` 2. the import on `getManager` in line 10 becomes `Manager` that the user have configured beforehand: `import {getManager} from "typeorm";` becomes `import {Manager} from "./config/DataSource";` 3.change entityManager definition in line 13: from `const entityManager = getManager(); // you can also get it via getConnection().manager` to `const entityManager = Manager;` * docs: update entitymanager definition changed line 10 from: `import {Manager} from "./config/DataSource";` to `import {DataSource} from "typeorm";` and changed line 13 and 14 from: `const entityManager = Manager;` `const user = await entityManager.findOne(User, 1);` to `const myDataSource = new DataSource({ /*...*/ });` `const user = await myDataSource.manager.findOne(User, 1);` for a simpler way of describing the origin of DataSource and how it works. * In return type doesn't seem to work in all cases * feat: mssql v7 support (#8592) Adds support for v7 of the mssql library as v6 is EOL. This also makes use of the new toReadableStream method on requests to return a native stream where required. * fix: prefix relation id columns contained in embedded entities (#6977) (#7432) * fix: prefix relation id columns contained in embedded entities (#6977) Searches embedded entity columns for relation ID column if relation column is in embedded entity. If not found, creates new relation ID with embedded metadata set to match the relation column. fixes: #2254 fixes: #3132 fixes: #3226 fixes: #6977 * test: prefix subcounters sub-entity with "sub" to fit in 30 character identifier for oracle Problem introduced with #6981 * fix: find by Date object in sqlite driver (#7538) * fix: find by Date object in sqlite driver In sqlite, Date objects are persisted as UtcDatetimeString. But a Date object parameter was escaped with .toISOString(), making such queries impossible. This commit aligns both transforms. This bug does *not* apply to better-sql where you can only bind numbers, strings, bigints, buffers, and null. This is breaking for when the user inserted their dates manually as ISO and relied on this old maltransformation, after this their find()s by Date won't work anymore. BREAKING CHANGE: Change Date serialization in selects Closes: #2286 * add failing test * fix: find by Date object in sqlite driver (with query builder) Also consider query builder parameter escaping * test: add test for 3426 Co-authored-by: James Ward <james@notjam.es> * manually ported changes from #7796 * updated changelog * fixes after merge * new findOne syntax * new find* syntax * new find* syntax * lint * tsc version bump * tsc version bump and fixed mongodb issues * moved date fns into non dev deps * returned oracledb dep into place * removed lock files * returned lock files back * eslint upgrade * fixing mongodb issue * fixing mongodb issue * test: keep junction aliases short (#8637) Tests a fix for an issue where junction aliases (e.g. in many-to-many relations) are not unique because they are too long and thus truncated by the driver. Closes: #8627 Related to: 76cee41dcf1c146d02715c7f48fed33672d28c67 * fixing mongodb issues * fixing sqlite test * fixing sqlite test * fixing sqlite test * fixing mongodb test * fixing entity schema tests * fixing entity schema tests * merged latest master * removed driver instanceof checks * removed function instanceof checks * removed Object instanceof checks * removing instanceof checks... * fixing instanceof checks * added InstanceChecker to remove remaining instanceof checks * fixed failing test * linting * fixing failing test * version bump * compiler fixes * Connection type usages replace to DataSource * updated dev deps * updated deps, add prettier, removed oracledb due to m1 issue * chalk downgrade * fixing failing test * applied prettier formatting * replaced eslint to prettier * okay I think we can call it lint * fixing linting * fixed prettier introduced compiler bug * fixed failing test * prettier; * fixed failing test * alias shortening only for junction tables; fixed failing tests; * changed aurora db names and reverted change of junction table name shorten algorithm * format * removed platform from docker compose * made numeric parameters to not use parameters to prevent parameters number limit issue. Also enabled shorten only for junction tables * fixing test * fixing returning columns bugs * fixing test * fixed returning issue * fixing merge conflicts * updating documentation * working on docs / improving api * working on docs * fixed isConnected issue * re-worked commands * commenting cli command tests for now * commenting cli command tests for now * removed platform * returned Connection back * refactor: export tree repository helper methods (#8753) * Migrated protected tree methods to util class * Added tree repository extend override * Ran prettier format * merge master into 0.3.0 Co-authored-by: Bitcollage <serkan.sipahi@yahoo.de> * working on documentation Co-authored-by: Bilel Taktak <47742269+Parsath@users.noreply.github.com> Co-authored-by: Salah Azzouz <52634440+Salah-Azzouz@users.noreply.github.com> Co-authored-by: Daniel Hensby <dhensby@users.noreply.github.com> Co-authored-by: Nebojša Cvetković <nebkat@gmail.com> Co-authored-by: Philip Waritschlager <philip+github@waritschlager.de> Co-authored-by: James Ward <james@notjam.es> Co-authored-by: Felix Gohla <37421906+felix-gohla@users.noreply.github.com> Co-authored-by: Dmitry Zotov <dmzt08@gmail.com> Co-authored-by: Jimmy Chen <50786287+Q16solver@users.noreply.github.com> Co-authored-by: Bitcollage <serkan.sipahi@yahoo.de>
8.1 KiB
Using CLI
- Installing CLI
- Initialize a new TypeORM project
- Create a new entity
- Create a new subscriber
- Create a new migration
- Generate a migration from existing table schema
- Run migrations
- Revert migrations
- Show migrations
- Sync database schema
- Log sync database schema queries without actual running them
- Drop database schema
- Run any SQL query
- Clear cache
- Check version
Installing CLI
If entities files are in javascript
If you have a local typeorm version, make sure it matches the global version we are going to install.
You can install typeorm globally with npm i -g typeorm.
You can also choose to use npx typeorm <params> for each command if you prefer not having to install it.
If entities files are in typescript
This CLI tool is written in javascript and to be run on node. If your entity files are in typescript, you will need to transpile them to javascript before using CLI. You may skip this section if you only use javascript.
You may setup ts-node in your project to ease the operation as follows:
Install ts-node:
npm install ts-node --save-dev
Add typeorm command under scripts section in package.json
"scripts": {
...
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js"
}
For ESM projects add this instead:
"scripts": {
...
"typeorm": "node --loader ts-node/esm ./node_modules/typeorm/cli.js"
}
If you want to load more modules like module-alias you can add more --require my-module-supporting-register
Then you may run the command like this:
npm run typeorm migration:run
If you need to pass parameter with dash to npm script, you will need to add them after --. For example, if you need to generate, the command is like this:
npm run typeorm migration:generate -- -n migrationNameHere
How to read the documentation
To reduce verbosity of the documentation, the following sections are using a globally installed typeorm CLI. Depending on how you installed the CLI, you may replace typeorm at the start of the command, by either npx typeorm or npm run typeorm.
Initialize a new TypeORM project
You can create a new project with everything already setup:
typeorm init
It creates all files needed for a basic project with TypeORM:
- .gitignore
- package.json
- README.md
- tsconfig.json
- src/entity/User.ts
- src/index.ts
Then you can run npm install to install all dependencies.
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:
typeorm init --name my-project
To specify a specific database you use you can use --database:
typeorm init --database mssql
To generate an ESM base project you can use --module esm:
typeorm init --name my-project --module esm
You can also generate a base project with Express:
typeorm init --name my-project --express
If you are using docker you can generate a docker-compose.yml file using:
typeorm init --docker
typeorm init is the easiest and fastest way to setup a TypeORM project.
Create a new entity
You can create a new entity using CLI:
typeorm entity:create -n User
where User is an entity file and class name.
Running the command will create a new empty entity in entitiesDir of the project.
To set up the entitiesDir of the project you must add it in data source options:
{
cli: {
entitiesDir: "src/entity"
}
}
Learn more about data source options. If you have a multi-module project structure with multiple entities in different directories you can provide the path to the CLI command where you want to generate an entity:
typeorm entity:create -n User -d src/user/entity
Learn more about entities.
Create a new subscriber
You can create a new subscriber using CLI:
typeorm subscriber:create -n UserSubscriber
where UserSubscriber is a subscriber file and class name.
Running the following command will create a new empty subscriber in the subscribersDir of the project.
To setup subscribersDir you must add it in data source options:
{
cli: {
subscribersDir: "src/subscriber"
}
}
Learn more about data source options. If you have a multi-module project structure with multiple subscribers in different directories you can provide a path to the CLI command where you want to generate a subscriber:
typeorm subscriber:create -n UserSubscriber -d src/user/subscriber
Learn more about Subscribers.
Create a new migration
You can create a new migration using CLI:
typeorm migration:create -n UserMigration
where UserMigration is a migration file and class name.
Running the command will create a new empty migration in the migrationsDir of the project.
To setup migrationsDir you must add it in data source options:
{
cli: {
migrationsDir: "src/migration"
}
}
Learn more about data source options. If you have a multi-module project structure with multiple migrations in different directories you can provide a path to the CLI command where you want to generate a migration:
typeorm migration:create -n UserMigration -d src/user/migration
Learn more about Migrations.
Generate a migration from existing table schema
Automatic migration generation creates a new migration file 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.
typeorm migration:generate -n UserMigration
The rule of thumb is to generate a migration after each entity change.
Learn more about Migrations.
Run migrations
To execute all pending migrations use following command:
typeorm migration:run
Learn more about Migrations.
Revert migrations
To revert the most recently executed migration use the following command:
typeorm migration:revert
This command will undo only the last executed migration. You can execute this command multiple times to revert multiple migrations. Learn more about Migrations.
Show migrations
To show all migrations and whether they've been run or not use following command:
typeorm migration:show
[X] = Migration has been ran
[ ] = Migration is pending/unapplied
This command also returns an error code if there are unapplied migrations.
Sync database schema
To synchronize a database schema use:
typeorm schema:sync
Be careful running this command in production - schema sync may cause data loss if you don't use it wisely. Check which sql queries it will run before running on production.
Log sync database schema queries without actual running them
To check what sql queries schema:sync is going to run use:
typeorm schema:log
Drop database schema
To completely drop a database schema use:
typeorm schema:drop
Be careful with this command on production since it completely removes data from your database.
Run any SQL query
You can execute any SQL query you want directly in the database using:
typeorm query "SELECT * FROM USERS"
Clear cache
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:
typeorm cache:clear
Check version
You can check what typeorm version you have installed (both local and global) by running:
typeorm version