列类型不一致:字符变化和字符变化(30)

Column type inconsistency: character varying and character varying(30)

对于我的应用程序,我创建了一个 SQL 文件补丁以将列 user_name 添加到现有的 table :

CREATE OR REPLACE FUNCTION add_col(
  _tbl VARCHAR,  -- Table                                                                                                                                                                                      
  _col VARCHAR,  -- Column to add                                                                                                                                                                              
  _type regtype -- Type of that column                                                                                                                                                                         
) RETURNS BOOL AS $$
BEGIN
  -- Returns true if column has been added; false otherwise.                                                                                                                                                   
  IF EXISTS (SELECT DISTINCT column_name
             FROM information_schema.columns
             WHERE table_schema LIKE current_schema and table_name LIKE _tbl and column_name LIKE _col
            )
  THEN
     -- Column already exists in that table of that schema: do nothing.                                                                                                                                        
     RETURN false;
  END IF;

  -- Add column                                                                                                                                                                                                
  EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || _col || ' ' || _type;

  RETURN true;
END; $$ language 'plpgsql';

SELECT add_col('ack_event', 'user_name', 'VARCHAR(30)');

如果我执行它并执行 SELECT 来显示 ack_event 内容,我们会看到添加了列 user_name,但“ 字符变化" 输入:

| id     | user_name         |
| bigint | character varying |
|--------+-------------------+
|        |                   |

但是如果ack_event列是直接用user_name列创建的,user_name的类型是“character_varying(30)" :

CREATE TABLE ACK_EVENT(
    ID int8 not null,
    USER_NAME VARCHAR(30),

     CONSTRAINT PK_ACK_EVENT PRIMARY KEY (ID)
);

结果:

| id     | user_name             |
| bigint | character varying(30) |
|--------+-----------------------+
|        |                       |

为什么会出现这种不一致?有没有办法纠正它并在两种情况下都改变字符 (30)?

这可能会引入一些验证问题,但如果您将 _type 的数据类型从 regtype 更改为文本数据类型,我认为它会更直接地输入您的 DDL:

CREATE OR REPLACE FUNCTION add_col(
  _tbl VARCHAR,
  _col VARCHAR,
  _type text -- this was previously regtype
) RETURNS varchar AS $$