2019-05-02 18:17:27 -04:00
# frozen_string_literal: true
2013-02-05 14:16:51 -05:00
class DraftSequence < ActiveRecord :: Base
2017-07-27 21:20:09 -04:00
def self . next! ( user , key )
2020-05-25 20:07:00 -04:00
return nil if ! user
2013-02-05 14:16:51 -05:00
user_id = user
2017-04-15 00:11:02 -04:00
user_id = user . id unless user . is_a? ( Integer )
2014-06-24 20:55:35 -04:00
2020-05-25 20:07:00 -04:00
return 0 if ! User . human_user_id? ( user_id )
2014-06-24 20:55:35 -04:00
2013-02-28 13:54:12 -05:00
h = { user_id : user_id , draft_key : key }
2014-05-06 09:41:59 -04:00
c = DraftSequence . find_by ( h )
2013-02-05 14:16:51 -05:00
c || = DraftSequence . new ( h )
c . sequence || = 0
c . sequence += 1
2017-09-15 04:44:04 -04:00
c . save!
2018-06-19 02:13:14 -04:00
DB . exec ( " DELETE FROM drafts WHERE user_id = :user_id AND draft_key = :draft_key AND sequence < :sequence " , draft_key : key , user_id : user_id , sequence : c . sequence )
2013-02-05 14:16:51 -05:00
c . sequence
end
def self . current ( user , key )
2020-05-25 20:07:00 -04:00
return nil if ! user
2013-02-05 14:16:51 -05:00
user_id = user
2017-04-15 00:11:02 -04:00
user_id = user . id unless user . is_a? ( Integer )
2013-02-05 14:16:51 -05:00
2020-05-25 20:07:00 -04:00
return 0 if ! User . human_user_id? ( user_id )
2020-05-12 01:56:24 -04:00
2013-02-05 14:16:51 -05:00
# perf critical path
2018-06-19 02:13:14 -04:00
r , _ = DB . query_single ( 'select sequence from draft_sequences where user_id = ? and draft_key = ?' , user_id , key )
r . to_i
2013-02-05 14:16:51 -05:00
end
end
2013-05-23 22:48:32 -04:00
# == Schema Information
#
# Table name: draft_sequences
#
# id :integer not null, primary key
# user_id :integer not null
2019-01-11 14:29:56 -05:00
# draft_key :string not null
2020-05-12 02:55:24 -04:00
# sequence :bigint not null
2013-05-23 22:48:32 -04:00
#
# Indexes
#
# index_draft_sequences_on_user_id_and_draft_key (user_id,draft_key) UNIQUE
#