如何防止 Knex 在 PostgreSQL 上插入尾随空格?
How can I prevent Knex from inserting trailing spaces on PostgreSQL?
我正在使用 Node
和包 pg
和 Knex
在 PostgreSQL
上插入数据。这是我的源代码:
var knex = require('knex')({
client: 'pg',
connection: 'postgres://postgres:52Ag98d5@localhost:5433/CRM'
});
var rows = [];
for(var i = 0; i < 20000; i++)
{
rows.push({
name: faker.Name.findName(),
email: faker.Internet.email()
});
}
knex.batchInsert('contact', rows)
.then(() => {
knex.destroy();
});
它工作得很好,除了字符串字段被尾随空格填充。我的意思是...如果一个字段是 character(50)
并且我用 10 个字符填充它,它将在末尾插入 40 个空格。请参阅 pgAdmin
上的突出显示:
我不知道这是谁的错。我不知道这是因为 Knex
还是因为 Node pg
驱动程序。
知道如何防止这种行为吗?
原因很简单。 Character(50)
是定长数据类型。
╔════════════════════════╦════════════════════════════╗
║ Name ║ Description ║
╠════════════════════════╬════════════════════════════╣
║ character(n), char(n) ║ fixed-length, blank padded ║
╚════════════════════════╩════════════════════════════╝
If the string to be stored is shorter than the declared length,
values of type character will be space-padded; values of type
character varying will simply store the shorter string.
解决方案:
改用VARCHAR(50)
。
我正在使用 Node
和包 pg
和 Knex
在 PostgreSQL
上插入数据。这是我的源代码:
var knex = require('knex')({
client: 'pg',
connection: 'postgres://postgres:52Ag98d5@localhost:5433/CRM'
});
var rows = [];
for(var i = 0; i < 20000; i++)
{
rows.push({
name: faker.Name.findName(),
email: faker.Internet.email()
});
}
knex.batchInsert('contact', rows)
.then(() => {
knex.destroy();
});
它工作得很好,除了字符串字段被尾随空格填充。我的意思是...如果一个字段是 character(50)
并且我用 10 个字符填充它,它将在末尾插入 40 个空格。请参阅 pgAdmin
上的突出显示:
我不知道这是谁的错。我不知道这是因为 Knex
还是因为 Node pg
驱动程序。
知道如何防止这种行为吗?
原因很简单。 Character(50)
是定长数据类型。
╔════════════════════════╦════════════════════════════╗ ║ Name ║ Description ║ ╠════════════════════════╬════════════════════════════╣ ║ character(n), char(n) ║ fixed-length, blank padded ║ ╚════════════════════════╩════════════════════════════╝
If the string to be stored is shorter than the declared length, values of type character will be space-padded; values of type character varying will simply store the shorter string.
解决方案:
改用VARCHAR(50)
。