database

package
v1.2.183 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 19 Imported by: 6

Documentation

Overview

Package database

General interface for distributed cache and data structure store (e.g. Redis)

Index

Constants

View Source
const (
	NOT_IMPLEMENTED  = "not implemented"
	NOT_SUPPORTED    = "not supported"
	TABLE_NOT_EXISTS = "DbTable does not exist"
)
View Source
const (
	INDEX_NOT_EXISTS = "index does not exist"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AggFunc added in v1.2.82

type AggFunc string

AggFunc represents an aggregation function type (e.g., count, sum, avg).

const (
	COUNT AggFunc = "count" // Count aggregation
	SUM   AggFunc = "sum"   // Sum aggregation
	AVG   AggFunc = "avg"   // Average aggregation
	MIN   AggFunc = "min"   // Minimum aggregation
	MAX   AggFunc = "max"   // Maximum aggregation
)

type FilterFunction

type FilterFunction func(raw map[string]any, filter QueryFilter) bool

FilterFunction signature of a filter function

type IAdvancedQuery added in v1.2.129

type IAdvancedQuery interface {
	IQuery
	IAnalyticQuery
}

IAdvancedQuery defines a composed interface that combines IQuery and IAnalyticQuery. It is intended for advanced querying capabilities, including both standard data retrieval and analytics.

type IAnalyticQuery added in v1.2.138

type IAnalyticQuery interface {

	// Sum calculates the sum of the specified field.
	Sum(fieldName string) IAnalyticQuery

	// Min calculates the minimum value of the specified field.
	Min(fieldName string) IAnalyticQuery

	// Max calculates the maximum value of the specified field.
	Max(fieldName string) IAnalyticQuery

	// Avg calculates the average value of the specified field.
	Avg(fieldName string) IAnalyticQuery

	// CountAll counts all occurrences of the specified field.
	CountAll(fieldName string) IAnalyticQuery

	// CountUnique counts unique occurrences of the specified field.
	CountUnique(fieldName string) IAnalyticQuery

	// GroupBy groups the results by the specified field and time period.
	GroupBy(fieldName string, timePeriod e.TimePeriodCode) IAnalyticQuery

	// Compute executes the analytic query and returns the results.
	Compute() (out []e.Entity, err error)
}

IAnalyticQuery defines the interface for building and executing analytic queries. It supports aggregation functions (Sum, Min, Max, Avg, Count) and grouping.

type IDataCache

type IDataCache interface {

	// Closer includes method Close() to close the cache connection.
	io.Closer

	// Ping tests the cache connectivity.
	// It retries the connection 'retries' times with an 'intervalInSeconds' delay between attempts.
	Ping(retries uint, intervalInSeconds uint) error

	// CloneDataCache returns a clone (copy) of the cache instance.
	CloneDataCache() (IDataCache, error)

	// Get retrieves the value of a key and unmarshals it into an Entity.
	Get(factory EntityFactory, key string) (Entity, error)

	// GetRaw retrieves the raw byte value of a key.
	GetRaw(key string) ([]byte, error)

	// GetKeys retrieves the values of multiple keys and unmarshals them into Entities.
	GetKeys(factory EntityFactory, keys ...string) ([]Entity, error)

	// GetRawKeys retrieves the raw byte values of multiple keys.
	GetRawKeys(keys ...string) ([]Tuple[string, []byte], error)

	// Set sets the value of a key with an optional expiration time.
	Set(key string, entity Entity, expiration ...time.Duration) error

	// SetRaw sets the raw byte value of a key with an optional expiration time.
	SetRaw(key string, bytes []byte, expiration ...time.Duration) error

	// SetNX sets the value of a key only if it does not exist.
	// Returns true if the key was set, false if it already exists.
	SetNX(key string, entity Entity, expiration ...time.Duration) (bool, error)

	// SetRawNX sets the raw byte value of a key only if it does not exist.
	// Returns true if the key was set, false if it already exists.
	SetRawNX(key string, bytes []byte, expiration ...time.Duration) (bool, error)

	// Add sets the value of a key only if it does not exist (alias for SetNX).
	Add(key string, entity Entity, expiration time.Duration) (bool, error)

	// AddRaw sets the raw byte value of a key only if it does not exist (alias for SetRawNX).
	AddRaw(key string, bytes []byte, expiration time.Duration) (bool, error)

	// Del deletes one or more keys.
	Del(keys ...string) (err error)

	// Rename changes the name of a key.
	Rename(key string, newKey string) (err error)

	// Exists checks if a key exists.
	Exists(key string) (result bool, err error)

	// Scan iterates over keys matching a pattern.
	Scan(from uint64, match string, count int64) (keys []string, cursor uint64, err error)

	// HGet retrieves the value of a hash field and unmarshals it into an Entity.
	HGet(factory EntityFactory, key, field string) (result Entity, err error)

	// HGetRaw retrieves the raw byte value of a hash field.
	HGetRaw(key, field string) ([]byte, error)

	// HKeys retrieves all field names in a hash.
	HKeys(key string) (fields []string, err error)

	// HGetAll retrieves all fields and values in a hash.
	HGetAll(factory EntityFactory, key string) (result map[string]Entity, err error)

	// HGetRawAll retrieves all fields and raw byte values in a hash.
	HGetRawAll(key string) (result map[string][]byte, err error)

	// HSet sets the value of a hash field.
	HSet(key, field string, entity Entity) (err error)

	// HSetRaw sets the raw byte value of a hash field.
	HSetRaw(key, field string, bytes []byte) (err error)

	// HSetNX sets the value of a hash field only if it does not exist.
	HSetNX(key, field string, entity Entity) (result bool, err error)

	// HSetRawNX sets the raw byte value of a hash field only if it does not exist.
	HSetRawNX(key, field string, bytes []byte) (result bool, err error)

	// HDel deletes one or more hash fields.
	HDel(key string, fields ...string) (err error)

	// HAdd sets the value of a hash field only if it does not exist (alias for HSetNX).
	HAdd(key, field string, entity Entity) (result bool, err error)

	// HAddRaw sets the raw byte value of a hash field only if it does not exist (alias for HSetRawNX).
	HAddRaw(key, field string, bytes []byte) (result bool, err error)

	// HExists checks if a hash field exists.
	HExists(key, field string) (result bool, err error)

	// RPush appends one or more values to the end of a list.
	RPush(key string, value ...Entity) (err error)

	// LPush prepends one or more values to the beginning of a list.
	LPush(key string, value ...Entity) (err error)

	// RPop removes and returns the last element of a list.
	RPop(factory EntityFactory, key string) (entity Entity, err error)

	// LPop removes and returns the first element of a list.
	LPop(factory EntityFactory, key string) (entity Entity, err error)

	// BRPop removes and returns the last element of a list, blocking if the list is empty.
	BRPop(factory EntityFactory, timeout time.Duration, keys ...string) (key string, entity Entity, err error)

	// BLPop removes and returns the first element of a list, blocking if the list is empty.
	BLPop(factory EntityFactory, timeout time.Duration, keys ...string) (key string, entity Entity, err error)

	// LRange retrieves a range of elements from a list.
	LRange(factory EntityFactory, key string, start, stop int64) (result []Entity, err error)

	// LLen returns the length of a list.
	LLen(key string) (result int64)

	// ObtainLocker tries to obtain a distributed lock with the given key and TTL.
	ObtainLocker(key string, ttl time.Duration) (ILocker, error)
}

IDataCache defines the interface for a distributed cache and data structure store (e.g., Redis). It supports key-value operations, hashes, lists, and distributed locking.

func NewInMemoryDataCache

func NewInMemoryDataCache() (IDataCache, error)

NewInMemoryDataCache creates a new instance of InMemoryDataCache.

type IDatabase

type IDatabase interface {

	// Closer includes method Close() to close the database connection.
	io.Closer

	// Ping tests the database connectivity.
	// It retries the connection 'retries' times with an 'intervalInSeconds' delay between attempts.
	Ping(retries uint, intervalInSeconds uint) error

	// CloneDatabase returns a clone (copy) of the database instance.
	// This is useful for creating a new instance with the same configuration but potentially different state or connection pool.
	CloneDatabase() (IDatabase, error)

	// Get retrieves a single entity by its ID.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Get(factory EntityFactory, entityID string, keys ...string) (result Entity, err error)

	// List retrieves multiple entities by their IDs.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	List(factory EntityFactory, entityIDs []string, keys ...string) (list []Entity, err error)

	// Exists checks if an entity exists by its ID.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Exists(factory EntityFactory, entityID string, keys ...string) (result bool, err error)

	// Insert adds a new entity to the database.
	// It returns the added entity (potentially with updated fields like ID or timestamps) or an error.
	Insert(entity Entity) (added Entity, err error)

	// Update modifies an existing entity in the database.
	// It returns the updated entity or an error if the entity does not exist or the update fails.
	Update(entity Entity) (updated Entity, err error)

	// Upsert updates an entity if it exists, or creates it if it does not.
	// It returns the updated or inserted entity.
	Upsert(entity Entity) (updated Entity, err error)

	// Delete removes an entity by its ID.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Delete(factory EntityFactory, entityID string, keys ...string) (err error)

	// BulkInsert adds multiple entities to the database in a batch operation.
	// It returns the number of affected records and any error encountered.
	BulkInsert(entities []Entity) (affected int64, err error)

	// BulkUpdate modifies multiple entities in the database in a batch operation.
	// It returns the number of affected records and any error encountered.
	BulkUpdate(entities []Entity) (affected int64, err error)

	// BulkUpsert updates or inserts multiple entities in the database in a batch operation.
	// It returns the number of affected records and any error encountered.
	BulkUpsert(entities []Entity) (affected int64, err error)

	// BulkDelete removes multiple entities by their IDs in a batch operation.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	BulkDelete(factory EntityFactory, entityIDs []string, keys ...string) (affected int64, err error)

	// SetField updates a single field of an entity in a single transaction.
	// This eliminates the need to fetch, change, and update the entire entity.
	SetField(factory EntityFactory, entityID string, field string, value any, keys ...string) (err error)

	// SetFields updates multiple fields of an entity in a single transaction.
	// The 'fields' argument is a map where the key is the field name and the value is the new value.
	SetFields(factory EntityFactory, entityID string, fields map[string]any, keys ...string) (err error)

	// BulkSetFields updates a specific field for multiple entities in a single transaction.
	// The 'values' argument is a map where the key is the entity ID and the value is the new value for the field.
	BulkSetFields(factory EntityFactory, field string, values map[string]any, keys ...string) (affected int64, err error)

	// Query returns a new IQuery builder for the given entity factory.
	// The IQuery builder allows for constructing complex queries with filters, sorting, and pagination.
	Query(factory EntityFactory) IQuery

	// AdvancedQuery returns an IAdvancedQuery builder, which supports analytic queries.
	// It is intended for working with sharded tables where the KEY() method is used to resolve the table name.
	AdvancedQuery(factory EntityFactory) IAdvancedQuery

	// ExecuteDDL executes Data Definition Language (DDL) commands to create tables and indexes.
	// The 'ddl' argument is a map where the key is the table name and the value is a list of fields to index.
	ExecuteDDL(ddl map[string][]string) (err error)

	// ExecuteSQL executes a raw SQL command.
	// It returns the number of affected records and any error encountered.
	ExecuteSQL(sql string, args ...any) (affected int64, err error)

	// ExecuteQuery executes a raw SQL query and returns the results as a list of Json maps.
	ExecuteQuery(source, sql string, args ...any) ([]Json, error)

	// DropTable drops a table and its indexes.
	DropTable(table string) (err error)

	// PurgeTable removes all data from a table (truncate).
	PurgeTable(table string) (err error)
}

IDatabase defines the interface for a Relational Database Management System (RDBMS) wrapper. It provides a unified API for CRUD operations, querying, schema management, and transaction handling.

func NewInMemoryDatabase

func NewInMemoryDatabase() (IDatabase, error)

NewInMemoryDatabase creates a new instance of InMemoryDatabase.

type IDatastore

type IDatastore interface {

	// Closer includes method Close() to close the datastore connection.
	io.Closer

	// Ping tests the datastore connectivity.
	// It retries the connection 'retries' times with an 'intervalInSeconds' delay between attempts.
	Ping(retries uint, intervalInSeconds uint) error

	// CloneDatastore returns a clone (copy) of the datastore instance.
	// This is useful for creating a new instance with the same configuration but potentially different state or connection pool.
	CloneDatastore() (IDatastore, error)

	// Get retrieves a single entity by its ID.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Get(factory EntityFactory, entityID string, keys ...string) (result Entity, err error)

	// List retrieves multiple entities by their IDs.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	List(factory EntityFactory, entityIDs []string, keys ...string) (list []Entity, err error)

	// Exists checks if an entity exists by its ID.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Exists(factory EntityFactory, entityID string, keys ...string) (result bool, err error)

	// Insert adds a new entity to the datastore.
	// It returns the added entity (potentially with updated fields like ID or timestamps) or an error.
	Insert(entity Entity) (added Entity, err error)

	// Update modifies an existing entity in the datastore.
	// It returns the updated entity or an error if the entity does not exist or the update fails.
	Update(entity Entity) (updated Entity, err error)

	// Upsert updates an entity if it exists, or creates it if it does not.
	// It returns the updated or inserted entity.
	Upsert(entity Entity) (updated Entity, err error)

	// Delete removes an entity by its ID.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Delete(factory EntityFactory, entityID string, keys ...string) (err error)

	// BulkInsert adds multiple entities to the datastore in a batch operation.
	// It returns the number of affected records and any error encountered.
	BulkInsert(entities []Entity) (affected int64, err error)

	// BulkUpdate modifies multiple entities in the datastore in a batch operation.
	// It returns the number of affected records and any error encountered.
	BulkUpdate(entities []Entity) (affected int64, err error)

	// BulkUpsert updates or inserts multiple entities in the datastore in a batch operation.
	// It returns the number of affected records and any error encountered.
	BulkUpsert(entities []Entity) (affected int64, err error)

	// BulkDelete removes multiple entities by their IDs in a batch operation.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	BulkDelete(factory EntityFactory, entityIDs []string, keys ...string) (affected int64, err error)

	// SetField updates a single field of an entity in a single transaction.
	// This eliminates the need to fetch, change, and update the entire entity.
	SetField(factory EntityFactory, entityID string, field string, value any, keys ...string) (err error)

	// SetFields updates multiple fields of an entity in a single transaction.
	// The 'fields' argument is a map where the key is the field name and the value is the new value.
	SetFields(factory EntityFactory, entityID string, fields map[string]any, keys ...string) (err error)

	// Query returns a new IQuery builder for the given entity factory.
	// The IQuery builder allows for constructing complex queries with filters, sorting, and pagination.
	Query(factory EntityFactory) IQuery

	// IndexExists checks if an index exists.
	IndexExists(indexName string) (exists bool)

	// CreateIndex creates a new index (without mapping).
	CreateIndex(indexName string) (name string, err error)

	// CreateEntityIndex creates an index for an entity and adds entity field mapping.
	CreateEntityIndex(factory EntityFactory, key string) (name string, err error)

	// ListIndices returns a list of all indices matching the pattern.
	ListIndices(pattern string) (map[string]int, error)

	// DropIndex drops an index.
	DropIndex(indexName string) (ack bool, err error)

	// ExecuteQuery executes a native query (e.g., KQL, N1QL) and returns the results as a list of Json maps.
	ExecuteQuery(source string, query string, args ...any) ([]Json, error)
}

IDatastore defines the interface for NoSQL Big Data (Document Store) wrapper implementations (e.g., Couchbase, ElasticSearch). It provides methods for CRUD operations, querying, and index management.

func NewInMemoryDatastore

func NewInMemoryDatastore() (IDatastore, error)

NewInMemoryDatastore creates a new instance of InMemoryDatastore.

type ILocker added in v1.2.54

type ILocker interface {
	// Key returns the key of the lock.
	Key() string

	// Token returns the unique token associated with the lock.
	Token() string

	// TTL returns the remaining time-to-live of the lock.
	// Returns 0 if the lock has expired.
	TTL(ctx context.Context) (time.Duration, error)

	// Refresh extends the lock's TTL.
	Refresh(ctx context.Context, ttl time.Duration) error

	// Release releases the lock.
	Release(ctx context.Context) error
}

ILocker defines the interface for a distributed lock.

type IQuery

type IQuery interface {

	// Apply adds a callback function to be applied to each result entity.
	Apply(cb func(in Entity) Entity) IQuery

	// Filter adds a single field filter to the query.
	Filter(filter QueryFilter) IQuery

	// Range adds a time frame filter on a specific time field.
	Range(field string, from Timestamp, to Timestamp) IQuery

	// MatchAll adds a list of filters, all of which must be satisfied (AND logic).
	MatchAll(filters ...QueryFilter) IQuery

	// MatchAny adds a list of filters, any of which must be satisfied (OR logic).
	MatchAny(filters ...QueryFilter) IQuery

	// Sort adds a sort order by field.
	// The sort parameter should be in the format: "field_name" (Ascending) or "field_name-" (Descending).
	Sort(sort string) IQuery

	// Page sets the requested page number for pagination (0-based).
	Page(page int) IQuery

	// Limit sets the page size limit for pagination.
	Limit(page int) IQuery

	// List executes the query to retrieve a list of entities by their IDs, ignoring other criteria.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	List(entityIDs []string, keys ...string) (out []Entity, err error)

	// Find executes the query based on criteria, order, and pagination.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Find(keys ...string) (out []Entity, total int64, err error)

	// Select executes the query and returns specific fields as a list of Json maps.
	Select(fields ...string) ([]Json, error)

	// Count executes the query and returns the number of matching entities.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Count(keys ...string) (total int64, err error)

	// Aggregation executes an aggregation function on a field for the matching entities.
	// Supported functions: count, sum, avg, min, max.
	Aggregation(field string, function AggFunc, keys ...string) (value float64, err error)

	// GroupCount executes the query and returns the count of entities per group (grouped by field).
	GroupCount(field string, keys ...string) (out map[any]int64, total int64, err error)

	// GroupAggregation executes the query and returns the aggregated value per group.
	// Each data point includes the count of documents and the calculated value.
	GroupAggregation(field string, function AggFunc, keys ...string) (out map[any]Tuple[int64, float64], total float64, err error)

	// Histogram returns time series data points based on a time field.
	// Supported intervals: Minute, Hour, Day, Week, Month.
	Histogram(field string, function AggFunc, timeField string, interval time.Duration, keys ...string) (out map[Timestamp]Tuple[int64, float64], total float64, err error)

	// Histogram2D returns two-dimensional time series data points based on a time field.
	Histogram2D(field string, function AggFunc, dim, timeField string, interval time.Duration, keys ...string) (out map[Timestamp]map[any]Tuple[int64, float64], total float64, err error)

	// FindSingle executes the query and returns the first matching entity.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	FindSingle(keys ...string) (entity Entity, err error)

	// GetMap executes the query and returns the results as a map of ID -> Entity.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	GetMap(keys ...string) (out map[string]Entity, err error)

	// GetIDs executes the query and returns a list of IDs of the matching entities.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	GetIDs(keys ...string) (out []string, err error)

	// Delete removes the entities matching the query criteria.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	Delete(keys ...string) (total int64, err error)

	// SetField updates a single field for all documents matching the criteria.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	SetField(field string, value any, keys ...string) (total int64, err error)

	// SetFields updates multiple fields for all documents matching the criteria.
	// The 'keys' argument is optional and can be used for sharding or other specific lookup mechanisms.
	SetFields(fields map[string]any, keys ...string) (total int64, err error)

	// ToString returns a string representation of the query.
	ToString() string
}

IQuery defines the interface for building and executing database queries. It supports filtering, sorting, pagination, and aggregation.

type ITable

type ITable interface {

	// Get retrieves a single entity by its ID.
	Get(entityID string) (entity Entity, err error)

	// Exists checks if an entity exists by its ID.
	Exists(entityID string) (result bool, err error)

	// Insert inserts a new entity into the table.
	Insert(entity Entity) (added Entity, err error)

	// Update updates an existing entity in the table.
	Update(entity Entity) (added Entity, err error)

	// Upsert inserts or updates an entity in the table.
	Upsert(entity Entity) (added Entity, err error)

	// Delete deletes an entity from the table by its ID.
	Delete(entityID string) (err error)

	// Table returns the underlying map storage of the table.
	Table() (result map[string]Entity)
}

ITable defines the interface for a database table. It provides methods for basic CRUD operations on entities within the table.

func NewInMemTable

func NewInMemTable() ITable

NewInMemTable creates a new instance of InMemoryTable.

type InMemoryDataCache

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

InMemoryDataCache represents an in-memory implementation of the IDataCache interface. It uses a TTL cache for keys, and maps for lists and queues. It is primarily used for testing and development.

func (*InMemoryDataCache) Add added in v1.2.1

func (dc *InMemoryDataCache) Add(key string, entity Entity, expiration time.Duration) (result bool, err error)

Add stores a value for a key only if it does not exist.

func (*InMemoryDataCache) AddRaw added in v1.2.54

func (dc *InMemoryDataCache) AddRaw(key string, bytes []byte, expiration time.Duration) (result bool, err error)

AddRaw stores a raw value for a key only if it does not exist.

func (*InMemoryDataCache) BLPop

func (dc *InMemoryDataCache) BLPop(factory EntityFactory, timeout time.Duration, keys ...string) (key string, entity Entity, err error)

BLPop removes and returns the first element of a list, blocking if the list is empty.

func (*InMemoryDataCache) BRPop

func (dc *InMemoryDataCache) BRPop(factory EntityFactory, timeout time.Duration, keys ...string) (key string, value Entity, err error)

BRPop removes and returns the last element of a list, blocking if the list is empty.

func (*InMemoryDataCache) CloneDataCache added in v1.2.62

func (dc *InMemoryDataCache) CloneDataCache() (IDataCache, error)

CloneDataCache creates a copy of the current cache instance.

func (*InMemoryDataCache) Close

func (dc *InMemoryDataCache) Close() error

Close closes the cache and frees resources.

func (*InMemoryDataCache) Del

func (dc *InMemoryDataCache) Del(keys ...string) (err error)

Del removes one or more keys from the cache.

func (*InMemoryDataCache) Exists

func (dc *InMemoryDataCache) Exists(key string) (result bool, err error)

Exists checks if a key exists in the cache.

func (*InMemoryDataCache) Get

func (dc *InMemoryDataCache) Get(factory EntityFactory, key string) (result Entity, err error)

Get retrieves the value of a key.

func (*InMemoryDataCache) GetKeys added in v1.2.1

func (dc *InMemoryDataCache) GetKeys(factory EntityFactory, keys ...string) (results []Entity, err error)

GetKeys retrieves the values of all the given keys.

func (*InMemoryDataCache) GetRaw added in v1.2.54

func (dc *InMemoryDataCache) GetRaw(key string) (res []byte, err error)

GetRaw retrieves the raw value of a key.

func (*InMemoryDataCache) GetRawKeys added in v1.2.54

func (dc *InMemoryDataCache) GetRawKeys(keys ...string) ([]Tuple[string, []byte], error)

GetRawKeys retrieves the raw values of all the given keys.

func (*InMemoryDataCache) HAdd added in v1.2.1

func (dc *InMemoryDataCache) HAdd(key, field string, entity Entity) (result bool, err error)

HAdd stores a value in a hash field only if it does not exist.

func (*InMemoryDataCache) HAddRaw added in v1.2.54

func (dc *InMemoryDataCache) HAddRaw(key, field string, bytes []byte) (result bool, err error)

HAddRaw stores a raw value in a hash field only if it does not exist.

func (*InMemoryDataCache) HDel

func (dc *InMemoryDataCache) HDel(key string, fields ...string) (err error)

HDel removes one or more fields from a hash.

func (*InMemoryDataCache) HExists

func (dc *InMemoryDataCache) HExists(key, field string) (result bool, err error)

HExists checks if a hash field exists.

func (*InMemoryDataCache) HGet

func (dc *InMemoryDataCache) HGet(factory EntityFactory, key, field string) (result Entity, err error)

HGet retrieves the value of a hash field.

func (*InMemoryDataCache) HGetAll

func (dc *InMemoryDataCache) HGetAll(factory EntityFactory, key string) (result map[string]Entity, err error)

HGetAll retrieves all the fields and values in a hash.

func (*InMemoryDataCache) HGetRaw added in v1.2.54

func (dc *InMemoryDataCache) HGetRaw(key, field string) ([]byte, error)

HGetRaw retrieves the raw value of a hash field.

func (*InMemoryDataCache) HGetRawAll added in v1.2.54

func (dc *InMemoryDataCache) HGetRawAll(key string) (result map[string][]byte, err error)

HGetRawAll retrieves all the fields and raw values in a hash.

func (*InMemoryDataCache) HKeys

func (dc *InMemoryDataCache) HKeys(key string) (fields []string, err error)

HKeys retrieves all the fields in a hash.

func (*InMemoryDataCache) HSet

func (dc *InMemoryDataCache) HSet(key, field string, entity Entity) (err error)

HSet stores a value in a hash field.

func (*InMemoryDataCache) HSetNX

func (dc *InMemoryDataCache) HSetNX(key, field string, entity Entity) (bool, error)

HSetNX stores a value in a hash field only if it does not exist.

func (*InMemoryDataCache) HSetRaw added in v1.2.54

func (dc *InMemoryDataCache) HSetRaw(key, field string, bytes []byte) (err error)

HSetRaw stores a raw value in a hash field.

func (*InMemoryDataCache) HSetRawNX added in v1.2.54

func (dc *InMemoryDataCache) HSetRawNX(key, field string, bytes []byte) (bool, error)

HSetRawNX stores a raw value in a hash field only if it does not exist.

func (*InMemoryDataCache) LLen

func (dc *InMemoryDataCache) LLen(key string) (result int64)

LLen returns the length of a list.

func (*InMemoryDataCache) LPop

func (dc *InMemoryDataCache) LPop(factory EntityFactory, key string) (entity Entity, err error)

LPop removes and returns the first element of a list.

func (*InMemoryDataCache) LPush

func (dc *InMemoryDataCache) LPush(key string, value ...Entity) (err error)

LPush prepends one or more values to the left end of a list.

func (*InMemoryDataCache) LRange

func (dc *InMemoryDataCache) LRange(factory EntityFactory, key string, start, stop int64) (result []Entity, err error)

LRange retrieves a range of elements from a list.

func (*InMemoryDataCache) ObtainLocker added in v1.2.54

func (dc *InMemoryDataCache) ObtainLocker(key string, ttl time.Duration) (ILocker, error)

ObtainLocker tries to obtain a new lock using a key with the given TTL.

func (*InMemoryDataCache) Ping

func (dc *InMemoryDataCache) Ping(retries uint, interval uint) error

Ping tests the cache connectivity (always returns nil for in-memory cache).

func (*InMemoryDataCache) RPop

func (dc *InMemoryDataCache) RPop(factory EntityFactory, key string) (entity Entity, err error)

RPop removes and returns the last element of a list.

func (*InMemoryDataCache) RPush

func (dc *InMemoryDataCache) RPush(key string, value ...Entity) (err error)

RPush appends one or more values to the right end of a list.

func (*InMemoryDataCache) Rename

func (dc *InMemoryDataCache) Rename(key string, newKey string) (err error)

Rename renames a key.

func (*InMemoryDataCache) Scan

func (dc *InMemoryDataCache) Scan(from uint64, match string, count int64) (keys []string, cursor uint64, err error)

Scan iterates over keys matching the pattern (regex) starting from the cursor.

func (*InMemoryDataCache) Set

func (dc *InMemoryDataCache) Set(key string, entity Entity, expiration ...time.Duration) (err error)

Set stores a value for a key with an optional expiration time.

func (*InMemoryDataCache) SetNX

func (dc *InMemoryDataCache) SetNX(key string, entity Entity, expiration ...time.Duration) (bool, error)

SetNX stores a value for a key only if it does not exist, with an optional expiration time. Returns true if the key was set, false otherwise.

func (*InMemoryDataCache) SetRaw added in v1.2.54

func (dc *InMemoryDataCache) SetRaw(key string, bytes []byte, expiration ...time.Duration) (err error)

SetRaw stores a raw value for a key with an optional expiration time.

func (*InMemoryDataCache) SetRawNX added in v1.2.54

func (dc *InMemoryDataCache) SetRawNX(key string, bytes []byte, expiration ...time.Duration) (bool, error)

SetRawNX stores a raw value for a key only if it does not exist, with an optional expiration time. Returns true if the key was set, false otherwise.

type InMemoryDatabase

type InMemoryDatabase struct {
	Db map[string]ITable `json:"db"` // Db is a map of table names to ITable instances.
}

InMemoryDatabase represents an in-memory database implementation using maps. It implements the IDatabase interface and is primarily used for testing and development.

func (*InMemoryDatabase) AdvancedQuery added in v1.2.139

func (d *InMemoryDatabase) AdvancedQuery(factory EntityFactory) IAdvancedQuery

AdvancedQuery creates a new advanced query builder (not implemented).

func (*InMemoryDatabase) Backup added in v1.2.166

func (d *InMemoryDatabase) Backup(path string) error

Backup creates a backup of the database to a file.

func (*InMemoryDatabase) BulkDelete

func (d *InMemoryDatabase) BulkDelete(factory EntityFactory, entityIDs []string, keys ...string) (affected int64, err error)

BulkDelete deletes multiple entities from the database by their IDs.

func (*InMemoryDatabase) BulkInsert

func (d *InMemoryDatabase) BulkInsert(entities []Entity) (affected int64, err error)

BulkInsert inserts multiple entities into the database.

func (*InMemoryDatabase) BulkSetFields added in v1.2.51

func (d *InMemoryDatabase) BulkSetFields(factory EntityFactory, field string, values map[string]any, keys ...string) (affected int64, error error)

BulkSetFields updates a specific field of multiple entities in a single transaction.

func (*InMemoryDatabase) BulkUpdate

func (d *InMemoryDatabase) BulkUpdate(entities []Entity) (affected int64, err error)

BulkUpdate updates multiple entities in the database.

func (*InMemoryDatabase) BulkUpsert

func (d *InMemoryDatabase) BulkUpsert(entities []Entity) (affected int64, err error)

BulkUpsert inserts or updates multiple entities in the database.

func (*InMemoryDatabase) CloneDatabase added in v1.2.62

func (d *InMemoryDatabase) CloneDatabase() (IDatabase, error)

CloneDatabase creates a copy of the current database instance. Note: This performs a shallow copy of the database structure.

func (*InMemoryDatabase) Close

func (d *InMemoryDatabase) Close() error

Close closes the database connection (no-op for in-memory database).

func (*InMemoryDatabase) Delete

func (d *InMemoryDatabase) Delete(factory EntityFactory, entityID string, keys ...string) (err error)

Delete deletes an entity from the database by its ID.

func (*InMemoryDatabase) DropTable

func (d *InMemoryDatabase) DropTable(table string) (err error)

DropTable drops a table and its related indexes.

func (*InMemoryDatabase) ExecuteDDL

func (d *InMemoryDatabase) ExecuteDDL(ddl map[string][]string) (err error)

ExecuteDDL executes a Data Definition Language (DDL) query. The ddl parameter is a map of strings (table names) to array of strings (list of fields to index).

func (*InMemoryDatabase) ExecuteQuery added in v1.2.64

func (d *InMemoryDatabase) ExecuteQuery(source, sql string, args ...any) ([]Json, error)

ExecuteQuery executes a native SQL query (not supported).

func (*InMemoryDatabase) ExecuteSQL

func (d *InMemoryDatabase) ExecuteSQL(sql string, args ...any) (affected int64, err error)

ExecuteSQL executes a raw SQL query (not supported).

func (*InMemoryDatabase) Exists

func (d *InMemoryDatabase) Exists(factory EntityFactory, entityID string, keys ...string) (result bool, err error)

Exists checks if an entity exists by its ID.

func (*InMemoryDatabase) Get

func (d *InMemoryDatabase) Get(factory EntityFactory, entityID string, keys ...string) (result Entity, err error)

Get retrieves a single entity by its ID.

func (*InMemoryDatabase) Insert

func (d *InMemoryDatabase) Insert(entity Entity) (added Entity, err error)

Insert inserts a new entity into the database.

func (*InMemoryDatabase) List

func (d *InMemoryDatabase) List(factory EntityFactory, entityIDs []string, keys ...string) (list []Entity, err error)

List retrieves a list of entities by their IDs.

func (*InMemoryDatabase) Ping

func (d *InMemoryDatabase) Ping(retries uint, intervalInSeconds uint) error

Ping tests the database connectivity (always returns nil for in-memory database).

func (*InMemoryDatabase) PurgeTable

func (d *InMemoryDatabase) PurgeTable(table string) (err error)

PurgeTable removes all data from a table (truncate).

func (*InMemoryDatabase) Query

func (d *InMemoryDatabase) Query(factory EntityFactory) IQuery

Query creates a new query builder for the specified entity factory.

func (*InMemoryDatabase) Restore added in v1.2.166

func (d *InMemoryDatabase) Restore(path string) error

Restore restores the database from a backup file.

func (*InMemoryDatabase) SetField

func (d *InMemoryDatabase) SetField(factory EntityFactory, entityID string, field string, value any, keys ...string) (err error)

SetField updates a single field of an entity.

func (*InMemoryDatabase) SetFields

func (d *InMemoryDatabase) SetFields(factory EntityFactory, entityID string, fields map[string]any, keys ...string) (err error)

SetFields updates multiple fields of an entity.

func (*InMemoryDatabase) Update

func (d *InMemoryDatabase) Update(entity Entity) (updated Entity, err error)

Update updates an existing entity in the database.

func (*InMemoryDatabase) Upsert

func (d *InMemoryDatabase) Upsert(entity Entity) (updated Entity, err error)

Upsert inserts or updates an entity in the database.

type InMemoryDatastore

type InMemoryDatastore struct {
	Db map[string]ITable `json:"db"` // Db is a map of collection names to ITable instances.
}

InMemoryDatastore represents an in-memory implementation of the IDatastore interface. It uses a map to store data (simulating tables/collections) and is primarily used for testing and development.

func (*InMemoryDatastore) BulkDelete

func (d *InMemoryDatastore) BulkDelete(factory EntityFactory, entityIDs []string, keys ...string) (affected int64, err error)

BulkDelete deletes multiple entities from the datastore by their IDs.

func (*InMemoryDatastore) BulkInsert

func (d *InMemoryDatastore) BulkInsert(entities []Entity) (affected int64, err error)

BulkInsert inserts multiple entities into the datastore.

func (*InMemoryDatastore) BulkSetFields added in v1.2.51

func (d *InMemoryDatastore) BulkSetFields(factory EntityFactory, field string, values map[string]any, keys ...string) (affected int64, error error)

BulkSetFields updates a specific field of multiple entities in a single transaction.

func (*InMemoryDatastore) BulkUpdate

func (d *InMemoryDatastore) BulkUpdate(entities []Entity) (affected int64, err error)

BulkUpdate updates multiple entities in the datastore.

func (*InMemoryDatastore) BulkUpsert

func (d *InMemoryDatastore) BulkUpsert(entities []Entity) (affected int64, err error)

BulkUpsert inserts or updates multiple entities in the datastore.

func (*InMemoryDatastore) CloneDatastore added in v1.2.62

func (d *InMemoryDatastore) CloneDatastore() (IDatastore, error)

CloneDatastore creates a copy of the current datastore instance.

func (*InMemoryDatastore) Close

func (d *InMemoryDatastore) Close() error

Close closes the datastore connection (no-op for in-memory datastore).

func (*InMemoryDatastore) CreateEntityIndex

func (d *InMemoryDatastore) CreateEntityIndex(factory EntityFactory, key string) (name string, err error)

CreateEntityIndex creates an index for the entity (no-op for in-memory datastore).

func (*InMemoryDatastore) CreateIndex

func (d *InMemoryDatastore) CreateIndex(indexName string) (name string, err error)

CreateIndex creates an index on the specified fields (no-op for in-memory datastore).

func (*InMemoryDatastore) Delete

func (d *InMemoryDatastore) Delete(factory EntityFactory, entityID string, keys ...string) (err error)

Delete deletes an entity from the datastore by its ID.

func (*InMemoryDatastore) DropIndex

func (d *InMemoryDatastore) DropIndex(indexName string) (ack bool, err error)

DropIndex drops an index (no-op for in-memory datastore).

func (*InMemoryDatastore) ExecuteQuery added in v1.2.80

func (d *InMemoryDatastore) ExecuteQuery(source string, query string, args ...any) ([]Json, error)

ExecuteQuery executes a native query (not implemented).

func (*InMemoryDatastore) Exists

func (d *InMemoryDatastore) Exists(factory EntityFactory, entityID string, keys ...string) (result bool, err error)

Exists checks if an entity exists by its ID.

func (*InMemoryDatastore) Get

func (d *InMemoryDatastore) Get(factory EntityFactory, entityID string, keys ...string) (result Entity, err error)

Get retrieves a single entity by its ID.

func (*InMemoryDatastore) IndexExists

func (d *InMemoryDatastore) IndexExists(indexName string) (exists bool)

IndexExists tests if index exists

func (*InMemoryDatastore) Insert

func (d *InMemoryDatastore) Insert(entity Entity) (added Entity, err error)

Insert inserts a new entity into the datastore.

func (*InMemoryDatastore) List

func (d *InMemoryDatastore) List(factory EntityFactory, entityIDs []string, keys ...string) (list []Entity, err error)

List retrieves a list of entities by their IDs.

func (*InMemoryDatastore) ListIndices added in v1.2.71

func (d *InMemoryDatastore) ListIndices(pattern string) (map[string]int, error)

ListIndices retrieves a list of existing indices (returns empty list for in-memory datastore).

func (*InMemoryDatastore) Ping

func (d *InMemoryDatastore) Ping(retries uint, intervalInSeconds uint) error

Ping tests the datastore connectivity (always returns nil for in-memory datastore).

func (*InMemoryDatastore) PurgeIndex added in v1.2.169

func (d *InMemoryDatastore) PurgeIndex(indexName string) (ack bool, err error)

PurgeIndex removes all data from an index (truncate).

func (*InMemoryDatastore) Query

func (d *InMemoryDatastore) Query(factory EntityFactory) IQuery

Query creates a new query builder for the specified entity factory.

func (*InMemoryDatastore) SetField

func (d *InMemoryDatastore) SetField(factory EntityFactory, entityID string, field string, value any, keys ...string) (err error)

SetField updates a single field of an entity.

func (*InMemoryDatastore) SetFields

func (d *InMemoryDatastore) SetFields(factory EntityFactory, entityID string, fields map[string]any, keys ...string) (err error)

SetFields updates multiple fields of an entity.

func (*InMemoryDatastore) Update

func (d *InMemoryDatastore) Update(entity Entity) (updated Entity, err error)

Update updates an existing entity in the datastore.

func (*InMemoryDatastore) Upsert

func (d *InMemoryDatastore) Upsert(entity Entity) (updated Entity, err error)

Upsert inserts or updates an entity in the datastore.

type InMemoryTable

type InMemoryTable struct {
	DbTable map[string]Entity `json:"dbTable"` // DbTable is the underlying map storage.
}

InMemoryTable represents an in-memory implementation of the ITable interface. It uses a map to store entities.

func (*InMemoryTable) Delete

func (tbl *InMemoryTable) Delete(entityID string) (err error)

Delete deletes an entity from the table by its ID.

func (*InMemoryTable) Exists

func (tbl *InMemoryTable) Exists(entityID string) (result bool, err error)

Exists checks if an entity exists by its ID.

func (*InMemoryTable) Get

func (tbl *InMemoryTable) Get(entityID string) (entity Entity, err error)

Get retrieves a single entity by its ID.

func (*InMemoryTable) Insert

func (tbl *InMemoryTable) Insert(entity Entity) (added Entity, err error)

Insert inserts a new entity into the table.

func (*InMemoryTable) Table

func (tbl *InMemoryTable) Table() (result map[string]Entity)

Table returns the underlying map storage of the table.

func (*InMemoryTable) Update

func (tbl *InMemoryTable) Update(entity Entity) (added Entity, err error)

Update updates an existing entity in the table.

func (*InMemoryTable) Upsert

func (tbl *InMemoryTable) Upsert(entity Entity) (added Entity, err error)

Upsert inserts or updates an entity in the table.

type QueryFilter

type QueryFilter interface {

	// Eq adds an "Equal" condition.
	Eq(value any) QueryFilter

	// Neq adds a "Not Equal" condition.
	Neq(value any) QueryFilter

	// Like adds a "Like" condition (similar to SQL LIKE).
	Like(value string) QueryFilter

	// NotLike adds a "Not Like" condition.
	NotLike(value string) QueryFilter

	// Gt adds a "Greater Than" condition.
	Gt(value any) QueryFilter

	// Gte adds a "Greater Than or Equal" condition.
	Gte(value any) QueryFilter

	// Lt adds a "Less Than" condition.
	Lt(value any) QueryFilter

	// Lte adds a "Less Than or Equal" condition.
	Lte(value any) QueryFilter

	// In adds an "In" condition (match one of the values).
	In(values ...any) QueryFilter

	// NotIn adds a "Not In" condition.
	NotIn(values ...any) QueryFilter

	// InSubQuery adds a condition to match values in the result of a sub-query.
	InSubQuery(field string, subQuery IQuery) QueryFilter

	// NotInSubQuery adds a condition to exclude values in the result of a sub-query.
	NotInSubQuery(field string, subQuery IQuery) QueryFilter

	// Between adds a "Between" condition (inclusive).
	Between(value1, value2 any) QueryFilter

	// Contains adds a condition to check if an array field contains the value.
	Contains(value any) QueryFilter

	// NotContains adds a condition to check if an array field does not contain the value.
	NotContains(value any) QueryFilter

	// WithFlag adds a condition to check if an integer field has specific bit flags set.
	WithFlag(value int) QueryFilter

	// WithNoFlag adds a condition to check if an integer field does not have specific bit flags set.
	WithNoFlag(value int) QueryFilter

	// IsEmpty adds a condition to check if a field is null or empty.
	IsEmpty() QueryFilter

	// IsTrue adds a condition to check if a boolean field is true.
	IsTrue() QueryFilter

	// IsFalse adds a condition to check if a boolean field is false or null.
	IsFalse() QueryFilter

	// If enables or disables the filter based on the boolean condition.
	If(value bool) QueryFilter

	// IsActive returns true if the filter is active.
	IsActive() bool

	// GetField returns the field name being filtered.
	GetField() string

	// GetOperator returns the filter operator.
	GetOperator() QueryOperator

	// GetValues returns the filter values.
	GetValues() []any

	// GetStringValue returns the string representation of the value at the given index.
	GetStringValue(index int) string

	// GetSubQuery returns the underlying sub-query.
	GetSubQuery() IQuery

	// GetSubQueryField returns the field used in the sub-query.
	GetSubQueryField() string
}

QueryFilter defines the interface for building query filters. It allows for constructing complex conditions for database queries.

func F added in v1.2.13

func F(field string) QueryFilter

F is a shorthand alias for Filter.

func Filter

func Filter(field string) QueryFilter

Filter creates a new QueryFilter for the specified field.

type QueryOperator

type QueryOperator string

QueryOperator represents a database query operator (e.g., =, !=, >, <). It defines the type of comparison or operation to be performed in a query filter.

const (
	Eq          QueryOperator = "="  // Eq represents the Equal operator.
	Neq         QueryOperator = "!"  // Neq represents the Not Equal operator.
	Like        QueryOperator = "~"  // Like represents the Like operator (Regex or Wildcard).
	NotLike     QueryOperator = "!~" // NotLike represents the Not Like operator.
	Gt          QueryOperator = ">"  // Gt represents the Greater Than operator.
	Gte         QueryOperator = ">=" // Gte represents the Greater Than or Equal operator.
	Lt          QueryOperator = "<"  // Lt represents the Less Than operator.
	Lte         QueryOperator = "<=" // Lte represents the Less Than or Equal operator.
	In          QueryOperator = "*"  // In represents the In operator (match one of the values).
	NotIn       QueryOperator = "-"  // NotIn represents the Not In operator.
	InSQ        QueryOperator = "*s" // InSQ represents the In Sub Query operator.
	NotInSQ     QueryOperator = "-s" // NotInSQ represents the Not In Sub Query operator.
	Between     QueryOperator = "#"  // Between represents the Between operator (inclusive).
	Contains    QueryOperator = "@"  // Contains represents the Contains operator (for array fields).
	NotContains QueryOperator = "!@" // NotContains represents the Not Contains operator.
	Empty       QueryOperator = "^"  // Empty represents the Is Empty operator (null or empty).
	True        QueryOperator = "t"  // True represents the Is True operator.
	False       QueryOperator = "f"  // False represents the Is False operator.
	WithFlag    QueryOperator = "&"  // WithFlag represents the With Flag operator (bitwise AND).
	WithNoFlag  QueryOperator = "!&" // WithNoFlag represents the With No Flag operator.
)

Jump to

Keyboard shortcuts

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