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/orchestrate.rb,
lib/pg_easy_replicate/index_manager.rb

Defined Under Namespace

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

Constant Summary collapse

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

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, 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



84
85
86
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
# File 'lib/pg_easy_replicate.rb', line 84

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



293
294
295
296
297
# File 'lib/pg_easy_replicate.rb', line 293

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



131
132
133
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
# File 'lib/pg_easy_replicate.rb', line 131

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
rescue => e
  abort_with("Unable to bootstrap: #{e.message}")
end

.cleanup(options) ⇒ Object



162
163
164
165
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
# File 'lib/pg_easy_replicate.rb', line 162

def cleanup(options)
  cleanup_steps = [
    -> do
      logger.info("Dropping groups table")
      Group.drop
    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
    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



29
30
31
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
# File 'lib/pg_easy_replicate.rb', line 29

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



259
260
261
262
# File 'lib/pg_easy_replicate.rb', line 259

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



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/pg_easy_replicate.rb', line 329

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 = "    create role \#{quote_ident(internal_user_name)} with password '\#{password}' login createdb createrole;\n    grant all privileges on database \#{quote_ident(db_name(conn_string))} TO \#{quote_ident(internal_user_name)};\n  SQL\n\n  Query.run(\n    query: sql,\n    connection_url: conn_string,\n    user: db_user(conn_string),\n    transaction: false,\n  )\n\n  sql =\n    if special_user_role\n      \"grant \#{quote_ident(special_user_role)} to \#{quote_ident(internal_user_name)};\"\n    else\n      \"alter user \#{quote_ident(internal_user_name)} with superuser;\"\n    end\n\n  Query.run(\n    query: sql,\n    connection_url: conn_string,\n    user: db_user(conn_string),\n    transaction: false,\n  )\n\n  return unless grant_permissions_on_schema\n  Query.run(\n    query:\n      \"grant all on schema \#{quote_ident(internal_schema_name)} to \#{quote_ident(internal_user_name)}\",\n    connection_url: conn_string,\n    user: db_user(conn_string),\n    transaction: false,\n  )\nrescue => e\n  raise \"Unable to create user: \#{e.message}\"\nend\n"

.drop_internal_schemaObject



219
220
221
222
223
224
225
226
227
228
229
# File 'lib/pg_easy_replicate.rb', line 219

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



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
# File 'lib/pg_easy_replicate.rb', line 376

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

  sql = "   revoke all privileges on database \#{quote_ident(db_name(conn_string))} from \#{quote_ident(user)};\n  SQL\n\n  Query.run(\n    query: sql,\n    connection_url: conn_string,\n    user: db_user(conn_string),\n  )\n\n  sql = <<~SQL\n    drop role if exists \#{quote_ident(user)};\n  SQL\n\n  Query.run(\n    query: sql,\n    connection_url: conn_string,\n    user: db_user(conn_string),\n  )\nrescue => e\n  raise \"Unable to drop user: \#{e.message}\"\nend\n"

.export_schema(conn_string:) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/pg_easy_replicate.rb', line 264

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

.import_schema(conn_string:) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
# File 'lib/pg_easy_replicate.rb', line 281

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)


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/pg_easy_replicate.rb', line 299

def is_super_user?(url, special_user_role = nil)
  if special_user_role
    sql = "      SELECT r.rolname AS username,\n        r1.rolname AS \"role\"\n      FROM pg_catalog.pg_roles r\n      LEFT JOIN pg_catalog.pg_auth_members m ON (m.member = r.oid)\n      LEFT JOIN pg_roles r1 ON (m.roleid=r1.oid)\n      WHERE r.rolname = '\#{db_user(url)}'\n      ORDER BY 1;\n    SQL\n\n    r = Query.run(query: sql, connection_url: url, user: db_user(url))\n    # If special_user_role is passed just ensure the url in conn_string has been granted\n    # the special_user_role\n    r.any? { |q| q[:role] == special_user_role }\n  else\n    r =\n      Query.run(\n        query:\n          \"SELECT rolname, rolsuper FROM pg_roles where rolname = '\#{db_user(url)}';\",\n        connection_url: url,\n        user: db_user(url),\n      )\n    r.any? { |q| q[:rolsuper] }\n  end\nrescue => e\n  raise \"Unable to check superuser conditions: \#{e.message}\"\nend\n"

.loggerObject



248
249
250
251
252
253
254
255
256
257
# File 'lib/pg_easy_replicate.rb', line 248

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



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/pg_easy_replicate.rb', line 231

def setup_internal_schema
  sql = "    create schema if not exists \#{quote_ident(internal_schema_name)};\n    grant usage on schema \#{quote_ident(internal_schema_name)} to \#{quote_ident(db_user(source_db_url))};\n    grant create on schema \#{quote_ident(internal_schema_name)} to \#{quote_ident(db_user(source_db_url))};\n  SQL\n\n  Query.run(\n    query: sql,\n    connection_url: source_db_url,\n    schema: internal_schema_name,\n    user: db_user(source_db_url),\n  )\nrescue => e\n  raise \"Unable to setup schema: \#{e.message}\"\nend\n"

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

Returns:

  • (Boolean)


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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/pg_easy_replicate.rb', line 422

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 = "    SELECT t.relname AS table_name,\n          CASE\n            WHEN t.relreplident = 'd' THEN 'default'\n            WHEN t.relreplident = 'n' THEN 'nothing'\n            WHEN t.relreplident = 'i' THEN 'index'\n            WHEN t.relreplident = 'f' THEN 'full'\n          END AS replica_identity\n    FROM pg_class t\n    JOIN pg_namespace ns ON t.relnamespace = ns.oid\n    WHERE ns.nspname = '\#{schema_name}'\n      AND t.relkind = 'r'\n      AND t.relname IN (\#{formatted_table_list})\n  SQL\n\n  results =\n    Query.run(\n      query: sql,\n      connection_url: conn_string,\n      user: db_user(conn_string),\n    )\n\n  results.all? { |r| r[:replica_identity] != \"nothing\" }\nend\n"

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

Returns:

  • (Boolean)


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 402

def user_exists?(conn_string:, user: internal_user_name)
  sql = "    SELECT r.rolname AS username,\n      r1.rolname AS \"role\"\n    FROM pg_catalog.pg_roles r\n    LEFT JOIN pg_catalog.pg_auth_members m ON (m.member = r.oid)\n    LEFT JOIN pg_roles r1 ON (m.roleid=r1.oid)\n    WHERE r.rolname = '\#{user}'\n    ORDER BY 1;\n  SQL\n\n  Query\n    .run(\n      query: sql,\n      connection_url: conn_string,\n      user: db_user(conn_string),\n    )\n    .any? { |q| q[:username] == user }\nend\n"