Module: Pgoutput::Client::LSN

Defined in:
lib/pgoutput/client/lsn.rb

Overview

PostgreSQL Log Sequence Number conversion helpers.

PostgreSQL represents LSNs as two hexadecimal 32-bit halves separated by a slash, such as ‘0/16B6C50`. The replication protocol transmits the same WAL position as an unsigned 64-bit integer. This module converts between those two representations.

Examples:

Parse a textual LSN

Pgoutput::Client::LSN.parse("0/10")
# => 16

Format an integer WAL position

Pgoutput::Client::LSN.format(16)
# => "0/10"

Class Method Summary collapse

Class Method Details

.format(value) ⇒ String

Format an integer WAL position as a PostgreSQL LSN string.

Parameters:

  • value (#to_int, #to_s)

    non-negative integer WAL position

Returns:

  • (String)

    LSN string in uppercase hexadecimal ‘HEX/HEX` form

Raises:

  • (ArgumentError)

    if the value is negative or cannot be coerced to an integer



44
45
46
47
48
49
50
51
# File 'lib/pgoutput/client/lsn.rb', line 44

def format(value)
  integer = Integer(value)
  raise ArgumentError, "LSN must be non-negative" if integer.negative?

  high = integer >> 32
  low = integer & 0xFFFF_FFFF
  "#{high.to_s(16).upcase}/#{low.to_s(16).upcase}"
end

.parse(value) ⇒ Integer

Parse a PostgreSQL LSN string into an integer WAL position.

Parameters:

  • value (#to_s)

    LSN string in ‘HEX/HEX` form

Returns:

  • (Integer)

    unsigned 64-bit WAL position

Raises:

  • (ArgumentError)

    if the value is not a valid LSN string



29
30
31
32
33
34
35
36
# File 'lib/pgoutput/client/lsn.rb', line 29

def parse(value)
  high, low = String(value).split("/", 2)
  raise ArgumentError, "invalid LSN: #{value.inspect}" if high.nil? || low.nil?

  (Integer(high, 16) << 32) + Integer(low, 16)
rescue ArgumentError
  raise ArgumentError, "invalid LSN: #{value.inspect}"
end