@@ -140,3 +140,58 @@ 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+ queryRi := "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+
150+ err := p .conn .QueryRow (p .ctx , queryRi , schema , parent ).Scan (& replIdent )
151+ if err != nil {
152+ return fmt .Errorf ("failed to check pg_class.relreplident for parent table: %w" , err )
153+ }
154+
155+ if replIdent == "f" { // replica identity = full
156+ queryFull := fmt .Sprintf ("ALTER TABLE %s.%s REPLICA IDENTITY FULL" , schema , table )
157+ p .logger .Debug ("Set identity full" , "query" , queryFull )
158+
159+ _ , err = p .conn .Exec (p .ctx , queryFull )
160+ if err != nil {
161+ return fmt .Errorf ("failed to set replica identity: %w" , err )
162+ }
163+ } else if replIdent == "i" { // replica identity = specific index
164+ var indexName string
165+ /* This query finds the index that is a child of the (only) index
166+ in the parent table having "indisreplident"=true.
167+ "pg_inherits" holds the (parent-index, child-index) relationship. */
168+ queryIdx := `
169+ SELECT c_idx_child.relname
170+ FROM pg_index i_parent JOIN pg_inherits inh ON (inh.inhparent=i_parent.indexrelid)
171+ JOIN pg_index i_child ON (i_child.indexrelid=inh.inhrelid)
172+ JOIN pg_class c_parent ON (c_parent.oid=i_parent.indrelid)
173+ JOIN pg_namespace ON (pg_namespace.oid=c_parent.relnamespace)
174+ JOIN pg_class c_idx_child ON (c_idx_child.oid=inh.inhrelid)
175+ JOIN pg_class c_child ON (c_child.oid=i_child.indrelid)
176+ WHERE pg_namespace.nspname= $1
177+ AND c_parent.relname = $2
178+ AND i_parent.indisreplident=true
179+ AND c_child.relname = $3
180+ `
181+
182+ err = p .conn .QueryRow (p .ctx , queryIdx , schema , parent , table ).Scan (& indexName )
183+ if err != nil {
184+ return fmt .Errorf ("failed to find the child index for the new partition: %w" , err )
185+ }
186+
187+ queryAlter := fmt .Sprintf ("ALTER TABLE %s.%s REPLICA IDENTITY USING INDEX %s" , schema , table , indexName )
188+ p .logger .Debug ("Set replica identity" , "schema" , schema , "table" , table , "index" , indexName , "query" , queryAlter )
189+
190+ _ , err := p .conn .Exec (p .ctx , queryAlter )
191+ if err != nil {
192+ return fmt .Errorf ("failed to set replica identity on the new partition: %w" , err )
193+ }
194+ }
195+
196+ return nil
197+ }
0 commit comments