Reputation: 591
For my application, I created a SQL file patch to add a column user_name to an existant 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)');
If I execute that and do a SELECT to display ack_event content, we see that the column user_name is added but with the "character varying" type:
| id | user_name |
| bigint | character varying |
|--------+-------------------+
| | |
However if the ack_event column is created directly with the user_name column, the type of user_name is "character_varying(30)" :
CREATE TABLE ACK_EVENT(
ID int8 not null,
USER_NAME VARCHAR(30),
CONSTRAINT PK_ACK_EVENT PRIMARY KEY (ID)
);
Result:
| id | user_name |
| bigint | character varying(30) |
|--------+-----------------------+
| | |
Why is there this inconsistency ? Is there a way to correct it and have character varying (30) in both cases ?
Upvotes: 1
Views: 384
Reputation: 16377
This may introduce some validation issues, but if you change the datatype of _type from regtype
to a text datatype, I think it will input your DDL much more literally:
CREATE OR REPLACE FUNCTION add_col(
_tbl VARCHAR,
_col VARCHAR,
_type text -- this was previously regtype
) RETURNS varchar AS $$
Upvotes: 1