{"modulePath":"github.com/bitechdev/ResolveSpec","version":"v1.3.14","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package common\n\n## Constants\n\n```go\nconst PrimaryKeySortColumn = \"$pk\"\n```\nPrimaryKeySortColumn is a sentinel SortOption.Column value that gets resolved to a model's actual primary key column name at query time. This lets a single global default sort (e.g. set once via Handler.SetDefaultSort) work across models with different primary keys, e.g. common.SortOption{Column: common.PrimaryKeySortColumn, Direction: \"asc\"}.\n\n```go\nconst TxHookName = \"on_tx_begin\"\n```\nTxHookName is the shared value of every spec's OnTxBegin HookType.\n\n## Functions\n\n```go\nfunc AddTablePrefixToColumns(where string, tableName string) string\n```\nAddTablePrefixToColumns adds table prefix to unqualified column references in a WHERE clause. This function only prefixes simple column references and skips:\n\n  - Columns already having a table prefix (containing a dot)\n  - Columns inside function calls or expressions (inside parentheses)\n  - Columns inside subqueries\n  - Columns that don't exist in the table (validation via model registry)\n\nExamples:\n\n  - \"status = 'active'\" -\u003e \"users.status = 'active'\" (if status exists in users table)\n  - \"COALESCE(status, 'default') = 'active'\" -\u003e unchanged (status inside function)\n  - \"users.status = 'active'\" -\u003e unchanged (already has prefix)\n  - \"(status = 'active')\" -\u003e \"(users.status = 'active')\" (grouping parens are OK)\n  - \"invalid\\_col = 'value'\" -\u003e unchanged (if invalid\\_col doesn't exist in table)\n\nParameters:\n\n  - where: The WHERE clause to process\n  - tableName: The table name to use as prefix\n\nReturns:\n\n  - The WHERE clause with table prefixes added to appropriate and valid columns\n\n```go\nfunc BuildArrayOverlapCondition(column string, v interface{}) (query string, args []interface{})\n```\nBuildArrayOverlapCondition builds a parameterized condition testing whether an array column has at least one element in common with the given value(s), using PostgreSQL's array overlap operator (\u0026\u0026). Unlike a text-cast ILIKE, this performs real element-wise containment (no substring false positives) and can use a GIN index on the column. A single value is treated as a one-element array. Returns (\"\", nil) if the value is empty.\n\n```go\nfunc BuildInCondition(column string, v interface{}) (query string, args []interface{})\n```\nBuildInCondition builds a parameterized IN condition from a filter value. Returns the condition string (e.g. \"col IN (?,?)\") and the individual values as args. Returns (\"\", nil) if the value is empty or not a slice.\n\n```go\nfunc BuildJSONFilterCondition(model interface{}, tableAlias, token, operator string, value interface{}) (condition string, args []interface{}, ok bool)\n```\nBuildJSONFilterCondition builds a complete WHERE condition for a JSON column token. ok is false when the token is not a JSON reference or the operator is not one this builder handles (the caller then keeps its existing behaviour).\n\nThe JSON path is always bound as a parameter, never interpolated. When the reference carries no explicit ::cast and the operator is an ordered comparison against a numeric value, the extracted text is cast to numeric so the comparison is numeric rather than lexical.\n\n```go\nfunc BuildSpatialCondition(column, operator string, value any) (query string, args []interface{}, ok bool)\n```\nBuildSpatialCondition builds a PostGIS spatial filter.\n\n\t\"st_dwithin\"    value: {\"geom\": \u003cgeojson|ewkt|hex\u003e, \"distance\": \u003cn\u003e}\n\t\"st_intersects\" / \"st_contains\" / \"st_within\" / \"st_covers\" /\n\t\"st_coveredby\" / \"st_overlaps\" / \"st_touches\" / \"st_crosses\" /\n\t\"st_equals\" / \"st_disjoint\"     value: \u003cgeojson|ewkt|hex\u003e\n\t\"bbox\" (alias \"\u0026\u0026\")             value: \u003cgeom\u003e or {\"bbox\":[minx,miny,maxx,maxy],\"srid\":4326}\n\n```go\nfunc BuildVectorCondition(column, operator string, value any) (query string, args []interface{}, ok bool)\n```\nBuildVectorCondition builds a pgvector distance-threshold filter.\n\n\toperator: \"l2_within\" | \"cosine_within\" | \"ip_within\"\n\tvalue:    {\"vector\": [...], \"distance\": \u003cn\u003e}\n\t          {\"vector\": [...], \"lt\"|\"lte\"|\"gt\"|\"gte\": \u003cn\u003e}\n\nProduces e.g. \\`embedding \\\u003c=\u003e ? \\\u003c ?\\` with args \\[vectorLiteral, threshold].\n\n```go\nfunc ConvertSliceForBun(value interface{}) interface{}\n```\nConvertSliceForBun converts \\[]interface{} values to PostgreSQL array literal strings. BUN's fallback appender for \\[]interface{} is JSON encoding, which produces \"\\[]\" — invalid PostgreSQL array syntax. PostgreSQL expects \"{}\" for empty arrays and \"{elem1,elem2}\" for non-empty ones. All other value types are returned unchanged.\n\n```go\nfunc EnsureOuterParentheses(clause string) string\n```\nEnsureOuterParentheses ensures that a SQL clause is wrapped in parentheses to prevent OR logic from escaping. It checks if the clause already has matching outer parentheses and only adds them if they don't exist.\n\nThis is particularly important for OR conditions and complex filters where the absence of parentheses could cause the logic to escape and affect the entire query incorrectly.\n\nParameters:\n\n  - clause: The SQL clause to check and potentially wrap\n\nReturns:\n\n  - The clause with guaranteed outer parentheses, or empty string if input is empty\n\n```go\nfunc ExtractColumnName(cond string) string\n```\nExtractColumnName extracts the column name from a WHERE condition For example: \"status = 'active'\" returns \"status\"\n\n```go\nfunc ExtractTagValue(tag, key string) string\n```\nExtractTagValue extracts the value for a given key from a struct tag string. It handles both semicolon and comma-separated tag formats (e.g., GORM and BUN tags). For tags like \"json:name;validate:required\" it will extract \"name\" for key \"json\". For tags like \"rel:has-many,join:table\" it will extract \"table\" for key \"join\".\n\n```go\nfunc FilterValueToSlice(v interface{}) []interface{}\n```\nFilterValueToSlice converts a filter value to \\[]interface{} for use with IN operators. JSON-decoded arrays arrive as \\[]interface{}, but typed slices (e.g. \\[]string) also work. Returns a single-element slice if the value is not a slice type.\n\n```go\nfunc GetHeadSpecHeaders() []string\n```\nGetHeadSpecHeaders returns all headers used by HeadSpec\n\n```go\nfunc GetTableNameFromModel(model interface{}) string\n```\nGetTableNameFromModel extracts the table name from a model. It checks the bun tag first, then falls back to converting the struct name to snake\\_case.\n\n```go\nfunc Hardening() config.HardeningConfig\n```\nHardening returns the security hardening toggles (config section \"hardening\").\n\n```go\nfunc IsJSONColumnToken(model interface{}, token string) bool\n```\nIsJSONColumnToken reports whether token is a JSON reference this package can resolve for model (arrow/hash syntax always; dotted shorthand only when the base is a JSON column).\n\n```go\nfunc IsNumericZeroFilter(model interface{}, column string, value interface{}) bool\n```\nIsNumericZeroFilter reports whether value is a numeric zero compared against a numeric column of model. Used by the \"null as zero\" option, which turns col = 0 into (col = 0 OR col IS NULL).\n\n```go\nfunc IsSQLExpression(cond string) bool\n```\nIsSQLExpression checks if a condition is a SQL expression that shouldn't be prefixed\n\n```go\nfunc IsSQLKeyword(word string) bool\n```\nIsSQLKeyword checks if a string is a SQL keyword that shouldn't be treated as a column name\n\n```go\nfunc IsSafeSortExpression(expr string) bool\n```\nIsSafeSortExpression validates that a sort expression (enclosed in brackets) is safe and doesn't contain SQL injection attempts or dangerous commands\n\n```go\nfunc IsSpatialOperator(op string) bool\n```\nIsSpatialOperator reports whether op is a spatial filter operator handled by BuildSpatialCondition.\n\n```go\nfunc IsTrivialCondition(cond string) bool\n```\nIsTrivialCondition checks if a condition is trivial and always evaluates to true These conditions should be removed from WHERE clauses as they have no filtering effect\n\n```go\nfunc IsVectorOperator(op string) bool\n```\nIsVectorOperator reports whether op is a vector similarity filter operator handled by BuildVectorCondition.\n\n```go\nfunc MainTableAlias(model interface{}, tableName string) string\n```\nMainTableAlias returns the alias the main table gets in the SELECT: the model's TableAlias() when provided, otherwise the bare table name.\n\n```go\nfunc MergeUpdateValues(existing, incoming map[string]interface{}, disallowNulls bool) map[string]interface{}\n```\nMergeUpdateValues merges the incoming request values into the existing record map (in place) and returns it.\n\nEvery key present in incoming overwrites the existing value, including empty strings and explicit nulls, so clients can clear a column by sending \"\" or null. Keys absent from incoming are left untouched.\n\nWhen disallowNulls is true, nil values are skipped and the existing value is kept. Empty strings are still applied.\n\n```go\nfunc NormalizeCastTarget(s string) (string, bool)\n```\nNormalizeCastTarget returns the canonical PostgreSQL type name for a user-supplied cast spelling, and whether it is on the allowlist.\n\n```go\nfunc NormalizeMainTableFilters(model interface{}, tableName string, opts *RequestOptions)\n```\nNormalizeMainTableFilters rewrites \"\\\u003cmain table or alias\u003e.\\\u003ccolumn\u003e\" filter columns on opts to the bare model column (on a copy, never the caller's slice) so the column validator keeps them.\n\n```go\nfunc ProcessCRUDRequest(handler CRUDHandler, w ResponseWriter, r Request, params map[string]string)\n```\nProcessCRUDRequest demonstrates using the CRUDHandler interface which works with resolvespec.Handler and restheadspec.Handler\n\n```go\nfunc ProcessMetadataRequest(handler CRUDHandler, w ResponseWriter, r Request, params map[string]string)\n```\nProcessMetadataRequest demonstrates getting metadata from CRUD handlers\n\n```go\nfunc QualifyModelColumn(model interface{}, alias, column string) string\n```\nQualifyModelColumn returns \"alias\".\"column\" when column is a plain identifier that exists on the model, so it stays unambiguous once joins are added. Anything else (expressions, JSON paths, other tables' columns) is returned unchanged.\n\n```go\nfunc QuoteIdent(qualifier string) string\n```\n\n```go\nfunc QuoteLiteral(value string) string\n```\n\n```go\nfunc RelationPathToBunAlias(relationPath string) string\n```\nRelationPathToBunAlias converts a relation path (e.g., \"Order.Customer\") to a Bun alias format. It converts to lowercase and replaces dots with double underscores. For example: \"Order.Customer\" -\u003e \"order\\_\\_customer\"\n\n```go\nfunc ReplaceTableReferencesInSQL(sqlExpr, baseTableName, targetAlias string) string\n```\nReplaceTableReferencesInSQL replaces references to a base table name in a SQL expression with the appropriate alias for the current preload level. For example, if baseTableName is \"mastertaskitem\" and targetAlias is \"mal\\_\\_mal\", it will replace \"mastertaskitem.rid\\_mastertaskitem\" with \"mal\\_\\_mal.rid\\_mastertaskitem\"\n\n```go\nfunc ResolveJSONColumnExpr(model interface{}, tableAlias, token string) (expr string, args []interface{}, alias string, ok bool)\n```\nResolveJSONColumnExpr resolves a raw column token that traverses into a JSON value into a parameterised SQL expression plus its args and a deterministic output alias. ok is false when the token is not a JSON reference, in which case the caller should handle it the way it did before.\n\ntableAlias, when non-empty, qualifies the base column.\n\n```go\nfunc RunRequestTx(ctx context.Context, db Database, tc TxContext, onBegin func() error, body func(tx Database) error) error\n```\nRunRequestTx opens a transaction on db, points tc at it, runs onBegin (the spec's OnTxBegin hooks) and then body. An error from onBegin or body rolls the transaction back; body is not run when onBegin fails.\n\n```go\nfunc SanitizeWhereClause(where string, tableName string, options ...*RequestOptions) string\n```\nSanitizeWhereClause removes trivial conditions and fixes incorrect table prefixes This function should be used everywhere a WHERE statement is sent to ensure clean, efficient SQL\n\nParameters:\n\n  - where: The WHERE clause string to sanitize\n  - tableName: The correct table/relation name to use when fixing incorrect prefixes\n  - options: Optional RequestOptions containing preload relations that should be allowed as valid prefixes\n\nReturns:\n\n  - The sanitized WHERE clause with trivial conditions removed and incorrect prefixes fixed\n  - An empty string if all conditions were trivial or the input was empty\n\nNote: This function will NOT add prefixes to unprefixed columns. It will only fix incorrect prefixes (e.g., wrong\\_table.column -\u003e correct\\_table.column), unless the prefix matches a preloaded relation name, in which case it's left unchanged.\n\nIMPORTANT: Outer parentheses are preserved if the clause contains top-level OR operators to prevent OR logic from escaping and affecting the entire query incorrectly.\n\n```go\nfunc SetCORSHeaders(w ResponseWriter, r Request, config CORSConfig)\n```\nSetCORSHeaders sets CORS headers on a response writer.\n\nThe request Origin is only reflected (and credentials only allowed) when it is listed in config.AllowedOrigins. A \"\\*\" entry allows any origin but never with credentials. Unlisted origins get no CORS headers, so browsers block the cross-origin read.\n\n```go\nfunc ShouldUseNestedProcessor(data map[string]interface{}, model interface{}, relationshipHelper RelationshipInfoProvider) bool\n```\nShouldUseNestedProcessor determines if we should use nested CUD processing It recursively checks if the data contains: 1. A \\_request field at any level, OR 2. Nested relations that themselves contain further nested relations or \\_request fields This ensures nested processing is only used when there are deeply nested operations\n\n```go\nfunc StripMainTablePrefix(model interface{}, column string, prefixes ...string) string\n```\nStripMainTablePrefix turns \"\\\u003cprefix\u003e.\\\u003ccolumn\u003e\" into \"\\\u003ccolumn\u003e\" when prefix is one of the main table's names/aliases and column exists on the model. Any other input is returned unchanged.\n\n```go\nfunc StripMainTablePrefixFromFilters(model interface{}, filters []FilterOption, prefixes ...string)\n```\nStripMainTablePrefixFromFilters applies StripMainTablePrefix to every filter column.\n\n```go\nfunc ValidateAndFixPreloadWhere(where string, relationName string) (string, error)\n```\nValidateAndFixPreloadWhere validates and normalizes WHERE clauses for preloads\n\nNOTE: For preload queries, table aliases from the parent query are not valid since the preload executes as a separate query with its own table alias. This function now simply validates basic syntax without requiring or adding prefixes. The actual alias normalization happens in the database adapter layer.\n\nReturns the WHERE clause and an error if it contains obviously invalid syntax.\n\n```go\nfunc VectorLiteral(value any) (string, error)\n```\nVectorLiteral converts a vector value into a pgvector literal string \"\\[1,2,3]\". Accepts \\[]float32, \\[]float64, \\[]int, \\[]any (of numbers), or an already-formatted string.\n\n```go\nfunc VectorOperator(metric string) string\n```\nVectorOperator maps a metric name to its pgvector distance operator.\n\n\t\"l2\" / \"euclidean\" / \"\"  -\u003e \u003c-\u003e\n\t\"cosine\"                 -\u003e \u003c=\u003e\n\t\"ip\" / \"inner\" / \"dot\"   -\u003e \u003c#\u003e\n\n```go\nfunc WrapHTTPRequest(w http.ResponseWriter, r *http.Request) (ResponseWriter, Request)\n```\nWrapHTTPRequest wraps standard http.ResponseWriter and \\*http.Request into common interfaces\n\n```go\nfunc WrapSQLError(err error, sql string) error\n```\nWrapSQLError wraps err with the given SQL. If err is nil it returns nil.\n\n## Types\n\n```go\ntype APIError struct {\n\tCode    string      `json:\"code\"`\n\tMessage string      `json:\"message\"`\n\tDetails interface{} `json:\"details,omitempty\"`\n\tDetail  string      `json:\"detail,omitempty\"`\n\tSQL     string      `json:\"sql,omitempty\"`\n}\n```\n\n```go\ntype CORSConfig struct {\n\tAllowedOrigins []string\n\tAllowedMethods []string\n\tAllowedHeaders []string\n\tMaxAge         int\n}\n```\nCORSConfig holds CORS configuration\n\n```go\nfunc DefaultCORSConfig() CORSConfig\n```\nDefaultCORSConfig returns a default CORS configuration suitable for HeadSpec\n\n```go\ntype CRUDHandler interface {\n\tSpecHandler\n\n\t// Handle processes API requests through router-agnostic interface\n\tHandle(w ResponseWriter, r Request, params map[string]string)\n\n\t// HandleGet processes GET requests for metadata\n\tHandleGet(w ResponseWriter, r Request, params map[string]string)\n}\n```\nCRUDHandler interface for handlers that support CRUD operations This is implemented by resolvespec.Handler and restheadspec.Handler\n\n```go\ntype CRUDRequestProvider interface {\n\tGetRequest() string\n}\n```\nCRUDRequestProvider interface for models that provide CRUD request strings\n\n```go\ntype Column struct {\n\tName       string `json:\"name\"`\n\tType       string `json:\"type\"`\n\tIsNullable bool   `json:\"is_nullable\"`\n\tIsPrimary  bool   `json:\"is_primary\"`\n\tIsUnique   bool   `json:\"is_unique\"`\n\tHasIndex   bool   `json:\"has_index\"`\n}\n```\n\n```go\ntype ColumnRef struct {\n\t// Base is the bare base column name, e.g. \"data\". Always a simple\n\t// identifier ([A-Za-z_][A-Za-z0-9_]*); qualified names are rejected.\n\tBase string\n\t// Path is the JSON key / array-index path, e.g. [\"address\", \"city\"].\n\t// Empty for a plain column reference.\n\tPath []string\n\t// AsText is true when the final extraction should yield text (-\u003e\u003e / #\u003e\u003e)\n\t// rather than jsonb (-\u003e / #\u003e).\n\tAsText bool\n\t// Cast is a normalised SQL type name to cast the whole expression to\n\t// (e.g. \"integer\", \"numeric\", \"timestamptz\"), or \"\" for no cast.\n\tCast string\n\t// Alias is a validated output identifier for `AS \u003calias\u003e`, or \"\".\n\tAlias string\n\t// Ambiguous is true when Path was produced from the dotted \"a.b.c\"\n\t// shorthand. The caller MUST verify that Base is a JSON column\n\t// (reflection.IsJSONColumn) before treating this as a JSON expression,\n\t// otherwise \"a.b\" is an ordinary table-qualified column.\n\tAmbiguous bool\n}\n```\nColumnRef is a parsed reference to a (possibly JSON-traversing) column.\n\n```go\nfunc ParseColumnRef(raw string) (ColumnRef, bool)\n```\nParseColumnRef parses a column token that traverses into a JSON value.\n\nok is true only when the token carries JSON traversal syntax (arrow chain, hash-path, or dotted shorthand with at least one sub-key). For a plain column name — with or without an alias/cast — ok is false and the caller should handle the token the way it did before.\n\nWhen ok is true and ref.Ambiguous is true, the caller must confirm that ref.Base is a JSON column before using ref.SQL; otherwise the dotted token is an ordinary \"table.column\" reference.\n\n```go\nfunc ResolveJSONColumnRef(model interface{}, token string) (ColumnRef, bool)\n```\nResolveJSONColumnRef parses token and, when it is a usable JSON reference for model, returns the parsed ColumnRef. For the dotted \"a.b\" shorthand (which is otherwise indistinguishable from a table-qualified column) ok is true only when model confirms the base is a JSON column.\n\n```go\nfunc (r ColumnRef) OutputAlias() string\n```\nOutputAlias returns the alias to use for this reference in a SELECT list: the explicit alias when given, otherwise a deterministic name derived from the base column and path (e.g. \"data\\_address\\_city\").\n\n```go\nfunc (r ColumnRef) SQL(tableAlias string) (expr string, args []interface{})\n```\nSQL renders the reference as a parameterised SQL expression plus its args. tableAlias, when non-empty, qualifies the base column (each dot-separated part is quoted independently, so \"public.users\" -\u003e \\`\"public\".\"users\"\\`).\n\n```go\ntype ColumnValidator struct {\n\t// contains filtered or unexported fields\n}\n```\nColumnValidator validates column names against a model's fields\n\n```go\nfunc NewColumnValidator(model interface{}) *ColumnValidator\n```\nNewColumnValidator creates a new column validator for a given model\n\n```go\nfunc (v *ColumnValidator) Columns() []string\n```\nColumns returns all valid column names known to this validator\n\n```go\nfunc (v *ColumnValidator) FilterRequestOptions(options RequestOptions) RequestOptions\n```\nFilterRequestOptions filters all column references in RequestOptions Returns a new RequestOptions with only valid columns, logging warnings for invalid ones\n\n```go\nfunc (v *ColumnValidator) FilterValidColumns(columns []string) []string\n```\nFilterValidColumns filters a list of columns, returning only valid ones Logs warnings for any invalid columns\n\n```go\nfunc (v *ColumnValidator) GetValidColumns() []string\n```\nGetValidColumns returns a list of all valid column names for debugging purposes\n\n```go\nfunc (v *ColumnValidator) IsValidColumn(column string) bool\n```\nIsValidColumn checks if a column is valid Returns true if valid, false if invalid\n\n```go\nfunc (v *ColumnValidator) ValidateColumn(column string) error\n```\nValidateColumn validates a single column name Returns nil if valid, error if invalid Columns prefixed with \"cql\" (case insensitive) are always valid Handles PostgreSQL JSON operators (-\u003e and -\u003e\u003e)\n\n```go\nfunc (v *ColumnValidator) ValidateColumns(columns []string) error\n```\nValidateColumns validates multiple column names Returns error with details about all invalid columns\n\n```go\nfunc (v *ColumnValidator) ValidateRequestOptions(options RequestOptions) error\n```\nValidateRequestOptions validates all column references in RequestOptions\n\n```go\ntype ComputedColumn struct {\n\tName       string `json:\"name\"`\n\tExpression string `json:\"expression\"`\n}\n```\n\n```go\ntype CustomOperator struct {\n\tName string `json:\"name\"`\n\tSQL  string `json:\"sql\"`\n}\n```\n\n```go\ntype Database interface {\n\t// Core query operations\n\tNewSelect() SelectQuery\n\tNewInsert() InsertQuery\n\tNewUpdate() UpdateQuery\n\tNewDelete() DeleteQuery\n\n\t// Raw SQL execution\n\tExec(ctx context.Context, query string, args ...interface{}) (Result, error)\n\tQuery(ctx context.Context, dest interface{}, query string, args ...interface{}) error\n\n\t// Transaction support\n\tBeginTx(ctx context.Context) (Database, error)\n\tCommitTx(ctx context.Context) error\n\tRollbackTx(ctx context.Context) error\n\tRunInTransaction(ctx context.Context, fn func(Database) error) error\n\n\t// GetUnderlyingDB returns the underlying database connection\n\t// For GORM, this returns *gorm.DB\n\t// For Bun, this returns *bun.DB\n\t// This is useful for provider-specific features like PostgreSQL NOTIFY/LISTEN\n\tGetUnderlyingDB() interface{}\n\n\t// DriverName returns the canonical name of the underlying database driver.\n\t// Possible values: \"postgres\", \"sqlite\", \"mssql\", \"mysql\".\n\t// All adapters normalise vendor-specific strings (e.g. Bun's \"pg\", GORM's\n\t// \"sqlserver\") to the values above before returning.\n\tDriverName() string\n}\n```\nDatabase interface designed to work with both GORM and Bun\n\n```go\nfunc ProcessWithAnyHandler(handler SpecHandler) Database\n```\nProcessWithAnyHandler demonstrates using the base SpecHandler interface which works with any handler type (resolvespec, restheadspec, or funcspec)\n\n```go\ntype DeleteQuery interface {\n\tModel(model interface{}) DeleteQuery\n\tTable(table string) DeleteQuery\n\tWhere(query string, args ...interface{}) DeleteQuery\n\n\t// Execution\n\tExec(ctx context.Context) (Result, error)\n}\n```\nDeleteQuery interface for building DELETE queries\n\n```go\ntype FilterOption struct {\n\tColumn        string      `json:\"column\"`\n\tOperator      string      `json:\"operator\"`\n\tValue         interface{} `json:\"value\"`\n\tLogicOperator string      `json:\"logic_operator\"` // \"AND\" or \"OR\" - how this filter combines with previous filters\n\n\t// NullAsZero makes an \"eq\" filter on a numeric column with a zero value also\n\t// match NULLs (COALESCE(col, 0) = 0). Set for x-fieldfilter headers only.\n\tNullAsZero bool `json:\"-\"`\n}\n```\n\n```go\ntype HTTPHandlerFunc func(ResponseWriter, Request)\n```\nHTTPHandlerFunc type for HTTP handlers\n\n```go\ntype InsertQuery interface {\n\tModel(model interface{}) InsertQuery\n\tTable(table string) InsertQuery\n\tValue(column string, value interface{}) InsertQuery\n\tOnConflict(action string) InsertQuery\n\t// ExcludeColumn omits columns from a Model()-based INSERT (e.g. generated columns).\n\tExcludeColumn(columns ...string) InsertQuery\n\tReturning(columns ...string) InsertQuery\n\n\t// Execution\n\tExec(ctx context.Context) (Result, error)\n\tScan(ctx context.Context, dest interface{}) error\n}\n```\nInsertQuery interface for building INSERT queries\n\n```go\ntype Metadata struct {\n\tTotal     int64  `json:\"total\"`\n\tCount     int64  `json:\"count\"`\n\tFiltered  int64  `json:\"filtered\"`\n\tLimit     int    `json:\"limit\"`\n\tOffset    int    `json:\"offset\"`\n\tRowNumber *int64 `json:\"row_number,omitempty\"`\n}\n```\n\n```go\ntype ModelRegistry interface {\n\tRegisterModel(name string, model interface{}) error\n\tGetModel(name string) (interface{}, error)\n\tGetAllModels() map[string]interface{}\n\tGetModelByEntity(schema, entity string) (interface{}, error)\n}\n```\nModelRegistry manages model registration and retrieval\n\n```go\ntype NestedCUDProcessor struct {\n\t// contains filtered or unexported fields\n}\n```\nNestedCUDProcessor handles recursive processing of nested object graphs\n\n```go\nfunc NewNestedCUDProcessor(db Database, registry ModelRegistry, relationshipHelper RelationshipInfoProvider) *NestedCUDProcessor\n```\nNewNestedCUDProcessor creates a new nested CUD processor\n\n```go\nfunc (p *NestedCUDProcessor) ProcessNestedCUD(\n\tctx context.Context,\n\toperation string,\n\tdata map[string]interface{},\n\tmodel interface{},\n\tparentIDs map[string]interface{},\n\ttableName string,\n) (*ProcessResult, error)\n```\nProcessNestedCUD recursively processes nested object graphs for Create, Update, Delete operations with automatic foreign key resolution\n\n```go\ntype Parameter struct {\n\tName     string `json:\"name\"`\n\tValue    string `json:\"value\"`\n\tSequence *int   `json:\"sequence\"`\n}\n```\n\n```go\ntype PreloadOption struct {\n\tRelation    string            `json:\"relation\"`\n\tTableName   string            `json:\"table_name\"` // Actual database table name (e.g., \"mastertaskitem\")\n\tColumns     []string          `json:\"columns\"`\n\tOmitColumns []string          `json:\"omit_columns\"`\n\tSort        []SortOption      `json:\"sort\"`\n\tFilters     []FilterOption    `json:\"filters\"`\n\tWhere       string            `json:\"where\"`\n\tLimit       *int              `json:\"limit\"`\n\tOffset      *int              `json:\"offset\"`\n\tUpdatable   *bool             `json:\"updateable\"`  // if true, the relation can be updated\n\tComputedQL  map[string]string `json:\"computed_ql\"` // Computed columns as SQL expressions\n\tRecursive   bool              `json:\"recursive\"`   // if true, preload recursively up to 5 levels\n\n\t// Relationship keys from XFiles - used to build proper foreign key filters\n\tPrimaryKey        string `json:\"primary_key\"`         // Primary key of the related table\n\tRelatedKey        string `json:\"related_key\"`         // For child tables: column in child that references parent\n\tForeignKey        string `json:\"foreign_key\"`         // For parent tables: column in current table that references parent\n\tRecursiveChildKey string `json:\"recursive_child_key\"` // For recursive tables: FK column used for recursion (e.g., \"rid_parentmastertaskitem\")\n\n\t// Custom SQL JOINs from XFiles - used when preload needs additional joins\n\tSqlJoins    []string `json:\"sql_joins\"`    // Custom SQL JOIN clauses\n\tJoinAliases []string `json:\"join_aliases\"` // Extracted table aliases from SqlJoins for validation\n}\n```\n\n```go\ntype PrimaryKeyNameProvider interface {\n\tGetIDName() string\n}\n```\nPrimaryKeyNameProvider interface for models that provide primary key column names\n\n```go\ntype ProcessResult struct {\n\tID           interface{}            // The ID of the processed record\n\tAffectedRows int64                  // Number of rows affected\n\tData         map[string]interface{} // The processed data\n\tRelationData map[string]interface{} // Data from processed relations\n}\n```\nProcessResult contains the result of processing a CUD operation\n\n```go\ntype QueryHandler interface {\n\tSpecHandler\n}\n```\nQueryHandler interface for handlers that execute SQL queries This is implemented by funcspec.Handler Note: funcspec uses standard http.ResponseWriter and \\*http.Request instead of common interfaces\n\n```go\ntype RelationshipInfo struct {\n\tFieldName    string      `json:\"field_name\"`\n\tJSONName     string      `json:\"json_name\"`\n\tRelationType string      `json:\"relation_type\"` // \"belongsTo\", \"hasMany\", \"hasOne\", \"many2many\"\n\tForeignKey   string      `json:\"foreign_key\"`\n\tReferences   string      `json:\"references\"`\n\tJoinTable    string      `json:\"join_table\"`\n\tRelatedModel interface{} `json:\"related_model\"`\n}\n```\nRelationshipInfo contains information about a model relationship\n\n```go\nfunc GetRelationshipInfo(modelType reflect.Type, relationName string) *RelationshipInfo\n```\nGetRelationshipInfo analyzes a model type and extracts relationship metadata for a specific relation field identified by its JSON name. Returns nil if the field is not found or is not a valid relationship.\n\n```go\ntype RelationshipInfoProvider interface {\n\tGetRelationshipInfo(modelType reflect.Type, relationName string) *RelationshipInfo\n}\n```\nRelationshipInfoProvider interface for handlers that can provide relationship info\n\n```go\ntype Request interface {\n\tMethod() string\n\tURL() string\n\tHeader(key string) string\n\tAllHeaders() map[string]string // Get all headers as a map\n\tBody() ([]byte, error)\n\tPathParam(key string) string\n\tQueryParam(key string) string\n\tAllQueryParams() map[string]string // Get all query parameters as a map\n\tUnderlyingRequest() *http.Request  // Get the underlying *http.Request for forwarding to other handlers\n}\n```\nRequest interface abstracts HTTP request\n\n```go\ntype RequestBody struct {\n\tOperation string         `json:\"operation\"`\n\tData      interface{}    `json:\"data\"`\n\tID        *int64         `json:\"id\"`\n\tOptions   RequestOptions `json:\"options\"`\n}\n```\n\n```go\ntype RequestOptions struct {\n\tPreload         []PreloadOption  `json:\"preload\"`\n\tColumns         []string         `json:\"columns\"`\n\tOmitColumns     []string         `json:\"omit_columns\"`\n\tFilters         []FilterOption   `json:\"filters\"`\n\tSort            []SortOption     `json:\"sort\"`\n\tLimit           *int             `json:\"limit\"`\n\tOffset          *int             `json:\"offset\"`\n\tCustomOperators []CustomOperator `json:\"customOperators\"`\n\tComputedColumns []ComputedColumn `json:\"computedColumns\"`\n\tParameters      []Parameter      `json:\"parameters\"`\n\n\t// Cursor pagination\n\tCursorForward  string  `json:\"cursor_forward\"`\n\tCursorBackward string  `json:\"cursor_backward\"`\n\tFetchRowNumber *string `json:\"fetch_row_number\"`\n\n\t// VectorSearch performs a pgvector nearest-neighbour ordering (KNN) and\n\t// optionally returns the computed distance as an extra column.\n\tVectorSearch *VectorSearchOption `json:\"vector_search\"`\n\n\t// Join table aliases (used for validation of prefixed columns in filters/sorts)\n\t// Not serialized to JSON as it's internal validation state\n\tJoinAliases []string `json:\"-\"`\n}\n```\n\n```go\ntype Response struct {\n\tSuccess  bool        `json:\"success\"`\n\tData     interface{} `json:\"data\"`\n\tMetadata *Metadata   `json:\"metadata,omitempty\"`\n\tError    *APIError   `json:\"error,omitempty\"`\n}\n```\nResponse structures\n\n```go\ntype ResponseWriter interface {\n\tSetHeader(key, value string)\n\tWriteHeader(statusCode int)\n\tWrite(data []byte) (int, error)\n\tWriteJSON(data interface{}) error\n\tUnderlyingResponseWriter() http.ResponseWriter // Get the underlying http.ResponseWriter for forwarding to other handlers\n}\n```\nResponseWriter interface abstracts HTTP response\n\n```go\ntype Result interface {\n\tRowsAffected() int64\n\tLastInsertId() (int64, error)\n}\n```\nResult interface for query execution results\n\n```go\ntype RouteRegistration interface {\n\tMethods(methods ...string) RouteRegistration\n\tPathPrefix(prefix string) RouteRegistration\n}\n```\nRouteRegistration allows method chaining for route configuration\n\n```go\ntype Router interface {\n\tHandleFunc(pattern string, handler HTTPHandlerFunc) RouteRegistration\n\tServeHTTP(w ResponseWriter, r Request)\n}\n```\nRouter interface for HTTP router abstraction\n\n```go\ntype SQLDBProvider interface {\n\t// SQLDB returns the current underlying *sql.DB. After an adapter reconnects it\n\t// returns the new handle, so do not cache it across reconnects.\n\tSQLDB() *sql.DB\n}\n```\nSQLDBProvider is implemented by adapters that wrap a \\*sql.DB (directly or through an ORM). It lets packages that work on database/sql, such as pkg/security/lookup, reuse the connection an application already configured. Transaction adapters do not implement it.\n\n```go\ntype SQLError struct {\n\tErr error\n\tSQL string\n}\n```\nSQLError wraps a database error together with the SQL that caused it, so callers can surface the query in API error responses for easier debugging.\n\n```go\nfunc (e *SQLError) Error() string\n```\n\n```go\nfunc (e *SQLError) Unwrap() error\n```\n\n```go\ntype SchemaProvider interface {\n\tSchemaName() string\n}\n```\nSchemaProvider interface for models that provide schema names\n\n```go\ntype SelectQuery interface {\n\tModel(model interface{}) SelectQuery\n\tTable(table string) SelectQuery\n\tColumn(columns ...string) SelectQuery\n\tColumnExpr(query string, args ...interface{}) SelectQuery\n\tWhere(query string, args ...interface{}) SelectQuery\n\tWhereOr(query string, args ...interface{}) SelectQuery\n\tJoin(query string, args ...interface{}) SelectQuery\n\tLeftJoin(query string, args ...interface{}) SelectQuery\n\tPreload(relation string, conditions ...interface{}) SelectQuery\n\tPreloadRelation(relation string, apply ...func(SelectQuery) SelectQuery) SelectQuery\n\tJoinRelation(relation string, apply ...func(SelectQuery) SelectQuery) SelectQuery\n\tOrder(order string) SelectQuery\n\tOrderExpr(order string, args ...interface{}) SelectQuery\n\tLimit(n int) SelectQuery\n\tOffset(n int) SelectQuery\n\tGroup(group string) SelectQuery\n\tHaving(having string, args ...interface{}) SelectQuery\n\n\t// Execution methods\n\tScan(ctx context.Context, dest interface{}) error\n\tScanModel(ctx context.Context) error\n\tCount(ctx context.Context) (int, error)\n\tExists(ctx context.Context) (bool, error)\n}\n```\nSelectQuery interface for building SELECT queries (compatible with both GORM and Bun)\n\n```go\nfunc ApplySelectColumns(query SelectQuery, model interface{}, tableAlias string, columns []string) SelectQuery\n```\nApplySelectColumns adds the requested columns to query, resolving any that are JSON sub-field references (data-\u003e\u003e'x', data#\u003e\u003e'{a,b}', or the dotted data.x shorthand for a JSON column) into safe parameterised expressions with a deterministic alias. Plain columns are passed through reflection.ExtractSourceColumn exactly as before. tableAlias, when non-empty, qualifies JSON base columns.\n\n```go\ntype SortOption struct {\n\tColumn    string `json:\"column\"`\n\tDirection string `json:\"direction\"`\n}\n```\n\n```go\nfunc ResolveSortColumns(sort []SortOption, pkName string) []SortOption\n```\nResolveSortColumns returns a copy of sort with any PrimaryKeySortColumn entries replaced by pkName. If pkName is empty, matching entries are dropped since there is no column to sort by.\n\n```go\ntype SpecHandler interface {\n\t// GetDatabase returns the underlying database connection\n\tGetDatabase() Database\n}\n```\nSpecHandler interface represents common functionality across all spec handlers This is the base interface implemented by:\n\n  - resolvespec.Handler: Handles CRUD operations via request body with explicit operation field\n  - restheadspec.Handler: Handles CRUD operations via HTTP methods (GET/POST/PUT/DELETE)\n  - funcspec.Handler: Handles custom SQL query execution with dynamic parameters\n\nThe interface hierarchy is:\n\n\tSpecHandler (base)\n\t├── CRUDHandler (resolvespec, restheadspec)\n\t└── QueryHandler (funcspec)\n\n```go\ntype StandardRequest struct {\n\t// contains filtered or unexported fields\n}\n```\nStandardRequest adapts \\*http.Request to Request interface\n\n```go\nfunc (s *StandardRequest) AllHeaders() map[string]string\n```\n\n```go\nfunc (s *StandardRequest) AllQueryParams() map[string]string\n```\n\n```go\nfunc (s *StandardRequest) Body() ([]byte, error)\n```\n\n```go\nfunc (s *StandardRequest) Header(key string) string\n```\n\n```go\nfunc (s *StandardRequest) Method() string\n```\n\n```go\nfunc (s *StandardRequest) PathParam(key string) string\n```\n\n```go\nfunc (s *StandardRequest) QueryParam(key string) string\n```\n\n```go\nfunc (s *StandardRequest) URL() string\n```\n\n```go\nfunc (s *StandardRequest) UnderlyingRequest() *http.Request\n```\n\n```go\ntype StandardResponseWriter struct {\n\t// contains filtered or unexported fields\n}\n```\nStandardResponseWriter adapts http.ResponseWriter to ResponseWriter interface\n\n```go\nfunc (s *StandardResponseWriter) SetHeader(key, value string)\n```\n\n```go\nfunc (s *StandardResponseWriter) UnderlyingResponseWriter() http.ResponseWriter\n```\n\n```go\nfunc (s *StandardResponseWriter) Write(data []byte) (int, error)\n```\n\n```go\nfunc (s *StandardResponseWriter) WriteHeader(statusCode int)\n```\n\n```go\nfunc (s *StandardResponseWriter) WriteJSON(data interface{}) error\n```\n\n```go\ntype TableAliasProvider interface {\n\tTableAlias() string\n}\n```\n\n```go\ntype TableMetadata struct {\n\tSchema    string   `json:\"schema\"`\n\tTable     string   `json:\"table\"`\n\tColumns   []Column `json:\"columns\"`\n\tRelations []string `json:\"relations\"`\n}\n```\n\n```go\ntype TableNameProvider interface {\n\tTableName() string\n}\n```\nTableNameProvider interface for models that provide table names\n\n```go\ntype TxContext interface {\n\tSetTx(tx Database)\n}\n```\nTxContext is implemented by a spec's HookContext so RunRequestTx can point it at the transaction it opens.\n\n```go\ntype UpdateQuery interface {\n\tModel(model interface{}) UpdateQuery\n\tTable(table string) UpdateQuery\n\tSet(column string, value interface{}) UpdateQuery\n\tSetMap(values map[string]interface{}) UpdateQuery\n\t// ExcludeColumn omits columns from a Model()-based UPDATE (e.g. generated columns).\n\tExcludeColumn(columns ...string) UpdateQuery\n\tWhere(query string, args ...interface{}) UpdateQuery\n\tReturning(columns ...string) UpdateQuery\n\n\t// Execution\n\tExec(ctx context.Context) (Result, error)\n}\n```\nUpdateQuery interface for building UPDATE queries\n\n```go\ntype ValidateAndUnwrapModelResult struct {\n\tModelType    reflect.Type\n\tModel        interface{}\n\tModelPtr     interface{}\n\tOriginalType reflect.Type\n}\n```\nValidateAndUnwrapModelResult contains the result of model validation\n\n```go\nfunc ValidateAndUnwrapModel(model interface{}) (*ValidateAndUnwrapModelResult, error)\n```\nValidateAndUnwrapModel validates that a model is a struct type and unwraps pointers, slices, and arrays to get to the base struct type. Returns an error if the model is not a valid struct type.\n\n```go\ntype VectorSearchOption struct {\n\tColumn    string    `json:\"column\"`\n\tVector    []float32 `json:\"vector\"`\n\tMetric    string    `json:\"metric\"`    // \"l2\" (default) | \"cosine\" | \"ip\"\n\tAs        string    `json:\"as\"`        // distance column alias; default \"_distance\"\n\tDirection string    `json:\"direction\"` // \"asc\" (default) | \"desc\"\n}\n```\nVectorSearchOption describes a pgvector KNN search: order rows by the distance between Column and Vector using Metric, and (when As is set) select that distance as an additional result column.\n\n```go\ntype WhereGrouper interface {\n\tWhereGroup(fn func(SelectQuery) SelectQuery) SelectQuery\n}\n```\nWhereGrouper is implemented by query builders that can wrap a set of conditions (including WhereOr) in one parenthesised group that is ANDed with the rest of the query. It is optional so existing SelectQuery implementations keep compiling.\n\n","path":"github.com/bitechdev/ResolveSpec/pkg/common","name":"common","synopsis":"","isRedistributable":true}
