@jimin4 - from their type defsin Repository.d.ts
`/**
* Finds first entity that matches given options.
*/
findOneOrFail(id?: string | number | Date | ObjectID, options?: FindOneOptions<Entity>): Promise<Entity>;
/**
* Finds first entity that matches given options.
*/
findOneOrFail(options?: FindOneOptions<Entity>): Promise<Entity>;
/**
* Finds first entity that matches given conditions.
*/
findOneOrFail(conditions?: FindConditions<Entity>, options?: FindOneOptions<Entity>): Promise<Entity>;
/**
* Executes a raw SQL query and returns a raw database results.
* Raw query execution is supported only by relational databases (MongoDB is not supported).`
Works exactly the same as FindOne in terms of function signature so all docs from there are applicable
save
or update
function.this.property = value
Hi all, in typeorm entity manager API documentation, there is method named release, it is used to release query runner of an entity manager. It also says here it should only be used when query runner was created and managed manually.
My question, what does "Used only when query runner was created and managed manually" means, and what is the use case for release to be used
Sorry for bad english, english not my first language
Hey there everyone, we recently ran a psql CREATE INDEX CONCURRENTLY
migration through the TypeORM migration system using queryRunner.connection.query
, and instead of async/await-ing the response, we defined .then
, .error
, and .finally
callbacks which would log when it was finished, so our webapp wouldn't be blocked while the concurrent index creation finished up.
On one of our servers, we see the log for "starting" the migration, but we never saw our logs for the .then
, .error
, and .finally
callbacks. This server was our instance with the most number of rows, and index creation definitely took longer than a couple minutes. But we verified in the DLL that the migration had successfully completed, despite never seeing our log statements.
Looking in the PSQL logs, I see that T+4s after the migration started, this error was printed LOG: could not receive data from client: Connection reset by peer
.
Does TypeORM or node have some sort of thing that kills promises after 4s? And if so, why didn't the query get killed or error out? My intuition says that normally the query would get canceled if a promise timeout occured
Hello there, I'm trying to convert raw mysql code to typeorm
how can i convert under sql?
select * from (
select acv.id, acv.week_title, MAX(acs.id) as m from development.audition_chart_v2 acv
inner join development.audition_chart_snapshots acs
ON acv.id = acs.audition_chart_id and acv.status = 'DONE'
group by acv.id
) as a
left join development.audition_chart_snapshots acs2 on acs2.id = a.m
Hi all,
I have a NestJS backend with TypeORM connected to a Postgres db.
The db has a table building_daly_max with a column named visitdate of type date. Data like the following:
building_id capacity wifi reserved workplaces visitdate
119 395 0 2020-10-26
13 354 0 2020-11-01
111 31 0 2020-11-01
120 530 0 2020-11-01
The entity looks like this:
@Entity({ name: 'building_daily_max' })
export class BuildingDailyOccupancyEntity {
@ManyToOne(() => BuildingEntity)
@JoinColumn({ name: 'building_id' })
building: BuildingEntity;
@PrimaryColumn({ name: 'visitdate', type: 'date' })
date: Date;
@Column({ name: 'capacity' })
capacity: number;
@Column({ name: 'wifi' })
maxWifiClientCount: number;
@Column({ name: 'reserved' })
maxReservationCount: number;
@Column({ name: 'workplaces' })
maxWorkplaceCount: number;
}
Querying by date only returns the first of the matching rows. However if I run the query typeorm performed manually in dbeaver I get all matching rows.
Also when running the raw query with the entitymanager returns all the rows.
Is this a bug in typeorm or am I missing something?
// Returns first row only
const result = await this.dailyOccupancyRepository.find({
relations: ['building'],
where: {
date: '2020-11-16',
},
});
// Returns first row only
const result = await this.dailyOccupancyRepository.createQueryBuilder()
.where('visitdate = :visitdate', { visitdate: '2020-11-16'})
.getMany();
// Returns all rows, but mapping to entities is a pain
const result = await this.entityManager.query('select * from building_daily_max bdm inner join buildings b on bdm.building_id = b.building_id where bdm.visitdate = $1', ['2020-11-16']);
I have a problem with where
clause and boolean value in TypeORM, like below:
async getUserProjects(user: User, isFavorite: boolean): Promise<User[]> {
const data = await this.conn.getRepository(User).find({
where: {
userId: user,
favorite: isFavorite
},
})
@Column({
type: 'bool'
})
favorite: boolean;
why this find
not work properly and always return me value where favorite
is false?
when my fav
== true
return me all data when favorite
== false..., can someone tell me what is wrong here?
@Entity()
^
SyntaxError: Invalid or unexpected token
Hi there, using typeOrm on node application I have this error when i start transaction to mysql:
(node:21) UnhandledPromiseRejectionWarning: QueryFailedError: ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction
at new QueryFailedError (/opt/app/node_modules/typeorm/error/QueryFailedError.js:11:28)
at Query.<anonymous> (/opt/app/node_modules/typeorm/driver/mysql/MysqlQueryRunner.js:170:45)
at Query.<anonymous> (/opt/app/node_modules/mysql/lib/Connection.js:526:10)
at Query._callback (/opt/app/node_modules/mysql/lib/Connection.js:488:16)
at Query.Sequence.end (/opt/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
at Query.ErrorPacket (/opt/app/node_modules/mysql/lib/protocol/sequences/Query.js:92:8)
at Protocol._parsePacket (/opt/app/node_modules/mysql/lib/protocol/Protocol.js:291:23)
at Parser._parsePacket (/opt/app/node_modules/mysql/lib/protocol/Parser.js:433:10)
at Parser.write (/opt/app/node_modules/mysql/lib/protocol/Parser.js:43:10)
at Protocol.write (/opt/app/node_modules/mysql/lib/protocol/Protocol.js:38:16)
at Socket.<anonymous> (/opt/app/node_modules/mysql/lib/Connection.js:88:28)
at Socket.<anonymous> (/opt/app/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at Socket.Readable.push (internal/streams/readable.js:223:10)
(node:21) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 377404)
21 - 2021-03-09T18:30:52.823Z - [ExceptionInterceptor] Database Exception - ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction
Error: Database Exception
at PartiesService.deleteContractParties (/opt/app/dist/apps/contracts-api/main.js:10592:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async ContractsService.update (/opt/app/dist/apps/contracts-api/main.js:11193:9)
21 - 2021-03-09T18:30:52.824Z - [ExceptionInterceptor] Catched DatabaseException exception -> throw InternalServerErrorException
21 - 2021-03-09T18:30:52.826Z - [ExceptionHandler] DatabaseException: {"type":"DatabaseException","subType":"Party","internalMessage":"ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction"}
Error: Database Exception
at CatchSubscriber.selector (/opt/app/dist/apps/contracts-api/main.js:1332:42)
at CatchSubscriber.error (/opt/app/node_modules/rxjs/internal/operators/catchError.js:48:31)
at MergeMapSubscriber.OuterSubscriber.notifyError (/opt/app/node_modules/rxjs/internal/OuterSubscriber.js:26:26)
at InnerSubscriber._error (/opt/app/node_modules/rxjs/internal/InnerSubscriber.js:31:21)
at InnerSubscriber.Subscriber.error (/opt/app/node_modules/rxjs/internal/Subscriber.js:72:18)
at SwitchMapSubscriber.Subscriber._error (/opt/app/node_modules/rxjs/internal/Subscriber.js:92:26)
at SwitchMapSubscriber.Subscriber.error (/opt/app/node_modules/rxjs/internal/Subscriber.js:72:18)
at /opt/app/node_modules/rxjs/internal/util/subscribeToPromise.js:10:43
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
some one can help me to fix it? any hint or ideas are appreciated
Hi all, I'm new to typeorm but I'm seeing a very strange issue with the synchronize: true
functionality when I modify an entity with a ManytoMany relationship. In short, any data that is in the join table before making the entity change, is gone after.
Here is my Project
Entity
@ObjectType()
@Entity("project")
export class Project extends BaseEntity {
@Field(() => Int)
@PrimaryColumn()
id: number;
@Field()
@Column("text")
name: string;
@Field({ nullable: true })
@Column("text", { nullable: true })
cluster?: string;
//project_groups
@ManyToMany((type) => Group, (group) => group.projects, { lazy: true })
@Field((type) => [Group], { nullable: true })
@JoinTable()
groups?: Group[];
}
Here is my Group
Entity
@ObjectType()
@Entity("group")
export class Group extends BaseEntity {
@Field(() => String)
@PrimaryColumn()
id: string;
@Field()
@Column("text")
name: string;
@Field({ nullable: true })
@Column("text")
type: string;
@Field({ nullable: true })
@Column("text", { nullable: true })
currency: string;
@Field((type) => [Project])
@ManyToMany((type) => Project, (project) => project.groups, { lazy: true })
projects: Project[];
//group_modifiers
@ManyToMany((type) => Modifier, (modifier) => modifier.group, { lazy: true })
@Field((type) => [Modifier])
@JoinTable()
modifiers: Modifier[];
}
If I add a new field to either the Group or the Project, the migration is automatically run and the following queries
query: CREATE TABLE "temporary_project" ("id" integer PRIMARY KEY NOT NULL, "name" text NOT NULL, "cluster" text, "asdfa" text)
query: INSERT INTO "temporary_project"("id", "name", "cluster") SELECT "id", "name", "cluster" FROM "project"
query: DROP TABLE "project"
query: ALTER TABLE "temporary_project" RENAME TO "project"
project_groups_group
table has data before, and is empty after the migration is finished
How to get count and num of relation.
but it's not work
Does anyone know if it's possible to set a field to null
using the save
method? Is there some fancy trick that I'm unaware of? Do I need to use some sort of helper function like IsNull
when you're working with the find
methods?
For example...
// Let's find Jeff and get rid of his stupid middle name
const jeff = await userRepository.findOne({firstName: 'Jeff'})
jeff.middleName = null
await userRepository.save(jeff)
// Doesn't work... Jeff still has a middle name
update
method to accomplish this, but my use case is dependent on the TypeORM events/subscribers system, and update
unfortunately does not work with the event system
Using TypeOrm for the first time against an already existing schema, the table names are plural and PascalCase and the entities should be singular. Therefore I'm using
@Entity('AccessLogs')
export class AccessLog {
To define the entity. When I run migrate:generate
it generates a change script that tries to create that Table AccessLogs
even though it already exists.
If I change the table name to lowercase:
@Entity('accesslogs')
export class AccessLog {
the problem goes away - but then the mapping in the Entity decorator is wrong and a newly created database with these migrations with generate the lowercase table name, which won't match all the other existing instances of the database. Surely I can't be the first person who doesn't have lowercase or snake_case table names?