Skip to content

Commit

Permalink
fix(database): post schema & its relations with user
Browse files Browse the repository at this point in the history
  • Loading branch information
Chilfish committed Feb 26, 2024
1 parent 6171110 commit e7def99
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 31 deletions.
Binary file modified apps/desktop/weibo-data.db
Binary file not shown.
3 changes: 2 additions & 1 deletion packages/database/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"typecheck": "tsc --noEmit -p ./tsconfig.json",
"sqlite:gen": "drizzle-kit generate:sqlite",
"sqlite:up": "drizzle-kit up:sqlite",
"sqlite:push": "pnpm rebuild && drizzle-kit push:sqlite"
"sqlite:push": "pnpm rebuild && drizzle-kit push:sqlite",
"studio": "pnpm rebuild && drizzle-kit studio"
},
"dependencies": {
"better-sqlite3": "^9.4.3",
Expand Down
12 changes: 3 additions & 9 deletions packages/database/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@ import { type BetterSQLite3Database, drizzle } from 'drizzle-orm/better-sqlite3'
import Database from 'better-sqlite3'
import fs from 'fs-extra'

import { postTable, userTable } from './schema'
import * as schema from './schema'

export * from './schema'
export * from './query'
export * from './shared'

export type DB = BetterSQLite3Database<{
user: typeof userTable
post: typeof postTable
}>
export type DB = BetterSQLite3Database<typeof schema>

export function createDatabase(path: string) {
try {
Expand All @@ -20,10 +17,7 @@ export function createDatabase(path: string) {

const sqlite = new Database(path)
const db = drizzle(sqlite, {
schema: {
user: userTable,
post: postTable,
},
schema,
})

return db
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ CREATE TABLE `posts` (
`repost` text,
`repost_text` text,
`card` text,
`comments` text DEFAULT '[]' NOT NULL,
`comments` text,
FOREIGN KEY (`uid`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
Expand Down
7 changes: 3 additions & 4 deletions packages/database/src/migrations/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"version": "5",
"dialect": "sqlite",
"id": "66dee71c-70f5-4a01-b464-3ebfc802ea00",
"id": "8a9f7f39-3e7f-4cb1-b62d-f0d5ff03b2ec",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"posts": {
Expand Down Expand Up @@ -109,9 +109,8 @@
"name": "comments",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
"notNull": false,
"autoincrement": false
}
},
"indexes": {
Expand Down
4 changes: 2 additions & 2 deletions packages/database/src/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
{
"idx": 0,
"version": "5",
"when": 1708868893884,
"tag": "0000_lucky_medusa",
"when": 1708925772706,
"tag": "0000_abnormal_adam_warlock",
"breakpoints": true
}
]
Expand Down
39 changes: 30 additions & 9 deletions packages/database/src/query.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { count, eq, like, or } from 'drizzle-orm'
import { postTable, userTable } from './schema'
import type { DB, DBMethods, PostTable, UserTable } from './index'
import type { DB, DBMethods, PostTableInsert, UserTable } from './index'

export class DBQuery implements DBMethods {
constructor(readonly db: DB) {}
Expand All @@ -10,7 +10,7 @@ export class DBQuery implements DBMethods {
}

async getUserById(id: number) {
return await this.db.query.user.findFirst({ where: eq(userTable.id, id) })
return await this.db.query.userTable.findFirst({ where: eq(userTable.id, id) })
}

async addUser(newUser: UserTable) {
Expand All @@ -19,9 +19,12 @@ export class DBQuery implements DBMethods {
}

async getPosts(page: number, pageSize: number) {
return await this.db.query.post.findMany({
return await this.db.query.postTable.findMany({
limit: pageSize,
offset: (page - 1) * pageSize,
with: {
user: true,
},
})
}

Expand All @@ -31,25 +34,43 @@ export class DBQuery implements DBMethods {
}

async getAllPosts() {
return await this.db.query.post.findMany()
return await this.db.query.postTable.findMany({
with: {
user: true,
},
})
}

async getPostById(id: number) {
return await this.db.query.post.findFirst({ where: eq(postTable.id, id) })
return await this.db.query.postTable.findFirst({
where: eq(postTable.id, id),
with: {
user: true,
},
})
}

async addPost(newPost: PostTable) {
const res = await this.db.insert(postTable).values(newPost).returning()
return res[0]
async addPost(newPost: PostTableInsert) {
try {
await this.db.insert(postTable).values(newPost)
return true
}
catch (e) {
console.error(`Failed to add post: ${e}`)
return false
}
}

async searchPost(text: string) {
return await this.db.query.post.findMany({
return await this.db.query.postTable.findMany({
where: or(
like(postTable.text, `%${text}%`),
like(postTable.card, `%${text}%`),
like(postTable.repostText, `%${text}%`),
),
with: {
user: true,
},
})
}
}
17 changes: 17 additions & 0 deletions packages/database/src/schema/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,19 @@
import { relations } from 'drizzle-orm'
import { userTable } from './user'
import { postTable } from './post'

// https://orm.drizzle.team/docs/rqb#include-relations

export const userRelations = relations(userTable, ({ many }) => ({
posts: many(postTable),
}))

export const postRelations = relations(postTable, ({ one }) => ({
user: one(userTable, {
fields: [postTable.uid],
references: [userTable.id],
}),
}))

export * from './post'
export * from './user'
10 changes: 7 additions & 3 deletions packages/database/src/schema/post.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
import type { CardInfo } from '@types'
import type { Comment } from '../shared'
import { userTable } from './user'
import { type UserTable, userTable } from './user'

export const postTable = sqliteTable('posts', {
id: integer('id').notNull().primaryKey({ autoIncrement: true }),
Expand All @@ -22,12 +22,16 @@ export const postTable = sqliteTable('posts', {
repost: text('repost', { mode: 'json' }).$type<any>(),
repostText: text('repost_text'), // for search
card: text('card', { mode: 'json' }).$type<CardInfo>(),
comments: text('comments', { mode: 'json' }).$type<any>().default('[]').notNull(),
comments: text('comments', { mode: 'json' }).$type<any>(),
})

type _PostTable = Omit<typeof postTable.$inferInsert, 'repost' | 'comments'>

export type PostTable = _PostTable & {
export type PostTableInsert = _PostTable & {
comments: Comment[]
repost: _PostTable
}

export type PostTable = Omit<PostTableInsert, 'uid'> & {
user: UserTable
}
4 changes: 2 additions & 2 deletions packages/database/src/shared.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { PostTable, UserTable } from './schema'
import type { PostTable, PostTableInsert, UserTable } from './schema'

export interface Comment {
id: number
Expand All @@ -25,6 +25,6 @@ export interface DBMethods {
getPosts: (page: number, pageSize: number,) => Promise<PostTable[]>
getAllPosts: () => Promise<PostTable[]>
getPostById: (id: number) => Promise<PostTable | undefined>
addPost: (newPost: PostTable) => Promise<PostTable>
addPost: (newPost: PostTableInsert) => Promise<boolean>
searchPost: (text: string) => Promise<PostTable[]>
}
6 changes: 6 additions & 0 deletions types/auto-imports.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ declare global {
const parsedData: typeof import('../packages/core/src/utils/parse')['parsedData']
const pausableWatch: typeof import('@vueuse/core')['pausableWatch']
const postFilter: typeof import('../packages/core/src/utils/parse')['postFilter']
const postRelations: typeof import('../packages/database/src/schema/index')['postRelations']
const postTable: typeof import('../packages/database/src/schema/post')['postTable']
const postsParser: typeof import('../packages/core/src/utils/parse')['postsParser']
const protocolMap: typeof import('../packages/core/src/utils/protocol')['protocolMap']
Expand Down Expand Up @@ -314,6 +315,7 @@ declare global {
const user: typeof import('../packages/database/src/schema/user')['user']
const userDetail: typeof import('../packages/core/src/services/userService')['userDetail']
const userInfo: typeof import('../packages/core/src/services/userService')['userInfo']
const userRelations: typeof import('../packages/database/src/schema/index')['userRelations']
const userTable: typeof import('../packages/database/src/schema/user')['userTable']
const waitForElement: typeof import('../packages/core/src/utils/dom')['waitForElement']
const watch: typeof import('vue')['watch']
Expand Down Expand Up @@ -434,6 +436,7 @@ declare module 'vue' {
readonly parsedData: UnwrapRef<typeof import('../packages/core/src/utils/parse')['parsedData']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly postFilter: UnwrapRef<typeof import('../packages/core/src/utils/parse')['postFilter']>
readonly postRelations: UnwrapRef<typeof import('../packages/database/src/schema/index')['postRelations']>
readonly postTable: UnwrapRef<typeof import('../packages/database/src/schema/post')['postTable']>
readonly postsParser: UnwrapRef<typeof import('../packages/core/src/utils/parse')['postsParser']>
readonly protocolMap: UnwrapRef<typeof import('../packages/core/src/utils/protocol')['protocolMap']>
Expand Down Expand Up @@ -650,6 +653,7 @@ declare module 'vue' {
readonly useWindowSize: UnwrapRef<typeof import('@vueuse/core')['useWindowSize']>
readonly userDetail: UnwrapRef<typeof import('../packages/core/src/services/userService')['userDetail']>
readonly userInfo: UnwrapRef<typeof import('../packages/core/src/services/userService')['userInfo']>
readonly userRelations: UnwrapRef<typeof import('../packages/database/src/schema/index')['userRelations']>
readonly userTable: UnwrapRef<typeof import('../packages/database/src/schema/user')['userTable']>
readonly waitForElement: UnwrapRef<typeof import('../packages/core/src/utils/dom')['waitForElement']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
Expand Down Expand Up @@ -763,6 +767,7 @@ declare module '@vue/runtime-core' {
readonly parsedData: UnwrapRef<typeof import('../packages/core/src/utils/parse')['parsedData']>
readonly pausableWatch: UnwrapRef<typeof import('@vueuse/core')['pausableWatch']>
readonly postFilter: UnwrapRef<typeof import('../packages/core/src/utils/parse')['postFilter']>
readonly postRelations: UnwrapRef<typeof import('../packages/database/src/schema/index')['postRelations']>
readonly postTable: UnwrapRef<typeof import('../packages/database/src/schema/post')['postTable']>
readonly postsParser: UnwrapRef<typeof import('../packages/core/src/utils/parse')['postsParser']>
readonly protocolMap: UnwrapRef<typeof import('../packages/core/src/utils/protocol')['protocolMap']>
Expand Down Expand Up @@ -979,6 +984,7 @@ declare module '@vue/runtime-core' {
readonly useWindowSize: UnwrapRef<typeof import('@vueuse/core')['useWindowSize']>
readonly userDetail: UnwrapRef<typeof import('../packages/core/src/services/userService')['userDetail']>
readonly userInfo: UnwrapRef<typeof import('../packages/core/src/services/userService')['userInfo']>
readonly userRelations: UnwrapRef<typeof import('../packages/database/src/schema/index')['userRelations']>
readonly userTable: UnwrapRef<typeof import('../packages/database/src/schema/user')['userTable']>
readonly waitForElement: UnwrapRef<typeof import('../packages/core/src/utils/dom')['waitForElement']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
Expand Down

0 comments on commit e7def99

Please sign in to comment.