This commit is contained in:
“xHuPo” 2025-05-27 17:44:24 +08:00
parent 44500afd3f
commit 5d370e1077
13 changed files with 529 additions and 519 deletions

View file

@ -25,11 +25,20 @@ func New(cfg *config.DatabaseConfig) (*DB, error) {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
// Configure connection pool with optimized settings
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(max(1, cfg.MaxOpenConns/2)) // 50% of max open connections
db.SetConnMaxLifetime(30 * time.Minute) // Longer lifetime to reduce connection churn
db.SetConnMaxIdleTime(5 * time.Minute) // Close idle connections after 5 minutes
// Configure connection pool based on database type
if cfg.Driver == "sqlite3" {
// SQLite is a file-based database - simpler connection settings
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
db.SetConnMaxLifetime(0) // Connections don't need to be recycled
db.SetConnMaxIdleTime(0)
} else {
// For other databases (MySQL, PostgreSQL etc.)
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(max(1, cfg.MaxOpenConns/2)) // 50% of max open connections
db.SetConnMaxLifetime(30 * time.Minute)
db.SetConnMaxIdleTime(5 * time.Minute)
}
// Verify connection with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@ -45,9 +54,16 @@ func New(cfg *config.DatabaseConfig) (*DB, error) {
// WithTx executes a function within a transaction with retry logic
func (db *DB) WithTx(ctx context.Context, fn func(*sqlx.Tx) error) error {
const maxRetries = 3
var maxRetries int
var lastErr error
// Adjust retry settings based on database type
if db.DriverName() == "sqlite3" {
maxRetries = 5 // SQLite needs more retries due to busy timeouts
} else {
maxRetries = 3
}
// Default transaction options
opts := &sql.TxOptions{
Isolation: sql.LevelReadCommitted,

View file

@ -1,6 +1,26 @@
CREATE TABLE IF NOT EXISTS otp (
id SERIAL PRIMARY KEY,
openid VARCHAR(255) UNIQUE NOT NULL,
token VARCHAR(255),
createtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id VARCHAR(255) NOT NULL,
openid VARCHAR(255) NOT NULL,
name VARCHAR(100) NOT NULL,
issuer VARCHAR(255),
secret VARCHAR(255) NOT NULL,
algorithm VARCHAR(10) NOT NULL DEFAULT 'SHA1',
digits INTEGER NOT NULL DEFAULT 6,
period INTEGER NOT NULL DEFAULT 30,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, name),
UNIQUE(openid)
);
-- Add index for faster lookups
CREATE INDEX IF NOT EXISTS idx_otp_user_id ON otp(user_id);
CREATE INDEX IF NOT EXISTS idx_otp_openid ON otp(openid);
-- Trigger to update the updated_at timestamp
CREATE TRIGGER IF NOT EXISTS update_otp_timestamp
AFTER UPDATE ON otp
BEGIN
UPDATE otp SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
END;

View file

@ -1,5 +1,5 @@
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
id INTEGER PRIMARY KEY AUTOINCREMENT,
openid VARCHAR(255) UNIQUE NOT NULL,
session_key VARCHAR(255) UNIQUE NOT NULL
);