@@ -103,42 +103,42 @@ WHERE pg_stat_activity.datname = 'source_database_name'
103103 AND pid <> pg_backend_pid();
104104```
105105
106- #### 2. Create Template Database
106+ #### 2. Create Template Database (Full Copy)
107107``` sql
108- -- Create the new template database with special template settings
108+ -- Create the new template database as a complete copy of the source
109109CREATE DATABASE template_database_name
110- WITH TEMPLATE template0
111- ENCODING ' UTF8'
112- LC_COLLATE = ' en_US.UTF-8'
113- LC_CTYPE = ' en_US.UTF-8'
114- IS_TEMPLATE = true;
110+ WITH TEMPLATE source_database_name
111+ OWNER template_owner;
115112```
116113
117- #### 3. Copy Schema Structure (Without Data)
114+ #### 3. Truncate All Data from Template
118115``` sql
119- -- Connect to template database and copy schema structure
120- -- This includes tables, views, functions, triggers, etc.
121- -- But excludes all data from tables
122-
123- -- Copy table structures
124- CREATE TABLE new_table (LIKE source_table INCLUDING ALL);
125-
126- -- Copy views
127- CREATE VIEW new_view AS SELECT * FROM source_view;
128-
129- -- Copy functions and procedures
130- -- (Function definitions are copied from source database)
131-
132- -- Copy triggers
133- -- (Trigger definitions are copied and recreated)
134-
135- -- Copy constraints and indexes
136- -- (Included with INCLUDING ALL clause)
116+ -- Connect to the template database and truncate all user tables
117+ -- This removes all data but preserves the complete schema structure
118+
119+ -- Get all user tables and truncate them
120+ DO $
121+ DECLARE
122+ table_name TEXT ;
123+ BEGIN
124+ FOR table_name IN
125+ SELECT schemaname|| ' .' || tablename
126+ FROM pg_tables
127+ WHERE schemaname NOT IN (' information_schema' , ' pg_catalog' )
128+ LOOP
129+ EXECUTE ' TRUNCATE TABLE ' || table_name || ' CASCADE;' ;
130+ END LOOP;
131+ END $;
137132```
138133
139- #### 4. Set Template Permissions
134+ #### 4. Set Template Properties
140135``` sql
141- -- Prevent connections to template database during creation
136+ -- Mark database as a template
137+ UPDATE pg_database
138+ SET datistemplate = true
139+ WHERE datname = ' template_database_name' ;
140+
141+ -- Prevent connections during final setup
142142UPDATE pg_database
143143SET datallowconn = false
144144WHERE datname = ' template_database_name' ;
@@ -147,9 +147,6 @@ WHERE datname = 'template_database_name';
147147UPDATE pg_database
148148SET datallowconn = true
149149WHERE datname = ' template_database_name' ;
150-
151- -- Set appropriate ownership and permissions
152- ALTER DATABASE template_database_name OWNER TO template_owner;
153150```
154151
155152#### 5. Template Deployment Commands
0 commit comments