   IF has_usable_primary_key THEN
 
     EXECUTE Format('SELECT max(%s) FROM %s',
-            primary_key_name, copyname)
+            const.pkey, copyname)
        INTO destseqmax;
 
     IF FOUND AND destseqmax IS NOT NULL THEN
-      EXECUTE Format('SELECT setval(''%s'', %s)', destseq, destseqmax);
+      PERFORM _CDB_SQL(Format('SELECT setval(''%s'', %s)', destseq, destseqmax), '_CDB_Rewrite_Table');
     END IF;
 
   END IF;
 
   -- Make the primary key use the sequence as its default value
   sql := Format('ALTER TABLE %s ALTER COLUMN %I SET DEFAULT nextval(''%s'')', 
-          copyname, primary_key_name, destseq);
-  RAISE DEBUG '_CDB_Rewrite_Table: %', sql;
-  EXECUTE sql;
+          copyname, const.pkey, destseq);
+  PERFORM _CDB_SQL(sql, '_CDB_Rewrite_Table');
 
   -- Make the sequence owned by the table, so when the table drops, 
   -- the sequence does too
-  sql := Format('ALTER SEQUENCE %s OWNED BY %s.%s', destseq, copyname, primary_key_name);
-  RAISE DEBUG '_CDB_Rewrite_Table: %', sql;
-  EXECUTE sql;
+  sql := Format('ALTER SEQUENCE %s OWNED BY %s.%s', destseq, copyname, const.pkey);
+  PERFORM _CDB_SQL(sql,'_CDB_Rewrite_Table');
   
   -- We just made a copy, so we can drop the original now
   sql := Format('DROP TABLE %s', reloid::text);
-  RAISE DEBUG '_CDB_Rewrite_Table: %', sql;
-  EXECUTE sql;
+  PERFORM _CDB_SQL(sql, '_CDB_Rewrite_Table');
   
   -- If we used a temporary destination table
   -- we can now rename it into place
   IF destschema = relschema THEN
     sql := Format('ALTER TABLE %s RENAME TO %s', copyname, destname);
-    RAISE DEBUG '_CDB_Rewrite_Table: %', sql;
-    EXECUTE sql;
+    PERFORM _CDB_SQL(sql, '_CDB_Rewrite_Table');
   END IF;
 
   RETURN true;

-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



-- Find a unique relation name in the given schema, starting from the 
-- template given. If the template is already unique, just return it; 

  -- a destination schema, so do that now
  IF NOT rewrite AND destschema != relschema THEN
    
    RAISE DEBUG 'CDB(CDB_CartodbfyTable2): perfect table needs to be moved to schema (%)', destschema;
    EXECUTE Format('ALTER TABLE %s SET SCHEMA %s', reloid::text, destschema);

  -- Don't move anything, just make sure our destination information is set right
  ELSIF NOT rewrite AND destschema = relschema THEN

    RAISE DEBUG 'CDB(CDB_CartodbfyTable2): perfect table in the perfect place';
  
  -- We must rewrite, so here we go...
  ELSIF rewrite THEN

    SELECT _CDB_Rewrite_Table(reloid, destschema, has_usable_primary_key, has_usable_geoms)
    INTO STRICT rewrite_success;
    
    IF NOT rewrite_success THEN
      PERFORM _CDB_Error('rewriting table', 'CDB_CartodbfyTable2');
    END IF;
      
  END IF;
