Last week, we were assisting a client who needed to resolve an issue related to partitioned tables.

Often, a table can include dozens or even hundreds of partitions. Unfortunately, some object-level parameters for tuning (like storage_parameter) cannot be modified from the parent table and must be manipulated directly through the child table. As a result, we came up with the idea of leveraging PostgreSQLl’s metacommand \gexec to speed up things. The \gexec approach can be used to automate and speed up several tasks, and it does not restrict itself to the previously mentioned scenario.

PostgreSQL includes some fantastic functions, such as \watch, \copy, and \crosstabview, among many others. You can learn about them from the official PostgreSQL documentation at https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-META-COMMAND-GEXEC

This time, we would like to share a helpful experience using \gexec, which can significantly accelerate some repetitive tasks.

\gexec in action

Consider the following scenario (and unleash your mind to the countless possibilities it applies).

1. You have a partitioned table:

2. Now, you need to perform changes over each table’s partition (or even database table, or database index, whatever), and the candidate’s list is too long. E.g., You want to perform a given task over the candidate tables, and you also want to avoid autovacuum running over the candidate tables (but you want to disable autovacuum at the database level).
All your tables have autovacuum enabled at table level (which is great)

3. Using custom queries and \gexec, you can modify all tables in a single shot as follows.

This time, we disabled autovacuum at the table level for every partition that matches the conditions in our custom query. Moreover, we added a statement_timeout value to add an extra security layer, avoiding long-term locks.

4. Then we verify the success of our task:

You can revert the operation by just modifying the custom query and inserting “SET (autovacuum_enabled = true);” instead of “SET (autovacuum_enabled = false);” This way, you can grant or revoke a long list of privileges, perform several DDLs in a shot, add a long list of tables on a given publication, and do many other things. The actual scope of this is only limited to your SQL skills and imagination in taking advantage of the pg_catalog and building your custom queries that match the required conditions.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments