How to get the dimensionality of an ARRAY column?

后端 未结 2 1874
无人及你
无人及你 2021-01-26 05:34

I\'m working on a project that collects information about your schema from the database directly. I can get the data_type of the column using information_sche

2条回答
  •  忘掉有多难
    2021-01-26 06:04

    Multidimensional arrays support in Postgres is very specific. Multidimensional array types do not exist. If you declare an array as multidimensional, Postgres casts it automatically to a simple array type:

    create table test(a integer[][]);
    \d test
    
          Table "public.test"
     Column |   Type    | Modifiers 
    --------+-----------+-----------
     a      | integer[] |     
    

    You can store arrays of different dimensions in a column of an array type:

    insert into test values
        (array[1,2]),
        (array[array[1,2], array[3,4]]);
    
    select a, a[1] a1, a[2] a2, a[1][1] a11, a[2][2] a22
    from test;
    
           a       | a1 | a2 | a11 | a22 
    ---------------+----+----+-----+-----
     {1,2}         |  1 |  2 |     |    
     {{1,2},{3,4}} |    |    |   1 |   4
    (2 rows)
    

    This is a key difference between Postgres and programming languages like C, python etc. The feature has its advantages and disadvantages but usually causes various problems for novices.

    You can find the number of dimensions in the system catalog pg_attribute:

    select attname, typname, attndims
    from pg_class c
    join pg_attribute a on c.oid = attrelid
    join pg_type t on t.oid = atttypid
    where relname = 'test'
    and attnum > 0;
    
     attname | typname | attndims 
    ---------+---------+----------
     a       | _int4   |        2
    (1 row)
    

    It is not clear whether you can rely on this number, as for the documentation:

    attndims - Number of dimensions, if the column is an array type; otherwise 0. (Presently, the number of dimensions of an array is not enforced, so any nonzero value effectively means "it's an array".)

提交回复
热议问题