jet/sqlbuilder/lock_statement.go

102 lines
2 KiB
Go
Raw Normal View History

2019-05-07 13:44:30 +02:00
package sqlbuilder
import (
"database/sql"
"github.com/pkg/errors"
"github.com/sub0zero/go-sqlbuilder/types"
)
type lockMode string
const (
LOCK_ACCESS_SHARE = "ACCESS SHARE"
LOCK_ROW_SHARE = "ROW SHARE"
LOCK_ROW_EXCLUSIVE = "ROW EXCLUSIVE"
LOCK_SHARE_UPDATE_EXCLUSIVE = "SHARE UPDATE EXCLUSIVE"
LOCK_SHARE = "SHARE"
LOCK_SHARE_ROW_EXCLUSIVE = "SHARE ROW EXCLUSIVE"
LOCK_EXCLUSIVE = "EXCLUSIVE"
LOCK_ACCESS_EXCLUSIVE = "ACCESS EXCLUSIVE"
)
type lockStatement interface {
2019-05-12 18:15:23 +02:00
Statement
2019-05-07 13:44:30 +02:00
IN(lockMode lockMode) lockStatement
NOWAIT() lockStatement
}
type lockStatementImpl struct {
tables []tableInterface
lockMode lockMode
nowait bool
}
func LOCK(tables ...tableInterface) lockStatement {
return &lockStatementImpl{
tables: tables,
}
}
func (l *lockStatementImpl) IN(lockMode lockMode) lockStatement {
l.lockMode = lockMode
return l
}
func (l *lockStatementImpl) NOWAIT() lockStatement {
l.nowait = true
return l
}
2019-05-12 18:15:23 +02:00
func (l *lockStatementImpl) DebugSql() (query string, err error) {
return DebugSql(l)
}
2019-05-07 13:44:30 +02:00
func (l *lockStatementImpl) Sql() (query string, args []interface{}, err error) {
if l == nil {
2019-05-12 18:15:23 +02:00
return "", nil, errors.New("nil Statement.")
2019-05-07 13:44:30 +02:00
}
if len(l.tables) == 0 {
return "", nil, errors.New("There is no table selected to be locked. ")
}
out := &queryData{}
2019-05-12 18:15:23 +02:00
out.nextLine()
out.writeString("LOCK TABLE")
2019-05-07 13:44:30 +02:00
for i, table := range l.tables {
if i > 0 {
out.writeString(", ")
2019-05-07 13:44:30 +02:00
}
err := table.serialize(lock_statement, out)
2019-05-07 13:44:30 +02:00
if err != nil {
return "", nil, err
}
}
if l.lockMode != "" {
2019-05-12 18:15:23 +02:00
out.writeString("IN")
out.writeString(string(l.lockMode))
2019-05-12 18:15:23 +02:00
out.writeString("MODE")
2019-05-07 13:44:30 +02:00
}
if l.nowait {
2019-05-12 18:15:23 +02:00
out.writeString("NOWAIT")
2019-05-07 13:44:30 +02:00
}
2019-05-12 18:15:23 +02:00
query, args = out.finalize()
return
2019-05-07 13:44:30 +02:00
}
func (l *lockStatementImpl) Query(db types.Db, destination interface{}) error {
return Query(l, db, destination)
}
func (l *lockStatementImpl) Execute(db types.Db) (sql.Result, error) {
return Execute(l, db)
}