ndb-rails 1.23.1 → 1.24.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 +4 -4
- data/lib/ndb/rails/commit_callbacks.rb +76 -0
- data/lib/ndb/rails/errors.rb +3 -0
- data/lib/ndb/rails/persistence.rb +12 -1
- data/lib/ndb/rails/record.rb +2 -0
- data/lib/ndb/rails/record_writes.rb +182 -0
- data/lib/ndb/rails/relation.rb +237 -13
- data/lib/ndb/rails/transactions.rb +26 -10
- data/lib/ndb/rails/version.rb +1 -1
- data/lib/ndb/rails.rb +2 -0
- metadata +5 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 49cf1194840830bc05ef3ab2cb78db49f6c13056b116dbfd168c17867d942132
|
|
4
|
+
data.tar.gz: 0753e2a3968e06ad58584f89242fb2766840b2a84333e3006bf884f373a8d0d3
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 0d05b4c532f3653def1630087bce411e99126dbc0fe62085b833021ebcd113d7e1767630132920024960fc31761c65e02d08f8f5d2630ba61b3fafc07f5b9cef
|
|
7
|
+
data.tar.gz: f488d217b85c8860804af096ef8b445aa165fe28a35b70b2fde597af1713cb5de4577e566587baddaa592e35ad49f9ac46a89ef1deda2ac11f1938ca45c6fea3
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ndb
|
|
4
|
+
# after_commit and after_rollback, as ActiveRecord. They run when the write
|
|
5
|
+
# is durable: after the write itself, or, inside Model.transaction, after
|
|
6
|
+
# the transaction commits. after_rollback runs when the transaction writes
|
|
7
|
+
# nothing (an exception or Ndb::Rollback).
|
|
8
|
+
#
|
|
9
|
+
# after_create_commit { Billing.notify(id) }
|
|
10
|
+
# after_commit :reindex, on: %i[create update]
|
|
11
|
+
module CommitCallbacks
|
|
12
|
+
extend ActiveSupport::Concern
|
|
13
|
+
|
|
14
|
+
included do
|
|
15
|
+
define_callbacks :commit, :rollback
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
class_methods do
|
|
19
|
+
def after_commit(*args, on: nil, **options, &block)
|
|
20
|
+
set_callback(:commit, :after, *args, **on_action(on, options), &block)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def after_rollback(*args, on: nil, **options, &block)
|
|
24
|
+
set_callback(:rollback, :after, *args, **on_action(on, options), &block)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def after_create_commit(*args, **options, &block)
|
|
28
|
+
after_commit(*args, on: :create, **options, &block)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def after_update_commit(*args, **options, &block)
|
|
32
|
+
after_commit(*args, on: :update, **options, &block)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def after_save_commit(*args, **options, &block)
|
|
36
|
+
after_commit(*args, on: %i[create update], **options, &block)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def after_destroy_commit(*args, **options, &block)
|
|
40
|
+
after_commit(*args, on: :destroy, **options, &block)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
def on_action(on, options)
|
|
46
|
+
return options unless on
|
|
47
|
+
|
|
48
|
+
actions = Array(on)
|
|
49
|
+
|
|
50
|
+
options.merge(if: Array(options[:if]) + [-> { actions.include?(@commit_action) }])
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
private
|
|
55
|
+
|
|
56
|
+
# A write of action (:create, :update, :destroy) is done: its commit
|
|
57
|
+
# callbacks run now, or when the transaction it joined ends.
|
|
58
|
+
def committed(action)
|
|
59
|
+
if (tx = RecordTransaction.current)
|
|
60
|
+
tx.on_commit(self, action)
|
|
61
|
+
|
|
62
|
+
return
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
run_commit_callbacks(:commit, action)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def run_commit_callbacks(kind, action)
|
|
69
|
+
@commit_action = action
|
|
70
|
+
|
|
71
|
+
run_callbacks(kind)
|
|
72
|
+
ensure
|
|
73
|
+
@commit_action = nil
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
data/lib/ndb/rails/errors.rb
CHANGED
|
@@ -10,6 +10,9 @@ module Ndb
|
|
|
10
10
|
|
|
11
11
|
included do
|
|
12
12
|
define_model_callbacks :save, :create, :update, :destroy
|
|
13
|
+
|
|
14
|
+
include CommitCallbacks
|
|
15
|
+
include RecordWrites
|
|
13
16
|
end
|
|
14
17
|
|
|
15
18
|
class_methods do
|
|
@@ -46,6 +49,7 @@ module Ndb
|
|
|
46
49
|
record = new(row.slice(*attribute_names))
|
|
47
50
|
|
|
48
51
|
record.send(:loaded!, version, source)
|
|
52
|
+
record.send(:clear_changes_information)
|
|
49
53
|
record.load_associations(row) if record.respond_to?(:load_associations)
|
|
50
54
|
|
|
51
55
|
record
|
|
@@ -92,8 +96,13 @@ module Ndb
|
|
|
92
96
|
return false if validate && !valid?(new_record? ? :create : :update)
|
|
93
97
|
|
|
94
98
|
@expire_in = wire_duration(expire_in)
|
|
99
|
+
action = new_record? ? :create : :update
|
|
100
|
+
|
|
101
|
+
saved = run_callbacks(:save) { action == :create ? create_record : update_record } ? true : false
|
|
95
102
|
|
|
96
|
-
|
|
103
|
+
committed(action) if saved
|
|
104
|
+
|
|
105
|
+
saved
|
|
97
106
|
ensure
|
|
98
107
|
@expire_in = nil
|
|
99
108
|
end
|
|
@@ -146,6 +155,8 @@ module Ndb
|
|
|
146
155
|
@destroyed = true
|
|
147
156
|
end
|
|
148
157
|
|
|
158
|
+
committed(:destroy) if result
|
|
159
|
+
|
|
149
160
|
result ? self : false
|
|
150
161
|
end
|
|
151
162
|
|
data/lib/ndb/rails/record.rb
CHANGED
|
@@ -30,6 +30,8 @@ module Ndb
|
|
|
30
30
|
QUERY_METHODS = %i[
|
|
31
31
|
where where_raw order limit offset page after group unwind includes lock encrypted find find_by find_by! first last count pluck exists?
|
|
32
32
|
find_each in_batches sum average minimum maximum to_a each destroy_all delete_all to_ndb
|
|
33
|
+
update_all first! last! take take! sole find_sole_by destroy_by delete_by ids pick none
|
|
34
|
+
reorder rewhere unscope distinct select
|
|
33
35
|
].freeze
|
|
34
36
|
|
|
35
37
|
delegate(*QUERY_METHODS, to: :all)
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ndb
|
|
4
|
+
# The small writes of ActiveRecord: touch, update_columns, toggle!,
|
|
5
|
+
# update_attribute, insert_all, the counters, the saved changes of Dirty
|
|
6
|
+
# and the cache keys.
|
|
7
|
+
module RecordWrites
|
|
8
|
+
extend ActiveSupport::Concern
|
|
9
|
+
|
|
10
|
+
included do
|
|
11
|
+
define_model_callbacks :touch, only: :after
|
|
12
|
+
|
|
13
|
+
attribute_method_affix prefix: "saved_change_to_", suffix: "?"
|
|
14
|
+
attribute_method_affix prefix: "will_save_change_to_", suffix: "?"
|
|
15
|
+
attribute_method_suffix "_before_last_save"
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
class_methods do
|
|
19
|
+
# Inserts many documents in one _bulk: no validations, no callbacks.
|
|
20
|
+
# Each gets created_at and updated_at. An _id that exists raises
|
|
21
|
+
# Ndb::RecordNotUnique (code duplicate_id), as insert_all! of
|
|
22
|
+
# ActiveRecord.
|
|
23
|
+
def insert_all(rows)
|
|
24
|
+
ensure_collection!
|
|
25
|
+
|
|
26
|
+
now = Conditions.json_value(current_time)
|
|
27
|
+
|
|
28
|
+
docs = rows.map do |attrs|
|
|
29
|
+
doc = upsert_document(attrs)
|
|
30
|
+
|
|
31
|
+
doc["created_at"] ||= now
|
|
32
|
+
doc["updated_at"] ||= now
|
|
33
|
+
|
|
34
|
+
doc
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
Rails.client.bulk(collection_name, docs)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
alias_method :insert_all!, :insert_all
|
|
41
|
+
|
|
42
|
+
# Adds to number attributes of the documents with these ids in one
|
|
43
|
+
# atomic write, and sets updated_at. Returns the count of matches.
|
|
44
|
+
#
|
|
45
|
+
# Post.update_counters("p1", views: 1, likes: -1)
|
|
46
|
+
def update_counters(id_or_ids, counters)
|
|
47
|
+
ids = Array(id_or_ids)
|
|
48
|
+
inc = counters.to_h { |name, by| [name.to_s, by] }
|
|
49
|
+
ops = { "$inc" => inc, "$set" => { "updated_at" => Conditions.json_value(current_time) } }
|
|
50
|
+
|
|
51
|
+
ndb_update({ primary_key => { "$in" => ids } }, ops, many: true)["matched"]
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def increment_counter(name, id, by: 1)
|
|
55
|
+
update_counters(id, name => by)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def decrement_counter(name, id, by: 1)
|
|
59
|
+
update_counters(id, name => -by)
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Sets updated_at, and the named datetime attributes, to now (or time)
|
|
64
|
+
# in one atomic write. No validations, no save callbacks; after_touch
|
|
65
|
+
# runs. Other unsaved changes stay unsaved.
|
|
66
|
+
def touch(*names, time: nil)
|
|
67
|
+
now = time || self.class.current_time
|
|
68
|
+
values = ["updated_at", *names.map(&:to_s)].to_h { |name| [name, now] }
|
|
69
|
+
|
|
70
|
+
write_columns(values)
|
|
71
|
+
run_callbacks(:touch)
|
|
72
|
+
|
|
73
|
+
true
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# $set of these attributes, cast by type, in one atomic write. No
|
|
77
|
+
# validations, no callbacks, and updated_at does not change.
|
|
78
|
+
def update_columns(attrs)
|
|
79
|
+
write_columns(attrs.to_h { |name, value| [name.to_s, value] })
|
|
80
|
+
|
|
81
|
+
true
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def update_column(name, value)
|
|
85
|
+
update_columns(name => value)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def toggle(attribute)
|
|
89
|
+
public_send("#{attribute}=", !public_send(attribute))
|
|
90
|
+
|
|
91
|
+
self
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def toggle!(attribute)
|
|
95
|
+
toggle(attribute)
|
|
96
|
+
|
|
97
|
+
update_attribute(attribute, public_send(attribute))
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Saves with the callbacks and without the validations.
|
|
101
|
+
def update_attribute(name, value)
|
|
102
|
+
public_send("#{name}=", value)
|
|
103
|
+
|
|
104
|
+
save(validate: false)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def saved_changes = previous_changes
|
|
108
|
+
|
|
109
|
+
def saved_change_to_attribute?(name) = attribute_previously_changed?(name.to_s)
|
|
110
|
+
|
|
111
|
+
def saved_change_to_attribute(name) = attribute_previous_change(name.to_s)
|
|
112
|
+
|
|
113
|
+
def attribute_before_last_save(name) = attribute_previously_was(name.to_s)
|
|
114
|
+
|
|
115
|
+
def will_save_change_to_attribute?(name) = attribute_changed?(name.to_s)
|
|
116
|
+
|
|
117
|
+
# "posts/p1", or "posts/new" for a new record. The version is apart, in
|
|
118
|
+
# cache_version, as ActiveRecord with cache versioning.
|
|
119
|
+
def cache_key
|
|
120
|
+
"#{model_name.cache_key}/#{persisted? ? id : 'new'}"
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# updated_at and the document version: it changes on every write.
|
|
124
|
+
def cache_version
|
|
125
|
+
return unless persisted?
|
|
126
|
+
|
|
127
|
+
[updated_at&.utc&.to_fs(:usec), version].compact.join("-")
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def cache_key_with_version
|
|
131
|
+
version = cache_version
|
|
132
|
+
|
|
133
|
+
version.present? ? "#{cache_key}-#{version}" : cache_key
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
def write_columns(values)
|
|
139
|
+
raise RecordNotSaved, "Cannot update a record that is not saved" unless persisted?
|
|
140
|
+
|
|
141
|
+
raise_if_readonly
|
|
142
|
+
|
|
143
|
+
names = values.keys
|
|
144
|
+
|
|
145
|
+
unknown = names - self.class.attribute_names
|
|
146
|
+
|
|
147
|
+
raise ArgumentError, "#{unknown.join(', ')} is not an attribute of #{self.class.name}" if unknown.any?
|
|
148
|
+
|
|
149
|
+
values.each { |name, value| public_send("#{name}=", value) }
|
|
150
|
+
|
|
151
|
+
set = {}
|
|
152
|
+
unset = {}
|
|
153
|
+
|
|
154
|
+
names.each do |name|
|
|
155
|
+
value = json_attribute(name)
|
|
156
|
+
|
|
157
|
+
value.nil? ? unset[name] = true : set[name] = value
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
ops = {}
|
|
161
|
+
ops["$set"] = set unless set.empty?
|
|
162
|
+
ops["$unset"] = unset unless unset.empty?
|
|
163
|
+
|
|
164
|
+
send_columns(ops)
|
|
165
|
+
clear_attribute_changes(names)
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def send_columns(ops)
|
|
169
|
+
if (tx = current_transaction)
|
|
170
|
+
tx.update(self, ops)
|
|
171
|
+
|
|
172
|
+
return
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
result = holding { self.class.ndb_update({ self.class.primary_key => id }, ops, **lock_options) }
|
|
176
|
+
|
|
177
|
+
raise NotFound.new("#{self.class.name} #{id} was deleted", code: "not_found") if result["matched"].zero?
|
|
178
|
+
|
|
179
|
+
@version = result["doc"]["_v"]
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
end
|
data/lib/ndb/rails/relation.rb
CHANGED
|
@@ -11,6 +11,7 @@ module Ndb
|
|
|
11
11
|
BATCH_SIZE = 1000
|
|
12
12
|
EMPTY = { where: [].freeze, order: {}.freeze, group: [].freeze }.freeze
|
|
13
13
|
PRELOADED = Data.define(:rows, :next, :total).new(rows: [].freeze, next: nil, total: nil)
|
|
14
|
+
NONE = PRELOADED.with(total: 0)
|
|
14
15
|
|
|
15
16
|
attr_reader :klass, :values
|
|
16
17
|
|
|
@@ -44,9 +45,16 @@ module Ndb
|
|
|
44
45
|
with(where: [{ "$or" => clauses }])
|
|
45
46
|
end
|
|
46
47
|
|
|
48
|
+
# order(:n), order(n: :desc) or the Active Record String forms "n",
|
|
49
|
+
# "n DESC" and "n asc, m desc". Any other String (a SQL expression)
|
|
50
|
+
# raises ArgumentError.
|
|
47
51
|
def order(*args)
|
|
48
52
|
sort = args.each_with_object(values[:order].dup) do |arg, out|
|
|
49
|
-
|
|
53
|
+
case arg
|
|
54
|
+
when Hash then arg.each { |f, dir| out[f.to_s] = direction(dir) }
|
|
55
|
+
when String then out.merge!(parse_order(arg))
|
|
56
|
+
else out[arg.to_s] = 1
|
|
57
|
+
end
|
|
50
58
|
end
|
|
51
59
|
|
|
52
60
|
with(order: sort)
|
|
@@ -109,6 +117,57 @@ module Ndb
|
|
|
109
117
|
with(unwind: field.to_s)
|
|
110
118
|
end
|
|
111
119
|
|
|
120
|
+
# The order replaced, not added to: order(:a).reorder(b: :desc).
|
|
121
|
+
def reorder(*args)
|
|
122
|
+
with(order: {}).order(*args)
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# The where of these attributes replaced: where(n: 1).rewhere(n: 2).
|
|
126
|
+
# Only the equality clauses of these fields are removed.
|
|
127
|
+
def rewhere(attrs)
|
|
128
|
+
keys = alias_id(attrs).keys.map(&:to_s)
|
|
129
|
+
kept = values[:where].map { |clause| clause.except(*keys) }.reject(&:empty?)
|
|
130
|
+
|
|
131
|
+
with(where: kept).where(attrs)
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
UNSCOPE = {
|
|
135
|
+
where: { where: [].freeze }, order: { order: {}.freeze }, limit: { limit: nil }, offset: { offset: nil },
|
|
136
|
+
page: { page: nil, per: nil }, after: { after: nil }, group: { group: [].freeze }, includes: { includes: nil },
|
|
137
|
+
select: { select: nil }, distinct: { distinct: nil }
|
|
138
|
+
}.freeze
|
|
139
|
+
|
|
140
|
+
# The relation without these parts: unscope(:where, :order, :limit...).
|
|
141
|
+
def unscope(*types)
|
|
142
|
+
changes = types.reduce({}) do |out, type|
|
|
143
|
+
out.merge(UNSCOPE.fetch(type.to_sym) { raise ArgumentError, "unscope takes #{UNSCOPE.keys.join(", ")}, got #{type.inspect}" })
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
with(changes)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Makes pluck give each value (or row of values) once.
|
|
150
|
+
def distinct(value = true)
|
|
151
|
+
with(distinct: value)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# select(:a, :b): the records with only these attributes loaded (the
|
|
155
|
+
# daemon projection; the primary key is always read). With a block, it
|
|
156
|
+
# is Enumerable#select.
|
|
157
|
+
def select(*fields, &block)
|
|
158
|
+
return super(&block) if block
|
|
159
|
+
|
|
160
|
+
raise ArgumentError, "select needs at least one field" if fields.empty?
|
|
161
|
+
|
|
162
|
+
with(select: fields.map(&:to_s))
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# An empty relation: it sends no request. to_a is [], count is 0, and
|
|
166
|
+
# update and delete_all write nothing.
|
|
167
|
+
def none
|
|
168
|
+
with(none: true)
|
|
169
|
+
end
|
|
170
|
+
|
|
112
171
|
# The JSON body that this relation sends to the daemon, as a String,
|
|
113
172
|
# with no request (like to_sql of ActiveRecord). It is the body of
|
|
114
173
|
# POST /{collection}/_search; pretty: true gives it on many lines.
|
|
@@ -133,32 +192,84 @@ module Ndb
|
|
|
133
192
|
query.merge!(window)
|
|
134
193
|
query["after"] = values[:after] if values[:after]
|
|
135
194
|
query["lookup"] = klass.lookup_for(values[:includes]) if values[:includes]&.any?
|
|
195
|
+
query["fields"] = ([klass.primary_key] + values[:select]).uniq if values[:select]
|
|
136
196
|
|
|
137
197
|
query
|
|
138
198
|
end
|
|
139
199
|
|
|
140
200
|
# Atomic writes. The daemon matches the where and writes in one step on
|
|
141
201
|
# every match, so the where needs the id or an indexed field
|
|
142
|
-
# (Ndb::UnindexedMany otherwise).
|
|
143
|
-
#
|
|
144
|
-
#
|
|
202
|
+
# (Ndb::UnindexedMany otherwise). Returns the number of modified
|
|
203
|
+
# documents. It takes attributes, as Active Record (update(status: "x")
|
|
204
|
+
# is a $set, cast by the attribute types), the operators of
|
|
205
|
+
# Ndb::Client#update ("$inc" => { "n" => 1 }), or both: the attributes
|
|
206
|
+
# join the $set. Unlike Active Record, it runs no validation and no
|
|
207
|
+
# callback (as update_all).
|
|
145
208
|
def update(ops = nil, expire_in: nil, **ops_kw)
|
|
146
|
-
ops = (ops || {}).merge(ops_kw)
|
|
147
|
-
|
|
209
|
+
ops = (ops || {}).merge(ops_kw).transform_keys(&:to_s)
|
|
210
|
+
attrs, ops = ops.partition { |key, _| !key.start_with?("$") }.map(&:to_h)
|
|
148
211
|
|
|
149
|
-
raise ArgumentError, "update takes
|
|
212
|
+
raise ArgumentError, "update takes attributes (status: \"x\") or operators (\"$inc\" => { n: 1 })" if attrs.empty? && ops.empty?
|
|
150
213
|
|
|
151
|
-
|
|
214
|
+
ops = with_attributes(ops, attrs) unless attrs.empty?
|
|
215
|
+
|
|
216
|
+
where = write_where
|
|
217
|
+
|
|
218
|
+
return 0 unless where
|
|
219
|
+
|
|
220
|
+
klass.ndb_update(where, with_updated_at(ops), many: true, expire_in: expire_in).fetch("modified")
|
|
152
221
|
end
|
|
153
222
|
|
|
154
223
|
# One daemon delete on every match, no callbacks (same rule as update).
|
|
155
224
|
# Returns how many. An unfiltered relation is refused by the daemon
|
|
156
|
-
# (Ndb::EmptyFilter).
|
|
225
|
+
# (Ndb::EmptyFilter). A limit, offset, page or cursor narrows it to
|
|
226
|
+
# those rows, as for update.
|
|
157
227
|
def delete_all
|
|
158
|
-
|
|
228
|
+
where = write_where
|
|
229
|
+
|
|
230
|
+
return 0 unless where
|
|
231
|
+
|
|
232
|
+
klass.ndb_delete(where, many: true).fetch("deleted")
|
|
159
233
|
end
|
|
160
234
|
|
|
161
235
|
alias delete delete_all
|
|
236
|
+
alias update_all update
|
|
237
|
+
|
|
238
|
+
# A new record with the equality attributes of the where, as the
|
|
239
|
+
# scoping of Active Record: Call.where(status: "new").new(caller: "a").
|
|
240
|
+
def new(attrs = {}, &block)
|
|
241
|
+
klass.new(scope_attributes.merge(attrs.transform_keys(&:to_s))).tap { |record| block&.call(record) }
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
alias build new
|
|
245
|
+
|
|
246
|
+
def create(attrs = {}, &)
|
|
247
|
+
new(attrs, &).tap(&:save)
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
def create!(attrs = {}, &)
|
|
251
|
+
new(attrs, &).tap(&:save!)
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
def find_or_initialize_by(attrs, &)
|
|
255
|
+
klass.find_or_initialize_by(scope_attributes.merge(attrs.transform_keys(&:to_s)), &)
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def find_or_create_by(attrs, &)
|
|
259
|
+
klass.find_or_create_by(scope_attributes.merge(attrs.transform_keys(&:to_s)), &)
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
def find_or_create_by!(attrs, &)
|
|
263
|
+
klass.find_or_create_by!(scope_attributes.merge(attrs.transform_keys(&:to_s)), &)
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
def destroy_by(attrs)
|
|
267
|
+
where(attrs).destroy_all
|
|
268
|
+
end
|
|
269
|
+
|
|
270
|
+
def delete_by(attrs)
|
|
271
|
+
where(attrs).delete_all
|
|
272
|
+
end
|
|
162
273
|
|
|
163
274
|
# Loads the matches and destroys each one, with its callbacks. Returns
|
|
164
275
|
# the records.
|
|
@@ -249,6 +360,43 @@ module Ndb
|
|
|
249
360
|
count ? found : found.last
|
|
250
361
|
end
|
|
251
362
|
|
|
363
|
+
def first!
|
|
364
|
+
first || raise(not_found)
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
def last!
|
|
368
|
+
last || raise(not_found)
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
# A record (or count of them) in no given order: the order of the
|
|
372
|
+
# relation, else the order of the daemon.
|
|
373
|
+
def take(count = nil)
|
|
374
|
+
return count ? records.first(count) : records.first if loaded?
|
|
375
|
+
|
|
376
|
+
found = limit(count || 1).to_a
|
|
377
|
+
|
|
378
|
+
count ? found : found.first
|
|
379
|
+
end
|
|
380
|
+
|
|
381
|
+
def take!
|
|
382
|
+
take || raise(not_found)
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
# The one record of the relation: Ndb::NotFound when none,
|
|
386
|
+
# Ndb::SoleRecordExceeded when more than one.
|
|
387
|
+
def sole
|
|
388
|
+
found = limit(2).to_a
|
|
389
|
+
|
|
390
|
+
raise not_found if found.empty?
|
|
391
|
+
raise SoleRecordExceeded, "Wanted only one #{klass.name}" if found.size > 1
|
|
392
|
+
|
|
393
|
+
found.first
|
|
394
|
+
end
|
|
395
|
+
|
|
396
|
+
def find_sole_by(attrs)
|
|
397
|
+
where(attrs).sole
|
|
398
|
+
end
|
|
399
|
+
|
|
252
400
|
# The relation with its order turned around (asc and desc swap). With no
|
|
253
401
|
# order, it is the primary key in descending order.
|
|
254
402
|
def reverse_order
|
|
@@ -284,7 +432,18 @@ module Ndb
|
|
|
284
432
|
return where(conditions).exists? if conditions.is_a?(Hash)
|
|
285
433
|
return where(klass.primary_key => conditions).exists? unless conditions == :none
|
|
286
434
|
|
|
287
|
-
|
|
435
|
+
limit = [window["limit"], 1].compact.min
|
|
436
|
+
|
|
437
|
+
return false if limit.zero?
|
|
438
|
+
|
|
439
|
+
fetch(to_query.except("lookup").merge("limit" => limit, "fields" => [klass.primary_key])).rows.any?
|
|
440
|
+
end
|
|
441
|
+
|
|
442
|
+
# The primary keys of the relation, in its order (one request).
|
|
443
|
+
def ids
|
|
444
|
+
return records.map { |record| record.public_send(klass.primary_key) } if loaded?
|
|
445
|
+
|
|
446
|
+
fetch(to_query.except("lookup").merge("fields" => [klass.primary_key])).rows.map { |row| row[klass.primary_key] }
|
|
288
447
|
end
|
|
289
448
|
|
|
290
449
|
def pluck(*fields)
|
|
@@ -293,15 +452,23 @@ module Ndb
|
|
|
293
452
|
names = fields.map(&:to_s)
|
|
294
453
|
rows = fetch(to_query.merge("fields" => names)).rows
|
|
295
454
|
|
|
296
|
-
rows.map do |row|
|
|
455
|
+
plucked = rows.map do |row|
|
|
297
456
|
values = names.map { |name| klass.attribute_types[name].cast(row.dig(*name.split("."))) }
|
|
298
457
|
|
|
299
458
|
values.size == 1 ? values.first : values
|
|
300
459
|
end
|
|
460
|
+
|
|
461
|
+
values[:distinct] ? plucked.uniq : plucked
|
|
462
|
+
end
|
|
463
|
+
|
|
464
|
+
# pluck of the first row: a value, an Array of values, or nil.
|
|
465
|
+
def pick(*fields)
|
|
466
|
+
limit(1).pluck(*fields).first
|
|
301
467
|
end
|
|
302
468
|
|
|
303
469
|
def count
|
|
304
470
|
return calculate(:count) unless values[:group].empty? && values[:unwind].nil?
|
|
471
|
+
return ids.size if narrowed?
|
|
305
472
|
|
|
306
473
|
fetch(to_query.slice("query").merge("count" => true, "limit" => 1, "fields" => [klass.primary_key])).total
|
|
307
474
|
end
|
|
@@ -377,13 +544,39 @@ module Ndb
|
|
|
377
544
|
private
|
|
378
545
|
|
|
379
546
|
def fetch(body)
|
|
547
|
+
return NONE if values[:none]
|
|
548
|
+
|
|
380
549
|
sealed_or_plain { klass.ndb_find(body) }
|
|
381
550
|
end
|
|
382
551
|
|
|
552
|
+
def not_found
|
|
553
|
+
NotFound.new("Couldn't find #{klass.name}", code: "not_found")
|
|
554
|
+
end
|
|
555
|
+
|
|
556
|
+
# The fields of the equality clauses of the where (status: "x"), for
|
|
557
|
+
# new and create. Operators ($in, $gte...) are not values.
|
|
558
|
+
def scope_attributes
|
|
559
|
+
values[:where].each_with_object({}) do |clause, out|
|
|
560
|
+
clause.each { |key, value| out[key] = value unless key.start_with?("$") || value.is_a?(Hash) || value.is_a?(Array) }
|
|
561
|
+
end
|
|
562
|
+
end
|
|
563
|
+
|
|
383
564
|
def sealed_or_plain(&)
|
|
384
565
|
values[:keep_encrypted] ? Rails.client.keep_encrypted(&) : yield
|
|
385
566
|
end
|
|
386
567
|
|
|
568
|
+
# ops with attrs, cast by their types, in its $set. A field in both is
|
|
569
|
+
# refused: it is not clear which value wins.
|
|
570
|
+
def with_attributes(ops, attrs)
|
|
571
|
+
set = (ops["$set"] || {}).transform_keys(&:to_s)
|
|
572
|
+
doc = klass.send(:upsert_document, attrs)
|
|
573
|
+
both = set.keys & doc.keys
|
|
574
|
+
|
|
575
|
+
raise ArgumentError, "update sets #{both.join(", ")} twice: as an attribute and in $set" if both.any?
|
|
576
|
+
|
|
577
|
+
ops.merge("$set" => set.merge(doc))
|
|
578
|
+
end
|
|
579
|
+
|
|
387
580
|
# The operators with $set of updated_at, unless they write it already.
|
|
388
581
|
def with_updated_at(ops)
|
|
389
582
|
ops = ops.transform_keys(&:to_s)
|
|
@@ -422,6 +615,37 @@ module Ndb
|
|
|
422
615
|
values[:limit] || values[:offset] || values[:page]
|
|
423
616
|
end
|
|
424
617
|
|
|
618
|
+
# A window or a cursor: the relation is fewer rows than its where.
|
|
619
|
+
def narrowed?
|
|
620
|
+
windowed? || values[:after]
|
|
621
|
+
end
|
|
622
|
+
|
|
623
|
+
# The filter of update and delete_all: the where, and the ids of the
|
|
624
|
+
# rows when the relation is narrowed (the daemon writes every match of
|
|
625
|
+
# a filter). nil when a narrowed relation has no row.
|
|
626
|
+
def write_where
|
|
627
|
+
return nil if values[:none]
|
|
628
|
+
return Conditions.combine(values[:where]) unless narrowed?
|
|
629
|
+
|
|
630
|
+
found = ids
|
|
631
|
+
|
|
632
|
+
return nil if found.empty?
|
|
633
|
+
|
|
634
|
+
Conditions.combine(values[:where] + [{ klass.primary_key => { "$in" => found } }])
|
|
635
|
+
end
|
|
636
|
+
|
|
637
|
+
ORDER_PART = /\A([\w.]+)(?:\s+(asc|desc))?\z/i
|
|
638
|
+
|
|
639
|
+
def parse_order(text)
|
|
640
|
+
text.split(",").to_h do |part|
|
|
641
|
+
match = ORDER_PART.match(part.strip)
|
|
642
|
+
|
|
643
|
+
raise ArgumentError, "order takes \"field\" or \"field asc|desc\", got #{text.inspect}" unless match
|
|
644
|
+
|
|
645
|
+
[match[1], direction(match[2])]
|
|
646
|
+
end
|
|
647
|
+
end
|
|
648
|
+
|
|
425
649
|
def direction(value)
|
|
426
650
|
%w[desc -1].include?(value.to_s.downcase) ? -1 : 1
|
|
427
651
|
end
|
|
@@ -482,7 +706,7 @@ module Ndb
|
|
|
482
706
|
|
|
483
707
|
def calculate(op, field = nil)
|
|
484
708
|
key = op.to_s
|
|
485
|
-
rows = sealed_or_plain { klass.ndb_aggregate(aggregate_body(op, field)) }.rows
|
|
709
|
+
rows = values[:none] ? [] : sealed_or_plain { klass.ndb_aggregate(aggregate_body(op, field)) }.rows
|
|
486
710
|
|
|
487
711
|
return rows.to_h { |row| [group_key(row["_id"]), row[key]] } unless values[:group].empty?
|
|
488
712
|
|
|
@@ -53,19 +53,25 @@ module Ndb
|
|
|
53
53
|
tx.lock_records(Array(lock), ttl: ttl, wait: wait) if lock
|
|
54
54
|
result = yield
|
|
55
55
|
tx.commit!
|
|
56
|
-
|
|
57
|
-
result
|
|
58
56
|
rescue Rollback
|
|
59
57
|
tx.abort!
|
|
58
|
+
RecordTransaction.current = nil
|
|
59
|
+
tx.run_commit_callbacks(:rollback)
|
|
60
60
|
|
|
61
|
-
nil
|
|
61
|
+
return nil
|
|
62
62
|
rescue Exception # rubocop:disable Lint/RescueException
|
|
63
63
|
tx.abort!
|
|
64
|
+
RecordTransaction.current = nil
|
|
65
|
+
tx.run_commit_callbacks(:rollback)
|
|
64
66
|
|
|
65
67
|
raise
|
|
66
68
|
ensure
|
|
67
69
|
RecordTransaction.current = nil
|
|
68
70
|
end
|
|
71
|
+
|
|
72
|
+
tx.run_commit_callbacks(:commit)
|
|
73
|
+
|
|
74
|
+
result
|
|
69
75
|
end
|
|
70
76
|
end
|
|
71
77
|
|
|
@@ -99,6 +105,7 @@ module Ndb
|
|
|
99
105
|
@tokens = []
|
|
100
106
|
@guarded = {}
|
|
101
107
|
@locked = {}
|
|
108
|
+
@commits = []
|
|
102
109
|
end
|
|
103
110
|
|
|
104
111
|
def collection = @klass.collection_name
|
|
@@ -152,17 +159,21 @@ module Ndb
|
|
|
152
159
|
add({ op: "delete", id: record.id, query: guard(record) }.compact, record)
|
|
153
160
|
end
|
|
154
161
|
|
|
162
|
+
# A save or destroy of the block: its after_commit callbacks run after
|
|
163
|
+
# the commit, its after_rollback callbacks after an abort.
|
|
164
|
+
def on_commit(record, action)
|
|
165
|
+
@commits << [record, action]
|
|
166
|
+
end
|
|
167
|
+
|
|
155
168
|
def commit!
|
|
156
169
|
if @ops.empty?
|
|
157
170
|
release
|
|
171
|
+
else
|
|
172
|
+
results = Rails.client.tx(collection, @ops.map(&:first), locks: @tokens, unlock: true)["results"]
|
|
158
173
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
results = Rails.client.tx(collection, @ops.map(&:first), locks: @tokens, unlock: true)["results"]
|
|
163
|
-
|
|
164
|
-
@ops.zip(results).each do |(_, record), result|
|
|
165
|
-
record.send(:written_in_transaction!, result["_v"]) if result["_v"]
|
|
174
|
+
@ops.zip(results).each do |(_, record), result|
|
|
175
|
+
record.send(:written_in_transaction!, result["_v"]) if result["_v"]
|
|
176
|
+
end
|
|
166
177
|
end
|
|
167
178
|
ensure
|
|
168
179
|
finish
|
|
@@ -173,6 +184,11 @@ module Ndb
|
|
|
173
184
|
finish
|
|
174
185
|
end
|
|
175
186
|
|
|
187
|
+
# Runs after the block ends, so a write in a callback is a new write.
|
|
188
|
+
def run_commit_callbacks(kind)
|
|
189
|
+
@commits.each { |record, action| record.send(:run_commit_callbacks, kind, action) }
|
|
190
|
+
end
|
|
191
|
+
|
|
176
192
|
private
|
|
177
193
|
|
|
178
194
|
def add(op, record)
|
data/lib/ndb/rails/version.rb
CHANGED
data/lib/ndb/rails.rb
CHANGED
|
@@ -11,6 +11,8 @@ require "ndb/rails/dynamic_finders"
|
|
|
11
11
|
require "ndb/rails/relation"
|
|
12
12
|
require "ndb/rails/validations"
|
|
13
13
|
require "ndb/rails/blob"
|
|
14
|
+
require "ndb/rails/commit_callbacks"
|
|
15
|
+
require "ndb/rails/record_writes"
|
|
14
16
|
require "ndb/rails/persistence"
|
|
15
17
|
require "ndb/rails/locking"
|
|
16
18
|
require "ndb/rails/transactions"
|
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.
|
|
4
|
+
version: 1.24.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.
|
|
46
|
+
version: 1.24.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.
|
|
56
|
+
version: 1.24.0
|
|
57
57
|
- - "<"
|
|
58
58
|
- !ruby/object:Gem::Version
|
|
59
59
|
version: '2'
|
|
@@ -70,6 +70,7 @@ files:
|
|
|
70
70
|
- lib/ndb/rails.rb
|
|
71
71
|
- lib/ndb/rails/associations.rb
|
|
72
72
|
- lib/ndb/rails/blob.rb
|
|
73
|
+
- lib/ndb/rails/commit_callbacks.rb
|
|
73
74
|
- lib/ndb/rails/configuration.rb
|
|
74
75
|
- lib/ndb/rails/database_cleaner.rb
|
|
75
76
|
- lib/ndb/rails/dynamic_finders.rb
|
|
@@ -80,6 +81,7 @@ files:
|
|
|
80
81
|
- lib/ndb/rails/persistence.rb
|
|
81
82
|
- lib/ndb/rails/railtie.rb
|
|
82
83
|
- lib/ndb/rails/record.rb
|
|
84
|
+
- lib/ndb/rails/record_writes.rb
|
|
83
85
|
- lib/ndb/rails/relation.rb
|
|
84
86
|
- lib/ndb/rails/rspec.rb
|
|
85
87
|
- lib/ndb/rails/testing.rb
|