[英]Why is syntax different for composite types in postgreSQL INSERT statements and depends on the fact that the data type is named or unnamed?
如果我在表中使用未命名的復合類型,我可以在 INSERT 中使用以下語法:
create table t1(
c1 varchar(2) array[2]
);
CREATE TABLE
create table t2(
c1 varchar(2)
);
CREATE TABLE
create table t3(
c1 int array[2]
);
CREATE TABLE
insert into t1 values ('{"aa", "bb"}');
INSERT 0 1
insert into t2 values ('aa');
INSERT 0 1
insert into t3 values ('{ 1, 2 }');
INSERT 0 1
但是,如果我使用名稱類型,它就不起作用:
CREATE TYPE test1 AS (field varchar(2) ARRAY[2]);
CREATE TYPE
CREATE TYPE test2 AS (field varchar(2) );
CREATE TYPE
CREATE TYPE test3 AS (field int ARRAY[2]);
CREATE TYPE
create table tt1(
c1 test1
);
CREATE TABLE
create table tt2(
c1 test2
);
CREATE TABLE
create table tt3(
c1 test3
);
CREATE TABLE
insert into tt1 values ('{"aa", "bb"}');
psql:tt0.sql:37: ERROR: malformed record literal: "{"aa", "bb"}"
LINE 1: insert into tt1 values ('{"aa", "bb"}');
^
DETAIL: Missing left parenthesis.
insert into tt2 values ('aa');
psql:tt0.sql:38: ERROR: malformed record literal: "aa"
LINE 1: insert into tt2 values ('aa');
^
DETAIL: Missing left parenthesis.
insert into tt3 values ('{ 1, 2 }');
psql:tt0.sql:39: ERROR: malformed record literal: "{ 1, 2 }"
LINE 1: insert into tt3 values ('{ 1, 2 }');
^
DETAIL: Missing left parenthesis.
如果我添加括號它仍然不起作用:
insert into tt1 values (('{"aa", "bb"}'));
ERROR: malformed record literal: "{"aa", "bb"}"
LINE 1: insert into tt1 values (('{"aa", "bb"}'));
^
DETAIL: Missing left parenthesis.
insert into tt2 values (('aa'));
ERROR: malformed record literal: "aa"
LINE 1: insert into tt2 values (('aa'));
^
DETAIL: Missing left parenthesis.
insert into tt3 values (('{ 1, 2 }'));
ERROR: malformed record literal: "{ 1, 2 }"
LINE 1: insert into tt3 values (('{ 1, 2 }'));
^
DETAIL: Missing left parenthesis.
如果我使用 ROW 和 ARRAY 語法,它可以工作:
insert into tt1(c1) values (ROW(ARRAY ['aa', 'bb' ]));
INSERT 0 1
insert into tt2 values (ROW ('aa'));
INSERT 0 1
insert into tt3 values (ROW(ARRAY[ 1, 2 ]));
INSERT 0 1
我用過 PostgreSQL 12.2。
它適用於第一種情況,因為默認情況下存在您的輸入和預期數據類型之間的轉換
前任:
select '1'::int;
int4
------
1
(1 row)
它不適用於自定義類型,因為沒有人編寫演員表。
CREATE TYPE testtype AS (field int);
select '1'::testtype;
ERROR: malformed record literal: "1"
LINE 1: select '1'::testtype;
^
DETAIL: Missing left parenthesis.
如果您在進行轉換之前構造row
,它確實有效,因為您不再直接轉換為類型,而是每個底層組件(在本示例中是單個組件),而這些組件又與自定義類型兼容
select row('1')::testtype;
row
-----
(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.