profile
viewpoint
Umed Khudoiberdiev pleerock @typeorm Anywhere https://twitter.com/pleerock Technical Lead and TS/JS FS developer. In web development since 2006

pleerock/gulpclass 160

Make a beautiful class-based gulpfiles with TypeScript and Gulpclass.

pleerock/event-dispatch 35

Dispatching and listening for application events in Typescript

pleerock/angular-disable-all 21

Angular directive that allows to disable any element (for example DIV) contents and disable clicks on the given element

pleerock/configuration-manager 3

Allows to manage configuration files in your project

pleerock/angular-auto-grow-input 2

This directive allows your inputs to grow as soon as user types. The input's width always fit the text user typed in the input.

pleerock/angular-select-options 2

A special angular directive that works like angular's ng-options but can be used in along with any element and has several specific abilities

pleerock/awesome-graphql 2

Awesome list of GraphQL & Relay

pleerock/class-transformer-demo 2

Example how to use class-transformer with Angular 2

Pull request review commenttypeorm/typeorm

feat: add select and map function to MySQL Driver (#296)

 export class MysqlDriver implements Driver {     /**      * Prepares given value to a value to be persisted, based on its column type or metadata.      */-    prepareHydratedValue(value: any, columnMetadata: ColumnMetadata): any {-        if (value === null || value === undefined)-            return columnMetadata.transformer ? ApplyValueTransformers.transformFrom(columnMetadata.transformer, value) : value;+    prepareHydratedValue(value: any, columnMetadata: ColumnMetadata | string): any {+        const columnType: any = columnMetadata instanceof ColumnMetadata ? columnMetadata.type : columnMetadata;

I would revert this statement to typeof columnMetadata === "string" ? x : y because instanceof has proven to be unreliable in some environments.

duprez

comment created time in 3 days

PullRequestReviewEvent

pull request commenttypeorm/typeorm

fix: wrap where clauses in parentheses

Would like to understand what problem this will solve. Also, as a note, it would make sense to omit parentheses in the case if the aren't really needed.

imnotjames

comment created time in 3 days

push eventtypeorm/typeorm

Abdüssamet Özay

commit sha fa23f36313d80a76539d7fa9d065a96dc5086fb4

docs: update usage-with-javascript.md (#6955)

view details

push time in 3 days

PR merged typeorm/typeorm

Update usage-with-javascript.md
+4 -2

0 comment

1 changed file

Abadii

pr closed time in 3 days

push eventtypeorm/typeorm

Duong Le

commit sha 43e7f394932a510e50f92911c22f9e61c4e192ab

docs: Remove unused variable (#6957) * docs: remove unused variable in many-to-many-relations.md * docs: remove unused variable in one-to-one-relations.md

view details

push time in 3 days

PR merged typeorm/typeorm

docs: Remove unused variable

This will fix the linting error as the no unused variable rule is widely used.

+11 -11

0 comment

2 changed files

duongle26

pr closed time in 3 days

push eventtypeorm/typeorm

Abdüssamet Özay

commit sha d624ca3b4efa7bbffe4802d04c5950aa5ac1e488

docs: update usage-with-javascript.md (#6952)

view details

push time in 4 days

pull request commenttypeorm/typeorm

Update usage-with-javascript.md

Thank you!

Abadii

comment created time in 4 days

PR merged typeorm/typeorm

Update usage-with-javascript.md
+2 -2

0 comment

1 changed file

Abadii

pr closed time in 4 days

PullRequestReviewEvent

push eventleonardofalk/typeorm

Umed Khudoiberdiev

commit sha 60d67de5b660f622c1204ffb0601e19528609d5a

added missing semicolon

view details

push time in 4 days

pull request commenttypeorm/typeorm

fix: lock Typescript to 3.6.0

yes, of course it does support 4.x. This PR is only about used compiler version for the internal development.

imnotjames

comment created time in 7 days

pull request commenttypeorm/typeorm

fix: Handle undefined querysets in QueryCommand

Thank you!

imnotjames

comment created time in 9 days

push eventtypeorm/typeorm

James Ward

commit sha 6f285dce1ac315707fe01a892c1c74521a98aae2

fix: Handle undefined querysets in QueryCommand (#6910) fixes #6612

view details

push time in 9 days

PR merged typeorm/typeorm

fix: Handle undefined querysets in QueryCommand

When a query fails and returns undefined instead of an actual query set the QueryCommand has a TypeError.

fixes #6612

+7 -2

0 comment

1 changed file

imnotjames

pr closed time in 9 days

issue closedtypeorm/typeorm

"TypeError: Cannot read property 'replace' of undefined" on running the cli `query` command with several SQL statements

Issue type:

<!-- Have a question? Check the "Support" Documentation on the best places to ask questions! --- https://github.com/typeorm/typeorm/blob/master/docs/support.md -->

[x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

On running the cli query command with several SQL statements all wrapped with double quotes I receive the following error from the cli-highlight:

> ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli --config ormconfig-migrations.ts "query" "SELECT * FROM folder;
SELECT * FROM sub_folder;"

Running query: SELECT * FROM folder;
SELECT * FROM sub_folder;
Query has been executed. Result: 
Error during query execution:
TypeError: Cannot read property 'replace' of undefined
    at escape (/usr/src/app/node_modules/highlight.js/lib/highlight.js:71:18)
    at Object.highlight (/usr/src/app/node_modules/highlight.js/lib/highlight.js:799:18)
    at Object.highlight (/usr/src/app/node_modules/cli-highlight/src/index.ts:97:21)
    at Function.PlatformTools.highlightJson (/usr/src/app/src/platform/PlatformTools.ts:221:16)
    at Object.<anonymous> (/usr/src/app/src/commands/QueryCommand.ts:55:39)
    at step (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:141:27)
    at Object.next (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:122:57)
    at fulfilled (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:112:62)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sindy@1.0.0 typeorm: `ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli --config ormconfig-migrations.ts "query" "SELECT * FROM folder;
npm ERR! SELECT * FROM sub_folder;"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the sindy@1.0.0 typeorm script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-08-24T13_13_49_857Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sindy@1.0.0 rls:on: `bash src/policies/enable-rls.sh`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the sindy@1.0.0 rls:on script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-08-24T13_13_49_873Z-debug.log

closed time in 9 days

nosteiner

pull request commenttypeorm/typeorm

fix: support changing comments in MySQL columns

It's super important for us to avoid breaking changes, and changes in schema sync are the most dangerous ones. That's why I'm always super dangerous on merging such PRs. Please make sure to check schema sync under different circumstances before merging it.

imnotjames

comment created time in 10 days

Pull request review commenttypeorm/typeorm

fix: support changing comments in MySQL columns

 export class MysqlQueryRunner extends BaseQueryRunner implements QueryRunner {             c += " PRIMARY KEY";         if (column.isGenerated && column.generationStrategy === "increment") // don't use skipPrimary here since updates can update already exist primary without auto inc.             c += " AUTO_INCREMENT";-        if (column.comment)-            c += ` COMMENT '${column.comment.replace("'", "''")}'`;+        if (column.comment != undefined && column.comment.length > 0)

!= ?

imnotjames

comment created time in 10 days

PullRequestReviewEvent

pull request commenttypeorm/typeorm

fix: use correct type for MongoQueryRunner.databaseConnection

Thank you!

imnotjames

comment created time in 10 days

push eventtypeorm/typeorm

James Ward

commit sha da70b405498b142ecc29f7ff01e7a37f88227360

fix: use correct type for MongoQueryRunner.databaseConnection (#6906) fixes #6453

view details

push time in 10 days

PR merged typeorm/typeorm

fix: use correct type for MongoQueryRunner.databaseConnection

it was using Db but instead it's actually MongoClient. Confirmed via the API docs for node-mongo, static analysis, and runtime verification.

fixes #6453

+3 -3

0 comment

1 changed file

imnotjames

pr closed time in 10 days

issue closedtypeorm/typeorm

MongoQueryRunner.databaseConnection is declared with a wrong type

Issue type:

[ ] question [x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [x] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

MongoQueryRunner.databaseConnection has the type Db while it should actually be MongoClient.

Where databaseConnection is defined in src/driver/mongodb/MongoQueryRunner.ts:

    /**
     * Real database connection from a connection pool used to perform queries.
     */
    databaseConnection: Db;

    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------

    constructor(connection: Connection, databaseConnection: Db) {
        this.connection = connection;
        this.databaseConnection = databaseConnection;
        this.broadcaster = new Broadcaster(this);
    }

Where it is created in src/driver/mongodb/MongoDriver.ts:

    connect(): Promise<void> {
        return new Promise<void>((ok, fail) => {
            this.mongodb.MongoClient.connect(
                this.buildConnectionUrl(),
                this.buildConnectionOptions(),
                (err: any, client: any) => {
                    if (err) return fail(err);

                    this.queryRunner = new MongoQueryRunner(this.connection, client);
                    ObjectUtils.assign(this.queryRunner, { manager: this.connection.manager });
                    ok();
                });
        });
    }

Reference to mongodb.MongoClient.connect: https://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#~connectCallback

<!-- To answer those questions you need to put "x" inside the square brackets, for example: [x] mysql [ ] postgres

Also, please format your code properly (by taking code blocks into ```ts .... ```)

--!>

closed time in 10 days

justin-lau

pull request commenttypeorm/typeorm

refactor: create base error and simplify error creation

I'm not that much fan of custom error classes. Do we really need them? This convention came to me (like to many people probably) from java background and I think this isn't necessary have to be here, in JavaScript. Same question applies to having a single error per file. The way I design errors last few years looks so.

imnotjames

comment created time in 10 days

Pull request review commenttypeorm/typeorm

fix: Handle undefined querysets in QueryCommand

 export class QueryCommand implements yargs.CommandModule {             console.log(chalk.green("Running query: ") + PlatformTools.highlightSql(args._[1]));             const queryResult = await queryRunner.query(args._[1]);             console.log(chalk.green("Query has been executed. Result: "));-            console.log(PlatformTools.highlightJson(JSON.stringify(queryResult, undefined, 2)));+            console.log(PlatformTools.highlightJson(+                queryResult === undefined ? "undefined" : JSON.stringify(queryResult, undefined, 2)

such logic isn't obvious at all. Maybe instead of showing undefined, we just tell something like "Query has been executed. No result was returned" instead?

imnotjames

comment created time in 10 days

PullRequestReviewEvent

push eventtypeorm/typeorm

James Ward

commit sha 84c18a9cab2e87b28eb046b5688bfca4d3ce9da6

feat: support query comments in the query builder (#6892) add a `comment` method to the QueryBuilder so we can include an arbitrary comment in our queries for a variety of purposes - from query plan stability to SQL reverse proxy routing, to debugging. the comment builder is supported in selects, inserts, deletes, and updates this is directly inspired by the functionality supported by hibernate to handle SQL Query comments it uses C-style queries which are ANSI SQL 2003 & supported in all of the dialects of SQL that we support as drivers fixes #3643

view details

push time in 10 days

pull request commenttypeorm/typeorm

feat: support query comments in the query builder

Thank you!

imnotjames

comment created time in 10 days

PR merged typeorm/typeorm

feat: support query comments in the query builder

add a comment method to the QueryBuilder so we can include an arbitrary comment in our queries for a variety of purposes - from query plan stability to SQL reverse proxy routing, to debugging. the comment builder is supported in selects, inserts, deletes, and updates

this is directly inspired by the functionality supported by hibernate to handle SQL Query comments

it uses C-style queries which are ANSI SQL 2003 & supported in all of the dialects of SQL that we support as drivers

fixes #3643

+131 -4

0 comment

8 changed files

imnotjames

pr closed time in 10 days

issue closedtypeorm/typeorm

Query Comments

Issue type:

[ ] question [ ] bug report [x] feature request [ ] documentation issue

Would you be open to a PR that added support for "naming" queries? I.e. something like:

Post.createQueryBuilder()
  .comment(`Lookup all the posts in ${ category } category`)
  .where({ category })
  .getSql()

/*
-- Lookup all the posts in foo category
SELECT ...

It would only be stored / used in TypeORM, obviously not submitted to the driver layer.

I've found a few times where I'm trying to diagnose a API call that makes multiple complex queries and is failing due to an SQL error. I end up trying to read the generated SQL and trying to infer where in my code that query came from. It would be nice to be able to label the queries such that I could easily trace them back when the error causes TypeORM to dump getSql() output.

closed time in 10 days

davewasmer

pull request commenttypeorm/typeorm

fix: sync the typeorm-model-shim

Thanks!

imnotjames

comment created time in 12 days

push eventtypeorm/typeorm

James Ward

commit sha c72e48b9c7b893f8a2483ba1ddaa7ded039fe349

fix: sync the typeorm-model-shim (#6891) this updates the shim to include all current decorators exported from index.ts - adding @Unique and a few others fixes: #6288 fixes: #5920

view details

push time in 12 days

PR merged typeorm/typeorm

fix: sync the typeorm-model-shim

this updates the shim to include all current decorators exported from index.ts - adding @Unique and a few others

fixes: #6288 fixes: #5920

+145 -128

0 comment

1 changed file

imnotjames

pr closed time in 12 days

issue closedtypeorm/typeorm

there is no Unique decoration export in typeorm-model-shim

Issue type: [v] feature request

TypeORM version: [v] latest

Hello, I'm developer who loves typeorm that holy powerful and super comfortable ORM framework since using Hibernate.

I found the error on my front-end when use typeorm-shims with @Unique decorators in entity.

typeorm shim.js is set on tsconfig. but after when I add @Unique decoration, In my case, Angular framework throw webpack_imported_module _9_ default(...) is not a function error.

I was manually patching Unique fake function to typeorm-model-shim.js, then fixing this issue.

Can you add Unique for typeorm shims? Or How can I support for you? I hope to help typeorm. Typeorm has insufficient features but the best on all javascript ORM. I'm totally fan of you.

closed time in 12 days

Overfacto

push eventpleerock/frameworkx

Umed Khudoiberdiev

commit sha 28e5f0407d1691981139f96061704445515b300a

added basic swagger support

view details

push time in 16 days

pull request commenttypeorm/typeorm

fix: create typeorm_metatable when running migrations

we don't have tests for cli commands yet.. if someone can contribute and start writing tests for CLI for the first time, this one is a good opportunity. If nobody wants, probably we can merge this one.

BitPatty

comment created time in 16 days

push eventtypeorm/typeorm

James Ward

commit sha 4abfb342aa390ab4643a1133daaf90c0996b61c2

fix: handle count multiple PK & edge cases more gracefully (#6870) currently we use concatenation of multiple primary keys and a COUNT DISTINCT of that to figure out how many records we have matched in a query. however, that fails if the records have keys when the keys are ambigious when concatenated (`"A", "AA"` & `"AA", "A"`) the fact that we do a distinct can also be a performance impact that isn't needed when we aren't doing joins as such, in MySQL & Postgres we can use the built in counting of multiple distinct values to resolve some of the issues, and in other environments we can make it SLIGHTLY better by adding delimiters between the concatenated values. It is not perfect because it technically could run into the same issue if the delimiters are in the primary keys but it's BETTER in most cases. also, in cases where we do not perform any joins we can short circuit all of this and do a much more performant `COUNT(1)` operation fixes #5989 fixes #5314 fixes #4550

view details

push time in 16 days

PR merged typeorm/typeorm

fix: handle count multiple PK & edge cases more gracefully

currently we use concatenation of multiple primary keys and a COUNT DISTINCT of that to figure out how many records we have matched in a query.

however, that fails if the records have keys when the keys are ambigious when concatenated ("A", "AA" & "AA", "A")

the fact that we do a distinct can also be a performance impact that isn't needed when we aren't doing joins

as such, in MySQL & Postgres we can use the built in counting of multiple distinct values to resolve some of the issues, and in other environments we can make it SLIGHTLY better by adding delimiters between the concatenated values. It is not perfect because it technically could run into the same issue if the delimiters are in the primary keys but it's BETTER in most cases.

also, in cases where we do not perform any joins we can short circuit all of this and do a much more performant COUNT(1) operation

fixes #5989 fixes #5314 fixes #4550 fixes: #4998

+151 -34

0 comment

3 changed files

imnotjames

pr closed time in 16 days

issue closedtypeorm/typeorm

getCount(). Perfs issues for multi columns primary key

Issue type:

[X ] question

Database system/driver: [X ] postgres

Version 0.2.18

I'm facing a perf issue when running getCount() Why when counting all records of a query, queryBuilder creates a SQL query that concatenates the columns that are part of the primary key ?

Typescript :

const query: SelectQueryBuilder<TEntity> = dbConnection
					.getRepository<TEntity>(entity)
					.createQueryBuilder(entity.name)
					.where(`"${entity.name}"."${id}"= :val`, {
						val: value.toLowerCase(),
					});

				const totalRecords: number = await query.getCount();

generated sql

SELECT COUNT(DISTINCT(
	CONCAT(
		"u"."a", 
		"u"."b",
		"u"."c")
	)
) as "cnt" FROM "sc"."tbl" "u"

That is destroying the performances for a table of 140K records. Creating an index on CONCAT using is not efficient, hard to maintain with 100 of tables, knowing that for some tables, some primay comumns are timestamp...

Is there a way or a parameter to set to avoid the concat and just running a kind of (select count(1) FROM "sc"."tbl" "u") ?

Rgds

closed time in 16 days

jeromeSH26

issue closedtypeorm/typeorm

Typeorm add select distinct in my query. I dont want select distinct. Help!

Issue type:

[x] question

[x] postgres

Hello I want to make a query where I get the data above, but the typeorm is putting select distinct in the query and because of this is giving error.

const [response, count] = await this.database .getRepository(Rating) .createQueryBuilder("rating") .select( 'rating.id as id, station.name as stationname, rating.stationtext as text, rating.operatorrating as orating, rating.stationrating as srating, fillin.created_at, customer.name as cname, rating.operatorname as oname' ) .innerJoin("rating.fillin", "fillin") .innerJoin("fillin.customer", "customer") .innerJoin("rating.station", "station") .where("fillin.is_deleted = false AND station.chain_id = :chainId", { chainId }) //.setParameter("chainId", chainId) .skip(skip) .take(take) .getManyAndCount();

The console return this:

query: SELECT DISTINCT "distinctAlias"."rating_id" as "ids_rating_id" FROM (SELECT "rating"."id" as id, "station"."name" as stationname, rating.stationtext as text, [1] rating.operatorrating as orating, rating.stationrating as srating, fillin.created_at, [1] "customer"."name" as cname, rating.operatorname as oname FROM "rating" "rating" INNER JOIN "fillin" "fillin" ON "fillin"."id"="rating"."fillinid" INNER JOIN "customer" "customer" ON "customer"."id"="fillin"."customer_id" INNER JOIN "station" "station" ON "station"."id"="rating"."stationid" WHERE fillin.is_deleted = false AND station.chain_id = $1) "distinctAlias" ORDER BY "rating_id" ASC LIMIT 10 -- PARAMETERS: ["aedbcc7f-d336-45d3-b04b-b598bd2445ee"] [1] query failed: SELECT DISTINCT "distinctAlias"."rating_id" as "ids_rating_id" FROM (SELECT "rating"."id" as id, "station"."name" as stationname, rating.stationtext as text, [1] rating.operatorrating as orating, rating.stationrating as srating, fillin.created_at, [1] "customer"."name" as cname, rating.operatorname as oname FROM "rating" "rating" INNER JOIN "fillin" "fillin" ON "fillin"."id"="rating"."fillinid" INNER JOIN "customer" "customer" ON "customer"."id"="fillin"."customer_id" INNER JOIN "station" "station" ON "station"."id"="rating"."stationid" WHERE fillin.is_deleted = false AND station.chain_id = $1) "distinctAlias" ORDER BY "rating_id" ASC LIMIT 10 -- PARAMETERS: ["aedbcc7f-d336-45d3-b04b-b598bd2445ee"] [1] Debug: handler, error [1] QueryFailedError: column distinctAlias.rating_id does not exist

closed time in 16 days

HenriqueRamos13

issue closedtypeorm/typeorm

Count returns incorrect results for multiple primary keys

When using an entity with multiple primary keys, count() can return an incorrect result.

The current behavior of count with primary keys is to concat the two keys together and then count the distinct result of that. If the primary keys are of the same data type and can contain the same values, this will result in an incorrect count. See below for an example.

There are other reasons why the current method of concat is not desirable, particular regarding performance as it causes indexes to be ignored.

Some related issues

  • #5314
  • #4550
  • #2535

Issue type:

[ ] question [X] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [X] mssql [ ] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[X] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

The following example incorrectly returns a count of 1 when there are 2 records

@Entity()
export class MyEntity {
	@PrimaryColumn()
	field1: number;

	@PrimaryColumn()
	field2: number;
}
{
	field1: 11,
	field2: 101
	// concat(field1, field2) = '11101'
},
{
	field1: 1,
	field2: 1101
	// concat(field1, field2) = '11101'
},

<!-- To answer those questions you need to put "x" inside the square brackets, for example: [x] mysql [ ] postgres

Also, please format your code properly (by taking code blocks into ```ts .... ```)

--!>

closed time in 16 days

dsbert

push eventtypeorm/typeorm

James Ward

commit sha 5c407deed4016c7eacb9cf25e4de7bade4a88407

chore: add `funding` to the package manifest (#6873) adds the funding key to the manifest as the opencollective per https://docs.npmjs.com/configuring-npm/package-json.html#funding fixes #4649

view details

push time in 16 days

PR merged typeorm/typeorm

chore: add `funding` to the package manifest

adds the funding key to the manifest as the opencollective per https://docs.npmjs.com/configuring-npm/package-json.html#funding

fixes #4649

+1 -0

0 comment

1 changed file

imnotjames

pr closed time in 16 days

issue closedtypeorm/typeorm

TypeORM OpenCollective does not show up on BackYourStack

I uploaded the package.json for a project of mine using TypeORM to https://backyourstack.com/ to get a list of projects we're using with OpenCollectives to try and get my client to pledge to.

However while https://opencollective.com/typeorm exists and #3267 has been trying to get people to support the library, that OpenCollective does not show up in the list. When I examine the detected dependencies it does not appear that the typeorm package is associated with any OpenCollective.

If the maintainers want to make more people aware of the TypeORM OpenCollective, https://backyourstack.com/faq suggests that the owners of the collective should contact OpenCollective support.

closed time in 16 days

dantman

pull request commenttypeorm/typeorm

feat(migrations): add lock mechanism

I think we should have this feature. There are many 👍 on this PR and it does matter. Also, I have faced this issue in a real world, and my solution might be not perfect for everyone and having this improvement might be handy for many people.

I went to look at a few different similar ORMs - the following don't support this:

some of ORMs are really less immature... so I wouldn't use comparison in this case.

It'd be one thing if we were using some sort of built in table locking mechanism to prevent multiple workers from touching the migration table at once, but implementing and maintaining our own pessimistic locking mechanism is a bit much.

do we have any database-level options to implement this feature? If yes, and it would be simpler - let's do it. If no, we need to improve this PR and merge it.

Regarding to this PR - to merge it, I have few notes:

  • I suggest following option signature:
private readonly migrationsLock?: {
    strategy: "none" | "wait-for-unlock"  | "throw-error" | "skip-migrations"; // "none" is default
    waitForUnlockInterval: number; // by default 1000 ms
};
  • use typeorm_metadata table, because we already have some other functionality storing metadata information, I would like to avoid creating many typeorm-specific tables, and store everything inside one table (table name isn't customizable yet, but we can add this as another feature). Also, we don't really need to drop this table in case if something fails.

Also, can you please provide a real-world scenarios where "throw-error" and "skip-migrations" are really needed?

But again, before applying these changes I would like to be sure if there are no ways to implement same logic using database-level locks.

Sorry @ruscon for being slow on reviewing this one.

ruscon

comment created time in 18 days

IssuesEvent
PullRequestEvent

pull request commenttypeorm/typeorm

doc: roadmap - remove stable release date temporarily

@gtpan77 join our slack group where you can ask more about what features are currently good to have / in priority to do

gtpan77

comment created time in 18 days

pull request commenttypeorm/typeorm

docker option in typeorm init command

does it work?

gtpan77

comment created time in 18 days

PR closed typeorm/typeorm

sample 35: one-to-one cascade deletion

Reason Users has doubt that removing any side of row in a relation would result in deletion of both side of row in the relation. link

Solution I found that only deleting referencing row would delete referenced row. Otherwise, it will only delete only one side.

If it looks legit, You can also close the issue.

+85 -1

8 comments

4 changed files

gtpan77

pr closed time in 18 days

pull request commenttypeorm/typeorm

sample 35: one-to-one cascade deletion

Great, thanks!

gtpan77

comment created time in 18 days

push eventtypeorm/typeorm

Nicolas Lenepveu

commit sha 990442e891e91cd829f9f34eff2114d4c623d24b

feat: schema synchronization for partitioned tables with PostgreSQL 12+ (#6780) * feat: ignore foreign keys on partitions of partitioned tables when syncing schema on postgresql 12+ * feat: consider partitionned tables as regular tables in order to keep them in sync

view details

push time in 18 days

pull request commenttypeorm/typeorm

Fix schema synchronization for partitioned tables with PostgreSQL 12+

Looks good, thanks

nlenepveu

comment created time in 18 days

PR merged typeorm/typeorm

Fix schema synchronization for partitioned tables with PostgreSQL 12+

Consider partitioned tables as regular tables

Typeorm currently excludes partitioned tables from schema synchronization. We could also take them into account as their behavior regarding schema modifications is the same as regular tables.

Ignore foreign keys on partitions of the partitioned tables when syncing schema on PostgreSQL 12+

When a table has foreign keys referencing a partitioned table, the PostgresQueryRunner will load the constraints from every partition. We need to ignore those foreign keys as they are not managed by the user.

Example: table_A has a foreign key constraint referencing table_B which is a partitioned table on key1 and key2.

The command typeorm schema:log will return this kind of list of queries to remove the FK constraints from table_A.

------------------------------------------------------------------
-- Schema syncronization will execute following sql queries (220):
------------------------------------------------------------------
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2__fkey";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey1";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey2";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey3";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey4";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey5";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey6";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey7";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey8";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey9";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey10";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey11";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey12";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey13";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey14";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey15";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey16";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey17";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey18";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey19";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey20";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey21";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey22";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey23";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey24";
ALTER TABLE "table_A" DROP CONSTRAINT "table_A_table_B_key1_key2_fkey25";
...

Typeorm should ignore those constraints.

+14 -3

1 comment

1 changed file

nlenepveu

pr closed time in 18 days

pull request commenttypeorm/typeorm

sample 35: one-to-one cascade deletion

I don't see enough reasons to merge this new sample. I you had a question, and I think you got your answer now. It will be helpful to others if you answer question on SO.

p.s. looks like subscribersDir change is needed since its a bugfix.

gtpan77

comment created time in 18 days

pull request commenttypeorm/typeorm

feat: backport ilike from next

Thank you!

imnotjames

comment created time in 18 days

push eventtypeorm/typeorm

James Ward

commit sha c8bf81ed2d47ba0822f8d6267ae1997180db2e31

feat: backport ilike from next (#6862) the next branch has support for ilike and this backports the FindOperator into the main branch

view details

push time in 18 days

PR merged typeorm/typeorm

feat: backport ilike from next

the next branch has support for ilike and this backports the FindOperator into the main branch

+58 -0

4 comments

5 changed files

imnotjames

pr closed time in 18 days

pull request commenttypeorm/typeorm

fix: prevent dangling transactions in sqlite

Per documentation, the QueryRunner is noted as running queries on a single database connection.

it's important to understand that SQLite* is the only driver where it's not possible to have multiple query runners. Because there is only one connection in SQLite, we have only one QueryRunner and it doesn't make sense to create other QueryRunners, there can be only one connection. Same, it doesn't make sense to release a query runner. Releasing it means disconnecting from the database, e.g. connection.disconnect()

imnotjames

comment created time in 19 days

pull request commenttypeorm/typeorm

feat: backport ilike from next

HMM, one of the mainline drivers don't support it either but I'm not sure which one.

It would be great I think to quickly understand from CI what exact driver failed, to improve our developer experience.

imnotjames

comment created time in 19 days

pull request commenttypeorm/typeorm

docs: improve the doc about Raw operator and add missing test

Out of curiosity, where does the :...data syntax come from ?

It is typeorm magic. Not a great implementation however, but it just works.

tychota

comment created time in 19 days

pull request commenttypeorm/typeorm

sample 35: one-to-one cascade deletion

I changed your code and tests are still passing - it means you don't need onDelete from both sides. Only from the side where JoinColumn persists. It's a basic behaviour of any RDBMS and relations, it's not really related to ORM.

gtpan77

comment created time in 19 days

push eventgtpan77/typeorm

Umed Khudoiberdiev

commit sha 82e36b00958a94d97c7f8c5577a1716c1b72228e

you shouldn't have onDelete on inverse side

view details

push time in 19 days

pull request commenttypeorm/typeorm

sample 35: one-to-one cascade deletion

can you please add a description to this PR - motivation behind this PR? Thanks.

gtpan77

comment created time in 19 days

Pull request review commenttypeorm/typeorm

sample 35: one-to-one cascade deletion

+import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from "../../../src/index";+import { Profile } from "./Profile";++@Entity()+export class User {++  @PrimaryGeneratedColumn()+  id: number;++  @Column()+  name: string;++  @OneToOne(() => Profile, (profile: { user: any; }) => profile.user, { eager: true, onDelete: "CASCADE" })

why do you need (profile: { user: any; }) ? why not just profile => profile.user ?

gtpan77

comment created time in 19 days

PullRequestReviewEvent

push eventtypeorm/typeorm

Jakob Wagner

commit sha 2d9a3ce737996152f52872d5461860dbf6ef3900

docs: update many-to-one-one-to-many-relations.md (#6832) Changing this as it would give an linting error (no unused variable)

view details

push time in 19 days

PR merged typeorm/typeorm

Update many-to-one-one-to-many-relations.md

Changing this as it would give an linting error (no unused variable)

reopened PR as mentioned in https://github.com/typeorm/typeorm/pull/6665#issuecomment-702703079

+2 -2

2 comments

1 changed file

jakobwgnr

pr closed time in 19 days

pull request commenttypeorm/typeorm

Update many-to-one-one-to-many-relations.md

Since its just a small fix in docs, we are safe to merge it. Thank you!

jakobwgnr

comment created time in 19 days

pull request commenttypeorm/typeorm

fix: allow for complex jsonb primary key columns

Thank you!

Maddimax

comment created time in 19 days

push eventtypeorm/typeorm

maddimax

commit sha f95e9d8f9a6c7a1117564b3e3f65b5294f8d5ff5

fix: allow for complex jsonb primary key columns (#6834) * fix: allow for complex jsonb primary key columns When using PrimaryColumn with a 'jsonb' type column ( on a postgres database ) the RawSqlResultsToEntityTransformer would simply convert the key to '[object Object]' instead of a unique value based on the key value. It would then wrongly consider each entity as having the same key. To allow for complex keys the transformer now uses JSON.stringify() to convert the keys value if they are of type obejct to a unique string that can be compared to other entities. fixes #6833 * test: add tests for jsonb primarykey columns These tests verify that Entities with jsonb primary columns are correctly converted to Entites

view details

push time in 19 days

issue closedtypeorm/typeorm

JSON Keys break RawResult to EntityTransformer

( I've provided a PR for this issue here: https://github.com/typeorm/typeorm/pull/6834 ) For the following entity:

class MyId {
   first: number;
   second: number;
}

@Entity({ name: 'tests' })
export class Test {
  @PrimaryColumn('jsonb')
  id: MyId;
}

With the following data:

id
{"first": 1, "second": 2}
{"first": 1, "second": 3}

The following code will only return one entity:

getRepository('tests').createQueryBuilder()
        .select()
        .where('id IN (:...ids)', {
          ids: [
            { first: 1, second: 2 },
            { first: 1, second: 3 },
          ],
        })
        .getMany();

This is due to:

https://github.com/typeorm/typeorm/blob/5ef94509b89f11f8337e18046c3f9d9632d234df/src/query-builder/transformer/RawSqlResultsToEntityTransformer.ts#L66

Adding

if (typeof keyValue === 'object') {
  return JSON.stringify(keyValue)
}

solves the issue

closed time in 19 days

Maddimax

PR merged typeorm/typeorm

fix: allow for complex jsonb primary key columns

Entities with 'jsonb' primary key are not correctly returned. ( see #6833 )

This PR adds a fix and tests for Issue #6833

+97 -0

0 comment

3 changed files

Maddimax

pr closed time in 19 days

pull request commenttypeorm/typeorm

fix: prevent dangling transactions in sqlite

why anyone needs to release a query runner in sqlite? We have only one query runner in sqlite, right? - it shouldn't be closed.

imnotjames

comment created time in 19 days

push eventtypeorm/typeorm

James Ward

commit sha 08ec0a8ed922225ff529790ad5ff19c0e463954e

fix: prevent create-type commands edge-case TypeErrors (#6836) in some cases - where the connection options couldn't be read - we would end up with the migration:create and similar commands failing with a TypeError this refactors the create commands a bit to defend against an undefined directory, preventing the TypeError fixes #6831

view details

push time in 19 days

PR merged typeorm/typeorm

fix: prevent create-type commands edge-case TypeErrors

in some cases - where the connection options couldn't be read - we would end up with the migration:create and similar commands failing with a TypeError

this refactors the create commands a bit to defend against an undefined directory, preventing the TypeError

fixes #6831

+15 -6

1 comment

3 changed files

imnotjames

pr closed time in 19 days

issue closedtypeorm/typeorm

[0.2.27] Regression: CLI migration:create fails with "TypeError: Cannot read property 'startsWith' of undefined"

Issue type:

[*] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [*] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[*] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

Run (with TYPEORM_MIGRATIONS_DIR=src/migrations in .env): node --require ts-node/register ./node_modules/typeorm/cli.js -- migration:create -n SomeName Or even: TYPEORM_MIGRATIONS_DIR=src/migrations node --require ts-node/register ./node_modules/typeorm/cli.js -- migration:create -n SomeName

Neither works. Only if I specify -d migration dir argument explicitly, it would create that migration.

Complete error output follows:

$ npm run typeorm -- migration:create -n SomeName

> xxx@0.0.1 typeorm /…/xxx
> node --require ts-node/register ./node_modules/typeorm/cli.js "migration:create" "-n" "SomeName"

Error during migration creation:
TypeError: Cannot read property 'startsWith' of undefined
    at Object.<anonymous> (/.../node_modules/.pnpm/typeorm@0.2.27/src/commands/MigrationCreateCommand.ts:62:37)
    at step (/.../node_modules/.pnpm/tslib@1.13.0/node_modules/tslib/tslib.js:141:27)
    at Object.throw (/.../node_modules/.pnpm/tslib@1.13.0/node_modules/tslib/tslib.js:122:57)
    at rejected (/.../node_modules/.pnpm/tslib@1.13.0/node_modules/tslib/tslib.js:113:69)
 ERROR  Command failed with exit code 1.

closed time in 19 days

constb

pull request commenttypeorm/typeorm

fix: prevent create-type commands edge-case TypeErrors

Thank you! At some point we would need a test coverage for CLI commands.

imnotjames

comment created time in 19 days

push eventtypeorm/typeorm

Gaurav Sharma

commit sha e9f9e1cae69d2e58dbf8f5c75abdac2e5e37407e

docs: docker-compose generation option in typeorm init command (#6841)

view details

push time in 19 days

pull request commenttypeorm/typeorm

feat: add ability for escaping for Raw() find operator

Thank you a lot!

temnov98

comment created time in 19 days

push eventtypeorm/typeorm

Temnov Aleksey

commit sha 91b85bfe6e73ff93db2684a13935b9bd6a9abcfd

feat: add ability for escaping for Raw() find operator (#6850) * feat: add ability for escaping for Raw() find operator * fix: update Raw() find operator * fix: fix tests for Raw() find operator * feat: add ability for escaping with object literal parameters for Raw() find operator * docs: correct the example comment of Raw() find operator * fix: delete redundant functional

view details

push time in 19 days

PR merged typeorm/typeorm

feat: add ability for escaping for Raw() find operator

Currently, find operator Raw() not supported escaping. I have updated the code so that it is now possible to use an escaping. The updated syntax is as follows:

await connection.getRepository(Post).find({
    likes: Raw((columnAlias, parameters) => {
        return `(${columnAlias} = ${parameters[0]}) OR (${columnAlias} = ${parameters[1]})`
    }, [2, 3]),
});

await connection.getRepository(Post).find({
    likes: Raw((columnAlias, parameters) => {
        return `(${columnAlias} = ANY(${parameters[0]})) AND (${columnAlias} < ${parameters[1]})`
    }, [[1, 4, 5, 6], 6]),
});

await connection.getRepository(Post).find({
    title: Raw((columnAlias, parameters) => {
        return `${columnAlias} = ANY(${parameters[0]})`;
    }, [["About #1", "About #3", "About #5"]]),
    likes: Raw((columnAlias, parameters) => `${columnAlias} IN (${parameters[0]}, ${parameters[1]})`, [5, 1]),
});

The tests for the new functionality have been written. The old functionality works unchanged.

+155 -12

5 comments

4 changed files

temnov98

pr closed time in 19 days

pull request commenttypeorm/typeorm

Use defaults provided in entity definition decorators

default in @Column is all about change in the database schema. I don't see a point to confuse things and introduce this change. If you don't need to change a database schema and instead just want to write some value, just use hooks or preset value before save.

jougene

comment created time in 20 days

pull request commenttypeorm/typeorm

fix: return null for nullable RelationId() column

Thank you!

anttimaki

comment created time in 20 days

push eventtypeorm/typeorm

Antti Mäki

commit sha 7147a0dbe7f2622a21c51edefa3b921f42e04b49

fix: return null for nullable RelationId() column (#6848) Fix issue where attempting to cast bigints to strings also did it for null values. Fix issue where transformRelationIds() filtered out null values when it should only be done for undefined. Closes: #6815

view details

push time in 20 days

PR merged typeorm/typeorm

fix: return null for nullable RelationId() column

Fix issue where attempting to cast bigints to strings also did it for null values.

Fix issue where transformRelationIds() filtered out null values when it should only be done for undefined.

Closes: #6815

+81 -3

0 comment

5 changed files

anttimaki

pr closed time in 20 days

issue closedtypeorm/typeorm

RelationId() on nullable relation returns 'null' string

Issue type:

<!-- Have a question? Check the "Support" Documentation on the best places to ask questions! --- https://github.com/typeorm/typeorm/blob/master/docs/support.md -->

[x] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [x] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[ ] latest [ ] @next [x] 0.2.25 (or put your version here)

Steps to reproduce or a small repository showing the problem:

@Entity()
export class ChildEntity {
  @PrimaryGeneratedColumn({ type: 'bigint' })
  id: string;
}

@Entity()
export class ParentEntity {
  @PrimaryGeneratedColumn({ type: 'bigint' })
  id: string;

  @OneToOne(() => ChildEntity, { nullable: true })
  @JoinColumn()
  child: ChildEntity | null;

  @RelationId((parent: ParentEntity) => parent.child)
  childId: string | null;
}

const parent = await entityManager.getRepository(ParentEntity).findOne(parentId);
console.log(parent) // parent.childId will be 'null' if column is null in database

Expected behaviour

childId should be null instead of 'null'

Additional comments

I am getting around this issue by using Column() instead of RelationId()

closed time in 20 days

angel200sdnot

PR merged typeorm/typeorm

refactor: check mysql constraint schema on join

in #6268 we pulled in a change that fixed the wrong FK getting loaded in a multi-database / multi-schema environment but in #6169 the approach was more desirable as it creates a simpler query that should be easier to change in the future

as such, this pulls over that change from #6169

+2 -2

2 comments

1 changed file

imnotjames

pr closed time in 20 days

push eventtypeorm/typeorm

James Ward

commit sha d2b914da6a425d47916c72ac50bfa69bea4847fb

fix: check mysql constraint schema on join (#6851) in #6268 we pulled in a change that fixed the wrong FK getting loaded in a multi-database / multi-schema environment but in #6169 the approach was more desirable as it creates a simpler query that should be easier to change in the future as such, this pulls over that change from #6169

view details

push time in 20 days

pull request commenttypeorm/typeorm

refactor: check mysql constraint schema on join

I'm always super scary to merge changes on QueryRunners and SQLs used for schema sync. Let's merge it, but keep track on breaking change issues.

imnotjames

comment created time in 20 days

Pull request review commenttypeorm/typeorm

feat: add ability for escaping for Raw() find operator

 import {FindOperator} from "../FindOperator";+import {ObjectLiteral} from "../../common/ObjectLiteral";  /**  * Find Options Operator.  * Example: { someField: Raw([...]) }  */-export function Raw<T>(value: string|((columnAlias: string) => string)): FindOperator<any> {-    return new FindOperator("raw", value as any, false);+export function Raw<T>(value: string): FindOperator<any>;++/**+ * Find Options Operator.+ * Example: { someField: Raw((columnAlias) => `${columnAlias} = 5`) }+ */+export function Raw<T>(sqlGenerator: ((columnAlias: string) => string)): FindOperator<any>;++/**+ * Find Options Operator.+ * For escaping parameters use next syntax:+ * Example: { someField: Raw((columnAlias, parameters) => `${columnAlias} = ${parameters[0]}`, [5]) }

Yes, it's just seems redundant. It's better to left only one syntax if they both do same and there are no technical issues.

temnov98

comment created time in 20 days

PullRequestReviewEvent

Pull request review commenttypeorm/typeorm

feat: add ability for escaping for Raw() find operator

 import {FindOperator} from "../FindOperator";+import {ObjectLiteral} from "../../common/ObjectLiteral";  /**  * Find Options Operator.  * Example: { someField: Raw([...]) }  */-export function Raw<T>(value: string|((columnAlias: string) => string)): FindOperator<any> {-    return new FindOperator("raw", value as any, false);+export function Raw<T>(value: string): FindOperator<any>;++/**+ * Find Options Operator.+ * Example: { someField: Raw((columnAlias) => `${columnAlias} = 5`) }+ */+export function Raw<T>(sqlGenerator: ((columnAlias: string) => string)): FindOperator<any>;++/**+ * Find Options Operator.+ * For escaping parameters use next syntax:+ * Example: { someField: Raw((columnAlias, parameters) => `${columnAlias} = ${parameters[0]}`, [5]) }

I can't understand why do we need this syntax. Isn't it redundant?

temnov98

comment created time in 20 days

PullRequestReviewEvent

Pull request review commenttypeorm/typeorm

feat: add ability for escaping for Raw() find operator

 import {FindOperator} from "../FindOperator";+import {ObjectLiteral} from "../../common/ObjectLiteral";  /**  * Find Options Operator.  * Example: { someField: Raw([...]) }

I think example is incorrect here

temnov98

comment created time in 20 days

PullRequestReviewEvent

push eventtypeorm/typeorm

James Ward

commit sha 7ebca2b9b1fd21e546b3a345a069637d6aab4b3e

feat: support ESM in ormconfig js & ts (#6853) fixes #5003

view details

push time in 20 days

pull request commenttypeorm/typeorm

fix: support ESM in ormconfig js & ts

Thank you!

imnotjames

comment created time in 20 days

more