u
This commit is contained in:
1 parent
7552670e4a
commit
01ea998605
13 files changed
+173
-45
No files matched your search
@@ -0,0 +1,38 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"base-framework/pkg/config"
|
||||
"base-framework/pkg/router"
|
||||
"base-framework/pkg/utils/response"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Client 封装数据库连接对象
|
||||
type Client struct {
|
||||
Conn *sql.DB
|
||||
}
|
||||
|
||||
// NewClient 根据 context 获取 orgId 并返回 Client 对象
|
||||
func NewClient(c *router.Context) *Client {
|
||||
val, ok := c.Get("orgId")
|
||||
fmt.Println(val)
|
||||
if !ok {
|
||||
response.Error(c).Code(response.CodeInvalidOrgCode).Send()
|
||||
return nil
|
||||
}
|
||||
|
||||
orgId, ok := val.(string)
|
||||
if !ok || orgId == "" {
|
||||
response.Error(c).Code(response.CodeInvalidOrgCode).Send()
|
||||
return nil
|
||||
}
|
||||
|
||||
conn, ok := config.GetDB(orgId)
|
||||
if !ok || conn == nil {
|
||||
response.Error(c).Code(response.CodeInvalidOrgCode).Send()
|
||||
return nil
|
||||
}
|
||||
|
||||
return &Client{Conn: conn}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package db
|
||||
@@ -0,0 +1 @@
|
||||
package db
|
||||
@@ -0,0 +1,53 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (c *Client) QueryRows(query string, args ...any) ([]map[string]any, error) {
|
||||
if c.Conn == nil {
|
||||
return nil, fmt.Errorf("database connection is nil")
|
||||
}
|
||||
|
||||
rows, err := c.Conn.Query(query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func(rows *sql.Rows) {
|
||||
_ = rows.Close()
|
||||
}(rows)
|
||||
|
||||
// 获取列名
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
results := make([]map[string]any, 0)
|
||||
for rows.Next() {
|
||||
// 为每列创建一个接口值的 slice
|
||||
values := make([]any, len(columns))
|
||||
valuePtrs := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
valuePtrs[i] = &values[i]
|
||||
}
|
||||
|
||||
if err := rows.Scan(valuePtrs...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rowMap := make(map[string]any)
|
||||
for i, col := range columns {
|
||||
rowMap[col] = values[i]
|
||||
}
|
||||
|
||||
results = append(results, rowMap)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package db
|
||||
Reference in new issue
Block a user