db.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Author: simon (ynwdlxm@163.com)
  2. // Date: 2025/9/15 18:04
  3. // Desc:
  4. package database
  5. import (
  6. "strings"
  7. "github.com/runningwater/go-redis/datastruct/dict"
  8. "github.com/runningwater/go-redis/interface/database"
  9. "github.com/runningwater/go-redis/interface/resp"
  10. "github.com/runningwater/go-redis/resp/reply"
  11. )
  12. type DB struct {
  13. index int
  14. data dict.Dict
  15. }
  16. type ExecFunc func(db *DB, args [][]byte) resp.Reply
  17. type CmdLine = [][]byte
  18. func NewDB() *DB {
  19. return &DB{
  20. index: 0,
  21. data: dict.NewSyncDict(),
  22. }
  23. }
  24. func (d *DB) Exec(c resp.Connection, cmdLine CmdLine) resp.Reply {
  25. // ping set setnx get
  26. cmdName := strings.ToLower(string(cmdLine[0]))
  27. // 查表
  28. cmd, ok := cmdTable[cmdName]
  29. if !ok {
  30. return reply.NewUnknownErrReply(cmdName)
  31. }
  32. // 参数校验
  33. if !validateArity(cmd.arity, cmdLine[1:]) {
  34. return reply.NewArgNumErrReply(cmdName)
  35. }
  36. if cmd.executor == nil {
  37. return reply.NewErrReply("command not implement")
  38. }
  39. return cmd.executor(d, cmdLine[1:])
  40. }
  41. func validateArity(arity int, args [][]byte) bool {
  42. if arity >= 0 {
  43. return arity == len(args)
  44. }
  45. // 变长的 arity 设置为 负的最小个数
  46. return len(args) >= -arity
  47. }
  48. func (d *DB) GetEntity(key string) (*database.DataEntity, bool) {
  49. raw, ok := d.data.Get(key)
  50. if !ok {
  51. return nil, false
  52. }
  53. entity, _ := raw.(*database.DataEntity)
  54. return entity, true
  55. }
  56. func (d *DB) PutEntity(key string, entity *database.DataEntity) int {
  57. return d.data.Put(key, entity)
  58. }
  59. func (d *DB) Remove(key string) {
  60. d.data.Remove(key)
  61. }
  62. func (d *DB) Removes(keys ...string) (deleted int) {
  63. deleted = 0
  64. for _, key := range keys {
  65. if _, exists := d.data.Get(key); exists {
  66. d.Remove(key)
  67. deleted++
  68. }
  69. }
  70. return
  71. }
  72. func (d *DB) Flush() {
  73. d.data.Clear()
  74. }