neo4j_bolt 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f9f38fc0e16014ae13f2f31d2ba77f119185249821da7d4f7858fa0ef3f9010f
4
- data.tar.gz: 5ab718f1dd9829aa1f118a6614f7d29d184d63eb20b4ce7d3e36fc92fea5f204
3
+ metadata.gz: 388dd7f6a3d0b491052bc844c0cd45bbaeb71eef90c1cdb3d93717167afe668a
4
+ data.tar.gz: 40ba4fbcd3dd14ec31cdc5672f6854681de6fe4d1e3de0643acd11effed3366f
5
5
  SHA512:
6
- metadata.gz: df61ebc16c46698ccab04c94e9a8abd6120ef07d899b7e52e8e9a80d13bcc4b2f8d17bddff330f6d10ff794faabd705ebfba3d3531fdad311cb8ea5de02dbc8c
7
- data.tar.gz: 6522b70e44f279f182c289ae3397dafd11d5dff4e72a3437247a5f25bd66d4185e6696b2aa2c96bce976f518d63a30c98c48ea86b2823d28383c3989df24b7eb
6
+ metadata.gz: 217aa1229a23d9bbcfabe4fd6977bd24e4988bcabbb34093627cb8fc8707457b1886694a9082edc9d65987108ef77fc2b70d4ba53f7d58810fd85f2e269d4da6
7
+ data.tar.gz: 1c74dd4f9d10e8ebb9dffa78cbef3375ba23d7e9223bec7c72d7f11baa6b416f53988e824ca0a798ee37b5461122476f2e3b6e4b586417a2aa29790b48b4fa7a
data/README.md CHANGED
@@ -4,14 +4,14 @@ Neo4jBolt 0.4 is a small compatibility and convenience layer for Ruby applicatio
4
4
 
5
5
  Neo4jBolt no longer implements the Bolt wire protocol itself.
6
6
 
7
- `0.5.0` requires Ruby 3.4 or newer and pins `neo4j-ruby-driver` to `6.2.1.beta.4`. Applications on older Rubies can remain on the Neo4jBolt 0.3.x line; this prerelease is intentionally not an automatic upgrade for them.
7
+ `0.5.2` requires Ruby 3.4 or newer and pins `neo4j-ruby-driver` to `6.2.1.beta.4`. Applications on older Rubies can remain on the Neo4jBolt 0.3.x line; this prerelease is intentionally not an automatic upgrade for them.
8
8
 
9
9
  ## Installation
10
10
 
11
11
  For this prerelease, specify the version explicitly:
12
12
 
13
13
  ```ruby
14
- gem "neo4j_bolt", "0.5.0"
14
+ gem "neo4j_bolt", "0.5.1"
15
15
  ```
16
16
 
17
17
  Then run `bundle install`. A running Neo4j database is required.
@@ -89,6 +89,12 @@ row = neo4j_query_expect_one(
89
89
 
90
90
  `neo4j_query_expect_one` raises `Neo4jBolt::ExpectedOneResultError` unless the query produces exactly one row.
91
91
 
92
+ String parameters always go to Neo4j as strings, whatever their Ruby encoding, as in 0.3. That matters for values taken from a Rack request: paths, query strings and headers arrive as binary (ASCII-8BIT) strings, which the upstream driver alone would send as byte arrays. Binary strings that are valid UTF-8 are sent as UTF-8 strings, strings in other encodings are converted, and a binary string that is not valid UTF-8 raises `Neo4jBolt::InvalidStringParameterError`. To store a byte array, wrap the data explicitly:
93
+
94
+ ```ruby
95
+ neo4j_query("CREATE (:Blob {data: $data})", data: Neo4jBolt::Bytes.new(binary_string))
96
+ ```
97
+
92
98
  ### Result compatibility
93
99
 
94
100
  Result-row keys are strings:
@@ -218,6 +224,8 @@ neo4j_bolt dump --data-only -o data.dump
218
224
  neo4j_bolt load --data-only database.dump
219
225
  ```
220
226
 
227
+ Property values that JSON cannot express keep their type: dates, datetimes, local datetimes, local times, times, durations and points are written as maps tagged with `"$neo4j"`, for example `{"$neo4j":"date","value":"1815-12-10"}`, carrying the driver's own fields so that loading restores the exact value, and a readable `value` where there is one. Neo4j properties are never maps, so a tagged map cannot clash with an ordinary value; older dumps, which wrote such values as strings, still load as before. A datetime with a named zone (`[Europe/Berlin]`) comes back with its offset only, as the driver reads it that way.
228
+
221
229
  The `0, 1, 2, ...` IDs are synthetic dump-local IDs. Database-internal IDs and element IDs are never written to the persistent format. Dumping keeps the count, node, and relationship reads in one transaction, so the driver-provided entity identity used to connect the two streamed result sets stays within Neo4j's transaction-scoped identity guarantee. To keep dump numbering deterministic, ordering uses `elementId()` on modern Neo4j and an internal `id()` fallback only on Neo4j 4.4, where `elementId()` does not exist. Old Neo4jBolt dumps containing only `n` and `r` records remain loadable.
222
230
 
223
231
  For relational loads, the adapter assigns a random temporary label and the fixed reserved property `__neo4j_bolt_load_id` to imported nodes. After the nodes are committed it builds a temporary `neo4j_bolt_` index on that property, uses indexed lookups while creating relationships, drops the index, and removes the temporary metadata in batches. The fixed property key is reused by every load instead of registering a new random property-key token each time. Neo4j can keep the property key registered after all values have been removed, so it may remain visible in Browser's property-key list; no imported node retains the property after successful cleanup. Relational loads refuse to run if the dump itself, or existing data during `force_append`, currently uses the reserved property. No database-internal identity is carried from one load transaction to another. Loading a relational dump therefore requires permission to create and drop an index.
@@ -257,7 +265,7 @@ The complete integration suite is run against both Community and Enterprise for
257
265
  - `neo4j:2026.06.0-community`
258
266
  - `neo4j:2026.06.0-enterprise`
259
267
 
260
- No compatibility beyond this matrix is claimed for `0.5.0`.
268
+ No compatibility beyond this matrix is claimed for `0.5.1`.
261
269
 
262
270
  Enterprise test containers are started with `NEO4J_ACCEPT_LICENSE_AGREEMENT=yes`. The Community targets verify that Community-compatible features remain portable; the Enterprise targets additionally exercise successful node-key dump/load instead of merely observing that Community rejects node keys.
263
271
 
@@ -297,6 +305,15 @@ To point RSpec itself at an already disposable database, set `NEO4J_BOLT_TEST_HO
297
305
  | CLI commands | Preserved |
298
306
  | `BoltSocket`, `BoltBuffer`, protocol markers/state/parser/packer | Intentionally removed private implementation details |
299
307
 
308
+ ## 0.5.2
309
+
310
+ - String parameters are sent as strings again, whatever their Ruby encoding (0.3 behavior). In 0.5.0/0.5.1 a binary (ASCII-8BIT) String – which is how Rack passes request paths, query strings and headers – went to Neo4j as a byte array: a lookup by a value from the URL matched nothing, and values from headers were stored as byte arrays. Byte arrays now need `Neo4jBolt::Bytes`; a binary string that is not valid UTF-8 raises `Neo4jBolt::InvalidStringParameterError`.
311
+ - Fork safety: a process forked after Neo4j was used (puma with workers and preloading, unicorn, …) inherited the parent's driver and hung on its first query. The child now drops the inherited driver (without closing the parent's connections) and opens its own, via `Process._fork`.
312
+
313
+ ## 0.5.1
314
+
315
+ - Dumps keep dates, datetimes, local datetimes, local times, times, durations and points; before, they were written as text and came back as strings. Older dumps load as before.
316
+
300
317
  ## 0.5.0 migration notes
301
318
 
302
319
  - Ruby 3.4 or newer is required; Ruby 2.x/3.0–3.3 applications should stay on 0.3.x until upgraded.
@@ -1,3 +1,3 @@
1
1
  module Neo4jBolt
2
- VERSION = "0.5.0"
2
+ VERSION = "0.5.2"
3
3
  end
data/lib/neo4j_bolt.rb CHANGED
@@ -1,9 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "date"
3
4
  require "json"
4
5
  require "securerandom"
5
6
  require "set"
6
7
  require "thread"
8
+ require "time"
7
9
  require "uri"
8
10
  require "neo4j/driver"
9
11
  require "neo4j_bolt/version"
@@ -20,6 +22,10 @@ module Neo4jBolt
20
22
  LOAD_PROGRESS_STEP = 5_000
21
23
  DUMP_PROGRESS_STEP = 1_000
22
24
  LOAD_ID_PROPERTY = "__neo4j_bolt_load_id"
25
+ # Dumps write temporal and spatial property values as maps tagged with
26
+ # this key. Neo4j properties are never maps, so a tagged map cannot be an
27
+ # ordinary value, and dumps without such values read as before.
28
+ DUMP_TYPE_KEY = "$neo4j"
23
29
  private_constant :LOAD_MEMORY_ERROR_CODES, :LOAD_MEMORY_GQL_STATUSES,
24
30
  :LOAD_PROGRESS_STEP, :DUMP_PROGRESS_STEP, :LOAD_ID_PROPERTY
25
31
 
@@ -237,6 +243,7 @@ module Neo4jBolt
237
243
  class SyntaxError < Error; end
238
244
  class ConstraintValidationFailedError < Error; end
239
245
  class ExpectedOneResultError < Error; end
246
+ class InvalidStringParameterError < Error; end
240
247
 
241
248
  class Node < Hash
242
249
  attr_reader :id, :labels, :element_id
@@ -268,6 +275,26 @@ module Neo4jBolt
268
275
 
269
276
  TransactionContext = Struct.new(:session, :transaction, :depth, :rollback_only, keyword_init: true)
270
277
 
278
+ # A byte array query parameter. Plain Ruby strings are always sent as
279
+ # strings, whatever their encoding (as in 0.3); wrap binary data in Bytes
280
+ # to store a Neo4j byte array.
281
+ class Bytes
282
+ attr_reader :data
283
+
284
+ def initialize(data)
285
+ @data = String(data).b.freeze
286
+ end
287
+
288
+ def ==(other)
289
+ other.is_a?(Bytes) && other.data == data
290
+ end
291
+ alias eql? ==
292
+
293
+ def hash
294
+ [Bytes, data].hash
295
+ end
296
+ end
297
+
271
298
  # Owns one process-wide upstream driver and its connection pool. Leases let
272
299
  # cleanup wait for in-flight sessions without serializing independent queries.
273
300
  module DriverRegistry
@@ -281,6 +308,25 @@ module Neo4jBolt
281
308
  release if driver
282
309
  end
283
310
 
311
+ # Called in a child process right after fork (see ForkHook). The child
312
+ # inherits the parent's driver object, but not the threads that serve
313
+ # its connections, and the sockets belong to the parent: using it hangs,
314
+ # closing it would disturb the parent. So the child forgets it (and the
315
+ # synchronization state, which another parent thread may have held) and
316
+ # opens its own driver on first use.
317
+ def after_fork
318
+ @mutex = Mutex.new
319
+ @condition = ConditionVariable.new
320
+ @driver = nil
321
+ @leases = 0
322
+ @closing = false
323
+ @pid = Process.pid
324
+ end
325
+
326
+ def forked?
327
+ !@pid.nil? && @pid != Process.pid
328
+ end
329
+
284
330
  def cleanup
285
331
  if Thread.current.thread_variable_get(LEASE_KEY).to_i.positive?
286
332
  raise Error, "cleanup_neo4j cannot run while this thread is using Neo4j"
@@ -310,8 +356,12 @@ module Neo4jBolt
310
356
  private
311
357
 
312
358
  def acquire
359
+ # second line of defence if the fork hook didn't run (e.g. a fork
360
+ # through a path that bypasses Process._fork)
361
+ after_fork if forked?
313
362
  driver = mutex.synchronize do
314
363
  condition.wait(mutex) while @closing
364
+ @pid ||= Process.pid
315
365
  @driver ||= build_driver
316
366
  @leases = leases + 1
317
367
  @driver
@@ -367,6 +417,18 @@ module Neo4jBolt
367
417
  end
368
418
  end
369
419
 
420
+ # Preloading servers (puma with workers, unicorn, ...) load the app, which
421
+ # may already have queried Neo4j, and then fork. Process._fork (Ruby >= 3.1)
422
+ # runs for every fork; in the child, the inherited driver is dropped.
423
+ module ForkHook
424
+ def _fork
425
+ pid = super
426
+ DriverRegistry.after_fork if pid.zero?
427
+ pid
428
+ end
429
+ end
430
+ Process.singleton_class.prepend(ForkHook)
431
+
370
432
  class << self
371
433
  attr_reader :bolt_host, :bolt_port, :bolt_username, :bolt_password
372
434
  attr_accessor :bolt_verbosity, :bolt_database
@@ -441,6 +503,7 @@ module Neo4jBolt
441
503
 
442
504
  def neo4j_query(query, data = {}, &block)
443
505
  validate_parameters!(data)
506
+ data = normalize_parameters(data)
444
507
  log_query(query, data)
445
508
 
446
509
  context = transaction_context
@@ -618,7 +681,7 @@ module Neo4jBolt
618
681
  "ORDER BY #{identity_function}(n)"
619
682
  ) do |row|
620
683
  dump_ids[row["identity"].to_s] = dumped_nodes if dump_ids
621
- io.puts "n #{JSON.generate(id: dumped_nodes, labels: row["labels"], properties: row["properties"])}"
684
+ io.puts "n #{JSON.generate(id: dumped_nodes, labels: row["labels"], properties: encode_dump_properties(row["properties"]))}"
622
685
  dumped_nodes += 1
623
686
  if (dumped_nodes % DUMP_PROGRESS_STEP).zero?
624
687
  progress.update(progress_message(
@@ -638,7 +701,7 @@ module Neo4jBolt
638
701
  from: dump_ids.fetch(row["from_identity"].to_s),
639
702
  to: dump_ids.fetch(row["to_identity"].to_s),
640
703
  type: row["type"],
641
- properties: row["properties"]
704
+ properties: encode_dump_properties(row["properties"])
642
705
  )}"
643
706
  dumped_relationships += 1
644
707
  if (dumped_relationships % DUMP_PROGRESS_STEP).zero?
@@ -899,6 +962,43 @@ module Neo4jBolt
899
962
  end
900
963
  end
901
964
 
965
+ # Strings go to Neo4j as strings, as in 0.3. The upstream driver would send
966
+ # a binary (ASCII-8BIT) String as a byte array instead – and Rack hands
967
+ # request paths, query strings and headers to the app as binary strings, so
968
+ # a query with such a value silently matched nothing ("tag" from the URL)
969
+ # or stored a byte array where a string belongs. Byte arrays now need an
970
+ # explicit Neo4jBolt::Bytes.
971
+ def normalize_parameters(value)
972
+ case value
973
+ when Bytes then value.data
974
+ when String then normalize_string_parameter(value)
975
+ when Hash
976
+ value.to_h do |key, nested_value|
977
+ [key.is_a?(String) ? normalize_string_parameter(key) : key, normalize_parameters(nested_value)]
978
+ end
979
+ when Array then value.map { |nested_value| normalize_parameters(nested_value) }
980
+ when Set then Set.new(value.map { |nested_value| normalize_parameters(nested_value) })
981
+ else value
982
+ end
983
+ end
984
+
985
+ def normalize_string_parameter(string)
986
+ return string if string.encoding == Encoding::UTF_8 && string.valid_encoding?
987
+
988
+ if [Encoding::BINARY, Encoding::US_ASCII, Encoding::UTF_8].include?(string.encoding)
989
+ utf8 = string.dup.force_encoding(Encoding::UTF_8)
990
+ return utf8 if utf8.valid_encoding?
991
+
992
+ raise InvalidStringParameterError,
993
+ "String parameter is not valid UTF-8 (#{string.bytesize} bytes); " \
994
+ "wrap binary data in Neo4jBolt::Bytes to store a byte array"
995
+ end
996
+
997
+ string.encode(Encoding::UTF_8)
998
+ rescue EncodingError => error
999
+ raise InvalidStringParameterError, "String parameter can't be converted to UTF-8: #{error.message}"
1000
+ end
1001
+
902
1002
  def raise_mapped_error(error)
903
1003
  mapped = case error.code
904
1004
  when "Neo.ClientError.Statement.SyntaxError"
@@ -1098,6 +1198,73 @@ module Neo4jBolt
1098
1198
  version.to_s.split(".").first.to_i >= 5 ? "elementId" : "id"
1099
1199
  end
1100
1200
 
1201
+ # Property values for a dump: JSON values as they are; dates, times,
1202
+ # durations and points as maps tagged with DUMP_TYPE_KEY that carry the
1203
+ # driver's own fields (so that loading restores the exact value) and, for
1204
+ # people reading the dump, the value as text.
1205
+ def encode_dump_properties(properties)
1206
+ return properties unless properties.is_a?(Hash)
1207
+
1208
+ properties.to_h { |key, value| [key, encode_dump_value(value)] }
1209
+ end
1210
+
1211
+ def encode_dump_value(value)
1212
+ tagged = ->(type, fields) { { DUMP_TYPE_KEY => type }.merge(fields) }
1213
+ case value
1214
+ when Array
1215
+ value.map { |item| encode_dump_value(item) }
1216
+ when Time
1217
+ tagged.call("datetime", "value" => value.iso8601(9))
1218
+ when DateTime
1219
+ tagged.call("datetime", "value" => value.to_time.iso8601(9))
1220
+ when Date
1221
+ tagged.call("date", "value" => value.iso8601)
1222
+ when Neo4j::Driver::Types::LocalDateTime
1223
+ tagged.call("local_datetime", "epoch_seconds" => value.epoch_seconds, "nanoseconds" => value.nanoseconds,
1224
+ "value" => value.to_s)
1225
+ when Neo4j::Driver::Types::LocalTime
1226
+ tagged.call("local_time", "nanoseconds" => value.nanoseconds, "value" => value.to_s)
1227
+ when Neo4j::Driver::Types::OffsetTime
1228
+ tagged.call("time", "nanoseconds" => value.nanoseconds, "tz_offset_seconds" => value.tz_offset_seconds,
1229
+ "value" => value.to_s)
1230
+ when Neo4j::Driver::Types::Duration
1231
+ tagged.call("duration", "months" => value.months, "days" => value.days, "seconds" => value.seconds,
1232
+ "nanoseconds" => value.nanoseconds, "value" => value.to_s)
1233
+ when Neo4j::Driver::Types::Point
1234
+ tagged.call("point", { "srid" => value.srid, "x" => value.x, "y" => value.y, "z" => value.z }.compact)
1235
+ else
1236
+ value
1237
+ end
1238
+ end
1239
+
1240
+ def decode_dump_properties(properties)
1241
+ return properties unless properties.is_a?(Hash)
1242
+
1243
+ properties.to_h { |key, value| [key, decode_dump_value(value)] }
1244
+ end
1245
+
1246
+ def decode_dump_value(value)
1247
+ return value.map { |item| decode_dump_value(item) } if value.is_a?(Array)
1248
+ return value unless value.is_a?(Hash) && value.key?(DUMP_TYPE_KEY)
1249
+
1250
+ case value[DUMP_TYPE_KEY]
1251
+ when "datetime" then Time.iso8601(value.fetch("value"))
1252
+ when "date" then Date.iso8601(value.fetch("value"))
1253
+ when "local_datetime"
1254
+ Neo4j::Driver::Types::LocalDateTime.new(value.fetch("epoch_seconds"), value.fetch("nanoseconds"))
1255
+ when "local_time" then Neo4j::Driver::Types::LocalTime.new(value.fetch("nanoseconds"))
1256
+ when "time" then Neo4j::Driver::Types::OffsetTime.new(value.fetch("nanoseconds"), value.fetch("tz_offset_seconds"))
1257
+ when "duration"
1258
+ Neo4j::Driver::Types::Duration.new(value.fetch("months"), value.fetch("days"), value.fetch("seconds"),
1259
+ value.fetch("nanoseconds"))
1260
+ when "point"
1261
+ Neo4j::Driver::Types::Point.new(srid: value.fetch("srid"), x: value.fetch("x"), y: value.fetch("y"),
1262
+ z: value["z"])
1263
+ else
1264
+ raise Error, "Unknown value type in dump: #{value[DUMP_TYPE_KEY].inspect}"
1265
+ end
1266
+ end
1267
+
1101
1268
  def parse_dump(io, node_batches, relationship_batches, progress = nil)
1102
1269
  node_count = 0
1103
1270
  relationship_count = 0
@@ -1116,10 +1283,12 @@ module Neo4jBolt
1116
1283
  value = JSON.parse(json)
1117
1284
  case kind
1118
1285
  when "n"
1286
+ value["properties"] = decode_dump_properties(value["properties"])
1119
1287
  labels = value.fetch("labels")
1120
1288
  node_batches[labels.sort] << value
1121
1289
  node_count += 1
1122
1290
  when "r"
1291
+ value["properties"] = decode_dump_properties(value["properties"])
1123
1292
  relationship_batches[value.fetch("type")] << value
1124
1293
  relationship_count += 1
1125
1294
  else
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: neo4j_bolt
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.0
4
+ version: 0.5.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Michael Specht