ndb-rails 0.3.3 → 1.0.0

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: 36faa77fbcb1e44d523252eb2869a286de0e463f39b20c6f387396b87cffae96
4
- data.tar.gz: 9e5071e77a89c1e76193c6a85e929e32d4613dd184c38fbae8ed510bf90899ab
3
+ metadata.gz: 3050b60a5fb5be69ee70851c954efaca60e5f5c52ad85c8e3917d0d8ba005a43
4
+ data.tar.gz: 42814105f52fb44652386a5a9a7ba0161c40d33d6d116fb8571a4ae6d46eff36
5
5
  SHA512:
6
- metadata.gz: 41b000dbd96455396f3534c7feed13ae49a94295a01a3cdaeb411bbd44004c577e8ebdbe33400fb2f47ee8e69af43dd47b57fa071ec0aa8d4b4b421932661732
7
- data.tar.gz: c3a43e41796660a41d260063d16ab43824ec56e8bef9155eb4d89b65f6cf1b4cd57fb4d0d9f9d26fd03e8225a40638eaf68c6252e1be002ef28dc2079035b8ba
6
+ metadata.gz: 9d5bb7101f186087cef41f009a8798da501a8369f12b58b1a08c1b1a7d82b593227accded758a52af7db626906bede08f1f8b310f8db54cc9d4072dcc6cf9555
7
+ data.tar.gz: 5b30ddc17868fe213b5d013ec4b5cdbbae698048f37749d7389fda137d2ee1f38f477a61b45c5b505ea6c1f6e824a2fe75bcc08837855fa4b1d4420e96c4e8bf
data/README.md CHANGED
@@ -6,7 +6,7 @@ ActiveModel layer for [ndb](https://github.com/thadeu/ndb), an NDJSON query daem
6
6
 
7
7
  No Rails, or no models? Use the gem `ndb` alone: it has no runtime dependency.
8
8
 
9
- Docs: [client guide](https://github.com/thadeu/ndb/blob/main/docs/dev/clients.md), [query language](https://github.com/thadeu/ndb/blob/main/docs/dev/query.md), [HTTP API](https://github.com/thadeu/ndb/blob/main/docs/dev/http-api.md).
9
+ Docs: [client guide](https://github.com/thadeu/ndb/blob/main/docs/dev/clients.md), [query language](https://github.com/thadeu/ndb/blob/main/docs/dev/query.md), [HTTP API](https://github.com/thadeu/ndb/blob/main/docs/dev/http.md).
10
10
 
11
11
  ## Install
12
12
 
@@ -102,6 +102,9 @@ end
102
102
  call = Call.create!(_id: "c1", status: "answered", caller: "a", at: Time.now.utc)
103
103
  Call.create!([{ _id: "c2", status: "failed", caller: "b" }, { _id: "c3", status: "answered", caller: "c" }])
104
104
 
105
+ Call.upsert(id: "c2", status: "answered") # create by id, or merge the given attributes; no callbacks
106
+ Call.upsert_all([{ id: "c2", status: "done" }, { id: "c5", status: "new" }])
107
+
105
108
  call = Call.new(_id: "c4", status: "answered", caller: "d")
106
109
  call.save # false when invalid
107
110
  call.save! # raises Ndb::RecordInvalid
@@ -213,7 +216,25 @@ Call.where(status: "failed").exists?
213
216
  - The order of the `order` keys is the order of the sort. The id is always the last key.
214
217
  - `page(n).per(size)` sets offset paging. The default page size is 25.
215
218
  - `pluck` asks the daemon for only those fields.
216
- - There is no `explain` on a relation. Use the client: `Ndb::Rails.client.find(coll, "where" => {...}, "explain" => true)` returns a `Page` with `plan` (the `X-Ndb-Plan` header: `id`, `index:<field>`, `scan`, `snapshot`) and `examined`.
219
+ - There is no `explain` on a relation. Use the client: `Ndb::Rails.client.search(Call.collection_name, "query" => {...}, "explain" => true)` returns a `Page` with `plan` (the `X-Ndb-Plan` header: `id`, `index:<field>`, `scan`, `snapshot`) and `examined`.
220
+
221
+ ### A query built elsewhere
222
+
223
+ A query from a search form or a saved search goes to `where_raw`. Its Hash is sent as it is, with no Rails conventions (an Array stays an Array, not `$in`), ANDed with the other clauses:
224
+
225
+ ```ruby
226
+ Call.where_raw("status" => "answered", "at" => { "$gte" => "now-7d" }).order(at: :desc).limit(50).to_a
227
+ ```
228
+
229
+ For a whole search body, use `Model.search`. The filter goes in `"query"`:
230
+
231
+ ```ruby
232
+ result = Call.search("query" => { "status" => "answered" }, "sort" => { "at" => -1 }, "limit" => 50, "count" => true)
233
+
234
+ result.records # Call instances
235
+ result.next_cursor # nil on the last page
236
+ result.total # with "count" => true
237
+ ```
217
238
 
218
239
  ### Regular expressions
219
240
 
@@ -289,7 +310,7 @@ page = Ndb::Rails.client.aggregate(Call.collection_name,
289
310
 
290
311
  page.rows # array of Hash
291
312
  page.total # with count: true
292
- page.next_cursor # nil on the last page
313
+ page.next # the cursor of the next page, nil on the last one
293
314
  ```
294
315
 
295
316
  `$dateTrunc` units are `minute`, `hour`, `day`, `week` and `month`. Optional `"timezone"`: a name such as `"Europe/Rome"`.
@@ -302,8 +323,8 @@ A watch streams the changes of a collection to a named consumer: first the event
302
323
  client = Ndb::Rails.client
303
324
 
304
325
  begin
305
- client.watch(Call.collection_name, "relay", where: { status: "answered" }) do |event|
306
- # event has "pos", "op" ("put", "del" or "truncate"), "_id", "v" and "doc"
326
+ client.watch(Call.collection_name, "relay", query: { status: "answered" }) do |event|
327
+ # event has "pos", "op" ("put", "del" or "truncate"), "_id", "_v" and "doc"
307
328
  handle(event)
308
329
 
309
330
  client.ack(Call.collection_name, "relay", event["pos"])
@@ -315,7 +336,7 @@ rescue Ndb::HistoryTruncated
315
336
  end
316
337
  ```
317
338
 
318
- - `where:` takes the same conditions as `where` on a model (Hash and Range). Only matching events come. A delete event has no `"doc"`; it is sent only if this stream saw an earlier matching put of that id.
339
+ - `query:` takes the same conditions as `where` on a model (Hash and Range). Only matching events come. A delete event has no `"doc"`; it is sent only if this stream saw an earlier matching put of that id.
319
340
  - `from: "now"` starts a new consumer at the end. `limit: n` ends the stream after n events.
320
341
  - Without a block, `watch` returns an Enumerator.
321
342
  - Delivery is at least once. After a restart an event can come again, so make the work safe to repeat.
@@ -376,7 +397,7 @@ rescue Ndb::RecordNotUnique => e
376
397
 
377
398
  ## Testing
378
399
 
379
- The tests of this gem build the daemon from the repository (`go build ./cmd/ndb`), start it on a short temp unix socket (macOS allows 104 bytes), wait for `GET /health` to return 200, and stop it at exit. To do the same by hand:
400
+ The tests of this gem build the daemon from the repository (`go build ./cmd/ndb`), start it on a short temp unix socket (macOS allows 104 bytes), wait for `GET /_health` to return 200, and stop it at exit. To do the same by hand:
380
401
 
381
402
  ```sh
382
403
  ndb -config /nonexistent.yml -data-dir "$(mktemp -d)" -unix /tmp/ndb-test.sock
@@ -42,9 +42,10 @@ module Ndb
42
42
  def instantiate(row)
43
43
  row = row.dup
44
44
  version = row.delete("_v")
45
+ source = row.delete("_coll")
45
46
  record = new(row.slice(*attribute_names))
46
47
 
47
- record.send(:loaded!, version)
48
+ record.send(:loaded!, version, source)
48
49
 
49
50
  record
50
51
  end
@@ -52,6 +53,10 @@ module Ndb
52
53
 
53
54
  attr_reader :version
54
55
 
56
+ # The collection a record was read from, when its model reads a
57
+ # collection pattern (self.collection_name = "logs-2026-*"); nil otherwise.
58
+ attr_reader :source_collection
59
+
55
60
  # id is an alias of _id.
56
61
  def id
57
62
  _id
@@ -200,7 +205,7 @@ module Ndb
200
205
  end
201
206
 
202
207
  def refresh_expiry(result, expires_at)
203
- @version = result["v"]
208
+ @version = result["_v"]
204
209
 
205
210
  field = self.class.expires_field
206
211
 
@@ -244,9 +249,10 @@ module Ndb
244
249
  self
245
250
  end
246
251
 
247
- def loaded!(version)
252
+ def loaded!(version, source = nil)
248
253
  @persisted = true
249
254
  @version = version
255
+ @source_collection = source if source
250
256
 
251
257
  changes_applied
252
258
  end
@@ -276,7 +282,7 @@ module Ndb
276
282
  result = self.class.ndb_insert(insert_document, expire_in: @expire_in)
277
283
 
278
284
  self.id = result["_id"] if id.nil?
279
- loaded!(result["v"])
285
+ loaded!(result["_v"])
280
286
 
281
287
  true
282
288
  end
@@ -18,9 +18,12 @@ module Ndb
18
18
 
19
19
  attribute :_id, :string
20
20
 
21
+ # The answer of Model.search.
22
+ SearchResult = Data.define(:records, :next_cursor, :total)
23
+
21
24
  class << self
22
25
  QUERY_METHODS = %i[
23
- where order limit offset page after group find find_by find_by! first count pluck exists?
26
+ where where_raw order limit offset page after group find find_by find_by! first count pluck exists?
24
27
  find_each in_batches sum average minimum maximum to_a each destroy_all delete_all
25
28
  ].freeze
26
29
 
@@ -36,6 +39,41 @@ module Ndb
36
39
  Relation.new(self)
37
40
  end
38
41
 
42
+ # Writes a document by its _id, like ActiveRecord upsert: it creates
43
+ # the document when the _id is free, and merges the given attributes
44
+ # into the stored document when it exists (the others stay). No
45
+ # validations or callbacks run. id is an alias of _id. Returns
46
+ # {"_id", "_v"}.
47
+ #
48
+ # User.upsert(id: "u1", plan: "pro")
49
+ def upsert(attributes = nil, expire_in: nil, **attrs)
50
+ upsert_all([attributes || attrs], expire_in: expire_in).first
51
+ end
52
+
53
+ # upsert for many documents in one transaction, all or nothing.
54
+ def upsert_all(attributes, expire_in: nil)
55
+ ensure_collection!
56
+
57
+ docs = attributes.map { |attrs| upsert_document(attrs) }
58
+
59
+ expire_in = expire_in.to_i if expire_in.is_a?(ActiveSupport::Duration)
60
+
61
+ Rails.client.bulk(collection_name, docs, expire_in: expire_in, upsert: true)
62
+ end
63
+
64
+ # Runs a find with a whole body built elsewhere, such as from a search
65
+ # form: { "query" => {...}, "sort" => {...}, "limit" => 50, "after" =>
66
+ # token, "count" => true }. The body is sent as is (the daemon
67
+ # validates it). Returns the records, the next cursor (nil on the last
68
+ # page) and the total (with "count" => true).
69
+ def search(body)
70
+ raise ArgumentError, "search takes a Hash, got #{body.class}" unless body.is_a?(Hash)
71
+
72
+ page = ndb_find(body.transform_keys(&:to_s))
73
+
74
+ SearchResult.new(page.rows.map { |row| instantiate(row) }, page.next, page.total)
75
+ end
76
+
39
77
  # Finds the record with these attributes, or builds an unsaved one.
40
78
  def find_or_initialize_by(attrs, &block)
41
79
  find_by(attrs) || new(attrs).tap { |record| block&.call(record) }
@@ -158,8 +196,17 @@ module Ndb
158
196
  definition
159
197
  end
160
198
 
161
- # Declares the collection once per process (and once per client).
199
+ # A collection pattern ("logs-2026-*") reads many collections and
200
+ # writes none.
201
+ def collection_pattern?
202
+ collection_name.include?("*")
203
+ end
204
+
205
+ # Declares the collection once per process (and once per client). A
206
+ # pattern declares nothing.
162
207
  def ensure_collection!
208
+ return if collection_pattern?
209
+
163
210
  client = Rails.client
164
211
 
165
212
  return if @ensured_client.equal?(client)
@@ -175,7 +222,7 @@ module Ndb
175
222
  def ndb_find(body)
176
223
  ensure_collection!
177
224
 
178
- Rails.client.find(collection_name, body.merge("versions" => true))
225
+ Rails.client.search(collection_name, body.merge("versions" => true))
179
226
  end
180
227
 
181
228
  def ndb_aggregate(body)
@@ -184,23 +231,35 @@ module Ndb
184
231
  Rails.client.aggregate(collection_name, body)
185
232
  end
186
233
 
234
+ # The given attributes, cast by their type, with id as _id.
235
+ def upsert_document(attrs)
236
+ attrs.to_h.each_with_object({}) do |(name, value), doc|
237
+ key = name.to_s == "id" ? primary_key : name.to_s
238
+ type = attribute_types[key]
239
+
240
+ doc[key] = Conditions.json_value(type ? type.serialize(type.cast(value)) : value)
241
+ end
242
+ end
243
+
187
244
  def ndb_insert(doc, expire_in: nil)
188
245
  ensure_collection!
189
246
 
190
- Rails.client.insert(collection_name, [doc], expire_in: expire_in).first
247
+ return Rails.client.insert(collection_name, doc) unless expire_in
248
+
249
+ Rails.client.bulk(collection_name, [doc], expire_in: expire_in).first
191
250
  end
192
251
 
193
- # Atomic update by filter, see Ndb::Client#update.
194
- def ndb_update(filter, ops, **options)
252
+ # Atomic update by query, see Ndb::Client#update_by.
253
+ def ndb_update(query, ops, **options)
195
254
  ensure_collection!
196
255
 
197
- Rails.client.update(collection_name, filter, ops, **options)
256
+ Rails.client.update_by(collection_name, query, ops, **options)
198
257
  end
199
258
 
200
- def ndb_delete(filter, **options)
259
+ def ndb_delete(query, **options)
201
260
  ensure_collection!
202
261
 
203
- Rails.client.delete(collection_name, filter, **options)
262
+ Rails.client.delete_by(collection_name, query, **options)
204
263
  end
205
264
 
206
265
  private
@@ -28,6 +28,15 @@ module Ndb
28
28
  add_clause(Conditions.equality(attrs))
29
29
  end
30
30
 
31
+ # A where Hash built elsewhere, such as from a search form, sent as is:
32
+ # no Rails conventions (an Array stays an Array, not $in). The daemon
33
+ # validates it. ANDed with the other clauses.
34
+ def where_raw(where)
35
+ raise ArgumentError, "where_raw takes a Hash, got #{where.class}" unless where.is_a?(Hash)
36
+
37
+ add_clause(Conditions.json_value(where))
38
+ end
39
+
31
40
  def or(other)
32
41
  clauses = [Conditions.combine(values[:where]), Conditions.combine(other.values[:where])]
33
42
 
@@ -71,7 +80,7 @@ module Ndb
71
80
  query = {}
72
81
  where = Conditions.combine(values[:where])
73
82
 
74
- query["where"] = where unless where.empty?
83
+ query["query"] = where unless where.empty?
75
84
  query["sort"] = values[:order] unless values[:order].empty?
76
85
  query.merge!(window)
77
86
  query["after"] = values[:after] if values[:after]
@@ -139,7 +148,7 @@ module Ndb
139
148
  def next_cursor
140
149
  load
141
150
 
142
- @result.next_cursor
151
+ @result.next
143
152
  end
144
153
 
145
154
  def first(count = nil)
@@ -170,7 +179,7 @@ module Ndb
170
179
  end
171
180
 
172
181
  def exists?
173
- klass.ndb_find(to_query.slice("where").merge("limit" => 1, "fields" => [klass.primary_key])).rows.any?
182
+ klass.ndb_find(to_query.slice("query").merge("limit" => 1, "fields" => [klass.primary_key])).rows.any?
174
183
  end
175
184
 
176
185
  def pluck(*fields)
@@ -189,7 +198,7 @@ module Ndb
189
198
  def count
190
199
  return calculate(:count) unless values[:group].empty?
191
200
 
192
- klass.ndb_find(to_query.slice("where").merge("count" => true, "limit" => 1, "fields" => [klass.primary_key])).total
201
+ klass.ndb_find(to_query.slice("query").merge("count" => true, "limit" => 1, "fields" => [klass.primary_key])).total
193
202
  end
194
203
 
195
204
  # Pagination
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "0.3.3"
5
+ VERSION = "1.0.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ndb-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.3
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - thadeu
@@ -43,14 +43,14 @@ dependencies:
43
43
  requirements:
44
44
  - - "~>"
45
45
  - !ruby/object:Gem::Version
46
- version: '0.1'
46
+ version: '1.0'
47
47
  type: :runtime
48
48
  prerelease: false
49
49
  version_requirements: !ruby/object:Gem::Requirement
50
50
  requirements:
51
51
  - - "~>"
52
52
  - !ruby/object:Gem::Version
53
- version: '0.1'
53
+ version: '1.0'
54
54
  description: Ndb::Record, a lazy Relation, validations, blobs and a Rails railtie
55
55
  on top of the ndb client gem. The gem only builds JSON; the daemon decides every
56
56
  query semantic.