Is it possible to store a multidimensional array in a column.
I have tried the following and received the error below coming from creating the records column.
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
Raised error
PG::InvalidTextRepresentation: ERROR: malformed array literal: "{{}}"
From the docs on arrays (emphasis added):
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.
Thus, there isn't really a multidimensional array type. To fix your issue, just change the default from {{}}
to {}
.
This means a varchar[][]
is the same type as a 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)
You will still be able to store multidimensional data, though.
A one and two dimensional array are not the same:
db=# select '{{foo}}'::varchar[] = '{foo}'::varchar[];
?column?
----------
f
(1 row)