Merge branch 'feature/m2-db-foundation' - M2 DB foundation (SQL wrapper, migrator, schema, tests)

This commit is contained in:
Ken Yasue
2026-06-25 00:21:37 +02:00
9 changed files with 1172 additions and 17 deletions

View File

@ -0,0 +1,257 @@
-- 001_initial.sql
-- シンプルグループウェア 初期スキーマ
-- 全16テーブル + インデックス
-- 1. users: システム利用ユーザー
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password_hash TEXT,
avatar_url TEXT,
role TEXT NOT NULL DEFAULT 'member',
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
-- 2. projects: プロジェクト
CREATE TABLE projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL DEFAULT 'active',
owner_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (owner_id) REFERENCES users(id)
);
-- 3. project_members: プロジェクトメンバー
CREATE TABLE project_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
joined_at TEXT NOT NULL,
UNIQUE(project_id, user_id),
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
-- 4. board_threads: 掲示板スレッド
CREATE TABLE board_threads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
body_md TEXT NOT NULL,
author_id INTEGER NOT NULL,
category TEXT,
is_pinned INTEGER NOT NULL DEFAULT 0,
is_important INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- 5. board_comments: 掲示板コメント
CREATE TABLE board_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
thread_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
body_md TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (thread_id) REFERENCES board_threads(id) ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- 6. chat_messages: チャットメッセージ
CREATE TABLE chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
body TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (author_id) REFERENCES users(id)
);
-- 7. todo_columns: ToDoカラム
CREATE TABLE todo_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
name TEXT NOT NULL,
order_index INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
);
-- 8. todo_items: ToDoタスク
CREATE TABLE todo_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
column_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
assignee_id INTEGER,
creator_id INTEGER NOT NULL,
priority TEXT NOT NULL DEFAULT 'normal',
start_date TEXT,
due_date TEXT,
completed_at TEXT,
order_index INTEGER NOT NULL DEFAULT 0,
milestone_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (column_id) REFERENCES todo_columns(id) ON DELETE CASCADE,
FOREIGN KEY (assignee_id) REFERENCES users(id),
FOREIGN KEY (creator_id) REFERENCES users(id)
);
-- 9. file_assets: ファイルアセット
CREATE TABLE file_assets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
uploader_id INTEGER NOT NULL,
filename TEXT NOT NULL,
original_name TEXT NOT NULL,
mime_type TEXT NOT NULL,
size INTEGER NOT NULL,
path TEXT NOT NULL,
created_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (uploader_id) REFERENCES users(id)
);
-- 10. project_notes: Markdownメモ
CREATE TABLE project_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
body_md TEXT NOT NULL,
tags TEXT,
is_pinned INTEGER NOT NULL DEFAULT 0,
created_by_id INTEGER NOT NULL,
updated_by_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES users(id),
FOREIGN KEY (updated_by_id) REFERENCES users(id)
);
CREATE INDEX idx_project_notes_project_id ON project_notes(project_id);
CREATE INDEX idx_project_notes_updated_at ON project_notes(updated_at);
-- 11. milestones: マイルストーン
CREATE TABLE milestones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
due_date TEXT,
status TEXT NOT NULL DEFAULT 'open',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
);
-- 12. calendar_events: カレンダーイベント
CREATE TABLE calendar_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
type TEXT NOT NULL,
start_at TEXT NOT NULL,
end_at TEXT,
created_by_id INTEGER NOT NULL,
related_todo_id INTEGER,
related_milestone_id INTEGER,
related_meeting_id INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES users(id)
);
-- 13. meetings: ミーティング
CREATE TABLE meetings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
title TEXT NOT NULL,
description TEXT,
location TEXT,
meeting_url TEXT,
start_at TEXT NOT NULL,
end_at TEXT NOT NULL,
agenda_md TEXT,
minutes_md TEXT,
created_by_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES users(id)
);
-- 14. meeting_members: ミーティング参加メンバー
CREATE TABLE meeting_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meeting_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'invited',
UNIQUE(meeting_id, user_id),
FOREIGN KEY (meeting_id) REFERENCES meetings(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- 15. notifications: 通知
CREATE TABLE notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
project_id INTEGER,
type TEXT NOT NULL,
title TEXT NOT NULL,
body TEXT,
read_at TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
);
-- 16. activity_logs: アクティビティログ
CREATE TABLE activity_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL,
actor_id INTEGER NOT NULL,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id INTEGER,
metadata_json TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
FOREIGN KEY (actor_id) REFERENCES users(id)
);
CREATE INDEX idx_activity_logs_project_id ON activity_logs(project_id);
CREATE INDEX idx_activity_logs_created_at ON activity_logs(created_at);
CREATE INDEX idx_notifications_user_id ON notifications(user_id);
CREATE INDEX idx_chat_messages_project_id ON chat_messages(project_id);
CREATE INDEX idx_board_threads_project_id ON board_threads(project_id);
CREATE INDEX idx_todo_items_project_id ON todo_items(project_id);
CREATE INDEX idx_meetings_project_id ON meetings(project_id);
CREATE INDEX idx_calendar_events_project_id ON calendar_events(project_id);

68
lib/db/migrator.ts Normal file
View File

@ -0,0 +1,68 @@
import fs from 'node:fs';
import path from 'node:path';
import { SqliteDatabase } from './sqlite';
/**
* SQLファイルベースのMigration機構。
* - Migrationファイルをファイル名順に実行する
* - 実行済みファイルは再実行しない
* - 1ファイルごとにトランザクションを張り、失敗時はロールバックする
*/
export class Migrator {
constructor(
private readonly db: SqliteDatabase,
private readonly migrationsDir: string
) {}
/**
* 未適用のMigrationをファイル名順に実行する
*/
migrate(): void {
this.ensureMigrationsTable();
const applied = this.db.query<{ filename: string }>(
'SELECT filename FROM schema_migrations'
);
const appliedSet = new Set(applied.map((x) => x.filename));
const files = fs
.readdirSync(this.migrationsDir)
.filter((file) => file.endsWith('.sql'))
.sort();
for (const file of files) {
if (appliedSet.has(file)) continue;
const fullPath = path.join(this.migrationsDir, file);
const sql = fs.readFileSync(fullPath, 'utf-8');
this.db.transaction(() => {
this.db.exec(sql);
this.db.execute(
`INSERT INTO schema_migrations (filename, applied_at) VALUES (@filename, @appliedAt)`,
{ filename: file, appliedAt: new Date().toISOString() }
);
});
}
}
/**
* 適用済みMigration一覧を取得する
*/
getAppliedMigrations(): { filename: string; applied_at: string }[] {
this.ensureMigrationsTable();
return this.db.query<{ filename: string; applied_at: string }>(
'SELECT filename, applied_at FROM schema_migrations ORDER BY filename'
);
}
private ensureMigrationsTable(): void {
this.db.execute(`
CREATE TABLE IF NOT EXISTS schema_migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL UNIQUE,
applied_at TEXT NOT NULL
)
`);
}
}

26
lib/db/run-migrations.ts Normal file
View File

@ -0,0 +1,26 @@
import path from 'node:path';
import fs from 'node:fs';
import { getDb, resetDbInstance } from './sqlite';
import { Migrator } from './migrator';
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
const dbDir = path.dirname(dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
const db = getDb();
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
const applied = migrator.getAppliedMigrations();
console.log(`Migrations applied: ${applied.length}`);
for (const m of applied) {
console.log(` - ${m.filename} (applied at ${m.applied_at})`);
}
db.close();
resetDbInstance();

98
lib/db/sqlite.ts Normal file
View File

@ -0,0 +1,98 @@
import Database from 'better-sqlite3';
export type SqlParams = Record<string, unknown> | unknown[];
export interface ExecuteResult {
changes: number;
lastInsertRowid: number | bigint;
}
/**
* SQLiteへのアクセスを一元管理する共通SQLラッパー。
* 各Repositoryは直接better-sqlite3を触らず、必ずこのクラスを通してSQLを実行する。
*/
export class SqliteDatabase {
private db: Database.Database;
constructor(dbPath: string) {
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('foreign_keys = ON');
}
/**
* 複数行を取得するSELECT
*/
query<T>(sql: string, params?: SqlParams): T[] {
return this.db.prepare(sql).all(params ?? {}) as T[];
}
/**
* 単一行を取得するSELECT該当なしの場合はnull
*/
get<T>(sql: string, params?: SqlParams): T | null {
const row = this.db.prepare(sql).get(params ?? {}) as T | undefined;
return row ?? null;
}
/**
* INSERT / UPDATE / DELETEを実行する単一プリペアドステートメント
*/
execute(sql: string, params?: SqlParams): ExecuteResult {
const result = this.db.prepare(sql).run(params ?? {});
return {
changes: result.changes,
lastInsertRowid: result.lastInsertRowid,
};
}
/**
* 複数ステートメントを含むSQLを一括実行するMigration用・パラメータバインド不可
* better-sqlite3の exec() を利用し、セミコロン区切りの複数文・コメントを処理する。
*/
exec(sql: string): void {
this.db.exec(sql);
}
/**
* トランザクション内でコールバックを実行する
*/
transaction<T>(callback: () => T): T {
const tx = this.db.transaction(callback);
return tx();
}
/**
* DB接続を閉じる
*/
close(): void {
this.db.close();
}
}
let instance: SqliteDatabase | null = null;
/**
* シングルトンのDB接続を取得する。
* dbPathは process.env.SQLITE_PATH ?? "./data/app.db"
*/
export function getDb(): SqliteDatabase {
if (!instance) {
const dbPath = process.env.SQLITE_PATH ?? './data/app.db';
instance = new SqliteDatabase(dbPath);
}
return instance;
}
/**
* テスト用途: シングルトンインスタンスをリセットする
*/
export function resetDbInstance(): void {
if (instance) {
instance.close();
instance = null;
}
}

241
lib/types/index.ts Normal file
View File

@ -0,0 +1,241 @@
/**
* 全Entity型定義・共有型
* functional-design.md のデータモデルに対応。
* タイムスタンプはISO8601文字列(TEXT)。真偽値はINTEGER(0/1)。
*/
// ===== 列挙型 =====
export type UserRole = 'system_admin' | 'project_admin' | 'member' | 'guest';
export type UserStatus = 'active' | 'inactive';
export type ProjectStatus = 'active' | 'on_hold' | 'completed' | 'archived';
export type ProjectMemberRole = 'admin' | 'member' | 'guest';
export type BoardCategory =
| 'notice'
| 'spec'
| 'minutes'
| 'question'
| 'decision'
| 'trouble'
| 'memo';
export type TodoPriority = 'low' | 'normal' | 'high';
export type MilestoneStatus = 'open' | 'closed';
export type CalendarEventType =
| 'meeting'
| 'deadline'
| 'milestone'
| 'todo'
| 'reminder'
| 'custom';
export type MeetingMemberStatus = 'invited' | 'accepted' | 'declined';
export type NotificationType =
| 'mention'
| 'todo_assigned'
| 'todo_due_soon'
| 'meeting_invited'
| 'board_commented'
| 'project_added'
| 'file_shared'
| 'note_updated';
// ===== エンティティ =====
export interface User {
id: number;
name: string;
email: string;
passwordHash: string | null;
avatarUrl: string | null;
role: UserRole;
status: UserStatus;
createdAt: string;
updatedAt: string;
}
export interface Project {
id: number;
name: string;
description: string | null;
status: ProjectStatus;
ownerId: number;
createdAt: string;
updatedAt: string;
}
export interface ProjectMember {
id: number;
projectId: number;
userId: number;
role: ProjectMemberRole;
joinedAt: string;
}
export interface BoardThread {
id: number;
projectId: number;
title: string;
bodyMd: string;
authorId: number;
category: BoardCategory | null;
isPinned: number;
isImportant: number;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface BoardComment {
id: number;
threadId: number;
authorId: number;
bodyMd: string;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface ChatMessage {
id: number;
projectId: number;
authorId: number;
body: string;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface TodoColumn {
id: number;
projectId: number;
name: string;
orderIndex: number;
createdAt: string;
updatedAt: string;
}
export interface TodoItem {
id: number;
projectId: number;
columnId: number;
title: string;
description: string | null;
assigneeId: number | null;
creatorId: number;
priority: TodoPriority;
startDate: string | null;
dueDate: string | null;
completedAt: string | null;
orderIndex: number;
milestoneId: number | null;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface FileAsset {
id: number;
projectId: number;
uploaderId: number;
filename: string;
originalName: string;
mimeType: string;
size: number;
path: string;
createdAt: string;
deletedAt: string | null;
}
export interface ProjectNote {
id: number;
projectId: number;
title: string;
bodyMd: string;
tags: string | null;
isPinned: number;
createdById: number;
updatedById: number;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface Milestone {
id: number;
projectId: number;
title: string;
description: string | null;
dueDate: string | null;
status: MilestoneStatus;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface CalendarEvent {
id: number;
projectId: number;
title: string;
description: string | null;
type: CalendarEventType;
startAt: string;
endAt: string | null;
createdById: number;
relatedTodoId: number | null;
relatedMilestoneId: number | null;
relatedMeetingId: number | null;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface Meeting {
id: number;
projectId: number;
title: string;
description: string | null;
location: string | null;
meetingUrl: string | null;
startAt: string;
endAt: string;
agendaMd: string | null;
minutesMd: string | null;
createdById: number;
createdAt: string;
updatedAt: string;
deletedAt: string | null;
}
export interface MeetingMember {
id: number;
meetingId: number;
userId: number;
status: MeetingMemberStatus;
}
export interface Notification {
id: number;
userId: number;
projectId: number | null;
type: NotificationType;
title: string;
body: string | null;
readAt: string | null;
createdAt: string;
}
export interface ActivityLog {
id: number;
projectId: number;
actorId: number;
action: string;
targetType: string;
targetId: number | null;
metadataJson: string | null;
createdAt: string;
}
export interface SchemaMigration {
id: number;
filename: string;
appliedAt: string;
}

17
package-lock.json generated
View File

@ -133,7 +133,6 @@
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.1",
"tslib": "^2.4.0"
@ -145,7 +144,6 @@
"integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
@ -1643,7 +1641,6 @@
"integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"playwright": "1.61.1"
},
@ -2142,7 +2139,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@ -2208,7 +2204,6 @@
"integrity": "sha512-dzHeT2gySzZtLDsuqxU9AkYgIsQoHAHtRBpOqM+Ofzx1Bwrd2RcCjQJ+6iQbsHOIR6NS33bF2W1k3blN1zLDrA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.62.0",
"@typescript-eslint/types": "8.62.0",
@ -2913,7 +2908,6 @@
"integrity": "sha512-izzd2zmnk8Nl5ECYkW27328RbQ1nKvkm6Bb5DAaz1Gk59EbLkiCMa6OLT0NoaAYTjOFS6N+SMYW1nh4/9ljPiw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@vitest/utils": "2.1.9",
"fflate": "^0.8.2",
@ -2957,7 +2951,6 @@
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@ -3524,7 +3517,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.10.38",
"caniuse-lite": "^1.0.30001799",
@ -4511,7 +4503,6 @@
"integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@ -6497,7 +6488,6 @@
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"jiti": "bin/jiti.js"
}
@ -8637,7 +8627,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.12",
"picocolors": "^1.1.1",
@ -8948,7 +8937,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
"integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@ -8958,7 +8946,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
"integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@ -10540,7 +10527,6 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@ -10672,7 +10658,6 @@
"integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "~0.28.0"
},
@ -10810,7 +10795,6 @@
"integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@ -11603,7 +11587,6 @@
"integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@vitest/expect": "2.1.9",
"@vitest/mocker": "2.1.9",

45
tests/helpers/db.ts Normal file
View File

@ -0,0 +1,45 @@
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { SqliteDatabase } from '@/lib/db/sqlite';
import { Migrator } from '@/lib/db/migrator';
let counter = 0;
/**
* テスト用の一時SQLite DBを作成する。
* 実DB(一時ファイル)を使用し、テスト終了時に自動削除される。
*/
export function createTestDb(): SqliteDatabase {
const tmpDir = os.tmpdir();
const dbPath = path.join(
tmpDir,
`test-${process.pid}-${Date.now()}-${counter++}.db`
);
const db = new SqliteDatabase(dbPath);
const originalClose = db.close.bind(db);
db.close = () => {
originalClose();
if (fs.existsSync(dbPath)) {
fs.unlinkSync(dbPath);
}
const walPath = `${dbPath}-wal`;
const shmPath = `${dbPath}-shm`;
if (fs.existsSync(walPath)) fs.unlinkSync(walPath);
if (fs.existsSync(shmPath)) fs.unlinkSync(shmPath);
};
return db;
}
/**
* マイグレーション済みのテスト用DBを作成する
*/
export function createMigratedTestDb(): SqliteDatabase {
const db = createTestDb();
const migrationsDir = path.join(process.cwd(), 'lib', 'db', 'migrations');
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
return db;
}

View File

@ -0,0 +1,185 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createTestDb } from '@/tests/helpers/db';
import { Migrator } from '@/lib/db/migrator';
import { SqliteDatabase } from '@/lib/db/sqlite';
function createTempMigrationsDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'migrations-'));
}
function writeMigration(dir: string, filename: string, sql: string): void {
fs.writeFileSync(path.join(dir, filename), sql, 'utf-8');
}
describe('Migrator', () => {
let db: SqliteDatabase;
let migrationsDir: string;
beforeEach(() => {
db = createTestDb();
migrationsDir = createTempMigrationsDir();
});
afterEach(() => {
db.close();
fs.rmSync(migrationsDir, { recursive: true, force: true });
});
it('creates the schema_migrations table', () => {
writeMigration(
migrationsDir,
'001_init.sql',
'CREATE TABLE sample (id INTEGER);'
);
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
const row = db.get<{ name: string }>(
"SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations'"
);
expect(row?.name).toBe('schema_migrations');
});
it('applies migration files in filename order', () => {
writeMigration(
migrationsDir,
'002_second.sql',
'CREATE TABLE second (id INTEGER);'
);
writeMigration(
migrationsDir,
'001_first.sql',
'CREATE TABLE first (id INTEGER);'
);
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
const applied = migrator.getAppliedMigrations();
expect(applied.map((m) => m.filename)).toEqual([
'001_first.sql',
'002_second.sql',
]);
expect(
db.get<{ name: string }>(
"SELECT name FROM sqlite_master WHERE name='first'"
)
).not.toBeNull();
expect(
db.get<{ name: string }>(
"SELECT name FROM sqlite_master WHERE name='second'"
)
).not.toBeNull();
});
it('skips already-applied migrations on subsequent runs', () => {
writeMigration(
migrationsDir,
'001_init.sql',
'CREATE TABLE sample (id INTEGER);'
);
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
expect(migrator.getAppliedMigrations()).toHaveLength(1);
expect(() => migrator.migrate()).not.toThrow();
expect(migrator.getAppliedMigrations()).toHaveLength(1);
});
it('rolls back and does not record a migration when its SQL fails', () => {
writeMigration(
migrationsDir,
'001_bad.sql',
'CREATE TABLE will_exist (id INTEGER); NOT A VALID STATEMENT;'
);
const migrator = new Migrator(db, migrationsDir);
expect(() => migrator.migrate()).toThrow();
expect(migrator.getAppliedMigrations()).toHaveLength(0);
expect(
db.get<{ name: string }>(
"SELECT name FROM sqlite_master WHERE name='will_exist'"
)
).toBeNull();
});
it('returns applied migrations ordered by filename', () => {
writeMigration(migrationsDir, '001_a.sql', 'CREATE TABLE a (id INTEGER);');
writeMigration(migrationsDir, '002_b.sql', 'CREATE TABLE b (id INTEGER);');
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
const applied = migrator.getAppliedMigrations();
expect(applied).toHaveLength(2);
expect(applied[0].filename).toBe('001_a.sql');
expect(applied[1].filename).toBe('002_b.sql');
expect(applied[0].applied_at).toBeTruthy();
});
it('only reads .sql files in the migrations directory', () => {
writeMigration(
migrationsDir,
'001_real.sql',
'CREATE TABLE real_t (id INTEGER);'
);
fs.writeFileSync(path.join(migrationsDir, 'README.md'), 'not a migration');
const migrator = new Migrator(db, migrationsDir);
migrator.migrate();
expect(migrator.getAppliedMigrations().map((m) => m.filename)).toEqual([
'001_real.sql',
]);
});
it('applies the real 001_initial.sql and creates all core tables', () => {
const realMigrationsDir = path.join(
process.cwd(),
'lib',
'db',
'migrations'
);
const migrator = new Migrator(db, realMigrationsDir);
migrator.migrate();
const tables = db
.query<{
name: string;
}>("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
.map((t) => t.name);
const expectedTables = [
'activity_logs',
'board_comments',
'board_threads',
'calendar_events',
'chat_messages',
'file_assets',
'meeting_members',
'meetings',
'milestones',
'notifications',
'project_members',
'project_notes',
'projects',
'schema_migrations',
'todo_columns',
'todo_items',
'users',
];
for (const table of expectedTables) {
expect(tables).toContain(table);
}
expect(migrator.getAppliedMigrations().map((m) => m.filename)).toEqual([
'001_initial.sql',
]);
});
});

View File

@ -0,0 +1,252 @@
import { describe, it, expect, afterEach } from 'vitest';
import { createTestDb } from '@/tests/helpers/db';
import { SqliteDatabase } from '@/lib/db/sqlite';
describe('SqliteDatabase', () => {
let db: SqliteDatabase;
afterEach(() => {
if (db) db.close();
});
describe('constructor', () => {
it('enables WAL journal mode', () => {
db = createTestDb();
const row = db.get<{ journal_mode: string }>('PRAGMA journal_mode');
expect(row?.journal_mode).toBe('wal');
});
it('enables foreign key constraints', () => {
db = createTestDb();
const row = db.get<{ foreign_keys: number }>('PRAGMA foreign_keys');
expect(row?.foreign_keys).toBe(1);
});
});
describe('query', () => {
it('returns multiple rows', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
db.execute("INSERT INTO items (name) VALUES ('a')");
db.execute("INSERT INTO items (name) VALUES ('b')");
const rows = db.query<{ id: number; name: string }>(
'SELECT * FROM items ORDER BY id'
);
expect(rows).toHaveLength(2);
expect(rows[0].name).toBe('a');
expect(rows[1].name).toBe('b');
});
it('returns an empty array when no rows match', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
const rows = db.query<{ id: number }>('SELECT * FROM items');
expect(rows).toEqual([]);
});
it('binds named parameters', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
db.execute("INSERT INTO items (name) VALUES ('target')");
db.execute("INSERT INTO items (name) VALUES ('other')");
const rows = db.query<{ name: string }>(
'SELECT * FROM items WHERE name = @name',
{ name: 'target' }
);
expect(rows).toHaveLength(1);
expect(rows[0].name).toBe('target');
});
});
describe('get', () => {
it('returns a single row when found', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
const { lastInsertRowid } = db.execute(
"INSERT INTO items (name) VALUES ('x')"
);
const row = db.get<{ id: number; name: string }>(
'SELECT * FROM items WHERE id = @id',
{ id: Number(lastInsertRowid) }
);
expect(row).not.toBeNull();
expect(row?.name).toBe('x');
});
it('returns null when no row is found', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
const row = db.get<{ id: number }>('SELECT * FROM items WHERE id = @id', {
id: 999,
});
expect(row).toBeNull();
});
});
describe('execute', () => {
it('returns changes and lastInsertRowid for an insert', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
const result = db.execute("INSERT INTO items (name) VALUES ('a')");
expect(result.changes).toBe(1);
expect(Number(result.lastInsertRowid)).toBeGreaterThan(0);
});
it('returns the number of affected rows for an update', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
db.execute("INSERT INTO items (name) VALUES ('a')");
db.execute("INSERT INTO items (name) VALUES ('b')");
const result = db.execute(
'UPDATE items SET name = @name WHERE name = @old',
{ name: 'updated', old: 'a' }
);
expect(result.changes).toBe(1);
});
it('returns the number of deleted rows for a delete', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
db.execute("INSERT INTO items (name) VALUES ('a')");
const result = db.execute('DELETE FROM items WHERE name = @name', {
name: 'a',
});
expect(result.changes).toBe(1);
});
});
describe('exec', () => {
it('executes multiple semicolon-separated statements', () => {
db = createTestDb();
db.exec(`
CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE b (id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
INSERT INTO a (name) VALUES ('first');
INSERT INTO b (value) VALUES (42);
`);
expect(db.get<{ name: string }>('SELECT name FROM a')?.name).toBe(
'first'
);
expect(db.get<{ value: number }>('SELECT value FROM b')?.value).toBe(42);
});
it('handles SQL comments alongside statements', () => {
db = createTestDb();
db.exec(`
-- this is a comment
CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
/* multi-line
comment */
INSERT INTO items (name) VALUES ('x');
`);
expect(db.query<{ name: string }>('SELECT name FROM items')).toHaveLength(
1
);
});
});
describe('transaction', () => {
it('commits changes when the callback succeeds', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
db.transaction(() => {
db.execute("INSERT INTO items (name) VALUES ('a')");
db.execute("INSERT INTO items (name) VALUES ('b')");
});
const rows = db.query<{ name: string }>(
'SELECT * FROM items ORDER BY id'
);
expect(rows).toHaveLength(2);
});
it('rolls back changes when the callback throws', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
expect(() =>
db.transaction(() => {
db.execute("INSERT INTO items (name) VALUES ('a')");
db.execute("INSERT INTO items (name) VALUES ('b')");
throw new Error('boom');
})
).toThrow('boom');
const rows = db.query<{ name: string }>('SELECT * FROM items');
expect(rows).toHaveLength(0);
});
it('returns the callback value', () => {
db = createTestDb();
db.execute(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
const result = db.transaction(() => {
db.execute("INSERT INTO items (name) VALUES ('a')");
return 'committed';
});
expect(result).toBe('committed');
});
});
describe('foreign key enforcement', () => {
it('rejects inserts that violate a foreign key constraint', () => {
db = createTestDb();
db.execute(
'CREATE TABLE parents (id INTEGER PRIMARY KEY, name TEXT NOT NULL)'
);
db.execute(
'CREATE TABLE children (id INTEGER PRIMARY KEY, parent_id INTEGER NOT NULL, FOREIGN KEY (parent_id) REFERENCES parents(id))'
);
expect(() =>
db.execute('INSERT INTO children (parent_id) VALUES (@parentId)', {
parentId: 999,
})
).toThrow();
});
});
});