dba

package module
v0.0.0-...-67722c6 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2024 License: Apache-2.0 Imports: 40 Imported by: 0

README

dba

Documentation

Index

Constants

View Source
const (
	MySQL      = "mysql"
	PostgreSQL = "postgres"
	SQLite     = "sqlite"
)
View Source
const SetToNullFlag = "$$$NULL$$$"

Variables

View Source
var DefaultNamespace = &Namespace{
	connections: new(sync.Map),
	schemas:     new(sync.Map),
}

Functions

func BatchExec

func BatchExec(query string, args ...any) (int, error)

func BatchExecBy

func BatchExecBy(connectionName string, query string, args ...any) (int, error)

func CheckPassword

func CheckPassword(inputPassword, targetPassword string) bool

func Connect

func Connect(config *ConnectConfig) error

func ConnectionNames

func ConnectionNames() []string

func DecodeURIComponent

func DecodeURIComponent(str string) string

func DiffDays

func DiffDays(start, end time.Time) []time.Time

func DiffDaysString

func DiffDaysString(start, end time.Time) []string

func Disconnect

func Disconnect(name ...string)

func DisconnectAll

func DisconnectAll()

func EncodeURIComponent

func EncodeURIComponent(str string) string

func EnsureDir

func EnsureDir(p string) error

func Exec

func Exec(query string, args ...any) (int, error)

func ExecBy

func ExecBy(connectionName string, query string, args ...any) (int, error)

func GenPassword

func GenPassword(inputPassword string) (string, error)

func GetFileMD5Sum

func GetFileMD5Sum(filePath string) (string, error)

func GetZeroSliceValueOfField

func GetZeroSliceValueOfField(input any, fieldName string) (reflect.Value, error)

GetZeroSliceValueOfField 返回字段值的切片类型的零值

func GetZeroValueOfField

func GetZeroValueOfField(input any, fieldName string) (reflect.Value, error)

GetZeroValueOfField 返回字段类型的零值

func IsAudio

func IsAudio(filePath string) bool

func IsImage

func IsImage(filePath string) bool

func IsNilOrZero

func IsNilOrZero(a any) bool

func IsVideo

func IsVideo(filePath string) bool

func Item2List

func Item2List(dst any) any

func JSONParse

func JSONParse(s string, v any) error

func JSONStringify

func JSONStringify(v any, format ...bool) string

func LookupSchema

func LookupSchema(name ...string) map[string]*Schema

func MD5Str

func MD5Str(str string) string

func MarkdownFindAndReplaceURLs

func MarkdownFindAndReplaceURLs(result string, keepText bool) (string, []string)

func NewRandomNumber

func NewRandomNumber(length int) string

func NewUUID

func NewUUID(upper bool, hyphen bool) string

func NewUUIDToken

func NewUUIDToken() string

func NewVar

func NewVar(src any) reflect.Value

func NextSnowflakeID

func NextSnowflakeID() snowflake.ID

func NextSnowflakeIntID

func NextSnowflakeIntID() int64

func NextSnowflakeStringID

func NextSnowflakeStringID() string

func ParseNullBool

func ParseNullBool(s string) null.Bool

func ParseNullFloat

func ParseNullFloat(s string) null.Float

func ParseNullInt

func ParseNullInt(s string) null.Int

func ParseNullString

func ParseNullString(s, defaultValue string) null.String

func ParseStruct

func ParseStruct(data any) map[string]any

ParseStruct recursively parses a struct or a pointer to a struct and returns a map[string]any.

func ParseTag

func ParseTag(tagName string) map[string]string

ParseTag "KEY=VALUE;KEY=VALUE;..."

func PathExists

func PathExists(p string) (bool, error)

func Query

func Query(dst any, query string, args ...any) error

func QueryBy

func QueryBy(connectionName string, dst any, query string, args ...any) error

func ReflectValueOf

func ReflectValueOf(ctx context.Context, structField reflect.StructField, structValue reflect.Value) reflect.Value

func RegisterSchema

func RegisterSchema(values ...any) error

func SplitAndTrimSpace

func SplitAndTrimSpace(s, sep string, removeEmpty ...bool) []string

func StructFieldByName

func StructFieldByName(obj any, fieldName string) any

func StructToMap

func StructToMap(input any) map[string]any

func TrimSpaceSlice

func TrimSpaceSlice(s []string)

Types

type Cond

type Cond map[string]any

type ConflictKind

type ConflictKind string
const (
	ConflictIgnore ConflictKind = "IGNORE"
	ConflictUpdate ConflictKind = "UPDATE"
)

type ConflictUpdateOptions

type ConflictUpdateOptions struct {
	Kind    ConflictKind
	Columns map[string]any // 在部分更新情况下指定要更新的列(保留原值的话,value为nil即可)
}

type ConnectConfig

type ConnectConfig struct {
	Driver        string
	Dsn           string
	Name          string
	CreateClauses string
	DeleteClauses string
	UpdateClauses string
	QueryClauses  string
}

type Connection

type Connection struct {
	CreateTemplate *template.Template
	UpdateTemplate *template.Template
	DeleteTemplate *template.Template
	QueryTemplate  *template.Template
	// contains filtered or unexported fields
}

func Session

func Session(name ...string) *Connection

func (*Connection) BatchExec

func (c *Connection) BatchExec(query string, args ...any) (int, error)

func (*Connection) Exec

func (c *Connection) Exec(query string, args ...any) (int, error)

func (*Connection) GenDDL

func (c *Connection) GenDDL(schs map[string]*Schema, ignoreComments ...bool) string

func (*Connection) Init

func (c *Connection) Init(schs ...map[string]*Schema) error

func (*Connection) Namespace

func (c *Connection) Namespace() *Namespace

func (*Connection) Query

func (c *Connection) Query(dst any, query string, args ...any) error

type CreateOptions

type CreateOptions struct {
	BatchSize        int
	SharedTx         bool                   // 用于指定是否所有批次共用一个事务
	ConflictUpdates  *ConflictUpdateOptions // 指定冲突处理方式
	RelatesWriteMode RelationWriteMode
	RelatesWrites    *RelatesWriteOptions
}

type DataModel

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

func Model

func Model(schemaName string, options ...*ModelOptions) *DataModel

func (*DataModel) Create

func (dm *DataModel) Create(value any, options ...*CreateOptions) error

func (*DataModel) Find

func (dm *DataModel) Find(conditions ...any) *Result

type Driver

type Driver interface {
	Name() string
	Connect(config *ConnectConfig) (*sqlx.DB, error)
	GenDDL(sortedNames []string, schs map[string]*Schema, ignoreComments ...bool) string
	CreateClauses() string
	DeleteClauses() string
	UpdateClauses() string
	QueryClauses() string
}

type Entry

type Entry struct {
	Key   string
	Op    entryOp
	Value any
}

type Field

type Field struct {
	Name            string      `json:"name,omitempty"`
	NativeName      string      `json:"native_name,omitempty"`
	Type            SchemaType  `json:"type,omitempty"`
	ItemType        string      `json:"item_type,omitempty"`
	NativeType      string      `json:"native_type,omitempty"`
	Title           string      `json:"title,omitempty"`
	Description     null.String `json:"description,omitempty"`
	Relation        *Relation   `json:"relation,omitempty"`
	RelationConfig  string      `json:"relation_config,omitempty"`
	IsPrimary       bool        `json:"is_primary"`
	IsUnsigned      bool        `json:"is_unsigned"`
	IsAutoIncrement bool        `json:"is_auto_increment"`

	// TODO 默认值配置实现
	//DefaultConfig  string
	// TODO 必填配置实现
	IsRequired     bool   `json:"is_required"`
	RequiredConfig string `json:"required_config,omitempty"`
}

func (*Field) Clone

func (f *Field) Clone() *Field

func (*Field) IsScalarType

func (f *Field) IsScalarType() bool

func (*Field) Valid

func (f *Field) Valid() bool

type File

type File struct {
	ThumbID   null.String `mod:"缩略图ID"`
	ThumbPath null.String `mod:"缩略图"`
	ThumbURL  null.String `mod:"缩略图"`
	Duration  null.Float  `mod:"音/视频时长(秒)"`

	UUID     string      `mod:"文件唯一ID"`
	FileKind FileKind    `mod:"文件类型"`
	MineType string      `mod:"文件Mine-Type"` // 如image/jpeg
	Name     string      `mod:"文件名称"`
	Path     string      `mod:"存储路径"`
	Ext      string      `mod:"文件扩展名"`
	URL      string      `mod:"下载路径"`
	Size     null.Int    `mod:"文件大小"`
	Sort     null.Int    `mod:"排序值"`
	MD5Sum   null.String `mod:"MD5校验码"`
	Width    null.Int    `mod:"宽度"`
	Height   null.Int    `mod:"高度"`

	Clazz     null.String `mod:"文件分类"`
	OwnerID   null.Int    `mod:"所属数据ID"`
	OwnerType null.String `mod:"所属数据类型"`
	// contains filtered or unexported fields
}

func (*File) SetMD5Sum

func (f *File) SetMD5Sum() *File

type FileKind

type FileKind string
const (
	FileKindText  FileKind = "TEXT"
	FileKindImage FileKind = "IMAGE"
	FileKindVideo FileKind = "VIDEO"
	FileKindAudio FileKind = "AUDIO"
	FileKindFile  FileKind = "FILE"
)

type FilepathObject

type FilepathObject struct {
	Raw           string
	FileNameNoExt string
	FullFileName  string
	FileExt       string
	FileDir       string
}

func ParseFilepath

func ParseFilepath(fileURL string) (fo *FilepathObject)

type Filter

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

func And

func And(conditions ...any) *Filter

func Or

func Or(conditions ...any) *Filter

type ModelOptions

type ModelOptions struct {
	ConnectionName string
	Tx             *sqlx.Tx
}

type Namespace

type Namespace struct {
	Name string
	// contains filtered or unexported fields
}

func (*Namespace) Connect

func (ns *Namespace) Connect(config *ConnectConfig) (*Connection, error)

func (*Namespace) ConnectionNames

func (ns *Namespace) ConnectionNames() []string

func (*Namespace) Disconnect

func (ns *Namespace) Disconnect(name ...string)

func (*Namespace) DisconnectAll

func (ns *Namespace) DisconnectAll()

func (*Namespace) Init

func (ns *Namespace) Init(connectionName ...string) error

func (*Namespace) LookupSchema

func (ns *Namespace) LookupSchema(names ...string) map[string]*Schema

func (*Namespace) Model

func (ns *Namespace) Model(schemaName string, options ...*ModelOptions) *DataModel

func (*Namespace) RegisterSchema

func (ns *Namespace) RegisterSchema(value ...any) error

func (*Namespace) SchemaBy

func (ns *Namespace) SchemaBy(name string) *Schema

func (*Namespace) Session

func (ns *Namespace) Session(connectionName ...string) *Connection

type PopulateOptions

type PopulateOptions struct {
	Path      string
	Match     *Filter
	BrgMatch  *Filter
	Fields    []string
	IsOmit    bool
	OrderBys  map[string]bool
	Limit     int
	Offset    int
	CustomRel *Relation
}

type ReflectUtils

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

func NewReflectUtils

func NewReflectUtils(a any) (*ReflectUtils, error)

NewReflectUtils 创建一个新的 ReflectUtils 对象

func (*ReflectUtils) CreateEmptyCopy

func (ru *ReflectUtils) CreateEmptyCopy() any

CreateEmptyCopy 创建变量a的空副本

func (*ReflectUtils) CreateEmptyElement

func (ru *ReflectUtils) CreateEmptyElement() any

CreateEmptyElement 返回切片或数组元素的空值对象

func (*ReflectUtils) GetAllFieldNamesOrKeys

func (ru *ReflectUtils) GetAllFieldNamesOrKeys(elem any) ([]string, error)

GetAllFieldNamesOrKeys 获取所有字段名或键名

func (*ReflectUtils) GetAllFieldValuesOrValues

func (ru *ReflectUtils) GetAllFieldValuesOrValues(elem any) ([]any, error)

GetAllFieldValuesOrValues 获取所有字段值或键值

func (*ReflectUtils) GetAllFieldsOrKeysAndValues

func (ru *ReflectUtils) GetAllFieldsOrKeysAndValues(elem any) (map[string]any, error)

GetAllFieldsOrKeysAndValues 获取所有字段名或键名及其对应的值

func (*ReflectUtils) GetElemFieldOrKey

func (ru *ReflectUtils) GetElemFieldOrKey(elem any, k string) (result any, isEmpty bool)

GetFieldOrKey 获取指定结构体字段或 map 键的值。 如果是结构体,将尝试获取字段的 reflect.Value 并返回其 Interface()。 如果是 map,将尝试获取指定键的值。 如果字段或键不存在,或类型不支持,返回错误。

func (*ReflectUtils) GetElement

func (ru *ReflectUtils) GetElement(index int) any

GetElement 获取指定下标的元素

func (*ReflectUtils) GetFieldOrKey

func (ru *ReflectUtils) GetFieldOrKey(k string) (result any, isEmpty bool)

GetFieldOrKey 获取指定结构体字段或 map 键的值。 如果是结构体,将尝试获取字段的 reflect.Value 并返回其 Interface()。 如果是 map,将尝试获取指定键的值。 如果字段或键不存在,或类型不支持,返回错误。

func (*ReflectUtils) GetLen

func (ru *ReflectUtils) GetLen() int

GetLen 获取数组或切片长度

func (*ReflectUtils) IndirectVal

func (ru *ReflectUtils) IndirectVal() reflect.Value

IndirectVal 返回反射值

func (*ReflectUtils) Raw

func (ru *ReflectUtils) Raw() any

Raw 返回原始值

func (*ReflectUtils) SetFieldOrKey

func (ru *ReflectUtils) SetFieldOrKey(elem any, k string, v any) (err error)

SetFieldOrKey 设置指定结构体字段或 map 键的值。 对于结构体类型,尝试获取字段的 reflect.Value 并设置新值。 对于 map 类型,通过键名设置对应的值。 如果字段不可设置或类型不支持,返回错误。

func (*ReflectUtils) TypeCategory

func (ru *ReflectUtils) TypeCategory() TypeCategory

TypeCategory 返回变量的类型类别

func (*ReflectUtils) Value

func (ru *ReflectUtils) Value() reflect.Value

Value 返回反射值

type ReflectValue

type ReflectValue struct {
	reflect.Value
	// contains filtered or unexported fields
}

func NewReflectValue

func NewReflectValue(src any) *ReflectValue

func (*ReflectValue) FieldByName

func (rv *ReflectValue) FieldByName(fieldName string) *reflect.Value

func (*ReflectValue) Keys

func (rv *ReflectValue) Keys() []string

func (*ReflectValue) Map

func (rv *ReflectValue) Map() map[string]any

func (*ReflectValue) Raw

func (rv *ReflectValue) Raw() *reflect.Value

func (*ReflectValue) Src

func (rv *ReflectValue) Src() any

func (*ReflectValue) Values

func (rv *ReflectValue) Values() []any

type RelatesWriteOptions

type RelatesWriteOptions struct {
	IgnoreFields  []string // 无 -1
	AppendFields  []string // 无ID创建 1
	UpsertFields  []string // 无ID创建;有ID更新关系字段+其他字段(如有) 2
	ReplaceFields []string // 无ID创建;有ID更新关系字段+其他字段(如有);删除不在范围内的档案(默认策略) 3
}

type Relation

type Relation struct {
	Kind      RelationKind `json:"kind,omitempty"`
	Field     string       `json:"field,omitempty"`
	SrcSchema string       `json:"src_schema,omitempty"`
	SrcField  string       `json:"src_field,omitempty"`
	DstSchema string       `json:"dst_schema,omitempty"`
	DstField  string       `json:"dst_field,omitempty"`

	BrgSchema   string `json:"brg_schema,omitempty"`
	BrgSrcField string `json:"brg_src_field,omitempty"`
	BrgDstField string `json:"brg_dst_field,omitempty"`
	BrgIsNative bool   `json:"brg_is_native,omitempty"`
}

func (*Relation) Clone

func (rs *Relation) Clone() *Relation

func (*Relation) Valid

func (rs *Relation) Valid() bool

type RelationKind

type RelationKind string
const (
	HasOne         RelationKind = "HAS_ONE"         // HasEntity
	HasMany        RelationKind = "HAS_MANY"        // HasEntities
	ReferencesOne  RelationKind = "REFERENCES_ONE"  // ReferencedEntity
	ReferencesMany RelationKind = "REFERENCES_MANY" // ReferencedEntities
)

type RelationWriteMode

type RelationWriteMode string
const (
	RelatesWriteModeIgnore  RelationWriteMode = "IGNORE"
	RelatesWriteModeAppend  RelationWriteMode = "APPEND"
	RelatesWriteModeUpsert  RelationWriteMode = "UPSERT"
	RelatesWriteModeReplace RelationWriteMode = "REPLACE"
)

type Result

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

func (*Result) AddAnd

func (r *Result) AddAnd(conditions ...any) *Result

func (*Result) AddOr

func (r *Result) AddOr(conditions ...any) *Result

func (*Result) All

func (r *Result) All(dst any) error

func (*Result) Count

func (r *Result) Count() (int, error)

func (*Result) Delete

func (r *Result) Delete() (int, error)

func (*Result) Limit

func (r *Result) Limit(limit int) *Result

func (*Result) Offset

func (r *Result) Offset(offset int) *Result

func (*Result) Omit

func (r *Result) Omit(names ...string) *Result

func (*Result) One

func (r *Result) One(dst any) error

func (*Result) OrderBy

func (r *Result) OrderBy(name ...string) *Result

func (*Result) OrderByDesc

func (r *Result) OrderByDesc(name ...string) *Result

func (*Result) Paginate

func (r *Result) Paginate(pageNum int, pageSize int, dst any) (totalRecords int, totalPages int, err error)

func (*Result) Populate

func (r *Result) Populate(names ...string) *Result

func (*Result) PopulateBy

func (r *Result) PopulateBy(options ...*PopulateOptions) *Result

func (*Result) Select

func (r *Result) Select(names ...string) *Result

func (*Result) Update

func (r *Result) Update(doc any) (int, error)

func (*Result) Where

func (r *Result) Where(conditions ...any) *Result

func (*Result) WithFields

func (r *Result) WithFields(names []string, isOmit bool) *Result

type Schema

type Schema struct {
	Name        string            `json:"name,omitempty"`
	NativeName  string            `json:"native_name,omitempty"`
	Description string            `json:"description,omitempty"`
	Fields      map[string]*Field `json:"fields,omitempty"`

	CreateClauses string `json:"create_clauses,omitempty"`
	UpdateClauses string `json:"update_clauses,omitempty"`
	DeleteClauses string `json:"delete_clauses,omitempty"`
	QueryClauses  string `json:"query_clauses,omitempty"`
	// contains filtered or unexported fields
}

func ParseSchema

func ParseSchema(values ...any) ([]*Schema, error)

func SchemaBy

func SchemaBy(name string) *Schema

func (*Schema) AutoIncrField

func (s *Schema) AutoIncrField() *Field

func (*Schema) Cache

func (s *Schema) Cache() *sync.Map

func (*Schema) Clone

func (s *Schema) Clone() *Schema

func (*Schema) NativeFieldNames

func (s *Schema) NativeFieldNames(names []string, scalarTypeOnly bool) []string

func (*Schema) NativeFields

func (s *Schema) NativeFields() map[string]*Field

func (*Schema) ParseValue

func (s *Schema) ParseValue(data any, useNativeName bool) map[string]any

func (*Schema) PrimaryField

func (s *Schema) PrimaryField() *Field

func (*Schema) PrimaryFields

func (s *Schema) PrimaryFields() []*Field

func (*Schema) ScalarFieldNativeNames

func (s *Schema) ScalarFieldNativeNames() []string

func (*Schema) ScalarFields

func (s *Schema) ScalarFields() []*Field

type SchemaInterface

type SchemaInterface interface {
	Schema() Schema
}

type SchemaType

type SchemaType string
const (
	String  SchemaType = "string"
	Integer SchemaType = "int"
	Float   SchemaType = "float"
	Boolean SchemaType = "bool"
	Time    SchemaType = "time"
	Object  SchemaType = "object"
	Array   SchemaType = "array"
)

type TypeCategory

type TypeCategory string

TypeCategory 表示变量类型的类别

const (
	CategoryStruct                          TypeCategory = "Struct"
	CategoryStructPointer                   TypeCategory = "StructPointer"
	CategoryMapStringAny                    TypeCategory = "MapStringAny"
	CategoryStructSliceOrArray              TypeCategory = "StructSliceOrArray"
	CategoryStructPointerSliceOrArray       TypeCategory = "StructPointerSliceOrArray"
	CategoryMapStringAnyPointerSliceOrArray TypeCategory = "MapStringAnyPointerSliceOrArray"
	CategoryUnknown                         TypeCategory = "Unknown"
)

Jump to

Keyboard shortcuts

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