GetTokenStatistics 获取按令牌统计的数据
(startTimestamp, endTimestamp int, username, tokenName, modelName string, channel int, group, defaultTime string)
| 161 | |
| 162 | // GetTokenStatistics 获取按令牌统计的数据 |
| 163 | func GetTokenStatistics(startTimestamp, endTimestamp int, username, tokenName, modelName string, channel int, group, defaultTime string) ([]TokenStatistics, error) { |
| 164 | var statistics []TokenStatistics |
| 165 | |
| 166 | // 构建查询条件 |
| 167 | tx := LOG_DB.Table("logs").Select(` |
| 168 | created_at, |
| 169 | token_name, |
| 170 | COUNT(*) as count, |
| 171 | SUM(quota) as quota |
| 172 | `).Where("type = ?", 2) // LogTypeConsume = 2 |
| 173 | |
| 174 | if username != "" { |
| 175 | tx = tx.Where("username = ?", username) |
| 176 | } |
| 177 | if tokenName != "" { |
| 178 | tx = tx.Where("token_name = ?", tokenName) |
| 179 | } |
| 180 | if modelName != "" { |
| 181 | tx = tx.Where("model_name LIKE ?", "%"+modelName+"%") |
| 182 | } |
| 183 | if channel != 0 { |
| 184 | tx = tx.Where("channel_id = ?", channel) |
| 185 | } |
| 186 | if group != "" { |
| 187 | tx = tx.Where("`group` = ?", group) |
| 188 | } |
| 189 | if startTimestamp != 0 { |
| 190 | tx = tx.Where("created_at >= ?", startTimestamp) |
| 191 | } |
| 192 | if endTimestamp != 0 { |
| 193 | tx = tx.Where("created_at <= ?", endTimestamp) |
| 194 | } |
| 195 | |
| 196 | // 按时间粒度分组 - 使用数据库无关的函数 |
| 197 | var groupBy string |
| 198 | switch defaultTime { |
| 199 | case "hour": |
| 200 | if common.UsingMySQL { |
| 201 | groupBy = "token_name, DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d %H:00:00')" |
| 202 | } else if common.UsingPostgreSQL { |
| 203 | groupBy = "token_name, TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY-MM-DD HH24:00:00')" |
| 204 | } else { |
| 205 | // SQLite |
| 206 | groupBy = "token_name, strftime('%Y-%m-%d %H:00:00', datetime(created_at, 'unixepoch'))" |
| 207 | } |
| 208 | case "day": |
| 209 | if common.UsingMySQL { |
| 210 | groupBy = "token_name, DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d')" |
| 211 | } else if common.UsingPostgreSQL { |
| 212 | groupBy = "token_name, TO_CHAR(TO_TIMESTAMP(created_at), 'YYYY-MM-DD')" |
| 213 | } else { |
| 214 | // SQLite |
| 215 | groupBy = "token_name, strftime('%Y-%m-%d', datetime(created_at, 'unixepoch'))" |
| 216 | } |
| 217 | case "week": |
| 218 | if common.UsingMySQL { |
| 219 | groupBy = "token_name, DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%U')" |
| 220 | } else if common.UsingPostgreSQL { |
no test coverage detected