Pass empty string to column datatype is enum postgres got error - postgresql

I got an error when I pass an empty string to completed but when I pass empty string to delivery_name is work fine
const queryBuilder = this.deliveryRepository
.createQueryBuilder('delivery')
.select([
'delivery.delivery_id AS delivery_id',
'delivery.price AS price',
'delivery.delivery_date AS invoice_date',
'delivery.invoice_id AS invoice_id',
'delivery.completed AS completed',
'delivery.deliveryman_id AS deliveryman_id',
'deliveryman.delivery_name AS delivery_name',
'deliveryman.vehicle AS vehicle',
'deliveryman.phone AS phone',
]).orWhere('LOWER(deliveryman.delivery_name) LIKE LOWER(:delivery_name)', {
delivery_name: `%${option.filter}%`,
}).orWhere('delivery.completed = :completed', {
completed: `%${option.filter}%`,
})
DeliveryEntity
import { DeliveryManEntity, InvoiceEntity } from '#entity';
import { DeliveryStatus } from '../../../constant/delivery/delivery-status';
import {
Column,
Entity,
JoinColumn,
ManyToOne,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { ShareEntity } from '#share-entity';
#Entity({ name: 'delivery' })
export class DeliveryEntity extends ShareEntity {
#PrimaryGeneratedColumn()
delivery_id: number;
#Column({ nullable: true, default: 0 })
price: number;
#Column({ type: 'date', default: () => 'NOW()' })
delivery_date: Date;
#OneToOne(() => InvoiceEntity, (entity) => entity.delivery)
#JoinColumn({ name: 'invoice_id', referencedColumnName: 'invoice_id' })
invoice: InvoiceEntity;
#Column()
invoice_id: number;
#Column({
enum: DeliveryStatus,
type: 'enum',
default: DeliveryStatus.PENDING,
enumName: 'delivery_status',
name: 'completed',
})
completed: DeliveryStatus;
#ManyToOne(() => DeliveryManEntity, (entity) => entity.delivery)
#JoinColumn({
name: 'deliveryman_id',
referencedColumnName: 'deliveryman_id',
})
deliveryman: DeliveryManEntity;
#Column()
deliveryman_id: number;
}
Delivery Status
export enum DeliveryStatus {
PENDING = 'PENDING',
COMPLETED = 'COMPLETED',
}
I want to pass an empty string to completed or I can pass PENDING OR COMPLETED
any solution how to query with empty string to completed field
I'm using typeorm + Nestjs +Postgresql

Based on your comment, what you should be doing is something like below:
const queryBuilder = this.deliveryRepository
.createQueryBuilder('delivery')
.select([
'delivery.delivery_id AS delivery_id',
'delivery.price AS price',
'delivery.delivery_date AS invoice_date',
'delivery.invoice_id AS invoice_id',
'delivery.completed AS completed',
'delivery.deliveryman_id AS deliveryman_id',
'deliveryman.delivery_name AS delivery_name',
'deliveryman.vehicle AS vehicle',
'deliveryman.phone AS phone',
]).orWhere('LOWER(deliveryman.delivery_name) LIKE LOWER(:delivery_name)', {
delivery_name: `%${option.filter}%`,
});
const filter = `%${option.filter}%`;
if (filter === "") {
queryBuilder.orWhere('delivery.completed IN (...:completed)', {
completed: [DeliveryStatus.COMPLETED, DeliveryStatus.PENDING],
});
} else {
queryBuilder.orWhere('delivery.completed = :completed', {
completed: filter,
});
}

Related

TypeORMError: alias was not found

I'm trying to make API pagination for GET /authors.
I have bidirectional many to many relation between authors and books table.
I found that problem is when using creatingQueryBuilder() in combination with .leftJoinAndSelect() and .skip() I get TypeORMError: ""authors"" alias was not found. Maybe you forgot to join it?. But I'm not sure how to solve it.
My database look like this:
library=# select * from authors;
id | first_name | last_name | birth_date | created_at | updated_at
----+------------+-----------+------------+----------------------------+----------------------------
library=# select * from books;
id | title | isbn | pages | created_at | updated_at
----+------------------+-----------------------+-------+----------------------------+----------------------------
library=# select * from books_authors
books_id | authors_id
----------+------------
(4 rows)
Entities look like this:
import { Exclude } from 'class-transformer';
import { BookEntity } from 'src/book/entities/book.entity';
import {
Entity,
PrimaryGeneratedColumn,
Column,
BeforeInsert,
ManyToMany,
} from 'typeorm';
#Entity({ name: 'authors' })
export class AuthorEntity {
#Exclude()
#PrimaryGeneratedColumn()
id: number;
#Column()
firstName: string;
#Column()
lastName: string;
#Column({ type: 'date', nullable: true })
birthDate: Date | null;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
updatedAt: Date;
#ManyToMany(() => BookEntity, (book) => book.authors)
books: BookEntity[];
#BeforeInsert()
updateTimestamp() {
this.updatedAt = new Date();
}
}
import { Exclude } from 'class-transformer';
import { AuthorEntity } from 'src/author/entities/author.entity';
import {
Entity,
PrimaryGeneratedColumn,
Column,
BeforeInsert,
ManyToMany,
JoinTable,
} from 'typeorm';
#Entity({ name: 'books' })
export class BookEntity {
#Exclude()
#PrimaryGeneratedColumn()
id: number;
#Column()
title: string;
#Column()
isbn: string;
#Column()
pages: number;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
updatedAt: Date;
#ManyToMany(() => AuthorEntity, (author) => author.books)
#JoinTable({ name: 'books_authors' })
authors: AuthorEntity[];
#BeforeInsert()
updateTimestamp() {
this.updatedAt = new Date();
}
}
Service method looks like this:
async findAll(
pageOptionsDto: PageOptionsDto,
filterAuthorDto: FilterAuthorDto,
): Promise<PageDto<AuthorEntity>> {
const builder = this.dataSource
.getRepository(AuthorEntity)
.createQueryBuilder('authors');
if (filterAuthorDto?.firstName) {
builder.where('"authors"."first_name" LIKE :firstName', {
firstName: `%${filterAuthorDto.firstName}%`,
});
}
if (filterAuthorDto?.lastName) {
builder.andWhere('"authors"."last_name" LIKE :lastName', {
lastName: `%${filterAuthorDto.lastName}%`,
});
}
// This part of code is problematic
builder
.innerJoinAndSelect('authors.books', 'books')
.orderBy('"authors"."created_at"', pageOptionsDto.order)
.skip(pageOptionsDto.skip)
.take(pageOptionsDto.perPage);
const total = await builder.getCount();
const { entities } = await builder.getRawAndEntities();
const pageMetaDto = new PageMetaDto({ total, pageOptionsDto });
return new PageDto(entities, pageMetaDto);
}
Just remove the double quotation inside the string, it's redundant and makes typeorm get confused and couldn't find related defined alias.
...
.orderBy('authors.created_at', pageOptionsDto.order)
...

Typeorm (Nestjs) update ManyToMany relation when using querybuilder violates not-null constraint

I have a simple ManyToMany setup with typeorm. According to the docs of typeORM on how to update/add a ManyToMany relation.
Link to the docs: https://typeorm.io/relational-query-builder
The error I get:
The query it produces, and here is the problem, it does not have 2 parameters and 'usersId' is empty. I think the user has to exist first before connecting them together, but maybe someone can confirm this? Why does it not create the user for me when adding a new user in enterprise?
query: SELECT "Enterprise"."id" AS "Enterprise_id", "Enterprise"."createdAt" AS "Enterprise_createdAt", "Enterprise"."updatedAt" AS "Enterprise_updatedAt", "Enterprise"."name" AS "Enterprise_name", "Enterprise"."erpCustomerCode" AS "Enterprise_erpCustomerCode", "Enterprise"."isActive" AS "Enterprise_isActive", "Enterprise"."street" AS "Enterprise_street", "Enterprise"."houseNumber" AS "Enterprise_houseNumber", "Enterprise"."city" AS "Enterprise_city", "Enterprise"."state" AS "Enterprise_state", "Enterprise"."country" AS "Enterprise_country", "Enterprise"."zip" AS "Enterprise_zip", "Enterprise"."geoLocation" AS "Enterprise_geoLocation", "Enterprise"."unitsSystem" AS "Enterprise_unitsSystem", "Enterprise"."weekNumberingSystem" AS "Enterprise_weekNumberingSystem", "Enterprise"."yearStart" AS "Enterprise_yearStart", "Enterprise"."weekStart" AS "Enterprise_weekStart" FROM "enterprises" "Enterprise" WHERE ("Enterprise"."id" = $1) LIMIT 1 -- PARAMETERS: ["d2f16db8-63be-4b09-a5ea-e04336069df4"]
User {}
query: INSERT INTO "enterprise_users"("enterprisesId", "usersId") VALUES ($1, DEFAULT) -- PARAMETERS: ["d2f16db8-63be-4b09-a5ea-e04336069df4"]
query failed: INSERT INTO "enterprise_users"("enterprisesId", "usersId") VALUES ($1, DEFAULT) -- PARAMETERS: ["d2f16db8-63be-4b09-a5ea-e04336069df4"]
I have the following setup:
enterprise.entity.ts
#Entity('enterprises')
export class Enterprise {
#PrimaryGeneratedColumn('uuid')
id: string;
#CreateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
#UpdateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
updatedAt: Date;
#Column({ unique: true, length: 50 })
name: string;
...
#ManyToMany(() => User, (users) => users.enterprises, { cascade: true })
#JoinTable({ name: 'enterprise_users' })
users: User[];
}
user.entity.ts
#Entity('users')
export class User {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#ManyToMany(() => Enterprise, (enterprise) => enterprise.users)
enterprises: Enterprise[];
}
enterprise.service.ts
#Injectable()
export class EnterpriseService {
constructor(
#InjectRepository(Enterprise)
private enterpriseRepository: Repository<Enterprise>,
) {}
async update(id: string, enterprise: UpdateEnterpriseDto) {
// for testing
const user = new User();
user.name = 'test123';
// triggers error
await this.enterpriseRepository.createQueryBuilder().relation(Enterprise, 'users').of(id).add(user);
return this.enterpriseRepository.save({ id, ...enterprise });
}
}

Data is not written to the database when using #AfterInsert(),#AfterUpdate()

And when using #BeforeInsert(), #BeforeUpdate() are recorded, but I don't need this behavior.
There are Entitys: Driver, Truck, Trip.
Trip has a relationship with the Truck and Driver tables.
Trip has a name_trip field, which should be generated and updated when the associated Driver, Truck data changes.
I'm trying to use Trip
#AfterInsert(), // #AfterUpdate()
Driver:
#Entity()
export class Driver extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
DriverName: string;
}
Truck:
#Entity()
export class Truck extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
AutoData: string;
}
Trip:
#Entity()
export class Trip extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#OneToOne(() => Truck, (truck) => truck.id, { nullable: true, eager: true })
#JoinColumn()
truck: Truck;
#OneToOne(() => Driver, (drive) => drive.DriverName, { nullable: true, eager: true }) // eager: true }
#JoinColumn()
driver: Driver;
#Column({ unique: true, nullable: true })
name_trip: string;
#AfterInsert()
// #BeforeInsert()
#BeforeUpdate()
// #AfterUpdate()
updateNameTrip() {
try {
let driverName = '';
let autoData = '';
console.log('this.driver', this.driver);
if (!this.driver) {
console.log('DriverName = Null');
driverName = Driver not found';
} else {
driverName = this.driver.DriverName;
}
if (!this.truck) {
console.log('AutoData = Null');
autoData = Auto not found';
} else {
autoData = this.truck.AutoData;
}
const name_trip = `${uuidv4()}: ID Trip: ${this.id}, driver:
${driverName}, autoData: ${autoData}`;
this.name_trip = name_trip;
console.log('name_trip', name_trip);
} catch (e) {
console.log('Entity Trip Error:', e);
}
}
}

Value of column in one to one relation using TypeORM + Postgres is null

I'm trying to set up a simple one-to-one relation between an item and item_name. The entity looks as follows:
#Entity('item')
export class ItemEntity {
#PrimaryColumn('integer')
id: number;
#OneToOne(() => ItemNameEntity)
#JoinColumn()
name: ItemNameEntity;
// ... other props
}
item-name.entity
#Entity('item_name')
export class ItemNameEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
en: string;
#Column()
fr: string;
// ... other properties
}
I insert an item using the following payload:
{
id: 26,
name: { en: 'English name', fr: 'French name' },
}
It stores the item as expected, and adds a nameId column. The problem is that it does not insert anything into item_name, and thus the nameId column is null.
What am I missing here?
From this.
You have to set cascade: true on name relation in ItemEntity:
#Entity('item')
export class ItemEntity {
#PrimaryColumn('integer')
id: number;
#OneToOne(() => ItemNameEntity, { cascade: true })
#JoinColumn()
name: ItemNameEntity;
// ... other props
}
Setting cascade: true on ItemEntity tells TypeORM that if a new itemName is "linked" on an item and the item is saved, the new itemName should also be saved to the database.
Example:
const manager = getManager();
const item: ItemEntity = manager.create(ItemEntity, {
id: 26,
name: manager.create(ItemNameEntity, {
en: 'English name',
fr: 'French name'
}),
});
await manager.save(ItemEntity, item);

Insert into table via relation id's

Below I have the Equipt entity it has three columns createdById, tribeId, userId.
I am trying to save a new row using the id's of each entity, and not the entities themselves:
This doesn't work:
let e = connection.getRepository(Equipt);
const check = await e.save({
userId: 1,
tribeId: 1,
createdById: 1,
})
This works:
let e = connection.getRepository(Equipt);
const check = await e.save({
user: user,
tribe: tribe,
createdBy: adminUser,
})
Entity:
import {ManyToOne, RelationId, JoinColumn, Entity} from "typeorm";
import {User} from './User';
import { Base } from "../base";
import { Tribe } from "./Tribe";
#Entity('Equipts')
export class Equipt extends Base {
#ManyToOne(type => User, { nullable: false })
#JoinColumn()
createdBy: User;
#RelationId((Equipt: Equipt) => Equipt.createdBy)
createdById: number;
#ManyToOne(type => Tribe, { nullable: false })
#JoinColumn()
Tribe: Tribe;
#RelationId((Equipt: Equipt) => Equipt.Tribe)
TribeId: number;
#ManyToOne(type => User, { nullable: false })
#JoinColumn()
user: User;
#RelationId((Equipt: Equipt) => Equipt.user)
userId: number;
}
Is there any way to insert using id's without having the pass the entire entity?