database

package
v1.23.10 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: BSD-3-Clause Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DATABASE_MYSQL = "zero.database.mysql"
)
View Source
const (
	DATABASE_ORACLE = "zero.database.oracle"
)
View Source
const (
	DATABASE_POSTGRES = "zero.database.postgres"
)
View Source
const (
	DATABASE_REDIS = "zero.database.redis"
)
View Source
const (
	DATABASE_SQLITE = "zero.database.sqlite3"
)

Variables

View Source
var CustomMySQLDatabase = func(registerName, prefix string) {

	dbURI := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true",
		global.StringValue(fmt.Sprintf("%s.username", prefix)),
		global.StringValue(fmt.Sprintf("%s.password", prefix)),
		global.StringValue(fmt.Sprintf("%s.hostname", prefix)),
		global.IntValue(fmt.Sprintf("%s.hostport", prefix)),
		global.StringValue(fmt.Sprintf("%s.dbname", prefix)))
	dialector := mysql.New(mysql.Config{
		DSN:                       dbURI,
		DefaultStringSize:         256,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	})
	database, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		panic(err)
	}
	dbPool, err := database.DB()
	if err != nil {
		panic(err)
	}

	dbPool.SetMaxIdleConns(global.IntValue(fmt.Sprintf("%s.maxIdleConns", prefix)))
	dbPool.SetMaxOpenConns(global.IntValue(fmt.Sprintf("%s.maxOpenConns", prefix)))
	dbPool.SetConnMaxLifetime(time.Second * time.Duration(global.IntValue(fmt.Sprintf("%s.maxLifetime", prefix))))

	global.Logger().Info(fmt.Sprintf(
		"mysql connect pool init success with %s, maxIdleConns: %d, maxOpenConns: %d, maxLifetime: %d",
		fmt.Sprintf("username:password@tcp(%s:%d)/%s?charset=utf8&parseTime=true",
			global.StringValue(fmt.Sprintf("%s.hostname", prefix)),
			global.IntValue(fmt.Sprintf("%s.hostport", prefix)),
			global.StringValue(fmt.Sprintf("%s.dbname", prefix))),
		global.IntValue(fmt.Sprintf("%s.maxIdleConns", prefix)),
		global.IntValue(fmt.Sprintf("%s.maxOpenConns", prefix)),
		global.IntValue(fmt.Sprintf("%s.maxLifetime", prefix))))
	dataSource := &GormDataSource{}
	dataSource.init(database)
	global.Key(registerName, dataSource)
}
View Source
var CustomOracleDatabase = func(registerName, hostname string, hostport int, servOsid, dbname, password string) {

	err := os.Setenv("NLS_LANG", "AMERICAN_AMERICA.AL32UTF8")
	if err != nil {
		panic(err)
	}

	dataSource := newOracleConnectsKeeper(ora.BuildUrl(
		hostname,
		hostport,
		servOsid,
		dbname,
		password, nil))
	global.Key(registerName, dataSource)
}
View Source
var CustomPostgresDatabase = func(registerName, prefix string) {

	dbURI := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable password=%s TimeZone=Asia/Shanghai",
		global.StringValue(fmt.Sprintf("%s.hostname", prefix)),
		global.IntValue(fmt.Sprintf("%s.hostport", prefix)),
		global.StringValue(fmt.Sprintf("%s.username", prefix)),
		global.StringValue(fmt.Sprintf("%s.dbname", prefix)),
		global.StringValue(fmt.Sprintf("%s.password", prefix)))
	dialector := postgres.New(postgres.Config{
		DSN:                  dbURI,
		PreferSimpleProtocol: false,
	})
	database, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		panic(err)
	}
	dbPool, err := database.DB()
	if err != nil {
		panic(err)
	}

	dbPool.SetMaxIdleConns(global.IntValue(fmt.Sprintf("%s.maxIdleConns", prefix)))
	dbPool.SetMaxOpenConns(global.IntValue(fmt.Sprintf("%s.maxOpenConns", prefix)))
	dbPool.SetConnMaxLifetime(time.Second * time.Duration(global.IntValue(fmt.Sprintf("%s.maxLifetime", prefix))))

	global.Logger().Info(fmt.Sprintf(
		"postgres connect pool init success with %s, maxIdleConns: %d, maxOpenConns: %d, maxLifetime: %d",
		fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai",
			global.StringValue(fmt.Sprintf("%s.hostname", prefix)),
			global.IntValue(fmt.Sprintf("%s.hostport", prefix)),
			global.StringValue(fmt.Sprintf("%s.username", prefix)),
			global.StringValue(fmt.Sprintf("%s.dbname", prefix))),
		global.IntValue(fmt.Sprintf("%s.maxIdleConns", prefix)),
		global.IntValue(fmt.Sprintf("%s.maxOpenConns", prefix)),
		global.IntValue(fmt.Sprintf("%s.maxLifetime", prefix))))
	dataSource := &GormDataSource{}
	dataSource.init(database)
	global.Key(registerName, dataSource)
}
View Source
var CustomSQLiteDatabase = func(registerName, prefix string, tables ...*table) {
	dbaddr := global.StringValue(fmt.Sprintf("zero.%s.dbaddr", prefix))
	if !strings.HasPrefix(dbaddr, "/") {
		dbaddr = path.Join(global.ServerAbsPath(), dbaddr)
	}

	if !structs.Xfexists(path.Dir(dbaddr)) {
		err := os.MkdirAll(path.Dir(dbaddr), 0777)
		if err != nil {
			panic(err)
		}
	}

	s := &SqliteDataSource{}
	s.open(dbaddr, tables...)
	global.Logger().Infof("sqlite open success with %s", dbaddr)
	global.Key(registerName, s)
}
View Source
var ElasticDatabase = func() {
	serverAddr = global.StringValue("zero.elastic.serverAddr")

}
View Source
var MySQLDatabase = func() {
	dbURI := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=true",
		global.StringValue("zero.mysql.username"),
		global.StringValue("zero.mysql.password"),
		global.StringValue("zero.mysql.hostname"),
		global.IntValue("zero.mysql.hostport"),
		global.StringValue("zero.mysql.dbname"))
	dialector := mysql.New(mysql.Config{
		DSN:                       dbURI,
		DefaultStringSize:         256,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	})
	database, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		panic(err)
	}
	dbPool, err := database.DB()
	if err != nil {
		panic(err)
	}

	dbPool.SetMaxIdleConns(global.IntValue("zero.mysql.maxIdleConns"))
	dbPool.SetMaxOpenConns(global.IntValue("zero.mysql.maxOpenConns"))
	dbPool.SetConnMaxLifetime(time.Second * time.Duration(global.IntValue("zero.mysql.maxLifetime")))

	global.Logger().Info(fmt.Sprintf(
		"mysql connect pool init success with %s, maxIdleConns: %d, maxOpenConns: %d, maxLifetime: %d",
		fmt.Sprintf("username:password@tcp(%s:%d)/%s?charset=utf8&parseTime=true",
			global.StringValue("zero.mysql.hostname"),
			global.IntValue("zero.mysql.hostport"),
			global.StringValue("zero.mysql.dbname")),
		global.IntValue("zero.mysql.maxIdleConns"),
		global.IntValue("zero.mysql.maxOpenConns"),
		global.IntValue("zero.mysql.maxLifetime")))
	dataSource := &GormDataSource{}
	dataSource.init(database)
	global.Key(DATABASE_MYSQL, dataSource)
}
View Source
var NewSQLiteTable = func(name, core string, dmls ...string) *table {
	return &table{
		Name: name,
		Core: core,
		DML:  dmls,
	}
}
View Source
var OracleDatabase = func() {

	err := os.Setenv("NLS_LANG", "AMERICAN_AMERICA.AL32UTF8")
	if err != nil {
		panic(err)
	}

	dataSource := newOracleConnectsKeeper(ora.BuildUrl(
		global.StringValue("zero.oracle.hostname"),
		global.IntValue("zero.oracle.hostport"),
		global.StringValue("zero.oracle.servOsid"),
		global.StringValue("zero.oracle.dbname"),
		global.StringValue("zero.oracle.password"), nil))
	global.Key(DATABASE_ORACLE, dataSource)
}
View Source
var PostgresDatabase = func() {
	dbURI := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable password=%s TimeZone=Asia/Shanghai",
		global.StringValue("zero.postgres.hostname"),
		global.IntValue("zero.postgres.hostport"),
		global.StringValue("zero.postgres.username"),
		global.StringValue("zero.postgres.dbname"),
		global.StringValue("zero.postgres.password"))
	dialector := postgres.New(postgres.Config{
		DSN:                  dbURI,
		PreferSimpleProtocol: false,
	})
	database, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		panic(err)
	}
	dbPool, err := database.DB()
	if err != nil {
		panic(err)
	}

	dbPool.SetMaxIdleConns(global.IntValue("zero.postgres.maxIdleConns"))
	dbPool.SetMaxOpenConns(global.IntValue("zero.postgres.maxOpenConns"))
	dbPool.SetConnMaxLifetime(time.Second * time.Duration(global.IntValue("zero.postgres.maxLifetime")))

	global.Logger().Info(fmt.Sprintf(
		"postgres connect pool init success with %s, maxIdleConns: %d, maxOpenConns: %d, maxLifetime: %d",
		fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai",
			global.StringValue("zero.myspostgresql.hostname"),
			global.IntValue("zero.postgres.hostport"),
			global.StringValue("zero.postgres.username"),
			global.StringValue("zero.postgres.dbname")),
		global.IntValue("zero.postgres.maxIdleConns"),
		global.IntValue("zero.postgres.maxOpenConns"),
		global.IntValue("zero.postgres.maxLifetime")))
	dataSource := &GormDataSource{}
	dataSource.init(database)
	global.Key(DATABASE_POSTGRES, dataSource)
}
View Source
var RedisDatabase = func(observers ...RedisKeyspaceExpiredObserver) {
	if len(global.StringValue("zero.redis.sentinel")) > 0 {
		if len(global.StringValue("zero.redis.password")) > 0 {
			failoverClient := redis.NewFailoverClient(&redis.FailoverOptions{
				MasterName:    global.StringValue("zero.redis.sentinel"),
				SentinelAddrs: global.SliceStringValue("zero.redis.hosts"),
				Password:      global.StringValue("zero.redis.password"),
				DB:            global.IntValue("zero.redis.database"),
				IdleTimeout:   time.Duration(global.IntValue("zero.redis.idleTimeout")),
				PoolSize:      global.IntValue("zero.redis.maxActive"),
				MinIdleConns:  global.IntValue("zero.redis.maxIdle"),
			})

			keeper := &xRedisKeeper{}
			keeper.init(failoverClient, observers...)
			global.Key(DATABASE_REDIS, keeper)
		} else {

			failoverClient := redis.NewFailoverClient(&redis.FailoverOptions{
				MasterName:    global.StringValue("zero.redis.sentinel"),
				SentinelAddrs: global.SliceStringValue("zero.redis.hosts"),
				DB:            global.IntValue("zero.redis.database"),
				IdleTimeout:   time.Duration(global.IntValue("zero.redis.idleTimeout")),
				PoolSize:      global.IntValue("zero.redis.maxActive"),
				MinIdleConns:  global.IntValue("zero.redis.maxIdle"),
			})

			keeper := &xRedisKeeper{}
			keeper.init(failoverClient, observers...)
			global.Key(DATABASE_REDIS, keeper)
		}
	} else {
		if len(global.StringValue("zero.redis.password")) > 0 {
			client := redis.NewClient(&redis.Options{
				Addr:         fmt.Sprintf("%s:%d", global.StringValue("zero.redis.hostname"), global.IntValue("zero.redis.hostport")),
				Password:     global.StringValue("zero.redis.password"),
				DB:           global.IntValue("zero.redis.database"),
				IdleTimeout:  time.Duration(global.IntValue("zero.redis.idleTimeout")),
				PoolSize:     global.IntValue("zero.redis.maxActive"),
				MinIdleConns: global.IntValue("zero.redis.maxIdle"),
			})

			keeper := &xRedisKeeper{}
			keeper.init(client, observers...)
			global.Key(DATABASE_REDIS, keeper)
		} else {
			client := redis.NewClient(&redis.Options{
				Addr:         fmt.Sprintf("%s:%d", global.StringValue("zero.redis.hostname"), global.IntValue("zero.redis.hostport")),
				DB:           global.IntValue("zero.redis.database"),
				IdleTimeout:  time.Duration(global.IntValue("zero.redis.idleTimeout")),
				PoolSize:     global.IntValue("zero.redis.maxActive"),
				MinIdleConns: global.IntValue("zero.redis.maxIdle"),
			})

			keeper := &xRedisKeeper{}
			keeper.init(client, observers...)
			global.Key(DATABASE_REDIS, keeper)
		}
	}
}
View Source
var SQLiteDatabase = func(tables ...*table) {
	dbaddr := global.StringValue("zero.sqlite3.dbaddr")
	if !strings.HasPrefix(dbaddr, "/") {
		dbaddr = path.Join(global.ServerAbsPath(), dbaddr)
	}

	if !structs.Xfexists(path.Dir(dbaddr)) {
		err := os.MkdirAll(path.Dir(dbaddr), 0777)
		if err != nil {
			panic(err)
		}
	}

	s := &SqliteDataSource{}
	s.open(dbaddr, tables...)
	global.Logger().Infof("sqlite open success with %s", dbaddr)
	global.Key(DATABASE_SQLITE, s)
}

Functions

This section is empty.

Types

type DataSource added in v1.2.0

type DataSource interface {
	Connect() *sql.DB
	Transaction() *sql.Tx
}

type EQueryRequest

type EQueryRequest struct {
	Query interface{} `json:"query,omitempty"`
	// contains filtered or unexported fields
}

func (*EQueryRequest) Append

func (query *EQueryRequest) Append() error

func (*EQueryRequest) Delete

func (query *EQueryRequest) Delete() error

func (*EQueryRequest) DeleteByQuery

func (query *EQueryRequest) DeleteByQuery() error

func (*EQueryRequest) Get

func (query *EQueryRequest) Get() (*EQueryResponse, error)

func (*EQueryRequest) Init

func (query *EQueryRequest) Init(indexName string, documentID string, deleteQuery bool)

func (*EQueryRequest) InitIndex

func (query *EQueryRequest) InitIndex(indexName string)

func (*EQueryRequest) Search

func (query *EQueryRequest) Search() (*EQueryResponse, error)

func (*EQueryRequest) Update

func (query *EQueryRequest) Update() error

type EQueryResponse

type EQueryResponse struct {
	Datas []interface{}
	Total int
	Error string
}

func (*EQueryResponse) ParserData

func (qresp *EQueryResponse) ParserData(resp *http.Response) error

func (*EQueryResponse) ParserError

func (qresp *EQueryResponse) ParserError(resp *http.Response) error

type EQuerySearch

type EQuerySearch struct {
	Source         []string      `json:"_source,omitempty"`
	Size           int           `json:"size,omitempty"`
	From           int           `json:"from,omitempty"`
	Sort           []interface{} `json:"sort,omitempty"`
	Query          interface{}   `json:"query,omitempty"`
	TrackTotalHits int           `json:"track_total_hits,omitempty"`
}

type GormDataSource added in v1.14.0

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

func (*GormDataSource) Connect added in v1.14.0

func (cp *GormDataSource) Connect() *sql.DB

func (*GormDataSource) SecureTransaction added in v1.22.2

func (cp *GormDataSource) SecureTransaction(performer func(*sql.Tx) any, onevents ...func(error)) any

func (*GormDataSource) Transaction added in v1.14.0

func (cp *GormDataSource) Transaction() *sql.Tx

type RedisKeeper added in v1.12.0

type RedisKeeper interface {
	Client() *redis.Client
	Del(...string) error
	Set(string, string) error
	SetEx(string, string, int) error
	Get(string) (string, error)
	Keys(string) ([]string, error)
}

type RedisKeyspaceExpiredObserver added in v1.12.1

type RedisKeyspaceExpiredObserver interface {
	OnMessage(*redis.Message) error
}

type SecureDataSource added in v1.22.1

type SecureDataSource interface {
	SecureTransaction(func(*sql.Tx) any, ...func(error)) any
}

type SqliteDataSource added in v1.22.1

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

func (*SqliteDataSource) SecureTransaction added in v1.22.2

func (st *SqliteDataSource) SecureTransaction(performer func(*sql.Tx) any, onevents ...func(error)) any

Jump to

Keyboard shortcuts

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