Module: PgEasyReplicate

Extended by:
Helper
Defined in:
lib/pg_easy_replicate.rb,
lib/pg_easy_replicate/cli.rb,
lib/pg_easy_replicate/group.rb,
lib/pg_easy_replicate/query.rb,
lib/pg_easy_replicate/stats.rb,
lib/pg_easy_replicate/helper.rb,
lib/pg_easy_replicate/version.rb,
lib/pg_easy_replicate/ddl_audit.rb,
lib/pg_easy_replicate/ddl_manager.rb,
lib/pg_easy_replicate/orchestrate.rb,
lib/pg_easy_replicate/index_manager.rb

Defined Under Namespace

Modules: DDLManager, Helper, IndexManager Classes: CLI, DDLAudit, Error, Group, Orchestrate, Query, Stats

Constant Summary collapse

SCHEMA_FILE_LOCATION =
"/tmp/pger_schema.sql"
VERSION =
"0.4.0"

Class Method Summary collapse

Methods included from Helper

abort_with, connection_info, convert_to_array, db_name, db_user, determine_tables, internal_schema_name, internal_user_name, list_all_tables, logger, publication_name, quote_ident, restore_connections_on_source_db, secondary_source_db_url, source_db_url, subscription_name, target_db_url, test_env?, underscore, validate_table_lists

Class Method Details

.assert_config(special_user_role: nil, copy_schema: false, tables: "", exclude_tables: "", schema_name: nil) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/pg_easy_replicate.rb', line 87

def assert_config(
  special_user_role: nil,
  copy_schema: false,
  tables: "",
  exclude_tables: "",
  schema_name: nil
)
  config_hash =
    config(
      special_user_role: special_user_role,
      copy_schema: copy_schema,
      tables: tables,
      exclude_tables: exclude_tables,
      schema_name: schema_name,
    )

  if copy_schema && !config_hash.dig(:pg_dump_exists)
    abort_with("pg_dump must exist if copy_schema (-c) is passed")
  end

  unless assert_wal_level_logical(config_hash.dig(:source_db))
    abort_with("WAL_LEVEL should be LOGICAL on source DB")
  end

  unless assert_wal_level_logical(config_hash.dig(:target_db))
    abort_with("WAL_LEVEL should be LOGICAL on target DB")
  end

  unless config_hash.dig(:source_db_is_super_user)
    abort_with("User on source database does not have super user privilege")
  end

  validate_table_lists(tables, exclude_tables, schema_name)

  unless config_hash.dig(:tables_have_replica_identity)
    abort_with(
      "Ensure all tables involved in logical replication have an appropriate replica identity set. This can be done using:
    1. Default (Primary Key): `ALTER TABLE table_name REPLICA IDENTITY DEFAULT;`
    2. Unique Index: `ALTER TABLE table_name REPLICA IDENTITY USING INDEX index_name;`
    3. Full (All Columns): `ALTER TABLE table_name REPLICA IDENTITY FULL;`",
    )
  end

  return if config_hash.dig(:target_db_is_super_user)
  abort_with("User on target database does not have super user privilege")
end

.assert_wal_level_logical(db_config) ⇒ Object



315
316
317
318
319
# File 'lib/pg_easy_replicate.rb', line 315

def assert_wal_level_logical(db_config)
  db_config&.find do |r|
    r.dig(:name) == "wal_level" && r.dig(:setting) == "logical"
  end
end

.bootstrap(options) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/pg_easy_replicate.rb', line 134

def bootstrap(options)
  logger.info("Setting up schema")
  setup_internal_schema

  if options[:copy_schema]
    logger.info("Setting up schema on target database")
    copy_schema(
      source_conn_string: source_db_url,
      target_conn_string: target_db_url,
    )
  end

  logger.info("Setting up replication user on source database")
  create_user(
    conn_string: source_db_url,
    special_user_role: options[:special_user_role],
    grant_permissions_on_schema: true,
  )

  logger.info("Setting up replication user on target database")
  create_user(
    conn_string: target_db_url,
    special_user_role: options[:special_user_role],
  )

  logger.info("Setting up groups tables")
  Group.setup
  logger.info("Bootstrap completed successfully")
rescue => e
  abort_with("Unable to bootstrap: #{e.message}")
end

.cleanup(options) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/pg_easy_replicate.rb', line 166

def cleanup(options)
  cleanup_steps = [
    -> do
      if options[:everything]
        logger.info("Dropping groups table")
        Group.drop
      else
        logger.info("Deleting group entry for #{options[:group_name]}")
        Group.delete(options[:group_name])
      end
    end,
    -> do
      if options[:restore_connection_on_source_db]
        restore_connections_on_source_db
      end
    end,
    -> do
      if options[:everything]
        logger.info("Dropping schema")
        drop_internal_schema
      end
    end,
    -> do
      if options[:everything] || options[:sync]
        logger.info("Dropping publication on source database")
        Orchestrate.drop_publication(
          group_name: options[:group_name],
          conn_string: source_db_url,
        )
      end
    end,
    -> do
      if options[:everything] || options[:sync]
        logger.info("Dropping subscription on target database")
        Orchestrate.drop_subscription(
          group_name: options[:group_name],
          target_conn_string: target_db_url,
        )
      end
    end,
    -> do
      if options[:everything]
        logger.info("Dropping replication user on source database")
        drop_user(conn_string: source_db_url)
      end
    end,
    -> do
      if options[:everything]
        logger.info("Dropping replication user on target database")
        drop_user(conn_string: target_db_url)
      end
      -> do
        if options[:everything]
          PgEasyReplicate::DDLManager.cleanup_ddl_tracking(
            conn_string: source_db_url,
            group_name: options[:group_name],
          )
        end
      end
    end,
  ]

  cleanup_steps.each do |step|
    step.call
  rescue => e
    logger.warn(
      "Part of the cleanup step failed with #{e.message}. Continuing...",
    )
  end

  logger.info("Cleanup process completed.")
rescue => e
  abort_with("Unable to cleanup: #{e.message}")
end

.config(special_user_role: nil, copy_schema: false, tables: "", exclude_tables: "", schema_name: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/pg_easy_replicate.rb', line 32

def config(
  special_user_role: nil,
  copy_schema: false,
  tables: "",
  exclude_tables: "",
  schema_name: nil
)
  abort_with("SOURCE_DB_URL is missing") if source_db_url.nil?
  abort_with("TARGET_DB_URL is missing") if target_db_url.nil?

  if !tables.empty? && !exclude_tables.empty?
    abort_with(
      "Options --tables(-t) and --exclude-tables(-e) cannot be used together.",
    )
  end

  system("which pg_dump")
  pg_dump_exists = $CHILD_STATUS.success?

  @config ||=
    begin
      q =
        "select name, setting from pg_settings where name in  ('max_wal_senders', 'max_worker_processes', 'wal_level',  'max_replication_slots', 'max_logical_replication_workers');"

      {
        source_db_is_super_user:
          is_super_user?(source_db_url, special_user_role),
        target_db_is_super_user:
          is_super_user?(target_db_url, special_user_role),
        source_db:
          Query.run(
            query: q,
            connection_url: source_db_url,
            user: db_user(source_db_url),
          ),
        target_db:
          Query.run(
            query: q,
            connection_url: target_db_url,
            user: db_user(target_db_url),
          ),
        pg_dump_exists: pg_dump_exists,
        tables_have_replica_identity:
          tables_have_replica_identity?(
            conn_string: source_db_url,
            tables: tables,
            exclude_tables: exclude_tables,
            schema_name: schema_name,
          ),
      }
    rescue => e
      abort_with("Unable to check config: #{e.message}")
    end
end

.copy_schema(source_conn_string:, target_conn_string:) ⇒ Object



281
282
283
284
# File 'lib/pg_easy_replicate.rb', line 281

def copy_schema(source_conn_string:, target_conn_string:)
  export_schema(conn_string: source_conn_string)
  import_schema(conn_string: target_conn_string)
end

.create_user(conn_string:, special_user_role: nil, grant_permissions_on_schema: false) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/pg_easy_replicate.rb', line 363

def create_user(
  conn_string:,
  special_user_role: nil,
  grant_permissions_on_schema: false
)
  return if user_exists?(conn_string: conn_string, user: internal_user_name)

  password = connection_info(conn_string)[:password].gsub("'") { "''" }

  sql = <<~SQL
    create role #{quote_ident(internal_user_name)} with password '#{password}' login createdb createrole;
    grant all privileges on database #{quote_ident(db_name(conn_string))} TO #{quote_ident(internal_user_name)};
  SQL

  Query.run(
    query: sql,
    connection_url: conn_string,
    user: db_user(conn_string),
    transaction: false,
  )

  sql = if special_user_role
    "grant #{quote_ident(special_user_role)} to #{quote_ident(internal_user_name)};"
  else
    "alter user #{quote_ident(internal_user_name)} with superuser;"
  end

  Query.run(
    query: sql,
    connection_url: conn_string,
    user: db_user(conn_string),
    transaction: false,
  )

  if grant_permissions_on_schema
    Query.run(
      query:
        "grant all on schema #{quote_ident(internal_schema_name)} to #{quote_ident(internal_user_name)}",
      connection_url: conn_string,
      user: db_user(conn_string),
      transaction: false,
    )
  end
rescue => e
  raise "Unable to create user: #{e.message}" unless special_user_role && e.message.include?("permission denied to grant role")

  pg_version = get_pg_version(conn_string: conn_string)
  version_info = if pg_version && pg_version >= 16
    "PostgreSQL #{pg_version} requires"
  else
    "PostgreSQL 16+ requires"
  end

  raise "Unable to create user: #{e.message}. " \
        "#{version_info} the user '#{db_user(conn_string)}' to have the ADMIN option on role '#{special_user_role}' to grant it to other users. " \
        "Please ensure the user has been granted the role with ADMIN option: " \
        "GRANT #{special_user_role} TO #{db_user(conn_string)} WITH ADMIN OPTION;"
end

.drop_internal_schemaObject



241
242
243
244
245
246
247
248
249
250
251
# File 'lib/pg_easy_replicate.rb', line 241

def drop_internal_schema
  Query.run(
    query:
      "DROP SCHEMA IF EXISTS #{quote_ident(internal_schema_name)} CASCADE",
    connection_url: source_db_url,
    schema: internal_schema_name,
    user: db_user(source_db_url),
  )
rescue => e
  raise "Unable to drop schema: #{e.message}"
end

.drop_user(conn_string:, user: internal_user_name) ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/pg_easy_replicate.rb', line 422

def drop_user(conn_string:, user: internal_user_name)
  return unless user_exists?(conn_string: conn_string, user: user)

  sql = <<~SQL
   revoke all privileges on database #{quote_ident(db_name(conn_string))} from #{quote_ident(user)};
  SQL

  Query.run(
    query: sql,
    connection_url: conn_string,
    user: db_user(conn_string),
  )

  sql = <<~SQL
    drop role if exists #{quote_ident(user)};
  SQL

  Query.run(
    query: sql,
    connection_url: conn_string,
    user: db_user(conn_string),
  )
rescue => e
  raise "Unable to drop user: #{e.message}"
end

.export_schema(conn_string:) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/pg_easy_replicate.rb', line 286

def export_schema(conn_string:)
  logger.info("Exporting schema to #{SCHEMA_FILE_LOCATION}")
  _, stderr, status =
    Open3.capture3(
      "pg_dump",
      conn_string,
      "-f",
      SCHEMA_FILE_LOCATION,
      "--schema-only",
    )

  success = status.success?
  raise stderr unless success
rescue => e
  raise "Unable to export schema: #{e.message}"
end

.get_pg_version(conn_string:) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
# File 'lib/pg_easy_replicate.rb', line 351

def get_pg_version(conn_string:)
  sql = "SELECT version()"
  result = Query.run(query: sql, connection_url: conn_string, user: db_user(conn_string))
  version_string = result.first[:version]
  # Extract major version number (e.g., "PostgreSQL 16.1..." -> 16)
  version_match = version_string.match(/PostgreSQL (\d+)\./)
  version_match ? version_match[1].to_i : nil
rescue => e
  logger.warn("Unable to determine PostgreSQL version: #{e.message}")
  nil
end

.import_schema(conn_string:) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
# File 'lib/pg_easy_replicate.rb', line 303

def import_schema(conn_string:)
  logger.info("Importing schema from #{SCHEMA_FILE_LOCATION}")

  _, stderr, status =
    Open3.capture3("psql", "-f", SCHEMA_FILE_LOCATION, conn_string)

  success = status.success?
  raise stderr unless success
rescue => e
  raise "Unable to import schema: #{e.message}"
end

.is_super_user?(url, special_user_role = nil) ⇒ Boolean

Returns:

  • (Boolean)


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/pg_easy_replicate.rb', line 321

def is_super_user?(url, special_user_role = nil)
  if special_user_role
    sql = <<~SQL
      SELECT r.rolname AS username,
        r1.rolname AS "role"
      FROM pg_catalog.pg_roles r
      LEFT JOIN pg_catalog.pg_auth_members m ON (m.member = r.oid)
      LEFT JOIN pg_roles r1 ON (m.roleid=r1.oid)
      WHERE r.rolname = '#{db_user(url)}'
      ORDER BY 1;
    SQL

    r = Query.run(query: sql, connection_url: url, user: db_user(url))
    # If special_user_role is passed just ensure the url in conn_string has been granted
    # the special_user_role
    r.any? { |q| q[:role] == special_user_role }
  else
    r =
      Query.run(
        query:
          "SELECT rolname, rolsuper FROM pg_roles where rolname = '#{db_user(url)}';",
        connection_url: url,
        user: db_user(url),
      )
    r.any? { |q| q[:rolsuper] }
  end
rescue => e
  raise "Unable to check superuser conditions: #{e.message}"
end

.loggerObject



270
271
272
273
274
275
276
277
278
279
# File 'lib/pg_easy_replicate.rb', line 270

def logger
  @logger ||=
    begin
      logger = Ougai::Logger.new($stdout)
      logger.level =
        ENV["DEBUG"] ? Ougai::Logger::TRACE : Ougai::Logger::INFO
      logger.with_fields = { version: PgEasyReplicate::VERSION }
      logger
    end
end

.setup_internal_schemaObject



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/pg_easy_replicate.rb', line 253

def setup_internal_schema
  sql = <<~SQL
    create schema if not exists #{quote_ident(internal_schema_name)};
    grant usage on schema #{quote_ident(internal_schema_name)} to #{quote_ident(db_user(source_db_url))};
    grant create on schema #{quote_ident(internal_schema_name)} to #{quote_ident(db_user(source_db_url))};
  SQL

  Query.run(
    query: sql,
    connection_url: source_db_url,
    schema: internal_schema_name,
    user: db_user(source_db_url),
  )
rescue => e
  raise "Unable to setup schema: #{e.message}"
end

.tables_have_replica_identity?(conn_string:, tables: "", exclude_tables: "", schema_name: nil) ⇒ Boolean

Returns:

  • (Boolean)


468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/pg_easy_replicate.rb', line 468

def tables_have_replica_identity?(
  conn_string:,
  tables: "",
  exclude_tables: "",
  schema_name: nil
)
  schema_name ||= "public"

  table_list =
    determine_tables(
      schema: schema_name,
      conn_string: source_db_url,
      list: tables,
      exclude_list: exclude_tables,
    )
  return false if table_list.empty?

  formatted_table_list = table_list.map { |table| "'#{table}'" }.join(", ")

  sql = <<~SQL
    SELECT t.relname AS table_name,
          CASE
            WHEN t.relreplident = 'd' THEN 'default'
            WHEN t.relreplident = 'n' THEN 'nothing'
            WHEN t.relreplident = 'i' THEN 'index'
            WHEN t.relreplident = 'f' THEN 'full'
          END AS replica_identity
    FROM pg_class t
    JOIN pg_namespace ns ON t.relnamespace = ns.oid
    WHERE ns.nspname = '#{schema_name}'
      AND t.relkind = 'r'
      AND t.relname IN (#{formatted_table_list})
  SQL

  results =
    Query.run(
      query: sql,
      connection_url: conn_string,
      user: db_user(conn_string),
    )

  results.all? { |r| r[:replica_identity] != "nothing" }
end

.user_exists?(conn_string:, user: internal_user_name) ⇒ Boolean

Returns:

  • (Boolean)


448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/pg_easy_replicate.rb', line 448

def user_exists?(conn_string:, user: internal_user_name)
  sql = <<~SQL
    SELECT r.rolname AS username,
      r1.rolname AS "role"
    FROM pg_catalog.pg_roles r
    LEFT JOIN pg_catalog.pg_auth_members m ON (m.member = r.oid)
    LEFT JOIN pg_roles r1 ON (m.roleid=r1.oid)
    WHERE r.rolname = '#{user}'
    ORDER BY 1;
  SQL

  Query
    .run(
      query: sql,
      connection_url: conn_string,
      user: db_user(conn_string),
    )
    .any? { |q| q[:username] == user }
end