Skip to content

Commit af4da59

Browse files
authored
Merge pull request #1 from eagerworks/feat/add-json-support
feat: add json support
2 parents af3a95c + 1fafa32 commit af4da59

3 files changed

Lines changed: 42 additions & 1 deletion

File tree

lib/staging_table/bulk_inserter.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# frozen_string_literal: true
22

3+
require "json"
4+
35
module StagingTable
46
class BulkInserter
57
attr_reader :model, :batch_size
@@ -37,7 +39,12 @@ def connection
3739
end
3840

3941
def quote(value)
40-
connection.quote(value)
42+
case value
43+
when Array, Hash
44+
connection.quote(value.to_json)
45+
else
46+
connection.quote(value)
47+
end
4148
end
4249
end
4350
end

spec/staging_table/bulk_inserter_spec.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,40 @@
8888
end
8989
end
9090

91+
shared_examples "bulk inserter with JSON support" do
92+
describe "#insert with JSON" do
93+
it "handles array values for JSON/JSONB columns" do
94+
records = [
95+
{name: "John", email: "john@example.com", tags: %w[admin user]}
96+
]
97+
98+
inserter.insert(records)
99+
100+
user = staging_model.first
101+
expect(user.tags).to eq(%w[admin user])
102+
end
103+
104+
it "handles hash values for JSON/JSONB columns" do
105+
records = [
106+
{name: "John", email: "john@example.com", metadata: {role: "admin", level: 5}}
107+
]
108+
109+
inserter.insert(records)
110+
111+
user = staging_model.first
112+
expect(user.metadata).to eq({"role" => "admin", "level" => 5})
113+
end
114+
end
115+
end
116+
91117
context "with PostgreSQL", :postgresql do
92118
include_examples "bulk inserter"
119+
include_examples "bulk inserter with JSON support"
93120
end
94121

95122
context "with MySQL", :mysql do
96123
include_examples "bulk inserter"
124+
include_examples "bulk inserter with JSON support"
97125
end
98126

99127
context "with SQLite", :sqlite do

spec/support/database_helper.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,17 @@ def create_test_tables
187187
DROP TABLE IF EXISTS test_users
188188
SQL
189189

190+
json_type = /postgresql/.match?(ActiveRecord::Base.connection.adapter_name.downcase) ? "JSONB" : "JSON"
191+
190192
ActiveRecord::Base.connection.execute(<<~SQL)
191193
CREATE TABLE test_users (
192194
id SERIAL PRIMARY KEY,
193195
name VARCHAR(255),
194196
email VARCHAR(255),
195197
age INTEGER,
196198
active BOOLEAN DEFAULT true,
199+
tags #{json_type},
200+
metadata #{json_type},
197201
created_at TIMESTAMP,
198202
updated_at TIMESTAMP
199203
)
@@ -219,6 +223,8 @@ def create_sqlite_test_tables
219223
email VARCHAR(255),
220224
age INTEGER,
221225
active BOOLEAN DEFAULT 1,
226+
tags TEXT,
227+
metadata TEXT,
222228
created_at DATETIME,
223229
updated_at DATETIME
224230
)

0 commit comments

Comments
 (0)