GoTest/sql/init.sql
2025-11-29 03:27:19 +08:00

63 lines
3.0 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- 创建数据库(如果不存在)
CREATE DATABASE IF NOT EXISTS yinli CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 使用数据库
USE yinli;
-- 创建用户表
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`name` varchar(100) NOT NULL COMMENT '用户名',
`password` varchar(255) NOT NULL COMMENT '密码',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '用户状态 1:正常 0:禁用',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_name` (`name`),
KEY `idx_status` (`status`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
-- 插入测试数据
INSERT INTO `user` (`name`, `password`, `status`) VALUES
('admin', '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 1),
('testuser', '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 1)
ON DUPLICATE KEY UPDATE `name` = VALUES(`name`);
-- 创建索引优化查询
CREATE INDEX IF NOT EXISTS `idx_user_name_status` ON `user` (`name`, `status`);
-- 创建会话表(可选,用于会话管理)
CREATE TABLE IF NOT EXISTS `user_session` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '会话ID',
`user_id` int(11) unsigned NOT NULL COMMENT '用户ID',
`token` varchar(500) NOT NULL COMMENT 'JWT令牌',
`expires_at` datetime NOT NULL COMMENT '过期时间',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_token` (`token`(255)),
KEY `idx_expires_at` (`expires_at`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户会话表';
-- 创建API访问日志表可选
CREATE TABLE IF NOT EXISTS `api_log` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '日志ID',
`user_id` int(11) unsigned DEFAULT NULL COMMENT '用户ID',
`method` varchar(10) NOT NULL COMMENT 'HTTP方法',
`path` varchar(255) NOT NULL COMMENT '请求路径',
`status_code` int(11) NOT NULL COMMENT '响应状态码',
`ip` varchar(45) NOT NULL COMMENT '客户端IP',
`user_agent` varchar(500) DEFAULT NULL COMMENT '用户代理',
`request_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '请求时间',
`response_time` int(11) DEFAULT NULL COMMENT '响应时间(毫秒)',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_path` (`path`),
KEY `idx_status_code` (`status_code`),
KEY `idx_ip` (`ip`),
KEY `idx_request_time` (`request_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='API访问日志表';