This commit is contained in:
oneao committed 2025-11-29 17:23:27 +08:00
1 parent 8408cf779f
commit 25a9e41025
58 files changed
+2079 -6308

No files matched your search

+30 -19
View File
@@ -2,7 +2,7 @@
package db
import (
"cn/oneao/base-go/config"
"cn/oneao/base-go/conf"
sqlcg "cn/oneao/base-go/db/sqlc"
"context"
"fmt"
@@ -11,19 +11,18 @@ import (
)
var (
DB *pgxpool.Pool
DBClient *sqlcg.Queries
DB *pgxpool.Pool
Queries *sqlcg.Queries
)
func InitDB() error {
cfg := config.Db
func InitDB() {
cfg := conf.GetConf().Pgsql
sslMode := "disable"
if cfg.SllMode {
sslMode = "require"
}
// 构建 DSN
dsn := fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s?sslmode=%s&TimeZone=%s",
cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Dbname, sslMode, cfg.TimeZone,
@@ -32,25 +31,37 @@ func InitDB() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
pool, err := pgxpool.New(ctx, dsn)
// 使用可修改配置
cfgPool, err := pgxpool.ParseConfig(dsn)
if err != nil {
return fmt.Errorf("unable to connect to database: %w", err)
panic(err)
}
// 给连接池参数设置默认值
if cfg.MaxOpenConns <= 0 {
cfg.MaxOpenConns = 10
}
if cfg.MaxIdleConns <= 0 {
cfg.MaxIdleConns = 5
}
if cfg.ConnMaxLifetime <= 0 {
cfg.ConnMaxLifetime = 30 * time.Minute
}
cfgPool.MaxConns = cfg.MaxOpenConns
cfgPool.MinConns = cfg.MaxIdleConns
cfgPool.MaxConnLifetime = cfg.ConnMaxLifetime
pool, err := pgxpool.NewWithConfig(ctx, cfgPool)
if err != nil {
panic(err)
}
// 测试连接
if err := pool.Ping(ctx); err != nil {
return fmt.Errorf("ping database failed: %w", err)
panic(err)
}
DB = pool
// 初始化 sqlc Queries,全局可用
DBClient = sqlcg.New(DB)
// 可选:设置连接池参数
pool.Config().MaxConns = int32(cfg.MaxOpenConns)
pool.Config().MinConns = int32(cfg.MaxIdleConns)
pool.Config().MaxConnLifetime = cfg.ConnMaxLifetime
return nil
Queries = sqlcg.New(DB)
}
Whitespace-only changes.
@@ -0,0 +1,2 @@
-- name: ListMoneySysCategory :many
SELECT * FROM money_sys_category;
@@ -0,0 +1,8 @@
-- name: BatchInsertMoneyUserCategories :copyfrom
INSERT INTO money_user_category (id, user_id, name, icon, type, sort_number)
VALUES ($1, $2, $3, $4, $5, $6);
-- name: FindUserMoneyCategoriesByUserID :many
SELECT *
FROM money_user_category
WHERE user_id = $1;
@@ -1,23 +1,30 @@
-- name: CreateUser :execrows
-- 插入用户并返回刚创建的记录
-- name: InsertUser :execrows
INSERT INTO user_info (id, account, password)
VALUES ($1, $2, $3);
-- name: GetUserById :one
-- 根据 ID 查询单条用户记录
-- name: GetUserById :one
SELECT *
FROM user_info
WHERE id = $1;
-- name: GetUserByAccountAndPassword :one
-- 根据账号查询单条用户记录
-- name: GetUserByAccount :one
SELECT *
FROM user_info
WHERE account = $1;
-- 根据账号和密码查询单条用户记录(登录用)
-- name: GetUserForLogin :one
SELECT *
FROM user_info
WHERE account = $1
AND password = $2;
-- 更新用户最后登录时间,并返回更新后的记录
-- name: UpdateUserLoginLastTime :execrows
-- 更新用户最后登录时间,并返回影响的行数
UPDATE user_info
SET last_login_time = now()
WHERE id = $1;
+2 -2
View File
@@ -26,7 +26,7 @@ CREATE TABLE money_sys_category(
id BIGINT PRIMARY KEY ,
name VARCHAR(255) NOT NULL ,
icon VARCHAR(255) NOT NULL,
type SMALLINT DEFAULT 0,
type INT DEFAULT 0,
sort_number INT DEFAULT 0,
create_time timestamp DEFAULT CURRENT_TIMESTAMP
);
@@ -36,7 +36,7 @@ CREATE TABLE money_user_category(
user_id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL ,
icon VARCHAR(255) NOT NULL,
type SMALLINT DEFAULT 0,
type INT DEFAULT 0,
sort_number INT DEFAULT 0,
create_time timestamp DEFAULT CURRENT_TIMESTAMP
)
@@ -0,0 +1,47 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: copyfrom.go
package dbtype
import (
"context"
)
// iteratorForBatchInsertMoneyUserCategories implements pgx.CopyFromSource.
type iteratorForBatchInsertMoneyUserCategories struct {
rows []BatchInsertMoneyUserCategoriesParams
skippedFirstNextCall bool
}
func (r *iteratorForBatchInsertMoneyUserCategories) Next() bool {
if len(r.rows) == 0 {
return false
}
if !r.skippedFirstNextCall {
r.skippedFirstNextCall = true
return true
}
r.rows = r.rows[1:]
return len(r.rows) > 0
}
func (r iteratorForBatchInsertMoneyUserCategories) Values() ([]interface{}, error) {
return []interface{}{
r.rows[0].ID,
r.rows[0].UserID,
r.rows[0].Name,
r.rows[0].Icon,
r.rows[0].Type,
r.rows[0].SortNumber,
}, nil
}
func (r iteratorForBatchInsertMoneyUserCategories) Err() error {
return nil
}
func (q *Queries) BatchInsertMoneyUserCategories(ctx context.Context, arg []BatchInsertMoneyUserCategoriesParams) (int64, error) {
return q.db.CopyFrom(ctx, []string{"money_user_category"}, []string{"id", "user_id", "name", "icon", "type", "sort_number"}, &iteratorForBatchInsertMoneyUserCategories{rows: arg})
}
+2 -1
View File
@@ -2,7 +2,7 @@
// versions:
// sqlc v1.30.0
package sqlcg
package dbtype
import (
"context"
@@ -15,6 +15,7 @@ type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}
func New(db DBTX) *Queries {
@@ -2,7 +2,7 @@
// versions:
// sqlc v1.30.0
package sqlcg
package dbtype
import (
"github.com/jackc/pgx/v5/pgtype"
@@ -23,7 +23,7 @@ type MoneySysCategory struct {
ID int64
Name string
Icon string
Type pgtype.Int2
Type pgtype.Int4
SortNumber pgtype.Int4
CreateTime pgtype.Timestamp
}
@@ -33,7 +33,7 @@ type MoneyUserCategory struct {
UserID int64
Name string
Icon string
Type pgtype.Int2
Type pgtype.Int4
SortNumber pgtype.Int4
CreateTime pgtype.Timestamp
}
@@ -0,0 +1,41 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: money_sys_category.sql
package dbtype
import (
"context"
)
const listMoneySysCategory = `-- name: ListMoneySysCategory :many
SELECT id, name, icon, type, sort_number, create_time FROM money_sys_category
`
func (q *Queries) ListMoneySysCategory(ctx context.Context) ([]MoneySysCategory, error) {
rows, err := q.db.Query(ctx, listMoneySysCategory)
if err != nil {
return nil, err
}
defer rows.Close()
var items []MoneySysCategory
for rows.Next() {
var i MoneySysCategory
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Icon,
&i.Type,
&i.SortNumber,
&i.CreateTime,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,55 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: money_user_category.sql
package dbtype
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
type BatchInsertMoneyUserCategoriesParams struct {
ID int64
UserID int64
Name string
Icon string
Type pgtype.Int4
SortNumber pgtype.Int4
}
const findUserMoneyCategoriesByUserID = `-- name: FindUserMoneyCategoriesByUserID :many
SELECT id, user_id, name, icon, type, sort_number, create_time
FROM money_user_category
WHERE user_id = $1
`
func (q *Queries) FindUserMoneyCategoriesByUserID(ctx context.Context, userID int64) ([]MoneyUserCategory, error) {
rows, err := q.db.Query(ctx, findUserMoneyCategoriesByUserID, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []MoneyUserCategory
for rows.Next() {
var i MoneyUserCategory
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Name,
&i.Icon,
&i.Type,
&i.SortNumber,
&i.CreateTime,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -3,47 +3,21 @@
// sqlc v1.30.0
// source: user_info.sql
package sqlcg
package dbtype
import (
"context"
)
const createUser = `-- name: CreateUser :execrows
INSERT INTO user_info (id, account, password)
VALUES ($1, $2, $3)
`
type CreateUserParams struct {
ID int64
Account string
Password string
}
// 插入用户并返回刚创建的记录
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (int64, error) {
result, err := q.db.Exec(ctx, createUser, arg.ID, arg.Account, arg.Password)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getUserByAccountAndPassword = `-- name: GetUserByAccountAndPassword :one
const getUserByAccount = `-- name: GetUserByAccount :one
SELECT id, seq_no, account, password, email, username, gender, create_time, update_time, last_login_time
FROM user_info
WHERE account = $1
AND password = $2
`
type GetUserByAccountAndPasswordParams struct {
Account string
Password string
}
// 根据账号和密码查询单条用户记录(登录用)
func (q *Queries) GetUserByAccountAndPassword(ctx context.Context, arg GetUserByAccountAndPasswordParams) (UserInfo, error) {
row := q.db.QueryRow(ctx, getUserByAccountAndPassword, arg.Account, arg.Password)
// 根据账号查询单条用户记录
func (q *Queries) GetUserByAccount(ctx context.Context, account string) (UserInfo, error) {
row := q.db.QueryRow(ctx, getUserByAccount, account)
var i UserInfo
err := row.Scan(
&i.ID,
@@ -85,13 +59,64 @@ func (q *Queries) GetUserById(ctx context.Context, id int64) (UserInfo, error) {
return i, err
}
const getUserForLogin = `-- name: GetUserForLogin :one
SELECT id, seq_no, account, password, email, username, gender, create_time, update_time, last_login_time
FROM user_info
WHERE account = $1
AND password = $2
`
type GetUserForLoginParams struct {
Account string
Password string
}
// 根据账号和密码查询单条用户记录(登录用)
func (q *Queries) GetUserForLogin(ctx context.Context, arg GetUserForLoginParams) (UserInfo, error) {
row := q.db.QueryRow(ctx, getUserForLogin, arg.Account, arg.Password)
var i UserInfo
err := row.Scan(
&i.ID,
&i.SeqNo,
&i.Account,
&i.Password,
&i.Email,
&i.Username,
&i.Gender,
&i.CreateTime,
&i.UpdateTime,
&i.LastLoginTime,
)
return i, err
}
const insertUser = `-- name: InsertUser :execrows
INSERT INTO user_info (id, account, password)
VALUES ($1, $2, $3)
`
type InsertUserParams struct {
ID int64
Account string
Password string
}
// 插入用户并返回刚创建的记录
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) (int64, error) {
result, err := q.db.Exec(ctx, insertUser, arg.ID, arg.Account, arg.Password)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateUserLoginLastTime = `-- name: UpdateUserLoginLastTime :execrows
UPDATE user_info
SET last_login_time = now()
WHERE id = $1
`
// 更新用户最后登录时间,并返回影响的行数
// 更新用户最后登录时间,并返回更新后的记录
func (q *Queries) UpdateUserLoginLastTime(ctx context.Context, id int64) (int64, error) {
result, err := q.db.Exec(ctx, updateUserLoginLastTime, id)
if err != nil {