没有数组数据的unnest
工作正常。我想插入一个数组列。我的输入是这样的:[[1, 2], [1]]
create table test_array
(
arr int[],
info text[]
);
CREATE OR REPLACE FUNCTION unnest_2d_1d(anyarray)
RETURNS SETOF anyarray AS
$func$
SELECT array_agg($1[d1][d2])
FROM generate_subscripts($1,1) d1
, generate_subscripts($1,2) d2
GROUP BY d1
ORDER BY d1
$func$ LANGUAGE sql IMMUTABLE;
insert into test_array(
arr)
values (
unnest_2d_1d(array[[1,2], [3,4]]::int[])); -- work fine
insert into test_array(
arr)
values (
unnest_2d_1d(array[[1,2], [3]]::int[])); -- will failed
失败的错误是:
ERROR: multidimensional arrays must have array expressions with matching dimensions
unnest_2d_1d
来自Unnest 数组的一级
虽然所有这些函数都不能支持不同长度的数组。
array_dims 发生了另一个相同的错误:
postgres=# SELECT array_dims(ARRAY[[1,2,3], [4,5,6], [7,8]])
postgres-# ;
ERROR: multidimensional arrays must have array expressions with matching dimensions
我需要做什么unnest_2d_1d
才能使失败的人成功?
为什么我必须使用 unnest。因为asyncpg
execute_many
丢弃返回值。所以我需要使用一个 sql 来插入数据。但是数组列就像一个具有不同长度的暗淡。
---- 添加一些python和asyncpg
我发现了一个与此问题相关的 github 问题, https://github.com/brianc/node-postgres/issues/1644尝试使用 python
当尝试这个:
async def h():
async with misc.pg_pool.acquire() as connection:
stmt = await connection.prepare(f"""
insert into test_array(info) select (info::text[]) from unnest($1::text[])
AS t(info)
""")
await stmt.fetch([["sd", "dg"]])
明白啦
InvalidTextRepresentationError: malformed array literal: "sd"
DETAIL: Array value must start with "{" or dimension information.