quicklite
Version:
A lightweight ORM toolkit for SQLite in Node.js applications
197 lines • 8.04 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataTransferUtil = void 0;
const fs_1 = __importDefault(require("fs"));
/**
* 数据传输工具
*/
class DataTransferUtil {
/**
* 导出表数据到JSON文件
* @param service 数据服务
* @param filePath 导出文件路径
* @param options 导出选项
* @returns 导出的数据条数
*/
static exportToJson(service, filePath, options) {
try {
// 使用服务查询数据
const records = service.find({
where: options === null || options === void 0 ? void 0 : options.where,
orderBy: options === null || options === void 0 ? void 0 : options.orderBy
});
// 准备导出数据
const exportData = {
tableName: service.tableInfo.name,
records,
metadata: {
exportTime: Date.now(),
...options === null || options === void 0 ? void 0 : options.metadata
}
};
// 写入文件
fs_1.default.writeFileSync(filePath, JSON.stringify(exportData, null, 2));
return records.length;
}
catch (error) {
console.error('导出数据失败:', error);
return 0;
}
}
/**
* 从JSON文件导入数据到表
* @param service 数据服务
* @param filePath 导入文件路径
* @param options 导入选项
* @returns 导入的数据条数
*/
static importFromJson(service, filePath, options) {
try {
// 检查文件是否存在
if (!fs_1.default.existsSync(filePath)) {
throw new Error(`导入文件不存在: ${filePath}`);
}
// 读取文件内容
const fileContent = fs_1.default.readFileSync(filePath, 'utf8');
const importData = JSON.parse(fileContent);
// 检查表名是否匹配
if ((options === null || options === void 0 ? void 0 : options.checkTableName) &&
importData.tableName !== service.tableInfo.name) {
throw new Error(`表名不匹配: 期望 ${service.tableInfo.name}, 实际 ${importData.tableName}`);
}
// 清空表
if (options === null || options === void 0 ? void 0 : options.clearTable) {
const db = service.db;
db.exec(`DELETE FROM ${service.tableInfo.name}`);
}
// 准备导入数据
let records = importData.records;
// 应用数据转换
if (options === null || options === void 0 ? void 0 : options.transform) {
records = records.map(options.transform);
}
// 使用事务批量插入
service.batchInsert(records);
return records.length;
}
catch (error) {
console.error('导入数据失败:', error);
return 0;
}
}
/**
* 导出查询结果到CSV文件
* @param db 数据库实例
* @param query SQL查询语句
* @param filePath 导出文件路径
* @param params 查询参数
* @returns 导出的数据条数
*/
static exportQueryToCsv(db, query, filePath, params = []) {
try {
// 执行查询
const stmt = db.prepare(query);
const records = stmt.all(...params);
if (records.length === 0) {
// 输出空文件
fs_1.default.writeFileSync(filePath, '');
return 0;
}
// 提取列名
const headers = Object.keys(records[0]);
// 生成CSV内容
let csvContent = headers.join(',') + '\n';
for (const record of records) {
const row = headers.map(header => {
const value = record[header];
// 处理CSV中特殊字符
if (value === null || value === undefined) {
return '';
}
if (typeof value === 'string') {
// 如果包含逗号、引号或换行符,用引号包围并将引号替换为两个引号
if (value.includes(',') || value.includes('"') || value.includes('\n')) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
}
return String(value);
}).join(',');
csvContent += row + '\n';
}
// 写入文件
fs_1.default.writeFileSync(filePath, csvContent);
return records.length;
}
catch (error) {
console.error('导出查询结果失败:', error);
return 0;
}
}
/**
* 从一个数据库复制表数据到另一个数据库
* @param sourceDb 源数据库实例
* @param targetDb 目标数据库实例
* @param tableName 表名
* @param options 复制选项
* @returns 复制的数据条数
*/
static copyTableData(sourceDb, targetDb, tableName, options) {
try {
// 获取表结构信息
const sourceColumns = sourceDb.prepare(`PRAGMA table_info(${tableName})`).all();
const targetColumns = targetDb.prepare(`PRAGMA table_info(${tableName})`).all();
// 找出共同的列
const sourceColNames = sourceColumns.map(c => c.name);
const targetColNames = targetColumns.map(c => c.name);
const commonColumns = sourceColNames.filter(col => targetColNames.includes(col));
if (commonColumns.length === 0) {
throw new Error('源表和目标表没有共同的列');
}
// 构建查询
const whereClause = (options === null || options === void 0 ? void 0 : options.where) ? ` WHERE ${options.where}` : '';
const query = `SELECT ${commonColumns.join(', ')} FROM ${tableName}${whereClause}`;
// 执行查询获取源数据
const stmt = sourceDb.prepare(query);
const sourceData = stmt.all(...((options === null || options === void 0 ? void 0 : options.params) || []));
if (sourceData.length === 0) {
return 0;
}
// 开始事务
targetDb.exec('BEGIN TRANSACTION');
try {
// 准备插入语句
const placeholders = commonColumns.map(() => '?').join(', ');
const insertStmt = targetDb.prepare(`INSERT INTO ${tableName} (${commonColumns.join(', ')}) VALUES (${placeholders})`);
// 批量插入
const batchSize = (options === null || options === void 0 ? void 0 : options.batchSize) || 100;
let count = 0;
for (let i = 0; i < sourceData.length; i += batchSize) {
const batch = sourceData.slice(i, i + batchSize);
for (const record of batch) {
const values = commonColumns.map(col => record[col]);
insertStmt.run(values);
count++;
}
}
// 提交事务
targetDb.exec('COMMIT');
return count;
}
catch (err) {
// 回滚事务
targetDb.exec('ROLLBACK');
throw err;
}
}
catch (error) {
console.error('复制表数据失败:', error);
return 0;
}
}
}
exports.DataTransferUtil = DataTransferUtil;
//# sourceMappingURL=DataTransferUtil.js.map