Dynamic trigger functions

The orders_insert_trigger() function shown above is static: the statements it executes are the same every time. As you might expect from reading the code, the actual execution time will vary based on which partition you are inserting into. Maintaining that trigger code is both monotonous and error prone. It's possible to remove the maintenance chore by just directly computing the partition required:

The execution time of this version is constant and predictable, whereas the static version's runtime will depend on how many comparisons happen before it finds the right partition to insert into. In return for that, and getting rid of the need to keep the more verbose static version up to date, there are a few downsides to this approach. You have to be careful to handle quoting and NULL values here. Because of how the statement is constructed and then executed as text, this will be slower than the static version, at least when the static one has the active partition as the beginning of its comparison list.

A more subtle downside is that dynamically generating these statements will then accept bad data pointing toward partitions that don't exist, without the clear error message the static version gives in that case. Before using this approach on a production system, you should rewrite this example procedure to catch insertion errors, because rows inserted into partitions that don't exist are still going to fail.