是否允许多次重复使用 pg QueryFile

Is it allowed to reuse pg QueryFile multiple times

我可以重复使用类型 QueryFile of pg-promise 吗?

例如

const pgp = require(`pg-promise`)(options);
const QueryFile = pgp.QueryFile;

const db = pgp(config.DB);
const query =  new QueryFile('queryPath/some.sql', { minify: true });

// running sql query
db.any(query, []);
db.any(query, []);
db.any(query, []);
db.any(query, []);    
db.any(query, []);

目前,每次我想执行它时,我都在创建新的 QueryFile。 例如

db.any(new QueryFile('queryPath/some.sql', { minify: true }), []);
db.any(new QueryFile('queryPath/some.sql', { minify: true }), []);
db.any(new QueryFile('queryPath/some.sql', { minify: true }), []);
db.any(new QueryFile('queryPath/some.sql', { minify: true }), []);

如果我多次重复使用同一个查询,有什么缺点吗?

Is it allowed to reuse pg QueryFile multiple times?

不,不允许,坚持!


输入QueryFile represents a virtual link to the file, and its use offers many advantages - as documented.

与此问题相关的两个关键特征是:

  • Parsing and minifying SQL (options minify/compress), for early error detection and compact queries.
  • Changes in external SQL can be automatically re-loaded (option debug), without restarting the app.

如果提供选项 minify/compress,第一个加载文件,解析并缩小它。这需要时间和 IO,并且不应多次执行,因为无论如何都没有意义。

第二点允许它用作虚拟 link,可以在开发模式(选项 debug)下自动检测任何文件更改,并自动重新加载和准备文件。在开发环境中,此功能是无价的,可防止您在外部 SQL 文件更改时重新加载应用程序。


所以缺点是:

  • 创建不必要的 IO(额外的文件读取 + SQL 解析和缩小)。在您的示例中,情况更糟 - 您每次执行查询时都在这样做。
  • 丢失类型 QueryFile 设计的关键功能(无法自动重新加载)

并且当您为同一个文件重新创建 QueryFile 类型时,您正在使用该类型来达到最有用的目的。这就是为什么它会向您报告警告 Creating a duplicate QueryFile object for the same file.

您应该为 SQL 个文件设置单独的结构,如 pg-promise-demo, see here.

中所示