mirror of
https://github.com/typeorm/typeorm.git
synced 2025-12-08 21:26:23 +00:00
* 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.9 KiB
8.9 KiB
EntityManager API
dataSource- The DataSource used byEntityManager.
const dataSource = manager.dataSource
queryRunner- The query runner used byEntityManager. Used only in transactional instances of EntityManager.
const queryRunner = manager.queryRunner
transaction- Provides a transaction where multiple database requests will be executed in a single database transaction. Learn more Transactions.
await manager.transaction(async (manager) => {
// NOTE: you must perform all database operations using the given manager instance
// it's a special instance of EntityManager working with this transaction
// and don't forget to await things here
})
query- Executes a raw SQL query.
const rawData = await manager.query(`SELECT * FROM USERS`)
createQueryBuilder- Creates a query builder use to build SQL queries. Learn more about QueryBuilder.
const users = await manager
.createQueryBuilder()
.select()
.from(User, "user")
.where("user.name = :name", { name: "John" })
.getMany()
hasId- Checks if given entity has its primary column property defined.
if (manager.hasId(user)) {
// ... do something
}
getId- Gets given entity's primary column property value. If the entity has composite primary keys then the returned value will be an object with names and values of primary columns.
const userId = manager.getId(user) // userId === 1
create- Creates a new instance ofUser. Optionally accepts an object literal with user properties which will be written into newly created user object.
const user = manager.create(User) // same as const user = new User();
const user = manager.create(User, {
id: 1,
firstName: "Timber",
lastName: "Saw",
}) // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
merge- Merges multiple entities into a single entity.
const user = new User()
manager.merge(User, user, { firstName: "Timber" }, { lastName: "Saw" }) // same as user.firstName = "Timber"; user.lastName = "Saw";
preload- Creates a new entity from the given plain javascript object. If the entity already exist 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 loaded from the database entity with all properties replaced from the new object.
const partialUser = {
id: 1,
firstName: "Rizzrak",
profile: {
id: 1,
},
}
const user = await manager.preload(User, partialUser)
// user will contain all missing data from partialUser with partialUser property values:
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }
save- Saves a given entity or array of entities. If the entity already exists in the database, then it's updated. If the entity does not exist in the database yet, it's inserted. It saves all given entities in a single transaction (in the case of entity manager is not transactional). Also supports partial updating since all undefined properties are skipped. In order to make a valueNULL, you must manually set the property to equalnull.
await manager.save(user)
await manager.save([category1, category2, category3])
remove- Removes a given entity or array of entities. It removes all given entities in a single transaction (in the case of entity, manager is not transactional).
await manager.remove(user)
await manager.remove([category1, category2, category3])
insert- Inserts a new entity, or array of entities.
await manager.insert(User, {
firstName: "Timber",
lastName: "Timber",
})
await manager.insert(User, [
{
firstName: "Foo",
lastName: "Bar",
},
{
firstName: "Rizz",
lastName: "Rak",
},
])
update- Partially updates entity by a given update options or entity id.
await manager.update(User, { firstName: "Timber" }, { firstName: "Rizzrak" })
// executes UPDATE user SET firstName = Rizzrak WHERE firstName = Timber
await manager.update(User, 1, { firstName: "Rizzrak" })
// executes UPDATE user SET firstName = Rizzrak WHERE id = 1
upsert- Inserts a new entity or array of entities unless they already exist in which case they are updated instead. Supported by AuroraDataApi, Cockroach, Mysql, Postgres, and Sqlite database drivers.
await manager.upsert(
User,
[
{ externalId: "abc123", firstName: "Rizzrak" },
{ externalId: "bca321", firstName: "Karzzir" },
],
["externalId"],
)
/** executes
* INSERT INTO user
* VALUES
* (externalId = abc123, firstName = Rizzrak),
* (externalId = cba321, firstName = Karzzir),
* ON CONFLICT (externalId) DO UPDATE firstName = EXCLUDED.firstName
**/
delete- Deletes entities by entity id, ids or given conditions:
await manager.delete(User, 1)
await manager.delete(User, [1, 2, 3])
await manager.delete(User, { firstName: "Timber" })
increment- Increments some column by provided value of entities that match given options.
await manager.increment(User, { firstName: "Timber" }, "age", 3)
decrement- Decrements some column by provided value that match given options.
await manager.decrement(User, { firstName: "Timber" }, "age", 3)
count- Counts entities that matchFindOptions. Useful for pagination.
const count = await manager.count(User, {
where: {
firstName: "Timber",
},
})
countBy- Counts entities that matchFindOptionsWhere. Useful for pagination.
const count = await manager.countBy(User, { firstName: "Timber" })
find- Finds entities that match givenFindOptions.
const timbers = await manager.find(User, {
where: {
firstName: "Timber",
},
})
findBy- Finds entities that match givenFindWhereOptions.
const timbers = await manager.findBy(User, {
firstName: "Timber",
})
findAndCount- Finds entities that match givenFindOptions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
const [timbers, timbersCount] = await manager.findAndCount(User, {
where: {
firstName: "Timber",
},
})
findAndCountBy- Finds entities that match givenFindOptionsWhere. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
const [timbers, timbersCount] = await manager.findAndCount(User, {
firstName: "Timber",
})
findOne- Finds the first entity that matches givenFindOptions.
const timber = await manager.findOne(User, {
where: {
firstName: "Timber",
},
})
findOneBy- Finds the first entity that matches givenFindOptionsWhere.
const timber = await manager.findOne(User, { firstName: "Timber" })
findOneOrFail- Finds the first entity that matches some id or find options. Rejects the returned promise if nothing matches.
const timber = await manager.findOneOrFail(User, {
where: {
firstName: "Timber",
},
})
findOneByOrFail- Finds the first entity that matches givenFindOptions. Rejects the returned promise if nothing matches.
const timber = await manager.findOneByOrFail(User, { firstName: "Timber" })
clear- Clears all the data from the given table (truncates/drops it).
await manager.clear(User)
getRepository- GetsRepositoryto perform operations on a specific entity. Learn more about Repositories.
const userRepository = manager.getRepository(User)
getTreeRepository- GetsTreeRepositoryto perform operations on a specific entity. Learn more about Repositories.
const categoryRepository = manager.getTreeRepository(Category)
getMongoRepository- GetsMongoRepositoryto perform operations on a specific entity. Learn more about MongoDB.
const userRepository = manager.getMongoRepository(User)
withRepository- Gets custom repository instance used in a transaction. Learn more about Custom repositories.
const myUserRepository = manager.getCustomRepository(UserRepository)
release- Releases query runner of an entity manager. Used only when query runner was created and managed manually.
await manager.release()