Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show generated SQL / raw SQL in TypeORM queryBuilder

Tags:

sql

typeorm

I developed typeorm querybuilder. For the purpose of debugging, I'd like to show the generated SQL query.

I tested printSql() method, but it didn't show any SQL query.

const Result = await this.attendanceRepository
  .createQueryBuilder("attendance")
  .innerJoin("attendance.child", "child")
  .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
  .where("attendance.id= :id", { id: id })
  .printSql()
  .getOne()

console.log(Result);

It returned the following:

Attendance { childId: 4, child: Child { class: 'S' } }

My desired result is to get the generated SQL query.

Is there any wrong point? Is there any good way to get the SQL query?

like image 216
Heisenberg Avatar asked Oct 18 '20 11:10

Heisenberg


People also ask

What is raw SQL query?

Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query. Raw SQL queries can return regular entity types or keyless entity types that are part of your model.

How do I join TypeORM?

TypeORM has a method called innerJoinAndSelect . You use plain innerJoin . That is why user table is not selected from. Once you change that part to innerJoinAndSelect , watch table will be selected from.


2 Answers

.getQuery() or .getSql()

const sql1 = await this.attendanceRepository
    .createQueryBuilder("attendance")
    .innerJoin("attendance.child", "child")
    .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
    .where("attendance.id= :id", { id: id })
    .getQuery();
console.log(sql1);
const sql2 = await this.attendanceRepository
    .createQueryBuilder("attendance")
    .innerJoin("attendance.child", "child")
    .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
    .where("attendance.id= :id", { id: id })
    .getSql();
console.log(sql2);    
like image 127
Art Olshansky Avatar answered Oct 06 '22 15:10

Art Olshansky


printSql can also be used, but it will only print when logging is enabled.


@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...options
      logging: true
    }),
  ],
})

await this.attendanceRepository
    .createQueryBuilder("attendance")
    .innerJoin("attendance.child", "child")
    .select(["attendance.childId","child.class","CONCAT(child.firstName, child.lastName)"])
    .where("attendance.id= :id", { id: id })
    .printSql();
like image 26
iAviator Avatar answered Oct 06 '22 14:10

iAviator