Commit f7f88a68 by liimin

feat(database): 动态添加数据库字段

- 在 DBManager 初始化时检查并添加新字段
- 新增 SQLite 类的 isColumnExists 和 addColumns 方法
- 优化 DBManager 类的代码结构和格式
1 parent d6ac1eaf
......@@ -159,6 +159,40 @@ class SQLite {
formatValue(value) {
return typeof value === 'object' && value !== null ? `'${JSON.stringify(value)}'` : `'${value}'`
}
/**
* 检查指定字段是否存在于表中
* @param {string} tableName - 表名
* @param {string} columnName - 要检查的字段名
* @returns {Promise<boolean>} - 字段存在返回true,否则返回false
*/
async isColumnExists(tableName, columnName) {
try {
const columnInfo = await this.executeSql(`PRAGMA table_info(${tableName})`)
return columnInfo.some(col => col.name === columnName)
} catch (error) {
console.error(`检查字段是否存在失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
/**
* 批量添加字段到表中
* @param {string} tableName - 表名
* @param {Array<{name: string, definition: string}>} columns - 要添加的字段数组
* @returns {Promise<void>}
*/
async addColumns(tableName, columns) {
try {
for (const column of columns) {
const { name, definition = 'TEXT DEFAULT ""' } = column
await this.executeSql(`ALTER TABLE ${tableName} ADD COLUMN ${name} ${definition}`)
}
} catch (error) {
console.error(`批量添加列失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
}
export default SQLite
// 使用示例
......
/*
* @Descripttion:
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-11-22 08:18:23
* @LastEditors: limin
* @LastEditTime: 2025-01-06 09:36:39
* @LastEditTime: 2025-08-06 00:56:24
* @FilePath: \gl_tape\utils\DBManager.js
*/
import { SQLite } from '../lib'
......@@ -19,34 +19,7 @@ class DBManager {
db_table_name = 'records'
db_description = 'zyzs db'
db_size = 50 * 1024 * 1024
table_columns = [
`id TEXT PRIMARY KEY`,
`staffUuid TEXT`,
`staffName TEXT`,
`serviceMerchantId INTEGER`,
'carModel TEXT',
'endReasonType INTEGER',
'customerName TEXT',
'phoneNumber TEXT',
'appCode TEXT',
'loginPhone TEXT',
'salesName TEXT',
'salesUuid TEXT',
'receptionStatus INTEGER',
'receptionStartTime TEXT',
'receptionEndTime TEXT',
'receptionCustomerPaySourceList TEXT',
'merchantId INTEGER',
'merchantName TEXT',
'bussinessType INTEGER',
'channelType INTEGER',
'receptionCustomerMaterialPointList TEXT',
'recordUrlList TEXT',
'carBrand TEXT',
'carBrandId INTEGER',
'oneCarBrand TEXT',
'oneCarBrandId INTEGER'
]
table_columns = [`id TEXT PRIMARY KEY`, `staffUuid TEXT`, `staffName TEXT`, `serviceMerchantId INTEGER`, 'carModel TEXT', 'endReasonType INTEGER', 'customerName TEXT', 'phoneNumber TEXT', 'appCode TEXT', 'loginPhone TEXT', 'salesName TEXT', 'salesUuid TEXT', 'receptionStatus INTEGER', 'receptionStartTime TEXT', 'receptionEndTime TEXT', 'receptionCustomerPaySourceList TEXT', 'merchantId INTEGER', 'merchantName TEXT', 'bussinessType INTEGER', 'channelType INTEGER', 'receptionCustomerMaterialPointList TEXT', 'recordUrlList TEXT', 'carBrand TEXT', 'carBrandId INTEGER', 'oneCarBrand TEXT', 'oneCarBrandId INTEGER']
sqlite = null
isTableExists = false
constructor(table_name, table_columns) {
......@@ -54,7 +27,7 @@ class DBManager {
this.table_columns = table_columns || this.table_columns
this.db = new SQLite(this.db_name, this.db_version, this.db_description, this.db_size)
}
async init () {
async init() {
try {
const isOpen = await this.db.isOpen()
if (!isOpen) {
......@@ -63,6 +36,16 @@ class DBManager {
const isTableExists = await this.db.isTableExists(this.table_name)
if (!isTableExists) {
await this.db.createTable(this.table_name, this.table_columns)
} else { //如果存在 判断需要新增的字段是否存在 不存在则添加
const isColumnExists = await this.db.isColumnExists(this.table_name, 'carBrand')
if (!isColumnExists) {
await this.db.addColumns(this.table_name, [
{ name: 'carBrand', definition: 'TEXT DEFAULT ""' },
{ name: 'carBrandId', definition: 'INTEGER DEFAULT 0' },
{ name: 'oneCarBrand', definition: 'TEXT DEFAULT ""' },
{ name: 'oneCarBrandId', definition: 'INTEGER DEFAULT 0' }
])
}
}
return true
} catch (error) {
......@@ -70,16 +53,14 @@ class DBManager {
throw new Error(error.message)
}
}
async openDB () {
}
async openDB() {}
/**
* 将一条新记录添加到当前对象的记录列表中
*
* @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord (record) {
async addRecord(record) {
await this.db.insert(this.table_name, record)
}
/**
......@@ -88,7 +69,7 @@ class DBManager {
* @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表
*/
async removeRecord (id) {
async removeRecord(id) {
return this.db.delete(this.table_name, { id })
}
/**
......@@ -98,7 +79,7 @@ class DBManager {
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
*
*/
async getRecordById (id) {
async getRecordById(id) {
const records = await this.db.select(this.table_name, { id })
return Array.isArray(records) ? records[0] : records // sqlite 返回数组
}
......@@ -107,7 +88,7 @@ class DBManager {
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
async getRecords () {
async getRecords() {
return this.db.select(this.table_name)
}
/**
......@@ -116,7 +97,7 @@ class DBManager {
* @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值
*/
async setRecords (records) {
async setRecords(records) {
return records.forEach(async record => {
this.addRecord(record)
})
......@@ -129,17 +110,17 @@ class DBManager {
* @param {Object} record - 要更新的记录对象,必须包含一个唯一的 id 属性
* @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误
*/
async updateRecord (setData, where) {
async updateRecord(setData, where) {
const { id, ...record } = setData
if (!where) {
where = { id }
}
return this.db.update(this.table_name, record, where)
}
async isOpen () {
async isOpen() {
return this.db.isOpen()
}
async isTableExists () {
async isTableExists() {
return this.db.isTableExists(this.table_name)
}
/**
......@@ -147,10 +128,10 @@ class DBManager {
*
* @returns {void} - 此函数不返回任何值
*/
async clearRecords () {
async clearRecords() {
this.db.delete(this.table_name)
}
async drop () {
async drop() {
this.db.drop(this.table_name)
}
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!