Rails PostgreSql 存储多维数组

Rails PostgreSql store multidimensional array

是否可以在列中存储多维数组。

我已经尝试了以下操作并收到了以下来自创建记录列的错误。

migration_file.rb

create_table :balance_sheets_details do |t|
  t.string :headers, array: true, default: []
  t.string :records, array: true, default: [[]]
  t.timestamps
end

出现错误

PG::InvalidTextRepresentation: ERROR: malformed array literal: "{{}}"

来自数组的文档(添加了重点):

The syntax for CREATE TABLE allows the exact size of arrays to be specified, for example:

CREATE TABLE tictactoe (
    squares   integer[3][3]
);

However, the current implementation ignores any supplied array size limits, i.e., the behavior is the same as for arrays of unspecified length.

The current implementation does not enforce the declared number of dimensions either. Arrays of a particular element type are all considered to be of the same type, regardless of size or number of dimensions. So, declaring the array size or number of dimensions in CREATE TABLE is simply documentation; it does not affect run-time behavior.

因此,实际上并没有多维数组类型。要解决您的问题,只需将默认值从 {{}} 更改为 {}

这意味着 varchar[][]varchar[] 的类型相同:

db=# select pg_typeof(a), pg_typeof(b) from (values ('{{hello},{world}}'::varchar[][], '{foo}'::varchar[])) x(a, b);
      pg_typeof      |      pg_typeof
---------------------+---------------------
 character varying[] | character varying[]
(1 row)

不过,您仍然可以存储多维数据。

一维和二维数组不一样:

db=# select '{{foo}}'::varchar[] = '{foo}'::varchar[];
 ?column?
----------
 f
(1 row)