github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/profile_reply_store.go (about)

     1  package common
     2  
     3  import (
     4  	"database/sql"
     5  
     6  	qgen "github.com/Azareal/Gosora/query_gen"
     7  )
     8  
     9  var Prstore ProfileReplyStore
    10  
    11  type ProfileReplyStore interface {
    12  	Get(id int) (*ProfileReply, error)
    13  	Exists(id int) bool
    14  	ClearIPs() error
    15  	Create(profileID int, content string, createdBy int, ip string) (id int, err error)
    16  	Count() (count int)
    17  }
    18  
    19  // TODO: Refactor this to stop using the global stmt store
    20  // TODO: Add more methods to this like Create()
    21  type SQLProfileReplyStore struct {
    22  	get    *sql.Stmt
    23  	exists *sql.Stmt
    24  	create *sql.Stmt
    25  	count  *sql.Stmt
    26  
    27  	clearIPs *sql.Stmt
    28  }
    29  
    30  func NewSQLProfileReplyStore(acc *qgen.Accumulator) (*SQLProfileReplyStore, error) {
    31  	ur := "users_replies"
    32  	return &SQLProfileReplyStore{
    33  		get:    acc.Select(ur).Columns("uid,content,createdBy,createdAt,lastEdit,lastEditBy,ip").Where("rid=?").Stmt(),
    34  		exists: acc.Exists(ur, "rid").Prepare(),
    35  		create: acc.Insert(ur).Columns("uid,content,parsed_content,createdAt,createdBy,ip").Fields("?,?,?,UTC_TIMESTAMP(),?,?").Prepare(),
    36  		count:  acc.Count(ur).Stmt(),
    37  
    38  		clearIPs: acc.Update(ur).Set("ip=''").Where("ip!=''").Stmt(),
    39  	}, acc.FirstError()
    40  }
    41  
    42  func (s *SQLProfileReplyStore) Get(id int) (*ProfileReply, error) {
    43  	r := ProfileReply{ID: id}
    44  	e := s.get.QueryRow(id).Scan(&r.ParentID, &r.Content, &r.CreatedBy, &r.CreatedAt, &r.LastEdit, &r.LastEditBy, &r.IP)
    45  	return &r, e
    46  }
    47  
    48  func (s *SQLProfileReplyStore) Exists(id int) bool {
    49  	e := s.exists.QueryRow(id).Scan(&id)
    50  	if e != nil && e != ErrNoRows {
    51  		LogError(e)
    52  	}
    53  	return e != ErrNoRows
    54  }
    55  
    56  func (s *SQLProfileReplyStore) ClearIPs() error {
    57  	_, e := s.clearIPs.Exec()
    58  	return e
    59  }
    60  
    61  func (s *SQLProfileReplyStore) Create(profileID int, content string, createdBy int, ip string) (id int, e error) {
    62  	if Config.DisablePostIP {
    63  		ip = ""
    64  	}
    65  	res, e := s.create.Exec(profileID, content, ParseMessage(content, 0, "", nil, nil), createdBy, ip)
    66  	if e != nil {
    67  		return 0, e
    68  	}
    69  	lastID, e := res.LastInsertId()
    70  	if e != nil {
    71  		return 0, e
    72  	}
    73  	// Should we reload the user?
    74  	return int(lastID), e
    75  }
    76  
    77  // TODO: Write a test for this
    78  // Count returns the total number of topic replies on these forums
    79  func (s *SQLProfileReplyStore) Count() (count int) {
    80  	return Count(s.count)
    81  }