ndb-rails 1.21.1 → 1.22.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: 75877e2f8425d5d6207cc105b3fcacf84c47c37fa09f61289cf03b21444e4fa0
4
- data.tar.gz: 84528890b7a7230b4ff6d6f5ae65769af01e55d355b39457f78d412857cc22ea
3
+ metadata.gz: 10dd7c29f96edb737881dc589a33112d56d122d205c662a97741da621cecc646
4
+ data.tar.gz: 2052bcdb719177f2b64a43e2be64c61b2e2c8fe042f5bde7aa126b15e2f88151
5
5
  SHA512:
6
- metadata.gz: 9efe5423c482bd44ab58defbe01a4a1ef3daa72d5c608fbc2bac10dc4c94f5d081d2e1b4169a213dcc78056861d6726e1289ff20629fcff9fbdd06f1598e5e78
7
- data.tar.gz: ddcb2f01811c5468ff5f51c17cb63e89b7affc79e5b9c7907b48033a88e80d4f974daac4f7ff4fe660f43a433f4cbee47ce35e2a141760bd9458508e562fd679
6
+ metadata.gz: fd79b804b57fcf85f1444a4df24aac1ff3fbe5c7989de603cee4822242ab4a47997756f5b23cce09538b35def6e0cbddf6a393d35dd8c448899977cb7d0078ef
7
+ data.tar.gz: ffa5baa0c2dc5ca177d63e77f15db230f9f325920785126626d9301b548eb50a410e38aac44c4cd2062526a267eeb3fa54f0ac737013b531502e9b6e761432c6
data/README.md CHANGED
@@ -82,7 +82,8 @@ end
82
82
 
83
83
  | Option or method | Meaning |
84
84
  |---|---|
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. |
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`, also in `where`, `find_by` and `exists?` (a model with its own `id` attribute keeps it). For a natural key (email, SKU) keep `_id` and use `unique: true` on that attribute. |
86
+ | `created_at` / `updated_at` | Every model has them, with an index, as the timestamps of ActiveRecord. Do not declare them. A save of a new record sets both (a value that you set stays). Each write sets `updated_at`: `save`, `update`, `increment!`, `Relation#update`, `upsert` and `upsert_all` (`created_at` only on a new document; one read finds the ids that exist). A save with no change writes nothing. The values are UTC with milliseconds (`2026-11-12T15:00:05.000Z`). |
86
87
  | `index: true` | Index this field. |
87
88
  | `unique: true` | Unique value. A second one raises `RecordNotUnique`. |
88
89
  | `time: true` | The collection time field. Used by zone maps, `$dateTrunc` and TTL. |
@@ -92,7 +93,9 @@ end
92
93
  | `source "glob"` | Declares a read-only direct-mode collection over files. Writes raise `ReadOnlyCollection`. |
93
94
 
94
95
  - Attributes are ActiveModel attributes, so every ActiveModel type works (`:string`, `:integer`, `:float`, `:boolean`, `:datetime`, `:date`, and so on). Times are sent as RFC 3339 UTC strings with milliseconds. `:blob` is added by this gem.
95
- - Validations, callbacks (`save`, `create`, `update`, `destroy`), dirty tracking and `as_json` work as in ActiveModel.
96
+ - Validations, callbacks (`validation`, `save`, `create`, `update`, `destroy`), dirty tracking and `as_json` work as in ActiveModel.
97
+ - `readonly?` works as in ActiveRecord: when it is true, `save`, `destroy` and `delete` raise `Ndb::ReadOnlyRecord`. Override it in a model (`def readonly? = true`), or call `record.readonly!`.
98
+ - `validates :name, uniqueness: true` (or `uniqueness: { scope: :app_id }`) asks the daemon if another document has the value, and adds `:taken` ("has already been taken") to the field. Two saves at the same time can both pass, so keep `unique: true` on the attribute: the unique index is the real guard (`Ndb::RecordNotUnique`).
96
99
  - The model declares its collection on first use, once per process.
97
100
  - Mark a base class with `self.abstract_class = true` to share settings.
98
101
 
@@ -137,7 +140,7 @@ Call.find_or_create_by!(_id: "c9", status: "new") # raises Record
137
140
 
138
141
  # Atomic writes on every match of a where (it needs the id or an indexed field).
139
142
  # update takes the operators of the client and returns the number of modified documents.
140
- Call.where(status: "failed").update({ "$set" => { "status" => "retry" } })
143
+ Call.where(status: "failed").update("$set" => { "status" => "retry" }) # the braces are optional
141
144
  Call.where(status: "retry").delete_all # one delete, no callbacks, returns how many (delete is an alias)
142
145
  Call.where(status: "retry").destroy_all # loads and destroys each record with its callbacks, returns them
143
146
  ```
@@ -210,6 +213,7 @@ Call.where(status: "answered").pluck(:_id) # one field: an array of valu
210
213
  Call.where(status: "answered").pluck(:_id, :status) # several: an array of arrays
211
214
  Call.where(status: "answered").first(5)
212
215
  Call.where(status: "failed").exists?
216
+ Call.exists?("c1") # by id; exists?(status: "failed") takes conditions
213
217
  ```
214
218
 
215
219
  - 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.
@@ -218,6 +222,27 @@ Call.where(status: "failed").exists?
218
222
  - `pluck` asks the daemon for only those fields.
219
223
  - 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
224
 
225
+ ### Scopes
226
+
227
+ A `scope` is a named query, as in ActiveRecord. A scope and a class method of the model can
228
+ also be called on a relation: the relation is the `all` of the call.
229
+
230
+ ```ruby
231
+ class Message < Ndb::Record
232
+ scope :recent, -> { order(created_at: :desc) }
233
+ scope :top, ->(count) { order(score: :desc).limit(count) }
234
+
235
+ def self.failed = where(status: "failed")
236
+ end
237
+
238
+ Message.where(app_id: app.id).recent.top(10)
239
+ Message.recent.failed
240
+ ```
241
+
242
+ - A relation runs only the methods that the model declares. The methods of `Ndb::Record`
243
+ (`truncate!`, `upsert`, ...) are not run on a relation.
244
+ - A scope cannot have the name of a relation method (`count`, `open`, ...): `ArgumentError`.
245
+
221
246
  ### A query built elsewhere
222
247
 
223
248
  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:
@@ -18,6 +18,24 @@ module Ndb
18
18
  module Associations
19
19
  extend ActiveSupport::Concern
20
20
 
21
+ FOREIGN_KEYS = Hash.new { |keys, name| keys[name] = Set.new }
22
+
23
+ # The foreign keys that has_many and has_one of other models put on the
24
+ # model with this class name: they are in its indexes.
25
+ def self.foreign_keys_of(class_name)
26
+ FOREIGN_KEYS.key?(class_name) ? FOREIGN_KEYS[class_name].to_a : []
27
+ end
28
+
29
+ # A model that declared its collection before the has_many was read
30
+ # declares it again on next use, with the new index.
31
+ def self.add_foreign_key(class_name, field)
32
+ return if FOREIGN_KEYS[class_name].include?(field)
33
+
34
+ FOREIGN_KEYS[class_name] << field
35
+
36
+ Record.descendants.each { |model| model.redeclare! if model.name == class_name }
37
+ end
38
+
21
39
  # One declared association.
22
40
  Reflection = Data.define(:name, :kind, :class_name, :foreign_key, :primary_key, :options) do
23
41
  def klass = class_name.constantize
@@ -47,18 +65,24 @@ module Ndb
47
65
  associate(name, :belongs_to, class_name || name.to_s.camelize, foreign_key, keys_pk(name, primary_key, pk), {})
48
66
  end
49
67
 
50
- def has_many(name, class_name: nil, foreign_key: nil, fk: nil, primary_key: nil, pk: nil, sort: nil, limit: nil, where: nil)
68
+ def has_many(name, class_name: nil, foreign_key: nil, fk: nil, primary_key: nil, pk: nil, sort: nil, limit: nil, where: nil, dependent: nil)
69
+ check_dependent(name, dependent)
70
+
51
71
  options = { sort: sort, limit: limit, query: where }.compact
52
72
  foreign_key = either(name, :foreign_key, foreign_key, :fk, fk) || "#{model_name.singular}_id"
53
73
 
54
74
  associate(name, :has_many, class_name || name.to_s.singularize.camelize, foreign_key, keys_pk(name, primary_key, pk), options)
75
+ destroy_with(name, dependent)
55
76
  end
56
77
 
57
- def has_one(name, class_name: nil, foreign_key: nil, fk: nil, primary_key: nil, pk: nil, sort: nil, where: nil)
78
+ def has_one(name, class_name: nil, foreign_key: nil, fk: nil, primary_key: nil, pk: nil, sort: nil, where: nil, dependent: nil)
79
+ check_dependent(name, dependent)
80
+
58
81
  options = { sort: sort, query: where }.compact
59
82
  foreign_key = either(name, :foreign_key, foreign_key, :fk, fk) || "#{model_name.singular}_id"
60
83
 
61
84
  associate(name, :has_one, class_name || name.to_s.camelize, foreign_key, keys_pk(name, primary_key, pk), options)
85
+ destroy_with(name, dependent)
62
86
  end
63
87
 
64
88
  def reflections
@@ -97,6 +121,25 @@ module Ndb
97
121
 
98
122
  private
99
123
 
124
+ DEPENDENT = %i[destroy delete_all].freeze
125
+
126
+ def check_dependent(name, dependent)
127
+ return if dependent.nil? || DEPENDENT.include?(dependent)
128
+
129
+ raise ArgumentError, "#{self.name}.#{name}: dependent: takes :destroy or :delete_all, got #{dependent.inspect}"
130
+ end
131
+
132
+ # dependent: :destroy loads the other records and destroys each one
133
+ # (callbacks run); :delete_all is one delete, no callbacks. Both run
134
+ # before the destroy of this record.
135
+ def destroy_with(name, dependent)
136
+ return unless dependent
137
+
138
+ name = name.to_s
139
+
140
+ before_destroy { remove_dependents(name, dependent) }
141
+ end
142
+
100
143
  def keys_pk(name, primary_key, pk)
101
144
  either(name, :primary_key, primary_key, :pk, pk) || "_id"
102
145
  end
@@ -117,6 +160,8 @@ module Ndb
117
160
  def associate(name, kind, class_name, foreign_key, primary_key, options)
118
161
  name = name.to_s
119
162
 
163
+ Associations.add_foreign_key(class_name.to_s, foreign_key.to_s) if kind != :belongs_to && foreign_key.to_s != "_id"
164
+
120
165
  own_reflections[name] = Reflection.new(name: name, kind: kind, class_name: class_name.to_s, foreign_key: foreign_key.to_s,
121
166
  primary_key: primary_key.to_s, options: options)
122
167
 
@@ -163,6 +208,20 @@ module Ndb
163
208
 
164
209
  private
165
210
 
211
+ def remove_dependents(name, dependent)
212
+ reflection = self.class.reflections.fetch(name)
213
+ key = association_key(reflection)
214
+
215
+ return if key.nil?
216
+
217
+ reflection.klass.prepare_lookup(reflection)
218
+
219
+ scope = reflection.klass.where(reflection.foreign_key => key)
220
+ scope = scope.where_raw(reflection.options[:query]) if reflection.options[:query]
221
+
222
+ dependent == :destroy ? scope.destroy_all : scope.delete_all
223
+ end
224
+
166
225
  # The field of this record the association reads: the foreign key of a
167
226
  # belongs_to, the primary key of a has_many or has_one.
168
227
  def association_key(reflection)
@@ -12,7 +12,8 @@ module Ndb
12
12
  attr_accessor :url, :socket, :token, :timeout, :pool_size, :ready_timeout
13
13
 
14
14
  # collection_prefix goes before every collection name of the models
15
- # ("test2_" for a parallel test worker). nil by default.
15
+ # ("test2_" for a parallel test worker). The default is NDB_PREFIX,
16
+ # else nil.
16
17
  attr_accessor :collection_prefix
17
18
 
18
19
  # user_agent is the token of the app (for example "myapp/1.2"). It goes
@@ -28,6 +29,7 @@ module Ndb
28
29
  @timeout = 30
29
30
  @pool_size = 16
30
31
  @ready_timeout = 10
32
+ @collection_prefix = ENV["NDB_PREFIX"].presence
31
33
  @streams = {}
32
34
  end
33
35
 
@@ -16,6 +16,9 @@ module Ndb
16
16
  end
17
17
  end
18
18
 
19
+ # Raised by save, destroy and delete of a record whose readonly? is true.
20
+ class ReadOnlyRecord < Error; end
21
+
19
22
  # Raised by save!/create!/update! when validations fail.
20
23
  class RecordInvalid < Error
21
24
  attr_reader :record
@@ -0,0 +1,5 @@
1
+ en:
2
+ activemodel:
3
+ errors:
4
+ messages:
5
+ taken: "has already been taken"
@@ -87,6 +87,8 @@ module Ndb
87
87
  # set the expires field to now + expire_in in the same write. The model
88
88
  # needs an `expires: true` attribute (Ndb::TtlNotEnabled otherwise).
89
89
  def save(validate: true, expire_in: nil)
90
+ raise_if_readonly
91
+
90
92
  return false if validate && !valid?(new_record? ? :create : :update)
91
93
 
92
94
  @expire_in = wire_duration(expire_in)
@@ -137,6 +139,8 @@ module Ndb
137
139
  end
138
140
 
139
141
  def destroy
142
+ raise_if_readonly
143
+
140
144
  result = run_callbacks(:destroy) do
141
145
  delete_record if persisted?
142
146
  @destroyed = true
@@ -151,6 +155,8 @@ module Ndb
151
155
 
152
156
  # Deletes by _id: no callbacks and no _v guard, like ActiveRecord.
153
157
  def delete
158
+ raise_if_readonly
159
+
154
160
  self.class.ndb_delete({ self.class.primary_key => id }) if persisted?
155
161
 
156
162
  @destroyed = true
@@ -240,12 +246,42 @@ module Ndb
240
246
  self
241
247
  end
242
248
 
249
+ # Like ActiveRecord: a record whose readonly? is true raises
250
+ # Ndb::ReadOnlyRecord on save, destroy and delete. Override readonly? in
251
+ # a model, or call readonly! on one record.
252
+ def readonly?
253
+ @readonly == true
254
+ end
255
+
256
+ def readonly!
257
+ @readonly = true
258
+
259
+ self
260
+ end
261
+
243
262
  def ==(other)
244
263
  other.instance_of?(self.class) && !id.nil? && id == other.id
245
264
  end
246
265
 
247
266
  private
248
267
 
268
+ # A new record: created_at and updated_at, unless the app set them.
269
+ def stamp_create
270
+ now = self.class.current_time
271
+
272
+ self.created_at ||= now
273
+ self.updated_at ||= now
274
+ end
275
+
276
+ # A write of a saved record: updated_at, unless the app changed it.
277
+ def stamp_update
278
+ self.updated_at = self.class.current_time unless changed.include?("updated_at")
279
+ end
280
+
281
+ def raise_if_readonly
282
+ raise ReadOnlyRecord, "#{self.class.name} is marked as readonly" if readonly?
283
+ end
284
+
249
285
  def wire_duration(value)
250
286
  value.is_a?(ActiveSupport::Duration) ? value.to_i : value
251
287
  end
@@ -291,22 +327,27 @@ module Ndb
291
327
  raise RecordNotSaved, "Cannot update a record that is not saved" unless persisted?
292
328
  raise ArgumentError, "#{name} is not an attribute of #{self.class.name}" unless self.class.attribute_names.include?(name)
293
329
 
330
+ now = self.class.current_time
331
+ ops = { "$inc" => { name => by }, "$set" => { "updated_at" => Conditions.json_value(now) } }
332
+
294
333
  if (tx = current_transaction)
295
- tx.update(self, { "$inc" => { name => by } })
334
+ tx.update(self, ops)
296
335
  public_send("#{name}=", (public_send(name) || 0) + by)
297
- clear_attribute_changes([name])
336
+ self.updated_at = now
337
+ clear_attribute_changes([name, "updated_at"])
298
338
 
299
339
  return self
300
340
  end
301
341
 
302
- result = holding { self.class.ndb_update({ self.class.primary_key => id }, { "$inc" => { name => by } }, **lock_options) }
342
+ result = holding { self.class.ndb_update({ self.class.primary_key => id }, ops, **lock_options) }
303
343
 
304
344
  raise NotFound.new("#{self.class.name} #{id} was deleted", code: "not_found") if result["matched"].zero?
305
345
 
306
346
  @version = result["doc"]["_v"]
307
347
 
308
348
  public_send("#{name}=", result["doc"][name])
309
- clear_attribute_changes([name])
349
+ self.updated_at = now
350
+ clear_attribute_changes([name, "updated_at"])
310
351
 
311
352
  self
312
353
  end
@@ -326,6 +367,8 @@ module Ndb
326
367
  [name, json_attribute(name)]
327
368
  end
328
369
 
370
+ stamp_create
371
+
329
372
  on_insert = insert_document.except(*filter.keys)
330
373
  result = self.class.ndb_update(filter, { "$setOnInsert" => on_insert }, upsert: true)
331
374
 
@@ -341,6 +384,7 @@ module Ndb
341
384
 
342
385
  def create_record
343
386
  run_callbacks(:create) do
387
+ stamp_create
344
388
  if (tx = current_transaction)
345
389
  raise ArgumentError, "expire_in is not supported inside a transaction" if @expire_in
346
390
 
@@ -362,6 +406,8 @@ module Ndb
362
406
 
363
407
  def update_record
364
408
  run_callbacks(:update) do
409
+ stamp_update if (changed - [self.class.primary_key]).any? || @expire_in
410
+
365
411
  set, unset = changed_fields
366
412
 
367
413
  if (tx = current_transaction)
@@ -6,6 +6,8 @@ module Ndb
6
6
  include ActiveModel::Model
7
7
  include ActiveModel::Attributes
8
8
  include ActiveModel::Validations
9
+ include ActiveModel::Validations::Callbacks
10
+ include Validations
9
11
  include ActiveModel::Callbacks
10
12
  include ActiveModel::Dirty
11
13
  include ActiveModel::Serializers::JSON
@@ -38,8 +40,42 @@ module Ndb
38
40
  @abstract_class == true
39
41
  end
40
42
 
43
+ # Inside scoping (a scope or a class method called on a relation), all
44
+ # is that relation, so where, order... add to it.
41
45
  def all
42
- Relation.new(self)
46
+ Thread.current[:ndb_scopes]&.[](self) || Relation.new(self)
47
+ end
48
+
49
+ # Runs the block with relation as all, like ActiveRecord scoping.
50
+ def scoping(relation)
51
+ scopes = (Thread.current[:ndb_scopes] ||= {})
52
+ before = scopes[self]
53
+
54
+ scopes[self] = relation
55
+
56
+ yield
57
+ ensure
58
+ scopes[self] = before
59
+ end
60
+
61
+ # A named query, like ActiveRecord scope. The body runs on the
62
+ # relation; it can also be called on a relation:
63
+ # `Message.where(app_id: id).recent`.
64
+ #
65
+ # scope :recent, -> { order(created_at: :desc) }
66
+ # scope :top, ->(n) { order(score: :desc).limit(n) }
67
+ def scope(name, body)
68
+ raise ArgumentError, "the body of scope #{name} must be callable" unless body.respond_to?(:call)
69
+
70
+ if Relation.method_defined?(name) || Relation.private_method_defined?(name)
71
+ raise ArgumentError, "#{self.name} cannot have a scope named #{name}: a relation already has that method"
72
+ end
73
+
74
+ define_singleton_method(name) do |*args, **kwargs|
75
+ relation = all
76
+
77
+ scoping(relation) { relation.instance_exec(*args, **kwargs, &body) } || relation
78
+ end
43
79
  end
44
80
 
45
81
  # Writes a document by its _id, like ActiveRecord upsert: it creates
@@ -53,11 +89,13 @@ module Ndb
53
89
  upsert_all([attributes || attrs], expire_in: expire_in).first
54
90
  end
55
91
 
56
- # upsert for many documents in one transaction, all or nothing.
92
+ # upsert for many documents in one transaction, all or nothing. Each
93
+ # document gets updated_at, and a new one also gets created_at: one
94
+ # read first finds the ids that exist.
57
95
  def upsert_all(attributes, expire_in: nil)
58
96
  ensure_collection!
59
97
 
60
- docs = attributes.map { |attrs| upsert_document(attrs) }
98
+ docs = stamp_upserts(attributes.map { |attrs| upsert_document(attrs) })
61
99
 
62
100
  expire_in = expire_in.to_i if expire_in.is_a?(ActiveSupport::Duration)
63
101
 
@@ -198,8 +236,10 @@ module Ndb
198
236
  (unique ? own_unique : own_indexed) << names.join(",")
199
237
  end
200
238
 
239
+ # The declared indexes, and the foreign keys that has_many and has_one
240
+ # of other models put here.
201
241
  def indexed_fields
202
- inherited_list(:indexed_fields) | own_indexed
242
+ inherited_list(:indexed_fields) | own_indexed | Associations.foreign_keys_of(name.to_s)
203
243
  end
204
244
 
205
245
  def unique_fields
@@ -254,6 +294,11 @@ module Ndb
254
294
  end
255
295
  end
256
296
 
297
+ # The next use declares the collection again.
298
+ def redeclare!
299
+ @ensured_client = nil
300
+ end
301
+
257
302
  # Every load asks for "_v", so a loaded record can guard its write with it.
258
303
  def ndb_find(body)
259
304
  ensure_collection!
@@ -267,6 +312,11 @@ module Ndb
267
312
  Rails.client.aggregate(collection_name, body)
268
313
  end
269
314
 
315
+ # The time of a write: UTC, in milliseconds (the precision stored).
316
+ def current_time
317
+ Time.now.utc.floor(3)
318
+ end
319
+
270
320
  # The given attributes, cast by their type, with id as _id.
271
321
  def upsert_document(attrs)
272
322
  attrs.to_h.each_with_object({}) do |(name, value), doc|
@@ -303,6 +353,22 @@ module Ndb
303
353
  def dynamic_finder_klass = self
304
354
  def dynamic_finder_scope = all
305
355
 
356
+ def stamp_upserts(docs)
357
+ now = Conditions.json_value(current_time)
358
+ stored = stored_ids(docs.filter_map { |doc| doc[primary_key] })
359
+
360
+ docs.each do |doc|
361
+ doc["updated_at"] ||= now
362
+ doc["created_at"] ||= now unless stored.include?(doc[primary_key])
363
+ end
364
+ end
365
+
366
+ def stored_ids(ids)
367
+ ids.uniq.each_slice(Relation::BATCH_SIZE).flat_map do |slice|
368
+ where(primary_key => slice).limit(slice.size).pluck(primary_key)
369
+ end.to_set
370
+ end
371
+
306
372
  def find_or_create(attrs, bang, &block)
307
373
  found = find_by(attrs)
308
374
 
@@ -335,5 +401,10 @@ module Ndb
335
401
  superclass.respond_to?(name) ? superclass.public_send(name) : []
336
402
  end
337
403
  end
404
+
405
+ # Like the timestamps of ActiveRecord, on every model with no
406
+ # declaration: a save sets them, and each write sets updated_at.
407
+ attribute :created_at, :datetime, index: true
408
+ attribute :updated_at, :datetime, index: true
338
409
  end
339
410
  end
@@ -26,7 +26,7 @@ module Ndb
26
26
  return WhereChain.new(self) if attrs == :chain
27
27
  raise ArgumentError, "where takes a Hash, got #{attrs.class}" unless attrs.is_a?(Hash)
28
28
 
29
- add_clause(Conditions.equality(attrs))
29
+ add_clause(Conditions.equality(alias_id(attrs)))
30
30
  end
31
31
 
32
32
  # A where Hash built elsewhere, such as from a search form, sent as is:
@@ -141,9 +141,14 @@ module Ndb
141
141
  # every match, so the where needs the id or an indexed field
142
142
  # (Ndb::UnindexedMany otherwise). ops is the operator Hash of
143
143
  # Ndb::Client#update ({ "$inc" => { "n" => 1 } }); returns the number of
144
- # modified documents.
145
- def update(ops, expire_in: nil)
146
- klass.ndb_update(Conditions.combine(values[:where]), ops, many: true, expire_in: expire_in).fetch("modified")
144
+ # modified documents. The braces are optional: update("$inc" => {...}).
145
+ def update(ops = nil, expire_in: nil, **ops_kw)
146
+ ops = (ops || {}).merge(ops_kw)
147
+ plain = ops.keys.reject { |key| key.to_s.start_with?("$") }
148
+
149
+ raise ArgumentError, "update takes operators such as \"$set\" => { status: ... }, got #{ops.keys.inspect}" if ops.empty? || plain.any?
150
+
151
+ klass.ndb_update(Conditions.combine(values[:where]), with_updated_at(ops), many: true, expire_in: expire_in).fetch("modified")
147
152
  end
148
153
 
149
154
  # One daemon delete on every match, no callbacks (same rule as update).
@@ -272,7 +277,13 @@ module Ndb
272
277
  find_by(attrs, &block) || raise(NotFound.new("Couldn't find #{klass.name}", code: "not_found"))
273
278
  end
274
279
 
275
- def exists?
280
+ # Like ActiveRecord: exists?, exists?("id") or exists?(status: "x").
281
+ # false or nil is false, with no request.
282
+ def exists?(conditions = :none)
283
+ return false if conditions.nil? || conditions == false
284
+ return where(conditions).exists? if conditions.is_a?(Hash)
285
+ return where(klass.primary_key => conditions).exists? unless conditions == :none
286
+
276
287
  fetch(to_query.slice("query").merge("limit" => 1, "fields" => [klass.primary_key])).rows.any?
277
288
  end
278
289
 
@@ -340,6 +351,20 @@ module Ndb
340
351
  { "pipeline" => stages }
341
352
  end
342
353
 
354
+ # A scope or a class method of the model, called on this relation: it
355
+ # runs with this relation as the model's all. Only the methods the model
356
+ # declares; the methods of Ndb::Record (truncate!, upsert...) are not
357
+ # run on a relation.
358
+ def method_missing(name, ...)
359
+ return super unless model_method?(name)
360
+
361
+ klass.scoping(self) { klass.public_send(name, ...) }
362
+ end
363
+
364
+ def respond_to_missing?(name, include_private = false)
365
+ model_method?(name) || super
366
+ end
367
+
343
368
  protected
344
369
 
345
370
  def dynamic_finder_klass = klass
@@ -359,6 +384,29 @@ module Ndb
359
384
  values[:keep_encrypted] ? Rails.client.keep_encrypted(&) : yield
360
385
  end
361
386
 
387
+ # The operators with $set of updated_at, unless they write it already.
388
+ def with_updated_at(ops)
389
+ ops = ops.transform_keys(&:to_s)
390
+
391
+ return ops if ops.values.any? { |fields| fields.is_a?(Hash) && fields.keys.map(&:to_s).include?("updated_at") }
392
+
393
+ set = (ops["$set"] || {}).merge("updated_at" => Conditions.json_value(klass.current_time))
394
+
395
+ ops.merge("$set" => set)
396
+ end
397
+
398
+ def model_method?(name)
399
+ klass.respond_to?(name) && !Record.respond_to?(name, true)
400
+ end
401
+
402
+ # id is an alias of _id, as on a record, unless the model has its own
403
+ # id attribute.
404
+ def alias_id(attrs)
405
+ return attrs if klass.attribute_names.include?("id")
406
+
407
+ attrs.transform_keys { |key| key.to_s == "id" ? klass.primary_key : key }
408
+ end
409
+
362
410
  def add_clause(clause)
363
411
  with(where: values[:where] + [clause])
364
412
  end
@@ -452,7 +500,7 @@ module Ndb
452
500
  end
453
501
 
454
502
  def not(attrs)
455
- @relation.send(:add_clause, Conditions.negation(attrs))
503
+ @relation.send(:add_clause, Conditions.negation(@relation.send(:alias_id, attrs)))
456
504
  end
457
505
  end
458
506
  end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # Validators that ActiveRecord has and ActiveModel does not.
5
+ module Validations
6
+ # validates :name, uniqueness: true (or { scope: :app_id }). It asks the
7
+ # daemon if another document has the value, so a form gets an error on
8
+ # the field. Two saves at the same time can both pass: the unique index
9
+ # (unique: true) stays the real guard (Ndb::RecordNotUnique).
10
+ class UniquenessValidator < ActiveModel::EachValidator
11
+ def validate_each(record, attribute, value)
12
+ conditions = { attribute => value }
13
+
14
+ Array(options[:scope]).each { |name| conditions[name] = record.public_send(name) }
15
+
16
+ others = record.class.where(conditions)
17
+ others = others.where.not(_id: record.id) if record.persisted?
18
+
19
+ record.errors.add(attribute, :taken, **options.except(:scope), value: value) if others.exists?
20
+ end
21
+ end
22
+ end
23
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "1.21.1"
5
+ VERSION = "1.22.0"
6
6
  end
7
7
  end
data/lib/ndb/rails.rb CHANGED
@@ -9,6 +9,7 @@ require "ndb/rails/errors"
9
9
  require "ndb/rails/configuration"
10
10
  require "ndb/rails/dynamic_finders"
11
11
  require "ndb/rails/relation"
12
+ require "ndb/rails/validations"
12
13
  require "ndb/rails/blob"
13
14
  require "ndb/rails/persistence"
14
15
  require "ndb/rails/locking"
@@ -17,6 +18,8 @@ require "ndb/rails/associations"
17
18
  require "ndb/rails/record"
18
19
  require "ndb/streams"
19
20
 
21
+ I18n.load_path << File.expand_path("rails/locale/en.yml", __dir__)
22
+
20
23
  module Ndb
21
24
  module Rails
22
25
  class << self
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: 1.21.1
4
+ version: 1.22.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - thadeu
@@ -43,7 +43,7 @@ dependencies:
43
43
  requirements:
44
44
  - - ">="
45
45
  - !ruby/object:Gem::Version
46
- version: 1.21.1
46
+ version: 1.22.0
47
47
  - - "<"
48
48
  - !ruby/object:Gem::Version
49
49
  version: '2'
@@ -53,7 +53,7 @@ dependencies:
53
53
  requirements:
54
54
  - - ">="
55
55
  - !ruby/object:Gem::Version
56
- version: 1.21.1
56
+ version: 1.22.0
57
57
  - - "<"
58
58
  - !ruby/object:Gem::Version
59
59
  version: '2'
@@ -74,6 +74,7 @@ files:
74
74
  - lib/ndb/rails/database_cleaner.rb
75
75
  - lib/ndb/rails/dynamic_finders.rb
76
76
  - lib/ndb/rails/errors.rb
77
+ - lib/ndb/rails/locale/en.yml
77
78
  - lib/ndb/rails/locking.rb
78
79
  - lib/ndb/rails/minitest.rb
79
80
  - lib/ndb/rails/persistence.rb
@@ -83,6 +84,7 @@ files:
83
84
  - lib/ndb/rails/rspec.rb
84
85
  - lib/ndb/rails/testing.rb
85
86
  - lib/ndb/rails/transactions.rb
87
+ - lib/ndb/rails/validations.rb
86
88
  - lib/ndb/rails/version.rb
87
89
  - lib/ndb/streams.rb
88
90
  - lib/ndb/streams/assertions.rb