{"modulePath":"github.com/aalemi-dev/stdlib-lab/postgres","version":"v1.3.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package postgres\n\nPackage postgres provides a PostgreSQL client built on top of GORM.\n\nThe package exposes a small, database-agnostic interface (\\`Client\\`) plus a fluent query builder (\\`QueryBuilder\\`). The concrete implementation (\\`\\*Postgres\\`) wraps a \\`\\*gorm.DB\\` and adds:\n\n  - Connection establishment + pool configuration\n  - Periodic health checks and automatic reconnection (via \\`MonitorConnection\\` + \\`RetryConnection\\`)\n  - Standardized CRUD and query-builder helpers\n  - Optional error normalization (\\`TranslateError\\`)\n\n### Concurrency model {#hdr-Concurrency_model}\n\nThe active \\`\\*gorm.DB\\` connection pointer is stored in an \\`atomic.Pointer\\`. Calls that need a DB snapshot simply load the pointer and run the operation without holding any package-level locks. Reconnection swaps the pointer atomically.\n\nBasic usage\n\n\tcfg := postgres.Config{\n\t    Connection: postgres.Connection{\n\t        Host:     \"localhost\",\n\t        Port:     \"5432\",\n\t        User:     \"postgres\",\n\t        Password: \"password\",\n\t        DbName:   \"mydb\",\n\t        SSLMode:  \"disable\",\n\t    },\n\t}\n\n\tpg, err := postgres.NewPostgres(cfg)\n\tif err != nil {\n\t    // handle\n\t}\n\tdefer pg.GracefulShutdown()\n\n\tvar users []User\n\tif err := pg.Find(ctx, \u0026users, \"active = ?\", true); err != nil {\n\t    // handle\n\t}\n\nTransaction usage\n\n\terr := pg.Transaction(ctx, func(tx postgres.Client) error {\n\t    if err := tx.Create(ctx, \u0026User{Name: \"Alice\"}); err != nil {\n\t        return err\n\t    }\n\t    return nil\n\t})\n\n### Observability (Observer hook) {#hdr-Observability__Observer_hook_}\n\nThe Postgres client supports optional observability through the unified \\`observability.Observer\\` interface (\\`github.com/aalemi-dev/stdlib-lab/observability\\`). If an observer is attached, it will be notified after each operation completes (success or error) with an \\`observability.OperationContext\\`.\n\nNon-Fx usage (builder pattern):\n\n\tpg, err := postgres.NewPostgres(cfg)\n\tif err != nil {\n\t    return err\n\t}\n\tpg = pg.WithObserver(myObserver)\n\nFx usage (optional injection):\n\n\tapp := fx.New(\n\t    postgres.FXModule,\n\t    fx.Provide(loadPostgresConfig),\n\t    fx.Provide(func() observability.Observer {\n\t        return myObserver\n\t    }),\n\t)\n\nThe Postgres client emits (at least) the following operation names:\n\n  - Basic ops: \"find\", \"first\", \"create\", \"save\", \"update\", \"update\\_column\", \"update\\_columns\", \"update\\_where\", \"delete\", \"count\", \"exec\"\n  - Query builder terminal ops: \"scan\", \"last\", \"pluck\", \"create\\_in\\_batches\", \"first\\_or\\_init\", \"first\\_or\\_create\"\n  - Transactions: \"transaction\"\n  - Migrations: \"auto\\_migrate\", \"migrate\\_up\", \"migrate\\_down\", \"migration\\_status\"\n\nResource conventions:\n\n  - Resource: table name when available (otherwise falls back to database name)\n  - SubResource: optional extra context (e.g. migration id / migrations dir)\n\n### Fx integration {#hdr-Fx_integration}\n\nThe package provides \\`FXModule\\` which constructs \\`\\*Postgres\\` and also exposes it as the \\`Client\\` interface, plus lifecycle hooks for starting/stopping monitoring.\n\n\tapp := fx.New(\n\t    postgres.FXModule,\n\t    fx.Provide(loadPostgresConfig),\n\t)\n\nPackage postgres provides PostgreSQL database operations with an interface-first design. The interfaces defined here (Client, QueryBuilder) can be implemented by other database packages (like mariadb) to provide a consistent API across different databases.\n\n## Constants\n\n```go\nconst (\n\t// DistanceL2 is Euclidean distance. Pairs with VectorL2Ops / SparseVectorL2Ops.\n\tDistanceL2 = \"\u003c-\u003e\"\n\t// DistanceInnerProduct is negative inner product. Pairs with VectorInnerProductOps /\n\t// SparseVectorInnerProductOps. Fastest when vectors are unit-normalized.\n\tDistanceInnerProduct = \"\u003c#\u003e\"\n\t// DistanceCosine is cosine distance. Pairs with VectorCosineOps / SparseVectorCosineOps.\n\t// Common default for unnormalized LLM embeddings.\n\tDistanceCosine = \"\u003c=\u003e\"\n\t// DistanceL1 is Manhattan distance. Pairs with VectorL1Ops.\n\t// Requires pgvector 0.7+. Not supported for sparsevec.\n\tDistanceL1 = \"\u003c+\u003e\"\n)\n```\nDistance operators used in similarity queries: ORDER BY column \\\u003cop\u003e target.\n\nThe operator you choose must match the operator class of any index on the column — otherwise Postgres silently falls back to a sequential scan and the index provides no benefit.\n\n```go\nconst (\n\tVectorL2Ops           = \"vector_l2_ops\"\n\tVectorInnerProductOps = \"vector_ip_ops\"\n\tVectorCosineOps       = \"vector_cosine_ops\"\n\tVectorL1Ops           = \"vector_l1_ops\" // HNSW only; pgvector 0.7+\n)\n```\nOperator classes for indexing dense \\`vector\\` columns. The class must match the distance operator used at query time.\n\n```go\nconst (\n\tSparseVectorL2Ops           = \"sparsevec_l2_ops\"\n\tSparseVectorInnerProductOps = \"sparsevec_ip_ops\"\n\tSparseVectorCosineOps       = \"sparsevec_cosine_ops\"\n)\n```\nOperator classes for indexing \\`sparsevec\\` columns. Only HNSW indexes support sparsevec — IVFFlat does not.\n\n## Variables\n\n```go\nvar (\n\t// ErrRecordNotFound is returned when a query doesn't find any matching records\n\tErrRecordNotFound = errors.New(\"record not found\")\n\n\t// ErrDuplicateKey is returned when an insert or update violates a unique constraint\n\tErrDuplicateKey = errors.New(\"duplicate key violation\")\n\n\t// ErrForeignKey is returned when an operation violates a foreign key constraint\n\tErrForeignKey = errors.New(\"foreign key violation\")\n\n\t// ErrInvalidData is returned when the data being saved doesn't meet validation rules\n\tErrInvalidData = errors.New(\"invalid data\")\n\n\t// ErrConnectionFailed is returned when database connection cannot be established\n\tErrConnectionFailed = errors.New(\"database connection failed\")\n\n\t// ErrTransactionFailed is returned when a transaction fails to commit or rollback\n\tErrTransactionFailed = errors.New(\"transaction failed\")\n\n\t// ErrQueryTimeout is returned when a query exceeds the allowed timeout\n\tErrQueryTimeout = errors.New(\"query timeout exceeded\")\n\n\t// ErrInvalidQuery is returned when the SQL query is malformed or invalid\n\tErrInvalidQuery = errors.New(\"invalid query\")\n\n\t// ErrPermissionDenied is returned when the user lacks necessary permissions\n\tErrPermissionDenied = errors.New(\"permission denied\")\n\n\t// ErrTableNotFound is returned when trying to access a non-existent table\n\tErrTableNotFound = errors.New(\"table not found\")\n\n\t// ErrColumnNotFound is returned when trying to access a non-existent column\n\tErrColumnNotFound = errors.New(\"column not found\")\n\n\t// ErrConstraintViolation is returned for general constraint violations\n\tErrConstraintViolation = errors.New(\"constraint violation\")\n\n\t// ErrCheckConstraintViolation is returned when a check constraint is violated\n\tErrCheckConstraintViolation = errors.New(\"check constraint violation\")\n\n\t// ErrNotNullViolation is returned when trying to insert null into a not-null column\n\tErrNotNullViolation = errors.New(\"not null constraint violation\")\n\n\t// ErrDataTooLong is returned when data exceeds column length limits\n\tErrDataTooLong = errors.New(\"data too long for column\")\n\n\t// ErrDeadlock is returned when a deadlock is detected during transaction\n\tErrDeadlock = errors.New(\"deadlock detected\")\n\n\t// ErrLockTimeout is returned when unable to acquire lock within timeout\n\tErrLockTimeout = errors.New(\"lock acquisition timeout\")\n\n\t// ErrInvalidDataType is returned when data type conversion fails\n\tErrInvalidDataType = errors.New(\"invalid data type\")\n\n\t// ErrDivisionByZero is returned for division by zero operations\n\tErrDivisionByZero = errors.New(\"division by zero\")\n\n\t// ErrNumericOverflow is returned when numeric operation causes overflow\n\tErrNumericOverflow = errors.New(\"numeric value overflow\")\n\n\t// ErrDiskFull is returned when database storage is full\n\tErrDiskFull = errors.New(\"disk full\")\n\n\t// ErrTooManyConnections is returned when connection pool is exhausted\n\tErrTooManyConnections = errors.New(\"too many connections\")\n\n\t// ErrInvalidJSON is returned when JSON data is malformed\n\tErrInvalidJSON = errors.New(\"invalid JSON data\")\n\n\t// ErrIndexCorruption is returned when database index is corrupted\n\tErrIndexCorruption = errors.New(\"index corruption detected\")\n\n\t// ErrConfigurationError is returned for database configuration issues\n\tErrConfigurationError = errors.New(\"database configuration error\")\n\n\t// ErrUnsupportedOperation is returned for operations not supported by the database\n\tErrUnsupportedOperation = errors.New(\"unsupported operation\")\n\n\t// ErrMigrationFailed is returned when database migration fails\n\tErrMigrationFailed = errors.New(\"migration failed\")\n\n\t// ErrBackupFailed is returned when database backup operation fails\n\tErrBackupFailed = errors.New(\"backup operation failed\")\n\n\t// ErrRestoreFailed is returned when database restore operation fails\n\tErrRestoreFailed = errors.New(\"restore operation failed\")\n\n\t// ErrSchemaValidation is returned when schema validation fails\n\tErrSchemaValidation = errors.New(\"schema validation failed\")\n\n\t// ErrSerializationFailure is returned when transaction serialization fails\n\tErrSerializationFailure = errors.New(\"serialization failure\")\n\n\t// ErrInsufficientPrivileges is returned when user lacks required privileges\n\tErrInsufficientPrivileges = errors.New(\"insufficient privileges\")\n\n\t// ErrInvalidPassword is returned for authentication failures\n\tErrInvalidPassword = errors.New(\"invalid password\")\n\n\t// ErrAccountLocked is returned when user account is locked\n\tErrAccountLocked = errors.New(\"account locked\")\n\n\t// ErrDatabaseNotFound is returned when specified database doesn't exist\n\tErrDatabaseNotFound = errors.New(\"database not found\")\n\n\t// ErrSchemaNotFound is returned when specified schema doesn't exist\n\tErrSchemaNotFound = errors.New(\"schema not found\")\n\n\t// ErrFunctionNotFound is returned when specified function doesn't exist\n\tErrFunctionNotFound = errors.New(\"function not found\")\n\n\t// ErrTriggerNotFound is returned when specified trigger doesn't exist\n\tErrTriggerNotFound = errors.New(\"trigger not found\")\n\n\t// ErrIndexNotFound is returned when specified index doesn't exist\n\tErrIndexNotFound = errors.New(\"index not found\")\n\n\t// ErrViewNotFound is returned when specified view doesn't exist\n\tErrViewNotFound = errors.New(\"view not found\")\n\n\t// ErrSequenceNotFound is returned when specified sequence doesn't exist\n\tErrSequenceNotFound = errors.New(\"sequence not found\")\n\n\t// ErrInvalidCursor is returned when cursor operation fails\n\tErrInvalidCursor = errors.New(\"invalid cursor\")\n\n\t// ErrCursorNotFound is returned when specified cursor doesn't exist\n\tErrCursorNotFound = errors.New(\"cursor not found\")\n\n\t// ErrStatementTimeout is returned when statement execution exceeds timeout\n\tErrStatementTimeout = errors.New(\"statement timeout\")\n\n\t// ErrIdleInTransaction is returned when transaction is idle too long\n\tErrIdleInTransaction = errors.New(\"idle in transaction timeout\")\n\n\t// ErrConnectionLost is returned when database connection is lost\n\tErrConnectionLost = errors.New(\"connection lost\")\n\n\t// ErrProtocolViolation is returned for database protocol violations\n\tErrProtocolViolation = errors.New(\"protocol violation\")\n\n\t// ErrInternalError is returned for internal database errors\n\tErrInternalError = errors.New(\"internal database error\")\n\n\t// ErrSystemError is returned for system-level database errors\n\tErrSystemError = errors.New(\"system error\")\n)\n```\nCommon database error types that can be used by consumers of this package. These provide a standardized set of errors that abstract away the underlying database-specific error details.\n\n```go\nvar FXModule = fx.Module(\"postgres\",\n\tfx.Provide(\n\t\tNewPostgresClientWithDI,\n\t\tfx.Annotate(\n\t\t\tProvideClient,\n\t\t\tfx.As(new(Client)),\n\t\t),\n\t),\n\tfx.Invoke(RegisterPostgresLifecycle),\n)\n```\nFXModule is an fx module that provides the Postgres database component. It registers the Postgres constructor for dependency injection and sets up lifecycle hooks to properly initialize and shut down the database connection.\n\nThis module provides:\n\n  - \\*Postgres (concrete type) - for direct use and lifecycle management\n  - Client (interface) - for consumers who want database abstraction\n\nConsumers can inject either:\n\n  - \\*Postgres for full access to all methods\n  - Client for interface-based programming\n\n## Functions\n\n```go\nfunc RegisterPostgresLifecycle(params PostgresLifeCycleParams)\n```\nRegisterPostgresLifecycle registers lifecycle hooks for the Postgres database component. It sets up: 1. Connection monitoring on the application starts 2. Automatic reconnection mechanism on application start 3. Graceful shutdown of database connections on application stop\n\nThe function uses a WaitGroup to ensure that all goroutines complete before the application terminates.\n\n## Types\n\n```go\ntype Client interface {\n\t// Basic CRUD operations\n\tFind(ctx context.Context, dest interface{}, conditions ...interface{}) error\n\tFirst(ctx context.Context, dest interface{}, conditions ...interface{}) error\n\tCreate(ctx context.Context, value interface{}) error\n\tSave(ctx context.Context, value interface{}) error\n\tUpdate(ctx context.Context, model interface{}, attrs interface{}) (int64, error)\n\tUpdateColumn(ctx context.Context, model interface{}, columnName string, value interface{}) (int64, error)\n\tUpdateColumns(ctx context.Context, model interface{}, columnValues map[string]interface{}) (int64, error)\n\tDelete(ctx context.Context, value interface{}, conditions ...interface{}) (int64, error)\n\tCount(ctx context.Context, model interface{}, count *int64, conditions ...interface{}) error\n\tUpdateWhere(ctx context.Context, model interface{}, attrs interface{}, condition string, args ...interface{}) (int64, error)\n\tExec(ctx context.Context, sql string, values ...interface{}) (int64, error)\n\n\t// Query builder for complex queries\n\t// Returns the QueryBuilder interface for method chaining\n\tQuery(ctx context.Context) QueryBuilder\n\n\t// Transaction support\n\t// The callback function receives a Client interface (not a concrete type)\n\t// This allows the same transaction code to work with any database implementation\n\tTransaction(ctx context.Context, fn func(tx Client) error) error\n\n\t// Raw GORM access for advanced use cases\n\t// Use this when you need direct access to GORM's functionality\n\tDB() *gorm.DB\n\n\t// Error translation / classification.\n\t//\n\t// std deliberately returns raw GORM/driver errors from CRUD/query methods.\n\t// Use TranslateError to normalize errors to std's exported sentinels (ErrRecordNotFound,\n\t// ErrDuplicateKey, ...), especially when working with the Client interface (e.g. inside\n\t// Transaction callbacks).\n\tTranslateError(err error) error\n\tGetErrorCategory(err error) ErrorCategory\n\tIsRetryable(err error) bool\n\tIsTemporary(err error) bool\n\tIsCritical(err error) bool\n\n\t// Lifecycle management\n\tGracefulShutdown() error\n}\n```\nClient is the main database client interface that provides CRUD operations, query building, and transaction management.\n\nThis interface allows applications to:\n\n  - Switch between PostgreSQL and MariaDB without code changes\n  - Write database-agnostic business logic\n  - Mock database operations easily for testing\n  - Depend on abstractions rather than concrete implementations\n\nThe Postgres type implements this interface.\n\n```go\nfunc ProvideClient(pg *Postgres) Client\n```\nProvideClient wraps the concrete \\*Postgres and returns it as Client interface. This enables applications to depend on the interface rather than concrete type.\n\n```go\ntype Config struct {\n\t// Connection contains the essential parameters needed to establish a database connection\n\tConnection Connection\n\n\t// ConnectionDetails contains configuration for the connection pool behavior\n\tConnectionDetails ConnectionDetails\n}\n```\nConfig represents the complete configuration for a PostgresSQL database connection. It encapsulates both the basic connection parameters and detailed connection pool settings.\n\n```go\ntype Connection struct {\n\t// Host specifies the database server hostname or IP address\n\tHost string\n\n\t// Port specifies the TCP port on which the database server is listening to\n\tPort string\n\n\t// User specifies the database username for authentication\n\tUser string\n\n\t// Password specifies the database user password for authentication\n\tPassword string `json:\"-\"` //nolint:gosec\n\n\t// DbName specifies the name of the database to connect to\n\tDbName string\n\n\t// SSLMode specifies the SSL mode for the connection (e.g., \"disable\", \"require\", \"verify-ca\", \"verify-full\")\n\t// For production environments, it's recommended to use at least \"require\"\n\tSSLMode string\n}\n```\nConnection holds the basic parameters required to connect to a PostgresSQL database. These parameters are used to construct the database connection string.\n\n```go\ntype ConnectionDetails struct {\n\t// MaxOpenConns controls the maximum number of open connections to the database.\n\t// Setting this appropriately helps prevent overwhelming the database with too many connections.\n\t// If set to 0, the package default is used.\n\tMaxOpenConns int\n\n\t// MaxIdleConns controls the maximum number of connections in the idle connection pool.\n\t// A higher value can improve performance under a concurrent load but consumes more resources.\n\t// If set to 0, the package default is used.\n\tMaxIdleConns int\n\n\t// ConnMaxLifetime is the maximum amount of time a connection may be reused.\n\t// Expired connections are closed and removed from the pool during connection acquisition.\n\t// This helps ensure database-enforced timeouts are respected.\n\t// If set to 0, the package default is used.\n\tConnMaxLifetime time.Duration\n}\n```\nConnectionDetails holds configuration settings for the database connection pool. These settings help optimize performance and resource usage by controlling how database connections are created, reused, and expired.\n\n```go\ntype ErrorCategory int\n```\nErrorCategory represents different categories of database errors\n\n```go\nconst (\n\tCategoryUnknown ErrorCategory = iota\n\tCategoryConnection\n\tCategoryQuery\n\tCategoryData\n\tCategoryConstraint\n\tCategoryPermission\n\tCategoryTransaction\n\tCategoryResource\n\tCategorySystem\n\tCategorySchema\n\tCategoryOperation\n)\n```\n\n```go\ntype HNSWOptions struct {\n\t// M is the max number of connections per layer. Higher improves recall\n\t// at the cost of memory and build time.\n\tM int\n\t// EfConstruction is the size of the dynamic candidate list during build.\n\t// Higher improves recall at the cost of build time.\n\tEfConstruction int\n\t// Name overrides the auto-generated index name.\n\tName string\n\t// Concurrently issues CREATE INDEX CONCURRENTLY. Cannot run inside a\n\t// transaction but avoids blocking writes during the build.\n\tConcurrently bool\n}\n```\nHNSWOptions configures an HNSW index build. Zero values defer to pgvector's own defaults (m=16, ef\\_construction=64).\n\n```go\ntype IVFFlatOptions struct {\n\t// Lists is the number of inverted lists to partition vectors into.\n\t// pgvector guidance: rows/1000 up to 1M rows, sqrt(rows) above that.\n\tLists int\n\t// Name overrides the auto-generated index name.\n\tName string\n\t// Concurrently issues CREATE INDEX CONCURRENTLY.\n\tConcurrently bool\n}\n```\nIVFFlatOptions configures an IVFFlat index build. Lists is required.\n\n```go\ntype Logger interface {\n\t// InfoWithContext logs an informational message with trace context.\n\tInfoWithContext(ctx context.Context, msg string, err error, fields ...map[string]interface{})\n\n\t// WarnWithContext logs a warning message with trace context.\n\tWarnWithContext(ctx context.Context, msg string, err error, fields ...map[string]interface{})\n\n\t// ErrorWithContext logs an error message with trace context.\n\tErrorWithContext(ctx context.Context, msg string, err error, fields ...map[string]interface{})\n}\n```\nLogger is an interface that matches the std/v1/logger.Logger interface. It provides context-aware structured logging with optional error and field parameters.\n\n```go\ntype Migration struct {\n\t// ID is a unique identifier for the migration, typically a timestamp (YYYYMMDDHHMMSS)\n\t// that also helps establish the execution order.\n\tID string\n\n\t// Name is a descriptive label for the migration, typically describing what it does.\n\tName string\n\n\t// Type categorizes the migration as either schema or data.\n\tType MigrationType\n\n\t// Direction indicates whether this is an up (apply) or down (rollback) migration.\n\tDirection MigrationDirection\n\n\t// SQL contains the actual SQL statements to execute for this migration.\n\tSQL string\n}\n```\nMigration represents a single database migration with all its metadata and content. Each migration contains the SQL to execute and information about its purpose and identity.\n\n```go\ntype MigrationDirection string\n```\nMigrationDirection specifies the direction of the migration, indicating whether it's applying a change or reverting one.\n\n```go\nconst (\n\t// UpMigration indicates a forward migration that applies a change.\n\tUpMigration MigrationDirection = \"up\"\n\n\t// DownMigration indicates a rollback migration that reverts a change.\n\tDownMigration MigrationDirection = \"down\"\n)\n```\n\n```go\ntype MigrationHistoryRecord struct {\n\t// ID matches the migration ID that was applied.\n\tID string\n\n\t// Name is the descriptive name of the migration.\n\tName string\n\n\t// Type indicates whether this was a schema or data migration.\n\tType string\n\n\t// ExecutedAt records when the migration was applied.\n\tExecutedAt time.Time\n\n\t// ExecutedBy tracks who or what system applied the migration.\n\tExecutedBy string\n\n\t// Duration measures how long the migration took to execute in milliseconds.\n\tDuration int64\n\n\t// Status indicates whether the migration completed successfully or failed.\n\tStatus string\n\n\t// ErrorMessage contains details if the migration failed.\n\tErrorMessage string `gorm:\"type:text\"`\n}\n```\nMigrationHistoryRecord represents a record in the migration history table. It tracks when and how each migration was applied, enabling the system to determine which migrations have been run and providing an audit trail.\n\n```go\ntype MigrationType string\n```\nMigrationType defines the type of migration, categorizing the purpose of the change. This helps track and organize migrations based on their impact on the database.\n\n```go\nconst (\n\t// SchemaType represents schema changes (tables, columns, indexes, etc.)\n\t// These migrations modify the structure of the database.\n\tSchemaType MigrationType = \"schema\"\n\n\t// DataType represents data manipulations (inserts, updates, etc.)\n\t// These migrations modify the content within the database.\n\tDataType MigrationType = \"data\"\n)\n```\n\n```go\ntype Postgres struct {\n\t// contains filtered or unexported fields\n}\n```\nPostgres is a wrapper around gorm.DB that provides connection monitoring, automatic reconnection, and standardized database operations.\n\nImplements both postgres.Client (deprecated) and database.Client interfaces.\n\nConcurrency: the active \\`\\*gorm.DB\\` pointer is stored in an atomic pointer and can be swapped during reconnection without blocking readers.\n\n```go\nfunc NewPostgres(cfg Config) (*Postgres, error)\n```\nNewPostgres creates a new Postgres instance with the provided configuration and Logger. It establishes the initial database connection and sets up the internal state for connection monitoring and recovery. If the initial connection fails, it logs a fatal error and terminates.\n\nReturns \\*Postgres concrete type (following Go best practice: \"accept interfaces, return structs\").\n\n```go\nfunc NewPostgresClientWithDI(params PostgresParams) (*Postgres, error)\n```\nNewPostgresClientWithDI creates a new Postgres Client using dependency injection. This function is designed to be used with Uber's fx dependency injection framework where the Config, Logger, and Observer dependencies are automatically provided via the PostgresParams struct.\n\nParameters:\n\n  - params: A PostgresParams struct containing the Config instance and optionally a Logger and Observer instances required to initialize the Postgres Client. This struct embeds fx.In to enable automatic injection of these dependencies.\n\nReturns:\n\n  - \\*Postgres: A fully initialized Postgres Client (concrete type). The FX module also provides this as Client interface for consumers who want abstraction.\n\nExample usage with fx:\n\n\tapp := fx.New(\n\t    postgres.FXModule,\n\t    logger.FXModule,  // Optional: provides logger\n\t    fx.Provide(\n\t        func() postgres.Config {\n\t            return loadPostgresConfig() // Your config loading function\n\t        },\n\t        func(metrics *prometheus.Metrics) observability.Observer {\n\t            return \u0026MyObserver{metrics: metrics}  // Optional observer\n\t        },\n\t    ),\n\t)\n\nThis function creates the client and injects the optional logger and observer before returning.\n\n```go\nfunc (p *Postgres) AutoMigrate(models ...interface{}) error\n```\nAutoMigrate is a wrapper around GORM's AutoMigrate with additional features. It tracks migrations in the migration history table and provides better error handling.\n\nParameters:\n\n  - models: The GORM models to auto-migrate\n\nReturns a GORM error if any part of the migration process fails.\n\nThis method is useful during development or for simple applications, but for production systems, explicit migrations are recommended.\n\n```go\nfunc (p *Postgres) Count(ctx context.Context, model interface{}, count *int64, conditions ...interface{}) error\n```\nCount determines the number of records that match the given conditions. It populates the count parameter with the result.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - model: The model type to count\n  - count: Pointer to an int64 where the count will be stored\n  - conditions: Query conditions to filter the records to count\n\nReturns a GORM error if the query fails or nil on success. Use TranslateError() to convert to standardized error types if needed.\n\nExample:\n\n\tvar count int64\n\terr := db.Count(ctx, \u0026User{}, \u0026count, \"age \u003e ?\", 18)\n\n```go\nfunc (p *Postgres) Create(ctx context.Context, value interface{}) error\n```\nCreate inserts a new record into the database. It processes the value parameter according to GORM conventions, performing hooks and validations defined on the model.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - value: The struct or slice of structs to be created\n\nReturns a GORM error if the creation fails or nil on success. Use TranslateError() to convert to standardized error types if needed.\n\nExample:\n\n\tuser := User{Name: \"John\", Email: \"john@example.com\"}\n\terr := db.Create(ctx, \u0026user)\n\n```go\nfunc (p *Postgres) CreateHNSWIndex(ctx context.Context, table, column, opClass string, opts HNSWOptions) error\n```\nCreateHNSWIndex creates an HNSW index on (table, column) using the given operator class. The class must match the distance operator used at query time — e.g. VectorCosineOps for \\`ORDER BY col \\\u003c=\u003e ?\\`, or SparseVectorInnerProductOps for sparsevec with \\`\\\u003c#\u003e\\`.\n\nHNSW supports both \\`vector\\` and \\`sparsevec\\` columns (with their respective op classes). For pure dense workloads IVFFlat is also an option.\n\n```go\nfunc (p *Postgres) CreateIVFFlatIndex(ctx context.Context, table, column, opClass string, opts IVFFlatOptions) error\n```\nCreateIVFFlatIndex creates an IVFFlat index on (table, column) using the given operator class. IVFFlat does not support sparsevec — use CreateHNSWIndex for sparse columns.\n\n```go\nfunc (p *Postgres) CreateMigration(migrationsDir, name string, migrationType MigrationType) (string, error)\n```\nCreateMigration generates a new migration file. It creates both up and down migration files with appropriate names and timestamps.\n\nParameters:\n\n  - migrationsDir: Directory where migration files should be created\n  - name: Descriptive name for the migration\n  - migrationType: Whether this is a schema or data migration\n\nReturns the base filename of the created migration or a wrapped error if creation fails.\n\nExample:\n\n\tfilename, err := db.CreateMigration(\"./migrations\", \"create_users_table\", postgres.SchemaType)\n\tif err == nil {\n\t    fmt.Printf(\"Created migration: %s\\n\", filename)\n\t}\n\n```go\nfunc (p *Postgres) DB() *gorm.DB\n```\nDB returns the underlying GORM DB Client instance. This method provides direct access to the database connection while maintaining thread safety through an atomic load.\n\nUse this method when you need to perform operations not covered by the wrapper methods or when you need to access specific GORM functionality. Note that direct usage bypasses some of the safety mechanisms, so use it with care.\n\n```go\nfunc (p *Postgres) Delete(ctx context.Context, value interface{}, conditions ...interface{}) (int64, error)\n```\nDelete removes records that match the given value and conditions from the database. It respects soft delete if implemented on the model.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - value: The model to delete or a slice for batch delete\n  - conditions: Additional conditions to filter records to delete\n\nReturns:\n\n  - int64: Number of rows affected by the delete operation\n  - error: GORM error if the deletion fails, nil on success\n\nExample:\n\n\t// Delete user with ID=1\n\trowsAffected, err := db.Delete(ctx, \u0026User{}, \"id = ?\", 1)\n\tif err != nil {\n\t    return err\n\t}\n\tfmt.Printf(\"Deleted %d rows\\n\", rowsAffected)\n\n\t// Or with a model instance\n\tuser := User{ID: 1}\n\trowsAffected, err := db.Delete(ctx, \u0026user)\n\n```go\nfunc (p *Postgres) EnableVectorExtension(ctx context.Context) error\n```\nEnableVectorExtension installs the pgvector extension in the connected database (CREATE EXTENSION IF NOT EXISTS vector).\n\nThe connecting role must hold CREATE privilege on the database. In managed Postgres this is typically a one-off DBA task, not something the application runs at startup — call this from a setup script or migration, not from a request handler.\n\n```go\nfunc (p *Postgres) Exec(ctx context.Context, sql string, values ...interface{}) (int64, error)\n```\nExec executes raw SQL directly against the database. This is useful for operations not easily expressed through GORM's API or for performance-critical code.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - sql: The SQL statement to execute\n  - values: Parameters for the SQL statement\n\nReturns:\n\n  - int64: Number of rows affected by the SQL execution\n  - error: GORM error if the execution fails, nil on success\n\nExample:\n\n\trowsAffected, err := db.Exec(ctx, \"UPDATE users SET status = ? WHERE last_login \u003c ?\",\n\t                             \"inactive\", time.Now().AddDate(0, -6, 0))\n\tif err != nil {\n\t    return err\n\t}\n\tfmt.Printf(\"Updated %d users\\n\", rowsAffected)\n\n```go\nfunc (p *Postgres) Find(ctx context.Context, dest interface{}, conditions ...interface{}) error\n```\nFind retrieves records from the database that match the given conditions. It populates the dest parameter with the query results.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - dest: Pointer to a slice where the results will be stored\n  - conditions: Optional query conditions (follows GORM conventions)\n\nReturns a GORM error if the query fails or nil on success. Use TranslateError() to convert to standardized error types if needed.\n\nExample:\n\n\tvar users []User\n\terr := db.Find(ctx, \u0026users, \"name LIKE ?\", \"%john%\")\n\n```go\nfunc (p *Postgres) First(ctx context.Context, dest interface{}, conditions ...interface{}) error\n```\nFirst retrieves the first record that matches the given conditions. It populates the dest parameter with the result or returns an error if no matching record exists.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - dest: Pointer to a struct where the result will be stored\n  - conditions: Optional query conditions (follows GORM conventions)\n\nReturns gorm.ErrRecordNotFound if no matching record exists, or another GORM error if the query fails. Use TranslateError() to convert to standardized error types if needed.\n\nExample:\n\n\tvar user User\n\terr := db.First(ctx, \u0026user, \"email = ?\", \"user@example.com\")\n\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t    // Handle not found\n\t}\n\n```go\nfunc (p *Postgres) GetErrorCategory(err error) ErrorCategory\n```\nGetErrorCategory returns the category of the given error\n\n```go\nfunc (p *Postgres) GetMigrationStatus(ctx context.Context, migrationsDir string) ([]map[string]interface{}, error)\n```\nGetMigrationStatus returns the status of all migrations. It compares available migrations with those that have been applied to build a comprehensive status report.\n\nParameters:\n\n  - ctx: Context for database operations\n  - migrationsDir: Directory containing the migration SQL files\n\nReturns a slice of maps with status information for each migration, or a wrapped error if the status cannot be determined. The error wraps the underlying GORM error with additional context.\n\nExample:\n\n\tstatus, err := db.GetMigrationStatus(ctx, \"./migrations\")\n\tif err == nil {\n\t    for _, m := range status {\n\t        fmt.Printf(\"Migration %s: %v\\n\", m[\"id\"], m[\"applied\"])\n\t    }\n\t}\n\n```go\nfunc (p *Postgres) GracefulShutdown() error\n```\n\n```go\nfunc (p *Postgres) IsCritical(err error) bool\n```\nIsCritical returns true if the error indicates a serious system problem\n\n```go\nfunc (p *Postgres) IsRetryable(err error) bool\n```\nIsRetryable returns true if the error might be resolved by retrying the operation\n\n```go\nfunc (p *Postgres) IsTemporary(err error) bool\n```\nIsTemporary returns true if the error is likely temporary and might resolve itself\n\n```go\nfunc (p *Postgres) MigrateDown(ctx context.Context, migrationsDir string) error\n```\nMigrateDown rolls back the last applied migration. It finds the most recently applied migration and executes its corresponding down migration to revert the changes.\n\nParameters:\n\n  - ctx: Context for database operations\n  - migrationsDir: Directory containing the migration SQL files\n\nReturns a wrapped error if the rollback fails or if the down migration can't be found. The error wraps the underlying GORM error with additional context.\n\nExample:\n\n\terr := db.MigrateDown(ctx, \"./migrations\")\n\n```go\nfunc (p *Postgres) MigrateUp(ctx context.Context, migrationsDir string) error\n```\nMigrateUp applies all pending migrations from the specified directory. It identifies which migrations haven't been applied yet, sorts them by ID, and applies them in order within transactions.\n\nParameters:\n\n  - ctx: Context for database operations\n  - migrationsDir: Directory containing the migration SQL files\n\nReturns a wrapped error if any migration fails or if there are issues accessing the migrations. The error wraps the underlying GORM error with additional context.\n\nExample:\n\n\terr := db.MigrateUp(ctx, \"./migrations\")\n\n```go\nfunc (p *Postgres) MonitorConnection(ctx context.Context)\n```\nMonitorConnection periodically checks the health of the database connection and triggers reconnection attempts when necessary. It runs as a goroutine that performs health checks at regular intervals (10 seconds) and signals the RetryConnection goroutine when a failure is detected.\n\nThe function respects context cancellation and shutdown signals, ensuring proper resource cleanup and graceful termination when requested.\n\n```go\nfunc (p *Postgres) Query(ctx context.Context) QueryBuilder\n```\nQuery provides a flexible way to build complex queries. It returns a QueryBuilder interface which can be used to chain query methods in a fluent interface. The builder snapshots the current \\`\\*gorm.DB\\` connection and does not hold any package-level locks while the chain is being built or executed.\n\nParameters:\n\n  - ctx: Context for the database operation\n\nReturns a QueryBuilder interface instance that can be used to construct the query.\n\nNote: QueryBuilder methods return GORM errors directly. Use Postgres.TranslateError() to convert them to standardized error types if needed.\n\nExample:\n\n\tusers := []User{}\n\terr := db.Query(ctx).\n\t    Where(\"age \u003e ?\", 18).\n\t    Order(\"created_at DESC\").\n\t    Limit(10).\n\t    Find(\u0026users)\n\tif err != nil {\n\t    err = db.TranslateError(err) // Optional: translate to standardized error\n\t}\n\n```go\nfunc (p *Postgres) RetryConnection(ctx context.Context)\n```\nRetryConnection continuously attempts to reconnect to the PostgresSQL database when notified of a connection failure. It operates as a goroutine that waits for signals on retryChanSignal before attempting reconnection. The function respects context cancellation and shutdown signals, ensuring graceful termination when requested.\n\nIt implements two nested loops: - The outer loop waits for retry signals - The inner loop attempts reconnection until successful\n\n```go\nfunc (p *Postgres) Save(ctx context.Context, value interface{}) error\n```\nSave updates the database record if the primary key exists, otherwise it creates a new record. It performs a full update of all fields, not just changed fields.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - value: The struct to be saved\n\nReturns a GORM error if the operation fails or nil on success. Use TranslateError() to convert to standardized error types if needed.\n\nExample:\n\n\tuser.Name = \"Updated Name\"\n\terr := db.Save(ctx, \u0026user)\n\n```go\nfunc (p *Postgres) Transaction(ctx context.Context, fn func(tx Client) error) error\n```\nTransaction executes the given function within a database transaction. It creates a transaction-specific Postgres instance and passes it as Client interface. If the function returns an error, the transaction is rolled back; otherwise, it's committed.\n\nThis method provides a clean way to execute multiple database operations as a single atomic unit, with automatic handling of commit/rollback based on the execution result.\n\nReturns a GORM error if the transaction fails or the error returned by the callback function.\n\nExample usage:\n\n\terr := pg.Transaction(ctx, func(tx Client) error {\n\t\tif err := tx.Create(ctx, user); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn tx.Create(ctx, userProfile)\n\t})\n\n```go\nfunc (p *Postgres) TranslateError(err error) error\n```\nTranslateError converts GORM/database-specific errors into standardized application errors. This function provides abstraction from the underlying database implementation details, allowing application code to handle errors in a database-agnostic way.\n\nIt maps common database errors to the standardized error types defined above. If an error doesn't match any known type, it's returned unchanged.\n\n```go\nfunc (p *Postgres) Update(ctx context.Context, model interface{}, attrs interface{}) (int64, error)\n```\nUpdate updates records that match the given model's non-zero fields or primary key. It only updates the fields provided in attrs and only affects records that match the model's primary key or query conditions.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - model: The model instance with primary key set, or struct with query conditions\n  - attrs: Map, struct, or individual field values to update\n\nReturns:\n\n  - int64: Number of rows affected by the update operation\n  - error: GORM error if the update fails, nil on success\n\nNote: The current implementation has a bug where it executes the query twice. This should be fixed to execute only once and return both values properly.\n\nExample:\n\n\t// Update user with ID=1\n\trowsAffected, err := db.Update(ctx, \u0026User{ID: 1}, map[string]interface{}{\n\t    \"name\": \"New Name\",\n\t    \"age\": 30,\n\t})\n\tif err != nil {\n\t    return err\n\t}\n\tfmt.Printf(\"Updated %d rows\\n\", rowsAffected)\n\n```go\nfunc (p *Postgres) UpdateColumn(ctx context.Context, model interface{}, columnName string, value interface{}) (int64, error)\n```\nUpdateColumn updates a single column's value for records that match the given model. Unlike Update, it doesn't run hooks and can be used to update fields that are zero values (like setting a string to empty or a number to zero).\n\nParameters:\n\n  - ctx: Context for the database operation\n  - model: The model instance with primary key set, or struct with query conditions\n  - columnName: Name of the column to update\n  - value: New value for the column\n\nReturns:\n\n  - int64: Number of rows affected by the update operation\n  - error: GORM error if the update fails, nil on success\n\nExample:\n\n\t// Set status to \"inactive\" for user with ID=1\n\trowsAffected, err := db.UpdateColumn(ctx, \u0026User{ID: 1}, \"status\", \"inactive\")\n\tif err != nil {\n\t    return err\n\t}\n\tfmt.Printf(\"Updated %d rows\\n\", rowsAffected)\n\n```go\nfunc (p *Postgres) UpdateColumns(ctx context.Context, model interface{}, columnValues map[string]interface{}) (int64, error)\n```\nUpdateColumns updates multiple columns with name/value pairs for records that match the given model. Like UpdateColumn, it doesn't run hooks and can update zero-value fields.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - model: The model instance with primary key set, or struct with query conditions\n  - columnValues: Map of column names to their new values\n\nReturns:\n\n  - int64: Number of rows affected by the update operation\n  - error: GORM error if the update fails, nil on success\n\nExample:\n\n\t// Update multiple fields for user with ID=1\n\trowsAffected, err := db.UpdateColumns(ctx, \u0026User{ID: 1}, map[string]interface{}{\n\t    \"status\": \"inactive\",\n\t    \"last_login\": time.Now(),\n\t})\n\tif err != nil {\n\t    return err\n\t}\n\tfmt.Printf(\"Updated %d rows\\n\", rowsAffected)\n\n```go\nfunc (p *Postgres) UpdateWhere(ctx context.Context, model interface{}, attrs interface{}, condition string, args ...interface{}) (int64, error)\n```\nUpdateWhere updates records that match the specified WHERE condition. This method provides more flexibility than Update for complex conditions.\n\nParameters:\n\n  - ctx: Context for the database operation\n  - model: The model type to update\n  - attrs: Fields to update (map, struct, or name/value pairs)\n  - condition: WHERE condition as a string\n  - args: Arguments for the WHERE condition\n\nReturns:\n\n  - int64: Number of rows affected by the update operation\n  - error: GORM error if the update fails, nil on success\n\nExample:\n\n\t// Update all users who haven't logged in for 6 months\n\trowsAffected, err := db.UpdateWhere(ctx, \u0026User{},\n\t                                    map[string]interface{}{\"status\": \"inactive\"},\n\t                                    \"last_login \u003c ?\",\n\t                                    time.Now().AddDate(0, -6, 0))\n\tif err != nil {\n\t    return err\n\t}\n\tfmt.Printf(\"Updated %d users to inactive status\\n\", rowsAffected)\n\n```go\nfunc (p *Postgres) WithLogger(logger Logger) *Postgres\n```\nWithLogger attaches a logger to the Postgres client for internal logging. This method uses the builder pattern and returns the client for method chaining.\n\nThe logger will be used for lifecycle events, connection monitoring, and background operations.\n\nExample:\n\n\tclient, err := postgres.NewPostgres(config)\n\tif err != nil {\n\t    return err\n\t}\n\tclient = client.WithLogger(myLogger)\n\tdefer client.GracefulShutdown()\n\n```go\nfunc (p *Postgres) WithObserver(observer observability.Observer) *Postgres\n```\nWithObserver attaches an observer to the Postgres client for observability hooks. This method uses the builder pattern and returns the client for method chaining.\n\nThe observer will be notified of all database operations, allowing external systems to track metrics, traces, or other observability data.\n\nExample:\n\n\tclient, err := postgres.NewPostgres(config)\n\tif err != nil {\n\t    return err\n\t}\n\tclient = client.WithObserver(myObserver)\n\tdefer client.GracefulShutdown()\n\n```go\ntype PostgresLifeCycleParams struct {\n\tfx.In\n\n\tLifecycle fx.Lifecycle\n\tPostgres  *Postgres\n}\n```\nPostgresLifeCycleParams groups the dependencies needed for Postgres lifecycle management. This struct combines all the components required to properly manage the lifecycle of a Postgres Client within an fx application, including startup, monitoring, and graceful shutdown.\n\nThe embedded fx.In marker enables automatic injection of the struct fields from the dependency container when this struct is used as a parameter in lifecycle registration functions.\n\n```go\ntype PostgresParams struct {\n\tfx.In\n\n\tConfig   Config\n\tLogger   Logger                 `optional:\"true\"`\n\tObserver observability.Observer `optional:\"true\"`\n}\n```\nPostgresParams groups the dependencies needed to create a Postgres Client via dependency injection. This struct is designed to work with Uber's fx dependency injection framework and provides the necessary parameters for initializing a Postgres database connection.\n\nThe embedded fx.In marker enables automatic injection of the struct fields from the dependency container when this struct is used as a parameter in provider functions.\n\n```go\ntype QueryBuilder interface {\n\t// Query modifiers - these return QueryBuilder for chaining\n\tSelect(query interface{}, args ...interface{}) QueryBuilder\n\tWhere(query interface{}, args ...interface{}) QueryBuilder\n\tOr(query interface{}, args ...interface{}) QueryBuilder\n\tNot(query interface{}, args ...interface{}) QueryBuilder\n\tJoins(query string, args ...interface{}) QueryBuilder\n\tLeftJoin(query string, args ...interface{}) QueryBuilder\n\tRightJoin(query string, args ...interface{}) QueryBuilder\n\tPreload(query string, args ...interface{}) QueryBuilder\n\tGroup(query string) QueryBuilder\n\tHaving(query interface{}, args ...interface{}) QueryBuilder\n\tOrder(value interface{}) QueryBuilder\n\tLimit(limit int) QueryBuilder\n\tOffset(offset int) QueryBuilder\n\tRaw(sql string, values ...interface{}) QueryBuilder\n\tModel(value interface{}) QueryBuilder\n\tDistinct(args ...interface{}) QueryBuilder\n\tTable(name string) QueryBuilder\n\tUnscoped() QueryBuilder\n\tScopes(funcs ...func(*gorm.DB) *gorm.DB) QueryBuilder\n\n\t// Locking methods\n\tForUpdate() QueryBuilder\n\tForShare() QueryBuilder\n\tForUpdateSkipLocked() QueryBuilder\n\tForShareSkipLocked() QueryBuilder\n\tForUpdateNoWait() QueryBuilder\n\tForNoKeyUpdate() QueryBuilder // PostgreSQL-specific\n\tForKeyShare() QueryBuilder    // PostgreSQL-specific\n\n\t// Conflict handling and returning\n\tOnConflict(onConflict interface{}) QueryBuilder\n\tReturning(columns ...string) QueryBuilder\n\n\t// Custom clauses\n\tClauses(conds ...interface{}) QueryBuilder\n\n\t// Terminal operations - these execute the query\n\tScan(dest interface{}) error\n\tFind(dest interface{}) error\n\tFirst(dest interface{}) error\n\tLast(dest interface{}) error\n\tCount(count *int64) error\n\tUpdates(values interface{}) (int64, error)\n\tDelete(value interface{}) (int64, error)\n\tPluck(column string, dest interface{}) (int64, error)\n\tCreate(value interface{}) (int64, error)\n\tCreateInBatches(value interface{}, batchSize int) (int64, error)\n\tFirstOrInit(dest interface{}, conds ...interface{}) error\n\tFirstOrCreate(dest interface{}, conds ...interface{}) error\n\n\t// Utility methods\n\tDone()                // Finalize builder (currently a no-op)\n\tToSubquery() *gorm.DB // Convert to GORM subquery\n}\n```\nQueryBuilder provides a fluent interface for building complex database queries. All chainable methods return the QueryBuilder interface, allowing method chaining. Terminal operations (like Find, First, Create) execute the query and return results.\n\nExample:\n\n\tvar users []User\n\terr := db.Query(ctx).\n\t    Where(\"age \u003e ?\", 18).\n\t    Order(\"created_at DESC\").\n\t    Limit(10).\n\t    Find(\u0026users)\n\n```go\ntype RowScanner interface {\n\t// Scan copies the column values from the current row into the values pointed to by dest.\n\t// The number of values in dest must match the number of columns in the row.\n\tScan(dest ...interface{}) error\n}\n```\nRowScanner provides an interface for scanning a single row of data. It abstracts the process of parsing column values into Go variables, allowing for efficient handling of individual rows returned from a query.\n\n```go\ntype RowsScanner interface {\n\t// Next prepares the next row for reading. It returns false when there are no more rows.\n\tNext() bool\n\n\t// Scan copies column values from the current row into the provided destination variables.\n\tScan(dest ...interface{}) error\n\n\t// Close closes the rows iterator, releasing any associated resources.\n\tClose() error\n\n\t// Err returns any error encountered during iteration.\n\tErr() error\n}\n```\nRowsScanner provides an interface for iterating through rows of data returned by a query. It extends RowScanner functionality with methods for navigation and error handling, allowing for efficient processing of result sets with multiple rows.\n\n```go\ntype SparseVector = pgvector.SparseVector\n```\nSparseVector is a sparse float32 vector mapped to pgvector's \\`sparsevec\\` column type. Use it when most dimensions are zero (e.g. SPLADE-style hybrid-search models over large vocabularies).\n\nExample:\n\n\ttype Document struct {\n\t    ID       uint\n\t    Features postgres.SparseVector `gorm:\"type:sparsevec(30000)\"`\n\t}\n\n\tfeats := postgres.NewSparseVectorFromMap(map[int32]float32{42: 0.8, 1337: 0.5}, 30000)\n\n```go\nfunc NewSparseVector(v []float32) SparseVector\n```\nNewSparseVector constructs a SparseVector by compressing a dense \\[]float32, keeping only non-zero entries. Dimension is inferred from len(v).\n\n```go\nfunc NewSparseVectorFromMap(elements map[int32]float32, dim int32) SparseVector\n```\nNewSparseVectorFromMap constructs a SparseVector from a map of index to value. Use this when the input is already sparse and you know the total dimension.\n\n```go\ntype Vector = pgvector.Vector\n```\nVector is a dense float32 vector mapped to pgvector's \\`vector\\` column type. It implements database/sql.Scanner and driver.Valuer, so GORM reads and writes it transparently when the struct field is tagged with the column type.\n\nExample:\n\n\ttype Document struct {\n\t    ID        uint\n\t    Embedding postgres.Vector `gorm:\"type:vector(1536)\"`\n\t}\n\n\tdoc := Document{Embedding: postgres.NewVector([]float32{0.1, 0.2, 0.3, ...})}\n\n```go\nfunc NewVector(v []float32) Vector\n```\nNewVector constructs a dense Vector from a \\[]float32.\n\n","path":"github.com/aalemi-dev/stdlib-lab/postgres","name":"postgres","synopsis":"Package postgres provides a PostgreSQL client built on top of GORM.","isRedistributable":true}
