ndb-rails 0.1.1 → 0.2.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: 93088e1e11be89558d972761a9e2a7a565d617f165b90361e732240ee92c9361
4
- data.tar.gz: e9e5eca9058d1bfa6ea840c4cc8fb17c734c69d5373b933f48b1d3dfb968ebfd
3
+ metadata.gz: bb7f5cac245eb4d62f7eb1890ddf40a2e7bc872630c6b5bc4758be1c09c09e86
4
+ data.tar.gz: 2a351c29f299b42965287fb00a07ebf68fe54bdd6988c9421ba4997fc8f54412
5
5
  SHA512:
6
- metadata.gz: c509825a020a9efff7a220a3fbbb842bde284f32c66d66368948234de6aa258585a0cac17b4da57feb1ff44b123fbf5c8d6cde8f998978f51aa406500cbb10ee
7
- data.tar.gz: 853957c1575a0653c04f91bd8f16efb65415cd42656ab5a9de44f39360820d434d63d2df2a54301ec1964805c4b286dcdde969f04fefe54b79ebd5b6784452ed
6
+ metadata.gz: 006a728e18fa51557fb31e64c9cc79ef9762b2340d6d5039fedc568314a91d1fc3c86a1f3f0ba28eb0109655df8879e6a09592b748827972213e99b9076365e8
7
+ data.tar.gz: 48ff4b9592b55347c772afd63d894dea900b79341e47126b38c5250f31c2917fda477f0dd8e9df36db925afb734f61d4a0c4a767ebac91feb8798072e6c7d438
data/README.md CHANGED
@@ -69,8 +69,6 @@ end
69
69
 
70
70
  ```ruby
71
71
  class Call < Ndb::Record
72
- primary_key :call_id
73
-
74
72
  attribute :status, :string, index: true
75
73
  attribute :caller, :string, unique: true
76
74
  attribute :duration, :integer
@@ -84,7 +82,7 @@ end
84
82
 
85
83
  | Option or method | Meaning |
86
84
  |---|---|
87
- | `primary_key :call_id` | The id field. Default is `_id` (a string, made by the daemon). |
85
+ | `_id` / `id` | The primary key is always `_id` (a string; the daemon makes a UUIDv7 when it is empty). `id` is an alias of `_id`. For a natural key (email, SKU) keep `_id` and use `unique: true` on that attribute. |
88
86
  | `index: true` | Index this field. |
89
87
  | `unique: true` | Unique value. A second one raises `RecordNotUnique`. |
90
88
  | `time: true` | The collection time field. Used by zone maps, `$dateTrunc` and TTL. |
@@ -101,10 +99,10 @@ end
101
99
  ## Insert, find, update, delete
102
100
 
103
101
  ```ruby
104
- call = Call.create!(call_id: "c1", status: "answered", caller: "a", at: Time.now.utc)
105
- Call.create!([{ call_id: "c2", status: "failed", caller: "b" }, { call_id: "c3", status: "answered", caller: "c" }])
102
+ call = Call.create!(_id: "c1", status: "answered", caller: "a", at: Time.now.utc)
103
+ Call.create!([{ _id: "c2", status: "failed", caller: "b" }, { _id: "c3", status: "answered", caller: "c" }])
106
104
 
107
- call = Call.new(call_id: "c4", status: "answered", caller: "d")
105
+ call = Call.new(_id: "c4", status: "answered", caller: "d")
108
106
  call.save # false when invalid
109
107
  call.save! # raises Ndb::RecordInvalid
110
108
 
@@ -112,13 +110,38 @@ call = Call.find("c1") # raises Ndb::NotFound
112
110
  Call.find_by(status: "failed") # nil when missing
113
111
  Call.find_by!(status: "x") # raises NotFound
114
112
 
115
- call.update!(status: "done") # sends only the changed fields
113
+ call.update!(status: "done") # $set of the changed fields only, filtered by id and version
116
114
  call.version # the document version
117
115
 
118
- call.destroy
116
+ call.increment!(:duration) # atomic $inc on the daemon, refreshes the attribute and the version
117
+ call.decrement!(:duration, 5)
118
+
119
+ call.destroy # callbacks, filtered by id and version
120
+ call.destroy! # raises Ndb::RecordNotDestroyed when a before_destroy callback aborts
121
+ call.delete # by id only: no callbacks, no version guard
122
+
123
+ Call.destroy("c1") # find, destroy, return the record (an Array of ids returns an Array)
124
+ Call.delete(["c2", "c3"]) # one delete by id, no callbacks, returns the count
125
+
126
+ # Dynamic finders, for declared attributes and id. The ! variant raises NotFound.
127
+ Call.find_by_status("failed")
128
+ Call.find_by_status_and_caller("failed", "a")
129
+ Call.where(caller: "a").find_by_status!("failed")
130
+
131
+ Call.find_or_initialize_by(_id: "c9") { |c| c.status = "new" } # unsaved when missing
132
+ Call.find_or_create_by(_id: "c9") { |c| c.status = "new" } # atomic: concurrent callers get one document
133
+ Call.find_or_create_by!(_id: "c9", status: "new") # raises RecordInvalid
134
+
135
+ # Atomic writes on every match of a where (it needs the id or an indexed field).
136
+ # update takes the operators of the client and returns the number of modified documents.
137
+ Call.where(status: "failed").update({ "$set" => { "status" => "retry" } })
138
+ Call.where(status: "retry").delete_all # one delete, no callbacks, returns how many (delete is an alias)
139
+ Call.where(status: "retry").destroy_all # loads and destroys each record with its callbacks, returns them
119
140
  ```
120
141
 
121
- - Every load asks for the version (`_v`). `save`, `update` and `destroy` send it back as `if_version`. If another writer changed the document first, you get `Ndb::StaleObjectError` (code `version_conflict`).
142
+ - Every load asks for the version (`_v`). `save`, `update` and `destroy` put the id and `_v` in the filter of the write. If another writer changed the document first, the filter matches nothing and you get `Ndb::StaleObjectError` (code `stale_object`).
143
+ - `find_or_create_by` is atomic. It checks validations and runs the `save` and `create` callbacks, then sends one upsert: the attributes you pass are the filter, and the other attributes go in `$setOnInsert`, so a writer that created the document first is never overwritten and you get that document. An invalid record is returned unsaved (the `!` form raises `Ndb::RecordInvalid`). Only the attributes you pass must be equality values.
144
+ - `delete_all` and `destroy_all` on a model without a `where` are refused by the daemon (`Ndb::EmptyFilter`); `delete_all` needs the id or an indexed field in the `where`.
122
145
  - Setting an attribute to `nil` and saving removes the field from the document.
123
146
  - A duplicate id raises `RecordNotUnique` (code `duplicate_id`).
124
147
  - `persisted?`, `new_record?`, `destroyed?`, `id` and `version` work as in ActiveRecord.
@@ -138,13 +161,11 @@ Give the model an `expires: true` attribute. The daemon sets it for you.
138
161
 
139
162
  ```ruby
140
163
  class Session < Ndb::Record
141
- primary_key :sid
142
-
143
164
  attribute :user, :string
144
165
  attribute :expires_at, :datetime, expires: true
145
166
  end
146
167
 
147
- Session.create!({ sid: "s1", user: "u" }, expire_in: 1.hour) # also create, save, update (seconds, a Duration or "30m")
168
+ Session.create!({ _id: "s1", user: "u" }, expire_in: 1.hour) # also create, save, update (seconds, a Duration or "30m")
148
169
  session = Session.find("s1")
149
170
 
150
171
  session.expire(30.minutes) # EXPIRE: sets expires_at in the object, other unsaved changes stay
@@ -176,18 +197,18 @@ Call.where(status: "failed").or(Call.where(duration: 60..))
176
197
  Call.where("$or" => [{ status: "failed" }, { duration: { "$gt" => 50 } }])
177
198
 
178
199
  Call.where(status: "answered")
179
- .order(at: :desc, call_id: :asc)
200
+ .order(at: :desc, _id: :asc)
180
201
  .limit(50)
181
202
  .offset(100)
182
203
  .to_a
183
204
 
184
- Call.where(status: "answered").pluck(:call_id) # one field: an array of values
185
- Call.where(status: "answered").pluck(:call_id, :status) # several: an array of arrays
205
+ Call.where(status: "answered").pluck(:_id) # one field: an array of values
206
+ Call.where(status: "answered").pluck(:_id, :status) # several: an array of arrays
186
207
  Call.where(status: "answered").first(5)
187
208
  Call.where(status: "failed").exists?
188
209
  ```
189
210
 
190
- - Chained `where` calls are ANDed. `$regex` does not exist in the daemon yet. See the [query language](https://github.com/thadeu/ndb/blob/main/docs/dev/query.md) for the full operator list.
211
+ - Chained `where` calls are ANDed. See the [query language](https://github.com/thadeu/ndb/blob/main/docs/dev/query.md) for the full operator list.
191
212
  - The order of the `order` keys is the order of the sort. The id is always the last key.
192
213
  - `page(n).per(size)` sets offset paging. The default page size is 25.
193
214
  - `pluck` asks the daemon for only those fields.
@@ -215,11 +236,11 @@ Call.where(status: "answered").count
215
236
  ### Cursor pagination
216
237
 
217
238
  ```ruby
218
- relation = Call.where(status: "answered").order(:call_id).limit(100)
239
+ relation = Call.where(status: "answered").order(:_id).limit(100)
219
240
  rows = relation.to_a
220
241
  token = relation.next_cursor # nil on the last page
221
242
 
222
- Call.where(status: "answered").order(:call_id).limit(100).after(token).to_a
243
+ Call.where(status: "answered").order(:_id).limit(100).after(token).to_a
223
244
  ```
224
245
 
225
246
  A token works only with the same `where` and `order`. Another query shape raises `InvalidCursor`.
@@ -227,7 +248,7 @@ A token works only with the same `where` and `order`. Another query shape raises
227
248
  To walk every row, use `find_each`. It follows the cursor in batches (default 1000):
228
249
 
229
250
  ```ruby
230
- Call.where(status: "answered").find_each(batch_size: 500) { |call| puts call.call_id }
251
+ Call.where(status: "answered").find_each(batch_size: 500) { |call| puts call._id }
231
252
 
232
253
  Call.in_batches(of: 500) { |batch| batch.each { |call| ... } }
233
254
  ```
@@ -281,7 +302,7 @@ client = Ndb::Rails.client
281
302
 
282
303
  begin
283
304
  client.watch(Call.collection_name, "relay", where: { status: "answered" }) do |event|
284
- # event has "pos", "op" ("put" or "del"), "id", "v" and "doc"
305
+ # event has "pos", "op" ("put" or "del"), "_id", "v" and "doc"
285
306
  handle(event)
286
307
 
287
308
  client.ack(Call.collection_name, "relay", event["pos"])
@@ -305,7 +326,7 @@ end
305
326
  Large values live in the blob store. The document keeps only a reference (`$blob`, `size`, `type`).
306
327
 
307
328
  ```ruby
308
- call = Call.new(call_id: "c1", status: "answered", caller: "a",
329
+ call = Call.new(_id: "c1", status: "answered", caller: "a",
309
330
  recording: File.open("call.wav")) # an IO or a String
310
331
  call.save! # uploads the blob, then saves
311
332
 
@@ -321,7 +342,7 @@ A blob behaves like a read-only IO (`read`, `each_chunk`, `eof?`, `rewind`). A l
321
342
 
322
343
  ## Errors
323
344
 
324
- The transport and daemon errors are defined by the gem `ndb`. They all live in the `Ndb` module (`Ndb::Error`, `Ndb::NotFound`, ...). For an ActiveRecord-like `rescue`, this gem adds two aliases: `Ndb::StaleObjectError` is `Ndb::VersionConflict`, and `Ndb::RecordNotUnique` is `Ndb::UniqueViolation`. They are the same classes, so a `rescue` of either name catches the same error. `Ndb::RecordInvalid` and `Ndb::RecordNotSaved` exist only here, and they inherit from `Ndb::Error`. Every error has `code` (the daemon code) and `status` (the HTTP status).
345
+ The transport and daemon errors are defined by the gem `ndb`. They all live in the `Ndb` module (`Ndb::Error`, `Ndb::NotFound`, ...). For an ActiveRecord-like `rescue`, this gem adds one alias: `Ndb::RecordNotUnique` is `Ndb::UniqueViolation` (the same class). `Ndb::StaleObjectError`, `Ndb::RecordInvalid` and `Ndb::RecordNotSaved` exist only here, and they inherit from `Ndb::Error`. Every error has `code` (the daemon code) and `status` (the HTTP status).
325
346
 
326
347
  | Class | Code |
327
348
  |---|---|
@@ -329,7 +350,8 @@ The transport and daemon errors are defined by the gem `ndb`. They all live in t
329
350
  | `NotReady` | `not_ready` |
330
351
  | `NotFound` | `not_found` |
331
352
  | `UnknownCollection` | `unknown_collection` |
332
- | `StaleObjectError` | `version_conflict` |
353
+ | `StaleObjectError` | `stale_object` (raised by the gem, not sent by the daemon) |
354
+ | `InvalidUpdate` and its subclasses | `unknown_operator`, `no_update`, `conflicting_update`, `invalid_field`, `unindexed_many`, `empty_filter` |
333
355
  | `RecordNotUnique` | `unique_violation`, `duplicate_id` |
334
356
  | `CatalogConflict` | `catalog_conflict` |
335
357
  | `CatalogInvalid` | `catalog_invalid` |
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # find_by_<attr>(value) and find_by_<a>_and_<b>(v1, v2), with a ! variant
5
+ # that raises Ndb::NotFound. Only declared attribute names (and id) work;
6
+ # any other name is a normal NoMethodError.
7
+ #
8
+ # The including object answers dynamic_finder_klass (the model) and
9
+ # dynamic_finder_scope (what find_by runs on).
10
+ module DynamicFinders
11
+ PATTERN = /\Afind_by_(.+?)(!)?\z/
12
+ AND = "_and_"
13
+
14
+ def method_missing(name, *args, &)
15
+ attrs, bang = dynamic_finder(name)
16
+
17
+ return super unless attrs
18
+
19
+ define_dynamic_finder(name, attrs, bang)
20
+
21
+ run_dynamic_finder(attrs, bang, args)
22
+ end
23
+
24
+ def respond_to_missing?(name, include_private = false)
25
+ dynamic_finder(name) ? true : super
26
+ end
27
+
28
+ private
29
+
30
+ def run_dynamic_finder(attrs, bang, args)
31
+ unless args.size == attrs.size
32
+ raise ArgumentError, "wrong number of arguments (given #{args.size}, expected #{attrs.size})"
33
+ end
34
+
35
+ conditions = attrs.map { |name| name == "id" ? "_id" : name }.zip(args).to_h
36
+ scope = dynamic_finder_scope
37
+
38
+ bang ? scope.find_by!(conditions) : scope.find_by(conditions)
39
+ end
40
+
41
+ # The method is cached on the singleton class of a model. A relation is
42
+ # short-lived, so it runs the finder without caching.
43
+ def define_dynamic_finder(name, attrs, bang)
44
+ return unless is_a?(Class)
45
+
46
+ define_singleton_method(name) { |*args| run_dynamic_finder(attrs, bang, args) }
47
+ end
48
+
49
+ def dynamic_finder(name)
50
+ match = PATTERN.match(name.to_s)
51
+
52
+ return unless match
53
+
54
+ attrs = segment(match[1], finder_names)
55
+
56
+ attrs && [attrs, !match[2].nil?]
57
+ end
58
+
59
+ def finder_names
60
+ dynamic_finder_klass.attribute_names | ["id"]
61
+ end
62
+
63
+ # Splits "a_and_b" into attribute names. A name may hold "_and_" itself.
64
+ def segment(text, names)
65
+ return [text] if names.include?(text)
66
+
67
+ names.each do |name|
68
+ next unless text.start_with?(name + AND)
69
+
70
+ rest = segment(text[(name.length + AND.length)..], names)
71
+
72
+ return [name, *rest] if rest
73
+ end
74
+
75
+ nil
76
+ end
77
+ end
78
+ end
@@ -1,11 +1,25 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Ndb
4
- # ActiveRecord-like names for two daemon errors. They are the same classes,
5
- # so a rescue of either name catches the same error.
6
- StaleObjectError = VersionConflict
4
+ # ActiveRecord-like name for a daemon error. It is the same class, so a
5
+ # rescue of either name catches the same error.
7
6
  RecordNotUnique = UniqueViolation
8
7
 
8
+ # A save or destroy matched nothing: the record changed or was deleted
9
+ # since it was loaded (its "_v" guard did not match).
10
+ class StaleObjectError < Error; end
11
+
12
+ # Raised by destroy! when a before_destroy callback aborts.
13
+ class RecordNotDestroyed < Error
14
+ attr_reader :record
15
+
16
+ def initialize(message = "Failed to destroy the record", record = nil)
17
+ @record = record
18
+
19
+ super(message)
20
+ end
21
+ end
22
+
9
23
  # Raised by save!/create!/update! when validations fail.
10
24
  class RecordInvalid < Error
11
25
  attr_reader :record
@@ -3,7 +3,8 @@
3
3
  module Ndb
4
4
  class RecordNotSaved < Error; end
5
5
 
6
- # Writes: dirty attributes -> set/unset, the loaded version -> if_version.
6
+ # Writes: dirty attributes -> $set/$unset, filtered by the id and the loaded
7
+ # version ("_v"). A write that matches nothing is a stale record.
7
8
  module Persistence
8
9
  extend ActiveSupport::Concern
9
10
 
@@ -51,12 +52,13 @@ module Ndb
51
52
 
52
53
  attr_reader :version
53
54
 
55
+ # id is an alias of _id.
54
56
  def id
55
- public_send(self.class.primary_key)
57
+ _id
56
58
  end
57
59
 
58
60
  def id=(value)
59
- public_send("#{self.class.primary_key}=", value)
61
+ self._id = value
60
62
  end
61
63
 
62
64
  def persisted?
@@ -130,13 +132,63 @@ module Ndb
130
132
 
131
133
  def destroy
132
134
  result = run_callbacks(:destroy) do
133
- self.class.ndb_delete(id, if_version: version) if persisted?
135
+ delete_record if persisted?
134
136
  @destroyed = true
135
137
  end
136
138
 
137
139
  result ? self : false
138
140
  end
139
141
 
142
+ def destroy!
143
+ destroy || raise(RecordNotDestroyed.new("Failed to destroy the record", self))
144
+ end
145
+
146
+ # Deletes by _id: no callbacks and no _v guard, like ActiveRecord.
147
+ def delete
148
+ self.class.ndb_delete({ self.class.primary_key => id }) if persisted?
149
+
150
+ @destroyed = true
151
+
152
+ self
153
+ end
154
+
155
+ # The save of find_or_create_by: validations, then the save and create
156
+ # callbacks around one daemon upsert. The filter is attrs; the other
157
+ # attributes are written only if the upsert creates the document
158
+ # ($setOnInsert), so a writer that got there first is never overwritten.
159
+ # Returns the new record, or the one that won the race, or this record
160
+ # unsaved when it is invalid.
161
+ def create_unless_exists(attrs)
162
+ return self unless valid?(:create)
163
+
164
+ saved = run_callbacks(:save) { run_callbacks(:create) { upsert_record(attrs) } }
165
+
166
+ saved ? @upsert_winner || self : self
167
+ ensure
168
+ @upsert_winner = nil
169
+ end
170
+
171
+ def create_unless_exists!(attrs)
172
+ raise RecordInvalid, self unless valid?(:create)
173
+
174
+ record = create_unless_exists(attrs)
175
+
176
+ raise RecordNotSaved, "Failed to save the record" unless record.persisted?
177
+
178
+ record
179
+ end
180
+
181
+ # Adds by (default 1) to a number attribute in one atomic write on the
182
+ # daemon, and refreshes the attribute and the version. Other unsaved
183
+ # changes stay unsaved.
184
+ def increment!(attribute, by = 1)
185
+ add_to!(attribute, by)
186
+ end
187
+
188
+ def decrement!(attribute, by = 1)
189
+ add_to!(attribute, -by)
190
+ end
191
+
140
192
  def ==(other)
141
193
  other.instance_of?(self.class) && !id.nil? && id == other.id
142
194
  end
@@ -160,6 +212,38 @@ module Ndb
160
212
  self
161
213
  end
162
214
 
215
+ def record_filter
216
+ filter = { self.class.primary_key => id }
217
+
218
+ filter["_v"] = version if version
219
+
220
+ filter
221
+ end
222
+
223
+ def delete_record
224
+ deleted = self.class.ndb_delete(record_filter)["deleted"]
225
+
226
+ raise StaleObjectError.new("#{self.class.name} #{id} changed or was deleted", code: "stale_object") if deleted.zero?
227
+ end
228
+
229
+ def add_to!(attribute, by)
230
+ name = attribute.to_s
231
+
232
+ raise RecordNotSaved, "Cannot update a record that is not saved" unless persisted?
233
+ raise ArgumentError, "#{name} is not an attribute of #{self.class.name}" unless self.class.attribute_names.include?(name)
234
+
235
+ result = self.class.ndb_update({ self.class.primary_key => id }, { "$inc" => { name => by } })
236
+
237
+ raise NotFound.new("#{self.class.name} #{id} was deleted", code: "not_found") if result["matched"].zero?
238
+
239
+ @version = result["doc"]["_v"]
240
+
241
+ public_send("#{name}=", result["doc"][name])
242
+ clear_attribute_changes([name])
243
+
244
+ self
245
+ end
246
+
163
247
  def loaded!(version)
164
248
  @persisted = true
165
249
  @version = version
@@ -167,11 +251,31 @@ module Ndb
167
251
  changes_applied
168
252
  end
169
253
 
254
+ def upsert_record(attrs)
255
+ filter = attrs.keys.to_h do |key|
256
+ name = key.to_s == "id" ? self.class.primary_key : key.to_s
257
+
258
+ [name, json_attribute(name)]
259
+ end
260
+
261
+ on_insert = insert_document.except(*filter.keys)
262
+ result = self.class.ndb_update(filter, { "$setOnInsert" => on_insert }, upsert: true)
263
+
264
+ if result["matched"].zero?
265
+ self.id = result["doc"]["_id"] if id.nil?
266
+ loaded!(result["doc"]["_v"])
267
+ else
268
+ @upsert_winner = self.class.instantiate(result["doc"])
269
+ end
270
+
271
+ true
272
+ end
273
+
170
274
  def create_record
171
275
  run_callbacks(:create) do
172
276
  result = self.class.ndb_insert(insert_document, expire_in: @expire_in)
173
277
 
174
- self.id = result["id"] if id.nil?
278
+ self.id = result["_id"] if id.nil?
175
279
  loaded!(result["v"])
176
280
 
177
281
  true
@@ -183,9 +287,11 @@ module Ndb
183
287
  set, unset = changed_fields
184
288
 
185
289
  unless set.empty? && unset.empty? && @expire_in.nil?
186
- result = self.class.ndb_update(id, set: set, unset: unset, if_version: version, expire_in: @expire_in)
290
+ result = self.class.ndb_update(record_filter, update_ops(set, unset), expire_in: @expire_in)
291
+
292
+ raise StaleObjectError.new("#{self.class.name} #{id} changed or was deleted", code: "stale_object") if result["matched"].zero?
187
293
 
188
- @version = result["v"]
294
+ @version = result["doc"]["_v"]
189
295
  end
190
296
 
191
297
  changes_applied
@@ -194,6 +300,15 @@ module Ndb
194
300
  end
195
301
  end
196
302
 
303
+ def update_ops(set, unset)
304
+ ops = {}
305
+
306
+ ops["$set"] = set unless set.empty?
307
+ ops["$unset"] = unset.to_h { |name| [name, true] } unless unset.empty?
308
+
309
+ ops.empty? ? { "$set" => {} } : ops
310
+ end
311
+
197
312
  def insert_document
198
313
  attribute_names.each_with_object({}) do |name, doc|
199
314
  value = json_attribute(name)
@@ -12,6 +12,7 @@ module Ndb
12
12
  include Persistence
13
13
 
14
14
  extend ActiveSupport::DescendantsTracker
15
+ extend DynamicFinders
15
16
 
16
17
  ENSURE_LOCK = Mutex.new
17
18
 
@@ -20,7 +21,7 @@ module Ndb
20
21
  class << self
21
22
  QUERY_METHODS = %i[
22
23
  where order limit offset page after group find find_by find_by! first count pluck exists?
23
- find_each in_batches sum average minimum maximum to_a each
24
+ find_each in_batches sum average minimum maximum to_a each destroy_all delete_all
24
25
  ].freeze
25
26
 
26
27
  delegate(*QUERY_METHODS, to: :all)
@@ -35,6 +36,38 @@ module Ndb
35
36
  Relation.new(self)
36
37
  end
37
38
 
39
+ # Finds the record with these attributes, or builds an unsaved one.
40
+ def find_or_initialize_by(attrs, &block)
41
+ find_by(attrs) || new(attrs).tap { |record| block&.call(record) }
42
+ end
43
+
44
+ # Atomic through the daemon: two callers with the same attrs get one
45
+ # document. An invalid record is returned unsaved.
46
+ def find_or_create_by(attrs, &)
47
+ find_or_create(attrs, false, &)
48
+ end
49
+
50
+ def find_or_create_by!(attrs, &)
51
+ find_or_create(attrs, true, &)
52
+ end
53
+
54
+ # Destroys the records with these ids (callbacks run). Returns the
55
+ # record, or an array for an array of ids.
56
+ def destroy(id_or_ids)
57
+ return find(id_or_ids).each(&:destroy) if id_or_ids.is_a?(Array)
58
+
59
+ find(id_or_ids).tap(&:destroy)
60
+ end
61
+
62
+ # Deletes by _id in one daemon call, without callbacks. Returns the count.
63
+ def delete(id_or_ids)
64
+ ids = Array(id_or_ids)
65
+
66
+ return 0 if ids.empty?
67
+
68
+ where(primary_key => ids).delete_all
69
+ end
70
+
38
71
  def collection_name
39
72
  @collection_name || model_name.plural
40
73
  end
@@ -43,17 +76,10 @@ module Ndb
43
76
  @collection_name = name.to_s
44
77
  end
45
78
 
46
- def primary_key(name = nil)
47
- if name
48
- @primary_key = name.to_s
49
- attribute(name, :string) unless attribute_types.key?(@primary_key)
50
- end
51
-
52
- @primary_key || (superclass.respond_to?(:primary_key) ? superclass.primary_key : "_id")
53
- end
54
-
55
- def primary_key=(name)
56
- primary_key(name)
79
+ # The primary key is always _id. For a natural key (an email, a SKU),
80
+ # keep _id and mark that attribute `unique: true`.
81
+ def primary_key
82
+ "_id"
57
83
  end
58
84
 
59
85
  def source(glob = nil)
@@ -99,7 +125,7 @@ module Ndb
99
125
 
100
126
  # The ensure_collection body for this model.
101
127
  def collection_definition
102
- definition = { "id" => primary_key }
128
+ definition = {}
103
129
 
104
130
  definition["indexes"] = indexed_fields if indexed_fields.any?
105
131
  definition["unique"] = unique_fields if unique_fields.any?
@@ -124,7 +150,7 @@ module Ndb
124
150
  end
125
151
  end
126
152
 
127
- # Every load asks for "_v", so a loaded record can send if_version.
153
+ # Every load asks for "_v", so a loaded record can guard its write with it.
128
154
  def ndb_find(body)
129
155
  ensure_collection!
130
156
 
@@ -143,20 +169,36 @@ module Ndb
143
169
  Rails.client.insert(collection_name, [doc], expire_in: expire_in).first
144
170
  end
145
171
 
146
- def ndb_update(id, **change)
172
+ # Atomic update by filter, see Ndb::Client#update.
173
+ def ndb_update(filter, ops, **options)
147
174
  ensure_collection!
148
175
 
149
- Rails.client.update(collection_name, id, **change)
176
+ Rails.client.update(collection_name, filter, ops, **options)
150
177
  end
151
178
 
152
- def ndb_delete(id, if_version: nil)
179
+ def ndb_delete(filter, **options)
153
180
  ensure_collection!
154
181
 
155
- Rails.client.delete(collection_name, id, if_version: if_version)
182
+ Rails.client.delete(collection_name, filter, **options)
156
183
  end
157
184
 
158
185
  private
159
186
 
187
+ def dynamic_finder_klass = self
188
+ def dynamic_finder_scope = all
189
+
190
+ def find_or_create(attrs, bang, &block)
191
+ found = find_by(attrs)
192
+
193
+ return found if found
194
+
195
+ record = new(attrs)
196
+
197
+ block&.call(record)
198
+
199
+ bang ? record.create_unless_exists!(attrs) : record.create_unless_exists(attrs)
200
+ end
201
+
160
202
  def own_indexed
161
203
  @own_indexed ||= []
162
204
  end
@@ -169,14 +211,5 @@ module Ndb
169
211
  superclass.respond_to?(name) ? superclass.public_send(name) : []
170
212
  end
171
213
  end
172
-
173
- # The generated _id stays out of the JSON when another field is the id.
174
- def serializable_hash(options = nil)
175
- hash = super
176
-
177
- hash.delete("_id") if self.class.primary_key != "_id" && hash["_id"].nil?
178
-
179
- hash
180
- end
181
214
  end
182
215
  end
@@ -5,6 +5,7 @@ module Ndb
5
5
  # request goes to the daemon on each, to_a, first, count, pluck, ...
6
6
  class Relation
7
7
  include Enumerable
8
+ include DynamicFinders
8
9
 
9
10
  DEFAULT_PER_PAGE = 25
10
11
  BATCH_SIZE = 1000
@@ -78,6 +79,30 @@ module Ndb
78
79
  query
79
80
  end
80
81
 
82
+ # Atomic writes. The daemon matches the where and writes in one step on
83
+ # every match, so the where needs the id or an indexed field
84
+ # (Ndb::UnindexedMany otherwise). ops is the operator Hash of
85
+ # Ndb::Client#update ({ "$inc" => { "n" => 1 } }); returns the number of
86
+ # modified documents.
87
+ def update(ops, expire_in: nil)
88
+ klass.ndb_update(Conditions.combine(values[:where]), ops, many: true, expire_in: expire_in).fetch("modified")
89
+ end
90
+
91
+ # One daemon delete on every match, no callbacks (same rule as update).
92
+ # Returns how many. An unfiltered relation is refused by the daemon
93
+ # (Ndb::EmptyFilter).
94
+ def delete_all
95
+ klass.ndb_delete(Conditions.combine(values[:where]), many: true).fetch("deleted")
96
+ end
97
+
98
+ alias delete delete_all
99
+
100
+ # Loads the matches and destroys each one, with its callbacks. Returns
101
+ # the records.
102
+ def destroy_all
103
+ to_a.each(&:destroy)
104
+ end
105
+
81
106
  # Loaders
82
107
 
83
108
  def load
@@ -213,6 +238,9 @@ module Ndb
213
238
 
214
239
  protected
215
240
 
241
+ def dynamic_finder_klass = klass
242
+ def dynamic_finder_scope = self
243
+
216
244
  def with(changes)
217
245
  self.class.new(klass, values.merge(changes))
218
246
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "0.1.1"
5
+ VERSION = "0.2.0"
6
6
  end
7
7
  end
data/lib/ndb/rails.rb CHANGED
@@ -7,6 +7,7 @@ require "ndb"
7
7
  require "ndb/rails/version"
8
8
  require "ndb/rails/errors"
9
9
  require "ndb/rails/configuration"
10
+ require "ndb/rails/dynamic_finders"
10
11
  require "ndb/rails/relation"
11
12
  require "ndb/rails/blob"
12
13
  require "ndb/rails/persistence"
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.1.1
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - thadeu
@@ -64,6 +64,7 @@ files:
64
64
  - lib/ndb/rails.rb
65
65
  - lib/ndb/rails/blob.rb
66
66
  - lib/ndb/rails/configuration.rb
67
+ - lib/ndb/rails/dynamic_finders.rb
67
68
  - lib/ndb/rails/errors.rb
68
69
  - lib/ndb/rails/persistence.rb
69
70
  - lib/ndb/rails/railtie.rb