Handle CREATE TABLE IF NOT EXISTS correctly
authorPavan Deolasee <[email protected]>
Thu, 18 Jun 2015 11:54:22 +0000 (17:24 +0530)
committerPavan Deolasee <[email protected]>
Thu, 18 Jun 2015 11:54:22 +0000 (17:24 +0530)
In XL we rewrite CTAS as CREATE TABLE followed by INSERT INTO. If the target
table already exists, we now issue a notice for the first step and skip the
second step completely. The ruleutils also now handles INE correctly for CTAS

src/backend/rewrite/rewriteHandler.c
src/backend/utils/adt/ruleutils.c

index fa1d07777e6f4ae4100bf92572cd0a2216c7098d..48fcd51836f227ad63f870efe36b856b604cd640 100644 (file)
@@ -3858,10 +3858,27 @@ QueryRewriteCTAS(Query *parsetree)
 
        relation = stmt->into->rel;
 
+       if (stmt->if_not_exists)
+       {
+               Oid                     nspid;
+
+               nspid = RangeVarGetCreationNamespace(stmt->into->rel);
+
+               if (get_relname_relid(stmt->into->rel->relname, nspid))
+               {
+                       ereport(NOTICE,
+                                       (errcode(ERRCODE_DUPLICATE_TABLE),
+                                        errmsg("relation \"%s\" already exists, skipping",
+                                                       stmt->into->rel->relname)));
+                       return NIL;
+               }
+       }
+
        /* Start building a CreateStmt for creating the target table */
        create_stmt = makeNode(CreateStmt);
        create_stmt->relation = relation;
        create_stmt->islocal = stmt->islocal;
+       create_stmt->if_not_exists = stmt->if_not_exists;
        into = stmt->into;
 
        /* Obtain the target list of new table */
index 83c51694309aaa659b41076ffae5cea61e12bacb..41e0b35d58f9e54bf7c6cefc11b5c408eb71f65e 100644 (file)
@@ -6225,10 +6225,11 @@ get_utility_query_def(Query *query, deparse_context *context)
                bool            istemp = (relation->relpersistence == RELPERSISTENCE_TEMP);
                bool            isunlogged = (relation->relpersistence == RELPERSISTENCE_UNLOGGED);
 
-               appendStringInfo(buf, "CREATE %s %s %s TABLE ",
+               appendStringInfo(buf, "CREATE %s %s %s TABLE %s ",
                                stmt->islocal ? "LOCAL" : "",
                                istemp ? "TEMP" : "",
-                               isunlogged ? "UNLOGGED" : "");
+                               isunlogged ? "UNLOGGED" : "",
+                               stmt->if_not_exists ? "IF NOT EXISTS " : "");
 
                if (!istemp && relation->schemaname && relation->schemaname[0])
                        appendStringInfo(buf, "%s.", relation->schemaname);