db

package
v0.0.0-...-fb98a72 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package db defines interfaces and implementations for interacting with entities in the database. It includes the AuditRepository interface, which outlines operations for querying and mutating Audit records, and the SQLAuditRepository struct, which provides a concrete implementation of the AuditRepository using GORM.

The SQLAuditRepository implementation leverages GORM to perform CRUD operations and complex queries on the database, abstracting the data layer away from the service layer to facilitate easier testing and maintenance.

Package db defines interfaces and implementations for interacting with entities in the database. It includes the FixitRepository interface, which outlines operations for querying and mutating Fixit records, and the SQLFixitRepository struct, which provides a concrete implementation of the FixitRepository using GORM.

The SQLFixitRepository implementation leverages GORM to perform CRUD operations and complex queries on the database, abstracting the data layer away from the service layer to facilitate easier testing and maintenance.

Package db defines interfaces and implementations for interacting with entities in the database. It includes the VocabRepository interface, which outlines operations for querying and mutating Vocab records, and the SQLVocabRepository struct, which provides a concrete implementation of the VocabRepository using GORM.

The SQLVocabRepository implementation leverages GORM to perform CRUD operations and complex queries on the database, abstracting the data layer away from the service layer to facilitate easier testing and maintenance.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateEnumIfNotExists

func CreateEnumIfNotExists(db *gorm.DB) error

CreateEnumIfNotExists checks if a custom ENUM type named 'status_type' exists in the PostgreSQL database. If it does not exist, the function creates this ENUM type with predefined values: 'pending', 'in_progress', and 'completed'. This function is useful for initializing or migrating databases to ensure that the necessary ENUM types are available for use in table definitions or elsewhere within the database schema.

The function executes a PostgreSQL DO block to conditionally create the ENUM type. This approach avoids errors that would occur from attempting to create a type that already exists, ensuring idempotency in database migrations or setups.

Parameters: - db: A pointer to a gorm.DB instance representing an established database connection.

Returns:

  • An error if the SQL execution fails, otherwise nil if the ENUM type is successfully checked for existence and created if needed.

Example usage:

if err := CreateEnumIfNotExists(db); err != nil {
    log.Fatalf("Failed to create or check ENUM 'status_type': %v", err)
}

Note: This function specifically targets PostgreSQL and uses features unique to that RDBMS. It may need adjustments for compatibility with other database systems.

func CreatePool

func CreatePool() (err error)

CreatePool initializes the global db connection pool using environment variables. The function configures the db connection pool with predefined settings for maximum idle connections, maximum open connections, and the maximum lifetime of a connection. If an error occurs while establishing a connection to the db, including setting up the connection pool, CreatePool returns an error.

func GetConnection

func GetConnection() (db *gorm.DB, err error)

GetConnection returns a reference to the global database connection. It checks if the global database connection (globalDb) has been established. If not, it returns an error indicating that the database connection is not available.

Returns: - db: A pointer to the gorm.DB instance representing the database connection. - err: An error if the global database connection has not been initialized.

Example usage: db, err := GetConnection()

if err != nil {
    log.Fatalf("Database connection error: %v", err)
}

func GetDatabaseURL

func GetDatabaseURL() string

GetDatabaseURL Get the database URL used to connect

func MigrateTables

func MigrateTables() (err error)

MigrateTables performs the necessary database migrations to ensure that the schema matches the expected structure defined by the internal models. This function is typically called during application initialization to prepare the database for use.

The migration process includes the following steps:

  1. Ensuring that a custom ENUM type 'status_type' exists in the PostgreSQL database, creating it if necessary. This ENUM is used by certain table columns.
  2. Automatically migrating the database schema to match the structure of the Fixit model.
  3. Automatically migrating the database schema to match the structure of the Audit model.

Note: This function presumes that the 'vocab' table already exists in the database and that its schema matches the structure defined by the internal models. It does not perform migration for the 'vocab' table. Ensure that any changes to the vocab model are manually reflected in the database or through separate migration scripts.

Returns:

  • An error if any part of the migration process fails, otherwise nil if all migrations are successful.

Example usage:

if err := MigrateTables(); err != nil {
    log.Fatalf("Database migration failed: %v", err)
}

This function utilizes the global database connection (globalDb) to perform migrations. It's important to ensure that this global connection is properly initialized and connected to the target database before calling MigrateTables.

Types

type AuditRepository

type AuditRepository interface {
	FindAuditByID(id int) (*mdl.Audit, error)
	FindAudits(tableName string, objectId int, duration *mdl.Duration, limit int) (audits *[]mdl.Audit, err error)
	CreateAudit(Audit *mdl.Audit) error
}

AuditRepository defines the operations available for an Audit entity.

type DbConnect

type DbConnect struct {
	UserName string `json:"username"`
	Password string `json:"password"`
	DbName   string `json:"dbname"`
	Host     string `json:"host"`
	Port     string `json:"port"`
}

DbConnect holds our db connection info

type FixitRepository

type FixitRepository interface {
	FindFixitByID(id int) (*mdl.Fixit, error)
	FindFixits(
		status mdl.StatusType,
		vocabID int,
		duration *mdl.Duration,
		limit int) (fixits *[]mdl.Fixit, err error)

	CreateFixit(Fixit *mdl.Fixit) error
	UpdateFixit(fixit *mdl.Fixit) error
}

FixitRepository defines the operations available for a Fixit entity.

type SQLAuditRepository

type SQLAuditRepository struct {
	// contains filtered or unexported fields
}

SQLAuditRepository provides a GORM-based implementation of the AuditRepository interface.

func NewSqlAuditRepository

func NewSqlAuditRepository() (repo *SQLAuditRepository, err error)

NewSqlAuditRepository initializes a new SQLAuditRepository with a database connection.

func (*SQLAuditRepository) CreateAudit

func (repo *SQLAuditRepository) CreateAudit(audit *mdl.Audit) error

CreateAudit inserts a new Audit record into the database. It establishes a database connection, then attempts to insert the provided Audit instance. Returns an error if the database connection fails or if the insert operation encounters an error.

func (*SQLAuditRepository) FindAuditByID

func (repo *SQLAuditRepository) FindAuditByID(id int) (audit *mdl.Audit, err error)

FindAuditByID retrieves a single Audit record from the database using its primary ID.

The function attempts to establish a database connection and then queries the Audit table for a record matching the specified ID. It is designed to fetch exactly one record or return an error if the record does not exist or in case of a connection or query execution error.

Parameters: - id: An integer representing the primary ID of the Audit record to retrieve.

Returns:

  • *mdl.Audit: A pointer to an Audit struct representing the found record. If no record is found or in case of an error, nil is returned.
  • error: An error object detailing any issues encountered during the database connection attempt or query execution. Errors could include connection failures, issues executing the query, or the situation where no record is found matching the provided ID. In cases where the operation succeeds and a record is found, nil is returned for the error.

Usage example: Audit, err := FindAuditByID(123)

if err != nil {
    log.Printf("An error occurred: %v", err)
} else {
	log.Printf("Retrieved Audit: %+v\n", Audit)
}

func (*SQLAuditRepository) FindAudits

func (repo *SQLAuditRepository) FindAudits(tableName string, objectId int, duration *mdl.Duration, limit int) (audits *[]mdl.Audit, err error)

FindAudits retrieves a list of Audit records filtered by the specified criteria. It allows filtering by table name and a time duration, and limits the number of returned records. This method is useful for fetching audit logs for specific database tables within a certain time frame.

Parameters:

  • tableName: The name of the database table for which to retrieve audit records. If an empty string is provided, audit records for all tables are considered.
  • objectId: Primary key used to narrow results to just changes to a single record. Must be used in conjunction with the table name filter. If a zero value is provided, audit records for all tables are considered.
  • duration: A pointer to a mdl.Duration struct specifying the start and end time for the time range filter. If nil, no time-based filtering is applied.
  • limit: The maximum number of audit records to retrieve.

Returns:

  • A pointer to a slice of mdl.Audit structs containing the retrieved audit records. Returns nil if an error occurs during query execution.
  • An error if there is an issue establishing a database connection, executing the query, or applying the specified filters. Returns nil if the query is successful.

Example usage: audits, err := repo.FindAudits("users", &mdl.Duration{Start: startTime, End: endTime}, 10)

if err != nil {
    log.Printf("Failed to find audits: %v", err)
} else {

    for _, audit := range *audits {
        fmt.Println(audit)
    }
}

type SQLFixitRepository

type SQLFixitRepository struct {
	// contains filtered or unexported fields
}

SQLFixitRepository provides a GORM-based implementation of the FixitRepository interface.

func NewSqlFixitRepository

func NewSqlFixitRepository() (repo *SQLFixitRepository, err error)

NewSqlFixitRepository initializes a new SQLFixitRepository with a database connection.

func (*SQLFixitRepository) CreateFixit

func (repo *SQLFixitRepository) CreateFixit(fixit *mdl.Fixit) error

CreateFixit inserts a new Fixit record into the database. It establishes a database connection, then attempts to insert the provided Fixit instance. Returns an error if the database connection fails or if the insert operation encounters an error.

func (*SQLFixitRepository) FindFixitByID

func (repo *SQLFixitRepository) FindFixitByID(id int) (fixit *mdl.Fixit, err error)

FindFixitByID retrieves a single Fixit record from the database using its primary ID.

The function attempts to establish a database connection and then queries the Fixit table for a record matching the specified ID. It is designed to fetch exactly one record or return an error if the record does not exist or in case of a connection or query execution error.

Parameters: - id: An integer representing the primary ID of the Fixit record to retrieve.

Returns:

  • *mdl.Fixit: A pointer to a Fixit struct representing the found record. If no record is found or in case of an error, nil is returned.
  • error: An error object detailing any issues encountered during the database connection attempt or query execution. Errors could include connection failures, issues executing the query, or the situation where no record is found matching the provided ID. In cases where the operation succeeds and a record is found, nil is returned for the error.

Usage example: Fixit, err := FindFixitByID(123)

if err != nil {
    log.Printf("An error occurred: %v", err)
} else {
	log.Printf("Retrieved Fixit: %+v\n", Fixit)
}

func (*SQLFixitRepository) FindFixits

func (repo *SQLFixitRepository) FindFixits(
	status mdl.StatusType,
	vocabID int,
	duration *mdl.Duration,
	limit int) (fixits *[]mdl.Fixit, err error)

FindFixits retrieves a slice of Fixit entities from the database that match the given criteria. It filters Fixits based on their status, associated vocab ID, and creation date within a specified duration. This method supports pagination through a 'limit' parameter, allowing clients to specify the maximum number of Fixits to retrieve.

Parameters:

  • status: A StatusType value to filter Fixits by their current status.
  • vocabID: An integer representing the vocab ID. If greater than 0, the method filters Fixits associated with this vocab ID.
  • duration: A pointer to a Duration struct specifying the start and end time for filtering Fixits based on their creation date. Fixits created within this duration are included in the result. If nil, no time-based filtering is applied.
  • limit: An integer defining the maximum number of Fixits to return. Useful for pagination.

Returns: - A pointer to a slice of Fixit entities matching the provided criteria. - An error if there's a problem executing the database query.

Example usage: fixits, err := fixitService.FindFixits(mdl.StatusType("pending"), 101, &mdl.Duration{Start: time.Now().Add(-7*24*time.Hour), End: time.Now()}, 10)

if err != nil {
    log.Printf("Error retrieving Fixits: %v", err)
} else {

    for _, fixit := range *fixits {
        fmt.Printf("Found Fixit: %+v\n", fixit)
    }
}

func (*SQLFixitRepository) UpdateFixit

func (repo *SQLFixitRepository) UpdateFixit(fixit *mdl.Fixit) error

UpdateFixit updates an existing Fixit record into the database. It establishes a database connection, then attempts to find and update the provided Fixit instance. Returns an error if the database connection fails or if the update operation encounters an error.

type SQLVocabRepository

type SQLVocabRepository struct {
	// contains filtered or unexported fields
}

SQLVocabRepository provides a GORM-based implementation of the VocabRepository interface.

func NewSqlVocabRepository

func NewSqlVocabRepository() (repo *SQLVocabRepository, err error)

NewSqlVocabRepository initializes a new SQLVocabRepository with a database connection.

func (*SQLVocabRepository) CreateVocab

func (repo *SQLVocabRepository) CreateVocab(vocab *mdl.Vocab) error

CreateVocab inserts a new Vocab record into the database. It establishes a database connection, then attempts to insert the provided Vocab instance. Returns an error if the database connection fails or if the insert operation encounters an error.

func (*SQLVocabRepository) FindVocabByID

func (repo *SQLVocabRepository) FindVocabByID(id int) (vocab *mdl.Vocab, err error)

FindVocabByID retrieves a single Vocab record from the database using its primary ID.

The function attempts to establish a database connection and then queries the Vocab table for a record matching the specified ID. It is designed to fetch exactly one record or return an error if the record does not exist or in case of a connection or query execution error.

Parameters: - id: An integer representing the primary ID of the Vocab record to retrieve.

Returns:

  • *mdl.Vocab: A pointer to a Vocab struct representing the found record. If no record is found or in case of an error, nil is returned.
  • error: An error object detailing any issues encountered during the database connection attempt or query execution. Errors could include connection failures, issues executing the query, or the situation where no record is found matching the provided ID. In cases where the operation succeeds and a record is found, nil is returned for the error.

Usage example: vocab, err := FindVocabByID(123)

if err != nil {
    log.Printf("An error occurred: %v", err)
} else {
	log.Printf("Retrieved vocab: %+v\n", vocab)
}

func (*SQLVocabRepository) FindVocabByLearningLang

func (repo *SQLVocabRepository) FindVocabByLearningLang(learningLang string) (vocab *mdl.Vocab, err error)

FindVocabByLearningLang retrieves a Vocab record from the database based on the learning language.

This function searches the database for a Vocab record that matches the specified learning language string. The learning language is expected to be unique for each record, hence only one record should match the criteria. If the connection to the database cannot be established, or if no record is found matching the given learning language, the function returns an error detailing the issue encountered.

Parameters: - learningLang: A string representing the learning language of the Vocab record to retrieve.

Returns:

  • *mdl.Vocab: A pointer to the retrieved Vocab record. If no record is found or in case of an error, nil is returned.
  • error: An error object that details any issues encountered during the database connection attempt or query execution. Possible errors include connection failures, issues executing the query, or the case where no record is found matching the provided learning language. In cases where the operation succeeds, nil is returned for the error.

Usage example: vocab, err := FindVocabByLearningLang("English")

if err != nil {
    log.Printf("An error occurred: %v", err)
} else {

    fmt.Printf("Retrieved vocab: %+v\n", vocab)
}

func (*SQLVocabRepository) FindVocabs

func (repo *SQLVocabRepository) FindVocabs(learningCode string, hasFirst bool, limit int) (vocabs *[]mdl.Vocab, err error)

FindVocabs retrieves a list of Vocab records filtered by learning language code and the presence or absence of a first language translation. It limits the number of records returned based on the specified limit. The function filters records based on the learningCode provided and whether each record has a non-empty first language translation as indicated by the hasFirst parameter. If hasFirst is true, only records with a first language translation are included. If hasFirst is false, it returns records without a first language translation.

Parameters:

  • learningCode: The code of the learning language to filter records by.
  • hasFirst: A boolean flag indicating whether to filter for records with (true) or without (false) a first language translation.
  • limit: The maximum number of records to return.

Returns: - vocabs: A pointer to a slice of Vocab records matching the criteria, or nil if an error occurs. - err: An error object if an error occurs during the query execution, otherwise nil.

Example of usage: vocabs, err := FindVocabs("es", true, 10)

if err != nil {
    log.Println("Error fetching vocabs:", err)
} else {
    for _, vocab := range *vocabs {
        fmt.Println(vocab)
    }
}

func (*SQLVocabRepository) UpdateVocab

func (repo *SQLVocabRepository) UpdateVocab(vocab *mdl.Vocab) error

UpdateVocab updates an existing Vocab record in the database. It establishes a database connection, then attempts to update the Vocab instance based on its ID. Returns an error if the database connection fails or if the update operation encounters an error.

type VocabRepository

type VocabRepository interface {
	FindVocabByID(id int) (*mdl.Vocab, error)
	FindVocabByLearningLang(learningLang string) (vocab *mdl.Vocab, err error)
	FindVocabs(learningCode string, hasFirst bool, limit int) (*[]mdl.Vocab, error)
	CreateVocab(vocab *mdl.Vocab) error
	UpdateVocab(vocab *mdl.Vocab) error
}

VocabRepository defines the operations available for a Vocab entity.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL