如何获取所有参数均转义的原始sql查询字符串?

时间:2020-01-02 12:14:59

标签: typeorm

ix = range(df.Date.min(), df.Date.max()+1)
df_final = (df.groupby(['id', 'Date']).size()
              .unstack(fill_value=0)
              .reindex(ix, axis=1, fill_value=0))

Out[205]:
Date  26009  26010  26011  26012  26013  26014  26015  26016  26017  26018
id
1000      1      0      0      0      0      0      0      1      0      1
1001      0      0      0      0      0      0      0      0      1      0
1002      0      1      0      0      0      0      0      0      0      0
1003      1      0      0      0      0      0      0      0      0      0

张照片: console.log( myRepo .createQueryBuilder() .select('id') .andWhere('uuid = :uuid', { uuid: '170eb26c-19e7-418b-aae8-3308d61ef7d5' }) .getSql() );

如何获取将SELECT id FROM "my_entities" "MyEntity" WHERE uuid = $1替换为参数值的查询字符串?请注意,我不想执行查询-我只需要不带参数的查询字符串。

2 个答案:

答案 0 :(得分:1)

我在此typeorm github问题中找到了解决方案:https://github.com/typeorm/typeorm/issues/556#issuecomment-317459125

async function rawQuery<T = any[]>(query: string, parameters: object = {}, manager?: EntityManager): Promise<T> {
  const conn = manager ? manager.connection : getConnection();
  const [ escapedQuery, escapedParams ] = conn.driver.escapeQueryWithParameters(query, parameters, {});
  return conn.query(escapedQuery, escapedParams);
}

// usage
const comments = await rawQuery<Array<{ id: number, comment: string }>>(
  'select id, comment from comments where post_id in (:...postIds)', { postIds: [1, 2, 3] }
);

答案 1 :(得分:0)

这个答案是针对MySql的,如果您使用的是Postgres,它将略有不同。 您可以使用基础连接驱动程序API来转义参数。

例如

Firebase Database

请注意,根据TypeOrm的新API规范,必须使用空括号,您可以在此处找到有关它的更多信息:https://github.com/typeorm/typeorm/issues/556#issuecomment-556042689