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.4"

Class Method Summary collapse

Methods included from Helper

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

Class Method Details

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



76
77
78
79
80
81
82
83
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
# File 'lib/pg_easy_replicate.rb', line 76

def assert_config(
  special_user_role: nil,
  copy_schema: false,
  tables: "",
  schema_name: nil
)
  config_hash =
    config(
      special_user_role: special_user_role,
      copy_schema: copy_schema,
      tables: 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

  if tables.split(",").size > 0 && (schema_name.nil? || schema_name == "")
    abort_with("Schema name is required if tables are passed")
  end

  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



261
262
263
264
265
# File 'lib/pg_easy_replicate.rb', line 261

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



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/pg_easy_replicate.rb', line 123

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



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/pg_easy_replicate.rb', line 154

def cleanup(options)
  logger.info("Dropping groups table")
  Group.drop

  if options[:everything]
    logger.info("Dropping schema")
    drop_internal_schema
  end

  if options[:everything] || options[:sync]
    Orchestrate.drop_publication(
      group_name: options[:group_name],
      conn_string: source_db_url,
    )

    Orchestrate.drop_subscription(
      group_name: options[:group_name],
      target_conn_string: target_db_url,
    )
  end

  if options[:everything]
    # Drop users at last
    logger.info("Dropping replication user on source database")
    drop_user(conn_string: source_db_url)

    logger.info("Dropping replication user on target database")
    drop_user(conn_string: target_db_url)
  end
rescue => e
  abort_with("Unable to cleanup: #{e.message}")
end

.config(special_user_role: nil, copy_schema: false, 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
# File 'lib/pg_easy_replicate.rb', line 29

def config(
  special_user_role: nil,
  copy_schema: false,
  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?

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



227
228
229
230
# File 'lib/pg_easy_replicate.rb', line 227

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



297
298
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/pg_easy_replicate.rb', line 297

def create_user(
  conn_string:,
  special_user_role: nil,
  grant_permissions_on_schema: false
)
  password = connection_info(conn_string)[:password].gsub("'") { "''" }

  drop_user(conn_string: conn_string)

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

  return unless 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,
  )
rescue => e
  raise "Unable to create user: #{e.message}"
end

.drop_internal_schemaObject



187
188
189
190
191
192
193
194
195
196
197
# File 'lib/pg_easy_replicate.rb', line 187

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



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

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



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

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



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

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)


267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/pg_easy_replicate.rb', line 267

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



216
217
218
219
220
221
222
223
224
225
# File 'lib/pg_easy_replicate.rb', line 216

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



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/pg_easy_replicate.rb', line 199

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: "", schema_name: nil) ⇒ Boolean

Returns:

  • (Boolean)


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
421
422
423
424
425
426
427
428
429
430
# File 'lib/pg_easy_replicate.rb', line 390

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

  table_list =
    determine_tables(
      schema: schema_name,
      conn_string: source_db_url,
      list: 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)


370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/pg_easy_replicate.rb', line 370

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