Documentation
¶
Overview ¶
Package shared contains common shared information, and utilities.
Index ¶
- Constants
- Variables
- func ApplyListParams(docs [][]byte, prm *list.List) ([][]byte, error)
- func AssembleItems(docs [][]byte) []byte
- func CreateHTTPTestServer(statusCode int, headers map[string]string, queryParams map[string]string, ...) *httptest.Server
- func Decode(r io.Reader, v any) error
- func Encode(w io.Writer, v any) error
- func ErrorContains(err error, text ...string) bool
- func GenerateID(ct string) string
- func GenerateUUID() string
- func IsEnvironment(environments ...string) bool
- func Marshal(v any) ([]byte, error)
- func MergeParams[T Param](defaults, overrides *T) *T
- func PaginateDocuments(docs [][]byte, offset, limit int) [][]byte
- func PrintErrorMessages(errors ...error) string
- func ProjectDocuments(docs [][]byte, fields []string) ([][]byte, error)
- func ReadAll(r io.Reader) ([]byte, error)
- func ResetCounters(counters ...*expvar.Int)
- func SliceContains(source []string, text string) bool
- func SortDocuments(docs [][]byte, s customsort.SortSlice) ([][]byte, error)
- func TargetName(name, alternative string) (string, error)
- func Unmarshal(data []byte, v any) error
- func ValidateSQLIdentifier(s string) error
- type HTTPMethod
- type Param
- type ResponseTestDataWithIDS
- type TestDataS
- type TestDataWithIDS
Constants ¶
const ( // Development is the development environment. Development = "development" // Integration is the integration environment. Integration = "integration" // Production is the production environment. Production = "production" // Staging is the staging environment. Staging = "staging" // Testing is the testing environment. Testing = "testing" )
const ( StatusPending = 0 StatusActive = 1 StatusDeleted = 99 )
General Status Codes
const ( // DatabaseName is the database name. DatabaseName = Test // TableName is the table/collection/index/etc name. TableName = Test // DefaultTimeout is the default timeout. DefaultTimeout = 30 * time.Minute // DocumentID is the document ID. DocumentID = "VFzrpYMBXu5BQSZxo0qX" // DocumentIDInvalid is an invalid document ID. DocumentIDInvalid = "VFzrpYMBXu5BQSZxo0qY" // DocumentName is the document name. DocumentName = Test // DocumentNameUpdated is the updated document name. DocumentNameUpdated = "Test2" // DocumentVersion is the document version. DocumentVersion = "1.0.0" RoleName = "test" // Test name. Test = "test" )
const Timeout = 30 * time.Second
Timeout is the default timeout.
Variables ¶
var ( // TestData is the test data. TestData = &TestDataS{ Name: DocumentName, Version: DocumentVersion, } // TestDataWithID is the test data. TestDataWithID = &TestDataWithIDS{ ID: DocumentID, Name: DocumentName, Version: DocumentVersion, } // UpdatedTestData is the updated test data. UpdatedTestData = &TestDataS{ Name: DocumentNameUpdated, Version: DocumentVersion, } // UpdatedTestDataID is the updated test data with ID. UpdatedTestDataID = &TestDataWithIDS{ ID: DocumentID, Name: DocumentNameUpdated, Version: DocumentVersion, } )
var TimeoutPing = 10 * time.Second
TimeoutPing is the timeout for ping.
Functions ¶
func ApplyListParams ¶
ApplyListParams post-processes the documents an in-process adapter collected, honoring the List params that adapter cannot push down to its backend.
Order matters and follows SQL: sort the full matched set, then paginate that ordering, then project. Projecting first would drop the sort key; paginating first would return the wrong page.
It exists so the adapters that must materialize their results anyway — memory, file, sftp, bolt, redis — honor Sort, Limit, Offset and Fields identically instead of each ignoring a different subset. Backends that can push these down (the SQL adapters) should keep doing so; this is for the ones that cannot.
A nil prm leaves docs untouched.
func AssembleItems ¶
AssembleItems wraps documents into the `{"items":[...]}` envelope the in-process adapters unmarshal into the caller's destination.
func CreateHTTPTestServer ¶
func CreateHTTPTestServer( statusCode int, headers map[string]string, queryParams map[string]string, body string, ) *httptest.Server
CreateHTTPTestServer creates a mocked HTTP server. Don't forget to defer close it!
SEE: Test for usage.
func ErrorContains ¶
ErrorContains checks if an error contains a string.
func GenerateID ¶
GenerateID generates MD5 hash (content-based) based on content. Good to be used to avoid duplicated messages.
func GenerateUUID ¶
func GenerateUUID() string
GenerateUUID generates a RFC4122 UUID and DCE 1.1: Authentication and Security Services.
func IsEnvironment ¶
IsEnvironment determines if the current environment is one of the provided.
func MergeParams ¶
func MergeParams[T Param](defaults, overrides *T) *T
MergeParams returns a copy of defaults with fields set by overrides applied.
The params structs do not track field presence, so zero handling has to be defined per field:
- count.Count: empty Routing is unset (`omitempty,gt=0`); empty Search is unset because it is `required`.
- create.Create: nil Any and empty ID, Routing, and TTL are unset (`omitempty,gt=0`).
- delete.Delete: empty ID is unset because it is `required`; empty Routing is unset (`omitempty,gt=0`); false Soft is meaningful and is always copied because the field has no `omitempty` validation; empty Target is genuinely ambiguous because it has no validation tag, but is treated as unset so a caller setting another field does not clear a default target.
- list.List: nil Any and empty Fields, Routing, Search, SearchRaw, and Sort are unset (`omitempty,gt=0`); zero Limit is unset (`omitempty,gt=0`) and list.New defaults it to 10, so zero cannot express "no limit"; zero Count and Offset are meaningful and always copied (`omitempty,gte=0`), representing an empty result and the first item. Omitted and explicit zero are ambiguous for Count and Offset because the params type has no presence bits; honoring their valid zero value wins.
- retrieve.Retrieve: nil Any and empty Fields and Routing are unset (`omitempty,gt=0`); empty ID is unset because it is `required`.
- update.Update: nil Any and empty Routing and TTL are unset (`omitempty,gt=0`); empty ID is unset because it is `required`.
Neither input is mutated. The returned struct is a shallow copy; reference fields are assigned but never modified by this function.
func PaginateDocuments ¶
PaginateDocuments applies offset then limit to docs.
A non-positive limit means "no limit". Limit carries `validate:"omitempty,gt=0"`, while list.New() sets it to 10; callers that pass a value returned by list.New therefore receive at most 10 records.
An offset past the end yields an empty slice rather than an error.
func PrintErrorMessages ¶
PrintErrorMessages prints the concatenated error messages.
func ProjectDocuments ¶
ProjectDocuments reduces each document to the requested fields.
An empty field list returns docs untouched. A field absent from a document is omitted rather than emitted as null, so projecting never invents keys.
func ResetCounters ¶
ResetCounters zeroes the given metrics.
Storage metrics are process-global, keyed by storage name, so every test in a package accumulates into the same counters. A test that asserts absolute counter values must therefore start from a known baseline — without one, its expectations change the moment any other test touches the same adapter.
func SliceContains ¶
SliceContains returns true if the slice contains the string.
NOTE: It's case insensitive.
NOTE: @andres moved to here.
func SortDocuments ¶
func SortDocuments(docs [][]byte, s customsort.SortSlice) ([][]byte, error)
SortDocuments orders docs — each a marshalled JSON object — according to s.
s is a `[][]string` of `[key, order]` pairs, applied left to right: the first pair is the primary key, the second breaks its ties, and so on. `order` is `asc` or `desc`, matching customsort; an unrecognised order is rejected rather than silently treated as ascending.
The sort is stable, so documents equal on every requested key keep the order the backend produced them in.
func TargetName ¶
TargetName returns the provided target name, or the configured one. A target, depending on the storage, is a collection, a table, a bucket, etc. For ElasticSearch - as it doesn't have a concept of a database - the target is the index.
func ValidateSQLIdentifier ¶
ValidateSQLIdentifier ensures s is a plain (optionally dot-qualified) SQL identifier, so it can be safely interpolated into a statement as a table name. It rejects anything carrying quotes, spaces, or statement separators, which would otherwise allow SQL injection through the target parameter.
Types ¶
type HTTPMethod ¶
type HTTPMethod string
HTTPMethod is the HTTP method.
const ( // MethodGet is the HTTP GET method. MethodGet HTTPMethod = http.MethodGet // MethodPost is the HTTP POST method. MethodPost HTTPMethod = http.MethodPost // MethodPut is the HTTP PUT method. MethodPut HTTPMethod = http.MethodPut // MethodPatch is the HTTP PATCH method. MethodPatch HTTPMethod = http.MethodPatch // MethodDelete is the HTTP DELETE method. MethodDelete HTTPMethod = http.MethodDelete )
func (HTTPMethod) String ¶
func (m HTTPMethod) String() string
type Param ¶
type Param interface {
count.Count | create.Create | delete.Delete | list.List | retrieve.Retrieve | update.Update
}
Param is the set of operation params supported by MergeParams.
type ResponseTestDataWithIDS ¶
type ResponseTestDataWithIDS struct {
Items []TestDataWithIDS `json:"items"`
}
ResponseTestDataWithIDS is the response from the Redis list SCAN command.
type TestDataS ¶
type TestDataS struct {
Name string `db:"name" dbType:"varchar(255)" json:"name,omitempty" query:"name"`
Version string `db:"version" dbType:"varchar(255)" json:"version,omitempty" query:"version"`
}
TestDataS is the test data definition.
type TestDataWithIDS ¶
type TestDataWithIDS struct {
ID string `bson:"_id" db:"id" dbType:"varchar(255)" json:"id,omitempty" query:"id"`
Name string `db:"name" dbType:"varchar(255)" json:"name,omitempty" query:"name"`
Version string `db:"version" dbType:"varchar(255)" json:"version,omitempty" query:"version"`
}
TestDataWithIDS is the test data definition.