SQL 注释

你可以使用 .comment() 方法为任何查询添加自定义标签。这些标签会以 sqlcommenter 格式的注释附加在每条查询的末尾,帮助你为查询跟踪、调试和数据库流量控制附加元数据。

.comment() 方法可用于 selectinsertupdatedelete 查询。

字符串注释

你可以传入一个原始字符串作为注释:

db.select().from(users).comment("my_first_tag");
select "id", "name" from "users" /*my_first_tag*/
db.select().from(users).comment("key='val'");
select "id", "name" from "users" /*key='val'*/

对象注释

你可以传入一个包含键值对的对象,用于结构化标签:

db.select().from(users).comment({ priority: 'high', category: 'analytics' });
select "id", "name" from "users" /*priority='high',category='analytics'*/
db.select().from(users).comment({ trace: true, route: '/api/users', version: 2 });
select "id", "name" from "users" /*route='%2Fapi%2Fusers',trace='true',version='2'*/

与 insert、update、delete 一起使用

db.insert(users).values({ name: 'Dan' }).comment({ operation: 'seed' });
insert into "users" ("name") values ('Dan') /*operation='seed'*/
db.update(users).set({ name: 'Dan' }).where(eq(users.id, 1)).comment({ operation: 'update' });
update "users" set "name" = 'Dan' where "users"."id" = 1 /*operation='update'*/
db.delete(users).where(eq(users.id, 1)).comment({ operation: 'cleanup' });
delete from "users" where "users"."id" = 1 /*operation='cleanup'*/

限制

你不能在语句已经 prepared 之后再使用 .comment()。Prepared statement 只会编译一次 SQL 查询,并在多次执行中复用,因此查询字符串在准备阶段就已固定,之后无法再修改——包括追加注释:

// can't be used
const p = db.select().from().prepare();
// ❌
p.comment({ key: 'val' }).execute();

相反,应在准备语句之前先添加注释:

// ✅
db.select().from(users).comment({ key: 'val' }).prepare();