db.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. // DB 数据库
  13. type DB struct {
  14. index int
  15. data dict.Dict
  16. }
  17. type ExecFunc func(db *DB, args [][]byte) resp.Reply
  18. type CmdLine = [][]byte
  19. func NewDB() *DB {
  20. return &DB{
  21. index: 0,
  22. data: dict.NewSyncDict(),
  23. }
  24. }
  25. // Exec 执行一个redis命令
  26. // 参数:
  27. // - c: 客户端连接对象,表示发送命令的客户端连接
  28. // - cmdLine: 命令行参数,包含命令名称和所有参数的字节切片
  29. //
  30. // 返回值:
  31. // - resp.Reply: 命令执行结果的回复
  32. func (d *DB) Exec(c resp.Connection, cmdLine CmdLine) resp.Reply {
  33. // 检查命令行参数是否为空
  34. if len(cmdLine) == 0 {
  35. return reply.NewErrReply("empty command")
  36. }
  37. // ping set setnx get
  38. cmdName := strings.ToLower(string(cmdLine[0]))
  39. // 查找命令
  40. cmd, ok := cmdTable[cmdName]
  41. if !ok {
  42. return reply.NewUnknownErrReply(cmdName)
  43. }
  44. // 参数校验
  45. if !validateArity(cmd.arity, cmdLine[1:]) {
  46. return reply.NewArgNumErrReply(cmdName)
  47. }
  48. if cmd.executor == nil {
  49. return reply.NewErrReply("command not implement")
  50. }
  51. return cmd.executor(d, cmdLine[1:])
  52. }
  53. func validateArity(arity int, args [][]byte) bool {
  54. if arity >= 0 {
  55. return arity == len(args)
  56. }
  57. // 变长的 arity 设置为 负的最小个数
  58. return len(args) >= -arity
  59. }
  60. func (d *DB) GetEntity(key string) (*database.DataEntity, bool) {
  61. raw, ok := d.data.Get(key)
  62. if !ok {
  63. return nil, false
  64. }
  65. entity, _ := raw.(*database.DataEntity)
  66. return entity, true
  67. }
  68. func (d *DB) PutEntity(key string, entity *database.DataEntity) int {
  69. return d.data.Put(key, entity)
  70. }
  71. func (d *DB) Remove(key string) {
  72. d.data.Remove(key)
  73. }
  74. func (d *DB) Removes(keys ...string) (deleted int) {
  75. deleted = 0
  76. for _, key := range keys {
  77. if _, exists := d.data.Get(key); exists {
  78. d.Remove(key)
  79. deleted++
  80. }
  81. }
  82. return
  83. }
  84. func (d *DB) Flush() {
  85. d.data.Clear()
  86. }