2024 lines
129 KiB
C#
2024 lines
129 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Data.SQLite;
|
|
using A69WD.Net;
|
|
using System.Drawing;
|
|
using A69WD.Data;
|
|
|
|
|
|
namespace A69WD {
|
|
|
|
|
|
public class DBTools {
|
|
/*
|
|
*
|
|
* Tabella per storicizzare i link downloadati:
|
|
* --------------------------------------------
|
|
* CREATE TABLE [LinksLog] ( /* Tabella per salvare il lavoro fatto sui link * /
|
|
* [LinkURL] TEXT UNIQUE NOT NULL PRIMARY KEY, /* URL del link * /
|
|
* [FileName] TEXT UNIQUE NOT NULL, /* Nome del file su cui salvo quanto downloadato * /
|
|
* [PlugID] TEXT NOT NULL, /* ID del plugin utilizzato per gestire questo particolare link * /
|
|
* [Fields] INTEGER NOT NULL, /* Campo in cui salvo tutti i dati significativi sul link, separati fra loro da -|- * /
|
|
* [Status] INTEGER NOT NULL, /* Stato della lavorazione * /
|
|
* [LastUpdate] TIMESTAMP NOT NULL /* Timestamp all'ultimo aggiornamento del record * /
|
|
* )
|
|
*
|
|
*/
|
|
|
|
#region Class Fields & Property: cn, DB_ok, objLock
|
|
|
|
/// <summary>
|
|
/// Connessione al DB
|
|
/// </summary>
|
|
public System.Data.SQLite.SQLiteConnection cn { get; set; }
|
|
|
|
/// <summary>
|
|
/// Indicatore che il DB è ready
|
|
/// </summary>
|
|
public bool DB_ok { get; set; }
|
|
|
|
/// <summary>
|
|
/// Oggetto per la sincronizzazione fra i threads:
|
|
/// </summary>
|
|
internal readonly object objLock = new object();
|
|
|
|
#endregion
|
|
|
|
#region Costruttore e distruttore:
|
|
|
|
public DBTools() {
|
|
// Copio il DB dal file in memoria e mantengo la connessione per utilizzarla durante l'applicazione
|
|
object obj = new Object();
|
|
lock (obj) {
|
|
System.Data.SQLite.SQLiteConnection conn = null;
|
|
// Check esistenza del DB dell'applicazione, altrimenti ne creo uno nuovo:
|
|
try {
|
|
if (!System.IO.File.Exists(System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName))) {
|
|
// Creo cartella se non esiste
|
|
if (!System.IO.Directory.Exists(Cfg.Settings.PathDB)) { System.IO.Directory.CreateDirectory(Cfg.Settings.PathDB); }
|
|
// Creo un nuovo file di database e definisco le tabelle in uso.
|
|
conn = new SQLiteConnection(Cfg.Settings.DBConnectionString);
|
|
conn.Open();
|
|
SQLiteCommand cmd = new SQLiteCommand(CreaA69DB(), conn);
|
|
int res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: ER01012", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CREATE TABLE [CreaA69DB])={0}", res) });
|
|
conn.Close();
|
|
conn.Dispose();
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: ER01010", "Errore in ATLib.Data.DBtools() durante il Check DB", ex });
|
|
DB_ok = false;
|
|
return;
|
|
} finally {
|
|
if ((conn != null) && (conn.State != System.Data.ConnectionState.Closed)) conn.Close();
|
|
}
|
|
// Riporto in memoria il DB per poter lavorare ad alta velocità.
|
|
try {
|
|
// Apro DB in memoria
|
|
if (cn == null) cn = new System.Data.SQLite.SQLiteConnection("data source=:memory:");
|
|
cn.Open();
|
|
// Creo tabelle in uso
|
|
SQLiteCommand cmd = new SQLiteCommand(CreaA69DB(false), cn);
|
|
int res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: ER01022", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CreaA69DB())={0}", res) });
|
|
// Attach DB A69DB su File
|
|
cmd = new SQLiteCommand(string.Format("ATTACH '{0}' AS A69DBfile", System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName)), cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: ER01026b", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS A69DBfile)", res) });
|
|
// Copio i dati
|
|
cmd = new SQLiteCommand("INSERT INTO [LinksLog] SELECT * FROM A69DBfile.LinksLog", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01001 - Nessun LinksLog riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Voti] SELECT * FROM A69DBfile.Voti", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01002 - Nessun Voti riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Racconti] SELECT * FROM A69DBfile.Racconti", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01003 - Nessun Racconti riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Autori] SELECT * FROM A69DBfile.Autori", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01004 - Nessun Autori riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Origini] SELECT * FROM A69DBfile.Origini", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01005 - Nessun Origini riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Tags] SELECT * FROM A69DBfile.Tags", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01006 - Nessun Tags riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Notes] SELECT * FROM A69DBfile.Notes", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01007 - Nessun Notes riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Trame] SELECT * FROM A69DBfile.Trame", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01008 - Nessun Trame riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Segnalini] SELECT * FROM A69DBfile.Segnalini", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Segnalini riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Users] SELECT * FROM A69DBfile.Users", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Users riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Aut] SELECT * FROM A69DBfile.Links_Rac_Aut", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Aut riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Not] SELECT * FROM A69DBfile.Links_Rac_Not", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Not riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Tag] SELECT * FROM A69DBfile.Links_Rac_Tag", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Tag riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Ori] SELECT * FROM A69DBfile.Links_Rac_Ori", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Ori riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Vot] SELECT * FROM A69DBfile.Links_Rac_Vot", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Vot riportato sul DB in memoria.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Sng] SELECT * FROM A69DBfile.Links_Rac_Sng", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Sng riportato sul DB in memoria.", res));
|
|
// Detach del DB su File
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: ER01020", "Errore in ATLib.Data.DBtools() durante il trasferimento in memoria del DB", ex });
|
|
DB_ok = false;
|
|
return;
|
|
}
|
|
// Memorizzo che il DB è stato correttamente caricato
|
|
DB_ok = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
public bool Dispose() {
|
|
object obj = new Object();
|
|
lock (obj) {
|
|
bool Res = false;
|
|
// Copio i valori creati: solo se il DB è OK:
|
|
if (!DB_ok) return Res;
|
|
try {
|
|
|
|
// Detach del DB su File
|
|
SQLiteCommand cmd = new SQLiteCommand("DETACH DATABASE A69DBfile", cn);
|
|
int res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: ER01026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(DETACH {0} AS A69DBfile)", res) });
|
|
|
|
// Elimino il file rinominandolo per backup
|
|
string FullNameDB = System.IO.Path.Combine(Cfg.Settings.PathDB,Cfg.Settings.DBName);
|
|
string FullNameBkDB = FullNameDB.Replace(".db","_BK_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".db");
|
|
System.IO.File.Move(FullNameDB, FullNameBkDB);
|
|
|
|
// Creo nuovo file vuoto su cui riportare i dati dalla memoria:
|
|
using (SQLiteConnection cnTmp = new SQLiteConnection(Cfg.Settings.DBConnectionString)) {
|
|
cnTmp.Open();
|
|
cmd = new SQLiteCommand(CreaA69DB(false), cnTmp);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 0) Logger.Log(new object[] { "Error Code: ER03011", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CreaDB(false, false))={0}", res) });
|
|
cnTmp.Close();
|
|
cnTmp.Dispose();
|
|
}
|
|
|
|
// Attach DB su File
|
|
cmd = new SQLiteCommand(string.Format("ATTACH '{0}' AS A69DBfile", System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName)), cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: ER03026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS A69DBfile)", res) });
|
|
|
|
// Copio i dati
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.LinksLog SELECT * FROM LinksLog", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03002 - Nessun LinksLog riportato sul file del DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Voti SELECT * FROM Voti", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03002 - Nessun Voti riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Racconti SELECT * FROM [Racconti]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03003 - Nessun Racconti riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Autori SELECT * FROM [Autori]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03004 - Nessun Autori riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Origini SELECT * FROM [Origini]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03005 - Nessun Origini riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Tags SELECT * FROM [Tags]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03006 - Nessun Tags riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Notes SELECT * FROM [Notes]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03007 - Nessun Notes riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Trame SELECT * FROM [Trame]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03008 - Nessun Trame riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Segnalini SELECT * FROM [Segnalini]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03009 - Nessun Segnalini riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Users SELECT * FROM [Users]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03010 - Nessun Users riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Aut SELECT * FROM [Links_Rac_Aut]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03011 - Nessun Links_Rac_Aut riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Not SELECT * FROM [Links_Rac_Not]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03012 - Nessun Links_Rac_Not riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Tag SELECT * FROM [Links_Rac_Tag]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03013 - Nessun Links_Rac_Tag riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Ori SELECT * FROM [Links_Rac_Ori]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03014 - Nessun Links_Rac_Ori riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Vot SELECT * FROM [Links_Rac_Vot]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03015 - Nessun Links_Rac_Vot riportato sul file DB.", res));
|
|
cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Sng SELECT * FROM [Links_Rac_Sng]", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res < 1) Logger.Information(string.Format("Info Code: IN03016 - Nessun Links_Rac_Sng riportato sul file DB.", res));
|
|
|
|
// Detach del DB su File
|
|
cmd = new SQLiteCommand("DETACH DATABASE A69DBfile", cn);
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: ER01026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(DETACH {0} AS A69DBfile)", res) });
|
|
|
|
Res = true;
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: ER03000", "Errore in ATLib.Data.Dispose() durante il trasferimento in memoria del DB", ex });
|
|
} finally {
|
|
if ((cn != null) && (cn.State != System.Data.ConnectionState.Closed)) cn.Close();
|
|
}
|
|
// Eseguo la compressione del DB su file per evitare di usare troppa memoria:
|
|
System.Data.SQLite.SQLiteConnection conn = null;
|
|
// Check esistenza del DB dell'applicazione, altrimenti ne creo uno nuovo:
|
|
try {
|
|
conn = new SQLiteConnection(Cfg.Settings.DBConnectionString);
|
|
conn.Open();
|
|
SQLiteCommand cmd = new SQLiteCommand("VACUUM", conn);
|
|
int res = cmd.ExecuteNonQuery();
|
|
if (res > 1) Logger.Log(new object[] { "Error Code: IN03027", string.Format("Possibile errore in ATLib.Data.Dispose() - cmd.ExecuteNonQuery(VACUUM)={0}", res) });
|
|
conn.Close();
|
|
conn.Dispose();
|
|
conn = null;
|
|
Res = Res && true;
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: ER03003", "Errore in ATLib.Data.Dispose() durante la compressione del DB", ex });
|
|
Res = false;
|
|
} finally {
|
|
try { if ((conn != null) && (conn.State != System.Data.ConnectionState.Closed)) conn.Close(); } catch { }
|
|
}
|
|
return Res;
|
|
}
|
|
}
|
|
|
|
private string CreaA69DB(bool FixedData = true) {
|
|
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
#region Definisco il DB dalla struttura sopra riportata
|
|
sb.AppendLine("------------------------------------------------------------------------------");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("-- Creazione delle tabelle principali:");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("CREATE TABLE [LinksLog] ( /* Tabella per salvare il lavoro fatto sui link */ ");
|
|
sb.AppendLine(" [LinkURL] TEXT UNIQUE NOT NULL PRIMARY KEY, /* URL del link */");
|
|
sb.AppendLine(" [FileName] TEXT UNIQUE NOT NULL, /* Nome del file su cui salvo quanto downloadato */ ");
|
|
sb.AppendLine(" [PlugID] TEXT NOT NULL, /* ID del plugin utilizzato per gestire questo particolare link */ ");
|
|
sb.AppendLine(" [Fields] INTEGER NOT NULL, /* Campo in cui salvo tutti i dati significativi sul link, separati fra loro da -|- */ ");
|
|
sb.AppendLine(" [Status] INTEGER NOT NULL, /* Stato della lavorazione */ ");
|
|
sb.AppendLine(" [LastUpdate] TIMESTAMP NOT NULL /* Timestamp all'ultimo aggiornamento del record */ ");
|
|
sb.AppendLine("); ");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("------------------------------------------------------------------------------");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" CREATE TABLE [Racconti] ( -- COMMENT ");
|
|
sb.AppendLine(" [IDrac] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [Title] TEXT NOT NULL DEFAULT 'Unknown', -- COMMENT 'Titolo del racconto' ");
|
|
sb.AppendLine(" [SubTitle] TEXT NOT NULL DEFAULT '', -- COMMENT 'Sottotitolo del racconto' ");
|
|
sb.AppendLine(" [Creato] TEXT NOT NULL DEFAULT '2000/12/31', -- COMMENT 'Data di creazione del racconto' ");
|
|
sb.AppendLine(" [Aggiornato] TEXT NOT NULL DEFAULT '2000/12/31' -- COMMENT 'Data dell''ultima modifica al racconto' ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Autori] ( -- COMMENT='Tabella con tutti gli Autori dei Racconti dell''archivio.' ");
|
|
sb.AppendLine(" [IDaut] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [Autore] TEXT NON NULL DEFAULT 'Unknown', -- COMMENT 'Nickname dell autore', ");
|
|
sb.AppendLine(" UNIQUE(Autore) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Notes] ( -- COMMENT 'Tabella per rappresentare tramite coppia key-value delle note da associare ad un racconto. Da utilizzare per salvare il link da cui ho downloadato il racconto, oppure l''eventuale riassunto, o altro.' ");
|
|
sb.AppendLine(" [IDnot] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo della nota' ");
|
|
sb.AppendLine(" [NKey] TEXT NON NULL DEFAULT 'Nota', -- COMMENT 'Nota Key: Identificativo del tipo di nota: Resume, Link, OriginalID, ...' ");
|
|
sb.AppendLine(" [NVal] TEXT NON NULL DEFAULT '', -- COMMENT 'Nota Value: valore della nota' ");
|
|
sb.AppendLine(" UNIQUE(NKey, NVal) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Origini] ( -- COMMENT 'Tabella con tutte le possibili Origini dei racconti.' ");
|
|
sb.AppendLine(" [IDori] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del origine' ");
|
|
sb.AppendLine(" [Origine] TEXT NON NULL DEFAULT 'Unknown', -- COMMENT 'Origine da cui ho preso il racconto' ");
|
|
sb.AppendLine(" UNIQUE(Origine) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Segnalini] ( -- COMMENT ");
|
|
sb.AppendLine(" [IDsng] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del segnalino' ");
|
|
sb.AppendLine(" [Linea] INTEGER NOT NULL DEFAULT 0, -- COMMENT 'Indice della linea che si vuole segnalare (0 inizio racconto)' ");
|
|
sb.AppendLine(" [Segnalino] TEXT NON NULL DEFAULT 'Read', -- COMMENT 'Descrizione del segnalino per semplice comprensione (Read pe ril segnalino automatico con il punto di lettura)' ");
|
|
sb.AppendLine(" UNIQUE(Linea, Segnalino) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Tags] ( -- COMMENT 'Tabella con tutte i tag che vogliamo associare ai Racconti.' ");
|
|
sb.AppendLine(" [IDtag] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del Tag' ");
|
|
sb.AppendLine(" [Tag] TEXT NON NULL COLLATE NOCASE, -- COMMENT 'Nome descrittivo del Tag' ");
|
|
sb.AppendLine(" UNIQUE(Tag) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Trame] ( -- COMMENT 'Tabella con tutte le Trame dei Racconti.' ");
|
|
sb.AppendLine(" [IDtra] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo della trama' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NON NULL, -- COMMENT 'Identificativo del racconto a cui la trama corrisponde (univoco perchè solo una trama per racconto). Rappresenta la relazione 1-1 fra Racconti-Trame' ");
|
|
sb.AppendLine(" [Trama] TEXT NON NULL, -- COMMENT 'Trama del racconto' ");
|
|
sb.AppendLine(" UNIQUE(IDrac), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Voti] ( -- COMMENT 'Tabella con tutti i possibili Voti associabili ai Racconti.' ");
|
|
sb.AppendLine(" [IDvot] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del voto' ");
|
|
sb.AppendLine(" [Rating] INTEGER CHECK (Rating>-1 AND Rating<11), -- COMMENT 'Valore del voto per statistiche' ");
|
|
sb.AppendLine(" [Voto] TEXT NON NULL COLLATE NOCASE, -- COMMENT 'Voto da attribuire ad un racconto' ");
|
|
sb.AppendLine(" UNIQUE(Voto) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Users] ( -- COMMENT 'Elenco degli utenti abilitati della web application' ");
|
|
sb.AppendLine(" [IDusr] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo dell''utente' ");
|
|
sb.AppendLine(" [Username] TEXT NOT NULL, -- COMMENT 'Username di identificazione dell''utente. Viene scelto dall''utente stesso al momento della registrazione' ");
|
|
sb.AppendLine(" [Password] TEXT NOT NULL, -- COMMENT 'Hash della password scelta dall''utente' ");
|
|
sb.AppendLine(" [Level] INTEGER NOT NULL DEFAULT 0, -- COMMENT 'Livello dell''utente nella web application. Di default è posto a 0 e solo l''amministratore può variarlo' ");
|
|
sb.AppendLine(" UNIQUE(Username) ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" -- Creazione delle tabelle per rappresentare i link fra i record ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" CREATE TABLE [Links_Rac_Aut] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e i propri Autori.' ");
|
|
sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Autori' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [IDaut] INTEGER NOT NULL, -- COMMENT 'Identificativo dell''autore' ");
|
|
sb.AppendLine(" UNIQUE(IDrac, IDaut), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDaut`) REFERENCES `Autori`(`IDaut`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE Links_Rac_Not ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e le note (coppie key-Value).' ");
|
|
sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Notes' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [IDnot] INTEGER NOT NULL, -- COMMENT 'Identificativo della nota' ");
|
|
sb.AppendLine(" UNIQUE(IDrac, IDnot), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDnot`) REFERENCES `Notes`(`IDnot`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Links_Rac_Tag] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e le propietà.' ");
|
|
sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Tags' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [IDtag] INTEGER NOT NULL, -- COMMENT 'Identificativo della propietà' ");
|
|
sb.AppendLine(" UNIQUE(IDrac, IDtag), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDtag`) REFERENCES `Tags`(`IDtag`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Links_Rac_Ori] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-1 fra i Racconti e le origini.' ");
|
|
sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Origini' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [IDori] INTEGER NOT NULL, -- COMMENT 'Identificativo dell'' origine' ");
|
|
sb.AppendLine(" UNIQUE(IDrac, IDori), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDori`) REFERENCES `Origini`(`IDori`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Links_Rac_Vot] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-1 fra i Racconti e i voti.' ");
|
|
sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Voti' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [IDvot] INTEGER NOT NULL, -- COMMENT 'Identificativo del voto' ");
|
|
sb.AppendLine(" UNIQUE(IDrac), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDvot`) REFERENCES `Voti`(`IDvot`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" CREATE TABLE [Links_Rac_Sng] ( -- COMMENT 'Tabella per rappresentare la relazione 1-Molti fra i Racconti e i segnalini.' ");
|
|
sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Segnalini' ");
|
|
sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' ");
|
|
sb.AppendLine(" [IDsng] INTEGER NOT NULL, -- COMMENT 'Identificativo del segnalino' ");
|
|
sb.AppendLine(" UNIQUE(IDsng), ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, ");
|
|
sb.AppendLine(" FOREIGN KEY(`IDsng`) REFERENCES `Segnalini`(`IDsng`) ON DELETE CASCADE ON UPDATE CASCADE ");
|
|
sb.AppendLine(" ); ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" -- Creazione degli indici: ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" CREATE INDEX IDX_Voti ON Voti ( Voto COLLATE NOCASE ); ");
|
|
if (FixedData) {
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" -- Inserimento dei dati iniziali noti: ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" INSERT INTO `origini` (`IDori`, `Origine`) VALUES ");
|
|
sb.AppendLine(" (1, 'Unknown'), ");
|
|
sb.AppendLine(" (2, 'Autocreazione'), ");
|
|
sb.AppendLine(" (3, 'A69'), ");
|
|
sb.AppendLine(" (4, 'eRac'), ");
|
|
sb.AppendLine(" (5, 'Mil'); ");
|
|
sb.AppendLine(" INSERT INTO `users` (`IDusr`, `Username`, `Password`, `Level`) VALUES ");
|
|
sb.AppendLine(" (1, 'root', 'e10adc3949ba59abbe56e057f20f883e', 9), ");
|
|
sb.AppendLine(" (2, 'Mrk', 'ABC', 8), ");
|
|
sb.AppendLine(" (3, 'reader', 'A', 5), ");
|
|
sb.AppendLine(" (4, 'guest', 'A', 0); ");
|
|
sb.AppendLine(" INSERT INTO `voti` (`IDvot`, `Rating`, `Voto`) VALUES ");
|
|
sb.AppendLine(" (0, 0, 'Non Letto'), ");
|
|
sb.AppendLine(" (1, 1, 'Da Cancellare'), ");
|
|
sb.AppendLine(" (2, 2, 'Pessimo'), ");
|
|
sb.AppendLine(" (3, 3, 'Brutto'), ");
|
|
sb.AppendLine(" (4, 4, 'Scarso'), ");
|
|
sb.AppendLine(" (5, 5, 'Insufficiente'), ");
|
|
sb.AppendLine(" (6, 6, 'Sufficiente'), ");
|
|
sb.AppendLine(" (7, 7, 'Carino'), ");
|
|
sb.AppendLine(" (8, 8, 'Bello'), ");
|
|
sb.AppendLine(" (9, 9, 'Ottimo'), ");
|
|
sb.AppendLine(" (10, 10, 'Da Collezione'); ");
|
|
}
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" -- Creazione dei trigger: ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Racconti: --- ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Racconti_Delete ");
|
|
sb.AppendLine(" AFTER DELETE ON Racconti ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" ");
|
|
sb.AppendLine(" DELETE FROM Links_Rac_Aut WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Links_Rac_Ori WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Links_Rac_Tag WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Links_Rac_Not WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Links_Rac_Vot WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Links_Rac_Sng WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Trame WHERE IDrac=OLD.IDrac; ");
|
|
sb.AppendLine(" DELETE FROM Notes WHERE IDnot NOT IN(SELECT Notes.IDnot FROM Notes, Links_Rac_not WHERE Notes.IDnot = Links_Rac_Not.IDnot); ");
|
|
sb.AppendLine(" DELETE FROM Segnalini WHERE IDsng NOT IN(SELECT Segnalini.IDsng FROM Segnalini, Links_Rac_Sng WHERE Segnalini.IDsng = Links_Rac_Sng.IDsng); ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Racconti_Insert ... END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Racconti_Update ... END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Autori: --- ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Autori_Delete ");
|
|
sb.AppendLine(" BEFORE DELETE ON Autori ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Aut WHERE IDaut=OLD.IDaut) > 0 ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore ancora riferito a dei racconti.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Autori_Insert ... END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Autori_Update ... END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Origini: --- ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Origini_Delete ");
|
|
sb.AppendLine(" BEFORE DELETE ON Origini ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Ori WHERE IDori=OLD.IDori) > 0 ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine ancora riferita a dei racconti.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Origini_Insert_Origine ... END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Origini_Update_Origine ... END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Tags: --- ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Tags_Delete ");
|
|
sb.AppendLine(" BEFORE DELETE ON Tags ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Tag WHERE IDtag=OLD.IDtag) > 0 ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà ancora riferita a dei racconti.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Tags_Insert ... END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Tags_Update ... END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Notes: --- ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Notes_Delete ");
|
|
sb.AppendLine(" BEFORE DELETE ON Notes ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Not WHERE IDnot=OLD.IDnot) > 0 ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota ancora riferita a dei racconti.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Notes_Insert ... END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Notes_Update ... END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Trame: --- ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Trama_Delete ... END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Trama_Insert ");
|
|
sb.AppendLine(" BEFORE INSERT ON Trame ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto associato alla trama non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Trama_Update_Trama ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDrac ON Trame ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto associato alla trama non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Segnalini: --- ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Segnalini_Delete ");
|
|
sb.AppendLine(" BEFORE DELETE ON Segnalini ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Sng WHERE IDsng=OLD.IDsng) > 0 ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino ancora riferito a dei racconti.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Segnalini_Insert ... END; ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Segnalini_Update ... END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Aut: --- ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Aut_Delete ... END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Insert ");
|
|
sb.AppendLine(" BEFORE INSERT ON Links_Rac_Aut ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all autore, non presente in ATDB.') ");
|
|
sb.AppendLine(" WHEN (SELECT IDaut from Autori WHERE IDaut=NEW.IDaut) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Update_a ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Aut ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all autore, non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Update_b ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDaut ON Links_Rac_Aut ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDaut from Autori WHERE IDaut=NEW.IDaut) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Ori: --- ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Ori_Delete ... END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Insert ");
|
|
sb.AppendLine(" BEFORE INSERT ON Links_Rac_Ori ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all origine, non presente in ATDB.') ");
|
|
sb.AppendLine(" WHEN (SELECT IDori from Origini WHERE IDori=NEW.IDori) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Update_a ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Ori ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all origine, non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Update_b ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDori ON Links_Rac_Ori ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDori from Origini WHERE IDori=NEW.IDori) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Tag: --- ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Tag_Delete ... END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Insert ");
|
|
sb.AppendLine(" BEFORE INSERT ON Links_Rac_Tag ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla propietà, non presente in ATDB.') ");
|
|
sb.AppendLine(" WHEN (SELECT IDtag from Tags WHERE IDtag=NEW.IDtag) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Update_a ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Tag ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla propietà, non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Update_b ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDtag ON Links_Rac_Tag ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDtag from Tags WHERE IDtag=NEW.IDtag) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Not: --- ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Not_Delete ... END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Insert ");
|
|
sb.AppendLine(" BEFORE INSERT ON Links_Rac_Not ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla nota, non presente in ATDB.') ");
|
|
sb.AppendLine(" WHEN (SELECT IDnot from Notes WHERE IDnot=NEW.IDnot) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Update_a ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Not ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla nota, non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Update_b ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDnot ON Links_Rac_Not ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDnot from Notes WHERE IDnot=NEW.IDnot) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Sng: --- ");
|
|
sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Sng_Delete ... END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Insert ");
|
|
sb.AppendLine(" BEFORE INSERT ON Links_Rac_Sng ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato al Segnalino, non presente in ATDB.') ");
|
|
sb.AppendLine(" WHEN (SELECT IDsng from Segnalini WHERE IDsng=NEW.IDsng) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Update_a ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Sng ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all Segnalino, non presente in ATDB.') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Update_b ");
|
|
sb.AppendLine(" BEFORE UPDATE OF IDsng ON Links_Rac_Sng ");
|
|
sb.AppendLine(" BEGIN ");
|
|
sb.AppendLine(" SELECT CASE ");
|
|
sb.AppendLine(" WHEN (SELECT IDsng from Segnalini WHERE IDsng=NEW.IDsng) IS NULL ");
|
|
sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino, da associare al racconto, non presente in ATDB') ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" END; ");
|
|
sb.AppendLine(" CREATE VIEW Autore_Browser_Autori AS ");
|
|
sb.AppendLine(" SELECT ");
|
|
sb.AppendLine(" IDaut, ");
|
|
sb.AppendLine(" Autore, ");
|
|
sb.AppendLine(" ( ");
|
|
sb.AppendLine(" SELECT COUNT(IDaut) ");
|
|
sb.AppendLine(" FROM Links_Rac_Aut ");
|
|
sb.AppendLine(" WHERE Links_Rac_Aut.IDaut = Autori.IDaut ");
|
|
sb.AppendLine(" ) AS Num, ");
|
|
sb.AppendLine(" ( ");
|
|
sb.AppendLine(" SELECT AVG(Voti.IDvot) ");
|
|
sb.AppendLine(" FROM Links_Rac_Aut, ");
|
|
sb.AppendLine(" Links_Rac_Vot, ");
|
|
sb.AppendLine(" Voti ");
|
|
sb.AppendLine(" WHERE Links_Rac_Aut.IDaut = Autori.IDaut AND ");
|
|
sb.AppendLine(" Links_Rac_Vot.IDrac = Links_Rac_Aut.IDrac AND ");
|
|
sb.AppendLine(" Voti.IDvot = Links_Rac_Vot.IDvot AND ");
|
|
sb.AppendLine(" Voti.IDvot <> 0 ");
|
|
sb.AppendLine(" ) AS Rate ");
|
|
sb.AppendLine(" FROM Autori ");
|
|
sb.AppendLine(" ORDER BY Num DESC, Rate DESC; ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" -- Inserimento delle viste: ");
|
|
sb.AppendLine(" -- ");
|
|
sb.AppendLine(" CREATE VIEW Tag_Browser_Tags AS ");
|
|
sb.AppendLine(" SELECT ");
|
|
sb.AppendLine(" IDtag, ");
|
|
sb.AppendLine(" Tag, ");
|
|
sb.AppendLine(" ( ");
|
|
sb.AppendLine(" SELECT COUNT(IDtag) ");
|
|
sb.AppendLine(" FROM Links_Rac_Tag ");
|
|
sb.AppendLine(" WHERE Links_Rac_Tag.IDtag = Tags.IDtag ");
|
|
sb.AppendLine(" ) AS Num, ");
|
|
sb.AppendLine(" ( ");
|
|
sb.AppendLine(" SELECT AVG(Voti.IDvot) ");
|
|
sb.AppendLine(" FROM Links_Rac_Tag, ");
|
|
sb.AppendLine(" Links_Rac_Vot, ");
|
|
sb.AppendLine(" Voti ");
|
|
sb.AppendLine(" WHERE Links_Rac_Tag.IDtag = Tags.IDtag AND ");
|
|
sb.AppendLine(" Links_Rac_Vot.IDrac = Links_Rac_Tag.IDrac AND ");
|
|
sb.AppendLine(" Voti.IDvot = Links_Rac_Vot.IDvot AND ");
|
|
sb.AppendLine(" Voti.IDvot <> 0 ");
|
|
sb.AppendLine(" ) AS Rate ");
|
|
sb.AppendLine(" FROM Tags ");
|
|
sb.AppendLine(" ORDER BY Num DESC, Rate DESC; ");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("-- ");
|
|
sb.AppendLine("------------------------------------------------------------------------------");
|
|
#endregion
|
|
|
|
return sb.ToString();
|
|
|
|
}
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// Ritorna lo stato di un link
|
|
/// </summary>
|
|
/// <param name="url">URL identificativo del link</param>
|
|
/// <returns>Stato del link nel DB (ToDownload se link non presente nel DB)</returns>
|
|
public eLinkState GetStateByURL(string url) {
|
|
lock (objLock) {
|
|
try {
|
|
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "SELECT Status FROM LinksLog WHERE LinkURL=@LinkURL LIMIT 1";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@LinkURL";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "LinkURL";
|
|
cmd.Parameters.Add(param);
|
|
cmd.Parameters[0].Value = url;
|
|
object obj = cmd.ExecuteScalar();
|
|
if (obj != null) return (eLinkState)((long)obj);
|
|
return eLinkState.ToDownload;
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: DB06521", string.Format("MyDownloader.DBTools.GetStateByURL({0})", url), ex });
|
|
return eLinkState.Error;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifica se il link è già presente nel DB
|
|
/// </summary>
|
|
/// <param name="url">URL del link da testare</param>
|
|
/// <param name="timeOffset">Offset temporale per la verifica (0 per l'intero DB)</param>
|
|
/// <returns>True se URL presente, false altrimenti</returns>
|
|
public bool IsPresent(string url, int timeOffset = 0) {
|
|
lock (objLock) {
|
|
try {
|
|
string query = timeOffset != 0 ?
|
|
"SELECT Status FROM LinksLog WHERE LinkURL=@LinkURL AND LastUpdate>=@LastUpdate LIMIT 1" :
|
|
"SELECT Status FROM LinksLog WHERE LinkURL=@LinkURL LIMIT 1" ;
|
|
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = query;
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@LinkURL";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "LinkURL";
|
|
cmd.Parameters.Add(param);
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@LastUpdate";
|
|
param.DbType = global::System.Data.DbType.DateTime;
|
|
param.SourceColumn = "LastUpdate";
|
|
cmd.Parameters.Add(param);
|
|
cmd.Parameters[0].Value = url;
|
|
cmd.Parameters[1].Value = DateTime.Now.AddHours(timeOffset);
|
|
object obj = cmd.ExecuteScalar();
|
|
if (obj != null) return true;
|
|
return false;
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: DB06521", string.Format("MyDownloader.DBTools.GetStateByURL({0})", url), ex });
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Aggiorna il log relativo al link nel DB.
|
|
/// </summary>
|
|
/// <returns>True se tutto ok; False altrimenti.</returns>
|
|
public bool LinkLog(iLink link) {
|
|
lock (objLock) {
|
|
return LinkLogUpdtate(link);
|
|
}
|
|
}
|
|
private bool LinkLogUpdtate(iLink link) {
|
|
// object obj = new Object();
|
|
// lock (obj) {
|
|
// Cancello riga (se non presente, non fa nulla)
|
|
// Inserisco riga
|
|
bool Res = false;
|
|
try {
|
|
// Cancello il link anche se non presente
|
|
System.Data.SQLite.SQLiteCommand cmd = new SQLiteCommand(string.Format("DELETE FROM [LinksLog] WHERE [LinkURL]='{0}'", link.URL), cn);
|
|
int res = cmd.ExecuteNonQuery();
|
|
cmd = null;
|
|
// Inserisco il link come se fosse nuovo
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "INSERT INTO [LinksLog] VALUES(@LinkURL, @FileName, @PlugID, @Fields, @Status, @LastUpdate)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@LinkURL";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "LinkURL";
|
|
cmd.Parameters.Add(param);
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@FileName";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "FileName";
|
|
cmd.Parameters.Add(param);
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@PlugID";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "PlugID";
|
|
cmd.Parameters.Add(param);
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@Fields";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "Fields";
|
|
cmd.Parameters.Add(param);
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@Status";
|
|
param.DbType = global::System.Data.DbType.Int32;
|
|
param.SourceColumn = "Status";
|
|
cmd.Parameters.Add(param);
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@LastUpdate";
|
|
param.DbType = global::System.Data.DbType.DateTime;
|
|
param.SourceColumn = "LastUpdate";
|
|
cmd.Parameters.Add(param);
|
|
cmd.Parameters[0].Value = link.URL;
|
|
cmd.Parameters[1].Value = link.FileName;
|
|
cmd.Parameters[2].Value = link.ID;
|
|
cmd.Parameters[3].Value = link.Fields;
|
|
cmd.Parameters[4].Value = link.Status;
|
|
cmd.Parameters[5].Value = DateTime.Now;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) {
|
|
Logger.Log(new object[] { "Error Code: DB06010", string.Format("MyDownloader.DBTools.LinkLogUpdtate({0})={1}", link, res), link.ToString() });
|
|
Res = false;
|
|
} else {
|
|
Res = true;
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Log(new object[] { "Error Code: DB06001", string.Format("MyDownloader.DBTools.LinkLogUpdtate({0})", link), link.ToString(), ex });
|
|
return false;
|
|
} finally {
|
|
//if ((cn != null) && (cn.State != System.Data.ConnectionState.Closed)) cn.Close();
|
|
}
|
|
return Res;
|
|
// } // lock (obj)
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// Seleziona dal DB il racconto richiesto
|
|
/// </summary>
|
|
/// <param name="IDrac">Identificativo del racconto desiderato</param>
|
|
/// <returns>Ritorna il racconto estratto dal DB</returns>
|
|
public cRac GetRacById_Orig(long IDrac) {
|
|
lock (objLock) {
|
|
cRac rac = null;
|
|
List<string> tmp = null;
|
|
try {
|
|
|
|
// Creo nuovo racconto vuoto:
|
|
rac = new cRac();
|
|
|
|
#region Estraggo i dati dalla tabella 'Racconti':
|
|
|
|
// Query per interrogare la tabella 'Racconti':
|
|
SQLiteCommand SelRac = new System.Data.SQLite.SQLiteCommand();
|
|
SelRac.Connection = cn;
|
|
SelRac.CommandText = "SELECT * FROM Racconti WHERE IDrac=@IDrac";
|
|
SelRac.CommandType = System.Data.CommandType.Text;
|
|
System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelRac.Parameters["@IDrac"].Value = IDrac;
|
|
SelRac.Parameters.Add(param);
|
|
SQLiteDataReader rdr = SelRac.ExecuteReader();
|
|
bool res = rdr.Read();
|
|
if (res == false) {
|
|
rdr.Close();
|
|
rdr = null;
|
|
Logger.Information(String.Format("Attenzione, il racconto richiesto ({0}), non è stasto trovato.", IDrac.ToString()));
|
|
return new cRac("Errore", "Attenzione, il racconto richiesto non è stato trovato.");
|
|
}
|
|
rac.IDrac = (long)(rdr["IDrac"]);
|
|
if (rac.IDrac != IDrac) throw new Exception("Attenzione trovato ID diverso da quello richiesto");
|
|
rac.Title = rdr["Title"] as string;
|
|
rac.SubTitle = rdr["SubTitle"] as string;
|
|
//rac.Creato = DateTime.Parse(rdr["Creato"].ToString());
|
|
rac.Creato = DateTime.Parse(rdr["Creato"] as string);
|
|
//rac.Updated = DateTime.Parse(rdr["Aggiornato"].ToString());
|
|
rac.Updated = DateTime.Parse(rdr["Aggiornato"].ToString());
|
|
rdr.Close();
|
|
rdr = null;
|
|
|
|
#endregion
|
|
|
|
#region Estraggo i dati dalla tabella 'Trame':
|
|
|
|
// Query per interrogare la tabella 'Trame':
|
|
SQLiteCommand SelTra = new System.Data.SQLite.SQLiteCommand();
|
|
SelTra.Connection = cn;
|
|
SelTra.CommandText = "SELECT Trama FROM Trame WHERE IDrac=@IDrac";
|
|
SelTra.CommandType = System.Data.CommandType.Text;
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelTra.Parameters["@IDrac"].Value = IDrac;
|
|
SelTra.Parameters.Add(param);
|
|
rdr = SelTra.ExecuteReader();
|
|
res = rdr.Read();
|
|
rac.Trama = rdr["Trama"] as string;
|
|
rdr.Close();
|
|
rdr = null;
|
|
|
|
#endregion
|
|
|
|
#region Estraggo i dati dalla tabella 'Autori':
|
|
|
|
// Query per interrogare la tabella 'Autori':
|
|
SQLiteCommand SelAut = new System.Data.SQLite.SQLiteCommand();
|
|
SelAut.Connection = cn;
|
|
SelAut.CommandText = "SELECT Autori.Autore AS Autore FROM Autori, Links_Rac_Aut WHERE Autori.IDaut=Links_Rac_Aut.IDaut AND Links_Rac_Aut.IDrac=@IDrac GROUP BY Autori.Autore";
|
|
SelAut.CommandType = System.Data.CommandType.Text;
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelAut.Parameters["@IDrac"].Value = IDrac;
|
|
SelAut.Parameters.Add(param);
|
|
rdr = SelAut.ExecuteReader();
|
|
if (rdr.HasRows) {
|
|
tmp = new List<string>();
|
|
while (rdr.Read()) {
|
|
tmp.Add(rdr["Autore"] as string);
|
|
}
|
|
tmp.Sort();
|
|
rac.Autori = tmp;
|
|
tmp = null;
|
|
}
|
|
rdr.Close();
|
|
rdr = null;
|
|
#endregion
|
|
|
|
#region Estraggo i dati dalla tabella 'Tags':
|
|
|
|
// Query per interrogare la tabella 'Tags':
|
|
SQLiteCommand SelTag = new System.Data.SQLite.SQLiteCommand();
|
|
SelTag.Connection = cn;
|
|
SelTag.CommandText = "SELECT Tags.Tag as Tag FROM Tags, Links_Rac_Tag WHERE Tags.IDtag=Links_Rac_Tag.IDtag AND Links_Rac_Tag.IDrac=@IDrac";
|
|
SelTag.CommandType = System.Data.CommandType.Text;
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelTag.Parameters["@IDrac"].Value = IDrac;
|
|
SelTag.Parameters.Add(param);
|
|
rdr = SelTag.ExecuteReader();
|
|
if (rdr.HasRows) {
|
|
tmp = new List<string>();
|
|
while (rdr.Read()) {
|
|
tmp.Add(rdr["Tag"] as string);
|
|
}
|
|
tmp.Sort();
|
|
rac.Tags = tmp;
|
|
tmp = null;
|
|
}
|
|
rdr.Close();
|
|
rdr = null;
|
|
|
|
#endregion
|
|
|
|
#region Estraggo i dati dalla tabella 'Origini':
|
|
|
|
// Query per interrogare la tabella 'Origini':
|
|
SQLiteCommand SelOri = new System.Data.SQLite.SQLiteCommand();
|
|
SelOri.Connection = cn;
|
|
SelOri.CommandText = "SELECT Origini.Origine as Origine FROM Origini, Links_Rac_Ori WHERE Origini.IDori=Links_Rac_Ori.IDori AND Links_Rac_Ori.IDrac=@IDrac";
|
|
SelOri.CommandType = System.Data.CommandType.Text;
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelOri.Parameters["@IDrac"].Value = IDrac;
|
|
SelOri.Parameters.Add(param);
|
|
rdr = SelOri.ExecuteReader();
|
|
if (rdr.HasRows) {
|
|
tmp = new List<string>();
|
|
while (rdr.Read()) {
|
|
tmp.Add(rdr["Origine"] as string);
|
|
}
|
|
tmp.Sort();
|
|
rac.Origini = tmp;
|
|
tmp = null;
|
|
}
|
|
rdr.Close();
|
|
rdr = null;
|
|
#endregion
|
|
|
|
#region Estraggo i dati dalla tabella 'Notes':
|
|
|
|
// Query per interrogare la tabella 'Notes':
|
|
SQLiteCommand SelNot = new System.Data.SQLite.SQLiteCommand();
|
|
SelNot.Connection = cn;
|
|
SelNot.CommandText = "SELECT Notes.NKey AS NKey, Notes.NVal AS NVal FROM Notes, Links_Rac_Not WHERE Notes.IDnot=Links_Rac_Not.IDnot AND Links_Rac_Not.IDrac=@IDrac";
|
|
SelNot.CommandType = System.Data.CommandType.Text;
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelNot.Parameters["@IDrac"].Value = IDrac;
|
|
SelNot.Parameters.Add(param);
|
|
rdr = SelNot.ExecuteReader();
|
|
rac.Notes = new List<cNota>();
|
|
if (rdr.HasRows) {
|
|
while (rdr.Read()) {
|
|
rac.Notes.Add(new cNota((rdr["NKey"] as string), (rdr["NVal"] as string)));
|
|
}
|
|
}
|
|
rdr.Close();
|
|
rdr = null;
|
|
|
|
#endregion
|
|
|
|
|
|
#region Estraggo i dati dalla tabella 'Voti':
|
|
|
|
// Query per interrogare la tabella 'Voti':
|
|
SQLiteCommand SelVot = new System.Data.SQLite.SQLiteCommand();
|
|
SelVot.Connection = cn;
|
|
SelVot.CommandText = "SELECT Voti.Voto as Voto FROM Voti, Links_Rac_Vot WHERE Voti.IDvot=Links_Rac_Vot.IDvot AND Links_Rac_Vot.IDrac=@IDrac";
|
|
SelVot.CommandType = System.Data.CommandType.Text;
|
|
param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@IDrac";
|
|
param.DbType = global::System.Data.DbType.Int64;
|
|
param.SourceColumn = "IDrac";
|
|
param.Value = IDrac; //SelTag.Parameters["@IDrac"].Value = IDrac;
|
|
SelVot.Parameters.Add(param);
|
|
rdr = SelVot.ExecuteReader();
|
|
res = rdr.Read();
|
|
rac.Voto = rdr["Voto"] as string;
|
|
rdr.Close();
|
|
rdr = null;
|
|
|
|
#endregion
|
|
|
|
rac.Validate();
|
|
return rac;
|
|
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00080", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
rac = null;
|
|
}
|
|
return rac;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Importa il racconto passato sul DB
|
|
/// </summary>
|
|
/// <param name="rac">Racconto d aimportare</param>
|
|
/// <returns>IDrac se tutto ok, -1 se importazione abortita per errore, -10 se importazione abortita per duplicato, ....</returns>
|
|
public int ImportRac(cRac rac) {
|
|
lock (objLock) {
|
|
// Inizializzo le variabili che occorrono
|
|
int res = 0;
|
|
long IDvot = 0;
|
|
long IDrac = 0;
|
|
long IDtag = 0;
|
|
long IDaut = 0;
|
|
long IDori = 0;
|
|
long IDnot = 0;
|
|
try {
|
|
SQLiteCommand cmd = null;
|
|
|
|
#region Verifico se il racconto da inserire è un duplicato
|
|
{
|
|
// Per ora definisco un racconto duplicato quando ha lo stesso titolo e la stessa trama.
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "SELECT IDrac FROM Trame WHERE Trama=@Trama LIMIT 1";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter();
|
|
param.ParameterName = "@Trama";
|
|
param.DbType = global::System.Data.DbType.String;
|
|
param.SourceColumn = "Trama";
|
|
param.Value = rac.Trama;
|
|
cmd.Parameters.Add(param);
|
|
object RacID = cmd.ExecuteScalar();
|
|
if (RacID != null) {
|
|
IDrac = (long)RacID;
|
|
if (IDrac > 0) {
|
|
|
|
#region Unione del duplicato:
|
|
{
|
|
|
|
// Ricavo il racconto originale su cui voglio unificare il duplicato:
|
|
cRac racOrig = GetRacById(IDrac);
|
|
|
|
// Title & SubTitle
|
|
// Se titoli diversi, metto tutti e due i titoli suddividendoli e numerandoli:
|
|
if (racOrig.Title != rac.Title) {
|
|
racOrig.Title = string.Format("1 -> {0} -|- 2 -> {1}", racOrig.Title, rac.Title);
|
|
}
|
|
if (racOrig.SubTitle != rac.SubTitle) {
|
|
racOrig.SubTitle = string.Format("1 -> {0} -|- 2 -> {1}", racOrig.SubTitle, rac.SubTitle);
|
|
}
|
|
|
|
// Creato
|
|
// Mantengo come data di creazione quella più antica delle due:
|
|
if (rac.Creato < racOrig.Creato) racOrig.Creato = rac.Creato;
|
|
|
|
// Updated
|
|
// Mantengo come data di aggiornamento, quella più recente delle due:
|
|
if (rac.Updated > racOrig.Updated) racOrig.Updated = rac.Updated;
|
|
|
|
// Autors
|
|
// Unisco tutti gli autori
|
|
if (racOrig.Autori == null) {
|
|
racOrig.Autori = rac.Autori;
|
|
} else {
|
|
foreach (string autore in rac.Autori) {
|
|
if (!racOrig.Autori.Contains(autore)) {
|
|
racOrig.Autori.Add(autore);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Voto
|
|
// Se uno dei due è "Non Letto" mantengo l'altro voto, altrimenti se non sono uguali lo segnalo.
|
|
if (rac.Voto != racOrig.Voto) {
|
|
if (racOrig.Voto == "Non Letto") {
|
|
racOrig.Voto = rac.Voto;
|
|
} else {
|
|
Logger.FailureAudit("ATTENZIONE UNIONE DI UN RACCONTO DUPLICATO; TROVATO VOTAZIONI DISCORDANTI");
|
|
return -222;
|
|
}
|
|
}
|
|
|
|
// Origine
|
|
// Unisco le varie origini raccogliendole tutte
|
|
if (racOrig.Origini == null) {
|
|
racOrig.Origini = rac.Origini;
|
|
} else {
|
|
foreach (string origine in rac.Origini) {
|
|
if (!racOrig.Origini.Contains(origine)) {
|
|
racOrig.Origini.Add(origine);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Tags
|
|
// Unisco le varie tag raccogliendole tutte
|
|
if (racOrig.Tags == null) {
|
|
racOrig.Tags = rac.Tags;
|
|
} else {
|
|
foreach (string tag in rac.Tags) {
|
|
if (!racOrig.Tags.Contains(tag)) {
|
|
racOrig.Tags.Add(tag);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Notes
|
|
// Per ora inserisco tutte le note ma devo fare attenzione ai duplicati o il DB mi dà errore:
|
|
if (racOrig.Notes == null) {
|
|
racOrig.Notes = rac.Notes;
|
|
} else {
|
|
foreach (cNota nota in rac.Notes) {
|
|
bool duplicata = false;
|
|
// Verifico se la key è già presente:
|
|
foreach (cNota notaOrig in racOrig.Notes) {
|
|
if (nota.Key == notaOrig.Key) {
|
|
if (nota.Description == notaOrig.Description) {
|
|
duplicata = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!duplicata) racOrig.Notes.Add(nota);
|
|
}
|
|
}
|
|
|
|
// Avviso di quanto fatto:
|
|
Logger.Warning("ATTENZIONE UNIONE DI UN RACCONTO DUPLICATO SUL RACCONTO: " + racOrig.strIDrac + " -> " + racOrig.fullTitle);
|
|
|
|
// Eseguo l'update delle informazioni sul DB:
|
|
return UpdateRac(racOrig);
|
|
}
|
|
#endregion
|
|
|
|
}
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
// Start a local transaction
|
|
SQLiteTransaction myTrans = cn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
|
|
|
|
|
|
#region 10) Inserisco sulla tabella Racconti
|
|
try {
|
|
// Creo il nuovo record
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "INSERT INTO [Racconti]([Title], [SubTitle], [Creato], [Aggiornato]) VALUES (@Title, @SubTitle, @Creato, @Aggiornato)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@Title", System.Data.DbType.String).Value = rac.Title;
|
|
cmd.Parameters.Add("@SubTitle", System.Data.DbType.String).Value = rac.SubTitle;
|
|
cmd.Parameters.Add("@Creato", System.Data.DbType.String).Value = rac.strCreato;
|
|
cmd.Parameters.Add("@Aggiornato", System.Data.DbType.String).Value = rac.strUpdated;
|
|
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -10; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDrac = (long)cmd.ExecuteScalar();
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00009", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -10;
|
|
}
|
|
#endregion
|
|
|
|
#region 20) Inserisco sulla tabella Trama
|
|
try {
|
|
// Creo il nuovo record
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "INSERT INTO [Trame]([IDrac], [Trama]) VALUES (@IDrac, @Trama)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac;
|
|
cmd.Parameters.Add("@Trama", System.Data.DbType.String).Value = rac.Trama;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -20; }
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00010", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -20;
|
|
}
|
|
#endregion
|
|
|
|
#region 30) Inserisco sulla tabella Links_Rac_Vot
|
|
try {
|
|
// Decodifico il voto
|
|
// ToDo: Ricavare il IDvot dal Voto e non assegnarlo d'ufficio.
|
|
IDvot = 0; // Si sa già che il voto "Non Letto" ha indice 1 perchè fa parte dei valori predefiniti.
|
|
// Creo il nuovo record
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Vot]([IDrac], [IDvot]) VALUES (@IDrac, @IDvot)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac;
|
|
cmd.Parameters.Add("@IDvot", System.Data.DbType.Int64).Value = IDvot;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -30; }
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00011", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -30;
|
|
}
|
|
#endregion
|
|
|
|
#region 40) Inserisco i Tags (edito tabelle: Tags, Links_Rac_Tag)
|
|
try {
|
|
//foreach (string tag in rac.Tags) {
|
|
for (int i = 0; i < rac.Tags.Count; i++) {
|
|
// Ricavo l'ID del tag o lo inserisco sul DB:
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "SELECT IDtag FROM [Tags] WHERE [Tag]=@Tag";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = rac.Tags[i];
|
|
try { IDtag = (long)cmd.ExecuteScalar(); } catch {
|
|
// Tag non presente in archivio, lo inserisco:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Tags]([Tag]) VALUES (@Tag)";
|
|
cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = rac.Tags[i];
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -40; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDtag = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Assegno al racconto il tag:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Tag]([IDrac], [IDtag]) VALUES (@IDrac, @IDtag)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac;
|
|
cmd.Parameters.Add("@IDtag", System.Data.DbType.Int64).Value = IDtag;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -40; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00012", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -40;
|
|
}
|
|
#endregion
|
|
|
|
#region 50) Inserisco gli Autori (edito tabelle: Autori, Links_Rac_Aut)
|
|
try {
|
|
//foreach (string autore in rac.Autori) {
|
|
for (int i=0; i<rac.Autori.Count; i++) {
|
|
string autore = rac.Autori[i];
|
|
// Ricavo l'ID del tag o lo inserisco sul DB:
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "SELECT IDaut FROM [Autori] WHERE [Autore]=@Autore";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@Autore", System.Data.DbType.String).Value = autore;
|
|
try { IDaut = (long)cmd.ExecuteScalar(); } catch {
|
|
// Tag non presente in archivio, lo inserisco:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Autori]([Autore]) VALUES (@Autore)";
|
|
cmd.Parameters.Add("@Autore", System.Data.DbType.String).Value = autore;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -50; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDaut = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Assegno al racconto il tag:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Aut]([IDrac], [IDaut]) VALUES (@IDrac, @IDaut)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac;
|
|
cmd.Parameters.Add("@IDaut", System.Data.DbType.Int64).Value = IDaut;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -50; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00013", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -50;
|
|
}
|
|
#endregion
|
|
|
|
#region 60) Inserisco le Origini (edito tabelle: Origini, Links_Rac_Ori)
|
|
try {
|
|
//foreach (string origine in rac.Origini) {
|
|
for (int i=0; i<rac.Origini.Count; i++) {
|
|
string origine = rac.Origini[i];
|
|
// Ricavo l'ID del tag o lo inserisco sul DB:
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "SELECT IDori FROM [Origini] WHERE [Origine]=@Origine";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@Origine", System.Data.DbType.String).Value = origine;
|
|
try { IDori = (long)cmd.ExecuteScalar(); } catch {
|
|
// Tag non presente in archivio, lo inserisco:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Origini]([Origine]) VALUES (@Origine)";
|
|
cmd.Parameters.Add("@Origine", System.Data.DbType.String).Value = origine;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -60; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDori = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Assegno al racconto il tag:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Ori]([IDrac], [IDori]) VALUES (@IDrac, @IDori)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac;
|
|
cmd.Parameters.Add("@IDori", System.Data.DbType.Int64).Value = IDori;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -60; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00014", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -60;
|
|
}
|
|
#endregion
|
|
|
|
#region 70) Inserisco le Note (edito tabelle: Notes, Links_Rac_Not)
|
|
try {
|
|
foreach (cNota nota in rac.Notes) {
|
|
// Creo il nuovo record
|
|
cmd = new System.Data.SQLite.SQLiteCommand();
|
|
cmd.Connection = cn;
|
|
cmd.CommandText = "INSERT INTO [Notes]([NKey], [NVal]) VALUES (@NKey, @NVal)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@NKey", System.Data.DbType.String).Value = nota.Key;
|
|
cmd.Parameters.Add("@NVal", System.Data.DbType.String).Value = nota.Description;
|
|
try {
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -70; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
} catch (Exception ex) {
|
|
if (ex.Message.Contains("UNIQUE")) {
|
|
// esiste già la nota, invece che inserirla devo ricavarne l'ID
|
|
cmd.CommandText = "SELECT IDnot FROM Notes WHERE NKey=@NKey AND NVal=@NVal";
|
|
}
|
|
}
|
|
IDnot = (long)cmd.ExecuteScalar();
|
|
// Lo associo al racconto
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Not]([IDrac], [IDnot]) VALUES (@IDrac, @IDnot)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac;
|
|
cmd.Parameters.Add("@IDnot", System.Data.DbType.Int64).Value = IDnot;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -70; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00015", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
myTrans.Rollback();
|
|
return -70;
|
|
}
|
|
#endregion
|
|
|
|
myTrans.Commit();
|
|
|
|
//return 1;
|
|
return (int)IDrac; // Ritorno l'ID del racconto inserito
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00094", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Aggiorna i dati del racconto passato.
|
|
/// Se ID è valido aggiorna i dati del racconto già presente in memoria, altrimenti ne inserisce uno nuovo.
|
|
/// </summary>
|
|
/// <param name="rac">Racconto da inserire sul DB</param>
|
|
/// <returns>Codice di errore se negativo</returns>
|
|
public int UpdateRac(cRac rac) {
|
|
if (rac.IDrac == 0) {
|
|
return ImportRac(rac);
|
|
} else {
|
|
return _updateRac(rac);
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Aggiorna, nel DB, i dati del racconto passato.
|
|
/// </summary>
|
|
/// <param name="rac">Racconto da inserire sul DB</param>
|
|
/// <returns>Codice di errore se negativo</returns>
|
|
private int _updateRac(cRac rac) {
|
|
lock (objLock) {
|
|
|
|
// Inizializzo le variabili che occorrono
|
|
int res = 0;
|
|
long IDvot = 0;
|
|
long IDtag = 0;
|
|
long IDaut = 0;
|
|
long IDori = 0;
|
|
long IDnot = 0;
|
|
|
|
// Elimino il racconto per poi reinserirlo:
|
|
|
|
try {
|
|
|
|
#region 05) Elimino il racconto per poi reinserirlo
|
|
try {
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "DELETE FROM [Racconti] WHERE [IDrac]=@IDrac",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -5; }
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00001", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -10;
|
|
}
|
|
#endregion
|
|
|
|
#region 10) Inserisco sulla tabella Racconti
|
|
try {
|
|
// Creo il nuovo record
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "INSERT INTO [Racconti]([IDrac], [Title], [SubTitle], [Creato], [Aggiornato]) VALUES (@IDrac, @Title, @SubTitle, @Creato, @Aggiornato)",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@Title", System.Data.DbType.String).Value = rac.Title;
|
|
cmd.Parameters.Add("@SubTitle", System.Data.DbType.String).Value = rac.SubTitle;
|
|
cmd.Parameters.Add("@Creato", System.Data.DbType.String).Value = rac.strCreato;
|
|
cmd.Parameters.Add("@Aggiornato", System.Data.DbType.String).Value = rac.strUpdated;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -10; }
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00002", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -10;
|
|
}
|
|
#endregion
|
|
|
|
#region 20) Inserisco sulla tabella Trama
|
|
try {
|
|
// Creo il nuovo record
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "INSERT INTO [Trame]([IDrac], [Trama]) VALUES (@IDrac, @Trama)",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@Trama", System.Data.DbType.String).Value = rac.Trama;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -20; }
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00003", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -20;
|
|
}
|
|
#endregion
|
|
|
|
#region 30) Inserisco sulla tabella Links_Rac_Vot
|
|
try {
|
|
// Decodifico il voto
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "SELECT IDvot FROM Voti WHERE Voto=@Voto",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@Voto", System.Data.DbType.String).Value = rac.Voto;
|
|
//IDvot = (long)cmd.ExecuteScalar(System.Data.CommandBehavior.Default);
|
|
IDvot = (long)cmd.ExecuteScalar();
|
|
// Creo il nuovo record
|
|
cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "INSERT INTO [Links_Rac_Vot]([IDrac], [IDvot]) VALUES (@IDrac, @IDvot)",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@IDvot", System.Data.DbType.Int64).Value = IDvot;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -30; }
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00004", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -30;
|
|
}
|
|
#endregion
|
|
|
|
#region 40) Inserisco i Tags (edito tabelle: Tags, Links_Rac_Tag)
|
|
try {
|
|
foreach (string tag in rac.Tags) {
|
|
// Ricavo l'ID del tag o lo inserisco sul DB:
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "SELECT IDtag FROM [Tags] WHERE [Tag]=@Tag",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = tag;
|
|
try { IDtag = (long)cmd.ExecuteScalar(); } catch {
|
|
// Tag non presente in archivio, lo inserisco:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Tags]([Tag]) VALUES (@Tag)";
|
|
cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = tag;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -40; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDtag = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Assegno al racconto il tag:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Tag]([IDrac], [IDtag]) VALUES (@IDrac, @IDtag)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@IDtag", System.Data.DbType.Int64).Value = IDtag;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -40; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00005", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -40;
|
|
}
|
|
#endregion
|
|
|
|
#region 50) Inserisco gli Autori (edito tabelle: Autori, Links_Rac_Aut)
|
|
try {
|
|
foreach (string autore in rac.Autori) {
|
|
// Ricavo l'ID del tag o lo inserisco sul DB:
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "SELECT IDaut FROM [Autori] WHERE [Autore]=@Autore",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@Autore", System.Data.DbType.String).Value = autore;
|
|
try { IDaut = (long)cmd.ExecuteScalar(); } catch {
|
|
// Tag non presente in archivio, lo inserisco:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Autori]([Autore]) VALUES (@Autore)";
|
|
cmd.Parameters.Add("@Autore", System.Data.DbType.String).Value = autore;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -50; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDaut = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Assegno al racconto il tag:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Aut]([IDrac], [IDaut]) VALUES (@IDrac, @IDaut)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@IDaut", System.Data.DbType.Int64).Value = IDaut;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -50; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00006", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -50;
|
|
}
|
|
#endregion
|
|
|
|
#region 60) Inserisco le Origini (edito tabelle: Origini, Links_Rac_Ori)
|
|
try {
|
|
foreach (string origine in rac.Origini) {
|
|
// Ricavo l'ID dell'origine:
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "SELECT IDori FROM [Origini] WHERE [Origine]=@Origine",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@Origine", System.Data.DbType.String).Value = origine;
|
|
try { IDori = (long)cmd.ExecuteScalar(); } catch {
|
|
// Tag non presente in archivio, lo inserisco:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Origini]([Origine]) VALUES (@Origine)";
|
|
cmd.Parameters.Add("@Origine", System.Data.DbType.String).Value = origine;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -60; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDori = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Assegno al racconto il tag:
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Ori]([IDrac], [IDori]) VALUES (@IDrac, @IDori)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@IDori", System.Data.DbType.Int64).Value = IDori;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -60; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00007", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -60;
|
|
}
|
|
#endregion
|
|
|
|
#region 70) Inserisco le Note (edito tabelle: Notes, Links_Rac_Not)
|
|
try {
|
|
foreach (cNota nota in rac.Notes) {
|
|
// Verifico se la nota esiste ancora:
|
|
SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "SELECT IDnot FROM Notes WHERE NKey=@NKey AND NVal=@NVal",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmd.Parameters.Add("@NKey", System.Data.DbType.String).Value = nota.Key;
|
|
cmd.Parameters.Add("@NVal", System.Data.DbType.String).Value = nota.Description;
|
|
//try { IDnot = (long)cmd.ExecuteScalar(System.Data.CommandBehavior.Default); } catch (Exception ex) {
|
|
try { IDnot = (long)cmd.ExecuteScalar(); } catch (Exception ex) {
|
|
// Nota non presente in archivio, la inserisco:
|
|
SQLiteCommand cmdi = new System.Data.SQLite.SQLiteCommand {
|
|
Connection = cn,
|
|
CommandText = "INSERT INTO [Notes]([NKey], [NVal]) VALUES (@NKey, @NVal)",
|
|
CommandType = System.Data.CommandType.Text
|
|
};
|
|
cmdi.Parameters.Add("@NKey", System.Data.DbType.String).Value = nota.Key;
|
|
cmdi.Parameters.Add("@NVal", System.Data.DbType.String).Value = nota.Description;
|
|
res = cmdi.ExecuteNonQuery();
|
|
if (res != 1) { return -70; }
|
|
// Ricavo l'ID del record appena inserito
|
|
cmd.CommandText = "SELECT last_insert_rowid()";
|
|
IDnot = (long)cmd.ExecuteScalar();
|
|
}
|
|
// Lo associo al racconto
|
|
cmd.Parameters.Clear();
|
|
cmd.CommandText = "INSERT INTO [Links_Rac_Not]([IDrac], [IDnot]) VALUES (@IDrac, @IDnot)";
|
|
cmd.CommandType = System.Data.CommandType.Text;
|
|
cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac;
|
|
cmd.Parameters.Add("@IDnot", System.Data.DbType.Int64).Value = IDnot;
|
|
res = cmd.ExecuteNonQuery();
|
|
if (res != 1) { return -70; }
|
|
}
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00008", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -70;
|
|
}
|
|
#endregion
|
|
|
|
return 1;
|
|
|
|
} catch (Exception ex) {
|
|
Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00093", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
return -1;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Metodi ricavati ottimizzando i miei tramite gemini
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// Ricava il racconto con l'ID indicato leggendolo dal DB
|
|
/// </summary>
|
|
/// <param name="IDrac">Indice identificativo del racconto voluto</param>
|
|
/// <returns>oggetto cRac che rappresenta il racconto</returns>
|
|
public cRac GetRacById(long IDrac) {
|
|
/*
|
|
* Il metodo più pulito e leggibile consiste nell'eseguire una query principale per
|
|
* i dati del racconto e poi delle query mirate per popolare le collezioni.
|
|
*
|
|
* Ecco come implementare la funzione in C# utilizzando Microsoft.Data.Sqlite.
|
|
*
|
|
* Spiegazione della logica:
|
|
* - LEFT JOIN: Ho usato i LEFT JOIN nella query principale così, anche se un racconto
|
|
* non ha ancora una trama o un voto assegnato, il record viene comunque recuperato
|
|
* correttamente senza errori.
|
|
* - Mapping Manuale: Poiché non stiamo usando un ORM pesante (come Entity Framework),
|
|
* mappiamo manualmente le colonne del reader alle proprietà dell'oggetto cRac.
|
|
* - Gestione Valori Nulli: Noterai il controllo reader["Trama"]?.ToString() ?? "" che
|
|
* evita eccezioni nel caso in cui certi campi opzionali siano vuoti nel database.
|
|
* - Helper GetList: Per evitare di riscrivere lo stesso codice 3 volte per Autori,
|
|
* Tags e Origini, ho creato una piccola funzione di supporto.
|
|
*
|
|
* Questo approccio è molto performante su SQLite e ti restituisce l'oggetto cRac
|
|
* esattamente come lo avevi immaginato, pronto per essere mostrato nella tua
|
|
* interfaccia utente.
|
|
*
|
|
*/
|
|
lock (objLock) {
|
|
try {
|
|
|
|
cRac rac = null;
|
|
|
|
// 1. Query principale: Dati Racconto, Trama e Voto
|
|
string queryBase = @"
|
|
SELECT r.*, t.Trama, v.Voto as Voto
|
|
FROM Racconti r
|
|
LEFT JOIN Trame t ON r.IDrac = t.IDrac
|
|
LEFT JOIN Links_Rac_Vot lrv ON r.IDrac = lrv.IDrac
|
|
LEFT JOIN Voti v ON lrv.IDvot = v.IDvot
|
|
WHERE r.IDrac = @IDrac";
|
|
using (SQLiteCommand cmd = new SQLiteCommand(queryBase, cn)) {
|
|
cmd.Parameters.AddWithValue("@IDrac", IDrac);
|
|
using (SQLiteDataReader reader = cmd.ExecuteReader()) {
|
|
if (reader.Read()) {
|
|
rac = new cRac {
|
|
IDrac = Convert.ToInt64(reader["IDrac"]),
|
|
Title = reader["Title"].ToString(),
|
|
SubTitle = reader["SubTitle"].ToString(),
|
|
Creato = DateTime.Parse(reader["Creato"] as string),
|
|
Updated = DateTime.Parse(reader["Aggiornato"].ToString()),
|
|
Trama = reader["Trama"]?.ToString() ?? "",
|
|
Voto = reader["Voto"]?.ToString() ?? "Non Letto"
|
|
};
|
|
}
|
|
}
|
|
}
|
|
if (rac == null) return null; // Racconto non trovato
|
|
|
|
// 2. Recupero Autori
|
|
rac.Autori = Helper.GetList(cn, "SELECT a.Autore FROM Autori a JOIN Links_Rac_Aut l ON a.IDaut = l.IDaut WHERE l.IDrac = @IDrac", IDrac);
|
|
|
|
// 3. Recupero Tags
|
|
rac.Tags = Helper.GetList(cn, "SELECT t.Tag FROM Tags t JOIN Links_Rac_Tag l ON t.IDtag = l.IDtag WHERE l.IDrac = @IDrac", IDrac);
|
|
|
|
// 4. Recupero Origini
|
|
rac.Origini = Helper.GetList(cn, "SELECT o.Origine FROM Origini o JOIN Links_Rac_Ori l ON o.IDori = l.IDori WHERE l.IDrac = @IDrac", IDrac);
|
|
|
|
// 5. Recupero Note (Key-Value)
|
|
string queryNotes = @"
|
|
SELECT n.NKey, n.NVal
|
|
FROM Notes n
|
|
JOIN Links_Rac_Not l ON n.IDnot = l.IDnot
|
|
WHERE l.IDrac = @IDrac";
|
|
using (var cmd = new SQLiteCommand(queryNotes, cn)) {
|
|
cmd.Parameters.AddWithValue("@IDrac", IDrac);
|
|
using (var reader = cmd.ExecuteReader()) {
|
|
while (reader.Read()) {
|
|
cNota nt = new cNota(reader["NKey"].ToString(), reader["NVal"].ToString());
|
|
rac.Notes.Add(nt);
|
|
}
|
|
}
|
|
}
|
|
|
|
// // 6. Recupero Segnalini
|
|
// string querySng = @"
|
|
// SELECT s.Linea, s.Segnalino
|
|
// FROM Segnalini s
|
|
// JOIN Links_Rac_Sng l ON s.IDsng = l.IDsng
|
|
// WHERE l.IDrac = @IDrac";
|
|
// using (var cmd = new SQLteCommand(querySng, cn) {
|
|
// cmd.Parameters.AddWithValue("@IDrac", IDrac);
|
|
// using (var reader = cmd.ExecuteReader()) {
|
|
// while (reader.Read()) {
|
|
// rac.Segnalini.Add(new SegnalinoInfo {
|
|
// Linea = Convert.ToInt32(reader["Linea"]),
|
|
// Descrizione = reader["Segnalino"].ToString()
|
|
// });
|
|
// }
|
|
// }
|
|
// }
|
|
|
|
return rac;
|
|
|
|
} catch (Exception ex) {
|
|
Logger.Error($"GetRacById({IDrac}) error: {ex.Message}");
|
|
return null;
|
|
}
|
|
}//lock
|
|
}
|
|
|
|
/// <summary>
|
|
/// Salva il racconto nel DB
|
|
/// </summary>
|
|
/// <param name="racconto">Racconto da salvare sul DB</param>
|
|
/// <returns>Esito del salvataggio</returns>
|
|
public SaveResult SalvaRacconto(cRac racconto) {
|
|
lock (objLock) {
|
|
using (var transaction = cn.BeginTransaction()) {
|
|
try {
|
|
|
|
// 1. Inserimento Record Principale [Racconti]
|
|
var cmdRac = new SQLiteCommand(@"
|
|
INSERT INTO Racconti (Title, SubTitle, Creato, Aggiornato)
|
|
VALUES (@t, @st, @c, @a);
|
|
SELECT last_insert_rowid();",
|
|
cn, transaction);
|
|
cmdRac.Parameters.AddWithValue("@t", racconto.Title);
|
|
cmdRac.Parameters.AddWithValue("@st", racconto.SubTitle);
|
|
cmdRac.Parameters.AddWithValue("@c", racconto.Creato);
|
|
cmdRac.Parameters.AddWithValue("@a", racconto.Updated);
|
|
|
|
long newIDrac = (long)cmdRac.ExecuteScalar(); //
|
|
racconto.IDrac = newIDrac;
|
|
|
|
// 2. Salvataggio Relazioni Molti-a-Molti
|
|
|
|
// Inserimento Trama (Tabella [Trame])
|
|
if (!string.IsNullOrWhiteSpace(racconto.Trama)) {
|
|
var cmdTra = new SQLiteCommand("INSERT INTO Trame (IDrac, Trama) VALUES (@id, @txt)", cn, transaction);
|
|
cmdTra.Parameters.AddWithValue("@id", newIDrac);
|
|
cmdTra.Parameters.AddWithValue("@txt", racconto.Trama);
|
|
cmdTra.ExecuteNonQuery(); //
|
|
}
|
|
|
|
// Inserimento Voto (Tabella [Links_Rac_Vot])
|
|
if (!string.IsNullOrWhiteSpace(racconto.Voto)) {
|
|
var cmdVot = new SQLiteCommand("INSERT OR REPLACE INTO Links_Rac_Vot (IDrac, IDvot) VALUES (@r, @v)", cn, transaction);
|
|
cmdVot.Parameters.AddWithValue("@r", newIDrac);
|
|
cmdVot.Parameters.AddWithValue("@v", racconto.Voto); // IDvot corrisponde al valore rating
|
|
cmdVot.ExecuteNonQuery();
|
|
}
|
|
|
|
// 3. Salvataggio Relazioni Molti-a-Molti
|
|
|
|
// Autori
|
|
racconto.Autori.ForEach(autore => {
|
|
long idAut = Helper.GetOrCreateId(cn, transaction, "Autori", "Autore", "IDaut", autore);
|
|
Helper.ExecuteLink(cn, transaction, "Links_Rac_Aut", "IDaut", newIDrac, idAut);
|
|
});
|
|
|
|
// Tags
|
|
racconto.Tags.ForEach(tag => {
|
|
long idTag = Helper.GetOrCreateId(cn, transaction, "Tags", "Tag", "IDtag", tag);
|
|
Helper.ExecuteLink(cn, transaction, "Links_Rac_Tag", "IDtag", newIDrac, idTag);
|
|
});
|
|
|
|
// Origini Multiple
|
|
racconto.Origini.ForEach(origine => {
|
|
long idOri = Helper.GetOrCreateId(cn, transaction, "Origini", "Origine", "IDori", origine);
|
|
Helper.ExecuteLink(cn, transaction, "Links_Rac_Ori", "IDori", newIDrac, idOri);
|
|
});
|
|
|
|
// Note (Coppia Chiave-Valore)
|
|
foreach (var nota in racconto.Notes) {
|
|
var idNot = Helper.GetOrCreateNoteId(cn, transaction, nota.Key, nota.Description);
|
|
Helper.ExecuteLink(cn, transaction, "Links_Rac_Not", "IDnot", newIDrac, idNot);
|
|
}
|
|
|
|
// // 4. Inserimento Segnalini (Tabella [Segnalini])
|
|
// foreach (var sng in racconto.Segnalini) {
|
|
// var cmdSng = new SqliteCommand(@"
|
|
// INSERT INTO Segnalini (Linea, Segnalino) VALUES (@l, @s);
|
|
// SELECT last_insert_rowid();", connection, transaction);
|
|
// cmdSng.Parameters.AddWithValue("@l", sng.Linea);
|
|
// cmdSng.Parameters.AddWithValue("@s", sng.Descrizione);
|
|
// long idSng = (long)cmdSng.ExecuteScalar();
|
|
//
|
|
// // Link Segnalino al Racconto
|
|
// ExecuteLink(connection, transaction, "Links_Rac_Sng", "IDsng", newIDrac, idSng);
|
|
// }
|
|
|
|
transaction.Commit();
|
|
Logger.Information($"Inserito racconto {newIDrac}");
|
|
return SaveResult.Success;
|
|
|
|
} catch (Exception ex) {
|
|
transaction.Rollback();
|
|
Logger.Information($"Errore SQL durante l'inserimento del racconto racconto {racconto.Title}");
|
|
return SaveResult.GenericError;
|
|
}
|
|
}//transaction
|
|
}//lock
|
|
}
|
|
|
|
|
|
|
|
#region Reader function: GetReport, GetRandomIDrac
|
|
|
|
|
|
private long GetNumRacs(string TagFilter = "") {
|
|
string query = "SELECT count (IDrac) FROM Racconti";
|
|
if (TagFilter != "") { query = "SELECT count (Racconti.IDrac) AS NUM FROM Racconti, Links_Rac_Vot, Voti WHERE Racconti.IDrac=Links_Rac_Vot.IDrac AND Links_Rac_Vot.IDvot=Voti.IDvot AND Voti.Voto='" + TagFilter + "'"; }
|
|
return Helper.ExecuteScalar(cn,query,objLock);
|
|
}
|
|
|
|
private long GetNumOri() { return Helper.CountSimpleRecord(cn, "Links_Rac_Ori", "IDori", objLock); }
|
|
|
|
private long GetNumAuts() { return Helper.CountSimpleRecord(cn, "Links_Rac_Aut", "IDaut", objLock); }
|
|
|
|
private long GetNumTags() { return Helper.CountSimpleRecord(cn, "Links_Rac_Tag", "IDtag", objLock); }
|
|
|
|
private long GetNumVot() { return Helper.CountSimpleRecord(cn, "Links_Rac_Vot", "IDvot", objLock); }
|
|
|
|
|
|
/// <summary>
|
|
/// ritorna il riepilogo del DB:
|
|
/// </summary>
|
|
/// <returns>Stringa con il riepilogo del DB</returns>
|
|
public string Report {
|
|
get {
|
|
string report = "A69WD:\r\n\r\n";
|
|
report += string.Format("L'archivio contiene {0} racconti:\r\n", GetNumRacs().ToString("000"));
|
|
report += string.Format("> {0} non letti\r\n", GetNumRacs("Non Letto").ToString("000"));
|
|
report += string.Format("> {0} sorgenti\r\n", GetNumOri().ToString("00"));
|
|
report += string.Format("> {0} autori\r\n", GetNumAuts().ToString("000"));
|
|
report += string.Format("> {0} tags\r\n", GetNumTags().ToString("000"));
|
|
report += string.Format("> {0} voti\r\n", GetNumVot().ToString("000"));
|
|
return report;
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Metodo per trovare un identificativo di un racconto scelto casualmente fra quelli che soddisfano il filtro indicato.
|
|
/// </summary>
|
|
/// <param name="queryFilter">Eventuale query per filtrare i racconti selezionabili</param>
|
|
/// <returns>Identificativo del racconto scelto casualmente</returns>
|
|
public long GetRandomIDrac(string queryFilter = "") {
|
|
//long ID = -3;
|
|
//SQLiteDataReader rdr = null;
|
|
//lock (objLock) {
|
|
//try {
|
|
//// Preparo i comandi SQL da usare:
|
|
//string query = "SELECT Links_Rac_Vot.IDrac AS IDrac FROM Links_Rac_Vot, Voti WHERE Voti.Voto='Non Letto' AND Links_Rac_Vot.IDVot=Voti.IDvot ORDER BY RANDOM() LIMIT 1";
|
|
//if (!string.IsNullOrEmpty(queryFilter)) query = string.Format("SELECT Links_Rac_Vot.IDrac AS IDrac FROM Links_Rac_Vot, Voti WHERE Links_Rac_Vot.IDVot=Voti.IDvot AND {0} ORDER BY RANDOM() LIMIT 1", queryFilter);
|
|
//SQLiteCommand cmd = new SQLiteCommand(query, cn);
|
|
//rdr = cmd.ExecuteReader();
|
|
//while (rdr.Read()) { ID = (long)rdr["IDrac"]; }
|
|
//rdr.Close();
|
|
//rdr = null;
|
|
//} catch (Exception ex) {
|
|
//Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00070", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message));
|
|
//ID = -2;
|
|
//}
|
|
//}
|
|
//return ID;
|
|
string query = "SELECT Links_Rac_Vot.IDrac AS IDrac FROM Links_Rac_Vot, Voti WHERE Voti.Voto='Non Letto' AND Links_Rac_Vot.IDVot=Voti.IDvot ORDER BY RANDOM() LIMIT 1";
|
|
if (!string.IsNullOrEmpty(queryFilter)) query = string.Format("SELECT Links_Rac_Vot.IDrac AS IDrac FROM Links_Rac_Vot, Voti WHERE Links_Rac_Vot.IDVot=Voti.IDvot AND {0} ORDER BY RANDOM() LIMIT 1", queryFilter);
|
|
return Helper.ExecuteScalar(cn, query, objLock);
|
|
}
|
|
|
|
public int UpdateVoto(long IDrac, string NewVoto) {
|
|
Logger.Warning("Funzione 'UpdateVoto(IDrac, NewVoto) ancora da fare.");
|
|
return -1;
|
|
}
|
|
|
|
#endregion
|
|
|
|
|
|
} //class DBTools
|
|
|
|
|
|
}//namespace A69WD
|