Riley Conrardy
Riley Conrardy

Reputation: 562

TypeORM Timestamp Date equality not working

I'm using TypeORM with an Entity that looks something like this:

@Entity('users')
export class UserEntity extends BaseEntity {
  @PrimaryColumn()
  id: string;

  @CreateDateColumn({ type: 'timestamp' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'timestamp' })
  updatedAt: Date;
}

However, when I try to do any sort of timestamp equality related SQL query using the TypeORM Entity's repository it does not work properly. For example the query:

const id = 'dbe9e81d-aefa-459d-8460-707ade0fa156';
const userEntity = userRepository.findOne(id); // UserEntity(...)
const sameUserEntity = userRepository.findOne({ where: { createdAt: userEntity.createdAt } }); // undefined

Returns the correct entity for userEntity and undefined for sameUserEntity. I looked at the logs constructed by TypeORM for this query and it looks like this:

SELECT "UserEntity"."id" AS "UserEntity_id", 
    "UserEntity"."created_at" AS "UserEntity_created_at",
    "UserEntity"."updated_at" AS "UserEntity_updated_at" 
FROM "users" "UserEntity"
WHERE "UserEntity"."created_at" = $1 LIMIT 1 -- PARAMETERS: ["2022-02-19T22:10:13.564Z"]

It seems like TypeORM is not converting the JavaScript Date object to the correct PostgreSQL timestamp format. The timestamp in the database looks like 2022-02-19 22:10:13.564432, which is a completely different format and is a higher precision.

Is there a specific way I should be doing timestamp related searches when using TypeORM?

Note: I've tried too look for people having this same issue but I do not see any clear solution. I'm trying to implement cursor based pagination around the created at date, however the greater than and less than operators are not work properly as well.

Upvotes: 2

Views: 10840

Answers (1)

Martijn
Martijn

Reputation: 56

I recently ran into the same problem and fixed it by adding precision: 3 to the column decorator. Please note that this is based on the assumption that you don't need that level of precision to begin with.

@Entity('users')
export class UserEntity extends BaseEntity {
  @PrimaryColumn()
  id: string;

  @CreateDateColumn({ 
    type: 'timestamp', 
    precision: 3
  })
  createdAt: Date;

  @UpdateDateColumn({
    type: 'timestamp', 
    precision: 3
  })
  updatedAt: Date;
}

Upvotes: 4

Related Questions