【发布时间】:2021-12-04 23:41:26
【问题描述】:
我是 Postgresql 的新手,每天都在学习新事物。所以我有这个博客项目,我想在其中使用 PostgreSQL 作为数据库。但我有点卡在最基本的插入查询中,这会引发错误。我有三张桌子,posts、authors 和 categories。我想我可以正确地创建表格,但是当我尝试插入数据时,我得到了这个错误:
error: syntax error at or near
length: 95,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '122',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1180',
routine: 'scanner_yyerror'
现在我不知道问题出在哪里,而且 Postgres 的错误也不是那么具体。
谁能告诉我哪里出错了?
这是表格:
const createInitialTables = `
CREATE TABLE authors (
id UUID NOT NULL,
author_name VARCHAR(100) NOT NULL UNIQUE CHECK (author_name <> ''),
author_slug VARCHAR(100) NOT NULL UNIQUE CHECK (author_slug <> ''),
PRIMARY KEY (id)
);
CREATE TABLE posts (
id UUID NOT NULL,
post VARCHAR(500) NOT NULL CHECK (post<> ''),
post_slug VARCHAR(500) NOT NULL CHECK (post_slug <> ''),
author_id UUID NOT NULL,
PRIMARY KEY (id),
CONSTRAINT fk_authors FOREIGN KEY(author_id) REFERENCES authors(id)
);
CREATE TABLE categories (
id UUID NOT NULL,
category_name VARCHAR(50) NOT NULL CHECK (category_name <> ''),
category_slug VARCHAR(50) NOT NULL CHECK (category_slug <> ''),
post_id UUID NOT NULL,
PRIMARY KEY (id),
CONSTRAINT fk_posts FOREIGN KEY(post_id) REFERENCES posts(id)
);
`;
这是我进行插入查询的异步函数:
const insertAuthor = async() => {
try {
const data = await fs.readFile( path.join( __dirname + '../../data/data.json' ) );
const parsedData = JSON.parse( data.toString() );
const authorID = short.generate();
const authorName = parsedData[ 0 ].author;
const authorSlug = slugify( parsedData[ 0 ].author, {
strict: true,
lower: true
} );
const insertData = `
INSERT INTO authors (id, author_name, author_slug)
VALUES
(${authorID}, ${authorName}, ${authorSlug});
`;
await pool.query( insertData );
console.log( 'Data inserted successfully!' );
} catch ( e ) {
console.log( e );
}
};
insertAuthor();
更新---------------------------------------
这是 Postgres 日志文件的样子:
2021-10-18 01:23:16.885 +06 [5964] ERROR: syntax error at or near "Paton" at character 122
2021-10-18 01:23:16.885 +06 [5964] STATEMENT:
INSERT INTO authors (id, author_name, author_slug)
VALUES
(an3cxZh8ZD3tdtqG4wuwPR, Alan Paton, alan-paton);
【问题讨论】:
-
Postgres 错误消息往往非常具体。看起来你的司机正在编辑细节。查看 Postgres 日志,它应该包含您需要的信息。如果您不理解它,请将错误消息复制并粘贴为文本以更新您的问题。
-
@AdrianKlaver 我已经用日志文件数据更新了 OP。
标签: sql node.js postgresql express