Commit b54cad6d by ning

新增数据库操作

parent 86e7d08d
......@@ -6,5 +6,7 @@
"description": "a npm package which contains arkUI2.0 page",
"main": "index.ets",
"version": "1.0.0",
"dependencies": {}
"dependencies": {
"reflect-metadata": "^0.1.13"
}
}
import rdb from '@ohos.data.relationalStore';
import Logger from '../utils/Logger';
import ITable from './ITable';
export type ValueType = number | string | boolean | Uint8Array;
export type ValuesBucket = {
[key: string]: ValueType | Uint8Array | null;
};
/**
* 数据库表抽象类,实现ITable接口,封装常用的增删改查操作
*/
export default abstract class BaseTable<T> implements ITable {
protected readonly tableName;
private readonly dbName;
protected readonly futureDb: Promise<rdb.RdbStore>
constructor(dbName: string, tableName: string) {
this.dbName = dbName;
this.tableName = tableName;
this.futureDb = this.initDb();
}
/**
* 初始化数据库
*/
private async initDb(): Promise<rdb.RdbStore> {
Logger.info(this, '初始化数据库,dbName=' + this.dbName + ',tableName=' + this.tableName);
let db = await rdb.getRdbStore(getContext(this), {
name: this.dbName,
securityLevel: rdb.SecurityLevel.S1
})
await this.init(db);
return db;
}
/**
* 初始化数据表
*/
protected async init(db: rdb.RdbStore): Promise<void> {
return db.executeSql(this.getCreateTableSql())
}
/**
* 获取表名
*/
getTableName(): string {
return this.tableName
}
/**
* 提供数据库管理对象
*/
getPredicates() {
return new rdb.RdbPredicates(this.tableName)
}
bindToValuesBucket(bucket: ValuesBucket, item: T) {
this.getTableColumns().forEach((col) => {
bucket[col] = item[col]
})
}
/**
* 清空表
*/
async clearTable(): Promise<void> {
let db = await this.futureDb;
try {
db.beginTransaction();
await db.executeSql("delete from " + this.tableName);
await db.executeSql("update sqlite_sequence SET seq = 0 where name ='" + this.tableName + "'")
} catch (e) {
Logger.error(this, "清空表失败:", e);
db.rollBack();
}
}
/**
* 插入数据
* @param item 插入对象
*/
async insert(item: T): Promise<number> {
let bucket = {};
this.bindToValuesBucket(bucket, item);
let db = await this.futureDb;
return db.insert(this.tableName, bucket);
}
/**
* 删除数据
*/
async delete(item: T): Promise<number> {
let predicates = this.getPredicates().equalTo(this.getColumnId(), this.getEntityId(item));
return this.deleteAll(predicates)
}
/**
* 删除数据
*/
async deleteAll(predicates: rdb.RdbPredicates): Promise<number> {
let db = await this.futureDb;
return db.delete(predicates);
}
async deleteItems(...items: T[]): Promise<number[]> {
if (!items) {
return [];
}
const results: number[] = [];
for (const item of items) {
let predicates = this.getPredicates().equalTo(this.getColumnId(), this.getEntityId(item));
results.push(await this.deleteAll(predicates))
}
return results;
}
async update(item: T, predicates?: rdb.RdbPredicates): Promise<number> {
let bucket = {};
this.bindToValuesBucket(bucket, item);
Logger.info(this, '更新数据,bucket=' + JSON.stringify(bucket));
bucket[this.getColumnId()] = undefined;
let db = await this.futureDb;
if (!predicates) {
predicates = this.getPredicates().equalTo(this.getColumnId(), this.getEntityId(item));
}
return db.update(bucket, predicates);
}
/**
* 查询所有数据
*/
async queryAll(predicates?: rdb.RdbPredicates): Promise<T[]> {
if (!predicates) {
predicates = this.getPredicates()
}
return this.query(predicates, this.getTableColumns())
}
/**
* 根据条件查询数据
* @param predicates
* @param columns
*/
async query(predicates: rdb.RdbPredicates, columns?: Array<string>): Promise<T[]> {
Logger.info(this, '查询数据')
let db = await this.futureDb
let resultSet = await db.query(predicates, columns)
let items = []
if (resultSet.goToFirstRow()) {
do {
Logger.info(this, 'queryAll rowIndex=' + resultSet.rowIndex)
items.push(this.createItem(resultSet))
} while (resultSet.goToNextRow())
}
Logger.e(this, 'queryAll items=' + JSON.stringify(items))
return items;
}
/**
* 创建表的SQL语句
*/
abstract getCreateTableSql(): string;
/**
* 表的列信息
*/
abstract getTableColumns(): string[];
/**
* 列主键
*/
abstract getColumnId(): string;
/**
* 列的数据类型
*/
abstract getEntityId(item: T): ValueType;
abstract createItem(cursor: rdb.ResultSet): T;
}
\ No newline at end of file
export enum ValueType {
TEXT, INTEGER, LONG
}
export default interface ColumnInfo {
name: string,
type: 'TEXT' | 'INTEGER',
isPrimaryKey?: boolean,
autoIncrement?: boolean,
unique?: boolean,
notNull?: boolean,
defaultValue?: ValueType
}
\ No newline at end of file
/**
* 数据库接口
*/
import BaseTable from './BaseTable';
export default interface IDatabase {
/**
* 获取数据库表对象
*/
getTable<T extends BaseTable<any>>(tableClass: { new(dbName, tableName): T }): T
}
\ No newline at end of file
/**
* 数据库表接口
*/
export default interface ITable {
/**
* 获取数据库表名
*/
getTableName(): string
/**
* 获取数据库主键
*/
getColumnId(): string
/**
* 获取数据库表项
*/
getTableColumns(): string[]
/**
* 获取创建表sql语句
*/
getCreateTableSql(): string
}
\ No newline at end of file
/**
* 管理单位的数据层
*/
import relationalStore from '@ohos.data.relationalStore';
import { Gldw } from '../../entity/Gldw';
import BaseTable, { ValueType } from '../BaseTable';
import { Table } from '../decorator/Decorators';
@Table({ db: 'db_wms_app', name: 'TAB_BZGL_KNZY_APP_BGDDW' })
export class GldwDao extends BaseTable<Gldw> {
createItem(cursor: relationalStore.ResultSet): Gldw {
throw new Error('Method not implemented.');
}
getEntityId(item: Gldw): ValueType {
throw new Error('Method not implemented.');
}
getColumnId(): string {
throw new Error('Method not implemented.');
}
getTableColumns(): string[] {
throw new Error('Method not implemented.');
}
getCreateTableSql(): string {
throw new Error('Method not implemented.');
}
}
\ No newline at end of file
import 'reflect-metadata';
export function Table(v: {
db: string,
name: string
}): ClassDecorator {
return (target) => {
Reflect.defineMetadata('Database', v.db, target);
Reflect.defineMetadata('TableName', v.name, target);
};
}
\ No newline at end of file
/**
* 管理单位信息
*/
export interface Gldw {
guid?: string,
dwfh: string,
dwdm: string,
dwxz: string
}
\ No newline at end of file
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
/**
* Common log for all features.
*
* @param {string} prefix Identifies the log tag.
*/
const DOMAIN: number = 0xFF00;
const PREFIX: string = '[Junmp-WMS]|';
const FORMAT: string = `%{public}s, %{public}s`;
let domain: number = 0xFF00;
let prefix: string = 'MultiShopping';
let format: string = `%{public}s, %{public}s`;
export class Logger {
static debug(...args: string[]) {
hilog.debug(domain, prefix, format, args);
}
/**
* 日志工具类
*/
export default class Logger {
static info(...args: string[]) {
hilog.info(domain, prefix, format, args);
/**
* DEBUG
*/
static debug(tag: any, ...args: string[]) {
hilog.debug(DOMAIN, PREFIX, FORMAT, this.wrapperArgs(tag, args));
}
static warn(...args: string[]) {
hilog.warn(domain, prefix, format, args);
/**
* INFO
*/
static info(tag: any, ...args: string[]) {
hilog.info(DOMAIN, PREFIX, FORMAT, this.wrapperArgs(tag, args));
}
static error(...args: string[]) {
hilog.error(domain, prefix, format, args);
/**
* WARN
*/
static warn(tag: any, ...args: string[]) {
hilog.warn(DOMAIN, PREFIX, FORMAT, this.wrapperArgs(tag, args));
}
static fatal(...args: string[]) {
hilog.fatal(domain, prefix, format, args);
/**
* ERROR
*/
static error(tag: any, ...args: string[]) {
hilog.error(DOMAIN, PREFIX, FORMAT, this.wrapperArgs(tag, args));
}
static isLoggable(level: LogLevel) {
hilog.isLoggable(domain, prefix, level);
/**
* TAG转换为字符串
*/
static wrapperArgs(tag: any, args: string[]): string[] {
let name: string;
if ((typeof tag) == 'string') {
name = tag;
} else if ((typeof tag) == 'function') {
name = tag.name;
} else if ((typeof tag) == 'object') {
name = tag.constructor.name;
} else {
name = (typeof tag) + '-' + tag;
}
if (name) {
if (args) {
args.splice(0, 0, name);
} else {
args = [name];
}
}
return args;
}
}
/**
* Log level define
*
* @syscap SystemCapability.HiviewDFX.HiLog
*/
enum LogLevel {
DEBUG = 3,
INFO = 4,
WARN = 5,
ERROR = 6,
FATAL = 7
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论