1

To be clear, I want to know what is the mechanism that is used to populate the default value not the SQL syntax needed to create the default value constraint on the table.

Does Postgres use some kind of trigger that updates the default value if it is missing or something else?. I couldn't find an explanation on the official website.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
shaffooo
  • 1,478
  • 23
  • 28
  • Unless this is just curiosity about PG internals, I think you will get a better response stating _why_ you want to know. – Andrew Lazarus Jan 30 '19 at 19:15
  • Yeah just curious to get a high level understanding of when and how that is done. – shaffooo Jan 30 '19 at 19:23
  • You could browse the source code. (remember: PG is open source) – wildplasser Jan 30 '19 at 20:33
  • That is exactly what I wanted to avoid- don't know much of C. I thought somebody would know and willing to help, hence posted it on stackoverflow. Not interested in too much detail just a high level understanding which google failed to help with. – shaffooo Jan 30 '19 at 20:39
  • 1
    The "high level" picture is that whenever you ask the server to execute a statement, it does it by running some code, and when you execute an `INSERT` statement, some of that code will fill in the missing columns with defaults. There are no triggers involved, or anything else that you might call a "mechanism"; it's just written that way. – Nick Barnes Jan 30 '19 at 23:16

1 Answers1

2

This happens in the rewriteTargetListIU function in src/backend/rewrite/rewriteHandler.c. The comment says it all:

/*
 * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
 *
 * This has the following responsibilities:
 *
 * 1. For an INSERT, add tlist entries to compute default values for any
 * attributes that have defaults and are not assigned to in the given tlist.
 * (We do not insert anything for default-less attributes, however.  The
 * planner will later insert NULLs for them, but there's no reason to slow
 * down rewriter processing with extra tlist nodes.)  Also, for both INSERT
 * and UPDATE, replace explicit DEFAULT specifications with column default
 * expressions.

So this happens during query rewrite, which is the step between parsing the SQL string and optimizing it.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263