mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-20 16:09:25 +02:00
chore(memoro): remove old NestJS backends (Phase 8+9)
Delete apps/memoro/apps/backend/ (NestJS) and apps/memoro/apps/audio-backend/ (NestJS) — all functionality has been ported to the new Hono/Bun servers (apps/server/ and apps/audio-server/). Also clean up root and memoro package.json scripts to remove references to the old @memoro/backend and @memoro/audio-backend packages. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
d097a9d8f0
commit
3fa218cbe0
430 changed files with 1190 additions and 35048 deletions
97
packages/cards-database/src/client.ts
Normal file
97
packages/cards-database/src/client.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as schema from './schema/index.js';
|
||||
|
||||
// Singleton instance for the database client
|
||||
let dbInstance: ReturnType<typeof drizzle<typeof schema>> | null = null;
|
||||
let pgClient: ReturnType<typeof postgres> | null = null;
|
||||
|
||||
/**
|
||||
* Get the database URL from environment variables
|
||||
*/
|
||||
function getDatabaseUrl(): string {
|
||||
const url = process.env.DATABASE_URL || process.env.MANADECK_DATABASE_URL;
|
||||
if (!url) {
|
||||
throw new Error(
|
||||
'Database URL not found. Set DATABASE_URL or MANADECK_DATABASE_URL environment variable.'
|
||||
);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new database client
|
||||
* Uses connection pooling with sensible defaults for serverless environments
|
||||
*/
|
||||
export function createClient(connectionString?: string) {
|
||||
const url = connectionString || getDatabaseUrl();
|
||||
|
||||
const client = postgres(url, {
|
||||
max: 10, // Maximum connections in the pool
|
||||
idle_timeout: 20, // Close idle connections after 20 seconds
|
||||
connect_timeout: 10, // Connection timeout in seconds
|
||||
prepare: false, // Disable prepared statements for serverless
|
||||
});
|
||||
|
||||
return drizzle(client, { schema });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the singleton database instance
|
||||
* Creates a new instance if one doesn't exist
|
||||
*/
|
||||
export function getDb() {
|
||||
if (!dbInstance) {
|
||||
const url = getDatabaseUrl();
|
||||
pgClient = postgres(url, {
|
||||
max: 10,
|
||||
idle_timeout: 20,
|
||||
connect_timeout: 10,
|
||||
prepare: false,
|
||||
});
|
||||
dbInstance = drizzle(pgClient, { schema });
|
||||
}
|
||||
return dbInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the database connection
|
||||
* Should be called when shutting down the application
|
||||
*/
|
||||
export async function closeDb() {
|
||||
if (pgClient) {
|
||||
await pgClient.end();
|
||||
pgClient = null;
|
||||
dbInstance = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Export the database type for typing purposes
|
||||
export type Database = ReturnType<typeof createClient>;
|
||||
|
||||
// Re-export commonly used Drizzle utilities
|
||||
export {
|
||||
eq,
|
||||
ne,
|
||||
gt,
|
||||
gte,
|
||||
lt,
|
||||
lte,
|
||||
and,
|
||||
or,
|
||||
not,
|
||||
inArray,
|
||||
notInArray,
|
||||
isNull,
|
||||
isNotNull,
|
||||
like,
|
||||
ilike,
|
||||
sql,
|
||||
asc,
|
||||
desc,
|
||||
count,
|
||||
sum,
|
||||
avg,
|
||||
min,
|
||||
max,
|
||||
} from 'drizzle-orm';
|
||||
34
packages/cards-database/src/index.ts
Normal file
34
packages/cards-database/src/index.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// Main entry point for @manacore/manadeck-database
|
||||
|
||||
// Export database client utilities
|
||||
export { createClient, getDb, closeDb, type Database } from './client.js';
|
||||
|
||||
// Export Drizzle utilities
|
||||
export {
|
||||
eq,
|
||||
ne,
|
||||
gt,
|
||||
gte,
|
||||
lt,
|
||||
lte,
|
||||
and,
|
||||
or,
|
||||
not,
|
||||
inArray,
|
||||
notInArray,
|
||||
isNull,
|
||||
isNotNull,
|
||||
like,
|
||||
ilike,
|
||||
sql,
|
||||
asc,
|
||||
desc,
|
||||
count,
|
||||
sum,
|
||||
avg,
|
||||
min,
|
||||
max,
|
||||
} from './client.js';
|
||||
|
||||
// Export all schemas and types
|
||||
export * from './schema/index.js';
|
||||
236
packages/cards-database/src/migrate-from-supabase.ts
Normal file
236
packages/cards-database/src/migrate-from-supabase.ts
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
/**
|
||||
* Migration script to move data from Supabase to the new PostgreSQL database
|
||||
*
|
||||
* Prerequisites:
|
||||
* 1. Set SUPABASE_URL and SUPABASE_SERVICE_KEY environment variables
|
||||
* 2. Set DATABASE_URL for the new PostgreSQL database
|
||||
* 3. Run migrations on the new database first: pnpm db:migrate
|
||||
*
|
||||
* Usage:
|
||||
* SUPABASE_URL=... SUPABASE_SERVICE_KEY=... DATABASE_URL=... tsx src/migrate-from-supabase.ts
|
||||
*/
|
||||
|
||||
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
|
||||
import { getDb, closeDb } from './client.js';
|
||||
import {
|
||||
decks,
|
||||
cards,
|
||||
studySessions,
|
||||
cardProgress,
|
||||
deckTemplates,
|
||||
aiGenerations,
|
||||
userStats,
|
||||
} from './schema/index.js';
|
||||
|
||||
// Initialize Supabase client
|
||||
const supabaseUrl = process.env.SUPABASE_URL;
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY;
|
||||
|
||||
if (!supabaseUrl || !supabaseServiceKey) {
|
||||
console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_KEY environment variables');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const supabase = createSupabaseClient(supabaseUrl, supabaseServiceKey);
|
||||
const db = getDb();
|
||||
|
||||
interface MigrationStats {
|
||||
table: string;
|
||||
migrated: number;
|
||||
errors: number;
|
||||
}
|
||||
|
||||
const stats: MigrationStats[] = [];
|
||||
|
||||
async function migrateTable<T>(
|
||||
tableName: string,
|
||||
supabaseTableName: string,
|
||||
drizzleTable: any,
|
||||
transformer: (row: any) => T
|
||||
) {
|
||||
console.log(`\nMigrating ${tableName}...`);
|
||||
let migrated = 0;
|
||||
let errors = 0;
|
||||
|
||||
try {
|
||||
// Fetch all data from Supabase
|
||||
const { data, error } = await supabase.from(supabaseTableName).select('*');
|
||||
|
||||
if (error) {
|
||||
console.error(`Error fetching ${tableName}:`, error);
|
||||
stats.push({ table: tableName, migrated: 0, errors: 1 });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
console.log(`No data found in ${tableName}`);
|
||||
stats.push({ table: tableName, migrated: 0, errors: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${data.length} rows in ${tableName}`);
|
||||
|
||||
// Process in batches of 100
|
||||
const batchSize = 100;
|
||||
for (let i = 0; i < data.length; i += batchSize) {
|
||||
const batch = data.slice(i, i + batchSize);
|
||||
const transformed = batch.map(transformer);
|
||||
|
||||
try {
|
||||
await db.insert(drizzleTable).values(transformed).onConflictDoNothing();
|
||||
migrated += batch.length;
|
||||
process.stdout.write(`\r Migrated ${migrated}/${data.length} rows`);
|
||||
} catch (err) {
|
||||
console.error(`\n Error inserting batch:`, err);
|
||||
errors += batch.length;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n Completed: ${migrated} migrated, ${errors} errors`);
|
||||
} catch (err) {
|
||||
console.error(`Error migrating ${tableName}:`, err);
|
||||
errors++;
|
||||
}
|
||||
|
||||
stats.push({ table: tableName, migrated, errors });
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('=== ManaDeck Data Migration ===');
|
||||
console.log('From: Supabase');
|
||||
console.log('To: PostgreSQL (Drizzle)');
|
||||
console.log('==============================\n');
|
||||
|
||||
try {
|
||||
// 1. Migrate decks
|
||||
await migrateTable('decks', 'decks', decks, (row) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
coverImageUrl: row.cover_image_url,
|
||||
isPublic: row.is_public ?? false,
|
||||
isFeatured: row.is_featured ?? false,
|
||||
featuredAt: row.featured_at ? new Date(row.featured_at) : null,
|
||||
settings: row.settings ?? {},
|
||||
tags: row.tags ?? [],
|
||||
metadata: row.metadata ?? {},
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: new Date(row.updated_at),
|
||||
}));
|
||||
|
||||
// 2. Migrate cards
|
||||
await migrateTable('cards', 'cards', cards, (row) => ({
|
||||
id: row.id,
|
||||
deckId: row.deck_id,
|
||||
position: row.position ?? 0,
|
||||
title: row.title,
|
||||
content: row.content,
|
||||
cardType: row.card_type,
|
||||
aiModel: row.ai_model,
|
||||
aiPrompt: row.ai_prompt,
|
||||
version: row.version ?? 1,
|
||||
isFavorite: row.is_favorite ?? false,
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: new Date(row.updated_at),
|
||||
}));
|
||||
|
||||
// 3. Migrate study sessions
|
||||
await migrateTable('study_sessions', 'study_sessions', studySessions, (row) => ({
|
||||
id: row.id,
|
||||
deckId: row.deck_id,
|
||||
userId: row.user_id,
|
||||
mode: row.mode,
|
||||
totalCards: row.total_cards ?? 0,
|
||||
completedCards: row.completed_cards ?? 0,
|
||||
correctCards: row.correct_cards ?? 0,
|
||||
startedAt: new Date(row.started_at),
|
||||
completedAt: row.completed_at ? new Date(row.completed_at) : null,
|
||||
timeSpentSeconds: row.time_spent_seconds ?? 0,
|
||||
}));
|
||||
|
||||
// 4. Migrate card progress
|
||||
await migrateTable('card_progress', 'card_progress', cardProgress, (row) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
cardId: row.card_id,
|
||||
easeFactor: row.ease_factor?.toString() ?? '2.5',
|
||||
interval: row.interval ?? 0,
|
||||
repetitions: row.repetitions ?? 0,
|
||||
lastReviewed: row.last_reviewed ? new Date(row.last_reviewed) : null,
|
||||
nextReview: row.next_review ? new Date(row.next_review) : null,
|
||||
status: row.status ?? 'new',
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: new Date(row.updated_at),
|
||||
}));
|
||||
|
||||
// 5. Migrate deck templates
|
||||
await migrateTable('deck_templates', 'deck_templates', deckTemplates, (row) => ({
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
category: row.category,
|
||||
templateData: row.template_data ?? { cards: [] },
|
||||
isActive: row.is_active ?? true,
|
||||
isPublic: row.is_public ?? true,
|
||||
popularity: row.popularity ?? 0,
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: new Date(row.updated_at),
|
||||
}));
|
||||
|
||||
// 6. Migrate AI generations
|
||||
await migrateTable('ai_generations', 'ai_generations', aiGenerations, (row) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
deckId: row.deck_id,
|
||||
functionName: row.function_name,
|
||||
prompt: row.prompt,
|
||||
model: row.model,
|
||||
status: row.status ?? 'pending',
|
||||
metadata: row.metadata ?? {},
|
||||
completedAt: row.completed_at ? new Date(row.completed_at) : null,
|
||||
createdAt: new Date(row.created_at),
|
||||
}));
|
||||
|
||||
// 7. Migrate user stats
|
||||
await migrateTable('user_stats', 'user_stats', userStats, (row) => ({
|
||||
userId: row.user_id,
|
||||
totalWins: row.total_wins ?? 0,
|
||||
totalSessions: row.total_sessions ?? 0,
|
||||
totalCardsStudied: row.total_cards_studied ?? 0,
|
||||
totalTimeSeconds: row.total_time_seconds ?? 0,
|
||||
averageAccuracy: row.average_accuracy?.toString() ?? '0',
|
||||
streakDays: row.streak_days ?? 0,
|
||||
longestStreak: row.longest_streak ?? 0,
|
||||
lastStudyDate: row.last_study_date,
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: new Date(row.updated_at),
|
||||
}));
|
||||
|
||||
// Print summary
|
||||
console.log('\n\n=== Migration Summary ===');
|
||||
console.log('-------------------------');
|
||||
let totalMigrated = 0;
|
||||
let totalErrors = 0;
|
||||
for (const stat of stats) {
|
||||
console.log(`${stat.table}: ${stat.migrated} migrated, ${stat.errors} errors`);
|
||||
totalMigrated += stat.migrated;
|
||||
totalErrors += stat.errors;
|
||||
}
|
||||
console.log('-------------------------');
|
||||
console.log(`Total: ${totalMigrated} rows migrated, ${totalErrors} errors`);
|
||||
|
||||
if (totalErrors === 0) {
|
||||
console.log('\n✅ Migration completed successfully!');
|
||||
} else {
|
||||
console.log('\n⚠️ Migration completed with some errors. Please review.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Migration failed:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await closeDb();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
23
packages/cards-database/src/migrate.ts
Normal file
23
packages/cards-database/src/migrate.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { migrate } from 'drizzle-orm/postgres-js/migrator';
|
||||
import { createClient } from './client.js';
|
||||
import path from 'path';
|
||||
|
||||
async function runMigrations() {
|
||||
console.log('Running migrations...');
|
||||
|
||||
const db = createClient();
|
||||
|
||||
try {
|
||||
await migrate(db, {
|
||||
migrationsFolder: path.join(__dirname, '../drizzle'),
|
||||
});
|
||||
console.log('Migrations completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('Migration failed:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
runMigrations();
|
||||
54
packages/cards-database/src/schema/aiGenerations.ts
Normal file
54
packages/cards-database/src/schema/aiGenerations.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { pgTable, uuid, text, varchar, timestamp, jsonb, index, pgEnum } from 'drizzle-orm/pg-core';
|
||||
import { relations } from 'drizzle-orm';
|
||||
import { decks } from './decks.js';
|
||||
|
||||
// AI generation status enum
|
||||
export const aiGenerationStatusEnum = pgEnum('ai_generation_status', [
|
||||
'pending',
|
||||
'processing',
|
||||
'completed',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
// AI generation metadata structure
|
||||
export interface AIGenerationMetadata {
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
totalTokens?: number;
|
||||
duration?: number;
|
||||
error?: string;
|
||||
cardCount?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export const aiGenerations = pgTable(
|
||||
'ai_generations',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: text('user_id').notNull(),
|
||||
deckId: uuid('deck_id').references(() => decks.id, { onDelete: 'set null' }),
|
||||
functionName: varchar('function_name', { length: 100 }).notNull(),
|
||||
prompt: text('prompt').notNull(),
|
||||
model: varchar('model', { length: 100 }),
|
||||
status: aiGenerationStatusEnum('status').default('pending').notNull(),
|
||||
metadata: jsonb('metadata').default({}).$type<AIGenerationMetadata>(),
|
||||
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_ai_generations_user_id').on(table.userId),
|
||||
index('idx_ai_generations_deck_id').on(table.deckId),
|
||||
index('idx_ai_generations_status').on(table.status),
|
||||
index('idx_ai_generations_created_at').on(table.createdAt),
|
||||
]
|
||||
);
|
||||
|
||||
export const aiGenerationsRelations = relations(aiGenerations, ({ one }) => ({
|
||||
deck: one(decks, {
|
||||
fields: [aiGenerations.deckId],
|
||||
references: [decks.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export type AIGeneration = typeof aiGenerations.$inferSelect;
|
||||
export type NewAIGeneration = typeof aiGenerations.$inferInsert;
|
||||
58
packages/cards-database/src/schema/cardProgress.ts
Normal file
58
packages/cards-database/src/schema/cardProgress.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
text,
|
||||
integer,
|
||||
timestamp,
|
||||
index,
|
||||
pgEnum,
|
||||
decimal,
|
||||
unique,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
import { relations } from 'drizzle-orm';
|
||||
import { cards } from './cards.js';
|
||||
|
||||
// Progress status enum (SM-2 algorithm states)
|
||||
export const progressStatusEnum = pgEnum('progress_status', [
|
||||
'new',
|
||||
'learning',
|
||||
'review',
|
||||
'relearning',
|
||||
]);
|
||||
|
||||
export const cardProgress = pgTable(
|
||||
'card_progress',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: text('user_id').notNull(),
|
||||
cardId: uuid('card_id')
|
||||
.notNull()
|
||||
.references(() => cards.id, { onDelete: 'cascade' }),
|
||||
// SM-2 algorithm fields
|
||||
easeFactor: decimal('ease_factor', { precision: 4, scale: 2 }).default('2.5').notNull(),
|
||||
interval: integer('interval').default(0).notNull(), // Days until next review
|
||||
repetitions: integer('repetitions').default(0).notNull(),
|
||||
lastReviewed: timestamp('last_reviewed', { withTimezone: true }),
|
||||
nextReview: timestamp('next_review', { withTimezone: true }),
|
||||
status: progressStatusEnum('status').default('new').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_card_progress_user_id').on(table.userId),
|
||||
index('idx_card_progress_card_id').on(table.cardId),
|
||||
index('idx_card_progress_next_review').on(table.nextReview),
|
||||
index('idx_card_progress_status').on(table.status),
|
||||
unique('unique_user_card').on(table.userId, table.cardId),
|
||||
]
|
||||
);
|
||||
|
||||
export const cardProgressRelations = relations(cardProgress, ({ one }) => ({
|
||||
card: one(cards, {
|
||||
fields: [cardProgress.cardId],
|
||||
references: [cards.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export type CardProgress = typeof cardProgress.$inferSelect;
|
||||
export type NewCardProgress = typeof cardProgress.$inferInsert;
|
||||
82
packages/cards-database/src/schema/cards.ts
Normal file
82
packages/cards-database/src/schema/cards.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
varchar,
|
||||
text,
|
||||
integer,
|
||||
boolean,
|
||||
timestamp,
|
||||
jsonb,
|
||||
index,
|
||||
pgEnum,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
import { relations } from 'drizzle-orm';
|
||||
import { decks } from './decks.js';
|
||||
import { cardProgress } from './cardProgress.js';
|
||||
|
||||
// Card type enum
|
||||
export const cardTypeEnum = pgEnum('card_type', ['text', 'flashcard', 'quiz', 'mixed']);
|
||||
|
||||
// Card content types
|
||||
export interface TextContent {
|
||||
text: string;
|
||||
formatting?: {
|
||||
bold?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface FlashcardContent {
|
||||
front: string;
|
||||
back: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export interface QuizContent {
|
||||
question: string;
|
||||
options: string[];
|
||||
correctAnswer: number;
|
||||
explanation?: string;
|
||||
}
|
||||
|
||||
export interface MixedContent {
|
||||
sections: Array<TextContent | FlashcardContent | QuizContent>;
|
||||
}
|
||||
|
||||
export type CardContent = TextContent | FlashcardContent | QuizContent | MixedContent;
|
||||
|
||||
export const cards = pgTable(
|
||||
'cards',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
deckId: uuid('deck_id')
|
||||
.notNull()
|
||||
.references(() => decks.id, { onDelete: 'cascade' }),
|
||||
position: integer('position').notNull().default(0),
|
||||
title: varchar('title', { length: 255 }),
|
||||
content: jsonb('content').notNull().$type<CardContent>(),
|
||||
cardType: cardTypeEnum('card_type').notNull(),
|
||||
aiModel: varchar('ai_model', { length: 100 }),
|
||||
aiPrompt: text('ai_prompt'),
|
||||
version: integer('version').default(1).notNull(),
|
||||
isFavorite: boolean('is_favorite').default(false).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_cards_deck_id').on(table.deckId),
|
||||
index('idx_cards_position').on(table.deckId, table.position),
|
||||
]
|
||||
);
|
||||
|
||||
export const cardsRelations = relations(cards, ({ one, many }) => ({
|
||||
deck: one(decks, {
|
||||
fields: [cards.deckId],
|
||||
references: [decks.id],
|
||||
}),
|
||||
progress: many(cardProgress),
|
||||
}));
|
||||
|
||||
export type Card = typeof cards.$inferSelect;
|
||||
export type NewCard = typeof cards.$inferInsert;
|
||||
37
packages/cards-database/src/schema/dailyProgress.ts
Normal file
37
packages/cards-database/src/schema/dailyProgress.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
text,
|
||||
date,
|
||||
integer,
|
||||
decimal,
|
||||
timestamp,
|
||||
index,
|
||||
unique,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
export const dailyProgress = pgTable(
|
||||
'daily_progress',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: text('user_id').notNull(),
|
||||
date: date('date').notNull(),
|
||||
cardsStudied: integer('cards_studied').default(0).notNull(),
|
||||
timeSpentMinutes: integer('time_spent_minutes').default(0).notNull(),
|
||||
accuracyPercentage: decimal('accuracy_percentage', { precision: 5, scale: 2 })
|
||||
.default('0')
|
||||
.notNull(),
|
||||
decksStudied: text('decks_studied').array().default([]),
|
||||
sessionsCompleted: integer('sessions_completed').default(0).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_daily_progress_user_id').on(table.userId),
|
||||
index('idx_daily_progress_date').on(table.date),
|
||||
unique('unique_user_date').on(table.userId, table.date),
|
||||
]
|
||||
);
|
||||
|
||||
export type DailyProgress = typeof dailyProgress.$inferSelect;
|
||||
export type NewDailyProgress = typeof dailyProgress.$inferInsert;
|
||||
46
packages/cards-database/src/schema/deckTemplates.ts
Normal file
46
packages/cards-database/src/schema/deckTemplates.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
varchar,
|
||||
text,
|
||||
boolean,
|
||||
integer,
|
||||
timestamp,
|
||||
jsonb,
|
||||
index,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
// Template data structure
|
||||
export interface DeckTemplateData {
|
||||
cards: Array<{
|
||||
title?: string;
|
||||
content: Record<string, unknown>;
|
||||
cardType: 'text' | 'flashcard' | 'quiz' | 'mixed';
|
||||
}>;
|
||||
settings?: Record<string, unknown>;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export const deckTemplates = pgTable(
|
||||
'deck_templates',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
title: varchar('title', { length: 255 }).notNull(),
|
||||
description: text('description'),
|
||||
category: varchar('category', { length: 100 }),
|
||||
templateData: jsonb('template_data').notNull().$type<DeckTemplateData>(),
|
||||
isActive: boolean('is_active').default(true).notNull(),
|
||||
isPublic: boolean('is_public').default(true).notNull(),
|
||||
popularity: integer('popularity').default(0).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_deck_templates_category').on(table.category),
|
||||
index('idx_deck_templates_is_active').on(table.isActive),
|
||||
index('idx_deck_templates_popularity').on(table.popularity),
|
||||
]
|
||||
);
|
||||
|
||||
export type DeckTemplate = typeof deckTemplates.$inferSelect;
|
||||
export type NewDeckTemplate = typeof deckTemplates.$inferInsert;
|
||||
48
packages/cards-database/src/schema/decks.ts
Normal file
48
packages/cards-database/src/schema/decks.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
text,
|
||||
varchar,
|
||||
boolean,
|
||||
timestamp,
|
||||
jsonb,
|
||||
index,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
import { relations } from 'drizzle-orm';
|
||||
import { cards } from './cards.js';
|
||||
import { studySessions } from './studySessions.js';
|
||||
import { aiGenerations } from './aiGenerations.js';
|
||||
|
||||
export const decks = pgTable(
|
||||
'decks',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: text('user_id').notNull(),
|
||||
title: varchar('title', { length: 255 }).notNull(),
|
||||
description: text('description'),
|
||||
coverImageUrl: text('cover_image_url'),
|
||||
isPublic: boolean('is_public').default(false).notNull(),
|
||||
isFeatured: boolean('is_featured').default(false).notNull(),
|
||||
featuredAt: timestamp('featured_at', { withTimezone: true }),
|
||||
settings: jsonb('settings').default({}).$type<Record<string, unknown>>(),
|
||||
tags: text('tags').array().default([]),
|
||||
metadata: jsonb('metadata').default({}).$type<Record<string, unknown>>(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_decks_user_id').on(table.userId),
|
||||
index('idx_decks_is_public').on(table.isPublic),
|
||||
index('idx_decks_is_featured').on(table.isFeatured),
|
||||
index('idx_decks_updated_at').on(table.updatedAt),
|
||||
]
|
||||
);
|
||||
|
||||
export const decksRelations = relations(decks, ({ many }) => ({
|
||||
cards: many(cards),
|
||||
studySessions: many(studySessions),
|
||||
aiGenerations: many(aiGenerations),
|
||||
}));
|
||||
|
||||
export type Deck = typeof decks.$inferSelect;
|
||||
export type NewDeck = typeof decks.$inferInsert;
|
||||
16
packages/cards-database/src/schema/index.ts
Normal file
16
packages/cards-database/src/schema/index.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// Export all schemas
|
||||
export * from './decks.js';
|
||||
export * from './cards.js';
|
||||
export * from './studySessions.js';
|
||||
export * from './cardProgress.js';
|
||||
export * from './deckTemplates.js';
|
||||
export * from './aiGenerations.js';
|
||||
export * from './userStats.js';
|
||||
export * from './dailyProgress.js';
|
||||
|
||||
// Re-export relations for use with Drizzle query builder
|
||||
export { decksRelations } from './decks.js';
|
||||
export { cardsRelations } from './cards.js';
|
||||
export { studySessionsRelations } from './studySessions.js';
|
||||
export { cardProgressRelations } from './cardProgress.js';
|
||||
export { aiGenerationsRelations } from './aiGenerations.js';
|
||||
39
packages/cards-database/src/schema/studySessions.ts
Normal file
39
packages/cards-database/src/schema/studySessions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { pgTable, uuid, text, integer, timestamp, index, pgEnum } from 'drizzle-orm/pg-core';
|
||||
import { relations } from 'drizzle-orm';
|
||||
import { decks } from './decks.js';
|
||||
|
||||
// Study mode enum
|
||||
export const studyModeEnum = pgEnum('study_mode', ['all', 'new', 'review', 'favorites', 'random']);
|
||||
|
||||
export const studySessions = pgTable(
|
||||
'study_sessions',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
deckId: uuid('deck_id')
|
||||
.notNull()
|
||||
.references(() => decks.id, { onDelete: 'cascade' }),
|
||||
userId: text('user_id').notNull(),
|
||||
mode: studyModeEnum('mode').notNull(),
|
||||
totalCards: integer('total_cards').notNull().default(0),
|
||||
completedCards: integer('completed_cards').notNull().default(0),
|
||||
correctCards: integer('correct_cards').notNull().default(0),
|
||||
startedAt: timestamp('started_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||
timeSpentSeconds: integer('time_spent_seconds').default(0).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_study_sessions_user_id').on(table.userId),
|
||||
index('idx_study_sessions_deck_id').on(table.deckId),
|
||||
index('idx_study_sessions_started_at').on(table.startedAt),
|
||||
]
|
||||
);
|
||||
|
||||
export const studySessionsRelations = relations(studySessions, ({ one }) => ({
|
||||
deck: one(decks, {
|
||||
fields: [studySessions.deckId],
|
||||
references: [decks.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
export type StudySession = typeof studySessions.$inferSelect;
|
||||
export type NewStudySession = typeof studySessions.$inferInsert;
|
||||
25
packages/cards-database/src/schema/userStats.ts
Normal file
25
packages/cards-database/src/schema/userStats.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { pgTable, text, integer, decimal, date, timestamp, index } from 'drizzle-orm/pg-core';
|
||||
|
||||
export const userStats = pgTable(
|
||||
'user_stats',
|
||||
{
|
||||
userId: text('user_id').primaryKey(),
|
||||
totalWins: integer('total_wins').default(0).notNull(),
|
||||
totalSessions: integer('total_sessions').default(0).notNull(),
|
||||
totalCardsStudied: integer('total_cards_studied').default(0).notNull(),
|
||||
totalTimeSeconds: integer('total_time_seconds').default(0).notNull(),
|
||||
averageAccuracy: decimal('average_accuracy', { precision: 5, scale: 2 }).default('0').notNull(),
|
||||
streakDays: integer('streak_days').default(0).notNull(),
|
||||
longestStreak: integer('longest_streak').default(0).notNull(),
|
||||
lastStudyDate: date('last_study_date'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_user_stats_total_wins').on(table.totalWins),
|
||||
index('idx_user_stats_streak_days').on(table.streakDays),
|
||||
]
|
||||
);
|
||||
|
||||
export type UserStats = typeof userStats.$inferSelect;
|
||||
export type NewUserStats = typeof userStats.$inferInsert;
|
||||
105
packages/cards-database/src/seed.ts
Normal file
105
packages/cards-database/src/seed.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { getDb, closeDb } from './client.js';
|
||||
import { deckTemplates } from './schema/index.js';
|
||||
|
||||
/**
|
||||
* Seed the database with initial data
|
||||
*/
|
||||
async function seed() {
|
||||
console.log('Seeding database...');
|
||||
|
||||
const db = getDb();
|
||||
|
||||
try {
|
||||
// Seed deck templates
|
||||
const templates = [
|
||||
{
|
||||
title: 'Language Basics',
|
||||
description: 'Learn basic vocabulary and phrases for a new language',
|
||||
category: 'languages',
|
||||
templateData: {
|
||||
cards: [
|
||||
{
|
||||
cardType: 'flashcard' as const,
|
||||
content: { front: 'Hello', back: 'Hallo', hint: 'Greeting' },
|
||||
},
|
||||
{
|
||||
cardType: 'flashcard' as const,
|
||||
content: { front: 'Goodbye', back: 'Auf Wiedersehen' },
|
||||
},
|
||||
],
|
||||
settings: { language: 'de' },
|
||||
tags: ['language', 'basics', 'german'],
|
||||
},
|
||||
isActive: true,
|
||||
isPublic: true,
|
||||
popularity: 100,
|
||||
},
|
||||
{
|
||||
title: 'Math Fundamentals',
|
||||
description: 'Essential math concepts and formulas',
|
||||
category: 'education',
|
||||
templateData: {
|
||||
cards: [
|
||||
{
|
||||
cardType: 'quiz' as const,
|
||||
content: {
|
||||
question: 'What is 2 + 2?',
|
||||
options: ['3', '4', '5', '6'],
|
||||
correctAnswer: 1,
|
||||
explanation: '2 + 2 equals 4',
|
||||
},
|
||||
},
|
||||
],
|
||||
settings: { difficulty: 'beginner' },
|
||||
tags: ['math', 'basics'],
|
||||
},
|
||||
isActive: true,
|
||||
isPublic: true,
|
||||
popularity: 80,
|
||||
},
|
||||
{
|
||||
title: 'Programming Concepts',
|
||||
description: 'Core programming concepts and terminology',
|
||||
category: 'technology',
|
||||
templateData: {
|
||||
cards: [
|
||||
{
|
||||
cardType: 'flashcard' as const,
|
||||
content: {
|
||||
front: 'Variable',
|
||||
back: 'A named storage location in memory that holds a value',
|
||||
},
|
||||
},
|
||||
{
|
||||
cardType: 'flashcard' as const,
|
||||
content: {
|
||||
front: 'Function',
|
||||
back: 'A reusable block of code that performs a specific task',
|
||||
},
|
||||
},
|
||||
],
|
||||
settings: {},
|
||||
tags: ['programming', 'coding', 'basics'],
|
||||
},
|
||||
isActive: true,
|
||||
isPublic: true,
|
||||
popularity: 90,
|
||||
},
|
||||
];
|
||||
|
||||
console.log('Inserting deck templates...');
|
||||
await db.insert(deckTemplates).values(templates).onConflictDoNothing();
|
||||
|
||||
console.log('Seeding completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('Seeding failed:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
await closeDb();
|
||||
}
|
||||
}
|
||||
|
||||
seed().catch((error) => {
|
||||
console.error('Seed script failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
44
packages/cards-database/src/test-connection.ts
Normal file
44
packages/cards-database/src/test-connection.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
* Test database connection
|
||||
* Usage: pnpm db:test
|
||||
*/
|
||||
|
||||
import { getDb, closeDb, sql } from './client.js';
|
||||
|
||||
async function testConnection() {
|
||||
console.log('Testing database connection...\n');
|
||||
|
||||
try {
|
||||
const db = getDb();
|
||||
|
||||
// Test basic connection
|
||||
const result = await db.execute(sql`SELECT NOW() as current_time, version() as pg_version`);
|
||||
console.log('✅ Connection successful!');
|
||||
console.log(` Time: ${result[0].current_time}`);
|
||||
console.log(` PostgreSQL: ${result[0].pg_version}\n`);
|
||||
|
||||
// List tables
|
||||
const tables = await db.execute(sql`
|
||||
SELECT tablename
|
||||
FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
ORDER BY tablename
|
||||
`);
|
||||
|
||||
if (tables.length > 0) {
|
||||
console.log('📋 Tables in database:');
|
||||
tables.forEach((t: any) => console.log(` - ${t.tablename}`));
|
||||
} else {
|
||||
console.log('📋 No tables found. Run "pnpm db:push" to create schema.');
|
||||
}
|
||||
|
||||
console.log('\n✅ All tests passed!');
|
||||
} catch (error) {
|
||||
console.error('❌ Connection failed:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await closeDb();
|
||||
}
|
||||
}
|
||||
|
||||
testConnection();
|
||||
Loading…
Add table
Add a link
Reference in a new issue