Skip to content

A platform for community discussion. Free, open, simple.

MT: Use typed COPY encoders in the importer

Gerhard Schlagera13b6b7926dc
diff --git a/migrations/importer/lib/migrations/importer/discourse_db.rb b/migrations/importer/lib/migrations/importer/discourse_db.rb
index 94a2b8f6f48..c46ba5a864d 100644
--- a/migrations/importer/lib/migrations/importer/discourse_db.rb
+++ b/migrations/importer/lib/migrations/importer/discourse_db.rb
@@ -9,7 +9,6 @@ module Migrations
SKIP_ROW_MARKER = :$skip
def initialize
- @encoder = PG::TextEncoder::CopyRow.new
@connection = PG::Connection.new(database_configuration)
@connection.type_map_for_results = PG::BasicTypeMapForResults.new(@connection)
end
@@ -23,6 +22,9 @@ module Migrations
column_count = column_names.size
data = Array.new(column_count)
+ type_map = build_type_map(table_name, column_names)
+ encoder = PG::TextEncoder::CopyRow.new(type_map:)
+
rows.each_slice(COPY_BATCH_SIZE) do |sliced_rows|
# TODO Maybe add error handling and check if all rows fail to insert, or only
# some of them fail. Currently, if a single row fails to insert, then an exception
@@ -30,7 +32,7 @@ module Migrations
# should ensure all data is valid. We might need to see how this works out in
# actual migrations...
@connection.transaction do
- @connection.copy_data(sql, @encoder) do
+ @connection.copy_data(sql, encoder) do
sliced_rows.each do |row|
if row[SKIP_ROW_MARKER]
skipped_rows << row
@@ -150,6 +152,31 @@ module Migrations
def quote_identifier(identifier)
PG::Connection.quote_ident(identifier.to_s)
end
+
+ def build_type_map(table_name, column_names)
+ sql = <<~SQL
+ SELECT a.attname AS name,
+ t.typname AS pg_type
+ FROM pg_attribute a
+ JOIN pg_type t ON a.atttypid = t.oid
+ WHERE a.attrelid = $1::regclass
+ AND a.attnum > 0
+ AND NOT a.attisdropped
+ SQL
+
+ result = @connection.exec_params(sql, [table_name]).to_a
+ column_type_map = result.to_h { |row| [row["name"].to_sym, row["pg_type"]] }
+
+ encoders =
+ column_names.map do |column_name|
+ pg_type = column_type_map[column_name]
+ raise "Column #{column_name} not found in table #{table_name}" unless pg_type
+
+ PgEncoderCache.get_encoder(pg_type)
+ end
+
+ PG::TypeMapByColumn.new(encoders)
+ end
end
end
end
diff --git a/migrations/importer/lib/migrations/importer/pg_encoder_cache.rb b/migrations/importer/lib/migrations/importer/pg_encoder_cache.rb
new file mode 100644
index 00000000000..d3110b642e2
--- /dev/null
+++ b/migrations/importer/lib/migrations/importer/pg_encoder_cache.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+require "json"
+require "pg"
+
+module Migrations
+ module Importer
+ module PgEncoderCache
+ @encoders = {}
+
+ # PG::TextEncoder::JSON passes the `quirks_mode` keyword, which the json gem
+ # dropped in 3.0; fixed in pg upstream but unreleased as of 1.6.3 — drop
+ # this once a fixed pg version is required
+ class JsonEncoder < PG::SimpleEncoder
+ def encode(value)
+ ::JSON.generate(value)
+ end
+ end
+
+ ENCODER_MAP = {
+ "bool" => -> { PG::TextEncoder::Boolean.new },
+ "date" => -> { PG::TextEncoder::Date.new },
+ "float8" => -> { PG::TextEncoder::Float.new },
+ "inet" => -> { PG::TextEncoder::Inet.new },
+ "int4" => -> { PG::TextEncoder::Integer.new },
+ "int8" => -> { PG::TextEncoder::Integer.new },
+ "json" => -> { JsonEncoder.new },
+ "jsonb" => -> { JsonEncoder.new },
+ "text" => -> { PG::TextEncoder::String.new },
+ "timestamp" => -> { PG::TextEncoder::String.new },
+ "uuid" => -> { PG::TextEncoder::String.new },
+ "varchar" => -> { PG::TextEncoder::String.new },
+ "int4range" => -> { PG::TextEncoder::String.new },
+ "inet[]" => -> { PG::TextEncoder::Array.new(name: "inet") },
+ "int4[]" => -> { PG::TextEncoder::Array.new(name: "int4") },
+ "int8[]" => -> { PG::TextEncoder::Array.new(name: "int8") },
+ "text[]" => -> { PG::TextEncoder::Array.new(name: "text") },
+ "varchar[]" => -> { PG::TextEncoder::Array.new(name: "varchar") },
+ }
+
+ def self.get_encoder(pg_type)
+ pg_type = normalize_pg_type(pg_type)
+
+ @encoders[pg_type] ||= begin
+ factory = ENCODER_MAP[pg_type]
+ raise "Unsupported PG type #{pg_type}" unless factory
+
+ factory.call
+ end
+ end
+
+ def self.normalize_pg_type(pg_type)
+ pg_type.start_with?("_") ? "#{pg_type[1..]}[]" : pg_type
+ end
+ end
+ end
+end
diff --git a/migrations/importer/spec/lib/migrations/importer/pg_encoder_cache_spec.rb b/migrations/importer/spec/lib/migrations/importer/pg_encoder_cache_spec.rb
new file mode 100644
index 00000000000..5d08c77d8ca
--- /dev/null
+++ b/migrations/importer/spec/lib/migrations/importer/pg_encoder_cache_spec.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+RSpec.describe Migrations::Importer::PgEncoderCache do
+ describe "JsonEncoder" do
+ subject(:encoder) { described_class::JsonEncoder.new }
+
+ it "encodes hashes, arrays and scalars as JSON" do
+ expect(encoder.encode({ "a" => 1 })).to eq('{"a":1}')
+ expect(encoder.encode([1, "two", nil])).to eq('[1,"two",null]')
+ expect(encoder.encode("plain")).to eq('"plain"')
+ expect(encoder.encode(42)).to eq("42")
+ end
+
+ it "encodes non-ASCII text without escaping" do
+ expect(encoder.encode({ "name" => "Müller" })).to eq('{"name":"Müller"}')
+ end
+ end
+
+ describe ".get_encoder" do
+ it "returns the JSON encoder for json and jsonb" do
+ expect(described_class.get_encoder("json")).to be_a(described_class::JsonEncoder)
+ expect(described_class.get_encoder("jsonb")).to be_a(described_class::JsonEncoder)
+ end
+
+ it "normalizes PG's internal array type names" do
+ expect(described_class.get_encoder("_int4")).to be_a(PG::TextEncoder::Array)
+ end
+
+ it "fails fast on unmapped types" do
+ expect { described_class.get_encoder("tsvector") }.to raise_error(
+ RuntimeError,
+ /Unsupported PG type tsvector/,
+ )
+ end
+ end
+
+ it "still needs JsonEncoder instead of PG::TextEncoder::JSON" do
+ # whether PG::TextEncoder::JSON raises depends on the loaded json version,
+ # so check what pg ships instead of calling it
+ encode_source_path = PG::TextEncoder::JSON.instance_method(:encode).source_location&.first
+
+ expect(encode_source_path).not_to be_nil,
+ "PG::TextEncoder::JSON#encode is no longer plain Ruby — " \
+ "check whether JsonEncoder is still needed"
+ expect(File.read(encode_source_path)).to include("quirks_mode"),
+ "the installed pg no longer passes quirks_mode — " \
+ "replace JsonEncoder with PG::TextEncoder::JSON and delete this example"
+ end
+end