database

package
v0.0.0-...-4c01ede Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxOpenConns = 4
	DefaultMaxIdleConns = 4
)

Default Parameters

View Source
const (
	WriteModeInsert = "insert"
)

Write to Database Schema

Variables

View Source
var (
	ErrNotValuerGoType = errors.New("field type is not ValuerGoType") // Error indicating that the interface is not a ValuerGoType.
)

Related to field errors.

Functions

func RegisterDialect

func RegisterDialect(name string, dialect Dialect)

RegisterDialect Registers a database dialect. A panic occurs when the registered name is the same or the dialect is empty.

func UnregisterAllDialects

func UnregisterAllDialects()

UnregisterAllDialects Unregisters all database dialects.

Types

type BaseConfig

type BaseConfig struct {
	TrimChar bool `json:"trimChar"`
}

BaseConfig is the configuration for the base table

type BaseConfigSetter

type BaseConfigSetter struct {
	BaseConfig
	// contains filtered or unexported fields
}

BaseConfigSetter is the setter for the base table configuration

func (*BaseConfigSetter) Config

func (b *BaseConfigSetter) Config() *config.JSON

Config retrieves the table configuration

func (*BaseConfigSetter) SetConfig

func (b *BaseConfigSetter) SetConfig(conf *config.JSON)

SetConfig sets the table configuration

func (*BaseConfigSetter) TrimByteChar

func (b *BaseConfigSetter) TrimByteChar(char []byte) []byte

TrimByteChar removes leading and trailing spaces from a byte array character

func (*BaseConfigSetter) TrimStringChar

func (b *BaseConfigSetter) TrimStringChar(char string) string

TrimStringChar removes leading and trailing spaces from a string character

type BaseFetchHandler

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

BaseFetchHandler Basic Record Handler Acquisition

func NewBaseFetchHandler

func NewBaseFetchHandler(createRecord func() (element.Record, error),
	onRecord func(element.Record) error) *BaseFetchHandler

NewBaseFetchHandler Create Basic Record Handler

func (*BaseFetchHandler) CreateRecord

func (b *BaseFetchHandler) CreateRecord() (element.Record, error)

CreateRecord Create a Record

func (*BaseFetchHandler) OnRecord

func (b *BaseFetchHandler) OnRecord(r element.Record) error

OnRecord Process Record r

type BaseField

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

BaseField: Represents a basic field, primarily storing the column name and column type.

func NewBaseField

func NewBaseField(index int, name string, fieldType FieldType) *BaseField

NewBaseField: Creates a new base field based on the column name and column type. Used for embedding other Fields, facilitating the implementation of database-specific Fields.

func (*BaseField) FieldType

func (b *BaseField) FieldType() FieldType

FieldType: Returns the field type.

func (*BaseField) Index

func (b *BaseField) Index() int

Index: Returns the field name.

func (*BaseField) Name

func (b *BaseField) Name() string

Name: Returns the field name.

func (*BaseField) String

func (b *BaseField) String() string

String: Displays a string representation when printing.

type BaseFieldType

type BaseFieldType struct {
	ColumnType
}

BaseFieldType: Represents the basic type of a field, embedding implementations for various database field types.

func NewBaseFieldType

func NewBaseFieldType(typ ColumnType) *BaseFieldType

NewBaseFieldType: Gets the field type.

func (*BaseFieldType) IsSupported

func (*BaseFieldType) IsSupported() bool

IsSupported: Determines if it is supported for parsing.

type BaseParam

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

BaseParam Basic parameters, used to embed SQL parameters for various databases

func NewBaseParam

func NewBaseParam(table Table, txOpts *sql.TxOptions) *BaseParam

NewBaseParam Generate basic parameters through table and transaction parameters txOps

func (*BaseParam) SetTable

func (b *BaseParam) SetTable(table Table)

SetTable Set table

func (*BaseParam) Table

func (b *BaseParam) Table() Table

Table Get table

func (*BaseParam) TxOptions

func (b *BaseParam) TxOptions() *sql.TxOptions

TxOptions Get transaction parameters

type BaseScanner

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

BaseScanner: Represents a basic scanner, embedding implementations for various database scanners.

func (*BaseScanner) Column

func (b *BaseScanner) Column() element.Column

Column: Retrieves the column value, facilitating a unified way to obtain column values.

func (*BaseScanner) SetColumn

func (b *BaseScanner) SetColumn(c element.Column)

SetColumn: Sets the column value for database-specific column data settings.

type BaseSource

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

BaseSource Basic data source for storing JSON configuration files Used to embed Source, facilitating the implementation of various database Fields

func NewBaseSource

func NewBaseSource(conf *config.JSON) *BaseSource

NewBaseSource Generate a basic data source from the JSON configuration file conf

func (*BaseSource) Config

func (b *BaseSource) Config() *config.JSON

Config Configuration file for the basic data source

type BaseTable

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

BaseTable Basic table, used to embed implementations of various database tables

func NewBaseTable

func NewBaseTable(instance, schema, name string) *BaseTable

NewBaseTable, acquire the basic table through instance name, schema name, and table name

func (*BaseTable) AppendField

func (b *BaseTable) AppendField(f Field)

AppendField Append column

func (*BaseTable) Fields

func (b *BaseTable) Fields() []Field

Fields Show all columns

func (*BaseTable) Instance

func (b *BaseTable) Instance() string

Instance Instance name, e.g., for MySQL, it's the database name; for Oracle, it's the instance name

func (*BaseTable) Name

func (b *BaseTable) Name() string

Name Table name, e.g., for MySQL, it's the table name

func (*BaseTable) Schema

func (b *BaseTable) Schema() string

Schema Schema name, e.g., for MySQL, it's the database name; for Oracle, it's the username

func (*BaseTable) String

func (b *BaseTable) String() string

String Display string for printing

type ColumnType

type ColumnType interface {
	Name() string                                   // Column name.
	ScanType() reflect.Type                         // Scanning type.
	Length() (length int64, ok bool)                // Length.
	DecimalSize() (precision, scale int64, ok bool) // Precision.
	Nullable() (nullable, ok bool)                  // Whether it is nullable.
	DatabaseTypeName() string                       // Name of the column's database type.
}

ColumnType: Represents the type of a column, abstracting sql.ColumnType and facilitating custom implementations.

type Config

type Config struct {
	Pool PoolConfig `json:"pool"`
}

Config is the basic configuration for database connections, typically used for sql.DB configurations

func NewConfig

func NewConfig(conf *config.JSON) (c *Config, err error)

NewConfig retrieves the database connection configuration 'c' from a JSON configuration 'err' refers to an error where the JSON configuration cannot be converted into a database connection configuration

type ConfigSetter

type ConfigSetter interface {
	SetConfig(conf *config.JSON)
}

ConfigSetter is an additional method for Table, used to set the JSON configuration file

type DB

type DB struct {
	Source
	// contains filtered or unexported fields
}

DB User Maintains Database Connection Pool

func NewDB

func NewDB(source Source) (d *DB, err error)

NewDB Acquire Database Connection Pool from Data Source source

func (*DB) BatchExec

func (d *DB) BatchExec(ctx context.Context, opts *ParameterOptions) (err error)

BatchExec Execute Multiple SQL Statements in Batch and Process Multiple Records

func (*DB) BatchExecStmt

func (d *DB) BatchExecStmt(ctx context.Context, opts *ParameterOptions) (err error)

BatchExecStmt Batch Prepare/Execute Multiple SQL Statements and Process Multiple Records

func (*DB) BatchExecStmtWithTx

func (d *DB) BatchExecStmtWithTx(ctx context.Context, opts *ParameterOptions) (err error)

BatchExecStmtWithTx Batch Transaction Prepare/Execute Multiple SQL Statements and Process Multiple Records

func (*DB) BatchExecWithTx

func (d *DB) BatchExecWithTx(ctx context.Context, opts *ParameterOptions) (err error)

BatchExecWithTx Execute Multiple SQL Statements in Batch Using Transaction and Process Multiple Records

func (*DB) BeginTx

func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

BeginTx Acquire Transaction

func (*DB) Close

func (d *DB) Close() (err error)

Close Close the Data Connection Pool

func (*DB) ExecContext

func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

ExecContext Execute Query and Acquire Result

func (*DB) FetchRecord

func (d *DB) FetchRecord(ctx context.Context, param Parameter, handler FetchHandler) (err error)

FetchRecord Acquire Multiple Rows of Records through Context ctx, SQL Parameter param, and Record Processing Function onRecord Returns an Error if Any

func (*DB) FetchRecordWithTx

func (d *DB) FetchRecordWithTx(ctx context.Context, param Parameter, handler FetchHandler) (err error)

FetchRecordWithTx Acquire Multiple Rows of Records Using Transaction through Context ctx, SQL Parameter param, and Record Processing Function onRecord Returns an Error if Any

func (*DB) FetchTable

func (d *DB) FetchTable(ctx context.Context, t *BaseTable) (Table, error)

FetchTable Acquire Corresponding Table through Context ctx and Basic Table Data t, Returns an Error if Any

func (*DB) FetchTableWithParam

func (d *DB) FetchTableWithParam(ctx context.Context, param Parameter) (Table, error)

FetchTableWithParam Acquire Corresponding Table through Context ctx and SQL Parameter param, Returns an Error if Any

func (*DB) PingContext

func (d *DB) PingContext(ctx context.Context) error

PingContext Query Multiple Rows of Data through Query

func (*DB) QueryContext

func (d *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

QueryContext Query Multiple Rows of Data through Query

type DBWrapper

type DBWrapper struct {
	*DB
	// contains filtered or unexported fields
}

DBWrapper is a wrapper for database connection pools, used to reuse relevant database connection pools (from unit to instance: user)

func Open

func Open(name string, conf *config.JSON) (dw *DBWrapper, err error)

Open can acquire a reusable database connection pool wrapper through the database name and JSON configuration conf, similar to a smart pointer

func (*DBWrapper) Close

func (d *DBWrapper) Close() (err error)

Close releases the database connection pool. If there are multiple references, the database connection pool will not be closed. When there are no references, it will be closed directly.

type Dialect

type Dialect interface {
	Source(*BaseSource) (Source, error) // Data Source
}

Dialect Database Dialect

type ExecParameter

type ExecParameter interface {
	ExecParam(string, *sql.TxOptions) (Parameter, bool)
}

ExecParameter Supplementary method for Table, used to get the method to generate SQL statements for write mode

type FetchHandler

type FetchHandler interface {
	OnRecord(element.Record) error
	CreateRecord() (element.Record, error)
}

FetchHandler Acquire Record Handler

type Field

type Field interface {
	fmt.Stringer

	Index() int                   // Index.
	Name() string                 // Field name.
	Quoted() string               // Referenced field name.
	BindVar(int) string           // Placeholder symbol, starting from 1.
	Select() string               // Selected field name.
	Type() FieldType              // Field type.
	Scanner() Scanner             // Scanner.
	Valuer(element.Column) Valuer // Valuer.
}

Field refers to a database field.

type FieldAdder

type FieldAdder interface {
	AddField(*BaseField) // Add specific column
}

FieldAdder Supplementary method for Table, used to add columns to a table

type FieldType

type FieldType interface {
	ColumnType

	IsSupported() bool // Whether it is supported.
}

FieldType: Represents the type of a field.

type FieldsFetcher

type FieldsFetcher interface {
	FetchFields(ctx context.Context, db *DB) error // Get specific column
}

FieldsFetcher Supplementary method for Table, used to specially fetch all columns of a table

type GoType

type GoType uint8

GoType refers to the type in the Golang language.

const (
	GoTypeUnknown GoType = iota // Unknown type.
	GoTypeBool                  // Boolean type.
	GoTypeInt64                 // Int64 type.
	GoTypeFloat64               // Float64 type.
	GoTypeString                // String type.
	GoTypeBytes                 // Byte stream type.
	GoTypeTime                  // Time type.
)

Enumeration of golang types.

func (GoType) String

func (t GoType) String() string

String description of the enumeration of golang types.

type GoValuer

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

GoValuer: Generates a Valuer using the GoType. Primarily done through the field 'f' and the incoming column value 'c'. Completes the generation of a Valuer using the GoType, facilitating the implementation of GoValuer.

func NewGoValuer

func NewGoValuer(f Field, c element.Column) *GoValuer

NewGoValuer: Generates a new Valuer using the GoType, primarily done through the field 'f' and the incoming column value 'c'.

func (*GoValuer) Value

func (g *GoValuer) Value() (driver.Value, error)

Value: Generates the corresponding driver-accepted value based on ValuerGoType.

type InsertParam

type InsertParam struct {
	*BaseParam
}

InsertParam Insert parameters

func NewInsertParam

func NewInsertParam(t Table, txOps *sql.TxOptions) *InsertParam

NewInsertParam Generate insert parameters through table and transaction parameters txOps

func (*InsertParam) Agrs

func (i *InsertParam) Agrs(records []element.Record) (valuers []interface{}, err error)

Args Generate bulk insert parameters from multiple records

func (*InsertParam) Query

func (i *InsertParam) Query(records []element.Record) (query string, err error)

Query Generate a bulk insert SQL statement from multiple records

type Judger

type Judger interface {
	schedule.RetryJudger

	ShouldOneByOne(err error) bool
}

Judger Error evaluator

type Parameter

type Parameter interface {
	SetTable(Table)                               // Set table or view
	Table() Table                                 // Table or view
	TxOptions() *sql.TxOptions                    // Transaction mode
	Query([]element.Record) (string, error)       // SQL prepare statement
	Agrs([]element.Record) ([]interface{}, error) // Prepare parameters
}

Parameter Execution parameters for SQL statements with table, transaction mode, and SQL

type ParameterOptions

type ParameterOptions struct {
	Table     Table            // Table or view
	Mode      string           // Write mode, e.g., for MySQL
	TxOptions *sql.TxOptions   // Transaction mode
	Records   []element.Record // Write row
}

ParameterOptions Options for parameters

type PoolConfig

type PoolConfig struct {
	MaxOpenConns    int            `json:"maxOpenConns"`    // Maximum number of open connections
	MaxIdleConns    int            `json:"maxIdleConns"`    // Maximum number of idle connections
	ConnMaxIdleTime times.Duration `json:"connMaxIdleTime"` // Maximum idle time for connections
	ConnMaxLifetime times.Duration `json:"connMaxLifetime"` // Maximum lifetime for connections
}

PoolConfig is the configuration for the database connection pool Generally, the maximum number of open connections should be the same as the maximum number of idle connections, otherwise it can lead to insufficient file resources due to unreleased connections

func (*PoolConfig) GetMaxIdleConns

func (c *PoolConfig) GetMaxIdleConns() int

GetMaxIdleConns retrieves the maximum number of idle connections, with a default return value of 4

func (*PoolConfig) GetMaxOpenConns

func (c *PoolConfig) GetMaxOpenConns() int

GetMaxOpenConns retrieves the maximum number of open connections, with a default return value of 4

type Scanner

type Scanner interface {
	sql.Scanner

	Column() element.Column // Get column data.
}

Scanner: Data scanner for columns. Converts database driver values into column data.

type Source

type Source interface {
	Config() *config.JSON   // Configuration Information
	Key() string            // Typically connection information
	DriverName() string     // Driver Name, used as the first parameter for sql.Open
	ConnectName() string    // Connection Information, used as the second parameter for sql.Open
	Table(*BaseTable) Table // Get Specific Table
}

Source Data Source, containing driver information, package information, configuration files, and connection information

func NewSource

func NewSource(name string, conf *config.JSON) (source Source, err error)

NewSource Obtain the corresponding data source by the name of the database dialect

type Table

type Table interface {
	fmt.Stringer

	Quoted() string   // Full name of the referenced table
	Instance() string // Instance name, e.g., for MySQL, it's the database name
	Schema() string   // Schema name, e.g., for Oracle, it's the username (schema name)
	Name() string     // Table name, e.g., for MySQL, it's the table name
	Fields() []Field  // Show all columns
}

Table Table structure

type TableQueryParam

type TableQueryParam struct {
	*BaseParam
}

TableQueryParam Table structure query parameters

func NewTableQueryParam

func NewTableQueryParam(table Table) *TableQueryParam

NewTableQueryParam Generate table structure query parameters from Table

func (*TableQueryParam) Agrs

func (t *TableQueryParam) Agrs(_ []element.Record) (a []interface{}, err error)

Args Generate parameters, but they are empty

func (*TableQueryParam) Query

func (t *TableQueryParam) Query(_ []element.Record) (s string, err error)

Query Generate a select * from table where 1=2 to acquire the table structure

type Valuer

type Valuer interface {
	driver.Valuer
}

Valuer: Converts corresponding data into database driver values.

type ValuerGoType

type ValuerGoType interface {
	GoType() GoType
}

type WithConnector

type WithConnector interface {
	Connector() (driver.Connector, error) // go 1.10 Get Connection
}

WithConnector Data Source with Connection, the data source prefers to call this method to generate a data connection pool DB

Directories

Path Synopsis
dbms

Jump to

Keyboard shortcuts

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