SupabaseAngelico de los ReyesExplainer
What are PostgreSQL Templates?
Summary
PostgreSQL bases every new database creation on an existing template database within the cluster, defaulting to template1. While administrators can directly modify template1 with tables, data, extensions, or procedural languages, altering it risks breaking future database creation commands if mistakes happen. Setting an existing database as a custom template using the ALTER DATABASE command allows users with the CREATEDB privilege to instantiate customized databases without polluting system templates. Any database creation from a template requires zero active connections on that template at execution time, making pg_dump the preferred tool for replicating active production environments. The immutable template0 system database serves as a fallback to recreate corrupted templates, restore clean dumps, or initialize databases with alternative character encodings.
Context
Directly modifying the default template1 database to pre-configure new databases risks breaking the CREATE DATABASE command if errors occur during manual modifications or database recreation.
Approach / What changed
Configuring custom template databases with ALTER DATABASE template_db_name WITH is_template TRUE isolates custom schemas across multiple use cases, while keeping template0 as an immutable fallback for recovery, clean dumps, and custom encodings.
Takeaways
Setting is_template to TRUE on an existing database allows any role with the CREATEDB privilege to use it as a template, whereas unflagged databases restrict template usage to superusers or owners.
The CREATE DATABASE command fails immediately if any active connections exist on the target template database at the start of execution, making pg_dump preferable for live database replication.
The pristine template0 database must remain unmodified after cluster initialization to enable recovery of corrupted template1 databases and allow database creation with alternative encodings such as SQL_ASCII.
Source and freshness
- Source
- supabase.com
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.