Class: TableSync::Model::Sequel
- Inherits:
-
Object
- Object
- TableSync::Model::Sequel
- Defined in:
- lib/table_sync/model/sequel.rb
Instance Method Summary collapse
- #after_commit(&block) ⇒ Object
- #columns ⇒ Object
- #destroy(data) ⇒ Object
-
#initialize(table_name) ⇒ Sequel
constructor
A new instance of Sequel.
- #primary_keys ⇒ Object
- #transaction(&block) ⇒ Object
- #upsert(data:, target_keys:, version_key:, first_sync_time_key:, default_values:) ⇒ Object
Constructor Details
#initialize(table_name) ⇒ Sequel
5 6 7 |
# File 'lib/table_sync/model/sequel.rb', line 5 def initialize(table_name) @raw_model = Class.new(::Sequel::Model(table_name)).tap(&:unrestrict_primary_key) end |
Instance Method Details
#after_commit(&block) ⇒ Object
56 57 58 |
# File 'lib/table_sync/model/sequel.rb', line 56 def after_commit(&block) db.after_commit(&block) end |
#columns ⇒ Object
9 10 11 |
# File 'lib/table_sync/model/sequel.rb', line 9 def columns dataset.columns end |
#destroy(data) ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/table_sync/model/sequel.rb', line 44 def destroy(data) result = dataset.returning.where(data).delete TableSync::Instrument.notify table: model_naming.table, schema: model_naming.schema, count: result.count, event: :destroy, direction: :receive result end |
#primary_keys ⇒ Object
13 14 15 |
# File 'lib/table_sync/model/sequel.rb', line 13 def primary_keys [raw_model.primary_key].flatten end |
#transaction(&block) ⇒ Object
52 53 54 |
# File 'lib/table_sync/model/sequel.rb', line 52 def transaction(&block) db.transaction(&block) end |
#upsert(data:, target_keys:, version_key:, first_sync_time_key:, default_values:) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/table_sync/model/sequel.rb', line 17 def upsert(data:, target_keys:, version_key:, first_sync_time_key:, default_values:) data = Array.wrap(data) qualified_version = ::Sequel.qualify(table_name, version_key) version_condition = ::Sequel.function(:coalesce, qualified_version, 0) < ::Sequel.qualify(:excluded, version_key) upd_spec = update_spec(data.first.keys - target_keys) data.map! { |d| default_values.merge(d) } insert_data = type_cast(data) if first_sync_time_key insert_data.each { |datum| datum[first_sync_time_key] = Time.current } end result = dataset.returning .insert_conflict( target: target_keys, update: upd_spec, update_where: version_condition, ) .multi_insert(insert_data) TableSync::Instrument.notify table: model_naming.table, schema: model_naming.schema, count: result.count, event: :update, direction: :receive result end |