Try to cast TEXT typed updated_at and created_at if present

If the cast fails we'll still rename those fields and create
new ones. See #27 (cartodb_id is still not done)
This commit is contained in:
Sandro Santilli 2014-05-22 13:10:42 +02:00
parent 75a40c9b63
commit 134d2d29b6
3 changed files with 32 additions and 21 deletions

View File

@ -163,27 +163,26 @@ BEGIN
IF had_column THEN
-- Check data type is a TIMESTAMP WITH TIMEZONE
SELECT t.typname, t.oid, a.attnotnull FROM pg_type t, pg_attribute a
WHERE a.atttypid = t.oid AND a.attrelid = reloid AND NOT a.attisdropped
AND a.attname = rec.cname
INTO STRICT rec2;
IF rec2.oid NOT IN (1184) THEN -- timestamptz {
RAISE NOTICE 'Existing % field is of invalid type % (need timestamptz), renaming', rec.cname, rec2.typname;
ELSE -- }{
sql := 'ALTER TABLE ' || reloid::text || ' ALTER ' || rec.cname
|| ' SET NOT NULL, ALTER ' || rec.cname || ' SET DEFAULT now()';
BEGIN
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXIT column_setup;
EXCEPTION
WHEN not_null_violation THEN
RAISE NOTICE '%, renaming', SQLERRM;
WHEN others THEN
RAISE EXCEPTION 'Got % (%)', SQLERRM, SQLSTATE;
END;
END IF; -- }
-- Ensure data type is a TIMESTAMP WITH TIMEZONE
sql := 'ALTER TABLE ' || reloid::text
|| ' ALTER ' || rec.cname
|| ' SET NOT NULL,'
|| ' ALTER ' || rec.cname
|| ' TYPE timestamptz USING ' || rec.cname || '::timestamptz,'
|| ' ALTER ' || rec.cname
|| ' SET DEFAULT now()';
BEGIN
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXIT column_setup;
EXCEPTION
WHEN not_null_violation THEN -- failed not-null
RAISE NOTICE '%, renaming', SQLERRM;
WHEN cannot_coerce THEN -- failed cast
RAISE NOTICE '%, renaming', SQLERRM;
WHEN others THEN
RAISE EXCEPTION 'Got % (%)', SQLERRM, SQLSTATE;
END;
-- invalid column, need rename and re-create it
i := 0;

View File

@ -170,6 +170,14 @@ SELECT CDB_CartodbfyTableCheck('t', 'trigger-protected the_geom');
SELECT 'extent',ST_Extent(ST_SnapToGrid(the_geom,0.1)) FROM t;
DROP TABLE t;
-- table with existing updated_at and created_at fields ot type text
CREATE TABLE t AS SELECT NOW()::text as created_at,
NOW()::text as updated_at,
NOW() as reftime;
SELECT CDB_CartodbfyTableCheck('t', 'text timestamps');
SELECT reftime-created_at, reftime-updated_at FROM t;
DROP TABLE t;
-- TODO: table with existing custom-triggered the_geom
DROP FUNCTION CDB_CartodbfyTableCheck(regclass, text);

View File

@ -25,5 +25,9 @@ CREATE TRIGGER
trigger-protected the_geom cartodbfied fine
extent|BOX(1 1,2 2)
DROP TABLE
SELECT 1
text timestamps cartodbfied fine
@ 0|@ 0
DROP TABLE
DROP FUNCTION
DROP FUNCTION