ndb-rails 0.1.2 → 0.2.1

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: cb272d6aadee253c818c30de3c3820c510903f06d42dac23dd56837bb585280a
4
- data.tar.gz: 4ccfbb876e868ebea9b229a5ef44292ad3240ed55933a46e3a5a432158f25012
3
+ metadata.gz: 725a7b1e419a8b375e0a00fc6b8493901c3351358bd9d3553be4d0e0b345cf10
4
+ data.tar.gz: 26be54c382d404c709a4624cf0f01b7e48ace439de753884f6e4f71062679d5a
5
5
  SHA512:
6
- metadata.gz: 0c24be778d6fc65e219b829d7c8219e810ecc3505a39c0670077e07a17c60a37824d5814a6869dd6926fa52eed09a85b6615622779be126e8c87e582ece20a0d
7
- data.tar.gz: 6360ba54f2208b4b438f269cfbbfd172fe0ebf9fd6907df523369d5241f88eec5a36ca617504dbde0553624fff00156b09c7cb892b05790d34e00cc4dde51f55
6
+ metadata.gz: 01206c2ff97c8d7a69092050f5978bd48d3e965273fec6c5092c935d79d103f6c116650a313ae23c13e44ebbdf20a53f5808b1278a43e83c419e9e7c964d47a5
7
+ data.tar.gz: 72319a51d406cda8478ceaae5ec1f15892b5fc142fe602dfaebbf8b2a377eefe533e72b4822aede05e301c6f50f14e160992e20b88505f8eb929e42cc3f8ccda
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
 
@@ -118,15 +116,32 @@ call.version # the document version
118
116
  call.increment!(:duration) # atomic $inc on the daemon, refreshes the attribute and the version
119
117
  call.decrement!(:duration, 5)
120
118
 
121
- call.destroy
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
122
134
 
123
135
  # Atomic writes on every match of a where (it needs the id or an indexed field).
124
136
  # update takes the operators of the client and returns the number of modified documents.
125
137
  Call.where(status: "failed").update({ "$set" => { "status" => "retry" } })
126
- Call.where(status: "retry").delete # returns how many it deleted
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
127
140
  ```
128
141
 
129
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`.
130
145
  - Setting an attribute to `nil` and saving removes the field from the document.
131
146
  - A duplicate id raises `RecordNotUnique` (code `duplicate_id`).
132
147
  - `persisted?`, `new_record?`, `destroyed?`, `id` and `version` work as in ActiveRecord.
@@ -146,13 +161,11 @@ Give the model an `expires: true` attribute. The daemon sets it for you.
146
161
 
147
162
  ```ruby
148
163
  class Session < Ndb::Record
149
- primary_key :sid
150
-
151
164
  attribute :user, :string
152
165
  attribute :expires_at, :datetime, expires: true
153
166
  end
154
167
 
155
- 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")
156
169
  session = Session.find("s1")
157
170
 
158
171
  session.expire(30.minutes) # EXPIRE: sets expires_at in the object, other unsaved changes stay
@@ -184,13 +197,13 @@ Call.where(status: "failed").or(Call.where(duration: 60..))
184
197
  Call.where("$or" => [{ status: "failed" }, { duration: { "$gt" => 50 } }])
185
198
 
186
199
  Call.where(status: "answered")
187
- .order(at: :desc, call_id: :asc)
200
+ .order(at: :desc, _id: :asc)
188
201
  .limit(50)
189
202
  .offset(100)
190
203
  .to_a
191
204
 
192
- Call.where(status: "answered").pluck(:call_id) # one field: an array of values
193
- 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
194
207
  Call.where(status: "answered").first(5)
195
208
  Call.where(status: "failed").exists?
196
209
  ```
@@ -223,11 +236,11 @@ Call.where(status: "answered").count
223
236
  ### Cursor pagination
224
237
 
225
238
  ```ruby
226
- relation = Call.where(status: "answered").order(:call_id).limit(100)
239
+ relation = Call.where(status: "answered").order(:_id).limit(100)
227
240
  rows = relation.to_a
228
241
  token = relation.next_cursor # nil on the last page
229
242
 
230
- 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
231
244
  ```
232
245
 
233
246
  A token works only with the same `where` and `order`. Another query shape raises `InvalidCursor`.
@@ -235,7 +248,7 @@ A token works only with the same `where` and `order`. Another query shape raises
235
248
  To walk every row, use `find_each`. It follows the cursor in batches (default 1000):
236
249
 
237
250
  ```ruby
238
- 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 }
239
252
 
240
253
  Call.in_batches(of: 500) { |batch| batch.each { |call| ... } }
241
254
  ```
@@ -289,7 +302,7 @@ client = Ndb::Rails.client
289
302
 
290
303
  begin
291
304
  client.watch(Call.collection_name, "relay", where: { status: "answered" }) do |event|
292
- # event has "pos", "op" ("put" or "del"), "id", "v" and "doc"
305
+ # event has "pos", "op" ("put" or "del"), "_id", "v" and "doc"
293
306
  handle(event)
294
307
 
295
308
  client.ack(Call.collection_name, "relay", event["pos"])
@@ -313,7 +326,7 @@ end
313
326
  Large values live in the blob store. The document keeps only a reference (`$blob`, `size`, `type`).
314
327
 
315
328
  ```ruby
316
- call = Call.new(call_id: "c1", status: "answered", caller: "a",
329
+ call = Call.new(_id: "c1", status: "answered", caller: "a",
317
330
  recording: File.open("call.wav")) # an IO or a String
318
331
  call.save! # uploads the blob, then saves
319
332
 
@@ -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
@@ -9,6 +9,17 @@ module Ndb
9
9
  # since it was loaded (its "_v" guard did not match).
10
10
  class StaleObjectError < Error; end
11
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
+
12
23
  # Raised by save!/create!/update! when validations fail.
13
24
  class RecordInvalid < Error
14
25
  attr_reader :record
@@ -52,12 +52,13 @@ module Ndb
52
52
 
53
53
  attr_reader :version
54
54
 
55
+ # id is an alias of _id.
55
56
  def id
56
- public_send(self.class.primary_key)
57
+ _id
57
58
  end
58
59
 
59
60
  def id=(value)
60
- public_send("#{self.class.primary_key}=", value)
61
+ self._id = value
61
62
  end
62
63
 
63
64
  def persisted?
@@ -138,6 +139,45 @@ module Ndb
138
139
  result ? self : false
139
140
  end
140
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
+
141
181
  # Adds by (default 1) to a number attribute in one atomic write on the
142
182
  # daemon, and refreshes the attribute and the version. Other unsaved
143
183
  # changes stay unsaved.
@@ -211,11 +251,31 @@ module Ndb
211
251
  changes_applied
212
252
  end
213
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
+
214
274
  def create_record
215
275
  run_callbacks(:create) do
216
276
  result = self.class.ndb_insert(insert_document, expire_in: @expire_in)
217
277
 
218
- self.id = result["id"] if id.nil?
278
+ self.id = result["_id"] if id.nil?
219
279
  loaded!(result["v"])
220
280
 
221
281
  true
@@ -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?
@@ -158,6 +184,21 @@ module Ndb
158
184
 
159
185
  private
160
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
+
161
202
  def own_indexed
162
203
  @own_indexed ||= []
163
204
  end
@@ -170,14 +211,5 @@ module Ndb
170
211
  superclass.respond_to?(name) ? superclass.public_send(name) : []
171
212
  end
172
213
  end
173
-
174
- # The generated _id stays out of the JSON when another field is the id.
175
- def serializable_hash(options = nil)
176
- hash = super
177
-
178
- hash.delete("_id") if self.class.primary_key != "_id" && hash["_id"].nil?
179
-
180
- hash
181
- end
182
214
  end
183
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
@@ -87,11 +88,21 @@ module Ndb
87
88
  klass.ndb_update(Conditions.combine(values[:where]), ops, many: true, expire_in: expire_in).fetch("modified")
88
89
  end
89
90
 
90
- # Deletes every match (same rule as update) and returns how many.
91
- def delete
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
92
95
  klass.ndb_delete(Conditions.combine(values[:where]), many: true).fetch("deleted")
93
96
  end
94
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
+
95
106
  # Loaders
96
107
 
97
108
  def load
@@ -227,6 +238,9 @@ module Ndb
227
238
 
228
239
  protected
229
240
 
241
+ def dynamic_finder_klass = klass
242
+ def dynamic_finder_scope = self
243
+
230
244
  def with(changes)
231
245
  self.class.new(klass, values.merge(changes))
232
246
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "0.1.2"
5
+ VERSION = "0.2.1"
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.2
4
+ version: 0.2.1
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