Documentation
¶
Index ¶
- Constants
- func ArrayRemove(elements ...interface{}) interface{}
- func ArrayUnion(elements ...interface{}) interface{}
- func Increment(n interface{}) interface{}
- type CollectionRef
- func (c *CollectionRef[T]) Count(ctx context.Context, query Query) (int64, error)
- func (c *CollectionRef[T]) Create(ctx context.Context, data *T, opts ...Options) (string, error)
- func (c *CollectionRef[T]) Delete(ctx context.Context, query Query, opts ...Options) error
- func (c *CollectionRef[T]) Find(ctx context.Context, query Query, opts ...Options) ([]Document[T], error)
- func (c *CollectionRef[T]) FindOne(ctx context.Context, query Query, opts ...Options) (Document[T], error)
- func (c *CollectionRef[T]) Update(ctx context.Context, query Query, data *T, opts ...Options) error
- func (c *CollectionRef[T]) Validate(ctx context.Context, data *T, opts ...Options) error
- type Connection
- func (c *Connection) Close() error
- func (c *Connection) RegisterErrorFormatter(errorFormatter ErrorFormatterFunc) error
- func (c *Connection) RegisterTransformation(name string, transformation Transformation, runOnNil ...bool) error
- func (c *Connection) RegisterValidation(name string, validation Validation, runOnNil ...bool) error
- func (c *Connection) RunTransaction(ctx context.Context, fn func(ctx context.Context, tx *Transaction) error) error
- type Direction
- type Document
- type ErrorFormatterFunc
- type FieldError
- type FieldScope
- type Options
- func (o Options) AllowEmptyFields(fields ...string) Options
- func (o Options) AsCreate() Options
- func (o Options) AsUpdate() Options
- func (o Options) CustomID(id string) Options
- func (o Options) ModifyOriginal() Options
- func (o Options) ReplaceAll() Options
- func (o Options) ReplaceFields(fields ...string) Options
- func (o Options) RequireExists() Options
- func (o Options) RequireLastUpdateTime(t time.Time) Options
- func (o Options) SkipValidationFields(fields ...string) Options
- func (o Options) SkipValidationRules(rules ...string) Options
- func (o Options) Transaction(tx *Transaction) Options
- type Query
- func (q Query) EndAt(values ...interface{}) Query
- func (q Query) EndBefore(values ...interface{}) Query
- func (q Query) ID(ids ...string) Query
- func (q Query) Limit(num int) Query
- func (q Query) LimitToLast(num int) Query
- func (q Query) Offset(num int) Query
- func (q Query) OrderBy(path string, direction Direction) Query
- func (q Query) StartAfter(values ...interface{}) Query
- func (q Query) StartAt(values ...interface{}) Query
- func (q Query) Where(path string, operator string, value interface{}) Query
- type Transaction
- type Transformation
- type TransformationFunc
- type TransformationFuncCtx
- type TransformationFuncCtxTx
- type TransformationFuncTx
- type Validation
- type ValidationFunc
- type ValidationFuncCtx
- type ValidationFuncCtxTx
- type ValidationFuncTx
Constants ¶
const Delete = firestore.Delete
Delete is used as a value in a call to Update to indicate that the corresponding key should be deleted.
const DocumentID = firestore.DocumentID
DocumentID is the special field name representing the ID of a document in queries.
const ServerTimestamp = firestore.ServerTimestamp
ServerTimestamp is used as a value in a call to Update to indicate that the key's value should be set to the time at which the server processed the request.
ServerTimestamp must be the value of a field directly; it cannot appear in array or struct values, or in any value that is itself inside an array or struct.
Variables ¶
This section is empty.
Functions ¶
func ArrayRemove ¶ added in v0.7.5
func ArrayRemove(elements ...interface{}) interface{}
ArrayRemove specifies elements to be removed from whatever array already exists.
If a value exists and it's an array, values are removed from it. All duplicate values are removed. If a value exists and it's not an array, the value is replaced by an empty array. If a value does not exist, an empty array is created.
ArrayRemove must be the value of a field directly; it cannot appear in array or struct values, or in any value that is itself inside an array or struct.
func ArrayUnion ¶ added in v0.7.5
func ArrayUnion(elements ...interface{}) interface{}
ArrayUnion specifies elements to be added to whatever array already exists, or to create an array if no value exists.
If a value exists and it's an array, values are appended to it. Any duplicate value is ignored. If a value exists and it's not an array, the value is replaced by an array of the values in the ArrayUnion. If a value does not exist, an array of the values in the ArrayUnion is created.
ArrayUnion must be the value of a field directly; it cannot appear in array or struct values, or in any value that is itself inside an array or struct.
func Increment ¶ added in v0.7.5
func Increment(n interface{}) interface{}
Increment returns a value that can be used in Update operations to increment a numeric value atomically.
If the field does not yet exist, the transformation will set the field to the given value.
The supported values are:
int, int8, int16, int32, int64 uint8, uint16, uint32 float32, float64
Types ¶
type CollectionRef ¶
type CollectionRef[T interface{}] struct {
// contains filtered or unexported fields
}
CollectionRef holds a reference to a Firestore Collection and allows for the fetching and modifying (with validation) of documents in it.
CollectionRef instances are lightweight and safe to create repeatedly. They can be freely used as needed, without concern for maintaining a singleton instance, as each instance independently references the specified Firestore collection.
func Collection ¶
func Collection[T interface{}](connection *Connection, path string) *CollectionRef[T]
Create a new CollectionRef instance.
CollectionRef holds a reference to a Firestore Collection and allows for the fetching and modifying (with validation) of documents in it.
CollectionRef instances are lightweight and safe to create repeatedly. They can be freely used as needed, without concern for maintaining a singleton instance, as each instance independently references the specified Firestore collection.
The path argument is a sequence of IDs, separated by slashes.
Returns nil if path contains an even number of IDs, or any ID is empty.
func (*CollectionRef[T]) Create ¶
Create a Firestore document with provided data (after validation).
By default, Firestore generates a unique document ID. Use Options to change this behaviour.
An error is returned if a document with the same ID already exists, whether auto-generated (unlikely), or provided.
To use inside a transaction, pass a transaction instance via Options.
func (*CollectionRef[T]) Delete ¶
Delete all Firestore documents which match provided Query.
If the Query doesn't contain an ID clause, documents are read first to retrieve their IDs. If no documents match, the operation does nothing and returns no error.
If the Query does contain an ID clause, the operation skips any ID that does not correspond to an existing document, without returning an error. Deletes to matching documents are applied.
In the event a precondition is set, the operation fails for any matching document that does not meet the precondition, returning an error. Other deletes are still processed.
The operation is not atomic, unless used inside a transaction via Options.
Note: In a transaction with no ID clause, document IDs are read first, which prevents any prior writes or subsequent reads in the same transaction. To work around this, use the Find/FindOne method before calling Delete.
func (*CollectionRef[T]) Find ¶
func (c *CollectionRef[T]) Find(ctx context.Context, query Query, opts ...Options) ([]Document[T], error)
Find all Firestore documents which match provided Query.
To use inside a transaction, pass a transaction instance via Options.
func (*CollectionRef[T]) FindOne ¶
func (c *CollectionRef[T]) FindOne(ctx context.Context, query Query, opts ...Options) (Document[T], error)
Find the first Firestore document which matches provided Query.
Returns an empty Document[T] (empty ID string and zero-value T Data), and no error if no documents are found.
To use inside a transaction, pass a transaction instance via Options.
func (*CollectionRef[T]) Update ¶
Update all Firestore documents which match provided Query (after data validation).
By default, data fields are merged, preserving existing document fields. Use Options to change this behaviour.
If the Query doesn't contain an ID clause, documents are read first to retrieve their IDs. If no documents match, the operation does nothing and returns no error.
If the Query does contain an ID clause, the operation fails for any ID not corresponding to an existing document, returning an error. Updates to matching documents are applied.
In the event a precondition is set, the operation fails for any matching document that does not meet the precondition, returning an error. Other updates are still processed.
The operation is not atomic, unless used inside a transaction via Options.
Note: In a transaction with no ID clause, document IDs are read first, which prevents any prior writes or subsequent reads in the same transaction. To work around this, use the Find/FindOne method before calling Update.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection provides access to Firevault services.
It is designed to be thread-safe and used as a singleton instance.
A cache is used under the hood to store struct validation metadata, parsing validation tags once per struct type. Using multiple instances defeats the purpose of caching.
func Connect ¶
func Connect(ctx context.Context, projectID string) (*Connection, error)
Create a new Connection instance.
Connection provides access to Firevault services.
It is designed to be thread-safe and used as a singleton instance.
A cache is used under the hood to store struct validation metadata, parsing validation tags once per struct type. Using multiple instances defeats the purpose of caching.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close closes the connection to Firevault.
Should be invoked when the connection is no longer required.
Close need not be called at program exit.
func (*Connection) RegisterErrorFormatter ¶ added in v0.6.2
func (c *Connection) RegisterErrorFormatter(errorFormatter ErrorFormatterFunc) error
Register a new error formatter.
Error formatters are used to generate a custom, user-friendly error message, whenever a FieldError is created (during a failed validation).
If none are registered, or if a formatter returns a nil error, an instance of a FieldError will be returned instead.
Registering error formatters is not thread-safe; it is intended that all such functions be registered, prior to any validation.
func (*Connection) RegisterTransformation ¶
func (c *Connection) RegisterTransformation( name string, transformation Transformation, runOnNil ...bool, ) error
Register a new transformation rule.
If a transformation rule with the same name already exists, the previous one will be replaced.
If the transformation name includes a method-specific suffix ("_create", "_update", or "_validate"), the rule will be applied exclusively during calls to the corresponding method type and ignored for others.
Registering such functions is not thread-safe; it is intended that all rules be registered, prior to any validation.
func (*Connection) RegisterValidation ¶
func (c *Connection) RegisterValidation( name string, validation Validation, runOnNil ...bool, ) error
Register a new validation rule.
If a validation rule with the same name already exists, the previous one will be replaced.
If the validation name includes a method-specific suffix ("_create", "_update", or "_validate"), the rule will be applied exclusively during calls to the corresponding method type and ignored for others.
Registering such functions is not thread-safe; it is intended that all rules be registered, prior to any validation.
func (*Connection) RunTransaction ¶ added in v0.8.0
func (c *Connection) RunTransaction( ctx context.Context, fn func(ctx context.Context, tx *Transaction) error, ) error
Run a Firestore transaction, ensuring all operations within the provided function are executed atomically.
If any operation fails, the transaction is retried up to Firestore’s default limit. If all retries fail, the transaction is rolled back and the error is returned.
The provided function receives a Transaction instance, which should be used for all reads and writes within the transaction.
This instance can be passed into CollectionRef methods, via Options, to ensure they execute as part of the transaction.
Returns an error if the transaction fails after all retries.
type Document ¶
type Document[T interface{}] struct { ID string Data T Metadata metadata }
Document holds the ID and data related to a fetched document.
type ErrorFormatterFunc ¶ added in v0.9.0
type ErrorFormatterFunc func(fe FieldError) error
ErrorFormatterFunc is the function that's executed to generate a custom, user-friendly error message, based on FieldError's fields.
If the function returns a nil error, an instance of FieldError will be returned instead.
type FieldError ¶
type FieldError interface { // Collection returns the path of the // collection that contains the document // modeled by the top-level struct. Collection() string // Field returns the field's name, with the tag // name taking precedence over the field's // struct name. Field() string // StructField returns the field's actual name // from the struct. StructField() string // DisplayField returns the field's struct name // in a human-readable form. It splits camel, // pascal, and snake case names into // space-separated words, including separating // adjacent letters and numbers // (e.g. "FirstName" -> "First Name"). DisplayField() string // Path returns the field's dot-separated path, // with the tag names taking precedence over the // fields' struct names (e.g. "names.first"). Path() string // StructPath returns the field's actual // dot-separated path from the stuct // (e.g. "Names.First"). StructPath() string // Value returns the field's reflect Value. Value() reflect.Value // Kind returns the Value's reflect Kind // (eg. time.Time's kind is a struct). Kind() reflect.Kind // Type returns the Value's reflect Type // (eg. time.Time's type is time.Time). Type() reflect.Type // Rule returns the validation rule that failed. Rule() string // Param returns the param value, in string form // for comparison. Param() string // Error returns the error message. Error() string }
FieldError interface gives access to all field validation error details, which aid in constructing a custom error message.
type FieldScope ¶ added in v0.6.2
type FieldScope interface { // Collection returns the path of the // collection that contains the document // modeled by the top-level struct. Collection() string // Struct returns the reflected parent struct // of the current field, if any. Struct() reflect.Value // Field returns the field's name, with the tag // name taking precedence over the field's // struct name. Field() string // StructField returns the field's actual name // from the struct. StructField() string // DisplayField returns the field's struct name // in a human-readable form. It splits camel, // pascal, and snake case names into // space-separated words, including separating // adjacent letters and numbers // (e.g. "FirstName" -> "First Name"). DisplayField() string // Path returns the field's dot-separated path, // with the tag names taking precedence over the // fields' actual names (e.g. "names.first"). Path() string // StructPath returns the field's actual // dot-separated path from the stuct // (e.g. "Names.First"). StructPath() string // Value returns the current field's reflected // value to be validated. Value() reflect.Value // Kind returns the Value's reflect Kind // (eg. time.Time's kind is a struct). Kind() reflect.Kind // Type returns the Value's reflect Type // (eg. time.Time's type is time.Time). Type() reflect.Type // Rule returns the current validation's rule name. Rule() string // Param returns the param value, in string form // for comparison. Param() string }
FieldScope interface gives access to all information needed to validate a field.
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options allows for the overriding of default options for CollectionRef methods.
Options values are immutable. Each Options method creates a new instance - it does not modify the old.
func NewOptions ¶
func NewOptions() Options
Create a new Options instance.
Options allows for the overriding of default options for CollectionRef methods.
Options values are immutable. Each Options method creates a new instance - it does not modify the old.
func (Options) AllowEmptyFields ¶
Specify which field paths (using dot-separated strings) should ignore the "omitempty" (including method-specific) rules.
This can be useful when zero values are needed only during a specific method call.
Multiple calls to the method are cumulative.
Only applies to the Validate, Create and Update methods.
func (Options) AsCreate ¶ added in v0.7.4
Allows the application of the same rules as if performing a Create operation (e.g. "required_create"), i.e. perform the same validation as the one before document creation.
Only applies to the Validate method.
func (Options) AsUpdate ¶ added in v0.7.4
Allows the application of the same rules as if performing an Update operation (e.g. "required_update"), i.e. perform the same validation as the one before document updating.
Only applies to the Validate method.
func (Options) CustomID ¶
Specify custom doc ID. If left empty, Firestore will automatically create one.
Only applies to the Create method.
func (Options) ModifyOriginal ¶ added in v0.7.0
Allows the updating of the original struct's values during transformations.
Note: Using this option makes the struct validation thread-unsafe. Use with caution.
Only applies to the Validate, Create and Update methods.
func (Options) ReplaceAll ¶ added in v0.7.7
Ensure that the entire document is replaced with the passed in data, meaning no existing fields will be preserved. This works like Firestore's Set operation with disabled merging.
The deletion of fields is based on the provided struct, not the Firestore document itself. If the struct has changed since the document was created, some fields may not be deleted.
This option overrides any previous calls to ReplaceFields.
Only applies to the Update method.
func (Options) ReplaceFields ¶ added in v0.7.7
Specify which field paths (using dot-separated strings) to be fully overwritten. Other fields on the existing document will be untouched. This works like Firestore's Set operation with specified fields to merge.
If a provided field path does not refer to a value in the data passed, it'll be ignored.
This option overrides any previous calls to ReplaceAll.
Multiple calls to the method are cumulative.
Only applies to the Update method.
func (Options) RequireExists ¶ added in v0.7.7
Set a precondition that the document must exist before proceeding with the operation.
This option overrides any previous calls to RequireLastUpdateTime.
Only applies to the Delete method.
func (Options) RequireLastUpdateTime ¶ added in v0.7.7
Set a precondition that the document must exist and have the specified last update timestamp before applying an update.
The operation will only proceed if the document's last update time matches the given timestamp exactly.
Timestamp must be microsecond aligned.
This option overrides any previous calls to RequireExists.
Only applies to the Update and Delete methods.
func (Options) SkipValidationFields ¶ added in v0.9.0
Skip validation for specific fields, while still enforcing the name, ignore, and omitempty rules.
If no field paths are provided, validation is skipped for all fields. Otherwise, only the specified fields (dot-separated paths) are skipped.
When used with SkipValidationRules, only the specified rules will be skipped for the provided fields.
Calling this method without arguments overrides previous calls that specified particular fields, ensuring validation is skipped for all fields.
Multiple calls to the method, with specified fields, are cumulative.
Only applies to the Validate, Create and Update methods.
func (Options) SkipValidationRules ¶ added in v0.9.0
Skip specific validation rules, while still enforcing the name, ignore, and omitempty rules.
If no rules are provided, all validation rules (including transformations) are skipped. Otherwise, only the specified rules are ignored.
When used with SkipValidationFields, the provided rules will be skipped only for the specified fields.
To skip a transformation rule, specify its name without a prefix.
Calling this method without arguments overrides previous calls that specified particular rules, ensuring all rules are skipped.
Multiple calls to the method, with specified rules, are cumulative.
Only applies to the Validate, Create and Update methods.
func (Options) Transaction ¶ added in v0.8.0
func (o Options) Transaction(tx *Transaction) Options
Execute the operation within the provided transaction.
If set, all reads and writes performed by this operation will be executed as part of the given transaction, ensuring atomicity and automatic rollback on failure.
This option overrides any previous calls to Transaction.
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query helps to filter and order Firestore documents.
Query values are immutable. Each Query method creates a new Query - it does not modify the old.
func NewQuery ¶
func NewQuery() Query
Create a new Query instance.
Query helps to filter and order Firestore documents.
Query values are immutable. Each Query method creates a new Query - it does not modify the old.
func (Query) EndAt ¶
EndAt returns a new Query that specifies that results should end at the document with the given field values.
EndAt should be called with one field value for each OrderBy clause, in the order that they appear.
If an OrderBy call uses the special DocumentID field path, the corresponding value should be the document ID relative to the query's collection.
Calling EndAt overrides a previous call to EndAt or EndBefore.
func (Query) EndBefore ¶
EndBefore returns a new Query that specifies that results should end just before the document with the given field values.
EndBefore should be called with one field value for each OrderBy clause, in the order that they appear.
If an OrderBy call uses the special DocumentID field path, the corresponding value should be the document ID relative to the query's collection.
Calling EndBefore overrides a previous call to EndAt or EndBefore.
func (Query) ID ¶
ID returns a new Query that exclusively filters the set of results based on provided IDs.
ID takes precedence over and completely overrides any previous or subsequent calls to other Query methods, including Where - if IDs are specified, only documents matching those IDs will be returned regardless of other filter conditions.
If you need to filter by ID as well as other criteria, use the Where method with the special DocumentID field, instead of calling ID.
Multiple calls to the method are cumulative (OR condition).
func (Query) Limit ¶
Limit returns a new Query that specifies the maximum number of first results to return. It must not be negative.
func (Query) LimitToLast ¶
LimitToLast returns a new Query that specifies the maximum number of last results to return. It must not be negative.
func (Query) Offset ¶
Offset returns a new Query that specifies the number of initial results to skip. It must not be negative.
func (Query) OrderBy ¶
OrderBy returns a new Query that specifies the order in which results are returned. A Query can have multiple OrderBy specifications. It appends the specification to the list of existing ones.
The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]".
To order by document name, use the special field path DocumentID.
func (Query) StartAfter ¶
StartAfter returns a new Query that specifies that results should start just after the document with the given field values.
StartAfter should be called with one field value for each OrderBy clause, in the order that they appear.
If an OrderBy call uses the special DocumentID field path, the corresponding value should be the document ID relative to the query's collection.
Calling StartAfter overrides a previous call to StartAt or StartAfter.
func (Query) StartAt ¶
StartAt returns a new Query that specifies that results should start at the document with the given field values.
StartAt should be called with one field value for each OrderBy clause, in the order that they appear.
If an OrderBy call uses the special DocumentID field path, the corresponding value should be the document ID relative to the query's collection.
Calling StartAt overrides a previous call to StartAt or StartAfter.
func (Query) Where ¶
Where returns a new Query that filters the set of results. A Query can have multiple filters.
The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]".
The operator argument must be one of "==", "!=", "<", "<=", ">", ">=", "array-contains", "array-contains-any", "in" or "not-in".
type Transaction ¶ added in v0.8.0
type Transaction = firestore.Transaction
Transaction is an alias of Firestore's Transaction.
type Transformation ¶ added in v0.9.0
type Transformation interface {
// contains filtered or unexported methods
}
Transformation interface wraps different transformation function types.
type TransformationFunc ¶ added in v0.9.0
type TransformationFunc func(fs FieldScope) (interface{}, error)
TransformationFunc is a function that's executed during a field transformation.
type TransformationFuncCtx ¶ added in v0.9.0
type TransformationFuncCtx func(ctx context.Context, fs FieldScope) (interface{}, error)
TransformationFuncCtx is a context-aware function that's executed during a field transformation.
Useful when a transformation requires access to a context.
type TransformationFuncCtxTx ¶ added in v0.9.0
type TransformationFuncCtxTx func(ctx context.Context, tx *Transaction, fs FieldScope) (interface{}, error)
TransformationFuncCtxTx is a context-aware and transaction-aware function that's executed during a field transformation.
Useful when a transformation requires access to a context and needs to be executed inside a transaction.
The transaction argument is nil, unless explicitly provided in the Options of the calling CollectionRef method.
type TransformationFuncTx ¶ added in v0.9.0
type TransformationFuncTx func(tx *Transaction, fs FieldScope) (interface{}, error)
TransformationFuncTx is a transaction-aware function that's executed during a field transformation.
Useful when a transformation needs to be executed inside a transaction.
The transaction argument is nil, unless explicitly provided in the Options of the calling CollectionRef method.
type Validation ¶ added in v0.9.0
type Validation interface {
// contains filtered or unexported methods
}
Validation interface wraps different validation function types.
type ValidationFunc ¶ added in v0.9.0
type ValidationFunc func(fs FieldScope) (bool, error)
ValidationFunc is a function that's executed during a field validation.
type ValidationFuncCtx ¶ added in v0.9.0
type ValidationFuncCtx func(ctx context.Context, fs FieldScope) (bool, error)
ValidationFuncCtx is a context-aware function that's executed during a field validation.
Useful when a validation requires access to a context.
type ValidationFuncCtxTx ¶ added in v0.9.0
type ValidationFuncCtxTx func(ctx context.Context, tx *Transaction, fs FieldScope) (bool, error)
ValidationFuncCtxTx is a context-aware and transaction-aware function that's executed during a field validation.
Useful when a validation requires access to a context and needs to be executed inside a transaction.
The transaction argument is nil, unless explicitly provided in the Options of the calling CollectionRef method.
type ValidationFuncTx ¶ added in v0.9.0
type ValidationFuncTx func(tx *Transaction, fs FieldScope) (bool, error)
ValidationFuncTx is a transaction-aware function that's executed during a field validation.
Useful when a validation needs to be executed inside a transaction.
The transaction argument is nil, unless explicitly provided in the Options of the calling CollectionRef method.