@@ -140,3 +140,55 @@ func (p Postgres) GetPartitionSettings(schema, table string) (strategy, key stri
140140
141141 return strategy , key , nil
142142}
143+
144+ func (p Postgres ) SetPartitionReplicaIdentity (schema , table , parent string ) error {
145+ var replIdent string
146+
147+ // Get the replica identity of the parent
148+ query_ri := "SELECT relreplident::text from pg_class c JOIN pg_namespace n ON (n.oid=c.relnamespace) WHERE n.nspname=$1 AND c.relname=$2"
149+ err := p .conn .QueryRow (p .ctx , query_ri , schema , parent ).Scan (& replIdent )
150+ if err != nil {
151+ return fmt .Errorf ("failed to check pg_class.relreplident for parent table: %w" , err )
152+ }
153+
154+ if replIdent == "f" { // replica identity = full
155+ query_f := fmt .Sprintf ("ALTER TABLE %s.%s REPLICA IDENTITY FULL" , schema , table )
156+ p .logger .Debug ("Set identity full" , "query" , query_f )
157+ _ , err = p .conn .Exec (p .ctx , query_f )
158+ if err != nil {
159+ return fmt .Errorf ("failed to set replica identity: %w" , err )
160+ }
161+
162+ } else if replIdent == "i" { // replica identity = specific index
163+ var indexName string
164+ /* This query finds the index that is a child of the (only) index
165+ in the parent table having "indisreplident"=true.
166+ "pg_inherits" holds the (parent-index, child-index) relationship. */
167+ query_idx := `
168+ SELECT c_idx_child.relname
169+ FROM pg_index i_parent JOIN pg_inherits inh ON (inh.inhparent=i_parent.indexrelid)
170+ JOIN pg_index i_child ON (i_child.indexrelid=inh.inhrelid)
171+ JOIN pg_class c_parent ON (c_parent.oid=i_parent.indrelid)
172+ JOIN pg_namespace ON (pg_namespace.oid=c_parent.relnamespace)
173+ JOIN pg_class c_idx_child ON (c_idx_child.oid=inh.inhrelid)
174+ JOIN pg_class c_child ON (c_child.oid=i_child.indrelid)
175+ WHERE pg_namespace.nspname= $1
176+ AND c_parent.relname = $2
177+ AND i_parent.indisreplident=true
178+ AND c_child.relname = $3
179+ `
180+ err = p .conn .QueryRow (p .ctx , query_idx , schema , parent , table ).Scan (& indexName )
181+ if err != nil {
182+ return fmt .Errorf ("failed to find the child index for the new partition: %w" , err )
183+ }
184+
185+ query_alter := fmt .Sprintf ("ALTER TABLE %s.%s REPLICA IDENTITY USING INDEX %s" , schema , table , indexName )
186+ p .logger .Debug ("Set replica identity" , "schema" , schema , "table" , table , "index" , indexName , "query" , query_alter )
187+
188+ _ , err := p .conn .Exec (p .ctx , query_alter )
189+ if err != nil {
190+ return fmt .Errorf ("failed to set replica identity on the new partition: %w" , err )
191+ }
192+ }
193+ return nil
194+ }
0 commit comments