structure

package
v1.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2023 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SKIPLIST_MAX_LEVEL is better to be log(n) for the best performance.
	SKIPLIST_MAX_LEVEL = 10   //
	SKIPLIST_PROB      = 0.25 // SkipList Probability
)

Variables

View Source
var (
	// ErrListEmpty is returned if the list is empty.
	ErrListEmpty = errors.New("Wrong operation: list is empty")
	// ErrIndexOutOfRange is returned if the index out of range.
	ErrIndexOutOfRange = errors.New("Wrong operation: index out of range")
)
View Source
var (
	// ErrInvalidXArgs is returned when the arguments are invalid
	ErrInvalidXArgs = errors.New("id or fields cannot be empty")
	// ErrExistID is returned when the message ID already exists
	ErrExistID = errors.New("message ID already exists")
	// ErrInvalidCount is returned when the count is invalid
	ErrInvalidCount = errors.New("invalid count")
	// ErrInvalidStream is returned when the stream is invalid
	ErrAmountOfData = errors.New("The number of queries exceeds the amount of data in the stream")
)
View Source
var (
	// ErrInvalidValue is returned if the value is invalid.
	ErrInvalidValue = errors.New("Wrong value: invalid value")
	// ErrInvalidType is returned if the type is invalid.
	ErrInvalidType = errors.New("Wrong value: invalid type")
	// ErrKeyExpired is returned if the key is expired.
	ErrKeyExpired = errors.New("Wrong value: key expired")
)
View Source
var (
	// ErrListEmpty is returned if the list is empty.
	ErrInvalidArgs = errors.New("Error Args: The args are wrong")
)

Functions

This section is empty.

Types

type BitMapStructure added in v1.0.8

type BitMapStructure struct {
	// contains filtered or unexported fields
}

func NewBitMapStructure added in v1.0.8

func NewBitMapStructure(options config.Options) (*BitMapStructure, error)

NewBitMapStructure returns a new BitMapStructure It will return a nil BitMapStructure if the database cannot be opened or the database cannot be created The database will be created if it does not exist

func (*BitMapStructure) BitCount added in v1.0.8

func (b *BitMapStructure) BitCount(key string, start uint, end uint) (int, error)

BitCount Count the number of bits set to 1 in the specified range of the bitmap If the key does not exist, it returns an error

func (*BitMapStructure) BitDel added in v1.0.8

func (b *BitMapStructure) BitDel(key string, offset uint) error

BitDel delete the bit at the specified offset in the bitmap If the key does not exist, it returns an error There is room for optimization

func (*BitMapStructure) BitDels added in v1.0.8

func (b *BitMapStructure) BitDels(key string, offsets ...uint) error

BitDels delete a group of bits at the specified offsets in the bitmap If the key does not exist, it returns an error There is room for optimization

func (*BitMapStructure) BitOp added in v1.0.8

func (b *BitMapStructure) BitOp(operation []byte, destkey string, keys ...string) error

BitOp count the number of bits set to 1 in the specified range of the bitmap If the key does not exist, it returns an error

func (*BitMapStructure) GetBit added in v1.0.8

func (b *BitMapStructure) GetBit(key string, offset uint) (bool, error)

GetBit Get the value of the bit at the specified offset in the bitmap If the key does not exist, it returns an error

func (*BitMapStructure) GetBits added in v1.0.8

func (b *BitMapStructure) GetBits(key string, offsets ...uint) ([]bool, error)

GetBits Get the values of a group of bits at the specified offsets in the bitmap If the key does not exist, it returns an error

func (*BitMapStructure) SetBit added in v1.0.8

func (b *BitMapStructure) SetBit(key string, offset uint, value bool) error

SetBit Set the bit at the specified offset in the bitmap to the specified value If the key does not exist, it will be created If the bitmap length is not sufficient, it will be extended

func (*BitMapStructure) SetBits added in v1.0.8

func (b *BitMapStructure) SetBits(key string, args ...interface{}) error

SetBits Set the bit at the specified offset in the bitmap to the specified value If the key does not exist, it will be created If the bitmap length is not sufficient, it will be extended

type BitOperation added in v1.0.7

type BitOperation string

BitOperation is a type used to define the operations that can be performed on bits

const (
	// BitAndOperation performs the AND operation.
	BitAndOperation BitOperation = "AND"
	// BitOrOperation performs the OR operation.
	BitOrOperation BitOperation = "OR"
	// BitXorOperation performs the XOR operation.
	BitXorOperation BitOperation = "XOR"
	// BitNotOperation performs the NOT operation.
	BitNotOperation BitOperation = "NOT"
)

Constants representing the different bit operations

type BitSet added in v1.0.7

type BitSet struct {
	// contains filtered or unexported fields
}

BitSet is a structure that holds a reference to a BitSet

func (*BitSet) At added in v1.0.7

func (b *BitSet) At(pos uint) bool

At function checks if the bit at the specified position is set

func (*BitSet) Next added in v1.0.7

func (b *BitSet) Next(pos uint) (uint, bool)

Next function finds the next set bit in the bitset

type BitmapStructure added in v1.0.7

type BitmapStructure struct {
	// contains filtered or unexported fields
}

BitmapStructure is a structure that holds a reference to the database engine

func NewBitmap added in v1.0.7

func NewBitmap(options config.Options) (*BitmapStructure, error)

NewBitmap function initializes a new BitmapStructure with the provided options

func (*BitmapStructure) BitCount added in v1.0.7

func (b *BitmapStructure) BitCount(k string, start, end uint) (uint, error)

BitCount function counts the number of set bits in the specified range in the bitmap for the provided key

func (*BitmapStructure) BitOp added in v1.0.7

func (b *BitmapStructure) BitOp(op BitOperation, destKey string, keys ...string) error

BitOp function performs the specified bit operation on the provided keys and stores the result in the destination key

func (*BitmapStructure) DelBit added in v1.0.7

func (b *BitmapStructure) DelBit(k string, off uint) error

DelBit function deletes a bit at the specified offset in the bitmap for the provided key

func (*BitmapStructure) DelBits added in v1.0.7

func (b *BitmapStructure) DelBits(k string, off ...uint) error

DelBits function deletes multiple bits at the specified offsets in the bitmap for the provided key

func (*BitmapStructure) GetBit added in v1.0.7

func (b *BitmapStructure) GetBit(k string, off uint) (bool, error)

GetBit function retrieves a bit at the specified offset in the bitmap for the provided key

func (*BitmapStructure) GetBits added in v1.0.7

func (b *BitmapStructure) GetBits(k string) (*BitSet, error)

GetBits function retrieves the bits for the provided key

func (*BitmapStructure) SetBit added in v1.0.7

func (b *BitmapStructure) SetBit(k string, off uint) error

SetBit function sets a bit at the specified offset in the bitmap for the provided key

func (*BitmapStructure) SetBits added in v1.0.7

func (b *BitmapStructure) SetBits(k string, off ...uint) error

SetBits function sets multiple bits at the specified offsets in the bitmap for the provided key

type DataStructure

type DataStructure = byte
const (
	// String is a string data structure
	String DataStructure = iota + 1
	// Hash is a hash data structure
	Hash
	// List is a list data structure
	List
	// Set is a set data structure
	Set
	// ZSet is a zset data structure
	ZSet
	// bitmap is a bitmap data structure
	Bitmap
	// Stream is a stream data structure
	Stream
	// Expire is a expire data structure
	Expire
)

type FZSet added in v1.0.9

type FZSet struct {
	// contains filtered or unexported fields
}

FZSet represents a specific data structure in the database, which is key to handling sorted sets (ZSets). This struct facilitates interactions with data stored in the sorted set, allowing for both complex and simple operations.

It contains three struct fields:

  • 'dict': A Go map with string keys and pointers to ZSetValue values. This map aims to provide quick access to individual values in the sorted set based on the provided key.

  • 'size': An integer value representing the current size (number of elements) in the FZSet struct. This information is efficiently kept track of whenever elements are added or removed from the set, so no separate computation is needed to retrieve this information.

  • 'skipList': A pointer towards a SkipList struct. SkipLists perform well under numerous operations, such as insertion, deletion, and searching. They are a crucial component in maintaining the sorted set in a practical manner. In this context, the SkipList is used to keep an ordered track of the elements in the FZSet struct.

func (*FZSet) Bytes added in v1.0.9

func (fzs *FZSet) Bytes() ([]byte, error)

Bytes encodes the FZSet instance into bytes using MessagePack binary serialization format. The encoded bytes can be used for storage or transmission. If the encoding operation fails, an error is returned.

func (*FZSet) FromBytes added in v1.0.9

func (fzs *FZSet) FromBytes(b []byte) error

FromBytes decodes the input byte slice into the FZSet object using MessagePack. Returns an error if decoding fails, otherwise nil.

func (*FZSet) InsertNode added in v1.0.9

func (fzs *FZSet) InsertNode(score int, member string, value interface{}) error

InsertNode is a method on the FZSet structure. It inserts a new node or updates an existing node in the skip list and the dictionary. It takes three parameters: score (an integer), key (a string), and value (of any interface type).

If key already exists in the dictionary and the score equals the existing score, it updates the value and score in the skip list and the dictionary. If the score is different, it only updates the value in the dictionary because the ranking doesn't change and there is no need for an update in the skip list.

If the key doesn't exist in the dictionary, it adds the new key, value and score to the dictionary, increments the size of the dictionary by 1, and also adds the node to the skip list.

func (*FZSet) MarshalBinary added in v1.0.9

func (fzs *FZSet) MarshalBinary() (_ []byte, err error)

MarshalBinary serializes the FZSet instance into a byte slice. It uses MessagePack format for serialization Returns the serialized byte slice and an error if the encoding fails.

func (*FZSet) RemoveNode added in v1.0.9

func (fzs *FZSet) RemoveNode(member string) error

RemoveNode is a method for FZSet structure. This method aims to delete a node from both the dictionary (dict) and the skip list (skipList).

The method receives one parameter:

  • member: a string that represents the key of the node to be removed from the FZSet structure.

The method follows these steps:

  1. Check if a node with key 'member' exists in the dictionary. If not, or if the dictionary itself is nil, it returns an error (_const.ErrKeyNotFound) indicating that the node cannot be found.
  2. If the node exists, it proceeds to remove the node from both the skip list and dictionary.
  3. After the successful removal of the node, it returns nil indicating the success of the operation.

The RemoveNode's primary purpose is to provide a way to securely and efficiently remove a node from the FZSet structure.

func (*FZSet) UnmarshalBinary added in v1.0.9

func (fzs *FZSet) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary de-serializes the given byte slice into FZSet instance it uses MessagePack format for de-serialization Returns an error if the decoding of size or insertion of node fails.

Parameters: data : a slice of bytes to be decoded

Returns: An error that will be nil if the function succeeds.

type HashField added in v1.0.6

type HashField struct {
	// contains filtered or unexported fields
}

type HashMetadata added in v1.0.6

type HashMetadata struct {
	// contains filtered or unexported fields
}

type HashStructure added in v1.0.6

type HashStructure struct {
	// contains filtered or unexported fields
}

func NewHashStructure added in v1.0.6

func NewHashStructure(options config.Options) (*HashStructure, error)

NewHashStructure Returns a new NewHashStructure

func (*HashStructure) Clean added in v1.0.9

func (hs *HashStructure) Clean()

func (*HashStructure) HDecrBy added in v1.0.6

func (hs *HashStructure) HDecrBy(k string, f interface{}, decrement int64) (int64, error)

HDecrBy decrements the integer value of a hash field by the given number.

func (*HashStructure) HDel added in v1.0.6

func (hs *HashStructure) HDel(k string, f interface{}) (bool, error)

HDel deletes one field from a hash.

func (*HashStructure) HExists added in v1.0.6

func (hs *HashStructure) HExists(k string, f interface{}) (bool, error)

HExists determines whether a hash field exists or not.

func (*HashStructure) HGet added in v1.0.6

func (hs *HashStructure) HGet(k string, f interface{}) (interface{}, error)

HGet gets the string value of a hash field.

func (*HashStructure) HIncrBy added in v1.0.6

func (hs *HashStructure) HIncrBy(k string, f interface{}, increment int64) (int64, error)

HIncrBy increments the integer value of a hash field by the given number.

func (*HashStructure) HIncrByFloat added in v1.0.6

func (hs *HashStructure) HIncrByFloat(k string, f interface{}, increment float64) (float64, error)

HIncrByFloat increments the float value of a hash field by the given number.

func (*HashStructure) HLen added in v1.0.6

func (hs *HashStructure) HLen(k string) (int, error)

HLen gets the number of fields contained in a hash.

func (*HashStructure) HMGet added in v1.0.7

func (hs *HashStructure) HMGet(k string, f ...interface{}) ([]interface{}, error)

HMGet gets the string value of a hash field.

func (*HashStructure) HMove added in v1.0.6

func (hs *HashStructure) HMove(source, destination string, f interface{}) (bool, error)

HMove moves field from the hash stored at source to the hash stored at destination.

func (*HashStructure) HSet added in v1.0.6

func (hs *HashStructure) HSet(k string, f, v interface{}) (bool, error)

HSet sets the string value of a hash field.

func (*HashStructure) HSetNX added in v1.0.6

func (hs *HashStructure) HSetNX(k string, f, v interface{}) (bool, error)

HSetNX sets field in the hash stored at key to value, only if field does not yet exist.

func (*HashStructure) HStrLen added in v1.0.6

func (hs *HashStructure) HStrLen(k string, f interface{}) (int, error)

HStrLen returns the string length of the value associated with field in the hash stored at key.

func (*HashStructure) HTypes added in v1.0.6

func (hs *HashStructure) HTypes(k string, f interface{}) (string, error)

HTypes returns if field is an existing hash key in the hash stored at key.

func (*HashStructure) HUpdate added in v1.0.6

func (hs *HashStructure) HUpdate(k string, f, v interface{}) (bool, error)

HUpdate updates the string value of a hash field.

func (*HashStructure) Stop added in v1.0.9

func (hs *HashStructure) Stop() error

type ListStructure

type ListStructure struct {
	// contains filtered or unexported fields
}

Due to the complexity of each operation is at least O(n) So we can directly use slice to implement the list at the bottom level If the implementation of the db is improved later, we need to switch to a linked list

func NewListStructure

func NewListStructure(options config.Options) (*ListStructure, error)

NewListStructure returns a new ListStructure It will return a nil ListStructure if the database cannot be opened or the database cannot be created The database will be created if it does not exist

func (*ListStructure) LIndex

func (l *ListStructure) LIndex(key string, index int) (interface{}, error)

LIndex returns the value of an element in a list associated with a key based on the index. If the key does not exist, an error is returned. If the list is empty, an error is returned. Negative indices can be used, where -1 represents the last element of the list, -2 represents the second last element, and so on.

func (*ListStructure) LLen

func (l *ListStructure) LLen(key string) (int, error)

LLen returns the size of a list associated with a key. If the key does not exist, an error is returned.

func (*ListStructure) LPop

func (l *ListStructure) LPop(key string) (interface{}, error)

LPop returns and removes the leftmost value of a list associated with a key. If the key does not exist, an error is returned. If the list is empty, an error is returned.

func (*ListStructure) LPush

func (l *ListStructure) LPush(key string, value interface{}) error

LPush adds a value to the left of the list corresponding to the key If the key does not exist, it will create the key

func (*ListStructure) LPushs

func (l *ListStructure) LPushs(key string, values ...interface{}) error

LPushs adds one or more values to the left of the list corresponding to the key If the key does not exist, it will create the key

func (*ListStructure) LRange

func (l *ListStructure) LRange(key string, start int, stop int) ([]interface{}, error)

LRange returns a range of elements from a list associated with a key. The range is inclusive, including both the start and stop indices. If the key does not exist, an error is returned. If the list is empty, an error is returned. Negative indices can be used, where -1 represents the last element of the list, -2 represents the second last element, and so on.

func (*ListStructure) LRem

func (l *ListStructure) LRem(key string, count int, value interface{}) error

LRem removes elements from a list associated with a key based on the count and value parameters. The count can have the following values: count > 0: Remove count occurrences of the value from the beginning of the list. count < 0: Remove count occurrences of the value from the end of the list. count = 0: Remove all occurrences of the value from the list. If the key does not exist, an error is returned.

func (*ListStructure) LSet

func (l *ListStructure) LSet(key string, index int, value interface{}) error

LSet sets the value of an element in a list associated with a key based on the index. If the index is out of range, an error is returned. If the list is empty, an error is returned.

func (*ListStructure) LTrim

func (l *ListStructure) LTrim(key string, start int, stop int) error

LTrim retains a range of elements in a list associated with a key. The range is inclusive, including both the start and stop indices. If the key does not exist, an error is returned. If the list is empty, an error is returned. Negative indices can be used, where -1 represents the last element of the list, -2 represents the second last element, and so on.

func (*ListStructure) RPOPLPUSH

func (l *ListStructure) RPOPLPUSH(source string, destination string) error

RPOPLPUSH removes the last element from one list and pushes it to another list. If the source list is empty, an error is returned. If the destination list is empty, it is created. Atomicity is not guaranteed.

func (*ListStructure) RPop

func (l *ListStructure) RPop(key string) (interface{}, error)

RPop returns and removes the rightmost value of a list associated with a key. If the key does not exist, an error is returned. If the list is empty, an error is returned.

func (*ListStructure) RPush

func (l *ListStructure) RPush(key string, value interface{}) error

RPush adds a value to the right of the list corresponding to the key If the key does not exist, it will create the key

func (*ListStructure) RPushs

func (l *ListStructure) RPushs(key string, values ...interface{}) error

RPushs appends one or more values to the right side of a list associated with a key. If the key does not exist, it will be created.

type SkipList added in v1.0.9

type SkipList struct {
	// contains filtered or unexported fields
}

SkipList represents a skip list data structure, an ordered list with a hierarchical structure that allows for fast search and insertion of elements.

type SkipListLevel added in v1.0.9

type SkipListLevel struct {
	// contains filtered or unexported fields
}

SkipListLevel is a structure encapsulating a single level in a skip list data structure. It contains two struct fields: - 'next': A pointer to the next SkipListNode in the current level. - 'span': An integer representing the span size of this SkipListLevel. The span is the number of nodes between the current node and the node to which the next pointer is pointing in the skip list.

type SkipListNode added in v1.0.9

type SkipListNode struct {
	// contains filtered or unexported fields
}

SkipListNode represents a single node in a SkipList structure. It is built with three elements:

  • 'prev': This is a pointer to the previous node in the skip list. Together with the 'next' pointers in the SkipListNodeLevel, it forms a network of nodes, where traversal of the skip list is possible both forwards and backwards.
  • 'level': This is an array (slice) of pointers towards SkipListLevel structures. Each element corresponds to a level of the skip list, embedding the 'next' node at that same level, and the span between the current node and that 'next' node.
  • 'value': This is a pointer towards a single ZSetValue structure. It holds the actual payload of the node (namely the 'score', 'key', and 'value' properties used in the context of Redis Sorted Sets), as well as provides the basis for ordering of nodes in the skip list.

type StreamGroup added in v1.0.9

type StreamGroup struct {
	// Name is the name of the group.
	Name string `json:"name"`
	// LastGeneratedID is the ID of the last generated message in the group.
	LastGeneratedID string `json:"last_generated_id"`
	// LastDeliveredTime is the timestamp of the last delivered message in the group.
	LastDeliveredTime time.Time `json:"last_delivered_time"`
	// PendingMessages is the list of pending messages in the group.
	PendingMessages map[string]*StreamMessage `json:"pending_messages"`
}

StreamGroup represents a consumer group in a stream. It holds information about the group name, the last generated message ID, the last delivered message time, and the list of pending messages.

type StreamMessage added in v1.0.9

type StreamMessage struct {
	// Id is the unique ID of the message.
	Id string `json:"id"`
	// Fields is the payload of the message.
	Fields map[string]interface{} `json:"fields"`
}

StreamMessage represents a message in a stream. It holds information about the unique ID of the message and the message payload.

type StreamStructure added in v1.0.9

type StreamStructure struct {
	// contains filtered or unexported fields
}

func NewStreamStructure added in v1.0.9

func NewStreamStructure(options config.Options) (*StreamStructure, error)

StreamStructure represents a stream structure

func (*StreamStructure) XAdd added in v1.0.9

func (s *StreamStructure) XAdd(name, id string, fields map[string]interface{}) (bool, error)

XAdd adds a new message to a stream. If the stream does not exist, it will be created. If the message ID already exists, it will return false.

Parameters:

name: The name of the stream.
id: The ID of the message.
fields: The fields (attributes) of the message.
        It should be a map[string]interface{} where the keys represent the field names
        and the values represent the field values.

Returns:

bool: Indicates whether the message was successfully added to the stream.
error: An error if any occurred during the operation, or nil on success.

Note: - The ID and fields parameters should be valid and non-empty. - The name parameter represents the name of the stream where the message will be added. - The fields parameter contains the attributes of the message. - If the stream with the specified name does not exist, a new stream will be created. - If the message ID already exists in the stream, the function will return false and ErrExistID. - Otherwise, the message will be added to the stream, and the stream will be stored in the database.

func (*StreamStructure) XDel added in v1.0.9

func (s *StreamStructure) XDel(name string, ids string) (bool, int, error)

XDel deletes a message from a stream. Returns true if the message was deleted. Returns false if the message was not deleted. Returns the number of messages in the stream after deletion.

Parameters:

name: The name of the stream.
ids: The ID of the message to delete.

Returns:

bool: Indicates whether the message was successfully deleted.
int: The number of messages in the stream after deletion.
error: An error if any occurred during the operation, or nil on success.

Note: - The name parameter represents the name of the stream to delete from. - The ids parameter specifies the ID of the message to delete. - It retrieves the stream from the database using the specified name. - If the stream does not exist, it will return ErrKeyNotFound. - It decodes the stream data and stores it in the internal s.streams field. - It iterates through the messages in the stream and removes the message with the specified ID. - It updates the s.streams.Messages slice to remove the deleted message. - It encodes the updated stream data. - It stores the updated stream in the database. - It returns true if the message was deleted successfully. - It returns false if the message was not found in the stream. - It returns the number of messages in the stream after deletion.

func (*StreamStructure) XGroup added in v1.0.9

func (s *StreamStructure) XGroup(name, group, id string) (bool, error)

XGroup creates a new consumer group. It takes the name of the stream, the name of the group, and the ID of the message as arguments, and returns a boolean indicating whether the group was created successfully or not, and an error if any.

Parameters:

name: The name of the stream.
group: The name of the consumer group.
id: The ID of the message.

Returns:

bool: A boolean indicating whether the group was created successfully or not.
error: An error if any occurred during the operation, or nil on success.

Note: - The name parameter represents the name of the stream to create the consumer group on. - The group parameter specifies the name of the consumer group to create. - The id parameter specifies the ID of the message. - It retrieves the stream from the database using the specified name. - If the stream does not exist, it will return ErrKeyNotFound. - It decodes the stream data and stores it in the internal s.streams field. - It creates a new StreamGroup with the specified name, last generated ID, and last delivered time. - It sets the StreamGroup in s.streams.Groups map with the group name as the key. - It encodes the streams and updates the stream in the database. - It returns true if the group was created successfully, and false otherwise. - If any error occurs during the operation, it will be returned along with false.

func (*StreamStructure) XLen added in v1.0.9

func (s *StreamStructure) XLen(name string) (int, error)

XLen returns the number of elements in a given stream. It takes the name of the stream as an argument and returns the number of elements in the stream.

Parameters:

name: The name of the stream.

Returns:

int: The number of elements (messages) in the stream.
error: An error if any occurred during the operation, or nil on success.

Note: - The name parameter represents the name of the stream to get the length of. - It retrieves the stream from the database using the specified name. - If the stream does not exist, it will return ErrKeyNotFound. - It decodes the stream data and stores it in the internal s.streams field. - It retrieves the messages from s.streams.Messages. - It returns the number of messages in the stream.

func (*StreamStructure) XRange added in v1.0.9

func (s *StreamStructure) XRange(name string, start, stop int) ([]StreamMessage, error)

XRange returns the messages in the stream. It takes the name of the stream, the start index, and the stop index as arguments, and returns a slice of StreamMessage containing the messages within the specified range.

Parameters:

name: The name of the stream.
start: The start index of the range (inclusive).
stop: The stop index of the range (exclusive).

Returns:

[]StreamMessage: A slice of StreamMessage containing the messages within the specified range.
error: An error if any occurred during the operation, or nil on success.

Note:

  • The name parameter represents the name of the stream to get the messages from.
  • The start parameter specifies the start index of the range (inclusive).
  • The stop parameter specifies the stop index of the range (exclusive).
  • It retrieves the stream from the database using the specified name.
  • If the stream does not exist, it will return ErrKeyNotFound.
  • It decodes the stream data and stores it in the internal s.streams field.
  • It retrieves the messages from s.streams.Messages.
  • If the number of messages in the stream is greater than or equal to stop, it returns a slice of StreamMessage within the specified range.
  • If the number of messages in the stream is less than stop, it returns ErrAmountOfData, indicating that there is not enough data in the stream.

func (*StreamStructure) XRead added in v1.0.9

func (s *StreamStructure) XRead(name string, count int) ([]StreamMessage, error)

XRead reads messages from a stream. Returns a slice of StreamMessage.

Parameters:

name: The name of the stream.
count: The maximum number of messages to read.

Returns:

[]StreamMessage: A slice of StreamMessage containing the read messages.
error: An error if any occurred during the operation, or nil on success.

Note:

  • The name parameter represents the name of the stream to read from.
  • The count parameter specifies the maximum number of messages to read.
  • If count is less than or equal to 0, it will return ErrInvalidCount.
  • It retrieves the stream from the database using the specified name.
  • If the stream does not exist, it will return ErrKeyNotFound.
  • It decodes the stream data and stores it in the internal s.streams field.
  • It retrieves the messages from s.streams.Messages.
  • If the number of messages in the stream is greater than or equal to count, it returns a slice of StreamMessage with the first count messages.
  • If the number of messages in the stream is less than count, it returns ErrAmountOfData, indicating that there is not enough data in the stream.

func (*StreamStructure) XRevRange added in v1.0.9

func (s *StreamStructure) XRevRange(name string, start, stop int) ([]StreamMessage, error)

XRevRange returns the messages in the stream in reverse order. It takes the name of the stream, the start index, and the stop index as arguments, and returns a slice of StreamMessage containing the messages within the specified range in reverse order.

Parameters:

name: The name of the stream.
start: The start index of the range (inclusive).
stop: The stop index of the range (exclusive).

Returns:

 []StreamMessage: A slice of StreamMessage containing the messages
				  within the specified range in reverse order.
 error: An error if any occurred during the operation, or nil on success.

Note:

  • The name parameter represents the name of the stream to get the messages from.
  • The start parameter specifies the start index of the range (inclusive).
  • The stop parameter specifies the stop index of the range (exclusive).
  • It retrieves the stream from the database using the specified name.
  • If the stream does not exist, it will return ErrKeyNotFound.
  • It decodes the stream data and stores it in the internal s.streams field.
  • It retrieves the messages from s.streams.Messages.
  • If the number of messages in the stream is greater than or equal to stop, it returns a slice of StreamMessage within the specified range in reverse order.
  • If the number of messages in the stream is less than stop, it returns ErrAmountOfData, indicating that there is not enough data in the stream.
  • The returned slice of StreamMessage is reversed compared to the original order.

func (*StreamStructure) XTrim added in v1.0.9

func (s *StreamStructure) XTrim(name string, maxLen int) (int, error)

XTrim trims the stream to a certain size. It takes the name of the stream and the maximum length as arguments, and returns the number of messages in the stream after the trim operation.

Parameters:

name: The name of the stream.
maxLen: The maximum length to trim the stream to.

Returns:

int: The number of messages in the stream after the trim operation.
error: An error if any occurred during the operation, or nil on success.

Note:

  • The name parameter represents the name of the stream to trim.
  • The maxLen parameter specifies the maximum length to trim the stream to.
  • It retrieves the stream from the database using the specified name.
  • If the stream does not exist, it will return ErrKeyNotFound.
  • It decodes the stream data and stores it in the internal s.streams field.
  • It retrieves the messages from s.streams.Messages.
  • If the number of messages in the stream is greater than or equal to maxLen, it trims the stream to the specified length.
  • If the number of messages in the stream is less than maxLen, it returns ErrAmountOfData, indicating that there is not enough data in the stream.
  • It sets the trimmed messages back to s.streams.Messages.
  • It encodes the streams and updates the stream in the database.
  • It returns the number of messages in the stream after the trim operation.

type Streams added in v1.0.9

type Streams struct {
	// Name is the name of the stream.
	Name string `json:"name"`
	// Messages is the list of messages in the stream.
	Messages []*StreamMessage `json:"messages"`
	// Groups is the list of consumer groups in the stream.
	Groups map[string]*StreamGroup `json:"groups"`
	// LastMessage is the timestamp of the last message in the stream.
	LastMessage time.Time
}

Streams represents a stream with messages and consumer groups. It holds information about the stream name, messages, consumer groups, and the last message in the stream.

type StringStructure

type StringStructure struct {
	// contains filtered or unexported fields
}

StringStructure is a structure that stores string data

func NewStringStructure

func NewStringStructure(options config.Options) (*StringStructure, error)

NewStringStructure returns a new StringStructure It will return a nil StringStructure if the database cannot be opened or the database cannot be created The database will be created if it does not exist

func (*StringStructure) Append

func (s *StringStructure) Append(key string, v interface{}, ttl time.Duration) error

Append appends a value to the value of a key

func (*StringStructure) Clean added in v1.0.7

func (s *StringStructure) Clean()

func (*StringStructure) Decr

func (s *StringStructure) Decr(key string, ttl time.Duration) error

Decr decrements the integer value of a key by 1

func (*StringStructure) DecrBy

func (s *StringStructure) DecrBy(key string, amount int, ttl time.Duration) error

DecrBy decrements the integer value of a key by the given amount

func (*StringStructure) Del

func (s *StringStructure) Del(k string) error

Del deletes the value of a key If the key does not exist, it will return nil If the key exists, it will be deleted If the key is expired, it will be deleted and return nil If the key is not expired, it will be updated and return nil

func (*StringStructure) Exists

func (s *StringStructure) Exists(key string) (bool, error)

Exists checks if a key exists

func (*StringStructure) Expire

func (s *StringStructure) Expire(key string, ttl time.Duration) error

Expire sets the expiration time of a key

func (*StringStructure) Get

func (s *StringStructure) Get(k string) (interface{}, error)

Get gets the value of a key If the key does not exist, it will return nil If the key exists, it will return the value If the key is expired, it will be deleted and return nil If the key is not expired, it will be updated and return the value

func (*StringStructure) GetSet

func (s *StringStructure) GetSet(key string, value interface{}, ttl time.Duration) (interface{}, error)

GetSet sets the value of a key and returns its old value

func (*StringStructure) Incr

func (s *StringStructure) Incr(key string, ttl time.Duration) error

Incr increments the integer value of a key by 1

func (*StringStructure) IncrBy

func (s *StringStructure) IncrBy(key string, amount int, ttl time.Duration) error

IncrBy increments the integer value of a key by the given amount

func (*StringStructure) IncrByFloat

func (s *StringStructure) IncrByFloat(key string, amount float64, ttl time.Duration) error

IncrByFloat increments the float value of a key by the given amount

func (*StringStructure) MGet added in v1.0.9

func (s *StringStructure) MGet(keys ...string) ([]interface{}, error)

func (*StringStructure) MSet added in v1.0.9

func (s *StringStructure) MSet(pairs ...interface{}) error

func (*StringStructure) MSetNX added in v1.0.9

func (s *StringStructure) MSetNX(pairs ...interface{}) (bool, error)

MSetNX sets multiple key-value pairs only if none of the specified keys exist

func (*StringStructure) Persist

func (s *StringStructure) Persist(key string) error

Persist removes the expiration time of a key

func (*StringStructure) Set

func (s *StringStructure) Set(k string, v interface{}, ttl time.Duration) error

Set sets the value of a key If the key does not exist, it will be created If the key exists, it will be overwritten If the key is expired, it will be deleted If the key is not expired, it will be updated func (s *StringStructure) Set(key, value []byte, ttl time.Duration) error {

func (*StringStructure) Stop added in v1.0.7

func (s *StringStructure) Stop() error

func (*StringStructure) StrLen

func (s *StringStructure) StrLen(k string) (int, error)

StrLen returns the length of the value of a key If the key does not exist, it will return 0 If the key exists, it will return the length of the value If the key is expired, it will be deleted and return 0 If the key is not expired, it will be updated and return the length of the value

func (*StringStructure) Type

func (s *StringStructure) Type(k string) (string, error)

Type returns the type of a key If the key does not exist, it will return "" If the key exists, it will return "string" If the key is expired, it will be deleted and return "" If the key is not expired, it will be updated and return "string"

type ZSetStructure added in v1.0.9

type ZSetStructure struct {
	// contains filtered or unexported fields
}

ZSetStructure is a structure for ZSet or SortedSet

func NewZSetStructure added in v1.0.9

func NewZSetStructure(options config.Options) (*ZSetStructure, error)

NewZSetStructure Returns a new ZSetStructure

func (*ZSetStructure) ZAdd added in v1.0.9

func (zs *ZSetStructure) ZAdd(key string, score int, member string, value string) error

ZAdd adds a value with its given score and member to a sorted set (ZSet), associated with the provided key. It is a method on the ZSetStructure type.

Parameters:

key:    a string that represents the key of the sorted set.
score:  an integer value that determines the order of the added element in the sorted set.
member: a string used for identifying the added value within the sorted set.
value:  the actual value to be stored within the sorted set.

If the key is an empty string, an error will be returned

func (*ZSetStructure) ZAdds added in v1.0.9

func (zs *ZSetStructure) ZAdds(key string, vals ...ZSetValue) error

ZAdds adds a value with its given score and member to a sorted set (ZSet), associated with the provided key. It is a method on the ZSetStructure type.

Parameters:

values:    ...ZSetValue multiple values of ZSetValue.

func (*ZSetStructure) ZCard added in v1.0.9

func (zs *ZSetStructure) ZCard(key string) (int, error)

The ZCard function returns the size of the dictionary of the sorted set stored at key in the database. It takes a string key as an argument.

func (*ZSetStructure) ZCount added in v1.0.9

func (zs *ZSetStructure) ZCount(key string, min int, max int) (count int, err error)

ZCount traverses through the elements of the ZSetStructure based on the given key. The count of elements between the range of min and max scores is determined.

The method takes a string as the key and two integers as min and max ranges. The range values are inclusive: [min, max]. If min is greater than max, an error is returned. The function ignores scores that fall out of the specified min and max range.

It returns the count of elements within the range, and an error if any occurs during the process.

For example, use as follows: count, err := zs.ZCount("exampleKey", 10, 50) This will count the number of elements that have the scores between 10 and 50 in the ZSetStructure associated with "exampleKey".

Returns:

  1. int: The total count of elements based on the score range.
  2. error: Errors that occurred during execution, if any.

func (*ZSetStructure) ZIncrBy added in v1.0.9

func (zs *ZSetStructure) ZIncrBy(key string, member string, incBy int) error

ZIncrBy increases the score of an existing member in a sorted set stored at specified key by the increment `incBy` provided. If member does not exist, ErrKeyNotFound error is returned. If the key does not exist, it treats it as an empty sorted set and returns an error.

The method accepts three parameters: `key`: a string type parameter that identifies the sorted set `member`: a string type parameter representing member in the sorted set `incBy`: an int type parameter provides the increment value for a member score

The method throws error under following circumstances - if provided key is empty (ErrKeyIsEmpty error), if provided key or member is not present in the database (ErrKeyNotFound error), if it's unable to fetch or create ZSet from DB, if there's an issue with node insertion, if unable to set ZSet to DB post increment operation

func (*ZSetStructure) ZRange added in v1.0.9

func (zs *ZSetStructure) ZRange(key string, start int, end int) ([]ZSetValue, error)

ZRange retrieves a specific range of elements from a sorted set (ZSet) denoted by a specific key. It returns a slice of ZSetValue containing the elements within the specified range (inclusive), and a nil error when successful.

The order of the returned elements is based on their rank in the set, not their score.

Parameters:

key: A string identifier representing the ZSet. The key shouldn't be an empty string.
start: A zero-based integer representing the first index of the range.
end: A zero-based integer representing the last index of the range.

Returns:

 []ZSetValue:
		Slice of ZSetValue containing elements within the specified range.
 error:
		An error if it occurs during execution, such as:
     		1. The provided key string is empty.
     		2. An error occurs while fetching the ZSet from the database, i.e., the ZSet represented by the given key doesn't exist.
     		In the case of an error, an empty slice and the actual error encountered will be returned.

Note: On successful execution, ZRange returns the elements starting from 'start' index up to 'end' index inclusive. If the set doesn't exist or an error occurs during execution, ZRange returns an empty slice and the error.

Example: Assume we have ZSet with the following elements: ["element1", "element2", "element3", "element4"] ZRange("someKey", 0, 2) will return ["element1", "element2", "element3"] and nil error.

This method is part of the ZSetStructure type.

func (*ZSetStructure) ZRank added in v1.0.9

func (zs *ZSetStructure) ZRank(key string, member string) (int, error)

ZRank is a method belonging to the ZSetStructure type. This method retrieves the rank of an element within a sorted set identified by a key. The rank is an integer corresponding to the element's 0-based position in the sorted set when it is arranged in ascending order.

Parameters: key (string): The key that identifies the sorted set. member (string): The element for which you want to find the rank.

Returns: int: An integer indicating the rank of the member in the set.

Rank zero means the member is not found in the set.

error: If an error occurs, an error object will be returned.

Possible errors include:
- key is empty
- failure to get or create the ZSet from the DB
- the provided key does not exist in the DB

Example: rank, err := zs.ZRank("myKey", "memberName")

if err != nil {
   log.Fatal(err)
}

fmt.Printf("The rank of '%s' in the set '%s' is %d\n", "memberName", "myKey", rank)

func (*ZSetStructure) ZRem added in v1.0.9

func (zs *ZSetStructure) ZRem(key string, member string) error

ZRem is a method belonging to ZSetStructure that removes a member from a ZSet.

Parameters:

  • key (string): The key of the ZSet.
  • member (string): The member to be removed.

Returns:

  • error: An error if the operation fails.

The ZRem method checks for a non-empty key, retrieves the corresponding ZSet from the database, removes the specified member, and then updates the ZSet in the database. If any point of this operation fails, the function will return the corresponding error.

func (*ZSetStructure) ZRems added in v1.0.9

func (zs *ZSetStructure) ZRems(key string, member ...string) error

ZRems method removes one or more specified members from the sorted set that's stored under the provided key. Params:

  • key string: the identifier for storing the sorted set in the database.
  • member ...string: a variadic parameter where each argument is a member string to remove.

Returns: error

The function will return an error if it fails at any point, if not it will return nil indicating a successful operation.

func (*ZSetStructure) ZRevRange added in v1.0.9

func (zs *ZSetStructure) ZRevRange(key string, startRank int, endRank int) ([]ZSetValue, error)

ZRevRange retrieves a range of elements from a sorted set (ZSet) in descending order. Inputs:

  • key: Name of the ZSet
  • startRank: Initial rank of the desired range
  • endRank: Final rank of the desired range

Output:

  • An array of ZSetValue, representing elements from the range [startRank, endRank] in descending order
  • Error if an issue occurs, such as when the key is empty or ZSet retrieval fails error

func (*ZSetStructure) ZRevRank added in v1.0.9

func (zs *ZSetStructure) ZRevRank(key string, member string) (int, error)

ZRevRank calculates the reverse rank of a member in a ZSet (Sorted Set) associated with a given key. ZSet exploits the Sorted Set data structure of Redis with O(log(N)) time complexity for Fetching the rank.

Parameters:

key:    This is a string that serves as the key of a ZSet stored in the database.
member: This is a string that represents a member of a ZSet whose rank needs to be obtained.

Returns:

int:    The integer represents the reverse rank of the member in the ZSet. It returns 0 if the member is not found in the ZSet.
        On successful execution, it returns the difference of the ZSet size and the member's rank.
error:  The error which will be null if no errors occurred. If the key provided is empty, an ErrKeyIsEmpty error is returned.
        If there's a problem getting or creating the ZSet from the database, an error message is returned with the format
        "failed to get or create ZSet from DB with key '%v': %w", where '%v' is the key and '%w' shows the error detail.
        If the member is not found in the ZSet, it returns an ErrKeyNotFound error.

Note: The reverse rank is calculated as 'size - rank', and the ranks start from 1.

func (*ZSetStructure) ZScore added in v1.0.9

func (zs *ZSetStructure) ZScore(key string, member string) (int, error)

ZScore method retrieves the score associated with the member in a sorted set stored at the key

type ZSetValue added in v1.0.9

type ZSetValue struct {
	// contains filtered or unexported fields
}

ZSetValue is a struct used in the SkipList data structure. In the context of Redis Sorted Set (ZSet) implementation, it represents a single node value in the skip list. A ZSetValue has three members: - 'score' which is an integer representing the score of the node. Nodes in a skip list are ordered by this score in ascending order. - 'member' which is a string defining the key of the node. For nodes with equal scores, order is determined with lexicographical comparison of keys. - 'value' which is an interface{}, meaning it can hold any data type. This represents the actual value of the node in the skip list.

func (*ZSetValue) MarshalBinary added in v1.0.9

func (d *ZSetValue) MarshalBinary() (_ []byte, err error)

MarshalBinary uses MessagePack as the encoding format to serialize the ZSetValue object into a byte array.

func (*ZSetValue) UnmarshalBinary added in v1.0.9

func (p *ZSetValue) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary de-serializes the given byte slice into ZSetValue instance It uses the MessagePack format for de-serialization Returns an error if the decoding of Key, Score, or Value fails.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL