2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
class DraftSequence < ActiveRecord::Base
|
|
|
|
def self.next!(user, key)
|
2020-05-26 08:07:00 +08:00
|
|
|
return nil if !user
|
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
user_id = user
|
2017-04-15 12:11:02 +08:00
|
|
|
user_id = user.id unless user.is_a?(Integer)
|
2014-06-25 08:55:35 +08:00
|
|
|
|
2020-05-26 08:07:00 +08:00
|
|
|
return 0 if !User.human_user_id?(user_id)
|
2014-06-25 08:55:35 +08:00
|
|
|
|
2021-03-06 03:40:00 +08:00
|
|
|
sequence = DB.query_single(<<~SQL, user_id: user_id, draft_key: key).first
|
|
|
|
INSERT INTO draft_sequences (user_id, draft_key, sequence)
|
|
|
|
VALUES (:user_id, :draft_key, 1)
|
|
|
|
ON CONFLICT (user_id, draft_key) DO
|
|
|
|
UPDATE
|
|
|
|
SET sequence = draft_sequences.sequence + 1
|
|
|
|
WHERE draft_sequences.user_id = :user_id
|
|
|
|
AND draft_sequences.draft_key = :draft_key
|
|
|
|
RETURNING sequence
|
|
|
|
SQL
|
|
|
|
|
|
|
|
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: sequence,
|
|
|
|
)
|
|
|
|
|
2021-08-04 18:30:37 +08:00
|
|
|
UserStat.update_draft_count(user_id)
|
|
|
|
|
2021-03-06 03:40:00 +08:00
|
|
|
sequence
|
2013-02-06 03:16:51 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.current(user, key)
|
2020-05-26 08:07:00 +08:00
|
|
|
return nil if !user
|
2013-02-06 03:16:51 +08:00
|
|
|
|
|
|
|
user_id = user
|
2017-04-15 12:11:02 +08:00
|
|
|
user_id = user.id unless user.is_a?(Integer)
|
2013-02-06 03:16:51 +08:00
|
|
|
|
2020-05-26 08:07:00 +08:00
|
|
|
return 0 if !User.human_user_id?(user_id)
|
2020-05-12 13:56:24 +08:00
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
# perf critical path
|
2018-06-19 14:13:14 +08:00
|
|
|
r, _ =
|
|
|
|
DB.query_single(
|
|
|
|
"select sequence from draft_sequences where user_id = ? and draft_key = ?",
|
|
|
|
user_id,
|
|
|
|
key,
|
|
|
|
)
|
|
|
|
r.to_i
|
2013-02-06 03:16:51 +08:00
|
|
|
end
|
|
|
|
end
|
2013-05-24 10:48:32 +08:00
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: draft_sequences
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# user_id :integer not null
|
2019-01-12 03:29:56 +08:00
|
|
|
# draft_key :string not null
|
2020-05-12 14:55:24 +08:00
|
|
|
# sequence :bigint not null
|
2013-05-24 10:48:32 +08:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
|
|
|
# index_draft_sequences_on_user_id_and_draft_key (user_id,draft_key) UNIQUE
|
|
|
|
#
|