database

package
v0.0.0-...-fcac5d6 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FILTER_FIELD_EMPTY                    = "FILTER_FIELD_EMPTY"
	FILTER_INVALID_DIRECTION              = "FILTER_INVALID_DIRECTION"
	FILTER_WHERE_EMPTY                    = "FILTER_WHERE_EMPTY"
	FILTER_CANNOT_MIX_INCLUSION_EXCLUSION = "FILTER_CANNOT_MIX_INCLUSION_EXCLUSION"
	FILTER_WHERE_CANNOT_BE_NIL            = "FILTER_WHERE_CANNOT_BE_NIL"
	FILTER_VALUE_CANNOT_BE_NIL            = "FILTER_VALUE_CANNOT_BE_NIL"
)
View Source
const (
	DtObjectID = "ObjectID"
	DtDate     = "Date"
)
View Source
const (
	INVALID_WHERE_PARAMETER     = "INVALID_WHERE_PARAMETER"
	INVALID_ORDER_PARAMETER     = "INVALID_ORDER_PARAMETER"
	WHERE_CLAUSE_NOT_ALLOWED    = "WHERE_CLAUSE_NOT_ALLOWED"
	INVALID_EXISTS_CONDITION    = "INVALID_EXISTS_CONDITION"
	INVALID_AND_OR_CONDITION    = "INVALID_AND_OR_CONDITION"
	INVALID_OBJECTID_COLLECTION = "INVALID_OBJECTID_COLLECTION"
	INVALID_OBJECTID            = "INVALID_OBJECTID"
	INVALID_DATE_COLLECTION     = "INVALID_DATE_COLLECTION"
	INVALID_DATE                = "INVALID_DATE"
	INVALID_DATE_FORMAT         = "INVALID_DATE_FORMAT"
)

Error codes for lb_filter_utils

View Source
const (
	ID             = "id"
	SET            = "$set"
	AND            = "$and"
	CREATED        = "created"
	MODIFIED       = "modified"
	DELETED        = "deleted"
	CURRENT_DATE   = "$currentDate"
	SET_ON_INSERT  = "$setOnInsert"
	TYPE           = "$type"
	COMMAND_PREFIX = "$"
	NO_DOCUMENTS   = "no documents founds"
	MIXED_UPDATE   = "the update has a mix between fields and commands"
)
View Source
const (
	MONGO_CONNECTOR_TYPE_MISMATCH = "MONGO_CONNECTOR_TYPE_MISMATCH"
	MONGO_CONNECTOR_NIL           = "MONGO_CONNECTOR_NIL"
	MONGO_CLIENT_NOT_INITIALIZED  = "MONGO_CLIENT_NOT_INITIALIZED"
	MONGO_DATABASE_NAME_REQUIRED  = "MONGO_DATABASE_NAME_REQUIRED"
	MONGO_ID_CANNOT_BE_NIL        = "MONGO_ID_CANNOT_BE_NIL"
	MONGO_UPDATE_CANNOT_BE_NIL    = "MONGO_UPDATE_CANNOT_BE_NIL"
	MONGO_NO_DOCUMENTS_FOUND      = "MONGO_NO_DOCUMENTS_FOUND"
	MONGO_DUPLICATE_KEY           = "MONGO_DUPLICATE_KEY"
	MONGO_OPERATION_FAILED        = "MONGO_OPERATION_FAILED"
	MONGO_CONNECTION_ERROR        = "MONGO_CONNECTION_ERROR"
	MONGO_VALIDATION_ERROR        = "MONGO_VALIDATION_ERROR"
	MONGO_TIMEOUT_ERROR           = "MONGO_TIMEOUT_ERROR"
)

Error codes for mongo_repository

Variables

View Source
var Operators = map[string]string{
	"eq":     "$eq",
	"neq":    "$ne",
	"gt":     "$gt",
	"gte":    "$gte",
	"lt":     "$lt",
	"lte":    "$lte",
	"inq":    "$in",
	"nin":    "$nin",
	"and":    "$and",
	"or":     "$or",
	"exists": "$exists",
}

Functions

func RegisterDatasourceRepository

func RegisterDatasourceRepository[T IModel](ds *Datasource, model T, repository Repository[T]) error

Types

type BeforeCreateHook

type BeforeCreateHook interface {
	BeforeCreate() error
}

type BeforeDeleteHook

type BeforeDeleteHook interface {
	BeforeDelete() error
}

type BeforeUpdateHook

type BeforeUpdateHook interface {
	BeforeUpdate() error
}

type Connector

type Connector interface {
	Ping() error
	Disconnect() error
	GetName() string
	GetDatabaseName() string
	GetDriver() any
}

Connector es una interfaz genérica para cualquier tipo de conector de base de datos

type Datasource

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

func (*Datasource) AddConnector

func (receiver *Datasource) AddConnector(connector Connector) error

func (*Datasource) Destroy

func (receiver *Datasource) Destroy()

func (*Datasource) EnsureIndexes

func (receiver *Datasource) EnsureIndexes() error

*

  • EnsureIndexes ensures that all indexes defined in registered models are created.
  • This method should be called after all models are registered.
  • It will delegate to the appropriate IndexManager for each connector type.

func (*Datasource) EnsureIndexesForModel

func (receiver *Datasource) EnsureIndexesForModel(model IModel) error

*

  • EnsureIndexesForModel ensures indexes for a specific model.
  • This is useful when you want to ensure indexes for a single model
  • instead of all registered models.

func (*Datasource) GetConnector

func (receiver *Datasource) GetConnector(name string) (Connector, error)

func (*Datasource) GetModel

func (receiver *Datasource) GetModel(modelName string) (IModel, error)

func (*Datasource) GetModelConnector

func (receiver *Datasource) GetModelConnector(model IModel) (Connector, error)

func (*Datasource) RegisterModel

func (receiver *Datasource) RegisterModel(model IModel) error

type Field

type Field struct {
	FieldName         string
	BsonName          string
	JsonName          string
	DataType          string
	IsPointer         bool
	FieldType         reflect.Type
	IndirectFieldType reflect.Type
	StructField       reflect.StructField
	Tag               reflect.StructTag
	FilterTags        FilterTags
}

type FieldDetails

type FieldDetails struct {
	BsonName  string
	JsonName  string
	FieldType string
}

type FieldTags

type FieldTags struct {
	Name      string
	OmitEmpty bool
	MinSize   bool
	Truncate  bool
	Inline    bool
	Skip      bool
	Required  bool
}

type FieldsOptions

type FieldsOptions string
const (
	FieldsAlways FieldsOptions = "always" // Always include the field
	FieldsNever  FieldsOptions = "never"  // Never include the field
)

type FilterBuilder

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

func NewFilter

func NewFilter() *FilterBuilder

func (*FilterBuilder) Build

func (b *FilterBuilder) Build() (*lbq.Filter, error)

func (*FilterBuilder) Clone

func (b *FilterBuilder) Clone() *FilterBuilder

func (*FilterBuilder) Fields

func (b *FilterBuilder) Fields(fields map[string]bool) *FilterBuilder

func (*FilterBuilder) FromLBFilter

func (b *FilterBuilder) FromLBFilter(filter *lbq.Filter) *FilterBuilder

func (*FilterBuilder) Include

func (b *FilterBuilder) Include(relation string, scope *lbq.Filter) *FilterBuilder

func (*FilterBuilder) Limit

func (b *FilterBuilder) Limit(limit uint) *FilterBuilder

func (*FilterBuilder) MergeWith

func (b *FilterBuilder) MergeWith(other *FilterBuilder, config ...*MergeConfig) *FilterBuilder

MergeWith combines this FilterBuilder with another FilterBuilder Returns a new FilterBuilder with merged conditions

func (*FilterBuilder) OrderByAsc

func (b *FilterBuilder) OrderByAsc(field string) *FilterBuilder

func (*FilterBuilder) OrderByDesc

func (b *FilterBuilder) OrderByDesc(field string) *FilterBuilder

func (*FilterBuilder) Page

func (b *FilterBuilder) Page(page, size uint) *FilterBuilder

func (*FilterBuilder) Reset

func (b *FilterBuilder) Reset() *FilterBuilder

func (*FilterBuilder) Skip

func (b *FilterBuilder) Skip(skip uint) *FilterBuilder

func (*FilterBuilder) ToJSON

func (f *FilterBuilder) ToJSON() (string, error)

func (*FilterBuilder) WithWhere

func (f *FilterBuilder) WithWhere(builder *WhereBuilder) *FilterBuilder

type FilterTags

type FilterTags struct {
	Fields FieldsOptions
}

type IModel

type IModel interface {
	GetTableName() string
	GetModelName() string
	GetConnectorName() string
	GetId() any
}

type IRelation

type IRelation interface {
	ResolveForMany(ctx context.Context, ds *Datasource, docs []IModel) (any, error) // Resolve the relation for multiple documents
	ResolveForOne(ctx context.Context, ds *Datasource, doc IModel) (any, error)     // Resolve the relation for a single document
	Set(value any) error                                                            // Set the value of the relation
	// contains filtered or unexported methods
}

type IRelationalModel

type IRelationalModel interface {
	Relations() map[string]ModelRelation
}

type IndexDefinition

type IndexDefinition struct {
	Name   string       // Index name
	Fields []IndexField // Fields that compose the index
	Unique bool         // Whether the index is unique
}

IndexDefinition is a generic, database-agnostic representation of an index

type IndexField

type IndexField struct {
	Name  string // Field name
	Order int    // 1 for ascending, -1 for descending
}

IndexField represents a field in an index

type IndexManager

type IndexManager interface {
	// EnsureIndexes creates the indexes for a given model
	EnsureIndexes(model IModel) error

	// ListIndexes returns all indexes for a given model's collection/table
	ListIndexes(model IModel) ([]string, error)

	// CompareIndexes compares defined indexes vs existing ones and returns warnings
	CompareIndexes(model IModel) ([]IndexWarning, error)
}

IndexManager is a generic interface for managing database indexes

type IndexWarning

type IndexWarning struct {
	Type    IndexWarningType
	Message string
	Details map[string]interface{}
}

IndexWarning represents a discrepancy between defined and actual indexes

type IndexWarningType

type IndexWarningType string
const (
	IndexWarningMissingInCode IndexWarningType = "missing_in_code" // Index exists in DB but not in code
	IndexWarningMissingInDB   IndexWarningType = "missing_in_db"   // Index defined in code but not in DB
	IndexWarningDifferent     IndexWarningType = "different"       // Index exists in both but with different options
)

type MergeConfig

type MergeConfig struct {
	// WhereOperator defines how to combine WHERE conditions: "and" (default) or "or"
	WhereOperator string
	// AllowFieldConflicts allows the other FilterBuilder to overwrite field projections
	AllowFieldConflicts bool
	// MaxLimit sets a maximum value for the limit when merging
	MaxLimit *uint
}

MergeConfig defines options for merging FilterBuilders

type ModelRelation

type ModelRelation struct {
	Name   string `json:"name"`
	IsList bool   `json:"isList"`

	Resolve func(ctx context.Context, ds *Datasource) (any, error)
	Set     func(value any) error
}

type MongoCollation

type MongoCollation struct {
	Locale          string
	CaseLevel       bool
	CaseFirst       string
	Strength        int
	NumericOrdering bool
	Alternate       string
	MaxVariable     string
	Backwards       bool
}

MongoCollation represents collation options for MongoDB

type MongoConnector

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

func NewDefaultMongoConnector

func NewDefaultMongoConnector() (*MongoConnector, error)

func NewMongoConnector

func NewMongoConnector(opts *MongoConnectorOpts) (*MongoConnector, error)

*

  • NewMongoConnector creates a new MongoDB connector.
  • It initializes the MongoDB client with the provided options and checks the connection.

func (*MongoConnector) Disconnect

func (receiver *MongoConnector) Disconnect() error

*

  • Disconnect closes the connection to the MongoDB server.

func (*MongoConnector) GetDatabaseName

func (receiver *MongoConnector) GetDatabaseName() string

func (*MongoConnector) GetDriver

func (receiver *MongoConnector) GetDriver() any

*

  • GetDriver returns the underlying MongoDB client.

func (*MongoConnector) GetIndexManager

func (receiver *MongoConnector) GetIndexManager() *MongoIndexManager

*

  • GetIndexManager returns the index manager for this connector.

func (*MongoConnector) GetName

func (receiver *MongoConnector) GetName() string

func (*MongoConnector) GetOptions

func (receiver *MongoConnector) GetOptions() MongoConnectorOpts

*

  • GetOptions returns the options used to create the MongoDB connector.

func (*MongoConnector) Ping

func (receiver *MongoConnector) Ping() error

*

  • Ping checks the connection to the MongoDB server.

type MongoConnectorOpts

type MongoConnectorOpts struct {
	options.ClientOptions
	Name     string
	Database string
}

type MongoDate

type MongoDate struct {
	time.Time
}

func (MongoDate) MarshalBSONValue

func (date MongoDate) MarshalBSONValue() (bson.Type, []byte, error)

func (*MongoDate) MarshalJSON

func (date *MongoDate) MarshalJSON() ([]byte, error)

func (*MongoDate) UnmarshalBSONValue

func (date *MongoDate) UnmarshalBSONValue(t bson.Type, data []byte) error

type MongoFilter

type MongoFilter struct {
	Where   bson.M
	Options MongoFilterOptions
	Include []MongoIncludes
}

type MongoFilterOptions

type MongoFilterOptions struct {
	Limit  *uint
	Skip   *uint
	Sort   any
	Fields map[string]bool
}

type MongoIncludes

type MongoIncludes struct {
	Relation string
	Scope    lbq.Filter
}

type MongoIndexDefinition

type MongoIndexDefinition struct {
	IndexDefinition

	// MongoDB-specific options
	Background         bool             // Create index in background
	Sparse             bool             // Only index documents that have the indexed field
	ExpireAfterSeconds *int32           // TTL in seconds (for TTL indexes)
	Unique             bool             // Enforce uniqueness
	PartialFilter      map[string]any   // Partial filter expression
	Collation          *MongoCollation  // Collation options
	Weights            map[string]int32 // Text search weights (for text indexes)
	DefaultLanguage    string           // Default language for text indexes
	LanguageOverride   string           // Field name containing language override
	TextVersion        *int32           // Text index version
	SphereVersion      *int32           // 2dsphere index version
	Bits               *int32           // Precision for geohash (for 2d indexes)
	Max                *float64         // Max boundary for 2d indexes
	Min                *float64         // Min boundary for 2d indexes
	BucketSize         *int32           // Bucket size for geoHaystack indexes
	StorageEngine      map[string]any   // Storage engine options
	Hidden             bool             // Hide index from query planner
	WildcardProjection map[string]any   // Wildcard index projection
}

MongoIndexDefinition represents a MongoDB index with all possible options

func NewMongo2DSphereIndex

func NewMongo2DSphereIndex(fieldName string) MongoIndexDefinition

NewMongo2DSphereIndex creates a 2dsphere geospatial index

func NewMongoCompoundIndex

func NewMongoCompoundIndex(name string, fields []IndexField, unique bool) MongoIndexDefinition

NewMongoCompoundIndex creates a compound index on multiple fields

func NewMongoCompoundTTLIndex

func NewMongoCompoundTTLIndex(name string, fields []IndexField, expireAfter time.Duration) MongoIndexDefinition

NewMongoCompoundTTLIndex creates a compound TTL index The first field MUST be a date field for TTL to work properly Additional fields can be used for better query performance

func NewMongoHashedIndex

func NewMongoHashedIndex(fieldName string) MongoIndexDefinition

NewMongoHashedIndex creates a hashed index

func NewMongoSimpleIndex

func NewMongoSimpleIndex(fieldName string, unique bool) MongoIndexDefinition

NewMongoSimpleIndex creates a simple ascending index on a single field

func NewMongoTTLIndex

func NewMongoTTLIndex(fieldName string, expireAfter time.Duration) MongoIndexDefinition

NewMongoTTLIndex creates a simple TTL (Time To Live) index on a single date field Note: TTL indexes in MongoDB must include a date field, but can be compound indexes

func NewMongoTextIndex

func NewMongoTextIndex(name string, fields []string) MongoIndexDefinition

NewMongoTextIndex creates a full-text search index

func (MongoIndexDefinition) WithBackground

func (idx MongoIndexDefinition) WithBackground(background bool) MongoIndexDefinition

WithBackground sets the background option

func (MongoIndexDefinition) WithCollation

func (idx MongoIndexDefinition) WithCollation(collation *MongoCollation) MongoIndexDefinition

WithCollation sets collation options for the index

func (MongoIndexDefinition) WithDefaultLanguage

func (idx MongoIndexDefinition) WithDefaultLanguage(language string) MongoIndexDefinition

WithDefaultLanguage sets the default language for text indexes

func (MongoIndexDefinition) WithHidden

func (idx MongoIndexDefinition) WithHidden(hidden bool) MongoIndexDefinition

WithHidden sets the hidden option

func (MongoIndexDefinition) WithPartialFilter

func (idx MongoIndexDefinition) WithPartialFilter(filter map[string]any) MongoIndexDefinition

WithPartialFilter sets a partial filter expression

func (MongoIndexDefinition) WithSparse

func (idx MongoIndexDefinition) WithSparse(sparse bool) MongoIndexDefinition

WithSparse sets the sparse option

func (MongoIndexDefinition) WithStorageEngine

func (idx MongoIndexDefinition) WithStorageEngine(options map[string]any) MongoIndexDefinition

WithStorageEngine sets storage engine specific options

func (MongoIndexDefinition) WithTTL

func (idx MongoIndexDefinition) WithTTL(expireAfter time.Duration) MongoIndexDefinition

WithTTL sets the TTL (Time To Live) for the index The index must include a date field for TTL to work

func (MongoIndexDefinition) WithWeights

func (idx MongoIndexDefinition) WithWeights(weights map[string]int32) MongoIndexDefinition

WithWeights sets text search weights

func (MongoIndexDefinition) WithWildcardProjection

func (idx MongoIndexDefinition) WithWildcardProjection(projection map[string]any) MongoIndexDefinition

WithWildcardProjection sets the wildcard projection for wildcard indexes

type MongoIndexManager

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

MongoIndexManager manages indexes for MongoDB collections

func NewMongoIndexManager

func NewMongoIndexManager(connector *MongoConnector) *MongoIndexManager

NewMongoIndexManager creates a new MongoDB index manager

func (*MongoIndexManager) CompareIndexes

func (m *MongoIndexManager) CompareIndexes(model IModel) ([]IndexWarning, error)

CompareIndexes compares defined indexes with existing ones

func (*MongoIndexManager) EnsureIndexes

func (m *MongoIndexManager) EnsureIndexes(model IModel) error

EnsureIndexes creates the indexes defined in the model

func (*MongoIndexManager) ListIndexes

func (m *MongoIndexManager) ListIndexes(model IModel) ([]string, error)

ListIndexes returns all index names for a model's collection

type MongoIndexType

type MongoIndexType string

MongoIndexType represents special MongoDB index types

const (
	MongoIndexTypeText     MongoIndexType = "text"     // Full text search
	MongoIndexType2D       MongoIndexType = "2d"       // 2D geospatial
	MongoIndexType2DSphere MongoIndexType = "2dsphere" // 2D sphere geospatial
	MongoIndexTypeHashed   MongoIndexType = "hashed"   // Hashed index
	MongoIndexTypeWildcard MongoIndexType = "wildcard" // Wildcard index
)

type MongoIndexableModel

type MongoIndexableModel interface {
	DefineMongoIndexes() []MongoIndexDefinition
}

MongoIndexableModel defines models that can specify MongoDB indexes

type MongoRepository

type MongoRepository[T IModel] struct {
	Options RepositoryOptions
	// contains filtered or unexported fields
}

func (*MongoRepository[T]) Count

func (repository *MongoRepository[T]) Count(ctx context.Context, filterBuilder *FilterBuilder) (int64, error)

func (*MongoRepository[T]) Create

func (repository *MongoRepository[T]) Create(ctx context.Context, doc T) (*T, error)

func (*MongoRepository[T]) DeleteById

func (repository *MongoRepository[T]) DeleteById(ctx context.Context, id any) error

func (*MongoRepository[T]) DeleteMany

func (repository *MongoRepository[T]) DeleteMany(ctx context.Context, filterBuilder *FilterBuilder) (int64, error)

func (*MongoRepository[T]) DeleteOne

func (repository *MongoRepository[T]) DeleteOne(ctx context.Context, filterBuilder *FilterBuilder) error

func (*MongoRepository[T]) Exists

func (repository *MongoRepository[T]) Exists(ctx context.Context, id any) (bool, error)

func (*MongoRepository[T]) Find

func (repository *MongoRepository[T]) Find(ctx context.Context, filterBuilder *FilterBuilder) ([]T, error)

func (*MongoRepository[T]) FindById

func (repository *MongoRepository[T]) FindById(ctx context.Context, id any, filterBuilder *FilterBuilder) (*T, error)

func (*MongoRepository[T]) FindOne

func (repository *MongoRepository[T]) FindOne(ctx context.Context, filterBuilder *FilterBuilder) (*T, error)

func (*MongoRepository[T]) FindOneAndUpdate

func (repository *MongoRepository[T]) FindOneAndUpdate(ctx context.Context, filterBuilder *FilterBuilder, update any) (*T, error)

func (*MongoRepository[T]) FindOneOrCreate

func (repository *MongoRepository[T]) FindOneOrCreate(ctx context.Context, filterBuilder *FilterBuilder, doc T) (*T, error)

func (*MongoRepository[T]) GetCollection

func (repository *MongoRepository[T]) GetCollection() *mongo.Collection

func (*MongoRepository[T]) GetConnector

func (repository *MongoRepository[T]) GetConnector() Connector

func (*MongoRepository[T]) GetSchema

func (repository *MongoRepository[T]) GetSchema() *Schema

func (*MongoRepository[T]) Insert

func (repository *MongoRepository[T]) Insert(ctx context.Context, doc T) (any, error)

func (*MongoRepository[T]) UpdateById

func (repository *MongoRepository[T]) UpdateById(ctx context.Context, id any, update any) error

func (*MongoRepository[T]) UpdateMany

func (repository *MongoRepository[T]) UpdateMany(ctx context.Context, filterBuilder *FilterBuilder, update any) (int64, error)

func (*MongoRepository[T]) UpdateOne

func (repository *MongoRepository[T]) UpdateOne(ctx context.Context, filterBuilder *FilterBuilder, update any) error

func (*MongoRepository[T]) Upsert

func (repository *MongoRepository[T]) Upsert(ctx context.Context, filterBuilder *FilterBuilder, update any) error

type MongoUpdate

type MongoUpdate struct {
	CurrentDate any `bson:"$currentDate,omitempty"`
	Inc         any `bson:"$inc,omitempty"`
	Min         any `bson:"$min,omitempty"`
	Max         any `bson:"$max,omitempty"`
	Mul         any `bson:"$mul,omitempty"`
	Rename      any `bson:"$rename,omitempty"`
	Set         any `bson:"$set,omitempty"`
	SetOnInsert any `bson:"$setOnInsert,omitempty"`
	Unset       any `bson:"$unset,omitempty"`
	AddToSet    any `bson:"$addToSet,omitempty"`
	Pop         any `bson:"$pop,omitempty"`
	Pull        any `bson:"$pull,omitempty"`
	PullAll     any `bson:"$pullAll,omitempty"`
	Push        any `bson:"$push,omitempty"`
}

type PostgresIndexDefinition

type PostgresIndexDefinition struct {
	IndexDefinition
}

PostgresIndexDefinition placeholder for future Postgres support

type PostgresIndexableModel

type PostgresIndexableModel interface {
	DefinePostgresIndexes() []PostgresIndexDefinition
}

PostgresIndexableModel defines models that can specify Postgres indexes (future)

type Relation

type Relation struct {
	FieldName    string
	JsonName     string
	RelationType RelationType
	TargetModel  IModel
}

type RelationHasOne

type RelationHasOne struct {
	Model       IModel   // Model for the relation
	Key         []string // Keys for the relation, e.g. ["userId", "userType"]
	TargetModel IModel   // Target model for the relation
	ForeignKey  []string // Keys in the target model that point to the source model, e.g. ["id", "type"]
	Set         func(any) error
}

type RelationType

type RelationType string
const (
	RelationTypeHasOne    RelationType = "hasOne"
	RelationTypeHasMany   RelationType = "hasMany"
	RelationTypeBelongsTo RelationType = "belongsTo"
)

type Repository

type Repository[T IModel] interface {
	// GetSchema returns the schema of the model used by this repository.
	GetSchema() *Schema

	// GetConnector returns the connector used by this repository.
	// This is useful for accessing the underlying database connection.
	// It is typically used for advanced operations that are not covered by the repository methods.
	GetConnector() Connector

	// Find retrieves all documents matching the filter.
	// If no documents match, it returns an empty slice.
	// If an error occurs, it returns an error.
	Find(ctx context.Context, filter *FilterBuilder) ([]T, error)

	// FindOne retrieves a single document matching the filter.
	// If multiple documents match, it returns the first one found.
	// If no documents match, it returns an error.
	FindOne(ctx context.Context, filter *FilterBuilder) (*T, error)

	// FindById retrieves a single document by its ID.
	// If the document does not exist, it returns an error.
	FindById(ctx context.Context, id any, filter *FilterBuilder) (*T, error)

	// Insert inserts a new document into the collection.
	// It returns the inserted document's ID or an error if the operation fails.
	Insert(ctx context.Context, doc T) (any, error)

	// Create inserts a new document into the collection and returns the created document.
	Create(ctx context.Context, doc T) (*T, error)

	// FindOneOrCreate finds a document matching the filter or creates a new one if it does not exist.
	FindOneOrCreate(ctx context.Context, filter *FilterBuilder, doc T) (*T, error)

	// Upsert updates a document matching the filter or inserts a new one if it does not exist.
	Upsert(ctx context.Context, filter *FilterBuilder, update any) error

	// UpdateOne updates a single document matching the filter.
	UpdateOne(ctx context.Context, filter *FilterBuilder, update any) error

	// UpdateById updates a single document by its ID.
	UpdateById(ctx context.Context, id any, update any) error

	// FindOneAndUpdate finds a single document matching the filter and updates it.
	FindOneAndUpdate(ctx context.Context, filter *FilterBuilder, update any) (*T, error)

	// UpdateMany updates all documents matching the filter.
	UpdateMany(ctx context.Context, filter *FilterBuilder, update any) (int64, error)

	// Count returns the number of documents matching the filter.
	Count(ctx context.Context, filter *FilterBuilder) (int64, error)

	// Exists checks if a document with the given ID exists in the collection.
	Exists(ctx context.Context, id any) (bool, error)

	// DeleteOne deletes a single document matching the filter.
	DeleteOne(ctx context.Context, filter *FilterBuilder) error

	// DeleteById deletes a single document by its ID.
	DeleteById(ctx context.Context, id any) error

	// DeleteMany deletes all documents matching the filter.
	DeleteMany(ctx context.Context, filter *FilterBuilder) (int64, error)
}

func GetDatasourceModelRepository

func GetDatasourceModelRepository[T IModel](datasource *Datasource, model T) (Repository[T], error)

func NewMongoRepository

func NewMongoRepository[T IModel](ds *Datasource, options RepositoryOptions) (Repository[T], error)

type RepositoryOptions

type RepositoryOptions struct {
	Created        bool
	Modified       bool
	Deleted        bool
	RequiredFields []string
}

type Schema

type Schema struct {
	Model                IModel
	Name                 string
	CollectionName       string
	JSONFields           map[string]*Field
	Fields               map[string]*Field
	RequiredFilterFields map[string]*Field
	BannedFields         map[string]*Field
	// Relations            []Relation
	ReflectValue reflect.Value
}

func NewSchema

func NewSchema(model IModel) *Schema

func (*Schema) AddField

func (s *Schema) AddField(field *Field, topLevelField bool)

func (*Schema) InitField

func (s *Schema) InitField(model *reflect.Value, fieldStruct reflect.StructField, jsonParentField string, bsonParentField string) error

func (*Schema) InitFields

func (s *Schema) InitFields(val *reflect.Value, jsonParentField string, bsonParentField string)

func (*Schema) InitRelations

func (s *Schema) InitRelations(val *reflect.Value) error

type TargetModel

type TargetModel struct {
	Name           string
	CollectionName string
}

type UpdateOptions

type UpdateOptions struct {
	Insert bool
	Update bool
}

type WhereBuilder

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

func NewWhere

func NewWhere() *WhereBuilder

func (*WhereBuilder) And

func (b *WhereBuilder) And(builders ...*WhereBuilder) *WhereBuilder

func (*WhereBuilder) Between

func (b *WhereBuilder) Between(field string, min any, max any, exclusive bool) *WhereBuilder

func (*WhereBuilder) Build

func (b *WhereBuilder) Build() (lbq.Where, error)

func (*WhereBuilder) Eq

func (b *WhereBuilder) Eq(field string, value any, strict ...bool) *WhereBuilder

func (*WhereBuilder) Gt

func (b *WhereBuilder) Gt(field string, value any) *WhereBuilder

func (*WhereBuilder) Gte

func (b *WhereBuilder) Gte(field string, value any) *WhereBuilder

func (*WhereBuilder) In

func (b *WhereBuilder) In(field string, values any) *WhereBuilder

func (*WhereBuilder) IsNotNull

func (b *WhereBuilder) IsNotNull(field string) *WhereBuilder

func (*WhereBuilder) IsNull

func (b *WhereBuilder) IsNull(field string) *WhereBuilder

func (*WhereBuilder) Like

func (b *WhereBuilder) Like(field string, pattern string, options ...string) *WhereBuilder

func (*WhereBuilder) Lt

func (b *WhereBuilder) Lt(field string, value any) *WhereBuilder

func (*WhereBuilder) Lte

func (b *WhereBuilder) Lte(field string, value any) *WhereBuilder

func (*WhereBuilder) Neq

func (b *WhereBuilder) Neq(field string, value any) *WhereBuilder

func (*WhereBuilder) Nin

func (b *WhereBuilder) Nin(field string, values any) *WhereBuilder

func (*WhereBuilder) Or

func (b *WhereBuilder) Or(builders ...*WhereBuilder) *WhereBuilder

func (*WhereBuilder) Raw

func (b *WhereBuilder) Raw(w lbq.Where) *WhereBuilder

Jump to

Keyboard shortcuts

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