{"modulePath":"github.com/cloudzero/cloudzero-agent","version":"v1.3.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package core\n\nPackage core provides foundational database repository infrastructure for CloudZero Agent storage operations. This package implements the Secondary Adapter layer in the hexagonal architecture, providing consistent database access patterns and transaction management across all CloudZero Agent data persistence operations.\n\nThe core storage infrastructure enables:\n\n  - Consistent transaction management: Context-based transaction propagation and nesting\n  - Repository pattern implementation: Base implementations for CRUD operations and common patterns\n  - Database abstraction: GORM-based ORM abstraction with error translation and context handling\n  - Resource metadata storage: Foundation for storing Kubernetes resource cost allocation data\n  - Operational data persistence: Storage for agent configuration, status, and audit information\n\nArchitecture:\n\n  - RawBaseRepoImpl: Low-level database access with transaction context management\n  - BaseRepoImpl: Higher-level repository base with model-specific operations\n  - Context management: Thread-safe transaction context propagation for nested operations\n  - Error translation: Consistent error handling and mapping from database errors to domain errors\n\nThe storage core enables CloudZero Agent components to persist and retrieve data using consistent patterns while maintaining transactional integrity across complex operations involving multiple tables and entities. This is essential for accurate cost allocation data and operational reliability.\n\nKey design principles:\n\n  - Transaction safety: All operations support transactional contexts with proper rollback\n  - Context propagation: Database connections and transactions flow through Go contexts\n  - Type safety: Generic repository patterns with compile-time type checking\n  - Performance optimization: Connection pooling, prepared statements, and efficient queries\n\nIntegration points:\n\n  - Resource repositories: Store Kubernetes resource metadata for cost allocation\n  - Configuration storage: Persist agent settings and dynamic configuration updates\n  - Audit logging: Store operational events and cost allocation decisions\n  - Status tracking: Maintain agent health and operational state information\n\nPackage core provides core functionalities for database repository implementations. This package includes base implementations for repositories that can be extended to fit specific use cases. It supports transaction management and context-based database operations.\n\nZeroLogAdapter is a custom logger adapter for GORM that uses zerolog for logging.\n\n## Functions\n\n```go\nfunc DatabaseNow() time.Time\n```\nDatabaseNow returns time.Now() in UTC, truncated to Milliseconds.\n\n```go\nfunc DatabaseNowPointer() *time.Time\n```\nDatabaseNowPointer returns a pointer to a time.Time created by DatabaseNow\n\n```go\nfunc FromContext(ctx context.Context) (*gorm.DB, bool)\n```\nFromContext returns the gorm.DB value stored in ctx, if any.\n\n```go\nfunc NewContext(ctx context.Context, db *gorm.DB) context.Context\n```\nNewContext returns a new Context that carries value db.\n\n```go\nfunc NewDriver(dialector gorm.Dialector) (*gorm.DB, error)\n```\nNewDriver creates a standard \\*gorm.DB for the database dialect passed in.\n\n```go\nfunc NewID() string\n```\nNewID generates a new unique identifier string using UUID version 4. It returns the UUID as a string.\n\n```go\nfunc TranslateError(err error) error\n```\nTranslateError maps GORM / SQLite errors to application-specific errors. If the error does not match any known GORM errors, it returns the original error.\n\n## Types\n\n```go\ntype BaseRepoImpl struct {\n\tRawBaseRepoImpl\n\t// contains filtered or unexported fields\n}\n```\nBaseRepoImpl adds core behaviors applicable to any database repository implementation. Repositories should be defined as follows:\n\n\t   type MyAwesomeRepoImpl struct {\n\t\t     core.BaseRepoImpl\n\t   }\n\nAnd constructed as follows:\n\n\t   func NewMyAwesomeRepoImpl(db *gorm.DB) *MyAwesomeRepoImpl {\n\t\t     return \u0026MyAwesomeRepoImpl{BaseRepoImpl:\n\t\t       core.NewBaseRepoImpl(db, \u0026MyAwesomeModel)}\n\t   }\n\nAny database operations should be invoked using the DB() function:\n\n\tr.DB(ctx).Where(...)\n\nWhich ensures the proper \\*gorm.DB instance is used (this enables transaction support).\n\n```go\nfunc NewBaseRepoImpl(db *gorm.DB, model interface{}) BaseRepoImpl\n```\nNewBaseRepoImpl creates a new BaseRepoImpl for use in a concrete instance of a repository, as shown above. The \\`model\\` parameter is used to specify the struct that this repository is associated with. It is used, for example, in the Count() function.\n\n```go\nfunc (b *BaseRepoImpl) Count(ctx context.Context) (int, error)\n```\nCount returns the number of rows in the table.\n\n```go\nfunc (b *BaseRepoImpl) DeleteAll(ctx context.Context) error\n```\nDeleteAll deletes all rows in the table (useful in testing).\n\n```go\ntype RawBaseRepoImpl struct {\n\t// contains filtered or unexported fields\n}\n```\nRawBaseRepoImpl provides low-level database access infrastructure for CloudZero Agent repositories. This struct implements the foundational database operations required by all repository implementations, including transaction management, context propagation, and connection pooling without assuming specific table models or entity structures.\n\nThe \"Raw\" designation indicates that this implementation provides direct database access without model-specific assumptions, making it suitable for repositories that need custom query logic or work with multiple tables/models within a single repository interface.\n\nKey capabilities:\n\n  - Transaction context management: Automatic detection and propagation of transaction contexts\n  - Connection pooling: Efficient reuse of database connections across operations\n  - Context cancellation: Proper handling of request cancellation and timeouts\n  - Error translation: Consistent error mapping from GORM to domain-specific errors\n\nUsage pattern:\n\n\tRaw base repositories are used when repositories need custom query logic that doesn't fit\n\tthe standard single-model pattern, such as repositories that join multiple tables or\n\tperform complex analytical queries for cost allocation reporting.\n\n```go\nfunc NewRawBaseRepoImpl(db *gorm.DB) RawBaseRepoImpl\n```\nNewRawBaseRepoImpl creates a new RawBaseRepoImpl for use in a concrete instance of a repository.\n\n```go\nfunc (b *RawBaseRepoImpl) DB(ctx context.Context) *gorm.DB\n```\nDB provides context-aware database access with automatic transaction detection and propagation. This method implements the core pattern used throughout CloudZero Agent storage operations to ensure consistent transaction behavior and proper context handling across all database operations.\n\nTransaction detection logic:\n\n 1. Check if the context contains an active transaction (via FromContext)\n 2. If transaction found, return the transaction-scoped database connection\n 3. If no transaction, return the default connection with context propagation\n 4. Always augment the connection with the current context for cancellation support\n\nContext propagation ensures:\n\n  - Request cancellation is properly handled during long-running queries\n  - Database timeouts are respected according to context deadlines\n  - Tracing and logging metadata flows through database operations\n  - Consistent behavior across transactional and non-transactional operations\n\nUsage patterns:\n\n  - All repository methods should use r.DB(ctx) instead of direct database access\n  - Enables seamless transaction support without changing repository method signatures\n  - Provides consistent error handling and context cancellation behavior\n  - Supports nested transactions through context propagation\n\nThis method is the foundation that enables CloudZero Agent repositories to participate in complex transactional operations while maintaining clean, context-aware interfaces.\n\n```go\nfunc (b *RawBaseRepoImpl) Tx(ctx context.Context, block func(ctxTx context.Context) error) error\n```\nTx executes a function within a database transaction, providing atomic operations for CloudZero Agent data consistency. This method enables complex multi-table operations to be performed atomically, ensuring data integrity for critical cost allocation operations and resource metadata management.\n\nTransaction lifecycle:\n\n 1. Creates a new database transaction using GORM's transaction support\n 2. Embeds the transaction connection into a new context (ctxTx)\n 3. Executes the provided block function with the transaction context\n 4. Automatically commits on successful block completion (no error returned)\n 5. Automatically rolls back if the block returns any error\n 6. Supports nested transactions through context layering\n\nAtomic operation examples:\n\n  - Resource metadata updates: Ensure webhook processing and storage are consistent\n  - Configuration changes: Update multiple configuration tables atomically\n  - Audit logging: Ensure operation and audit records are written together\n  - Batch operations: Process multiple resource updates with rollback capability\n\nContext propagation:\n\n\tThe ctxTx context passed to the block contains the transaction connection,\n\tenabling all repository operations within the block to automatically participate\n\tin the transaction without explicit transaction parameter passing.\n\nNested transaction support:\n\n\tIf the current context already contains a transaction, GORM handles nested\n\ttransactions appropriately using savepoints, enabling complex operation composition.\n\nError handling:\n\n  - Any error returned by the block function triggers automatic rollback\n  - Database-level errors during commit/rollback are propagated to the caller\n  - Context cancellation during the transaction triggers rollback\n  - Panic recovery within GORM ensures transaction cleanup\n\nThis method is essential for maintaining data consistency in CloudZero Agent operations where resource metadata, configuration, and audit information must be kept synchronized.\n\n```go\ntype ZeroLogAdapter struct{}\n```\n\n```go\nfunc (l ZeroLogAdapter) Error(ctx context.Context, msg string, opts ...interface{})\n```\n\n```go\nfunc (l ZeroLogAdapter) Info(ctx context.Context, msg string, opts ...interface{})\n```\n\n```go\nfunc (l ZeroLogAdapter) LogMode(logger.LogLevel) logger.Interface\n```\n\n```go\nfunc (l ZeroLogAdapter) Trace(ctx context.Context, begin time.Time, f func() (string, int64), err error)\n```\nTrace logs the execution of a SQL query using zerolog. It logs the duration of the query execution and additional information such as the SQL statement and the number of rows affected.\n\nParameters:\n\n  - ctx: The context for the logging operation.\n  - begin: The time when the query execution started.\n  - f: A function that returns the SQL statement and the number of rows affected.\n  - err: An error that occurred during the query execution, if any.\n\n```go\nfunc (l ZeroLogAdapter) Warn(ctx context.Context, msg string, opts ...interface{})\n```\n\n","path":"github.com/cloudzero/cloudzero-agent/app/storage/core","name":"core","synopsis":"Package core provides foundational database repository infrastructure for CloudZero Agent storage operations.","isRedistributable":true}
