postgresql 修改字段长度

postgresql 9.0以后更改字段长度会重写表,如果表比较大,那么表会加锁,需要很长时间,这里介绍一种方法通过修改pg_attribute.atttypmod字段修改长度,不需要重写表

举例:

新建表,插入超出字段长度的值报错

postgres=# create table tb1 (a int, b varchar(2));
CREATE TABLE

postgres=# insert into tb1 values(1,'ashdkhasdjsadhkj');
ERROR:  value too long for type character varying(2)
postgres=# select * from pg_relation_filepath('tb1');
 pg_relation_filepath
----------------------
 base/12699/32786

可以看到这里atttypemod为6,变长类型头信息占去4个字节,这里6-4=2就是我们字段的长度

postgres=# \x
Expanded display is on.
postgres=# select * from pg_attribute where attrelid='tb1'::regclass and attname='b';
-[ RECORD 1 ]-+------
attrelid      | 32786
attname       | b
atttypid      | 1043
attstattarget | -1
attlen        | -1
attnum        | 2
attndims      | 0
attcacheoff   | -1
atttypmod     | 6
attbyval      | f
attstorage    | x
attalign      | i
attnotnull    | f
atthasdef     | f
attisdropped  | f
attislocal    | t
attinhcount   | 0
attcollation  | 100
attacl        |
attoptions    |

修改atttypemod为24,那么字段长度为20

postgres=# update pg_attribute set atttypmod=24 where attrelid='tb1'::regclass and attname='b';
UPDATE 1
postgres=# select * from pg_attribute where attrelid='tb1'::regclass and attname='b';
-[ RECORD 1 ]-+------
attrelid      | 32786
attname       | b
atttypid      | 1043
attstattarget | -1
attlen        | -1
attnum        | 2
attndims      | 0
attcacheoff   | -1
atttypmod     | 24
attbyval      | f
attstorage    | x
attalign      | i
attnotnull    | f
atthasdef     | f
attisdropped  | f
attislocal    | t
attinhcount   | 0
attcollation  | 100
attacl        |
attoptions    |

再次插入值,没有报错,字段值变为20,所在的数据文件路径没有改变

postgres=# insert into tb1 values(1,'ashdkhasdjsadhkj');
INSERT 0 1
postgres=# \d tb1
             Table "public.tb1"
 Column |         Type          | Modifiers
--------+-----------------------+-----------
 a      | integer               |
 b      | character varying(20) |

postgres=#  select * from pg_relation_filepath('tb1');
-[ RECORD 1 ]--------+-----------------
pg_relation_filepath | base/12699/32786

 

你可能感兴趣的:(#,postgreSQL)