-
-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #68 from whywaita/fix/67
Implement datastore lock
- Loading branch information
Showing
4 changed files
with
87 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package mysql | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/whywaita/myshoes/pkg/datastore" | ||
) | ||
|
||
const ( | ||
// LockKey is key of database lock | ||
LockKey = "myshoes" | ||
) | ||
|
||
// GetLock get lock | ||
func (m *MySQL) GetLock(ctx context.Context) error { | ||
var res int | ||
|
||
query := fmt.Sprintf(`SELECT GET_LOCK('%s', 10)`, LockKey) | ||
if err := m.Conn.GetContext(ctx, &res, query); err != nil { | ||
return fmt.Errorf("failed to GET_LOCK: %w", err) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// IsLocked return status of lock | ||
func (m *MySQL) IsLocked(ctx context.Context) (string, error) { | ||
var res int | ||
|
||
query := fmt.Sprintf(`SELECT IS_FREE_LOCK('%s')`, LockKey) | ||
if err := m.Conn.GetContext(ctx, &res, query); err != nil { | ||
return "", fmt.Errorf("failed to IS_FREE_LOCK: %w", err) | ||
} | ||
|
||
switch res { | ||
case 1: | ||
return datastore.IsNotLocked, nil | ||
case 0: | ||
return datastore.IsLocked, nil | ||
} | ||
|
||
return "", fmt.Errorf("IS_FREE_LOCK return NULL") | ||
} |