Feat: add database

This commit is contained in:
cheliangzhao 2023-10-07 13:36:58 +08:00
parent fae226f4fa
commit b5c0263868
12 changed files with 426 additions and 2 deletions

View File

@ -0,0 +1,23 @@
import relationalStore from '@ohos.data.relationalStore'
export const DatabaseConfig = {
RDB_TAG: '[Debug.Rdb]',
STORE_CONFIG: {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1,
},
TODO_TABLE: {
tableName: 'todoTable',
sqlCreate: `CREATE TABLE IF NOT EXISTS todoTable(
id INTEGER PRIMARY KEY AUTOINCREMENT,
status INTEGER,
content TEXT
)`,
columns: ['id', 'status', 'content'],
update1to3: ``,
update2to3: ``,
},
}

View File

@ -0,0 +1,82 @@
import relationalStore from '@ohos.data.relationalStore';
import { DatabaseConfig } from '../config';
export default class Rdb {
private rdbStore: relationalStore.RdbStore = null;
private tableName: string;
private sqlCreateTable: string;
private columns: Array<string>;
constructor(tableName: string, sqlCreateTable: string, columns: Array<string>) {
this.tableName = tableName;
this.sqlCreateTable = sqlCreateTable;
this.columns = columns;
}
async getRdbStore(callback) {
const context = getContext(this)
try {
const store = await relationalStore.getRdbStore(context, DatabaseConfig.STORE_CONFIG)
this.rdbStore = store;
console.info('getRdbStore() finished.');
callback(store)
} catch (err) {
console.error('getRdbStore() failed, error: ' + err)
}
}
async insertData(data) {
const valueBucket = data
try {
const rowId = await this.rdbStore.insert(this.tableName, valueBucket);
console.info("insertData() finished: ", rowId)
return rowId;
} catch (err) {
console.error('insertData() failed, err: ' + err)
}
}
async updateData(predicates, data) {
const valueBucket = data;
try {
const rows = await this.rdbStore.update(valueBucket, predicates);
console.info('updateData() finished: ' + rows);
return rows;
} catch (err) {
console.error('update() failed, err: ' + err);
}
}
async deleteData(predicates) {
try {
const rows = await this.rdbStore.delete(predicates);
console.info('deleteData() finished: ' + rows);
return rows;
} catch (err) {
console.error('deleteData() failed, err: ' + err);
}
}
async query(predicates, mapFunc: Function) {
try {
const resSet = await this.rdbStore.query(predicates, this.columns)
const resList = [];
while (resSet.goToNextRow()) {
const resKeys = this.columns;
const resItem = mapFunc(resKeys, resSet);
resList.push(resItem);
}
resSet.close()
return resList;
}
catch (err) {
console.error('query() failed, err: ', err);
}
}
}

View File

@ -0,0 +1,85 @@
import { TodoData } from '../../types/Todo'
import { DatabaseConfig } from '../../config'
import Rdb from '../Rdb'
import relationalStore from '@ohos.data.relationalStore'
export default class TodoTable {
private todoTable = new Rdb(
DatabaseConfig.TODO_TABLE.tableName,
DatabaseConfig.TODO_TABLE.sqlCreate,
DatabaseConfig.TODO_TABLE.columns
)
constructor(callback: Function = () => {
}) {
this.getRdbStore(callback)
}
private getRdbStore(callback) {
// 假设当前数据库版本为3
this.todoTable.getRdbStore(store => {
// 当数据库创建时数据库版本默认为0
if (store.version == 0) {
store.executeSql(DatabaseConfig.TODO_TABLE.sqlCreate);
store.version = 3;
}
// 如果数据库版本不为0且和当前数据库的版本不匹配需要进行升降级操作
// 当数据库存在并假定版本为1时将其升级为2版本
if (store.version != 3 && store.version == 1) {
store.executeSql(DatabaseConfig.TODO_TABLE.update1to3);
store.version = 2;
}
// 当数据库存在并假定版本为2时将其升级为3版本
if (store.version != 3 && store.version == 2) {
store.executeSql(DatabaseConfig.TODO_TABLE.update2to3);
store.version = 3;
}
})
if (callback) callback()
}
async insertData(data: TodoData) {
return await this.todoTable.insertData(generateBucket(data));
}
async updateData(data: TodoData) {
const valueBucket = generateBucket(data)
const predicates = new relationalStore.RdbPredicates(DatabaseConfig.TODO_TABLE.tableName)
predicates.equalTo('id', data.id)
return await this.todoTable.updateData(predicates, valueBucket)
}
async deleteData(data: TodoData) {
const predicates = new relationalStore.RdbPredicates(DatabaseConfig.TODO_TABLE.tableName);
predicates.equalTo('id', data.id);
return await this.todoTable.deleteData(predicates);
}
async query(content: string) {
const predicates = new relationalStore.RdbPredicates(DatabaseConfig.TODO_TABLE.tableName)
predicates.contains('content', content)
return await this.todoTable.query(predicates, (_, resSet: relationalStore.ResultSet): TodoData => {
return {
id: resSet.getLong(resSet.getColumnIndex('id')),
status: resSet.getLong(resSet.getColumnIndex('status')),
content: resSet.getString(resSet.getColumnIndex('content')),
}
})
}
}
function generateBucket(account: TodoData) {
let obj = {};
DatabaseConfig.TODO_TABLE.columns.forEach((item) => {
if (item != 'id') {
obj[item] = account[item];
}
});
return obj;
}

View File

@ -0,0 +1,5 @@
export interface TodoData {
id: number,
status: number,
content: string,
}

View File

@ -6,6 +6,8 @@ import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
}

View File

@ -0,0 +1,19 @@
/**
* Database apply demo
*/
@Entry
@Component
struct Todo {
@State message: string = "This a Template Project"
build() {
Row() {
Text(this.message)
.fontSize(40)
.fontWeight(FontWeight.Bold)
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
}

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2022 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 { ILogger } from './ILogger';
export class ConsoleLogger implements ILogger {
private appIdentifier: string;
constructor(appIdentifier: string) {
this.appIdentifier = appIdentifier;
}
public verbose(tag: string, msg: string): void {
console.log(`[${this.appIdentifier}] [verbose] tag:${tag} msg:${msg}`);
}
public debug(tag: string, msg: string): void {
console.debug(`[${this.appIdentifier}] [debug] tag:${tag} msg:${msg}`);
}
public info(tag: string, msg: string): void {
console.info(`[${this.appIdentifier}] [info] tag:${tag} msg:${msg}`);
}
public warn(tag: string, msg: string): void {
console.warn(`[${this.appIdentifier}] [warn] tag:${tag} msg:${msg}`);
}
public error(tag: string, msg: string): void {
console.error(`[${this.appIdentifier}] [error] tag:${tag} msg:${msg}`);
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2022 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';
import { ILogger } from './ILogger';
export class HiLogger implements ILogger {
private appIdentifier: string;
private appDomain: number = 0x0001;
constructor(appIdentifier: string) {
this.appIdentifier = appIdentifier;
}
public verbose(tag: string, msg: string): void {
hilog.debug(this.appDomain, tag, `[${this.appIdentifier}] [verbose] tag:${tag} msg:${msg}`);
}
public debug(tag: string, msg: string): void {
hilog.debug(this.appDomain, tag, `[${this.appIdentifier}] [debug] tag:${tag} msg:${msg}`);
}
public info(tag: string, msg: string): void {
hilog.info(this.appDomain, tag, `[${this.appIdentifier}] [info] tag:${tag} msg:${msg}`);
}
public warn(tag: string, msg: string): void {
hilog.warn(this.appDomain, tag, `[${this.appIdentifier}] [warn] tag:${tag} msg:${msg}`);
}
public error(tag: string, msg: string): void {
hilog.error(this.appDomain, tag, `[${this.appIdentifier}] [error] tag:${tag} msg:${msg}`);
}
}

View File

@ -0,0 +1,26 @@
/*
* Copyright (c) 2022 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.
*/
export interface ILogger {
verbose(tag: string, msg: string): void;
debug(tag: string, msg: string): void;
info(tag: string, msg: string): void;
warn(tag: string, msg: string): void;
error(tag: string, msg: string): void;
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2022 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 { ILogger } from './ILogger';
import { HiLogger } from './HiLogger';
import { ConsoleLogger } from './ConsoleLogger';
export class Logger implements ILogger {
private static isAppDebugMode: boolean = true;
private static appIdentifier: string = 'RDB';
// if true, use a ConsoleLogger, or HiLogger otherwise
private static useConsoleLogger: boolean = true;
public static verbose(tag: string, msg: string): void {
if (Logger.isAppDebugMode) {
Logger.getInstance().verbose(tag, msg);
}
}
public static debug(tag: string, msg: string): void {
if (Logger.isAppDebugMode) {
Logger.getInstance().debug(tag, msg);
}
}
public static info(tag: string, msg: string): void {
if (Logger.isAppDebugMode) {
Logger.getInstance().info(tag, msg);
}
}
public static warn(tag: string, msg: string): void {
if (Logger.isAppDebugMode) {
Logger.getInstance().warn(tag, msg);
}
}
public static error(tag: string, msg: string): void {
if (Logger.isAppDebugMode) {
Logger.getInstance().error(tag, msg);
}
}
private static logger: ILogger;
private constructor() {
}
public static getInstance(): Logger {
if (!Logger.logger) {
Logger.logger = Logger.useConsoleLogger
? new ConsoleLogger(Logger.appIdentifier)
: new HiLogger(Logger.appIdentifier);
}
return Logger.logger;
}
public verbose(tag: string, msg: string): void {
Logger.logger.verbose(tag, msg);
}
public debug(tag: string, msg: string): void {
Logger.debug(tag, msg);
}
public info(tag: string, msg: string): void {
Logger.info(tag, msg);
}
public warn(tag: string, msg: string): void {
Logger.warn(tag, msg);
}
public error(tag: string, msg: string): void {
Logger.error(tag, msg);
}
}

View File

@ -1,5 +1,6 @@
{
"src": [
"pages/Index"
"pages/Index",
"pages/TodoPage"
]
}

View File

@ -9,5 +9,5 @@
},
"devDependencies": {
"@ohos/hypium": "1.0.6"
}
},
}