Add multi-language support and new repository methods for book synchronization
- Extend repository methods to handle API requests for fetching books, chapters, characters, and other entities with multilingual support (`lang: 'fr' | 'en'`). - Add `uploadBookForSync` logic to consolidate and decrypt book data for synchronization. - Refactor schema migration logic to remove console logs and streamline table recreation. - Enhance error handling across database repositories and IPC methods.
This commit is contained in:
@@ -34,14 +34,10 @@ export class DatabaseService {
|
||||
this.db = new sqlite3.Database(dbPath);
|
||||
this.userEncryptionKey = encryptionKey;
|
||||
this.userId = userId;
|
||||
|
||||
// Initialize schema (creates tables if they don't exist)
|
||||
|
||||
initializeSchema(this.db);
|
||||
|
||||
// Run migrations (updates existing tables if needed)
|
||||
|
||||
runMigrations(this.db);
|
||||
|
||||
console.log(`Database initialized for user ${userId} at ${dbPath}`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -432,7 +432,7 @@ export default class Book {
|
||||
return BookRepo.insertBook(id,userId,encryptedTitle,hashedTitle,encryptedSubTitle,hashedSubTitle,encryptedSummary,type,serie,publicationDate,desiredWordCount,lang);
|
||||
}
|
||||
|
||||
public static async getBook(userId:string,bookId: string): Promise<BookProps> {
|
||||
public static async getBook(userId:string,bookId: string, lang: 'fr' | 'en'): Promise<BookProps> {
|
||||
const book:Book = new Book(bookId);
|
||||
await book.getBookInfos(userId);
|
||||
return {
|
||||
@@ -1334,6 +1334,217 @@ export default class Book {
|
||||
});
|
||||
}
|
||||
|
||||
static async uploadBookForSync(userId:string,bookId: string,lang: "fr" | "en"): Promise<CompleteBook> {
|
||||
const userKey: string = getUserEncryptionKey(userId);
|
||||
const [
|
||||
eritBooksRaw,
|
||||
actSummariesRaw,
|
||||
aiGuideLineRaw,
|
||||
chaptersRaw,
|
||||
charactersRaw,
|
||||
guideLineRaw,
|
||||
incidentsRaw,
|
||||
issuesRaw,
|
||||
locationsRaw,
|
||||
plotPointsRaw,
|
||||
worldsRaw
|
||||
]: [
|
||||
EritBooksTable[],
|
||||
BookActSummariesTable[],
|
||||
BookAIGuideLineTable[],
|
||||
BookChaptersTable[],
|
||||
BookCharactersTable[],
|
||||
BookGuideLineTable[],
|
||||
BookIncidentsTable[],
|
||||
BookIssuesTable[],
|
||||
BookLocationTable[],
|
||||
BookPlotPointsTable[],
|
||||
BookWorldTable[]
|
||||
] = await Promise.all([
|
||||
BookRepo.fetchEritBooksTable(userId, bookId,lang),
|
||||
BookRepo.fetchBookActSummaries(userId, bookId,lang),
|
||||
BookRepo.fetchBookAIGuideLine(userId, bookId,lang),
|
||||
BookRepo.fetchBookChapters(userId, bookId,lang),
|
||||
BookRepo.fetchBookCharacters(userId, bookId,lang),
|
||||
BookRepo.fetchBookGuideLineTable(userId, bookId,lang),
|
||||
BookRepo.fetchBookIncidents(userId, bookId,lang),
|
||||
BookRepo.fetchBookIssues(userId, bookId,lang),
|
||||
BookRepo.fetchBookLocations(userId, bookId,lang),
|
||||
BookRepo.fetchBookPlotPoints(userId, bookId,lang),
|
||||
BookRepo.fetchBookWorlds(userId, bookId,lang)
|
||||
]);
|
||||
|
||||
const [
|
||||
chapterContentsNested,
|
||||
chapterInfosNested,
|
||||
characterAttributesNested,
|
||||
worldElementsNested,
|
||||
locationElementsNested
|
||||
]: [
|
||||
BookChapterContentTable[][],
|
||||
BookChapterInfosTable[][],
|
||||
BookCharactersAttributesTable[][],
|
||||
BookWorldElementsTable[][],
|
||||
LocationElementTable[][]
|
||||
] = await Promise.all([
|
||||
Promise.all(chaptersRaw.map((chapter: BookChaptersTable): Promise<BookChapterContentTable[]> => BookRepo.fetchBookChapterContents(userId, chapter.chapter_id,lang))),
|
||||
Promise.all(chaptersRaw.map((chapter: BookChaptersTable): Promise<BookChapterInfosTable[]> => BookRepo.fetchBookChapterInfos(userId, chapter.chapter_id,lang))),
|
||||
Promise.all(charactersRaw.map((character: BookCharactersTable): Promise<BookCharactersAttributesTable[]> => BookRepo.fetchBookCharactersAttributes(userId, character.character_id,lang))),
|
||||
Promise.all(worldsRaw.map((world: BookWorldTable): Promise<BookWorldElementsTable[]> => BookRepo.fetchBookWorldElements(userId, world.world_id,lang))),
|
||||
Promise.all(locationsRaw.map((location: BookLocationTable): Promise<LocationElementTable[]> => BookRepo.fetchLocationElements(userId, location.loc_id,lang)))
|
||||
]);
|
||||
|
||||
const chapterContentsRaw: BookChapterContentTable[] = chapterContentsNested.flat();
|
||||
const chapterInfosRaw: BookChapterInfosTable[] = chapterInfosNested.flat();
|
||||
const characterAttributesRaw: BookCharactersAttributesTable[] = characterAttributesNested.flat();
|
||||
const worldElementsRaw: BookWorldElementsTable[] = worldElementsNested.flat();
|
||||
const locationElementsRaw: LocationElementTable[] = locationElementsNested.flat();
|
||||
|
||||
const locationSubElementsNested: LocationSubElementTable[][] = await Promise.all(
|
||||
locationElementsRaw.map((element: LocationElementTable): Promise<LocationSubElementTable[]> => BookRepo.fetchLocationSubElements(userId, element.element_id,lang))
|
||||
);
|
||||
const locationSubElementsRaw: LocationSubElementTable[] = locationSubElementsNested.flat();
|
||||
|
||||
const eritBooks: EritBooksTable[] = eritBooksRaw.map((book: EritBooksTable): EritBooksTable => ({
|
||||
...book,
|
||||
title: System.decryptDataWithUserKey(book.title, userKey),
|
||||
sub_title: book.sub_title ? System.decryptDataWithUserKey(book.sub_title, userKey) : null,
|
||||
summary: book.summary ? System.decryptDataWithUserKey(book.summary, userKey) : null,
|
||||
cover_image: book.cover_image ? System.decryptDataWithUserKey(book.cover_image, userKey) : null
|
||||
}));
|
||||
|
||||
const actSummaries: BookActSummariesTable[] = actSummariesRaw.map((actSummary: BookActSummariesTable): BookActSummariesTable => ({
|
||||
...actSummary,
|
||||
summary: actSummary.summary ? System.decryptDataWithUserKey(actSummary.summary, userKey) : null
|
||||
}));
|
||||
|
||||
const aiGuideLine: BookAIGuideLineTable[] = aiGuideLineRaw.map((guideLine: BookAIGuideLineTable): BookAIGuideLineTable => ({
|
||||
...guideLine,
|
||||
global_resume: guideLine.global_resume ? System.decryptDataWithUserKey(guideLine.global_resume, userKey) : null,
|
||||
themes: guideLine.themes ? System.decryptDataWithUserKey(guideLine.themes, userKey) : null,
|
||||
tone: guideLine.tone ? System.decryptDataWithUserKey(guideLine.tone, userKey) : null,
|
||||
atmosphere: guideLine.atmosphere ? System.decryptDataWithUserKey(guideLine.atmosphere, userKey) : null,
|
||||
current_resume: guideLine.current_resume ? System.decryptDataWithUserKey(guideLine.current_resume, userKey) : null
|
||||
}));
|
||||
|
||||
const chapters: BookChaptersTable[] = chaptersRaw.map((chapter: BookChaptersTable): BookChaptersTable => ({
|
||||
...chapter,
|
||||
title: System.decryptDataWithUserKey(chapter.title, userKey)
|
||||
}));
|
||||
|
||||
const chapterContents: BookChapterContentTable[] = chapterContentsRaw.map((chapterContent: BookChapterContentTable): BookChapterContentTable => ({
|
||||
...chapterContent,
|
||||
content: chapterContent.content ? JSON.parse(System.decryptDataWithUserKey(chapterContent.content, userKey)) : null
|
||||
}));
|
||||
|
||||
const chapterInfos: BookChapterInfosTable[] = chapterInfosRaw.map((chapterInfo: BookChapterInfosTable): BookChapterInfosTable => ({
|
||||
...chapterInfo,
|
||||
summary: chapterInfo.summary ? System.decryptDataWithUserKey(chapterInfo.summary, userKey) : null,
|
||||
goal: chapterInfo.goal ? System.decryptDataWithUserKey(chapterInfo.goal, userKey) : null
|
||||
}));
|
||||
|
||||
const characters: BookCharactersTable[] = charactersRaw.map((character: BookCharactersTable): BookCharactersTable => ({
|
||||
...character,
|
||||
first_name: System.decryptDataWithUserKey(character.first_name, userKey),
|
||||
last_name: character.last_name ? System.decryptDataWithUserKey(character.last_name, userKey) : null,
|
||||
category: System.decryptDataWithUserKey(character.category, userKey),
|
||||
title: character.title ? System.decryptDataWithUserKey(character.title, userKey) : null,
|
||||
role: character.role ? System.decryptDataWithUserKey(character.role, userKey) : null,
|
||||
biography: character.biography ? System.decryptDataWithUserKey(character.biography, userKey) : null,
|
||||
history: character.history ? System.decryptDataWithUserKey(character.history, userKey) : null
|
||||
}));
|
||||
|
||||
const characterAttributes: BookCharactersAttributesTable[] = characterAttributesRaw.map((attribute: BookCharactersAttributesTable): BookCharactersAttributesTable => ({
|
||||
...attribute,
|
||||
attribute_name: System.decryptDataWithUserKey(attribute.attribute_name, userKey),
|
||||
attribute_value: System.decryptDataWithUserKey(attribute.attribute_value, userKey)
|
||||
}));
|
||||
|
||||
const guideLine: BookGuideLineTable[] = guideLineRaw.map((guide: BookGuideLineTable): BookGuideLineTable => ({
|
||||
...guide,
|
||||
tone: guide.tone ? System.decryptDataWithUserKey(guide.tone, userKey) : null,
|
||||
atmosphere: guide.atmosphere ? System.decryptDataWithUserKey(guide.atmosphere, userKey) : null,
|
||||
writing_style: guide.writing_style ? System.decryptDataWithUserKey(guide.writing_style, userKey) : null,
|
||||
themes: guide.themes ? System.decryptDataWithUserKey(guide.themes, userKey) : null,
|
||||
symbolism: guide.symbolism ? System.decryptDataWithUserKey(guide.symbolism, userKey) : null,
|
||||
motifs: guide.motifs ? System.decryptDataWithUserKey(guide.motifs, userKey) : null,
|
||||
narrative_voice: guide.narrative_voice ? System.decryptDataWithUserKey(guide.narrative_voice, userKey) : null,
|
||||
pacing: guide.pacing ? System.decryptDataWithUserKey(guide.pacing, userKey) : null,
|
||||
intended_audience: guide.intended_audience ? System.decryptDataWithUserKey(guide.intended_audience, userKey) : null,
|
||||
key_messages: guide.key_messages ? System.decryptDataWithUserKey(guide.key_messages, userKey) : null
|
||||
}));
|
||||
|
||||
const incidents: BookIncidentsTable[] = incidentsRaw.map((incident: BookIncidentsTable): BookIncidentsTable => ({
|
||||
...incident,
|
||||
title: System.decryptDataWithUserKey(incident.title, userKey),
|
||||
summary: incident.summary ? System.decryptDataWithUserKey(incident.summary, userKey) : null
|
||||
}));
|
||||
|
||||
const issues: BookIssuesTable[] = issuesRaw.map((issue: BookIssuesTable): BookIssuesTable => ({
|
||||
...issue,
|
||||
name: System.decryptDataWithUserKey(issue.name, userKey)
|
||||
}));
|
||||
|
||||
const locations: BookLocationTable[] = locationsRaw.map((location: BookLocationTable): BookLocationTable => ({
|
||||
...location,
|
||||
loc_name: System.decryptDataWithUserKey(location.loc_name, userKey)
|
||||
}));
|
||||
|
||||
const plotPoints: BookPlotPointsTable[] = plotPointsRaw.map((plotPoint: BookPlotPointsTable): BookPlotPointsTable => ({
|
||||
...plotPoint,
|
||||
title: System.decryptDataWithUserKey(plotPoint.title, userKey),
|
||||
summary: plotPoint.summary ? System.decryptDataWithUserKey(plotPoint.summary, userKey) : null
|
||||
}));
|
||||
|
||||
const worlds: BookWorldTable[] = worldsRaw.map((world: BookWorldTable): BookWorldTable => ({
|
||||
...world,
|
||||
name: System.decryptDataWithUserKey(world.name, userKey),
|
||||
history: world.history ? System.decryptDataWithUserKey(world.history, userKey) : null,
|
||||
politics: world.politics ? System.decryptDataWithUserKey(world.politics, userKey) : null,
|
||||
economy: world.economy ? System.decryptDataWithUserKey(world.economy, userKey) : null,
|
||||
religion: world.religion ? System.decryptDataWithUserKey(world.religion, userKey) : null,
|
||||
languages: world.languages ? System.decryptDataWithUserKey(world.languages, userKey) : null
|
||||
}));
|
||||
|
||||
const worldElements: BookWorldElementsTable[] = worldElementsRaw.map((worldElement: BookWorldElementsTable): BookWorldElementsTable => ({
|
||||
...worldElement,
|
||||
name: System.decryptDataWithUserKey(worldElement.name, userKey),
|
||||
description: worldElement.description ? System.decryptDataWithUserKey(worldElement.description, userKey) : null
|
||||
}));
|
||||
|
||||
const locationElements: LocationElementTable[] = locationElementsRaw.map((locationElement: LocationElementTable): LocationElementTable => ({
|
||||
...locationElement,
|
||||
element_name: System.decryptDataWithUserKey(locationElement.element_name, userKey),
|
||||
element_description: locationElement.element_description ? System.decryptDataWithUserKey(locationElement.element_description, userKey) : null
|
||||
}));
|
||||
|
||||
const locationSubElements: LocationSubElementTable[] = locationSubElementsRaw.map((locationSubElement: LocationSubElementTable): LocationSubElementTable => ({
|
||||
...locationSubElement,
|
||||
sub_elem_name: System.decryptDataWithUserKey(locationSubElement.sub_elem_name, userKey),
|
||||
sub_elem_description: locationSubElement.sub_elem_description ? System.decryptDataWithUserKey(locationSubElement.sub_elem_description, userKey) : null
|
||||
}));
|
||||
|
||||
return {
|
||||
eritBooks,
|
||||
actSummaries,
|
||||
aiGuideLine,
|
||||
chapters,
|
||||
chapterContents,
|
||||
chapterInfos,
|
||||
characters,
|
||||
characterAttributes,
|
||||
guideLine,
|
||||
incidents,
|
||||
issues,
|
||||
locations,
|
||||
plotPoints,
|
||||
worlds,
|
||||
worldElements,
|
||||
locationElements,
|
||||
locationSubElements
|
||||
};
|
||||
}
|
||||
|
||||
static async saveCompleteBook(userId: string, data: CompleteBook, lang: "fr" | "en"):Promise<boolean> {
|
||||
const userKey: string = getUserEncryptionKey(userId);
|
||||
|
||||
@@ -1723,7 +1934,6 @@ export default class Book {
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(data.id)
|
||||
const book: EritBooksTable[] = await BookRepo.fetchCompleteBookById(data.id, lang);
|
||||
if (book.length>0) {
|
||||
const bookDataItem: EritBooksTable = book[0];
|
||||
|
||||
@@ -1048,6 +1048,244 @@ export default class BookRepo {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static async fetchEritBooksTable(userId:string,bookId:string, lang: 'fr' | 'en'):Promise<EritBooksTable[]>{
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT book_id, type, author_id, title, hashed_title, sub_title, hashed_sub_title, summary, serie_id, desired_release_date, desired_word_count, words_count, cover_image, last_update FROM erit_books WHERE book_id=? AND author_id=?', [bookId, userId]) as EritBooksTable[];
|
||||
} catch (e:unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les informations du livre.` : `Unable to retrieve book information.`);
|
||||
} else {
|
||||
console.error("An unknown error occurred.");
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookActSummaries(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookActSummariesTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT act_sum_id, book_id, user_id, act_index, summary, last_update FROM book_act_summaries WHERE user_id=? AND book_id=?', [userId, bookId]) as BookActSummariesTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les résumés des actes.` : `Unable to retrieve act summaries.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookAIGuideLine(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookAIGuideLineTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT user_id, book_id, global_resume, themes, verbe_tense, narrative_type, langue, dialogue_type, tone, atmosphere, current_resume, last_update FROM book_ai_guide_line WHERE user_id=? AND book_id=?', [userId, bookId]) as BookAIGuideLineTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer la ligne directrice IA.` : `Unable to retrieve AI guideline.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookChapters(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookChaptersTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT chapter_id, book_id, author_id, title, hashed_title, words_count, chapter_order, last_update FROM book_chapters WHERE author_id=? AND book_id=?', [userId, bookId]) as BookChaptersTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les chapitres.` : `Unable to retrieve chapters.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookChapterContents(userId: string,chapterId:string, lang: 'fr' | 'en'): Promise<BookChapterContentTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT content_id, chapter_id, author_id, version, content, words_count, time_on_it, last_update FROM book_chapter_content WHERE author_id=? AND chapter_id=?', [userId, chapterId]) as BookChapterContentTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer le contenu des chapitres.` : `Unable to retrieve chapter contents.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookChapterInfos(userId: string, chapterId: string, lang: 'fr' | 'en'): Promise<BookChapterInfosTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT chapter_info_id, chapter_id, act_id, incident_id, plot_point_id, book_id, author_id, summary, goal, last_update FROM book_chapter_infos WHERE author_id=? AND chapter_id=?', [userId, chapterId]) as BookChapterInfosTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les infos des chapitres.` : `Unable to retrieve chapter infos.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookCharacters(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookCharactersTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT character_id, book_id, user_id, first_name, last_name, category, title, image, role, biography, history, last_update FROM book_characters WHERE user_id=? AND book_id=?', [userId, bookId]) as BookCharactersTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les personnages.` : `Unable to retrieve characters.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookCharactersAttributes(userId: string, characterId:string, lang: 'fr' | 'en'): Promise<BookCharactersAttributesTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT attr_id, character_id, user_id, attribute_name, attribute_value, last_update FROM book_characters_attributes WHERE user_id=? AND character_id=?', [userId, characterId]) as BookCharactersAttributesTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les attributs des personnages.` : `Unable to retrieve character attributes.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookGuideLineTable(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookGuideLineTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT user_id, book_id, tone, atmosphere, writing_style, themes, symbolism, motifs, narrative_voice, pacing, intended_audience, key_messages, last_update FROM book_guide_line WHERE user_id=? AND book_id=?', [userId, bookId]) as BookGuideLineTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer la ligne directrice.` : `Unable to retrieve guideline.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookIncidents(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookIncidentsTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT incident_id, author_id, book_id, title, hashed_title, summary, last_update FROM book_incidents WHERE author_id=? AND book_id=?', [userId, bookId]) as BookIncidentsTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les incidents.` : `Unable to retrieve incidents.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookIssues(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookIssuesTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT issue_id, author_id, book_id, name, hashed_issue_name, last_update FROM book_issues WHERE author_id=? AND book_id=?', [userId, bookId]) as BookIssuesTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les problématiques.` : `Unable to retrieve issues.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookLocations(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookLocationTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT loc_id, book_id, user_id, loc_name, loc_original_name, last_update FROM book_location WHERE user_id=? AND book_id=?', [userId, bookId]) as BookLocationTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les lieux.` : `Unable to retrieve locations.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookPlotPoints(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookPlotPointsTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT plot_point_id, title, hashed_title, summary, linked_incident_id, author_id, book_id, last_update FROM book_plot_points WHERE author_id=? AND book_id=?', [userId, bookId]) as BookPlotPointsTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les points d'intrigue.` : `Unable to retrieve plot points.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookWorlds(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookWorldTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT world_id, name, hashed_name, author_id, book_id, history, politics, economy, religion, languages, last_update FROM book_world WHERE author_id=? AND book_id=?', [userId, bookId]) as BookWorldTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les mondes.` : `Unable to retrieve worlds.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchBookWorldElements(userId: string,worldId:string, lang: 'fr' | 'en'): Promise<BookWorldElementsTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT element_id, world_id, user_id, element_type, name, original_name, description, last_update FROM book_world_elements WHERE user_id=? AND world_id=?', [userId, worldId]) as BookWorldElementsTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les éléments du monde.` : `Unable to retrieve world elements.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchLocationElements(userId: string,locationId:string, lang: 'fr' | 'en'): Promise<LocationElementTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT element_id, location, user_id, element_name, original_name, element_description, last_update FROM location_element WHERE user_id=? AND location=?', [userId, locationId]) as LocationElementTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les éléments de lieu.` : `Unable to retrieve location elements.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async fetchLocationSubElements(userId: string,elementId:string, lang: 'fr' | 'en'): Promise<LocationSubElementTable[]> {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
return db.all('SELECT sub_element_id, element_id, user_id, sub_elem_name, original_name, sub_elem_description, last_update FROM location_sub_element WHERE user_id=? AND element_id=?', [userId, elementId]) as LocationSubElementTable[];
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.error(`DB Error: ${e.message}`);
|
||||
throw new Error(lang === 'fr' ? `Impossible de récupérer les sous-éléments de lieu.` : `Unable to retrieve location sub-elements.`);
|
||||
} else {
|
||||
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
|
||||
}
|
||||
}
|
||||
}
|
||||
static fetchSyncedBooks(userId: string, lang: 'fr' | 'en'): SyncedBookResult[] {
|
||||
try {
|
||||
const db: Database = System.getDb();
|
||||
|
||||
@@ -483,7 +483,6 @@ function dropColumnIfExists(db: Database, tableName: string, columnName: string)
|
||||
if (columnExists(db, tableName, columnName)) {
|
||||
try {
|
||||
db.exec(`ALTER TABLE ${tableName} DROP COLUMN ${columnName}`);
|
||||
console.log(`[Migration] Dropped column ${columnName} from ${tableName}`);
|
||||
} catch (e) {
|
||||
console.error(`[Migration] Failed to drop column ${columnName} from ${tableName}:`, e);
|
||||
}
|
||||
@@ -502,7 +501,6 @@ function recreateTable(db: Database, tableName: string, newSchema: string, colum
|
||||
db.exec(`INSERT INTO ${tableName} (${columnsToKeep}) SELECT ${columnsToKeep} FROM ${tableName}_backup`);
|
||||
db.exec(`DROP TABLE ${tableName}_backup`);
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
console.log(`[Migration] Recreated table ${tableName}`);
|
||||
} catch (e) {
|
||||
console.error(`[Migration] Failed to recreate table ${tableName}:`, e);
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
@@ -519,12 +517,8 @@ export function runMigrations(db: Database): void {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[Migration] Upgrading schema from version ${currentVersion} to ${SCHEMA_VERSION}`);
|
||||
|
||||
// Migration v2: Remove NOT NULL constraints to allow null values from server sync
|
||||
if (currentVersion < 2) {
|
||||
console.log('[Migration] Running migration v2: Allowing NULL in certain columns...');
|
||||
|
||||
// Recreate erit_books with nullable hashed_sub_title and summary
|
||||
recreateTable(db, 'erit_books', `
|
||||
CREATE TABLE erit_books (
|
||||
@@ -578,11 +572,8 @@ export function runMigrations(db: Database): void {
|
||||
FOREIGN KEY (plot_point_id) REFERENCES book_plot_points(plot_point_id) ON DELETE CASCADE
|
||||
)
|
||||
`, 'chapter_info_id, chapter_id, act_id, incident_id, plot_point_id, book_id, author_id, summary, goal, last_update');
|
||||
|
||||
console.log('[Migration] Migration v2 completed');
|
||||
}
|
||||
|
||||
// Update schema version
|
||||
setDbSchemaVersion(db, SCHEMA_VERSION);
|
||||
console.log(`[Migration] Schema updated to version ${SCHEMA_VERSION}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user