报错 throw new Error('invalid "instanceof" keyword value ' + c)解决办法

欢迎访问我的个人博客:http://www.xiaolongwu.cn

显示如下报错
D:\myProjectDemos\webpackDemo\node_modules\ajv-keywords\keywords\instanceof.js:52
    throw new Error('invalid "instanceof" keyword value ' + c);
    ^

Error: invalid "instanceof" keyword value Promise
    at getConstructor (D:\myProjectDemos\webpackDemo\node_modules\ajv-keywords\keywords\instanceof.js:52:11)
    at Ajv.compile (D:\myProjectDemos\webpa
数据插入失败,正在进行第2次重试: StatementCallback; uncategorized SQLException for SQL [INSERT INTO my_battery_info_M240910700000001 USING my_battery_info TAGS ('M240910700000001') (ts, id, battery_voltage, battery_current, battery_soc, battery_hard_version, battery_soft_version, battery_work_mode, battery_protect_code, battery_error_code, battery_temperature_max, battery_temperature_min, battery_voltage_max, battery_voltage_min, mos_status, mos_temp, battery_cycle_times, steady_status, cell_voltage, model, manufacture, imei, imsi, iccid, tracker_hardware_version, tracker_software_version, csq, network_type, location_mode, longitude, longitude_direction, latitude, latitude_direction, gps_speed, gps_signal, satellite_num, accuracy, flag, client_id, topic, product_key, handled, todo_now, needack, businessmode, upload_time, create_time, update_time, payload, project_id, sn, soh, battery_temperature_avg, charge_mode, low_battery_warn, charge_current_max, discharge_current_max, charge_current_avg, discharge_current_avg, gps_cog, total_charge_energy, charge_cycles_history, charge_capacity_history, discharge_capacity_history, ntc1, ntc2, ntc3, ntc4, tracker_communication_status, battery_kind, dsoc, correction_rate, tsoc, bsoc, fcc, actual_soh, charging_sop, discharging_sop, task_max_delay_1ms, task_max_delay_10ms, task_max_delay_100ms, task_max_delay_500ms, task_max_time_1ms, task_max_time_10ms, task_max_time_100ms, task_max_time_500ms, empty_count, cell_info, gps_max_signal, msg_delay_time, data_type, battery_vehicle_status, storage_status, ota_status, lock_status, battery_vehicle_alarm_status) VALUES ('2024-09-23 08:58:06.000', 320, 70000, 0, 0, NULL, 'V1.00', '48', NULL, '000000000008000000000004', 24, -31, 3199, 3177, 8, 25, 0, NULL, NULL, NULL, NULL, '865271061996824', NULL, '898607F01124F9007644', NULL, '2024-09-20 14:35', NULL, NULL, NULL, '0', 'E', '0', 'N', NULL, '9', NULL, NULL, 1, NULL, NULL, NULL, 0, NULL, NULL, NULL, '2024-09-23 08:58:06.000', '2024-09-23 13:54:31.000', '2024-09-23 13:54:31.000', '{"ts":1727053086,"code":200,"data":[1,0,1,0,0,0,0,25,225,26,2,188,12,127,12,105,48,8,0,0,0,0,0,0,0,8,0,0,0,0,0,4,105,120],"tracker":[0,0,9,"865271061996824","898607F01124F9007644","2024-09-20 14:35"]}', 38, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0)]; SQL state []; error code [9730]; TDengine ERROR (0x2602): sql: INSERT INTO my_battery_info_M240910700000001 USING my_battery_info TAGS ('M240910700000001') (ts, id, battery_voltage, battery_current, battery_soc, battery_hard_version, battery_soft_version, battery_work_mode, battery_protect_code, battery_error_code, battery_temperature_max, battery_temperature_min, battery_voltage_max, battery_voltage_min, mos_status, mos_temp, battery_cycle_times, steady_status, cell_voltage, model, manufacture, imei, imsi, iccid, tracker_hardware_version, tracker_software_version, csq, network_type, location_mode, longitude, longitude_direction, latitude, latitude_direction, gps_speed, gps_signal, satellite_num, accuracy, flag, client_id, topic, product_key, handled, todo_now, needack, businessmode, upload_time, create_time, update_time, payload, project_id, sn, soh, battery_temperature_avg, charge_mode, low_battery_warn, charge_current_max, discharge_current_max, charge_current_avg, discharge_current_avg, gps_cog, total_charge_energy, charge_cycles_history, charge_capacity_history, discharge_capacity_history, ntc1, ntc2, ntc3, ntc4, tracker_communication_status, battery_kind, dsoc, correction_rate, tsoc, bsoc, fcc, actual_soh, charging_sop, discharging_sop, task_max_delay_1ms, task_max_delay_10ms, task_max_delay_100ms, task_max_delay_500ms, task_max_time_1ms, task_max_time_10ms, task_max_time_100ms, task_max_time_500ms, empty_count, cell_info, gps_max_signal, msg_delay_time, data_type, battery_vehicle_status, storage_status, ota_status, lock_status, battery_vehicle_alarm_status) VALUES ('2024-09-23 08:58:06.000', 320, 70000, 0, 0, NULL, 'V1.00', '48', NULL, '000000000008000000000004', 24, -31, 3199, 3177, 8, 25, 0, NULL, NULL, NULL, NULL, '865271061996824', NULL, '898607F01124F9007644', NULL, '2024-09-20 14:35', NULL, NULL, NULL, '0', 'E', '0', 'N', NULL, '9', NULL, NULL, 1, NULL, NULL, NULL, 0, NULL, NULL, NULL, '2024-09-23 08:58:06.000', '2024-09-23 13:54:31.000', '2024-09-23 13:54:31.000', '{"ts":1727053086,"code":200,"data":[1,0,1,0,0,0,0,25,225,26,2,188,12,127,12,105,48,8,0,0,0,0,0,0,0,8,0,0,0,0,0,4,105,120],"tracker":[0,0,9,"865271061996824","898607F01124F9007644","2024-09-20 14:35"]}', 38, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, 0), desc: Invalid column name: id,超级表的创建sql是:CREATE STABLE IF NOT EXISTS my_battery_info ( ts TIMESTAMP, battery_voltage INT, battery_current INT, battery_soc INT, battery_hard_version BINARY(100), battery_soft_version BINARY(100), battery_work_mode BINARY(100), battery_protect_code BINARY(100), battery_error_code BINARY(100), battery_temperature_max INT, battery_temperature_min INT, battery_voltage_max INT, battery_voltage_min INT, mos_status INT, mos_temp INT, battery_cycle_times INT, steady_status INT, cell_voltage BINARY(500), model BINARY(100), manufacture BINARY(100), imei BINARY(100), imsi BINARY(100), iccid BINARY(100), tracker_hardware_version BINARY(100), tracker_software_version BINARY(100), csq BINARY(100), network_type BINARY(100), location_mode BINARY(100), longitude BINARY(100), longitude_direction BINARY(100), latitude BINARY(100), latitude_direction BINARY(100), gps_speed BINARY(100), gps_signal BINARY(100), satellite_num BINARY(100), accuracy BINARY(100), flag INT, client_id BINARY(100), `topic` BINARY(100), product_key BINARY(100), handled INT, todo_now INT, needack TINYINT, businessmode BINARY(100), create_time TIMESTAMP, update_time TIMESTAMP, payload BINARY(5000), project_id INT, sn BINARY(100), soh INT, battery_temperature_avg INT, charge_mode INT, low_battery_warn INT, charge_current_max INT, discharge_current_max INT, charge_current_avg INT, discharge_current_avg INT, gps_cog BINARY(100), total_charge_energy DOUBLE, charge_cycles_history INT, charge_capacity_history DOUBLE, discharge_capacity_history DOUBLE, ntc1 INT, ntc2 INT, ntc3 INT, ntc4 INT, tracker_communication_status BINARY(100), battery_kind BINARY(100), dsoc INT, correction_rate INT, tsoc INT, bsoc INT, fcc INT, actual_soh INT, charging_sop INT, discharging_sop INT, task_max_delay_1ms INT, task_max_delay_10ms INT, task_max_delay_100ms INT, task_max_delay_500ms INT, task_max_time_1ms INT, task_max_time_10ms INT, task_max_time_100ms INT, task_max_time_500ms INT, empty_count INT, cell_info BINARY(5000), gps_max_signal INT, msg_delay_time INT, data_type INT, battery_vehicle_status INT, storage_status INT, ota_status INT, lock_status INT, battery_vehicle_alarm_status INT ) TAGS ( battery_id BINARY(100) );。然后Java代码是:package com.bms.sync.data.service; import com.bms.sync.data.util.TimeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Arrays; @Service public class DataMigrationService { private final JdbcTemplate mysqlJdbcTemplate; private final JdbcTemplate tdengineJdbcTemplate; @Value("${table.tag.columns}") private String tagColumnsConfig; @Value("${table.timestamp.field}") private String timestampField; // TDengine时间戳字段名 @Value("${table.tdengine.timestamp.field}") private String tdengineTimestampField; @Value("${performance.batch-size.historical}") private int historicalBatchSize; @Value("${performance.batch-size.incremental}") private int incrementalBatchSize; // 重试配置 @Value("${retry.max-attempts}") private int maxRetries; @Value("${retry.interval}") private long retryInterval; @Autowired private PerformanceMonitorService performanceMonitorService; @Autowired private TableAutoCreateService tableAutoCreateService; @Autowired private RedisQueueService redisQueueService; @Autowired public DataMigrationService(JdbcTemplate mysqlJdbcTemplate, JdbcTemplate tdengineJdbcTemplate, PerformanceMonitorService performanceMonitorService, TableAutoCreateService tableAutoCreateService, RedisQueueService redisQueueService) { this.mysqlJdbcTemplate = mysqlJdbcTemplate; this.tdengineJdbcTemplate = tdengineJdbcTemplate; this.performanceMonitorService = performanceMonitorService; this.tableAutoCreateService = tableAutoCreateService; this.redisQueueService = redisQueueService; } /** * 迁移数据(支持批量处理) * @param mysqlTableName MySQL表名 * @param superTableName TDengine超级表名 */ public void migrateData(String mysqlTableName, String superTableName) { long startTime = System.currentTimeMillis(); try { System.out.println("开始数据迁移: " + mysqlTableName + " -> " + superTableName); // 确保表结构已创建 System.out.println("步骤1: 确保表结构已创建"); ensureTableStructureExists(mysqlTableName, superTableName); // 1. 获取总记录数 System.out.println("步骤2: 获取总记录数"); int totalRecords = getTotalRecordCount(mysqlTableName); if (totalRecords == 0) { System.out.println("没有数据需要迁移"); return; } System.out.println("总记录数: " + totalRecords); // 2. 分批迁移数据(增加批处理大小以提高效率) int batchSize = historicalBatchSize; // 每批处理5000条记录 int totalBatches = (int) Math.ceil((double) totalRecords / batchSize); System.out.println("总批次数: " + totalBatches + ",批处理大小: " + batchSize); // 使用Redis队列处理历史数据 System.out.println("步骤3: 使用Redis队列处理历史数据"); processHistoricalDataWithQueue(mysqlTableName, superTableName, totalRecords, batchSize); System.out.println("数据迁移完成"); } catch (Exception e) { System.err.println("数据迁移失败: " + e.getMessage()); e.printStackTrace(); } finally { long endTime = System.currentTimeMillis(); performanceMonitorService.recordTime("data.migration", endTime - startTime); performanceMonitorService.incrementCounter("data.migration.totalRecords", getTotalRecordCount(mysqlTableName)); System.out.println("数据迁移总耗时: " + (endTime - startTime) + "ms"); } } /** * 确保表结构已创建 * @param mysqlTableName MySQL表名 * @param superTableName TDengine超级表名 */ public void ensureTableStructureExists(String mysqlTableName, String superTableName) { try { System.out.println("确保表结构存在: " + mysqlTableName + " -> " + superTableName); // 从配置中获取标签列 String[] tagColumnsArray = tagColumnsConfig.split(","); List<String> tagColumns = Arrays.asList(tagColumnsArray); // 自动创建表结构 tableAutoCreateService.autoCreateTableStructure(mysqlTableName, superTableName, tagColumns); System.out.println("表结构创建完成"); } catch (Exception e) { System.err.println("确保表结构存在时失败: " + e.getMessage()); e.printStackTrace(); } } /** * 使用Redis队列处理历史数据 * @param mysqlTableName MySQL表名 * @param superTableName TDengine超级表名 * @param totalRecords 总记录数 * @param batchSize 批处理大小 */ private void processHistoricalDataWithQueue(String mysqlTableName, String superTableName, int totalRecords, int batchSize) { try { String queueName = mysqlTableName + "_to_" + superTableName; // 清空之前的队列数据 redisQueueService.clearQueue(queueName); // 使用基于时间戳的分页方式替代LIMIT/OFFSET,避免数据遗漏 String lastProcessedTime = null; String currentTime = java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); long startTime = System.currentTimeMillis(); int totalProcessed = 0; boolean hasMoreData = true; while (hasMoreData) { // 构建查询SQL,使用时间戳分页 StringBuilder querySql = new StringBuilder(); querySql.append("SELECT * FROM ").append(mysqlTableName); // 添加时间范围条件,确保时间字段不为空 querySql.append(" WHERE ").append(timestampField).append(" IS NOT NULL"); // 确保时间字段不为空 if (lastProcessedTime != null && !lastProcessedTime.isEmpty()) { querySql.append(" AND ").append(timestampField).append(" > '").append(lastProcessedTime).append("'"); } querySql.append(" ORDER BY ").append(timestampField).append(" ASC"); List<Map<String, Object>> records = mysqlJdbcTemplate.queryForList(querySql.toString()); if (!records.isEmpty()) { // 将数据放入Redis队列 redisQueueService.pushHistoricalDataToQueue(queueName, records); // 更新最大时间戳 Object lastTimestamp = records.get(records.size() - 1).get(timestampField); if (lastTimestamp != null) { lastProcessedTime = lastTimestamp.toString(); } totalProcessed += records.size(); System.out.println("已将 " + records.size() + " 条记录放入Redis队列,总计已处理: " + totalProcessed); } else { hasMoreData = false; } } long endTime = System.currentTimeMillis(); System.out.println("历史数据已全部放入Redis队列,队列大小: " + redisQueueService.getQueueSize(queueName) + ",耗时: " + (endTime - startTime) + "ms"); // 从Redis队列中取出数据并同步到TDengine int successCount = syncDataFromQueue(queueName, superTableName); System.out.println("历史数据同步完成,总计成功同步记录数: " + successCount); } catch (Exception e) { System.err.println("使用Redis队列处理历史数据失败: " + e.getMessage()); e.printStackTrace(); } } /** * 从Redis队列中取出数据并同步到TDengine * @param queueName 队列名称 * @param superTableName TDengine超级表名 * @return 成功同步的记录数 */ private int syncDataFromQueue(String queueName, String superTableName) { int totalSynced = 0; int batchSize = incrementalBatchSize; // 从队列中每次取出100条记录进行同步 long startTime = System.currentTimeMillis(); System.out.println("开始从Redis队列同步数据到TDengine,批处理大小: " + batchSize); int batchCount = 0; while (redisQueueService.getQueueSize(queueName) > 0) { // 先查看但不移除队列中的数据 List<Object> records = redisQueueService.peekBatchFromQueue(queueName, batchSize); if (records != null && !records.isEmpty()) { // 转换为正确的类型 List<Map<String, Object>> convertedRecords = (List<Map<String, Object>>) (List<?>) records; // 批量插入到TDengine并统计成功插入的记录数 int successCount = batchInsertIntoTDengine(superTableName, convertedRecords); totalSynced += successCount; batchCount++; // 只有在数据成功同步后才从队列中移除 if (successCount > 0) { // 从队列中移除已成功处理的数据 redisQueueService.removeBatchFromQueue(queueName, successCount); } // 每处理10批打印一次进度信息 if (batchCount % 10 == 0) { System.out.println("已同步 " + batchCount + " 批次数据,当前批次成功记录数: " + successCount + ",总计已同步: " + totalSynced); } } } long endTime = System.currentTimeMillis(); // 只有在有数据成功同步时才打印完成信息 if (totalSynced > 0) { System.out.println("从Redis队列同步数据完成,总计同步: " + totalSynced + " 条记录,总批次数: " + batchCount + ",耗时: " + (endTime - startTime) + "ms"); } else { System.out.println("Redis队列中没有数据需要同步"); } return totalSynced; } /** * 获取记录数 * @param mysqlTableName MySQL表名 * @return 记录数 */ public int getRecordCount(String mysqlTableName) { // 直接从数据库获取,不使用缓存 String countSql = "SELECT COUNT(*) FROM " + mysqlTableName; Integer count = mysqlJdbcTemplate.queryForObject(countSql, Integer.class); return count != null ? count : 0; } /** * 获取总记录数 * @param tableName 表名 * @return 总记录数 */ public int getTotalRecordCount(String tableName) { // 直接从数据库获取,不使用缓存 String countSql = "SELECT COUNT(*) FROM " + tableName; Integer count = mysqlJdbcTemplate.queryForObject(countSql, Integer.class); return count != null ? count : 0; } /** * 批量插入数据到TDengine * @param superTableName TDengine超级表名 * @param records 记录列表 * @return 成功插入的记录数 */ private int batchInsertIntoTDengine(String superTableName, List<Map<String, Object>> records) { if (records.isEmpty()) { return 0; } int successCount = 0; try { // 一次性检查并创建所有需要的子表 ensureAllChildTablesExist(superTableName, records); // 然后批量插入数据 for (Map<String, Object> record : records) { try { insertIntoTDengine(superTableName, record); successCount++; } catch (Exception e) { System.err.println("单条记录插入失败: " + e.getMessage()); } } } catch (Exception e) { System.err.println("批量数据插入失败: " + e.getMessage()); // 不打印完整堆栈,减少日志输出 } return successCount; } /** * 一次性检查并创建所有需要的子表 * @param superTableName 超级表名 * @param records 记录列表 */ private void ensureAllChildTablesExist(String superTableName, List<Map<String, Object>> records) { try { // 首先确保超级表存在 // 不使用缓存检查超级表是否存在 // 直接确保超级表存在 ensureSuperTableExists(superTableName); // 不使用缓存存储超级表存在信息 // 收集所有需要的子表名 java.util.Set<String> childTableNames = new java.util.HashSet<>(); java.util.Map<String, String> childTableToTagMap = new java.util.HashMap<>(); String tagColumn = tagColumnsConfig; for (Map<String, Object> record : records) { Object tagValueObj = record.get(tagColumn); String tagValue = (tagValueObj != null) ? tagValueObj.toString() : "null"; String childTableName = superTableName + "_" + tagValue; // 仅处理缓存中不存在的表 String cacheKey = "tdengine:table:" + childTableName; // 不使用缓存,直接检查表是否存在 if (!childTableNames.contains(childTableName)) { childTableNames.add(childTableName); childTableToTagMap.put(childTableName, tagValue); } } // 一次性查询所有子表是否存在 if (!childTableNames.isEmpty()) { // 使用更高效的方式检查表是否存在 for (String childTableName : childTableNames) { if (!isTableExists(childTableName)) { String tagValue = childTableToTagMap.get(childTableName); createChildTable(superTableName, childTableName, tagValue); } else { // 缓存已存在的表信息 // 不使用缓存存储表存在信息 } } } } catch (Exception e) { System.err.println("批量检查子表存在时失败: " + e.getMessage()); // 不打印完整堆栈,减少日志输出 } } /** * 检查TDengine表是否存在 * @param tableName 表名 * @return 是否存在 */ private boolean isTableExists(String tableName) { try { String checkSql = "SELECT table_name FROM information_schema.ins_tables WHERE table_name = ?"; List<Map<String, Object>> result = tdengineJdbcTemplate.queryForList(checkSql, tableName); return !result.isEmpty(); } catch (Exception e) { System.err.println("检查表是否存在时出错: " + e.getMessage()); return false; } } /** * 创建子表 * @param superTableName 超级表名 * @param childTableName 子表名 * @param tagValue 标签值 */ private void createChildTable(String superTableName, String childTableName, String tagValue) { try { String createChildTableSql = "CREATE TABLE IF NOT EXISTS " + childTableName + " USING " + superTableName + " TAGS ('" + tagValue + "')"; tdengineJdbcTemplate.execute(createChildTableSql); // 缓存表存在信息 // 不使用缓存存储表存在信息 System.out.println("创建子表: " + childTableName); } catch (Exception e) { System.err.println("创建子表失败: " + e.getMessage()); } } /** * 插入数据到TDengine * @param superTableName TDengine超级表名 * @param record 记录 */ public void insertIntoTDengine(String superTableName, Map<String, Object> record) { long startTime = System.currentTimeMillis(); int retryCount = 0; while (retryCount < maxRetries) { try { // 获取标签列名(从配置中获取) String tagColumn = tagColumnsConfig; // 获取标签值 Object tagValueObj = record.get(tagColumn); String tagValue = (tagValueObj != null) ? tagValueObj.toString() : "null"; // 生成子表名(使用标签值) String childTableName = superTableName + "_" + tagValue; // 优化:仅在缓存中不存在时检查子表 String cacheKey = "tdengine:table:" + childTableName; // 不使用缓存检查表是否存在 // 直接检查表是否存在 if (!isTableExists(childTableName)) { // 确保子表存在 ensureChildTableExists(superTableName, childTableName, tagValue); // 缓存表存在信息,避免频繁检查 // 不使用缓存存储表存在信息 } // 构建SQL StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(childTableName).append(" USING ").append(superTableName) .append(" TAGS ('").append(tagValue).append("') (").append(tdengineTimestampField).append(", "); // 添加列名 boolean first = true; for (String columnName : record.keySet()) { // 跳过标签列和时间戳字段 if (tagColumn.equals("id")||tagColumn.equals(columnName) || tdengineTimestampField.equals(columnName)) { continue; } if (!first) { sql.append(", "); } // 处理关键字冲突 sql.append(escapeKeyword(columnName)); first = false; } // 获取时间戳字段的值 Object timestampValue = record.get(timestampField); if (timestampValue == null) { // 如果时间戳为空,跳过这条记录 System.err.println("警告: 记录的时间戳字段为空,跳过该记录"); return; } String formattedTimestamp; if (timestampValue instanceof Timestamp) { // 格式化时间戳 Timestamp ts = (Timestamp) timestampValue; formattedTimestamp = "'" + TimeUtils.formatWithMillis(TimeUtils.from(ts)) + "'"; } else if (timestampValue instanceof LocalDateTime) { // 格式化LocalDateTime LocalDateTime ldt = (LocalDateTime) timestampValue; formattedTimestamp = "'" + TimeUtils.formatWithMillis(ldt) + "'"; } else { // 其他情况使用字符串值 String timestampStr = timestampValue.toString(); // 检查是否需要调整毫秒格式 if (timestampStr.matches(".*\\.\\d{3}$")) { // 如果已经包含毫秒,直接使用 formattedTimestamp = "'" + timestampStr + "'"; } else if (timestampStr.matches(".*\\.\\d{1,2}$")) { // 如果毫秒部分不足3位,补零 String[] parts = timestampStr.split("\\."); if (parts.length == 2) { String millis = parts[1]; while (millis.length() < 3) { millis += "0"; } formattedTimestamp = "'" + parts[0] + "." + millis + "'"; } else { formattedTimestamp = "'" + timestampStr + "'"; } } else if (timestampStr.matches(".*:\\d{2}$")) { // 如果没有毫秒部分,添加.000 formattedTimestamp = "'" + timestampStr + ".000'"; } else { formattedTimestamp = "'" + timestampStr + "'"; } } sql.append(") VALUES (").append(formattedTimestamp).append(", "); // 添加值 first = true; for (Map.Entry<String, Object> entry : record.entrySet()) { String columnName = entry.getKey(); Object value = entry.getValue(); // 跳过标签列和时间戳字段 if (tagColumn.equals(columnName) || tdengineTimestampField.equals(columnName)) { continue; } if (!first) { sql.append(", "); } // 处理NULL值 if (value == null) { sql.append("NULL"); } else if (value instanceof String || value instanceof Timestamp || value instanceof LocalDateTime) { // 对字符串和时间戳类型进行特殊处理 if (value instanceof Timestamp) { // 格式化时间戳 Timestamp ts = (Timestamp) value; sql.append("'").append(TimeUtils.formatWithMillis(TimeUtils.from(ts))).append("'"); } else if (value instanceof LocalDateTime) { // 格式化LocalDateTime LocalDateTime ldt = (LocalDateTime) value; sql.append("'").append(TimeUtils.formatWithMillis(ldt)).append("'"); } else { // 字符串值需要添加引号,并处理NULL字符串 String strValue = value.toString(); if ("NULL".equalsIgnoreCase(strValue)) { sql.append("NULL"); } else { sql.append("'").append(strValue.replace("'", "''")).append("'"); } } } else { // 其他类型直接添加 sql.append(value.toString()); } first = false; } sql.append(")"); // System.out.println("SQL语句: " + sql.toString()); tdengineJdbcTemplate.execute(sql.toString()); // 更新性能监控 performanceMonitorService.incrementCounter("data.migration.insert.success", 1); break; // 成功执行,跳出重试循环 } catch (Exception e) { retryCount++; System.err.println("数据插入失败,正在进行第" + retryCount + "次重试: " + e.getMessage()); if (retryCount >= maxRetries) { System.err.println("数据插入最终失败: " + e.getMessage()); performanceMonitorService.incrementCounter("data.migration.insert.failure", 1); throw new RuntimeException("数据插入失败", e); } else { try { Thread.sleep(retryInterval * retryCount); // 使用配置的重试间隔和指数退避 } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("重试被中断", ie); } } } finally { long endTime = System.currentTimeMillis(); performanceMonitorService.recordTime("data.migration.insert", endTime - startTime); } } } /** * 确保子表存在 * @param superTableName 超级表名 * @param childTableName 子表名 * @param tagValue 标签值 */ private void ensureChildTableExists(String superTableName, String childTableName, String tagValue) { // 使用类级锁来确保在多线程环境下不会重复创建表 synchronized (DataMigrationService.class) { try { // 首先确保超级表存在(使用缓存优化) String superTableCacheKey = "tdengine:stable:" + superTableName; // 不使用缓存检查超级表是否存在 // 直接确保超级表存在 ensureSuperTableExists(superTableName); // 不使用缓存存储超级表存在信息 // 检查子表是否存在 if (!isTableExists(childTableName)) { createChildTable(superTableName, childTableName, tagValue); } } catch (Exception e) { System.err.println("确保子表存在时失败: " + e.getMessage()); // 不打印完整堆栈,减少日志输出 } } } /** * 确保超级表存在 * @param superTableName 超级表名 */ private void ensureSuperTableExists(String superTableName) { try { // 检查超级表是否存在 if (!isTableExists(superTableName)) { // 超级表应该已经由TableAutoCreateService创建,这里只是确保缓存存在 // 不再创建默认的超级表结构 System.out.println("警告: 超级表 " + superTableName + " 不存在,需要先分析MySQL表结构并创建"); } } catch (Exception e) { System.err.println("确保超级表存在时失败: " + e.getMessage()); // 不打印完整堆栈,减少日志输出 } } /** * 处理SQL关键字冲突,为字段名添加反引号 * @param columnName 字段名 * @return 处理后的字段名 */ private String escapeKeyword(String columnName) { // TDengine中的关键字列表(部分) String[] keywords = {"query", "order", "group", "limit", "offset", "select", "from", "where", "insert", "update", "delete"}; for (String keyword : keywords) { if (keyword.equalsIgnoreCase(columnName)) { return "`" + columnName + "`"; } } return columnName; } }给我优化后的完整代码
11-15
<?php /*! * Medoo database framework * https://medoo.in * Version 1.7.10 * * Copyright 2020, Angel Lai * Released under the MIT license */ namespace Medoo; use PDO; use Exception; use PDOException; use InvalidArgumentException; class Raw { public $map; public $value; } class Medoo { public $pdo; protected $type; protected $prefix; protected $statement; protected $dsn; protected $logs = []; protected $logging = false; protected $debug_mode = false; protected $guid = 0; protected $errorInfo = null; public function __construct(array $options) { if (isset($options[ 'database_type' ])) { $this->type = strtolower($options[ 'database_type' ]); if ($this->type === 'mariadb') { $this->type = 'mysql'; } } if (isset($options[ 'prefix' ])) { $this->prefix = $options[ 'prefix' ]; } if (isset($options[ 'logging' ]) && is_bool($options[ 'logging' ])) { $this->logging = $options[ 'logging' ]; } $option = isset($options[ 'option' ]) ? $options[ 'option' ] : []; $commands = (isset($options[ 'command' ]) && is_array($options[ 'command' ])) ? $options[ 'command' ] : []; switch ($this->type) { case 'mysql': // Make MySQL using standard quoted identifier $commands[] = 'SET SQL_MODE=ANSI_QUOTES'; break; case 'mssql': // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting $commands[] = 'SET QUOTED_IDENTIFIER ON'; // Make ANSI_NULLS is ON for NULL value $commands[] = 'SET ANSI_NULLS ON'; break; } if (isset($options[ 'pdo' ])) { if (!$options[ 'pdo' ] instanceof PDO) { throw new InvalidArgumentException('Invalid PDO object supplied'); } $this->pdo = $options[ 'pdo' ]; foreach ($commands as $value) { $this->pdo->exec($value); } return; } if (isset($options[ 'dsn' ])) { if (is_array($options[ 'dsn' ]) && isset($options[ 'dsn' ][ 'driver' ])) { $attr = $options[ 'dsn' ]; } else { throw new InvalidArgumentException('Invalid DSN option supplied'); } } else { if ( isset($options[ 'port' ]) && is_int($options[ 'port' ] * 1) ) { $port = $options[ 'port' ]; } $is_port = isset($port); switch ($this->type) { case 'mysql': $attr = [ 'driver' => 'mysql', 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'socket' ])) { $attr[ 'unix_socket' ] = $options[ 'socket' ]; } else { $attr[ 'host' ] = $options[ 'server' ]; if ($is_port) { $attr[ 'port' ] = $port; } } break; case 'pgsql': $attr = [ 'driver' => 'pgsql', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'sybase': $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'oracle': $attr = [ 'driver' => 'oci', 'dbname' => $options[ 'server' ] ? '//' . $options[ 'server' ] . ($is_port ? ':' . $port : ':1521') . '/' . $options[ 'database_name' ] : $options[ 'database_name' ] ]; if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } break; case 'mssql': if (isset($options[ 'driver' ]) && $options[ 'driver' ] === 'dblib') { $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ] . ($is_port ? ':' . $port : ''), 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'appname' ] = $options[ 'appname' ]; } if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } } else { $attr = [ 'driver' => 'sqlsrv', 'Server' => $options[ 'server' ] . ($is_port ? ',' . $port : ''), 'Database' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'APP' ] = $options[ 'appname' ]; } $config = [ 'ApplicationIntent', 'AttachDBFileName', 'Authentication', 'ColumnEncryption', 'ConnectionPooling', 'Encrypt', 'Failover_Partner', 'KeyStoreAuthentication', 'KeyStorePrincipalId', 'KeyStoreSecret', 'LoginTimeout', 'MultipleActiveResultSets', 'MultiSubnetFailover', 'Scrollable', 'TraceFile', 'TraceOn', 'TransactionIsolation', 'TransparentNetworkIPResolution', 'TrustServerCertificate', 'WSID', ]; foreach ($config as $value) { $keyname = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $value)); if (isset($options[ $keyname ])) { $attr[ $value ] = $options[ $keyname ]; } } } break; case 'sqlite': $attr = [ 'driver' => 'sqlite', $options[ 'database_file' ] ]; break; } } if (!isset($attr)) { throw new InvalidArgumentException('Incorrect connection options'); } $driver = $attr[ 'driver' ]; if (!in_array($driver, PDO::getAvailableDrivers())) { throw new InvalidArgumentException("Unsupported PDO driver: {$driver}"); } unset($attr[ 'driver' ]); $stack = []; foreach ($attr as $key => $value) { $stack[] = is_int($key) ? $value : $key . '=' . $value; } $dsn = $driver . ':' . implode(';', $stack); if ( in_array($this->type, ['mysql', 'pgsql', 'sybase', 'mssql']) && isset($options[ 'charset' ]) ) { $commands[] = "SET NAMES '{$options[ 'charset' ]}'" . ( $this->type === 'mysql' && isset($options[ 'collation' ]) ? " COLLATE '{$options[ 'collation' ]}'" : '' ); } $this->dsn = $dsn; try { $this->pdo = new PDO( $dsn, isset($options[ 'username' ]) ? $options[ 'username' ] : null, isset($options[ 'password' ]) ? $options[ 'password' ] : null, $option ); foreach ($commands as $value) { $this->pdo->exec($value); } } catch (PDOException $e) { throw new PDOException($e->getMessage()); } } public function query($query, $map = []) { $raw = $this->raw($query, $map); $query = $this->buildRaw($raw, $map); return $this->exec($query, $map); } public function exec($query, $map = []) { $this->statement = null; if ($this->debug_mode) { echo $this->generate($query, $map); $this->debug_mode = false; return false; } if ($this->logging) { $this->logs[] = [$query, $map]; } else { $this->logs = [[$query, $map]]; } $statement = $this->pdo->prepare($query); if (!$statement) { $this->errorInfo = $this->pdo->errorInfo(); $this->statement = null; return false; } $this->statement = $statement; foreach ($map as $key => $value) { $statement->bindValue($key, $value[ 0 ], $value[ 1 ]); } $execute = $statement->execute(); $this->errorInfo = $statement->errorInfo(); if (!$execute) { $this->statement = null; } return $statement; } protected function generate($query, $map) { $identifier = [ 'mysql' => '`$1`', 'mssql' => '[$1]' ]; $query = preg_replace( '/"([a-zA-Z0-9_]+)"/i', isset($identifier[ $this->type ]) ? $identifier[ $this->type ] : '"$1"', $query ); foreach ($map as $key => $value) { if ($value[ 1 ] === PDO::PARAM_STR) { $replace = $this->quote($value[ 0 ]); } elseif ($value[ 1 ] === PDO::PARAM_NULL) { $replace = 'NULL'; } elseif ($value[ 1 ] === PDO::PARAM_LOB) { $replace = '{LOB_DATA}'; } else { $replace = $value[ 0 ]; } $query = str_replace($key, $replace, $query); } return $query; } public static function raw($string, $map = []) { $raw = new Raw(); $raw->map = $map; $raw->value = $string; return $raw; } protected function isRaw($object) { return $object instanceof Raw; } protected function buildRaw($raw, &$map) { if (!$this->isRaw($raw)) { return false; } $query = preg_replace_callback( '/(([`\']).*?)?((FROM|TABLE|INTO|UPDATE|JOIN)\s*)?\<(([a-zA-Z0-9_]+)(\.[a-zA-Z0-9_]+)?)\>(.*?\2)?/i', function ($matches) { if (!empty($matches[ 2 ]) && isset($matches[ 8 ])) { return $matches[ 0 ]; } if (!empty($matches[ 4 ])) { return $matches[ 1 ] . $matches[ 4 ] . ' ' . $this->tableQuote($matches[ 5 ]); } return $matches[ 1 ] . $this->columnQuote($matches[ 5 ]); }, $raw->value); $raw_map = $raw->map; if (!empty($raw_map)) { foreach ($raw_map as $key => $value) { $map[ $key ] = $this->typeMap($value, gettype($value)); } } return $query; } public function quote($string) { return $this->pdo->quote($string); } protected function tableQuote($table) { if (!preg_match('/^[a-zA-Z0-9_]+$/i', $table)) { throw new InvalidArgumentException("Incorrect table name \"$table\""); } return '"' . $this->prefix . $table . '"'; } protected function mapKey() { return ':MeDoO_' . $this->guid++ . '_mEdOo'; } protected function typeMap($value, $type) { $map = [ 'NULL' => PDO::PARAM_NULL, 'integer' => PDO::PARAM_INT, 'double' => PDO::PARAM_STR, 'boolean' => PDO::PARAM_BOOL, 'string' => PDO::PARAM_STR, 'object' => PDO::PARAM_STR, 'resource' => PDO::PARAM_LOB ]; if ($type === 'boolean') { $value = ($value ? '1' : '0'); } elseif ($type === 'NULL') { $value = null; } return [$value, $map[ $type ]]; } protected function columnQuote($string) { if (!preg_match('/^[a-zA-Z0-9_]+(\.?[a-zA-Z0-9_]+)?$/i', $string)) { throw new InvalidArgumentException("Incorrect column name \"$string\""); } if (strpos($string, '.') !== false) { return '"' . $this->prefix . str_replace('.', '"."', $string) . '"'; } return '"' . $string . '"'; } protected function columnPush(&$columns, &$map, $root, $is_join = false) { if ($columns === '*') { return $columns; } $stack = []; if (is_string($columns)) { $columns = [$columns]; } foreach ($columns as $key => $value) { if (!is_int($key) && is_array($value) && $root && count(array_keys($columns)) === 1) { $stack[] = $this->columnQuote($key); $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (is_array($value)) { $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (!is_int($key) && $raw = $this->buildRaw($value, $map)) { preg_match('/(?<column>[a-zA-Z0-9_\.]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $match); $stack[] = $raw . ' AS ' . $this->columnQuote($match[ 'column' ]); } elseif (is_int($key) && is_string($value)) { if ($is_join && strpos($value, '*') !== false) { throw new InvalidArgumentException('Cannot use table.* to select all columns while joining table'); } preg_match('/(?<column>[a-zA-Z0-9_\.]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $match); if (!empty($match[ 'alias' ])) { $stack[] = $this->columnQuote($match[ 'column' ]) . ' AS ' . $this->columnQuote($match[ 'alias' ]); $columns[ $key ] = $match[ 'alias' ]; if (!empty($match[ 'type' ])) { $columns[ $key ] .= ' [' . $match[ 'type' ] . ']'; } } else { $stack[] = $this->columnQuote($match[ 'column' ]); } } } return implode(',', $stack); } protected function arrayQuote($array) { $stack = []; foreach ($array as $value) { $stack[] = is_int($value) ? $value : $this->pdo->quote($value); } return implode(',', $stack); } protected function innerConjunct($data, $map, $conjunctor, $outer_conjunctor) { $stack = []; foreach ($data as $value) { $stack[] = '(' . $this->dataImplode($value, $map, $conjunctor) . ')'; } return implode($outer_conjunctor . ' ', $stack); } protected function dataImplode($data, &$map, $conjunctor) { $stack = []; foreach ($data as $key => $value) { $type = gettype($value); if ( $type === 'array' && preg_match("/^(AND|OR)(\s+#.*)?$/", $key, $relation_match) ) { $relationship = $relation_match[ 1 ]; $stack[] = $value !== array_keys(array_keys($value)) ? '(' . $this->dataImplode($value, $map, ' ' . $relationship) . ')' : '(' . $this->innerConjunct($value, $map, ' ' . $relationship, $conjunctor) . ')'; continue; } $map_key = $this->mapKey(); if ( is_int($key) && preg_match('/([a-zA-Z0-9_\.]+)\[(?<operator>\>\=?|\<\=?|\!?\=)\]([a-zA-Z0-9_\.]+)/i', $value, $match) ) { $stack[] = $this->columnQuote($match[ 1 ]) . ' ' . $match[ 'operator' ] . ' ' . $this->columnQuote($match[ 3 ]); } else { preg_match('/([a-zA-Z0-9_\.]+)(\[(?<operator>\>\=?|\<\=?|\!|\<\>|\>\<|\!?~|REGEXP)\])?/i', $key, $match); $column = $this->columnQuote($match[ 1 ]); if (isset($match[ 'operator' ])) { $operator = $match[ 'operator' ]; if (in_array($operator, ['>', '>=', '<', '<='])) { $condition = $column . ' ' . $operator . ' '; if (is_numeric($value)) { $condition .= $map_key; $map[ $map_key ] = [$value, is_float($value) ? PDO::PARAM_STR : PDO::PARAM_INT]; } elseif ($raw = $this->buildRaw($value, $map)) { $condition .= $raw; } else { $condition .= $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } $stack[] = $condition; } elseif ($operator === '!') { switch ($type) { case 'NULL': $stack[] = $column . ' IS NOT NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' NOT IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' != ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' != ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } elseif ($operator === '~' || $operator === '!~') { if ($type !== 'array') { $value = [ $value ]; } $connector = ' OR '; $data = array_values($value); if (is_array($data[ 0 ])) { if (isset($value[ 'AND' ]) || isset($value[ 'OR' ])) { $connector = ' ' . array_keys($value)[ 0 ] . ' '; $value = $data[ 0 ]; } } $like_clauses = []; foreach ($value as $index => $item) { $item = strval($item); if (!preg_match('/(\[.+\]|[\*\?\!\%#^-_]|%.+|.+%)/', $item)) { $item = '%' . $item . '%'; } $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $map_key . 'L' . $index; $map[ $map_key . 'L' . $index ] = [$item, PDO::PARAM_STR]; } $stack[] = '(' . implode($connector, $like_clauses) . ')'; } elseif ($operator === '<>' || $operator === '><') { if ($type === 'array') { if ($operator === '><') { $column .= ' NOT'; } $stack[] = '(' . $column . ' BETWEEN ' . $map_key . 'a AND ' . $map_key . 'b)'; $data_type = (is_numeric($value[ 0 ]) && is_numeric($value[ 1 ])) ? PDO::PARAM_INT : PDO::PARAM_STR; $map[ $map_key . 'a' ] = [$value[ 0 ], $data_type]; $map[ $map_key . 'b' ] = [$value[ 1 ], $data_type]; } } elseif ($operator === 'REGEXP') { $stack[] = $column . ' REGEXP ' . $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } } else { switch ($type) { case 'NULL': $stack[] = $column . ' IS NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' = ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' = ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } } } return implode($conjunctor . ' ', $stack); } protected function whereClause($where, &$map) { $where_clause = ''; if (is_array($where)) { $where_keys = array_keys($where); $conditions = array_diff_key($where, array_flip( ['GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LIKE', 'MATCH'] )); if (!empty($conditions)) { $where_clause = ' WHERE ' . $this->dataImplode($conditions, $map, ' AND'); } if (isset($where[ 'MATCH' ]) && $this->type === 'mysql') { $MATCH = $where[ 'MATCH' ]; if (is_array($MATCH) && isset($MATCH[ 'columns' ], $MATCH[ 'keyword' ])) { $mode = ''; $mode_array = [ 'natural' => 'IN NATURAL LANGUAGE MODE', 'natural+query' => 'IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION', 'boolean' => 'IN BOOLEAN MODE', 'query' => 'WITH QUERY EXPANSION' ]; if (isset($MATCH[ 'mode' ], $mode_array[ $MATCH[ 'mode' ] ])) { $mode = ' ' . $mode_array[ $MATCH[ 'mode' ] ]; } $columns = implode(', ', array_map([$this, 'columnQuote'], $MATCH[ 'columns' ])); $map_key = $this->mapKey(); $map[ $map_key ] = [$MATCH[ 'keyword' ], PDO::PARAM_STR]; $where_clause .= ($where_clause !== '' ? ' AND ' : ' WHERE') . ' MATCH (' . $columns . ') AGAINST (' . $map_key . $mode . ')'; } } if (isset($where[ 'GROUP' ])) { $GROUP = $where[ 'GROUP' ]; if (is_array($GROUP)) { $stack = []; foreach ($GROUP as $column => $value) { $stack[] = $this->columnQuote($value); } $where_clause .= ' GROUP BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($GROUP, $map)) { $where_clause .= ' GROUP BY ' . $raw; } else { $where_clause .= ' GROUP BY ' . $this->columnQuote($GROUP); } if (isset($where[ 'HAVING' ])) { if ($raw = $this->buildRaw($where[ 'HAVING' ], $map)) { $where_clause .= ' HAVING ' . $raw; } else { $where_clause .= ' HAVING ' . $this->dataImplode($where[ 'HAVING' ], $map, ' AND'); } } } if (isset($where[ 'ORDER' ])) { $ORDER = $where[ 'ORDER' ]; if (is_array($ORDER)) { $stack = []; foreach ($ORDER as $column => $value) { if (is_array($value)) { $stack[] = 'FIELD(' . $this->columnQuote($column) . ', ' . $this->arrayQuote($value) . ')'; } elseif ($value === 'ASC' || $value === 'DESC') { $stack[] = $this->columnQuote($column) . ' ' . $value; } elseif (is_int($column)) { $stack[] = $this->columnQuote($value); } } $where_clause .= ' ORDER BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($ORDER, $map)) { $where_clause .= ' ORDER BY ' . $raw; } else { $where_clause .= ' ORDER BY ' . $this->columnQuote($ORDER); } if ( isset($where[ 'LIMIT' ]) && in_array($this->type, ['oracle', 'mssql']) ) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $LIMIT = [0, $LIMIT]; } if ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' OFFSET ' . $LIMIT[ 0 ] . ' ROWS FETCH NEXT ' . $LIMIT[ 1 ] . ' ROWS ONLY'; } } } if (isset($where[ 'LIMIT' ]) && !in_array($this->type, ['oracle', 'mssql'])) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $where_clause .= ' LIMIT ' . $LIMIT; } elseif ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' LIMIT ' . $LIMIT[ 1 ] . ' OFFSET ' . $LIMIT[ 0 ]; } } } elseif ($raw = $this->buildRaw($where, $map)) { $where_clause .= ' ' . $raw; } return $where_clause; } protected function selectContext($table, &$map, $join, &$columns = null, $where = null, $column_fn = null) { preg_match('/(?<table>[a-zA-Z0-9_]+)\s*\((?<alias>[a-zA-Z0-9_]+)\)/i', $table, $table_match); if (isset($table_match[ 'table' ], $table_match[ 'alias' ])) { $table = $this->tableQuote($table_match[ 'table' ]); $table_query = $table . ' AS ' . $this->tableQuote($table_match[ 'alias' ]); } else { $table = $this->tableQuote($table); $table_query = $table; } $is_join = false; $join_key = is_array($join) ? array_keys($join) : null; if ( isset($join_key[ 0 ]) && strpos($join_key[ 0 ], '[') === 0 ) { $is_join = true; $table_query .= ' ' . $this->buildJoin($table, $join); } else { if (is_null($columns)) { if ( !is_null($where) || (is_array($join) && isset($column_fn)) ) { $where = $join; $columns = null; } else { $where = null; $columns = $join; } } else { $where = $columns; $columns = $join; } } if (isset($column_fn)) { if ($column_fn === 1) { $column = '1'; if (is_null($where)) { $where = $columns; } } elseif ($raw = $this->buildRaw($column_fn, $map)) { $column = $raw; } else { if (empty($columns) || $this->isRaw($columns)) { $columns = '*'; $where = $join; } $column = $column_fn . '(' . $this->columnPush($columns, $map, true) . ')'; } } else { $column = $this->columnPush($columns, $map, true, $is_join); } return 'SELECT ' . $column . ' FROM ' . $table_query . $this->whereClause($where, $map); } protected function buildJoin($table, $join) { $table_join = []; $join_array = [ '>' => 'LEFT', '<' => 'RIGHT', '<>' => 'FULL', '><' => 'INNER' ]; foreach($join as $sub_table => $relation) { preg_match('/(\[(?<join>\<\>?|\>\<?)\])?(?<table>[a-zA-Z0-9_]+)\s?(\((?<alias>[a-zA-Z0-9_]+)\))?/', $sub_table, $match); if ($match[ 'join' ] !== '' && $match[ 'table' ] !== '') { if (is_string($relation)) { $relation = 'USING ("' . $relation . '")'; } if (is_array($relation)) { // For ['column1', 'column2'] if (isset($relation[ 0 ])) { $relation = 'USING ("' . implode('", "', $relation) . '")'; } else { $joins = []; foreach ($relation as $key => $value) { $joins[] = ( strpos($key, '.') > 0 ? // For ['tableB.column' => 'column'] $this->columnQuote($key) : // For ['column1' => 'column2'] $table . '."' . $key . '"' ) . ' = ' . $this->tableQuote(isset($match[ 'alias' ]) ? $match[ 'alias' ] : $match[ 'table' ]) . '."' . $value . '"'; } $relation = 'ON ' . implode(' AND ', $joins); } } $table_name = $this->tableQuote($match[ 'table' ]) . ' '; if (isset($match[ 'alias' ])) { $table_name .= 'AS ' . $this->tableQuote($match[ 'alias' ]) . ' '; } $table_join[] = $join_array[ $match[ 'join' ] ] . ' JOIN ' . $table_name . $relation; } } return implode(' ', $table_join); } protected function columnMap($columns, &$stack, $root) { if ($columns === '*') { return $stack; } foreach ($columns as $key => $value) { if (is_int($key)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $key_match); $column_key = !empty($key_match[ 'alias' ]) ? $key_match[ 'alias' ] : $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $value ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $value ] = [$column_key, 'String']; } } elseif ($this->isRaw($value)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $key_match); $column_key = $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $key ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $key ] = [$column_key, 'String']; } } elseif (!is_int($key) && is_array($value)) { if ($root && count(array_keys($columns)) === 1) { $stack[ $key ] = [$key, 'String']; } $this->columnMap($value, $stack, false); } } return $stack; } protected function dataMap($data, $columns, $column_map, &$stack, $root, &$result) { if ($root) { $columns_key = array_keys($columns); if (count($columns_key) === 1 && is_array($columns[$columns_key[0]])) { $index_key = array_keys($columns)[0]; $data_key = preg_replace("/^[a-zA-Z0-9_]+\./i", "", $index_key); $current_stack = []; foreach ($data as $item) { $this->dataMap($data, $columns[ $index_key ], $column_map, $current_stack, false, $result); $index = $data[ $data_key ]; $result[ $index ] = $current_stack; } } else { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, false, $result); $result[] = $current_stack; } return; } foreach ($columns as $key => $value) { $isRaw = $this->isRaw($value); if (is_int($key) || $isRaw) { $map = $column_map[ $isRaw ? $key : $value ]; $column_key = $map[ 0 ]; $item = $data[ $column_key ]; if (isset($map[ 1 ])) { if ($isRaw && in_array($map[ 1 ], ['Object', 'JSON'])) { continue; } if (is_null($item)) { $stack[ $column_key ] = null; continue; } switch ($map[ 1 ]) { case 'Number': $stack[ $column_key ] = (double) $item; break; case 'Int': $stack[ $column_key ] = (int) $item; break; case 'Bool': $stack[ $column_key ] = (bool) $item; break; case 'Object': $stack[ $column_key ] = unserialize($item); break; case 'JSON': $stack[ $column_key ] = json_decode($item, true); break; case 'String': $stack[ $column_key ] = $item; break; } } else { $stack[ $column_key ] = $item; } } else { $current_stack = []; $this->dataMap($data, $value, $column_map, $current_stack, false, $result); $stack[ $key ] = $current_stack; } } } public function create($table, $columns, $options = null) { $stack = []; $tableName = $this->prefix . $table; foreach ($columns as $name => $definition) { if (is_int($name)) { $stack[] = preg_replace('/\<([a-zA-Z0-9_]+)\>/i', '"$1"', $definition); } elseif (is_array($definition)) { $stack[] = $name . ' ' . implode(' ', $definition); } elseif (is_string($definition)) { $stack[] = $name . ' ' . $this->query($definition); } } $table_option = ''; if (is_array($options)) { $option_stack = []; foreach ($options as $key => $value) { if (is_string($value) || is_int($value)) { $option_stack[] = "$key = $value"; } } $table_option = ' ' . implode(', ', $option_stack); } elseif (is_string($options)) { $table_option = ' ' . $options; } return $this->exec("CREATE TABLE IF NOT EXISTS $tableName (" . implode(', ', $stack) . ")$table_option"); } public function drop($table) { $tableName = $this->prefix . $table; return $this->exec("DROP TABLE IF EXISTS $tableName"); } public function select($table, $join, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $index = 0; $column = $where === null ? $join : $columns; $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where), $map); $this->columnMap($columns, $column_map, true); if (!$this->statement) { return false; } if ($columns === '*') { return $query->fetchAll(PDO::FETCH_ASSOC); } while ($data = $query->fetch(PDO::FETCH_ASSOC)) { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, true, $result); } if ($is_single) { $single_result = []; $result_key = $column_map[ $column ][ 0 ]; foreach ($result as $item) { $single_result[] = $item[ $result_key ]; } return $single_result; } return $result; } public function insert($table, $datas) { $stack = []; $columns = []; $fields = []; $map = []; if (!isset($datas[ 0 ])) { $datas = [$datas]; } foreach ($datas as $data) { foreach ($data as $key => $value) { $columns[] = $key; } } $columns = array_unique($columns); foreach ($datas as $data) { $values = []; foreach ($columns as $key) { if ($raw = $this->buildRaw($data[ $key ], $map)) { $values[] = $raw; continue; } $map_key = $this->mapKey(); $values[] = $map_key; if (!isset($data[ $key ])) { $map[ $map_key ] = [null, PDO::PARAM_NULL]; } else { $value = $data[ $key ]; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } $stack[] = '(' . implode(', ', $values) . ')'; } foreach ($columns as $key) { $fields[] = $this->columnQuote(preg_replace("/(\s*\[JSON\]$)/i", '', $key)); } return $this->exec('INSERT INTO ' . $this->tableQuote($table) . ' (' . implode(', ', $fields) . ') VALUES ' . implode(', ', $stack), $map); } public function update($table, $data, $where = null) { $fields = []; $map = []; foreach ($data as $key => $value) { $column = $this->columnQuote(preg_replace("/(\s*\[(JSON|\+|\-|\*|\/)\]$)/i", '', $key)); if ($raw = $this->buildRaw($value, $map)) { $fields[] = $column . ' = ' . $raw; continue; } $map_key = $this->mapKey(); preg_match('/(?<column>[a-zA-Z0-9_]+)(\[(?<operator>\+|\-|\*|\/)\])?/i', $key, $match); if (isset($match[ 'operator' ])) { if (is_numeric($value)) { $fields[] = $column . ' = ' . $column . ' ' . $match[ 'operator' ] . ' ' . $value; } } else { $fields[] = $column . ' = ' . $map_key; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $fields) . $this->whereClause($where, $map), $map); } public function delete($table, $where) { $map = []; return $this->exec('DELETE FROM ' . $this->tableQuote($table) . $this->whereClause($where, $map), $map); } public function replace($table, $columns, $where = null) { if (!is_array($columns) || empty($columns)) { return false; } $map = []; $stack = []; foreach ($columns as $column => $replacements) { if (is_array($replacements)) { foreach ($replacements as $old => $new) { $map_key = $this->mapKey(); $stack[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)'; $map[ $map_key . 'a' ] = [$old, PDO::PARAM_STR]; $map[ $map_key . 'b' ] = [$new, PDO::PARAM_STR]; } } } if (!empty($stack)) { return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $stack) . $this->whereClause($where, $map), $map); } return false; } public function get($table, $join = null, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $current_stack = []; if ($where === null) { $column = $join; unset($columns[ 'LIMIT' ]); } else { $column = $columns; unset($where[ 'LIMIT' ]); } $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where) . ' LIMIT 1', $map); if (!$this->statement) { return false; } $data = $query->fetchAll(PDO::FETCH_ASSOC); if (isset($data[ 0 ])) { if ($column === '*') { return $data[ 0 ]; } $this->columnMap($columns, $column_map, true); $this->dataMap($data[ 0 ], $columns, $column_map, $current_stack, true, $result); if ($is_single) { return $result[ 0 ][ $column_map[ $column ][ 0 ] ]; } return $result[ 0 ]; } } public function has($table, $join, $where = null) { $map = []; $column = null; if ($this->type === 'mssql') { $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, Medoo::raw('TOP 1 1')), $map); } else { $query = $this->exec('SELECT EXISTS(' . $this->selectContext($table, $map, $join, $column, $where, 1) . ')', $map); } if (!$this->statement) { return false; } $result = $query->fetchColumn(); return $result === '1' || $result === 1 || $result === true; } public function rand($table, $join = null, $columns = null, $where = null) { $type = $this->type; $order = 'RANDOM()'; if ($type === 'mysql') { $order = 'RAND()'; } elseif ($type === 'mssql') { $order = 'NEWID()'; } $order_raw = $this->raw($order); if ($where === null) { if ($columns === null) { $columns = [ 'ORDER' => $order_raw ]; } else { $column = $join; unset($columns[ 'ORDER' ]); $columns[ 'ORDER' ] = $order_raw; } } else { unset($where[ 'ORDER' ]); $where[ 'ORDER' ] = $order_raw; } return $this->select($table, $join, $columns, $where); } private function aggregate($type, $table, $join = null, $column = null, $where = null) { $map = []; $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, strtoupper($type)), $map); if (!$this->statement) { return false; } $number = $query->fetchColumn(); return is_numeric($number) ? $number + 0 : $number; } public function count($table, $join = null, $column = null, $where = null) { return $this->aggregate('count', $table, $join, $column, $where); } public function avg($table, $join, $column = null, $where = null) { return $this->aggregate('avg', $table, $join, $column, $where); } public function max($table, $join, $column = null, $where = null) { return $this->aggregate('max', $table, $join, $column, $where); } public function min($table, $join, $column = null, $where = null) { return $this->aggregate('min', $table, $join, $column, $where); } public function sum($table, $join, $column = null, $where = null) { return $this->aggregate('sum', $table, $join, $column, $where); } public function action($actions) { if (is_callable($actions)) { $this->pdo->beginTransaction(); try { $result = $actions($this); if ($result === false) { $this->pdo->rollBack(); } else { $this->pdo->commit(); } } catch (Exception $e) { $this->pdo->rollBack(); throw $e; } return $result; } return false; } public function id() { if ($this->statement == null) { return null; } $type = $this->type; if ($type === 'oracle') { return 0; } elseif ($type === 'pgsql') { return $this->pdo->query('SELECT LASTVAL()')->fetchColumn(); } $lastId = $this->pdo->lastInsertId(); if ($lastId != "0" && $lastId != "") { return $lastId; } return null; } public function debug() { $this->debug_mode = true; return $this; } public function error() { return $this->errorInfo; } public function last() { $log = end($this->logs); return $this->generate($log[ 0 ], $log[ 1 ]); } public function log() { return array_map(function ($log) { return $this->generate($log[ 0 ], $log[ 1 ]); }, $this->logs ); } public function info() { $output = [ 'server' => 'SERVER_INFO', 'driver' => 'DRIVER_NAME', 'client' => 'CLIENT_VERSION', 'version' => 'SERVER_VERSION', 'connection' => 'CONNECTION_STATUS' ]; foreach ($output as $key => $value) { $output[ $key ] = @$this->pdo->getAttribute(constant('PDO::ATTR_' . $value)); } $output[ 'dsn' ] = $this->dsn; return $output; } } require_once 'Medoo.php'; use Medoo\Medoo; $database = new Medoo([ // required 'database_type' => 'mysql', 'database_name' => 'db_hk4e_gm', 'server' => '127.0.0.1', 'username' => 'db_hk4e_gm', 'password' => 'syxywl.cn', // [optional] 'charset' => 'utf8', 'port' => 3306, ]); 这是medoo.php
11-29
这是api/api.php文件代码 <?php // api/api.php // === 配置区 === define('MUIP_API', 'http://127.0.0.1:62221/api'); define('REGION', 'dev_gio'); define('TIME_TOLERANT', 5); define('PRIVATE_KEY_SIZE', 4096); define('PRIVATE_KEY', '$$$PRIVATE_KEY$$$'); // 签名函数(根据实际算法调整) function calcSign($params, $secretKey) { ksort($params); $str = ''; foreach ($params as $k => $v) { $str .= $k . '=' . $v . '&'; } $str = rtrim($str, '&'); return md5($str . $secretKey); } // 返回 JSON 并结束 function returnJSON($data, $code = 200) { http_response_code($code); header('Content-Type: application/json'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; } // === 认证校验 === if ($_GET["adminpass"] !== "syxywlQQ28009618hello") { returnJSON(['success' => false, 'message' => 'gm码错误'], 403); } if ($_GET["sha"] !== md5("getflag")) { returnJSON(['success' => false, 'message' => 'gm码错误'], 403); } $uid = intval($_GET["uid"]); $item = $_GET["item"] ?? ''; $number = max(1, intval($_GET["number"] ?? 1)); if ($uid <= 0) { returnJSON(['success' => false, 'message' => '无效UID'], 400); } // === 命令类型映射表 === $commandMap = [ 'item' => "item add $item $number", 'mcoin' => "mcoin $number", 'level' => "player level $item", 'exp' => "player exp $item", 'money' => "player money $item", 'vip' => "player vip $item", 'teleport' => "player teleport " . (floatval($item) ?: '0') . " 0", 'custom_cmd' => $item, ]; // 获取命令类型 $cmdType = $_GET['cmd_type'] ?? 'item'; // 特殊兼容:item=203 → mcoin if ($item == 203) { $cmdType = 'mcoin'; } if (!isset($commandMap[$cmdType])) { returnJSON(['success' => false, 'message' => "不支持的命令类型: $cmdType"], 400); } $command = $commandMap[$cmdType]; // === 构造并发送 GM 请求 === $query = [ 'cmd' => 1116, 'uid' => $uid, 'msg' => $command, 'region' => REGION ]; $query['sign'] = calcSign($query, "27bwq^d4zzXpdUxf"); $ch = curl_init(MUIP_API . '?' . http_build_query($query)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $rsp = curl_exec($ch); if (curl_error($ch)) { returnJSON(['success' => false, 'message' => '请求失败: ' . curl_error($ch)], 500); } curl_close($ch); $rspData = @json_decode($rsp, true); returnJSON([ 'success' => isset($rspData['retcode']) && $rspData['retcode'] === 0, 'message' => $rspData['msg'] ?? '操作完成', 'data' => $rspData['data'] ?? null, 'debug' => [ // 调试用,上线前可删除 'command_sent' => $command, 'cmd_type' => $cmdType, 'uid' => $uid ] ]); ?> 这是index.php文件代码 <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <title>CDK兑换中心</title> <style> body { font-family: Arial, sans-serif; background: #f4f4f4; padding: 20px; } .container { max-width: 600px; margin: auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } input[type="text"] { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; font-size: 16px; } button { background: #007BFF; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; } button:hover { background: #0056b3; } .message { padding: 10px; margin: 10px 0; border-radius: 5px; } .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; } .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; } </style> </head> <body> <div class="container"> <h2 style="text-align:center;">🎮 CDK兑换系统</h2> <form method="post"> UID: <input type="text" name="uid" placeholder="输入你的游戏UID" required /><br/> CDK: <input type="text" name="cdk" placeholder="输入兑换码" required /><br/> <button type="submit">立即兑换</button> </form> <?php // 引入 Medoo(请确保路径正确) require_once './medoo.php'; // 根据实际路径调整,如:vendor/medoo/medoo.min.php use Medoo\Medoo; // 初始化数据库连接 $database = new Medoo([ 'database_type' => 'mysql', 'database_name' => 'db_hk4e_gm', 'server' => '127.0.0.1', 'username' => 'db_hk4e_gm', 'password' => 'syxywl.cn', 'charset' => 'utf8', 'port' => 3306, ]); if ($_POST) { $Uid = trim($_POST['uid']); $cdk_input = trim($_POST['cdk']); if (!is_numeric($Uid) || intval($Uid) <= 0) { echo "<div class='message error'>❌ 请输入有效的数字UID!</div>"; return; } $Uid = intval($Uid); try { // === 查询 CDK 是否存在且启用 === $cdkData = $database->get("cdk", [ "id", "item", "number", "command_type" ], [ "AND" => [ "cdk" => $cdk_input, "start" => 1 ] ]); if (!$cdkData) { echo "<div class='message error'>❌ CDK不存在或已停用!<br>卡密: $cdk_input</div>"; return; } // === 检查是否已兑换过该 CDK === $used = $database->get("used_cdk", ["id"], [ "AND" => [ "uid" => $Uid, "cdk" => $cdk_input ] ]); if ($used) { echo "<div class='message error'>❌ 此CDK已被您兑换过!<br>卡密: $cdk_input</div>"; return; } // === 准备调用 API 发放奖励 === $cmd_type = $cdkData["command_type"] ?? "item"; $item_value = $cdkData["item"]; $number_value = intval($cdkData["number"]); // 特殊兼容:item=203 → mcoin if ($item_value == 203) { $cmd_type = "mcoin"; } $api_url = "http://202.189.14.206:344/api/api.php?" . http_build_query([ 'sha' => md5("getflag"), 'adminpass' => 'syxywlQQ28009618hello', 'uid' => $Uid, 'item' => urlencode($item_value), 'number' => $number_value, 'cmd_type' => urlencode($cmd_type) ]); $result = @file_get_contents($api_url); $run = json_decode($result, true); if ($run && !empty($run['success']) && $run['success'] === true) { // 记录已使用 $database->insert("used_cdk", [ "uid" => $Uid, "cdk" => $cdk_input, "used_time" => date("Y-m-d H:i:s") ]); echo "<div class='message success'>✅ 兑换成功!<br>奖励已发放:<strong>$cdk_input</strong></div>"; } else { $msg = $run['message'] ?? '接口无响应或失败'; echo "<div class='message error'>❌ 发放失败!<br>错误信息: $msg</div>"; } } catch (Exception $e) { echo "<div class='message error'>❌ 系统异常:<br>" . $e->getMessage() . "</div>"; } } ?> </div> </body> </html> 这是medoo.php文件代码 <?php /*! * Medoo database framework * https://medoo.in * Version 1.7.10 * * Copyright 2020, Angel Lai * Released under the MIT license */ namespace Medoo; use PDO; use Exception; use PDOException; use InvalidArgumentException; class Raw { public $map; public $value; } class Medoo { public $pdo; protected $type; protected $prefix; protected $statement; protected $dsn; protected $logs = []; protected $logging = false; protected $debug_mode = false; protected $guid = 0; protected $errorInfo = null; public function __construct(array $options) { if (isset($options[ 'database_type' ])) { $this->type = strtolower($options[ 'database_type' ]); if ($this->type === 'mariadb') { $this->type = 'mysql'; } } if (isset($options[ 'prefix' ])) { $this->prefix = $options[ 'prefix' ]; } if (isset($options[ 'logging' ]) && is_bool($options[ 'logging' ])) { $this->logging = $options[ 'logging' ]; } $option = isset($options[ 'option' ]) ? $options[ 'option' ] : []; $commands = (isset($options[ 'command' ]) && is_array($options[ 'command' ])) ? $options[ 'command' ] : []; switch ($this->type) { case 'mysql': // Make MySQL using standard quoted identifier $commands[] = 'SET SQL_MODE=ANSI_QUOTES'; break; case 'mssql': // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting $commands[] = 'SET QUOTED_IDENTIFIER ON'; // Make ANSI_NULLS is ON for NULL value $commands[] = 'SET ANSI_NULLS ON'; break; } if (isset($options[ 'pdo' ])) { if (!$options[ 'pdo' ] instanceof PDO) { throw new InvalidArgumentException('Invalid PDO object supplied'); } $this->pdo = $options[ 'pdo' ]; foreach ($commands as $value) { $this->pdo->exec($value); } return; } if (isset($options[ 'dsn' ])) { if (is_array($options[ 'dsn' ]) && isset($options[ 'dsn' ][ 'driver' ])) { $attr = $options[ 'dsn' ]; } else { throw new InvalidArgumentException('Invalid DSN option supplied'); } } else { if ( isset($options[ 'port' ]) && is_int($options[ 'port' ] * 1) ) { $port = $options[ 'port' ]; } $is_port = isset($port); switch ($this->type) { case 'mysql': $attr = [ 'driver' => 'mysql', 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'socket' ])) { $attr[ 'unix_socket' ] = $options[ 'socket' ]; } else { $attr[ 'host' ] = $options[ 'server' ]; if ($is_port) { $attr[ 'port' ] = $port; } } break; case 'pgsql': $attr = [ 'driver' => 'pgsql', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'sybase': $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ], 'dbname' => $options[ 'database_name' ] ]; if ($is_port) { $attr[ 'port' ] = $port; } break; case 'oracle': $attr = [ 'driver' => 'oci', 'dbname' => $options[ 'server' ] ? '//' . $options[ 'server' ] . ($is_port ? ':' . $port : ':1521') . '/' . $options[ 'database_name' ] : $options[ 'database_name' ] ]; if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } break; case 'mssql': if (isset($options[ 'driver' ]) && $options[ 'driver' ] === 'dblib') { $attr = [ 'driver' => 'dblib', 'host' => $options[ 'server' ] . ($is_port ? ':' . $port : ''), 'dbname' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'appname' ] = $options[ 'appname' ]; } if (isset($options[ 'charset' ])) { $attr[ 'charset' ] = $options[ 'charset' ]; } } else { $attr = [ 'driver' => 'sqlsrv', 'Server' => $options[ 'server' ] . ($is_port ? ',' . $port : ''), 'Database' => $options[ 'database_name' ] ]; if (isset($options[ 'appname' ])) { $attr[ 'APP' ] = $options[ 'appname' ]; } $config = [ 'ApplicationIntent', 'AttachDBFileName', 'Authentication', 'ColumnEncryption', 'ConnectionPooling', 'Encrypt', 'Failover_Partner', 'KeyStoreAuthentication', 'KeyStorePrincipalId', 'KeyStoreSecret', 'LoginTimeout', 'MultipleActiveResultSets', 'MultiSubnetFailover', 'Scrollable', 'TraceFile', 'TraceOn', 'TransactionIsolation', 'TransparentNetworkIPResolution', 'TrustServerCertificate', 'WSID', ]; foreach ($config as $value) { $keyname = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $value)); if (isset($options[ $keyname ])) { $attr[ $value ] = $options[ $keyname ]; } } } break; case 'sqlite': $attr = [ 'driver' => 'sqlite', $options[ 'database_file' ] ]; break; } } if (!isset($attr)) { throw new InvalidArgumentException('Incorrect connection options'); } $driver = $attr[ 'driver' ]; if (!in_array($driver, PDO::getAvailableDrivers())) { throw new InvalidArgumentException("Unsupported PDO driver: {$driver}"); } unset($attr[ 'driver' ]); $stack = []; foreach ($attr as $key => $value) { $stack[] = is_int($key) ? $value : $key . '=' . $value; } $dsn = $driver . ':' . implode(';', $stack); if ( in_array($this->type, ['mysql', 'pgsql', 'sybase', 'mssql']) && isset($options[ 'charset' ]) ) { $commands[] = "SET NAMES '{$options[ 'charset' ]}'" . ( $this->type === 'mysql' && isset($options[ 'collation' ]) ? " COLLATE '{$options[ 'collation' ]}'" : '' ); } $this->dsn = $dsn; try { $this->pdo = new PDO( $dsn, isset($options[ 'username' ]) ? $options[ 'username' ] : null, isset($options[ 'password' ]) ? $options[ 'password' ] : null, $option ); foreach ($commands as $value) { $this->pdo->exec($value); } } catch (PDOException $e) { throw new PDOException($e->getMessage()); } } public function query($query, $map = []) { $raw = $this->raw($query, $map); $query = $this->buildRaw($raw, $map); return $this->exec($query, $map); } public function exec($query, $map = []) { $this->statement = null; if ($this->debug_mode) { echo $this->generate($query, $map); $this->debug_mode = false; return false; } if ($this->logging) { $this->logs[] = [$query, $map]; } else { $this->logs = [[$query, $map]]; } $statement = $this->pdo->prepare($query); if (!$statement) { $this->errorInfo = $this->pdo->errorInfo(); $this->statement = null; return false; } $this->statement = $statement; foreach ($map as $key => $value) { $statement->bindValue($key, $value[ 0 ], $value[ 1 ]); } $execute = $statement->execute(); $this->errorInfo = $statement->errorInfo(); if (!$execute) { $this->statement = null; } return $statement; } protected function generate($query, $map) { $identifier = [ 'mysql' => '`$1`', 'mssql' => '[$1]' ]; $query = preg_replace( '/"([a-zA-Z0-9_]+)"/i', isset($identifier[ $this->type ]) ? $identifier[ $this->type ] : '"$1"', $query ); foreach ($map as $key => $value) { if ($value[ 1 ] === PDO::PARAM_STR) { $replace = $this->quote($value[ 0 ]); } elseif ($value[ 1 ] === PDO::PARAM_NULL) { $replace = 'NULL'; } elseif ($value[ 1 ] === PDO::PARAM_LOB) { $replace = '{LOB_DATA}'; } else { $replace = $value[ 0 ]; } $query = str_replace($key, $replace, $query); } return $query; } public static function raw($string, $map = []) { $raw = new Raw(); $raw->map = $map; $raw->value = $string; return $raw; } protected function isRaw($object) { return $object instanceof Raw; } protected function buildRaw($raw, &$map) { if (!$this->isRaw($raw)) { return false; } $query = preg_replace_callback( '/(([`\']).*?)?((FROM|TABLE|INTO|UPDATE|JOIN)\s*)?\<(([a-zA-Z0-9_]+)(\.[a-zA-Z0-9_]+)?)\>(.*?\2)?/i', function ($matches) { if (!empty($matches[ 2 ]) && isset($matches[ 8 ])) { return $matches[ 0 ]; } if (!empty($matches[ 4 ])) { return $matches[ 1 ] . $matches[ 4 ] . ' ' . $this->tableQuote($matches[ 5 ]); } return $matches[ 1 ] . $this->columnQuote($matches[ 5 ]); }, $raw->value); $raw_map = $raw->map; if (!empty($raw_map)) { foreach ($raw_map as $key => $value) { $map[ $key ] = $this->typeMap($value, gettype($value)); } } return $query; } public function quote($string) { return $this->pdo->quote($string); } protected function tableQuote($table) { if (!preg_match('/^[a-zA-Z0-9_]+$/i', $table)) { throw new InvalidArgumentException("Incorrect table name \"$table\""); } return '"' . $this->prefix . $table . '"'; } protected function mapKey() { return ':MeDoO_' . $this->guid++ . '_mEdOo'; } protected function typeMap($value, $type) { $map = [ 'NULL' => PDO::PARAM_NULL, 'integer' => PDO::PARAM_INT, 'double' => PDO::PARAM_STR, 'boolean' => PDO::PARAM_BOOL, 'string' => PDO::PARAM_STR, 'object' => PDO::PARAM_STR, 'resource' => PDO::PARAM_LOB ]; if ($type === 'boolean') { $value = ($value ? '1' : '0'); } elseif ($type === 'NULL') { $value = null; } return [$value, $map[ $type ]]; } protected function columnQuote($string) { if (!preg_match('/^[a-zA-Z0-9_]+(\.?[a-zA-Z0-9_]+)?$/i', $string)) { throw new InvalidArgumentException("Incorrect column name \"$string\""); } if (strpos($string, '.') !== false) { return '"' . $this->prefix . str_replace('.', '"."', $string) . '"'; } return '"' . $string . '"'; } protected function columnPush(&$columns, &$map, $root, $is_join = false) { if ($columns === '*') { return $columns; } $stack = []; if (is_string($columns)) { $columns = [$columns]; } foreach ($columns as $key => $value) { if (!is_int($key) && is_array($value) && $root && count(array_keys($columns)) === 1) { $stack[] = $this->columnQuote($key); $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (is_array($value)) { $stack[] = $this->columnPush($value, $map, false, $is_join); } elseif (!is_int($key) && $raw = $this->buildRaw($value, $map)) { preg_match('/(?<column>[a-zA-Z0-9_\.]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $match); $stack[] = $raw . ' AS ' . $this->columnQuote($match[ 'column' ]); } elseif (is_int($key) && is_string($value)) { if ($is_join && strpos($value, '*') !== false) { throw new InvalidArgumentException('Cannot use table.* to select all columns while joining table'); } preg_match('/(?<column>[a-zA-Z0-9_\.]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $match); if (!empty($match[ 'alias' ])) { $stack[] = $this->columnQuote($match[ 'column' ]) . ' AS ' . $this->columnQuote($match[ 'alias' ]); $columns[ $key ] = $match[ 'alias' ]; if (!empty($match[ 'type' ])) { $columns[ $key ] .= ' [' . $match[ 'type' ] . ']'; } } else { $stack[] = $this->columnQuote($match[ 'column' ]); } } } return implode(',', $stack); } protected function arrayQuote($array) { $stack = []; foreach ($array as $value) { $stack[] = is_int($value) ? $value : $this->pdo->quote($value); } return implode(',', $stack); } protected function innerConjunct($data, $map, $conjunctor, $outer_conjunctor) { $stack = []; foreach ($data as $value) { $stack[] = '(' . $this->dataImplode($value, $map, $conjunctor) . ')'; } return implode($outer_conjunctor . ' ', $stack); } protected function dataImplode($data, &$map, $conjunctor) { $stack = []; foreach ($data as $key => $value) { $type = gettype($value); if ( $type === 'array' && preg_match("/^(AND|OR)(\s+#.*)?$/", $key, $relation_match) ) { $relationship = $relation_match[ 1 ]; $stack[] = $value !== array_keys(array_keys($value)) ? '(' . $this->dataImplode($value, $map, ' ' . $relationship) . ')' : '(' . $this->innerConjunct($value, $map, ' ' . $relationship, $conjunctor) . ')'; continue; } $map_key = $this->mapKey(); if ( is_int($key) && preg_match('/([a-zA-Z0-9_\.]+)\[(?<operator>\>\=?|\<\=?|\!?\=)\]([a-zA-Z0-9_\.]+)/i', $value, $match) ) { $stack[] = $this->columnQuote($match[ 1 ]) . ' ' . $match[ 'operator' ] . ' ' . $this->columnQuote($match[ 3 ]); } else { preg_match('/([a-zA-Z0-9_\.]+)(\[(?<operator>\>\=?|\<\=?|\!|\<\>|\>\<|\!?~|REGEXP)\])?/i', $key, $match); $column = $this->columnQuote($match[ 1 ]); if (isset($match[ 'operator' ])) { $operator = $match[ 'operator' ]; if (in_array($operator, ['>', '>=', '<', '<='])) { $condition = $column . ' ' . $operator . ' '; if (is_numeric($value)) { $condition .= $map_key; $map[ $map_key ] = [$value, is_float($value) ? PDO::PARAM_STR : PDO::PARAM_INT]; } elseif ($raw = $this->buildRaw($value, $map)) { $condition .= $raw; } else { $condition .= $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } $stack[] = $condition; } elseif ($operator === '!') { switch ($type) { case 'NULL': $stack[] = $column . ' IS NOT NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' NOT IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' != ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' != ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } elseif ($operator === '~' || $operator === '!~') { if ($type !== 'array') { $value = [ $value ]; } $connector = ' OR '; $data = array_values($value); if (is_array($data[ 0 ])) { if (isset($value[ 'AND' ]) || isset($value[ 'OR' ])) { $connector = ' ' . array_keys($value)[ 0 ] . ' '; $value = $data[ 0 ]; } } $like_clauses = []; foreach ($value as $index => $item) { $item = strval($item); if (!preg_match('/(\[.+\]|[\*\?\!\%#^-_]|%.+|.+%)/', $item)) { $item = '%' . $item . '%'; } $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $map_key . 'L' . $index; $map[ $map_key . 'L' . $index ] = [$item, PDO::PARAM_STR]; } $stack[] = '(' . implode($connector, $like_clauses) . ')'; } elseif ($operator === '<>' || $operator === '><') { if ($type === 'array') { if ($operator === '><') { $column .= ' NOT'; } $stack[] = '(' . $column . ' BETWEEN ' . $map_key . 'a AND ' . $map_key . 'b)'; $data_type = (is_numeric($value[ 0 ]) && is_numeric($value[ 1 ])) ? PDO::PARAM_INT : PDO::PARAM_STR; $map[ $map_key . 'a' ] = [$value[ 0 ], $data_type]; $map[ $map_key . 'b' ] = [$value[ 1 ], $data_type]; } } elseif ($operator === 'REGEXP') { $stack[] = $column . ' REGEXP ' . $map_key; $map[ $map_key ] = [$value, PDO::PARAM_STR]; } } else { switch ($type) { case 'NULL': $stack[] = $column . ' IS NULL'; break; case 'array': $placeholders = []; foreach ($value as $index => $item) { $stack_key = $map_key . $index . '_i'; $placeholders[] = $stack_key; $map[ $stack_key ] = $this->typeMap($item, gettype($item)); } $stack[] = $column . ' IN (' . implode(', ', $placeholders) . ')'; break; case 'object': if ($raw = $this->buildRaw($value, $map)) { $stack[] = $column . ' = ' . $raw; } break; case 'integer': case 'double': case 'boolean': case 'string': $stack[] = $column . ' = ' . $map_key; $map[ $map_key ] = $this->typeMap($value, $type); break; } } } } return implode($conjunctor . ' ', $stack); } protected function whereClause($where, &$map) { $where_clause = ''; if (is_array($where)) { $where_keys = array_keys($where); $conditions = array_diff_key($where, array_flip( ['GROUP', 'ORDER', 'HAVING', 'LIMIT', 'LIKE', 'MATCH'] )); if (!empty($conditions)) { $where_clause = ' WHERE ' . $this->dataImplode($conditions, $map, ' AND'); } if (isset($where[ 'MATCH' ]) && $this->type === 'mysql') { $MATCH = $where[ 'MATCH' ]; if (is_array($MATCH) && isset($MATCH[ 'columns' ], $MATCH[ 'keyword' ])) { $mode = ''; $mode_array = [ 'natural' => 'IN NATURAL LANGUAGE MODE', 'natural+query' => 'IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION', 'boolean' => 'IN BOOLEAN MODE', 'query' => 'WITH QUERY EXPANSION' ]; if (isset($MATCH[ 'mode' ], $mode_array[ $MATCH[ 'mode' ] ])) { $mode = ' ' . $mode_array[ $MATCH[ 'mode' ] ]; } $columns = implode(', ', array_map([$this, 'columnQuote'], $MATCH[ 'columns' ])); $map_key = $this->mapKey(); $map[ $map_key ] = [$MATCH[ 'keyword' ], PDO::PARAM_STR]; $where_clause .= ($where_clause !== '' ? ' AND ' : ' WHERE') . ' MATCH (' . $columns . ') AGAINST (' . $map_key . $mode . ')'; } } if (isset($where[ 'GROUP' ])) { $GROUP = $where[ 'GROUP' ]; if (is_array($GROUP)) { $stack = []; foreach ($GROUP as $column => $value) { $stack[] = $this->columnQuote($value); } $where_clause .= ' GROUP BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($GROUP, $map)) { $where_clause .= ' GROUP BY ' . $raw; } else { $where_clause .= ' GROUP BY ' . $this->columnQuote($GROUP); } if (isset($where[ 'HAVING' ])) { if ($raw = $this->buildRaw($where[ 'HAVING' ], $map)) { $where_clause .= ' HAVING ' . $raw; } else { $where_clause .= ' HAVING ' . $this->dataImplode($where[ 'HAVING' ], $map, ' AND'); } } } if (isset($where[ 'ORDER' ])) { $ORDER = $where[ 'ORDER' ]; if (is_array($ORDER)) { $stack = []; foreach ($ORDER as $column => $value) { if (is_array($value)) { $stack[] = 'FIELD(' . $this->columnQuote($column) . ', ' . $this->arrayQuote($value) . ')'; } elseif ($value === 'ASC' || $value === 'DESC') { $stack[] = $this->columnQuote($column) . ' ' . $value; } elseif (is_int($column)) { $stack[] = $this->columnQuote($value); } } $where_clause .= ' ORDER BY ' . implode(',', $stack); } elseif ($raw = $this->buildRaw($ORDER, $map)) { $where_clause .= ' ORDER BY ' . $raw; } else { $where_clause .= ' ORDER BY ' . $this->columnQuote($ORDER); } if ( isset($where[ 'LIMIT' ]) && in_array($this->type, ['oracle', 'mssql']) ) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $LIMIT = [0, $LIMIT]; } if ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' OFFSET ' . $LIMIT[ 0 ] . ' ROWS FETCH NEXT ' . $LIMIT[ 1 ] . ' ROWS ONLY'; } } } if (isset($where[ 'LIMIT' ]) && !in_array($this->type, ['oracle', 'mssql'])) { $LIMIT = $where[ 'LIMIT' ]; if (is_numeric($LIMIT)) { $where_clause .= ' LIMIT ' . $LIMIT; } elseif ( is_array($LIMIT) && is_numeric($LIMIT[ 0 ]) && is_numeric($LIMIT[ 1 ]) ) { $where_clause .= ' LIMIT ' . $LIMIT[ 1 ] . ' OFFSET ' . $LIMIT[ 0 ]; } } } elseif ($raw = $this->buildRaw($where, $map)) { $where_clause .= ' ' . $raw; } return $where_clause; } protected function selectContext($table, &$map, $join, &$columns = null, $where = null, $column_fn = null) { preg_match('/(?<table>[a-zA-Z0-9_]+)\s*\((?<alias>[a-zA-Z0-9_]+)\)/i', $table, $table_match); if (isset($table_match[ 'table' ], $table_match[ 'alias' ])) { $table = $this->tableQuote($table_match[ 'table' ]); $table_query = $table . ' AS ' . $this->tableQuote($table_match[ 'alias' ]); } else { $table = $this->tableQuote($table); $table_query = $table; } $is_join = false; $join_key = is_array($join) ? array_keys($join) : null; if ( isset($join_key[ 0 ]) && strpos($join_key[ 0 ], '[') === 0 ) { $is_join = true; $table_query .= ' ' . $this->buildJoin($table, $join); } else { if (is_null($columns)) { if ( !is_null($where) || (is_array($join) && isset($column_fn)) ) { $where = $join; $columns = null; } else { $where = null; $columns = $join; } } else { $where = $columns; $columns = $join; } } if (isset($column_fn)) { if ($column_fn === 1) { $column = '1'; if (is_null($where)) { $where = $columns; } } elseif ($raw = $this->buildRaw($column_fn, $map)) { $column = $raw; } else { if (empty($columns) || $this->isRaw($columns)) { $columns = '*'; $where = $join; } $column = $column_fn . '(' . $this->columnPush($columns, $map, true) . ')'; } } else { $column = $this->columnPush($columns, $map, true, $is_join); } return 'SELECT ' . $column . ' FROM ' . $table_query . $this->whereClause($where, $map); } protected function buildJoin($table, $join) { $table_join = []; $join_array = [ '>' => 'LEFT', '<' => 'RIGHT', '<>' => 'FULL', '><' => 'INNER' ]; foreach($join as $sub_table => $relation) { preg_match('/(\[(?<join>\<\>?|\>\<?)\])?(?<table>[a-zA-Z0-9_]+)\s?(\((?<alias>[a-zA-Z0-9_]+)\))?/', $sub_table, $match); if ($match[ 'join' ] !== '' && $match[ 'table' ] !== '') { if (is_string($relation)) { $relation = 'USING ("' . $relation . '")'; } if (is_array($relation)) { // For ['column1', 'column2'] if (isset($relation[ 0 ])) { $relation = 'USING ("' . implode('", "', $relation) . '")'; } else { $joins = []; foreach ($relation as $key => $value) { $joins[] = ( strpos($key, '.') > 0 ? // For ['tableB.column' => 'column'] $this->columnQuote($key) : // For ['column1' => 'column2'] $table . '."' . $key . '"' ) . ' = ' . $this->tableQuote(isset($match[ 'alias' ]) ? $match[ 'alias' ] : $match[ 'table' ]) . '."' . $value . '"'; } $relation = 'ON ' . implode(' AND ', $joins); } } $table_name = $this->tableQuote($match[ 'table' ]) . ' '; if (isset($match[ 'alias' ])) { $table_name .= 'AS ' . $this->tableQuote($match[ 'alias' ]) . ' '; } $table_join[] = $join_array[ $match[ 'join' ] ] . ' JOIN ' . $table_name . $relation; } } return implode(' ', $table_join); } protected function columnMap($columns, &$stack, $root) { if ($columns === '*') { return $stack; } foreach ($columns as $key => $value) { if (is_int($key)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(?:\s*\((?<alias>[a-zA-Z0-9_]+)\))?(?:\s*\[(?<type>(?:String|Bool|Int|Number|Object|JSON))\])?/i', $value, $key_match); $column_key = !empty($key_match[ 'alias' ]) ? $key_match[ 'alias' ] : $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $value ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $value ] = [$column_key, 'String']; } } elseif ($this->isRaw($value)) { preg_match('/([a-zA-Z0-9_]+\.)?(?<column>[a-zA-Z0-9_]+)(\s*\[(?<type>(String|Bool|Int|Number))\])?/i', $key, $key_match); $column_key = $key_match[ 'column' ]; if (isset($key_match[ 'type' ])) { $stack[ $key ] = [$column_key, $key_match[ 'type' ]]; } else { $stack[ $key ] = [$column_key, 'String']; } } elseif (!is_int($key) && is_array($value)) { if ($root && count(array_keys($columns)) === 1) { $stack[ $key ] = [$key, 'String']; } $this->columnMap($value, $stack, false); } } return $stack; } protected function dataMap($data, $columns, $column_map, &$stack, $root, &$result) { if ($root) { $columns_key = array_keys($columns); if (count($columns_key) === 1 && is_array($columns[$columns_key[0]])) { $index_key = array_keys($columns)[0]; $data_key = preg_replace("/^[a-zA-Z0-9_]+\./i", "", $index_key); $current_stack = []; foreach ($data as $item) { $this->dataMap($data, $columns[ $index_key ], $column_map, $current_stack, false, $result); $index = $data[ $data_key ]; $result[ $index ] = $current_stack; } } else { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, false, $result); $result[] = $current_stack; } return; } foreach ($columns as $key => $value) { $isRaw = $this->isRaw($value); if (is_int($key) || $isRaw) { $map = $column_map[ $isRaw ? $key : $value ]; $column_key = $map[ 0 ]; $item = $data[ $column_key ]; if (isset($map[ 1 ])) { if ($isRaw && in_array($map[ 1 ], ['Object', 'JSON'])) { continue; } if (is_null($item)) { $stack[ $column_key ] = null; continue; } switch ($map[ 1 ]) { case 'Number': $stack[ $column_key ] = (double) $item; break; case 'Int': $stack[ $column_key ] = (int) $item; break; case 'Bool': $stack[ $column_key ] = (bool) $item; break; case 'Object': $stack[ $column_key ] = unserialize($item); break; case 'JSON': $stack[ $column_key ] = json_decode($item, true); break; case 'String': $stack[ $column_key ] = $item; break; } } else { $stack[ $column_key ] = $item; } } else { $current_stack = []; $this->dataMap($data, $value, $column_map, $current_stack, false, $result); $stack[ $key ] = $current_stack; } } } public function create($table, $columns, $options = null) { $stack = []; $tableName = $this->prefix . $table; foreach ($columns as $name => $definition) { if (is_int($name)) { $stack[] = preg_replace('/\<([a-zA-Z0-9_]+)\>/i', '"$1"', $definition); } elseif (is_array($definition)) { $stack[] = $name . ' ' . implode(' ', $definition); } elseif (is_string($definition)) { $stack[] = $name . ' ' . $this->query($definition); } } $table_option = ''; if (is_array($options)) { $option_stack = []; foreach ($options as $key => $value) { if (is_string($value) || is_int($value)) { $option_stack[] = "$key = $value"; } } $table_option = ' ' . implode(', ', $option_stack); } elseif (is_string($options)) { $table_option = ' ' . $options; } return $this->exec("CREATE TABLE IF NOT EXISTS $tableName (" . implode(', ', $stack) . ")$table_option"); } public function drop($table) { $tableName = $this->prefix . $table; return $this->exec("DROP TABLE IF EXISTS $tableName"); } public function select($table, $join, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $index = 0; $column = $where === null ? $join : $columns; $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where), $map); $this->columnMap($columns, $column_map, true); if (!$this->statement) { return false; } if ($columns === '*') { return $query->fetchAll(PDO::FETCH_ASSOC); } while ($data = $query->fetch(PDO::FETCH_ASSOC)) { $current_stack = []; $this->dataMap($data, $columns, $column_map, $current_stack, true, $result); } if ($is_single) { $single_result = []; $result_key = $column_map[ $column ][ 0 ]; foreach ($result as $item) { $single_result[] = $item[ $result_key ]; } return $single_result; } return $result; } public function insert($table, $datas) { $stack = []; $columns = []; $fields = []; $map = []; if (!isset($datas[ 0 ])) { $datas = [$datas]; } foreach ($datas as $data) { foreach ($data as $key => $value) { $columns[] = $key; } } $columns = array_unique($columns); foreach ($datas as $data) { $values = []; foreach ($columns as $key) { if ($raw = $this->buildRaw($data[ $key ], $map)) { $values[] = $raw; continue; } $map_key = $this->mapKey(); $values[] = $map_key; if (!isset($data[ $key ])) { $map[ $map_key ] = [null, PDO::PARAM_NULL]; } else { $value = $data[ $key ]; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } $stack[] = '(' . implode(', ', $values) . ')'; } foreach ($columns as $key) { $fields[] = $this->columnQuote(preg_replace("/(\s*\[JSON\]$)/i", '', $key)); } return $this->exec('INSERT INTO ' . $this->tableQuote($table) . ' (' . implode(', ', $fields) . ') VALUES ' . implode(', ', $stack), $map); } public function update($table, $data, $where = null) { $fields = []; $map = []; foreach ($data as $key => $value) { $column = $this->columnQuote(preg_replace("/(\s*\[(JSON|\+|\-|\*|\/)\]$)/i", '', $key)); if ($raw = $this->buildRaw($value, $map)) { $fields[] = $column . ' = ' . $raw; continue; } $map_key = $this->mapKey(); preg_match('/(?<column>[a-zA-Z0-9_]+)(\[(?<operator>\+|\-|\*|\/)\])?/i', $key, $match); if (isset($match[ 'operator' ])) { if (is_numeric($value)) { $fields[] = $column . ' = ' . $column . ' ' . $match[ 'operator' ] . ' ' . $value; } } else { $fields[] = $column . ' = ' . $map_key; $type = gettype($value); switch ($type) { case 'array': $map[ $map_key ] = [ strpos($key, '[JSON]') === strlen($key) - 6 ? json_encode($value) : serialize($value), PDO::PARAM_STR ]; break; case 'object': $value = serialize($value); case 'NULL': case 'resource': case 'boolean': case 'integer': case 'double': case 'string': $map[ $map_key ] = $this->typeMap($value, $type); break; } } } return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $fields) . $this->whereClause($where, $map), $map); } public function delete($table, $where) { $map = []; return $this->exec('DELETE FROM ' . $this->tableQuote($table) . $this->whereClause($where, $map), $map); } public function replace($table, $columns, $where = null) { if (!is_array($columns) || empty($columns)) { return false; } $map = []; $stack = []; foreach ($columns as $column => $replacements) { if (is_array($replacements)) { foreach ($replacements as $old => $new) { $map_key = $this->mapKey(); $stack[] = $this->columnQuote($column) . ' = REPLACE(' . $this->columnQuote($column) . ', ' . $map_key . 'a, ' . $map_key . 'b)'; $map[ $map_key . 'a' ] = [$old, PDO::PARAM_STR]; $map[ $map_key . 'b' ] = [$new, PDO::PARAM_STR]; } } } if (!empty($stack)) { return $this->exec('UPDATE ' . $this->tableQuote($table) . ' SET ' . implode(', ', $stack) . $this->whereClause($where, $map), $map); } return false; } public function get($table, $join = null, $columns = null, $where = null) { $map = []; $result = []; $column_map = []; $current_stack = []; if ($where === null) { $column = $join; unset($columns[ 'LIMIT' ]); } else { $column = $columns; unset($where[ 'LIMIT' ]); } $is_single = (is_string($column) && $column !== '*'); $query = $this->exec($this->selectContext($table, $map, $join, $columns, $where) . ' LIMIT 1', $map); if (!$this->statement) { return false; } $data = $query->fetchAll(PDO::FETCH_ASSOC); if (isset($data[ 0 ])) { if ($column === '*') { return $data[ 0 ]; } $this->columnMap($columns, $column_map, true); $this->dataMap($data[ 0 ], $columns, $column_map, $current_stack, true, $result); if ($is_single) { return $result[ 0 ][ $column_map[ $column ][ 0 ] ]; } return $result[ 0 ]; } } public function has($table, $join, $where = null) { $map = []; $column = null; if ($this->type === 'mssql') { $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, Medoo::raw('TOP 1 1')), $map); } else { $query = $this->exec('SELECT EXISTS(' . $this->selectContext($table, $map, $join, $column, $where, 1) . ')', $map); } if (!$this->statement) { return false; } $result = $query->fetchColumn(); return $result === '1' || $result === 1 || $result === true; } public function rand($table, $join = null, $columns = null, $where = null) { $type = $this->type; $order = 'RANDOM()'; if ($type === 'mysql') { $order = 'RAND()'; } elseif ($type === 'mssql') { $order = 'NEWID()'; } $order_raw = $this->raw($order); if ($where === null) { if ($columns === null) { $columns = [ 'ORDER' => $order_raw ]; } else { $column = $join; unset($columns[ 'ORDER' ]); $columns[ 'ORDER' ] = $order_raw; } } else { unset($where[ 'ORDER' ]); $where[ 'ORDER' ] = $order_raw; } return $this->select($table, $join, $columns, $where); } private function aggregate($type, $table, $join = null, $column = null, $where = null) { $map = []; $query = $this->exec($this->selectContext($table, $map, $join, $column, $where, strtoupper($type)), $map); if (!$this->statement) { return false; } $number = $query->fetchColumn(); return is_numeric($number) ? $number + 0 : $number; } public function count($table, $join = null, $column = null, $where = null) { return $this->aggregate('count', $table, $join, $column, $where); } public function avg($table, $join, $column = null, $where = null) { return $this->aggregate('avg', $table, $join, $column, $where); } public function max($table, $join, $column = null, $where = null) { return $this->aggregate('max', $table, $join, $column, $where); } public function min($table, $join, $column = null, $where = null) { return $this->aggregate('min', $table, $join, $column, $where); } public function sum($table, $join, $column = null, $where = null) { return $this->aggregate('sum', $table, $join, $column, $where); } public function action($actions) { if (is_callable($actions)) { $this->pdo->beginTransaction(); try { $result = $actions($this); if ($result === false) { $this->pdo->rollBack(); } else { $this->pdo->commit(); } } catch (Exception $e) { $this->pdo->rollBack(); throw $e; } return $result; } return false; } public function id() { if ($this->statement == null) { return null; } $type = $this->type; if ($type === 'oracle') { return 0; } elseif ($type === 'pgsql') { return $this->pdo->query('SELECT LASTVAL()')->fetchColumn(); } $lastId = $this->pdo->lastInsertId(); if ($lastId != "0" && $lastId != "") { return $lastId; } return null; } public function debug() { $this->debug_mode = true; return $this; } public function error() { return $this->errorInfo; } public function last() { $log = end($this->logs); return $this->generate($log[ 0 ], $log[ 1 ]); } public function log() { return array_map(function ($log) { return $this->generate($log[ 0 ], $log[ 1 ]); }, $this->logs ); } public function info() { $output = [ 'server' => 'SERVER_INFO', 'driver' => 'DRIVER_NAME', 'client' => 'CLIENT_VERSION', 'version' => 'SERVER_VERSION', 'connection' => 'CONNECTION_STATUS' ]; foreach ($output as $key => $value) { $output[ $key ] = @$this->pdo->getAttribute(constant('PDO::ATTR_' . $value)); } $output[ 'dsn' ] = $this->dsn; return $output; } } 完整写出修复后的代码 我复制
最新发布
11-29
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值