Module: Motor::Queries::Persistance

Defined in:
lib/motor/queries/persistance.rb

Constant Summary collapse

NameAlreadyExists =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.archive_with_existing_name(query) ⇒ Object


59
60
61
62
# File 'lib/motor/queries/persistance.rb', line 59

def archive_with_existing_name(query)
  Motor::Query.where(['name = ? AND id != ?', query.name, query.id])
              .update_all(deleted_at: Time.current)
end

.assign_attributes(query, params) ⇒ Object


52
53
54
55
56
57
# File 'lib/motor/queries/persistance.rb', line 52

def assign_attributes(query, params)
  query.assign_attributes(params.slice(:name, :description, :sql_body, :preferences))
  query.updated_at = [params[:updated_at], Time.current].min if params[:updated_at].present?

  Motor::Tags.assign_tags(query, params[:tags])
end

.build_from_params(params, current_user = nil) ⇒ Object


10
11
12
13
14
15
16
# File 'lib/motor/queries/persistance.rb', line 10

def build_from_params(params, current_user = nil)
  query = assign_attributes(Query.new, params)

  query.author = current_user

  query
end

.create_from_params!(params, current_user = nil) ⇒ Object


18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/motor/queries/persistance.rb', line 18

def create_from_params!(params, current_user = nil)
  raise NameAlreadyExists if Query.exists?(name: params[:name])

  query = build_from_params(params, current_user)

  ApplicationRecord.transaction do
    query.save!
  end

  query
rescue ActiveRecord::RecordNotUnique
  retry
end

.name_already_exists?(query) ⇒ Boolean

Returns:

  • (Boolean)

64
65
66
67
68
69
70
# File 'lib/motor/queries/persistance.rb', line 64

def name_already_exists?(query)
  if query.new_record?
    Query.exists?(name: query.name)
  else
    Query.exists?(['name = ? AND id != ?', query.name, query.id])
  end
end

.update_from_params!(query, params, force_replace: false) ⇒ Object


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/motor/queries/persistance.rb', line 32

def update_from_params!(query, params, force_replace: false)
  tag_ids = query.tags.ids

  query = assign_attributes(query, params)

  raise NameAlreadyExists if !force_replace && name_already_exists?(query)

  ApplicationRecord.transaction do
    archive_with_existing_name(query) if force_replace

    query.save!
  end

  query.touch if tag_ids.sort != query.tags.reload.ids.sort && params[:updated_at].blank?

  query
rescue ActiveRecord::RecordNotUnique
  retry
end