Skip to content

Commit

Permalink
feat: add new database table
Browse files Browse the repository at this point in the history
  • Loading branch information
ayangweb committed Mar 10, 2023
1 parent 404d391 commit 619a0e9
Show file tree
Hide file tree
Showing 14 changed files with 139 additions and 64 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package-lock.json*
yarn.lock*
pnpm-lock.yaml*
auto-import.d.ts
components.d.ts

node_modules
dist
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
]
},
"dependencies": {
"@iconify-json/carbon": "^1.1.16",
"@multiavatar/multiavatar": "^1.0.7",
"@tauri-apps/api": "^1.2.0",
"pinia": "^2.0.33",
Expand All @@ -28,6 +27,7 @@
"vue": "^3.2.45"
},
"devDependencies": {
"@arco-design/web-vue": "^2.44.1",
"@commitlint/cli": "^17.4.4",
"@commitlint/config-conventional": "^17.4.4",
"@kidonng/daisyui": "^2.51.3",
Expand All @@ -49,7 +49,8 @@
"unocss": "^0.50.4",
"unocss-preset-daisy": "^2.0.0",
"unplugin-auto-import": "^0.15.1",
"unplugin-vue-components": "^0.24.1",
"vite": "^4.0.0",
"vue-tsc": "^1.0.11"
}
}
}
34 changes: 18 additions & 16 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,40 @@
import { appWindow } from '@tauri-apps/api/window'
import Theme from './components/Theme/index.vue'
import Avatar from './components/Avatar/index.vue'
import { useThemeStore, useUuidStore } from '@/stores'
import { useThemeStore, useUuidStore, useRecordStore } from '@/stores'
import { initSQL } from '@/sqls'
const { themeClass } = storeToRefs(useThemeStore())
const { uuid } = storeToRefs(useUuidStore())
const borderClass = ref('border border-[var(--border-color)] border-solid')
const { recordList } = storeToRefs(useRecordStore())
onMounted(async () => {
initSQL()
// 监听窗口有无获取焦点
appWindow.onFocusChanged(({ payload }) => {
if (payload) {
borderClass.value = 'border border-[var(--border-color)] border-solid'
} else {
borderClass.value = ''
}
if (!payload) appWindow.minimize()
})
})
</script>

<template>
<div
class="app relative h-screen overflow-hidden rounded-xl"
:class="[themeClass, borderClass]"
class="app relative h-screen overflow-hidden rounded-xl border border-solid border-[var(--border-color)]"
:class="themeClass"
>
<Theme />

<!-- 内容区 -->
<div class="h-[calc(100%-48px)]" data-tauri-drag-region>
<Avatar />
<Avatar :value="uuid" />
</div>
<ul class="flex h-[calc(100%-48px)] flex-col gap-4 overflow-auto p-4">
<li
v-for="(item, index) of recordList"
:key="index"
data-tauri-drag-region
>
<Avatar :value="!(index % 2) ? uuid : undefined" />
</li>
</ul>

<!-- 输入框 -->
<div
Expand All @@ -44,9 +44,11 @@ onMounted(async () => {
<input
type="text"
placeholder="输入问题并回车..."
class="input input-ghost outline-0! border-0! bg-opacity-0! w-full"
class="input input-ghost outline-0! border-0! bg-opacity-0! pr-13! w-full"
/>
<div class=""></div>
<i
class="i-carbon-recently-viewed top-50% absolute right-3 h-6 w-6 -translate-y-1/2 cursor-pointer"
></i>
</div>
</div>
</template>
Expand Down
9 changes: 3 additions & 6 deletions src/components/Theme/index.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { useThemeStore } from '@/stores'
import { APP_THEME } from '@/constants'
import { THEME } from '@/constants'
const { themeMode } = storeToRefs(useThemeStore())
</script>
Expand All @@ -9,11 +9,8 @@ const { themeMode } = storeToRefs(useThemeStore())
<label class="swap swap-rotate fixed! top-4 right-4">
<input
type="checkbox"
:checked="themeMode === APP_THEME.light"
@click="
themeMode =
themeMode === APP_THEME.light ? APP_THEME.dark : APP_THEME.light
"
:checked="themeMode === THEME.light"
@click="themeMode = themeMode === THEME.light ? THEME.dark : THEME.light"
/>

<i class="swap-on i-carbon-moon text-7"></i>
Expand Down
2 changes: 1 addition & 1 deletion src/constants/shared.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export enum APP_THEME {
export enum THEME {
light = 'light',
dark = 'dark'
}
71 changes: 56 additions & 15 deletions src/sqls/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { configDir } from '@tauri-apps/api/path'
import Database from 'tauri-plugin-sql-api'
import { dialogErrorMessage } from '@/utils'
import type { HistoryRecord, RecordData } from '@/types'
import { isString, isObject } from '@/utils'
import type { TableName, TablePayload } from '@/types'

const dbFile = import.meta.env.DEV ? 'sql.dev.db' : 'sql.db'
const db = await Database.load(
`sqlite:${await configDir()}/${import.meta.env.VITE_APP_NAME}/${dbFile}`
)
const tableName = 'history'

/**
* 执行 sql 语句
Expand All @@ -23,6 +23,8 @@ export const executeSQL = async (sql: string) => {
await db.execute(sql)
}
} catch (error) {
console.log('error', error)

let action = '创建'

if (sliceSQL === 'SELECT') {
Expand All @@ -44,39 +46,77 @@ export const executeSQL = async (sql: string) => {
*/
export const initSQL = () => {
executeSQL(
`CREATE TABLE IF NOT EXISTS ${tableName} (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, data TEXT, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`
`
CREATE TABLE IF NOT EXISTS history (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, data TEXT, role_id INTEGER, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS role (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT);
CREATE TABLE IF NOT EXISTS credit (id INTEGER PRIMARY KEY AUTOINCREMENT, history_id INTEGER, token_cost INTEGER, api_key TEXT);
`
)
}

/**
* 查找的 sql 语句
* @param tableName 表名称
* @returns
*/
export const selectSQL = async () => {
return (await executeSQL(
`SELECT * FROM ${tableName} ORDER BY id;`
)) as HistoryRecord[]
export const selectSQL = async (tableName: TableName) => {
return (await executeSQL(`SELECT * FROM ${tableName} ORDER BY id;`)) as any[]
}

/**
* 添加的 sql 语句
* @param data 聊天内容
* @param tableName 表名称
* @param payload 添加的数据
*/
export const insertSQL = async (data: RecordData[]) => {
export const insertSQL = async (
tableName: TableName,
payload: TablePayload
) => {
const insertKeys = [],
insertValues = []

for (const key in payload) {
insertKeys.push(key)

let value = payload[key as keyof typeof payload]

if (isObject(value)) {
value = JSON.stringify(value)
}

insertValues.push(isString(value) ? `'${value}'` : value)
}

await executeSQL(
`INSERT INTO ${tableName} (data) VALUES ('${JSON.stringify(data)}');`
`INSERT INTO ${tableName} (${insertKeys.join()}) VALUES (${insertValues.join()});`
)
}

/**
* 更新的 sql 语句
* @param id 更新数据的 id
* @param title 聊天内容标题
* @param tableName 表名称
* @param payload 修改的数据
*/
export const updateSQL = async (id: number, payload: HistoryRecord) => {
export const updateSQL = async (
tableName: TableName,
payload: TablePayload
) => {
const id = payload.id

delete payload.id

const updateParams: string[] = []

for (const key in payload) {
updateParams.push(`${key}='${payload[key as keyof typeof payload]}'`)
let value = payload[key as keyof typeof payload]

if (isObject(value)) {
value = `'${JSON.stringify(value)}'`
} else if (isString(value)) {
value = `'${value}'`
}

updateParams.push(`${key}=${value}`)
}

await executeSQL(
Expand All @@ -86,9 +126,10 @@ export const updateSQL = async (id: number, payload: HistoryRecord) => {

/**
* 删除的 sql 语句
* @param tableName 表名称
* @param id 删除数据的 id
*/
export const deleteSQL = async (id?: number) => {
export const deleteSQL = async (tableName: TableName, id?: number) => {
if (id) {
await executeSQL(`DELETE FROM ${tableName} WHERE id=${id};`)
} else {
Expand Down
1 change: 1 addition & 0 deletions src/stores/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './theme'
export * from './uuid'
export * from './record'
16 changes: 8 additions & 8 deletions src/stores/record.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import { selectSQL, insertSQL, updateSQL, deleteSQL } from '@/sqls'
import type { HistoryRecord, RecordData } from '@/types'
import type { TablePayload, RecordData } from '@/types'

export const useRecordStore = defineStore('recordStore', () => {
const currentRecord = ref<number>()

const recordList = ref<HistoryRecord[]>([])
const recordList = ref<RecordData[]>([])

const getRecord = async () => {
recordList.value = await selectSQL()
recordList.value = await selectSQL('history')
}

const addRecord = async (data: RecordData[]) => {
await insertSQL(data)
const addRecord = async (payload: TablePayload) => {
await insertSQL('history', payload)

getRecord()
}

const updateRecord = async (id: number, payload: HistoryRecord) => {
await updateSQL(id, payload)
const updateRecord = async (payload: TablePayload) => {
await updateSQL('history', payload)

getRecord()
}

const deleteRecord = async (id?: number) => {
await deleteSQL(id)
await deleteSQL('history', id)

getRecord()
}
Expand Down
6 changes: 3 additions & 3 deletions src/stores/theme.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { APP_THEME } from '@/constants'
import { THEME } from '@/constants'

// @unocss-include
export const useThemeStore = defineStore(
'themeStore',
() => {
const themeMode = ref(APP_THEME.light)
const themeMode = ref(THEME.light)

const themeClass = computed(() =>
themeMode.value === APP_THEME.light ? 'bg-white/70' : 'bg-black/70'
themeMode.value === THEME.light ? 'bg-white/70' : 'bg-black/70'
)

watch(themeMode, (newTheme) => {
Expand Down
2 changes: 1 addition & 1 deletion src/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './shared'
export * from './sql'
11 changes: 0 additions & 11 deletions src/types/shared.d.ts

This file was deleted.

20 changes: 20 additions & 0 deletions src/types/sql.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
type Role = 'system' | 'user' | 'assistant'

export type TableName = 'history' | 'role' | 'credit'

export interface RecordData {
role: Role
content: string
}

export interface TablePayload {
id?: number
title?: string
data?: RecordData[]
time?: Date | number
name?: string
description?: string
history_id?: id
token_cost?: id
api_key?: id
}
12 changes: 12 additions & 0 deletions src/utils/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,15 @@
* @param value 数据
*/
export const isNil = (value: any) => value == null

/**
* 判断数据是否为字符串
* @param value 数据
*/
export const isString = (value: any) => typeof value === 'string'

/**
* 判断数据是否为对象
* @param value 数据
*/
export const isObject = (value: any) => typeof value === 'object'
13 changes: 12 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import Unocss from 'unocss/vite'
import { presetUno, presetIcons, transformerDirectives } from 'unocss'
import { presetDaisy } from 'unocss-preset-daisy'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ArcoResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig(async () => ({
plugins: [
Expand All @@ -17,7 +19,16 @@ export default defineConfig(async () => ({
eslintrc: {
enabled: false
},
imports: ['vue', 'pinia']
imports: ['vue', 'pinia'],
resolvers: [ArcoResolver()]
}),
Components({
dts: './src/types/components.d.ts',
resolvers: [
ArcoResolver({
sideEffect: true
})
]
})
],
resolve: {
Expand Down

0 comments on commit 619a0e9

Please sign in to comment.