SQLiteProvider.cs 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215
  1. using System.Collections;
  2. using System.Data;
  3. using System.Data.SQLite;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using System.Resources;
  8. using System.Runtime.Serialization.Formatters.Binary;
  9. using System.Text;
  10. using InABox.Core;
  11. using Microsoft.CodeAnalysis;
  12. using NPOI.POIFS.FileSystem;
  13. namespace InABox.Database.SQLite
  14. {
  15. internal abstract class SQLiteAccessor : IDisposable
  16. {
  17. public SQLiteConnection Connection { get; private set; }
  18. protected static int nConnections = 0;
  19. public void Dispose()
  20. {
  21. Connection?.Close();
  22. --nConnections;
  23. }
  24. public SQLiteCommand CreateCommand()
  25. {
  26. return new SQLiteCommand(Connection);
  27. }
  28. protected void Setup(string url)
  29. {
  30. var sb = new SQLiteConnectionStringBuilder();
  31. sb.DataSource = url;
  32. sb.Version = 3;
  33. sb.DateTimeFormat = SQLiteDateFormats.Ticks;
  34. sb.JournalMode = SQLiteJournalModeEnum.Wal;
  35. var conn = sb.ToString();
  36. Connection = new SQLiteConnection(conn);
  37. Connection.BusyTimeout = Convert.ToInt32(TimeSpan.FromMinutes(2).TotalMilliseconds);
  38. Connection.Open();
  39. Connection.SetLimitOption(SQLiteLimitOpsEnum.SQLITE_LIMIT_VARIABLE_NUMBER, 10000);
  40. ++nConnections;
  41. }
  42. }
  43. internal class SQLiteReadAccessor : SQLiteAccessor
  44. {
  45. public SQLiteReadAccessor(string url)
  46. {
  47. Setup(url);
  48. }
  49. }
  50. internal class SQLiteWriteAccessor : SQLiteAccessor
  51. {
  52. private static readonly object writelock = new();
  53. public SQLiteWriteAccessor(string url)
  54. {
  55. if (Monitor.TryEnter(writelock, new TimeSpan(0, 1, 0)))
  56. try
  57. {
  58. Setup(url);
  59. }
  60. catch(Exception e)
  61. {
  62. throw new Exception($"Exception while acquiring write lock! {nConnections} connections open.", e);
  63. }
  64. finally
  65. {
  66. Monitor.Exit(writelock);
  67. }
  68. if (Connection == null)
  69. throw new Exception($"Timeout while aqcuiring write lock! {nConnections} connections open.");
  70. }
  71. public SQLiteTransaction BeginTransaction()
  72. {
  73. return Connection.BeginTransaction();
  74. }
  75. }
  76. public class SQLiteProvider : IProvider
  77. {
  78. private static object writelock = new();
  79. private bool bForceRebuild;
  80. private bool RebuildTriggers = false;
  81. public SQLiteProvider(string filename)
  82. {
  83. var path = Path.GetDirectoryName(filename);
  84. if (!path.IsNullOrWhiteSpace())
  85. Directory.CreateDirectory(path);
  86. URL = filename;
  87. }
  88. public string URL { get; set; }
  89. public event LogEvent? OnLog;
  90. /// <summary>
  91. /// An array containing every <see cref="Entity"/> type in the database.
  92. /// </summary>
  93. public Type[] Types { get; set; } = [];
  94. public void Start()
  95. {
  96. var chkfile = Path.ChangeExtension(URL, "chk");
  97. bForceRebuild = File.Exists(chkfile);
  98. if (!File.Exists(URL))
  99. {
  100. SQLiteConnection.CreateFile(URL);
  101. }
  102. else if (bForceRebuild)
  103. {
  104. var i = 0;
  105. while (File.Exists(Path.ChangeExtension(URL, string.Format("{0:D3}", i))))
  106. i++;
  107. File.Copy(URL, Path.ChangeExtension(URL, string.Format("{0:D3}", i)));
  108. }
  109. using var access = GetWriteAccess();
  110. ExecuteSQL(access, "PRAGMA journal_mode=WAL;");
  111. //using (var access = GetReadAccess())
  112. //{
  113. // using (var command = access.CreateCommand())
  114. // {
  115. // command.CommandText = "PRAGMA compile_options";
  116. // using (var reader = command.ExecuteReader())
  117. // {
  118. // while (reader.Read())
  119. // OnLog?.Invoke(LogType.Information,String.Format("{0}",reader.GetValue(0)));
  120. // }
  121. // }
  122. //}
  123. //ExecuteSQL("PRAGMA foreign_keys = on;");
  124. foreach(var type in Types)
  125. {
  126. DatabaseSchema.CheckProperties(type);
  127. }
  128. // Need to arrange the typelist to ensure that foreign keys
  129. // refer to tables that already exist
  130. var ordered = new List<Type>();
  131. foreach (var type in Types)
  132. LoadType(type, ordered);
  133. //Load up the metadata
  134. var metadata = LoadMetaData();
  135. var table = typeof(CustomProperty).EntityName().Split('.').Last();
  136. if (!metadata.TryGetValue(table, out var value))
  137. {
  138. OnLog?.Invoke(LogType.Information, $"Creating Table: {nameof(CustomProperty)}");
  139. CreateTable(access, typeof(CustomProperty), true, []);
  140. }
  141. else
  142. {
  143. CheckFields(access, typeof(CustomProperty), value.Item1, []);
  144. }
  145. var customproperties = Load<CustomProperty>(); // new Filter<CustomProperty>(x => x.Class).IsEqualTo(type.EntityName()))
  146. metadata = LoadMetaData();
  147. foreach (var type in ordered)
  148. {
  149. if (type.GetCustomAttribute<AutoEntity>() == null)
  150. {
  151. table = type.EntityName().Split('.').Last();
  152. if (!metadata.ContainsKey(table))
  153. {
  154. OnLog?.Invoke(LogType.Information, "Creating Table: " + type.Name);
  155. CreateTable(access, type, true, customproperties);
  156. }
  157. }
  158. }
  159. metadata = LoadMetaData();
  160. foreach (var type in ordered)
  161. {
  162. if (type.GetCustomAttribute<AutoEntity>() == null)
  163. {
  164. table = type.EntityName().Split('.').Last();
  165. CheckFields(access, type, metadata[table].Item1, customproperties);
  166. }
  167. }
  168. metadata = LoadMetaData();
  169. foreach (var type in ordered)
  170. {
  171. if (type.GetCustomAttribute<AutoEntity>() == null)
  172. {
  173. table = type.Name;
  174. CheckTriggers(access, type, metadata[table].Item2);
  175. }
  176. }
  177. metadata = LoadMetaData();
  178. foreach (var type in ordered)
  179. {
  180. if (type.GetCustomAttribute<AutoEntity>() == null)
  181. {
  182. table = type.EntityName().Split('.').Last();
  183. CheckIndexes(access, type, metadata[table].Item3);
  184. }
  185. }
  186. metadata = LoadMetaData();
  187. foreach (var type in ordered)
  188. {
  189. if (type.GetCustomAttribute<AutoEntity>() != null)
  190. {
  191. table = type.EntityName().Split('.').Last();
  192. if (!metadata.ContainsKey(table))
  193. {
  194. OnLog?.Invoke(LogType.Information, "Creating Table: " + type.EntityName().Split('.').Last());
  195. CreateTable(access, type, true, customproperties);
  196. }
  197. else
  198. {
  199. CheckFields(access, type, metadata[table].Item1, customproperties);
  200. }
  201. }
  202. }
  203. if (bForceRebuild)
  204. {
  205. ExecuteSQL(access, "VACUUM;");
  206. File.Delete(chkfile);
  207. }
  208. }
  209. public bool IsRelational()
  210. {
  211. return true;
  212. }
  213. private void Connection_Trace(object sender, TraceEventArgs e)
  214. {
  215. var type = LogType.Query;
  216. string[] updates = { "INSERT ", "UPDATE ", "DELETE ", "ALTER ", "DROP ", "CREATE ", "VACUUM" };
  217. foreach (var update in updates)
  218. type = e.Statement.ToUpper().StartsWith(update) ? LogType.Update : type;
  219. OnLog?.Invoke(type, e.Statement + ";");
  220. }
  221. private SQLiteReadAccessor GetReadAccess()
  222. {
  223. var result = new SQLiteReadAccessor(URL);
  224. result.Connection.Trace += Connection_Trace;
  225. return result;
  226. }
  227. private SQLiteWriteAccessor GetWriteAccess()
  228. {
  229. var result = new SQLiteWriteAccessor(URL);
  230. result.Connection.Trace += Connection_Trace;
  231. return result;
  232. }
  233. private int ExecuteSQL(SQLiteWriteAccessor writer, string statement)
  234. {
  235. var result = 0;
  236. try
  237. {
  238. using (var command = writer.CreateCommand())
  239. {
  240. command.CommandText = statement;
  241. result = command.ExecuteNonQuery();
  242. }
  243. }
  244. catch (Exception)
  245. {
  246. throw;
  247. }
  248. return result;
  249. }
  250. #region Database Structure Management
  251. private class MetadataEntry
  252. {
  253. public String Name { get; set; }
  254. public String SQL { get; set; }
  255. }
  256. private class Metadata
  257. {
  258. public List<MetadataEntry> Tables { get; init; }
  259. public List<MetadataEntry> Views { get; init; }
  260. public List<MetadataEntry> Indexes { get; init; }
  261. public List<MetadataEntry> Triggers { get; init; }
  262. public Metadata() : base()
  263. {
  264. Tables = new List<MetadataEntry>();
  265. Views = new List<MetadataEntry>();
  266. Indexes = new List<MetadataEntry>();
  267. Triggers = new List<MetadataEntry>();
  268. }
  269. }
  270. private Dictionary<string, Tuple<Dictionary<string, string>, Dictionary<string, string>, Dictionary<string, string>>> LoadMetaData()
  271. {
  272. // Key is table name
  273. // Item1 = Field Name / Field Type map
  274. // Item2 = Trigger Name / Trigger SQL
  275. // Item3 = Index Name / Index SQL
  276. // Item4 = View Name /View SQL
  277. var metadata = new Dictionary<string, Tuple<Dictionary<string, string>, Dictionary<string, string>, Dictionary<string, string>>>();
  278. using (var access = GetReadAccess())
  279. {
  280. using (var command = access.CreateCommand())
  281. {
  282. command.CommandText = "SELECT tbl_name, sql, type FROM sqlite_master WHERE type='table' or type='view' ORDER BY type;";
  283. using (var reader = command.ExecuteReader())
  284. {
  285. if (reader.HasRows)
  286. while (reader.Read())
  287. {
  288. var tblinfo = new Tuple<Dictionary<string, string>, Dictionary<string, string>, Dictionary<string, string>>(
  289. new Dictionary<string, string>(), new Dictionary<string, string>(), new Dictionary<string, string>());
  290. var table = reader.GetString(0);
  291. var sql = reader.GetString(1);
  292. bool istable = String.Equals(reader.GetString(2),"table");
  293. if (istable)
  294. {
  295. sql = sql.Replace("\"", "")
  296. .Replace(string.Format("CREATE TABLE {0} (", table), "");
  297. sql = sql.Remove(sql.Length - 1).Trim();
  298. var fields = sql.Replace("\n\t", "").Replace("\t", " ").Replace("\"", "").Trim().Split(',');
  299. var primarykey = "";
  300. foreach (var fld in fields)
  301. {
  302. var field = fld.Trim().Replace("\t", " ").Replace("\"", "").Replace("[", "").Replace("]", "");
  303. //if (field.ToUpper().StartsWith("CONSTRAINT"))
  304. // tblinfo.Item2.Add(field);
  305. if (field.ToUpper().StartsWith("PRIMARY KEY"))
  306. {
  307. primarykey = field.Replace("PRIMARY KEY(", "").Replace(")", "");
  308. }
  309. else
  310. {
  311. var comps = field.Split(' ');
  312. tblinfo.Item1[comps[0]] = string.Format("{0}{1}", comps[1],
  313. field.Contains("PRIMARY KEY") ? " PRIMARY KEY" : "");
  314. }
  315. }
  316. if (!string.IsNullOrEmpty(primarykey))
  317. {
  318. var pkfld = tblinfo.Item1[primarykey];
  319. if (!pkfld.ToUpper().Contains("PRIMARY KEY"))
  320. tblinfo.Item1[primarykey] = string.Format("{0} PRIMARY KEY", pkfld.Trim());
  321. }
  322. }
  323. else
  324. {
  325. sql = sql.Replace("\"", "")
  326. .Replace("DISTINCT ", "");
  327. sql = sql.Split(new String[] { " AS SELECT " }, StringSplitOptions.TrimEntries).Last();
  328. sql = sql.Split(new String[] { " FROM " }, StringSplitOptions.TrimEntries).First();
  329. var fields = sql.Replace("\n\t", "").Replace("\t", " ").Replace("\"", "").Trim().Split(',');
  330. foreach (var fld in fields)
  331. {
  332. var field = fld.Trim()
  333. .Replace("\t", " ")
  334. .Replace("\"", "")
  335. .Replace("[", "").Replace("]", "");
  336. var parts = field.Split(" as ");
  337. if(parts.Length == 1)
  338. {
  339. tblinfo.Item1[field] = "";
  340. }
  341. else if(parts.Length == 2)
  342. {
  343. field = parts[1];
  344. if (parts[0] != "NULL")
  345. {
  346. tblinfo.Item1[field] = "";
  347. }
  348. }
  349. }
  350. }
  351. metadata[table] = tblinfo;
  352. }
  353. reader.Close();
  354. }
  355. // Now Load Up all the indexes
  356. command.CommandText = "select name, tbl_name, sql from sqlite_master where type='index' and sql is not null;";
  357. using (var reader = command.ExecuteReader())
  358. {
  359. if (reader.HasRows)
  360. while (reader.Read())
  361. {
  362. var name = reader.GetString(0);
  363. var table = reader.GetString(1);
  364. if (metadata.ContainsKey(table))
  365. {
  366. var tblInfo = metadata[table];
  367. var sql = reader.GetString(2);
  368. tblInfo.Item3[name] = sql;
  369. }
  370. }
  371. }
  372. // Now Load Up all the triggers
  373. command.CommandText = "select name, tbl_name, sql from sqlite_master where type='trigger';";
  374. using (var reader = command.ExecuteReader())
  375. {
  376. if (reader.HasRows)
  377. while (reader.Read())
  378. {
  379. var name = reader.GetString(0);
  380. var table = reader.GetString(1);
  381. if (metadata.ContainsKey(table))
  382. {
  383. var tblInfo = metadata[table];
  384. var sql = reader.GetString(2);
  385. tblInfo.Item2[name] = sql;
  386. }
  387. }
  388. }
  389. }
  390. }
  391. return metadata;
  392. }
  393. private static void LoadType(Type type, List<Type> into)
  394. {
  395. if (into.Contains(type))
  396. return;
  397. var props = type.GetProperties().Where(x => x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)));
  398. if (!props.Any())
  399. {
  400. into.Insert(0, type);
  401. }
  402. else
  403. {
  404. into.Add(type);
  405. foreach (var prop in props)
  406. {
  407. var subtype = prop.PropertyType.BaseType;
  408. while (subtype != null && !subtype.GetGenericArguments().Any())
  409. subtype = subtype.BaseType;
  410. subtype = subtype?.GetGenericArguments().FirstOrDefault();
  411. if (subtype != null && subtype != type)
  412. LoadType(subtype, into);
  413. }
  414. }
  415. }
  416. private string ColumnName(params PropertyInfo[] properties)
  417. {
  418. var bits = new List<string>();
  419. foreach (var property in properties)
  420. bits.Add(property.Name);
  421. var result = string.Join(".", bits);
  422. return result;
  423. }
  424. private string ColumnType(Type type)
  425. {
  426. if (type.IsOrdinal())
  427. return "INT";
  428. if (type.IsEnum)
  429. return "TEXT";
  430. if (type == typeof(DateTime))
  431. return "TEXT";
  432. if (type == typeof(TimeSpan))
  433. return "NUM";
  434. if (type == typeof(string[]))
  435. return "BLOB";
  436. if (type == typeof(byte[]))
  437. return "BLOB";
  438. if (type.IsFloatingPoint())
  439. return "NUM";
  440. if (type.GetInterfaces().Contains(typeof(IPackable)))
  441. return "BLOB";
  442. return "TEXT";
  443. }
  444. private void LoadFields(Type type, Dictionary<string, string> fields, List<PropertyInfo>? prefixes, CustomProperty[] customproperties)
  445. {
  446. if (prefixes == null)
  447. prefixes = new List<PropertyInfo>();
  448. AutoEntity? view = type.GetCustomAttribute<AutoEntity>();
  449. Type definition = view?.Generator != null
  450. ? view.Generator.Definition
  451. : type;
  452. var properties = CoreUtils.GetInheritedProperties(definition).Where(x =>
  453. x.GetCustomAttribute<DoNotPersist>() == null
  454. // We think this is wrong; but who knows? && x.GetCustomAttribute<DoNotSerialize>() == null
  455. && x.GetCustomAttributes().FirstOrDefault(a => a.GetType().Equals(typeof(AggregateAttribute))) == null
  456. && x.GetCustomAttributes().FirstOrDefault(a => a.GetType().Equals(typeof(FormulaAttribute))) == null
  457. && x.GetCustomAttributes().FirstOrDefault(a => a.GetType().Equals(typeof(ConditionAttribute))) == null
  458. && x.GetCustomAttributes().FirstOrDefault(a => a.GetType().Equals(typeof(ChildEntityAttribute))) == null
  459. && x.CanWrite
  460. && x.PropertyType != typeof(UserProperties)
  461. );
  462. foreach (var property in properties)
  463. if (property.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  464. {
  465. LoadFields(property.PropertyType, fields, prefixes.Concat(new[] { property }).ToList(), customproperties);
  466. }
  467. else if (property.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  468. {
  469. var subprop = property.PropertyType.GetProperty("ID")!; // Not-null because IEntityLink has ID
  470. var subname = ColumnName(prefixes.Concat(new[] { property, subprop }).ToArray());
  471. var subtype = ColumnType(subprop.PropertyType);
  472. fields[subname] = subtype;
  473. }
  474. else
  475. {
  476. var colname = ColumnName(prefixes.Concat(new[] { property }).ToArray());
  477. var coltype = ColumnType(property.PropertyType);
  478. fields[colname] = string.Format("{0}{1}", coltype, colname.Equals("ID") ? " PRIMARY KEY" : "");
  479. }
  480. // Now add in the Custom Properties (if any exist)
  481. //CustomProperty[] customprops = Load<CustomProperty>(new Filter<CustomProperty>(x=>x.Class).IsEqualTo(type.EntityName()));
  482. foreach (var prop in customproperties.Where(x => x.Class.Equals(type.EntityName())))
  483. fields[prop.Name] = ColumnType(prop.PropertyType);
  484. }
  485. private List<string> LoadIndexes(Type type)
  486. {
  487. var result = new List<string>();
  488. var properties = type.GetProperties().Where(x =>
  489. x.GetCustomAttribute<DoNotSerialize>() == null && x.GetCustomAttribute<DoNotPersist>() == null &&
  490. x.GetCustomAttributes().FirstOrDefault(a => a.GetType().IsSubclassOf(typeof(AggregateAttribute))) == null
  491. && x.GetCustomAttributes().FirstOrDefault(a => a.GetType().Equals(typeof(ChildEntityAttribute))) == null
  492. && x.CanWrite);
  493. foreach (var property in properties)
  494. if (property.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  495. {
  496. var subprop = property.PropertyType.GetProperty("ID")!; // Not-null because IEntityLink has ID
  497. var subname = ColumnName(property, subprop);
  498. var tablename = type.EntityName().Split('.').Last();
  499. result.Add(string.Format("CREATE INDEX idx{0}{1} ON {0} ([{2}])", tablename, subname.Replace(".", ""), subname));
  500. }
  501. else
  502. {
  503. var index = property.GetCustomAttributes<SecondaryIndexAttribute>().FirstOrDefault();
  504. if (index != null)
  505. {
  506. var colname = ColumnName(property);
  507. var tablename = type.EntityName().Split('.').Last();
  508. result.Add(string.Format("CREATE INDEX idx{0}{1} ON {0} ([{2}])", tablename, colname.Replace(".", ""), colname));
  509. }
  510. }
  511. return result;
  512. }
  513. private void LoadDeletions(Type type)
  514. {
  515. var cascades = new List<Tuple<Type, List<string>>>();
  516. var setNulls = new List<Tuple<Type, List<string>>>();
  517. foreach(var otherType in Types.Where(x => x.GetCustomAttribute<AutoEntity>() is null))
  518. {
  519. var setNullFields = new List<string>();
  520. var cascadeFields = new List<string>();
  521. var props = DatabaseSchema.RootProperties(otherType)
  522. .Where(x => x.IsEntityLink
  523. && x.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>))?.GenericTypeArguments[0] == type
  524. && !x.IsCalculated);
  525. foreach(var prop in props)
  526. {
  527. var fieldname = $"{prop.Name}.ID";
  528. if(prop.GetAttribute<EntityRelationshipAttribute>() is EntityRelationshipAttribute attr
  529. && attr.Action == DeleteAction.Cascade)
  530. {
  531. cascadeFields.Add(fieldname);
  532. }
  533. else
  534. {
  535. setNullFields.Add(fieldname);
  536. }
  537. }
  538. cascadeFields.Sort();
  539. setNullFields.Sort();
  540. cascades.Add(new(otherType, cascadeFields));
  541. setNulls.Add(new(otherType, setNullFields));
  542. }
  543. if(cascades.Count > 0)
  544. {
  545. _cascades[type] = cascades;
  546. }
  547. if(setNulls.Count > 0)
  548. {
  549. _setNulls[type] = setNulls;
  550. }
  551. }
  552. private string? LoadTrigger(Type type)
  553. {
  554. var actions = new List<string>();
  555. if(_setNulls.TryGetValue(type, out var setNulls))
  556. {
  557. foreach(var (otherType, fields) in setNulls)
  558. {
  559. foreach(var field in fields)
  560. {
  561. actions.Add($"UPDATE {otherType.Name} SET [{field}] = NULL WHERE [{field}] = old.ID;");
  562. }
  563. }
  564. }
  565. if(_cascades.TryGetValue(type, out var cascades))
  566. {
  567. foreach(var (otherType, fields) in cascades)
  568. {
  569. foreach(var field in fields)
  570. {
  571. actions.Add($"DELETE FROM {otherType.Name} WHERE [{field}] = old.ID;");
  572. }
  573. }
  574. }
  575. if (actions.Count != 0)
  576. {
  577. return $"CREATE TRIGGER {type.Name}_BEFOREDELETE BEFORE DELETE ON {type.Name} FOR EACH ROW BEGIN {string.Join(' ', actions)} END";
  578. }
  579. else
  580. {
  581. return null;
  582. }
  583. }
  584. public void ForceRecreateViews()
  585. {
  586. var ordered = new List<Type>();
  587. foreach (var type in Types)
  588. LoadType(type, ordered);
  589. var customproperties = Load<CustomProperty>();
  590. var metadata = LoadMetaData();
  591. foreach (var type in ordered)
  592. {
  593. var view = type.GetCustomAttribute<AutoEntity>();
  594. if (view?.Generator != null)
  595. {
  596. var table = type.EntityName().Split('.').Last();
  597. if (!metadata.ContainsKey(table))
  598. {
  599. OnLog?.Invoke(LogType.Information, "Creating Table: " + type.EntityName().Split('.').Last());
  600. using (var access = GetWriteAccess())
  601. {
  602. CreateTable(access, type, true, customproperties);
  603. }
  604. }
  605. else
  606. {
  607. var type_fields = new Dictionary<string, string>();
  608. LoadFields(view.Generator.Definition, type_fields, null, customproperties);
  609. using (var access = GetWriteAccess())
  610. {
  611. RebuildTable(access, type, metadata[table].Item1, type_fields, customproperties);
  612. }
  613. }
  614. }
  615. }
  616. }
  617. private Dictionary<string, object?> CheckDefaultColumns(IAutoEntityGenerator generator)
  618. {
  619. var viewfields = new Dictionary<string, string>();
  620. LoadFields(generator.Definition, viewfields, null, new CustomProperty[] { });
  621. Dictionary<String, object?> result = new Dictionary<string, object?>();
  622. if (!viewfields.ContainsKey("ID"))
  623. result["ID"] = null;
  624. if (!viewfields.ContainsKey("Created"))
  625. result["Created"] = null;
  626. if (!viewfields.ContainsKey("CreatedBy"))
  627. result["CreatedBy"] = null;
  628. if (!viewfields.ContainsKey("LastUpdate"))
  629. result["LastUpdate"] = null;
  630. if (!viewfields.ContainsKey("LastUpdateBy"))
  631. result["LastUpdateBy"] = null;
  632. return result;
  633. }
  634. private void CreateTable(SQLiteWriteAccessor access, Type type, bool includeconstraints, CustomProperty[] customproperties)
  635. {
  636. var tablename = type.EntityName().Split('.').Last();
  637. var ddl = new List<string>();
  638. var view = type.GetCustomAttribute<AutoEntity>();
  639. if (view != null)
  640. {
  641. using (var command = access.CreateCommand())
  642. {
  643. command.CommandText = $"select name from sqlite_master where type='view' and name='{tablename}';";
  644. using (var reader = command.ExecuteReader())
  645. {
  646. if (reader.HasRows)
  647. while (reader.Read())
  648. ExecuteSQL(access,string.Format("DROP VIEW {0}", reader.GetString(0)));
  649. }
  650. }
  651. ddl.Add("CREATE VIEW");
  652. ddl.Add(type.EntityName().Split('.').Last());
  653. ddl.Add("AS");
  654. if (view.Generator is IAutoEntityUnionGenerator union)
  655. {
  656. List<String> queries = new List<String>();
  657. foreach (var table in union.Tables)
  658. {
  659. var columns = Columns.None(table.Entity);
  660. var constants = CheckDefaultColumns(union);
  661. var interfacefields = new Dictionary<string, string>();
  662. LoadFields(union.Definition, interfacefields, null, new CustomProperty[] { });
  663. var entityfields = new Dictionary<string, string>();
  664. LoadFields(table.Entity, entityfields, null, new CustomProperty[] { });
  665. foreach (var field in interfacefields.Keys)
  666. {
  667. if (entityfields.ContainsKey(field))
  668. columns.Add(field);
  669. else
  670. {
  671. var constant = table.Constants.FirstOrDefault(x => String.Equals(x.Mapping.Property, field));
  672. if (constant != null)
  673. constants[field] = constant.Value;
  674. else
  675. constants[field] = null;
  676. }
  677. }
  678. var query = PrepareSelectNonGeneric(table.Entity, new SQLiteCommand(), 'A',
  679. table.Filter, columns, null,
  680. null, constants, int.MaxValue, union.Distinct, false);
  681. queries.Add(query);
  682. }
  683. // var viewfields = new Dictionary<string, string>();
  684. //LoadFields(union.Definition, viewfields, null, new CustomProperty[] { });
  685. // var fields = viewfields.Keys.Select(x => String.Format("[{0}]", x)).ToList();
  686. // if (!fields.Contains("[ID]"))
  687. // fields.Add(String.Format("NULL as [ID]"));
  688. // if (!fields.Contains("[Created]"))
  689. // fields.Add(String.Format("NULL as [Created]"));
  690. // if (!fields.Contains("[CreatedBy]"))
  691. // fields.Add(String.Format("NULL as [CreatedBy]"));
  692. // if (!fields.Contains("[LastUpdate]"))
  693. // fields.Add(String.Format("NULL as [LastUpdate]"));
  694. // if (!fields.Contains("[LastUpdateBy]"))
  695. // fields.Add(String.Format("NULL as [LastUpdateBy]"));
  696. //
  697. // List<String> queries = new List<String>();
  698. // foreach (var entity in union.Entities)
  699. // queries.Add(String.Format("SELECT {0} {1} FROM {2}",
  700. // union.Distinct ? "DISTINCT" : "",
  701. // String.Join(", ", fields),
  702. // entity.EntityName().Split('.').Last())
  703. // );
  704. ddl.Add(String.Join(" UNION ", queries));
  705. }
  706. else if ( view.Generator is IAutoEntityCrossGenerator cross)
  707. {
  708. List<String> constants = new List<string>();
  709. foreach (var constant in CheckDefaultColumns(cross))
  710. constants.Add($"{EscapeValue(constant.Value)} as [{constant.Key}]");
  711. String query = String.Format(
  712. "SELECT {0} {1}.[{2}] as [{3}], {4}.[{5}] as [{6}], {7} FROM {1}, {4} WHERE {1}.[{8}] = {4}.[{9}]",
  713. cross.Distinct ? "DISTINCT" : "",
  714. cross.LeftEntity(),
  715. cross.LeftProperty(),
  716. cross.LeftMapping(),
  717. cross.RightEntity(),
  718. cross.RightProperty(),
  719. cross.RightMapping(),
  720. String.Join(", ", constants),
  721. cross.LeftLink(),
  722. cross.RightLink()
  723. );
  724. ddl.Add(query);
  725. }
  726. else if ( view.Generator is IAutoEntityCartesianGenerator cartesian)
  727. {
  728. List<String> fields = new List<string>();
  729. List<String> tables = new List<String>();
  730. List<String> filters = new List<String>();
  731. int iTable = 0;
  732. foreach (var table in cartesian.Tables)
  733. {
  734. var subQueryText = PrepareSelectNonGeneric(table.Type, new SQLiteCommand(), 'A',
  735. table.Filter, table.Columns, null,
  736. null, null, int.MaxValue, cartesian.Distinct, false);
  737. tables.Add($"({subQueryText}) T{iTable}");
  738. foreach (var mapping in table.Mappings)
  739. fields.Add($"T{iTable}.[{mapping.Column.Property}] as [{mapping.Mapping.Property}]");
  740. iTable++;
  741. }
  742. foreach (var constant in cartesian.Constants)
  743. fields.Add($"{EscapeValue(constant.Constant)} as [{constant.Mapping.Property}]");
  744. foreach (var constant in CheckDefaultColumns(cartesian))
  745. fields.Add($"{EscapeValue(constant.Value)} as [{constant.Key}]");
  746. StringBuilder sb = new StringBuilder();
  747. sb.Append("SELECT ");
  748. sb.Append(String.Join(", ", fields));
  749. sb.Append(" FROM ");
  750. sb.Append(String.Join(", ", tables));
  751. if (filters.Any())
  752. sb.Append($" WHERE {String.Join(" AND ", filters)}");
  753. ddl.Add(sb.ToString());
  754. }
  755. ddl.Add(";");
  756. var viewstatement = string.Join(" ", ddl);
  757. }
  758. else
  759. {
  760. ddl.Add("CREATE TABLE");
  761. ddl.Add(type.EntityName().Split('.').Last());
  762. ddl.Add("(");
  763. var fields = new Dictionary<string, string>();
  764. var constraints = new List<string>();
  765. var indexes = new List<string>();
  766. LoadFields(type, fields, null, customproperties);
  767. var defs = new List<string>();
  768. foreach (var key in fields.Keys)
  769. defs.Add(string.Format("[{0}] {1}", key, fields[key]));
  770. if (includeconstraints)
  771. defs.AddRange(constraints);
  772. ddl.Add(string.Join(", ", defs));
  773. ddl.Add(");");
  774. }
  775. var statement = string.Join(" ", ddl);
  776. try
  777. {
  778. ExecuteSQL(access, statement);
  779. }
  780. catch (Exception e)
  781. {
  782. OnLog?.Invoke(LogType.Error, "Unable to Create Table: " + e.Message);
  783. throw;
  784. }
  785. }
  786. private void RebuildTable(SQLiteWriteAccessor access, Type type, Dictionary<string, string> table_fields,
  787. Dictionary<string, string> type_fields,
  788. CustomProperty[] customproperties)
  789. {
  790. var table = type.EntityName().Split('.').Last();
  791. if (type.GetCustomAttribute<AutoEntity>() != null)
  792. {
  793. OnLog?.Invoke(LogType.Information, "Recreating View: " + table);
  794. try
  795. {
  796. String drop = "";
  797. using (var command = access.CreateCommand())
  798. {
  799. command.CommandText =
  800. $"select name from sqlite_master where type='trigger' and tbl_name='{table}' and sql is not null;";
  801. using (var reader = command.ExecuteReader())
  802. {
  803. if (reader.HasRows)
  804. while (reader.Read())
  805. ExecuteSQL(access,string.Format("DROP TRIGGER {0}", reader.GetString(0)));
  806. }
  807. command.CommandText = "select type from sqlite_master where name='" + table + "' and sql is not null;";
  808. using (var reader = command.ExecuteReader())
  809. {
  810. if (reader.HasRows)
  811. while (reader.Read())
  812. drop = reader.GetString(0).ToUpper();
  813. }
  814. }
  815. if (!String.IsNullOrWhiteSpace(drop))
  816. ExecuteSQL(access, string.Format("DROP {0} {1};", drop, table));
  817. CreateTable(access, type, true, customproperties);
  818. }
  819. catch (Exception e)
  820. {
  821. OnLog?.Invoke(LogType.Error, string.Format("RebuildTable({0}) [VIEW] failed: {1}\n{2}", table, e.Message, e.StackTrace));
  822. throw;
  823. }
  824. }
  825. else
  826. {
  827. OnLog?.Invoke(LogType.Information, "Rebuilding Table: " + table);
  828. try
  829. {
  830. ExecuteSQL(access, "PRAGMA foreign_keys = off;");
  831. // using (var command = access.CreateCommand())
  832. // {
  833. //
  834. // command.CommandText =
  835. // $"select name from sqlite_master where type='trigger' and tbl_name='{table}' and sql is not null;";
  836. // using (var reader = command.ExecuteReader())
  837. // {
  838. // if (reader.HasRows)
  839. // while (reader.Read())
  840. // ExecuteSQL(access,string.Format("DROP TRIGGER {0}", reader.GetString(0)));
  841. // }
  842. // command.CommandText = $"select name from sqlite_master where type='view' and name='{table}';";
  843. // using (var reader = command.ExecuteReader())
  844. // {
  845. // if (reader.HasRows)
  846. // while (reader.Read())
  847. // ExecuteSQL(access,string.Format("DROP VIEW {0}", reader.GetString(0)));
  848. // }
  849. // }
  850. using (var transaction = access.Connection.BeginTransaction())
  851. {
  852. var drops = new List<string>();
  853. using (var command = access.CreateCommand())
  854. {
  855. //command.CommandText = String.Format("select name from sqlite_master where type='trigger' and tbl_name='{0}' and sql is not null;", table);
  856. command.CommandText = "select name from sqlite_master where type='view' and sql is not null;";
  857. using (var reader = command.ExecuteReader())
  858. {
  859. if (reader.HasRows)
  860. while (reader.Read())
  861. drops.Add(string.Format("DROP VIEW {0}", reader.GetString(0)));
  862. }
  863. //command.CommandText = String.Format("select name from sqlite_master where type='trigger' and tbl_name='{0}' and sql is not null;", table);
  864. command.CommandText = "select name from sqlite_master where type='trigger' and sql is not null;";
  865. using (var reader = command.ExecuteReader())
  866. {
  867. if (reader.HasRows)
  868. while (reader.Read())
  869. drops.Add(string.Format("DROP TRIGGER {0}", reader.GetString(0)));
  870. }
  871. command.CommandText = string.Format(
  872. "select name from sqlite_master where type='index' and tbl_name='{0}' and sql is not null;",
  873. table);
  874. using (var reader = command.ExecuteReader())
  875. {
  876. if (reader.HasRows)
  877. while (reader.Read())
  878. drops.Add(string.Format("DROP INDEX {0}", reader.GetString(0)));
  879. }
  880. }
  881. foreach (var drop in drops)
  882. ExecuteSQL(access, drop);
  883. bool existingtable = false;
  884. using (var command = access.CreateCommand())
  885. {
  886. command.CommandText =
  887. $"select name from sqlite_master where type='table' and tbl_name='{table}' and sql is not null;";
  888. using (var reader = command.ExecuteReader())
  889. {
  890. if (reader.HasRows)
  891. existingtable = true;
  892. }
  893. }
  894. if (existingtable)
  895. ExecuteSQL(access, string.Format("ALTER TABLE {0} RENAME TO _{0}_old;", table));
  896. CreateTable(access, type, true, customproperties);
  897. var fields = new List<string>();
  898. foreach (var field in type_fields.Keys)
  899. if (table_fields.ContainsKey(field))
  900. fields.Add("[" + field + "]");
  901. if (existingtable)
  902. {
  903. ExecuteSQL(access,
  904. string.Format("INSERT INTO {0} ({1}) SELECT {1} FROM _{0}_old;", table,
  905. string.Join(", ", fields)));
  906. ExecuteSQL(access, string.Format("DROP TABLE _{0}_old;", table));
  907. }
  908. transaction.Commit();
  909. }
  910. ExecuteSQL(access, "PRAGMA foreign_keys = on;");
  911. }
  912. catch (Exception e)
  913. {
  914. OnLog?.Invoke(LogType.Error, string.Format("RebuildTable({0}) [TABLE] failed: {1}\n{2}", table, e.Message, e.StackTrace));
  915. throw;
  916. }
  917. }
  918. }
  919. private void CheckFields(SQLiteWriteAccessor access, Type type, Dictionary<string, string> current_fields, CustomProperty[] customproperties)
  920. {
  921. var type_fields = new Dictionary<string, string>();
  922. var view = type.GetCustomAttribute<AutoEntity>();
  923. if ((view != null) && (view.Generator != null))
  924. LoadFields(view.Generator.Definition, type_fields, null, customproperties);
  925. else
  926. LoadFields(type, type_fields, null, customproperties);
  927. var bRebuild = false;
  928. foreach (var field in type_fields.Keys)
  929. {
  930. try
  931. {
  932. Type tType;
  933. var cprop = customproperties.FirstOrDefault(x => string.Equals(x.Name, field));
  934. if (cprop != null)
  935. tType = cprop.PropertyType;
  936. else
  937. tType = CoreUtils.GetProperty(type, field).PropertyType;
  938. if ((view == null) && (tType == typeof(TimeSpan)) && current_fields.ContainsKey(field) && !current_fields[field].Equals(type_fields[field]))
  939. {
  940. var sql = string.Format(
  941. "update {0} set [{1}] = cast(substr([{1}],1,2) as double) + cast(substr([{1}],4,2) as double)/60 + cast(substr([{1}],7,2) as double)/3600 where [{1}] like \"%:%:%\"",
  942. type.Name, field);
  943. ExecuteSQL(access, sql);
  944. }
  945. }
  946. catch (Exception e)
  947. {
  948. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  949. }
  950. if (!current_fields.ContainsKey(field) || (!String.IsNullOrWhiteSpace(current_fields[field])) && (current_fields[field] != type_fields[field]))
  951. bRebuild = true;
  952. }
  953. foreach (var field in current_fields.Keys)
  954. if (!type_fields.ContainsKey(field))
  955. bRebuild = true;
  956. if (bForceRebuild || bRebuild)
  957. RebuildTable(access, type, current_fields, type_fields, customproperties);
  958. }
  959. private void CheckIndexes(SQLiteWriteAccessor access, Type type, Dictionary<string, string> db_indexes)
  960. {
  961. var type_indexes = LoadIndexes(type);
  962. foreach (var index in db_indexes.Keys)
  963. if (!type_indexes.Contains(db_indexes[index]))
  964. ExecuteSQL(access, string.Format("DROP INDEX {0}", index));
  965. foreach (var index in type_indexes)
  966. if (!db_indexes.ContainsValue(index))
  967. ExecuteSQL(access, index);
  968. }
  969. private void CheckTriggers(SQLiteWriteAccessor access, Type type, Dictionary<string, string> db_triggers)
  970. {
  971. LoadDeletions(type);
  972. /*
  973. #if PURGE
  974. foreach (var trigger in db_triggers.Keys)
  975. ExecuteSQL(access, string.Format("DROP TRIGGER {0}", trigger));
  976. #else*/
  977. var type_trigger = LoadTrigger(type);
  978. foreach (var (key, trigger) in db_triggers)
  979. if (!Equals(type_trigger, trigger))
  980. ExecuteSQL(access, $"DROP TRIGGER {key}");
  981. if(type_trigger is not null)
  982. {
  983. if (!db_triggers.ContainsValue(type_trigger))
  984. ExecuteSQL(access, type_trigger);
  985. }
  986. //#endif
  987. }
  988. // private void CheckViews(SQLiteWriteAccessor access, Type type, Dictionary<String, String> db_views)
  989. // {
  990. // var type_view = LoadView(type);
  991. //
  992. //
  993. // if (!type_triggers.Contains(db_triggers[viewname]))
  994. // ExecuteSQL(access, string.Format("DROP TRIGGER {0}", trigger));
  995. //
  996. // if (!db_views.ContainsValue(type_view))
  997. // ExecuteSQL(access, type_view);
  998. // }
  999. #endregion
  1000. #region CRUD Operations
  1001. private static bool IsNull([NotNullWhen(false)] object? o)
  1002. {
  1003. return o == null || o is DBNull;
  1004. }
  1005. public object? Decode(object o, Type type)
  1006. {
  1007. if (IsNull(o))
  1008. return type == typeof(string) ? "" : type.GetDefault();
  1009. if (type == typeof(string[]))
  1010. {
  1011. if (!IsNull(o))
  1012. {
  1013. if (o is byte[] array)
  1014. using (var ms = new MemoryStream(array))
  1015. {
  1016. #pragma warning disable SYSLIB0011
  1017. var deser = new BinaryFormatter().Deserialize(ms);
  1018. #pragma warning restore SYSLIB0011
  1019. return deser as string[];
  1020. }
  1021. return Array.Empty<string>();
  1022. }
  1023. return Array.Empty<string>();
  1024. }
  1025. if (type.GetInterfaces().Contains(typeof(IPackable)))
  1026. {
  1027. var packable = (Activator.CreateInstance(type) as IPackable)!; // Not-null because of above check
  1028. if (!IsNull(o))
  1029. {
  1030. if (o is byte[] array)
  1031. {
  1032. using (var ms = new MemoryStream(array))
  1033. packable.Unpack(new BinaryReader(ms));
  1034. }
  1035. }
  1036. return packable;
  1037. }
  1038. if (type == typeof(DateTime))
  1039. return IsNull(o) || string.IsNullOrEmpty(o.ToString()) ? DateTime.MinValue : DateTime.Parse(o.ToString() ?? "");
  1040. if (type == typeof(TimeSpan))
  1041. {
  1042. if (IsNull(o))
  1043. return TimeSpan.MinValue;
  1044. var oStr = o.ToString() ?? "";
  1045. if (double.TryParse(oStr, out var hrs))
  1046. return TimeSpan.FromHours(hrs);
  1047. if (oStr.Contains(':'))
  1048. return TimeSpan.Parse(oStr);
  1049. }
  1050. if (type == typeof(Guid))
  1051. return IsNull(o) ? Guid.Empty : Guid.Parse(o.ToString() ?? "");
  1052. if (type == typeof(bool))
  1053. {
  1054. var oStr = o.ToString() ?? "";
  1055. return !IsNull(o) && (oStr.Equals("1") || oStr.ToUpper().Equals("TRUE"));
  1056. }
  1057. if (type.IsEnum)
  1058. return Enum.Parse(type, o.ToString() ?? "");
  1059. if (IsNull(o))
  1060. return null;
  1061. if (type == typeof(long))
  1062. return o;
  1063. var result = CoreUtils.ChangeType(o, type);
  1064. return result;
  1065. }
  1066. public static object Encode(object? o, Type? type)
  1067. {
  1068. if (IsNull(o) || type is null)
  1069. return DBNull.Value;
  1070. if (type == typeof(DateTime) && o.GetType() == typeof(string))
  1071. o = DateTime.Parse(o.ToString() ?? "");
  1072. if (type == typeof(double) && o.GetType() == typeof(string))
  1073. o = double.Parse(o.ToString() ?? "");
  1074. if (type == typeof(float) && o.GetType() == typeof(string))
  1075. o = float.Parse(o.ToString() ?? "");
  1076. if (type == typeof(long) && o.GetType() == typeof(string))
  1077. o = long.Parse(o.ToString() ?? "");
  1078. if (type.IsEnum && o.GetType() == typeof(string))
  1079. o = Enum.Parse(type, o.ToString() ?? "");
  1080. if (type == typeof(TimeSpan) && o.GetType() == typeof(string))
  1081. {
  1082. if (o.ToString()?.Contains(':') == true)
  1083. {
  1084. if (TimeSpan.TryParse(o.ToString(), out var time))
  1085. o = time;
  1086. }
  1087. else if (double.TryParse(o.ToString(), out var hrs))
  1088. {
  1089. o = TimeSpan.FromHours(hrs);
  1090. }
  1091. }
  1092. if (type == typeof(bool))
  1093. {
  1094. if (o.GetType() == typeof(string))
  1095. o = bool.Parse(o.ToString() ?? "");
  1096. if (o.Equals(false))
  1097. return DBNull.Value;
  1098. return o;
  1099. }
  1100. if (type == typeof(string) && string.IsNullOrEmpty(o.ToString()))
  1101. return DBNull.Value;
  1102. if (type == typeof(Guid) && o.GetType() == typeof(string))
  1103. o = Guid.Parse(o.ToString() ?? "");
  1104. if (o is string[])
  1105. using (var ms = new MemoryStream())
  1106. {
  1107. #pragma warning disable SYSLIB0011
  1108. new BinaryFormatter().Serialize(ms, o);
  1109. #pragma warning restore SYSLIB0011
  1110. return ms.GetBuffer();
  1111. }
  1112. if (o is IPackable pack)
  1113. {
  1114. using var ms = new MemoryStream();
  1115. using var writer = new BinaryWriter(ms);
  1116. pack.Pack(writer);
  1117. return ms.ToArray();
  1118. }
  1119. if (o.GetType() == typeof(double) && o.Equals(default(double)))
  1120. return DBNull.Value;
  1121. if (o.GetType() == typeof(float) && o.Equals(default(float)))
  1122. return DBNull.Value;
  1123. if (o.GetType() == typeof(int) && o.Equals(default(int)))
  1124. return DBNull.Value;
  1125. if (o.GetType() == typeof(long) && o.Equals(default(long)))
  1126. return DBNull.Value;
  1127. if (o.GetType() == typeof(DateTime))
  1128. {
  1129. if ((DateTime)o == DateTime.MinValue)
  1130. return DBNull.Value;
  1131. return string.Format("{0:yyyy-MM-dd HH:mm:ss.FFFFFFF}", o);
  1132. }
  1133. if (o.GetType() == typeof(TimeSpan))
  1134. {
  1135. if (((TimeSpan)o).Ticks == 0L)
  1136. return DBNull.Value;
  1137. return ((TimeSpan)o).TotalHours;
  1138. }
  1139. if (o.GetType() == typeof(Guid))
  1140. {
  1141. if (o.Equals(Guid.Empty))
  1142. return DBNull.Value;
  1143. return o.ToString() ?? "";
  1144. }
  1145. if (type == typeof(double) && o.GetType() == typeof(string))
  1146. if (double.TryParse((string)o, out var value))
  1147. o = value;
  1148. if (o.GetType().IsEnum)
  1149. return o.ToString() ?? "";
  1150. return o;
  1151. }
  1152. private static readonly Dictionary<Operator, string> operators = new()
  1153. {
  1154. { Operator.IsEqualTo, "{0} = {1}" },
  1155. { Operator.IsNotEqualTo, "{0} != {1}" },
  1156. { Operator.IsGreaterThan, "{0} > {1}" },
  1157. { Operator.IsGreaterThanOrEqualTo, "{0} >= {1}" },
  1158. { Operator.IsLessThan, "{0} < {1}" },
  1159. { Operator.IsLessThanOrEqualTo, "{0} <= {1}" },
  1160. { Operator.BeginsWith, "{0} LIKE {1} || '%'" },
  1161. { Operator.Contains, "{0} LIKE '%' || {1} || '%'" },
  1162. { Operator.EndsWith, "{0} LIKE '%' || {1}" },
  1163. { Operator.InList, "{0} IN ({1})" },
  1164. { Operator.NotInList, "{0} NOT IN ({1})" },
  1165. { Operator.InQuery, "{0} IN ({1})" },
  1166. { Operator.NotInQuery, "{0} NOT IN ({1})" }
  1167. };
  1168. private static string EscapeValue(object? value)
  1169. {
  1170. if (IsNull(value))
  1171. return "NULL";
  1172. if ((value is string) || (value is Enum) || (value is Guid))
  1173. return string.Format("\'" + "{0}" + "\'", value.ToString()?.Replace("\'", "\'\'"));
  1174. if (value is string[])
  1175. return string.Format("hex({0})", BitConverter.ToString(Encoding.ASCII.GetBytes(value.ToString() ?? "")).Replace("-", ""));
  1176. if (value is IColumn col)
  1177. return $"[{col.Property}]";
  1178. return value.ToString() ?? "";
  1179. }
  1180. private static string GetFilterConstant(FilterConstant constant)
  1181. {
  1182. return constant switch
  1183. {
  1184. FilterConstant.Now => "datetime()",
  1185. FilterConstant.Today => "datetime(date())",
  1186. FilterConstant.Zero => "0",
  1187. // These figures are based around today
  1188. FilterConstant.OneWeekAgo => "datetime(date(),'-7 days')",
  1189. FilterConstant.OneWeekAhead => "datetime(date(),'+7 days')",
  1190. FilterConstant.OneMonthAgo => "datetime(date(),'-1 month')",
  1191. FilterConstant.OneMonthAhead => "datetime(date(),'+1 month')",
  1192. FilterConstant.ThreeMonthsAgo => "datetime(date(),'-3 months')",
  1193. FilterConstant.ThreeMonthsAhead => "datetime(date(),'+3 months')",
  1194. FilterConstant.SixMonthsAgo => "datetime(date(),'-6 months')",
  1195. FilterConstant.SixMonthsAhead => "datetime(date(),'+6 months')",
  1196. FilterConstant.OneYearAgo => "datetime(date(),'-1 year')",
  1197. FilterConstant.OneYearAhead => "datetime(date(),'+1 year')",
  1198. // Relative Week values run from Monday thru Sunday
  1199. FilterConstant.StartOfLastWeek => "datetime(date(), 'weekday 0', '-13 days')",
  1200. FilterConstant.EndOfLastWeek => "datetime(date(), 'weekday 0', '-6 days', '-000.0001 seconds')",
  1201. FilterConstant.StartOfThisWeek => "datetime(date(), 'weekday 0', '-6 days')",
  1202. FilterConstant.EndOfThisWeek => "datetime(date(), 'weekday 0', '+1 day', '-000.0001 seconds')",
  1203. FilterConstant.StartOfNextWeek => "datetime(date(), 'weekday 0', '+1 days')",
  1204. FilterConstant.EndOfNextWeek => "datetime(date(), 'weekday 0', '+8 days', '-000.0001 seconds')",
  1205. FilterConstant.StartOfLastMonth => "datetime(date(), 'start of month', '-1 month')",
  1206. FilterConstant.EndOfLastMonth => "datetime(date(), 'start of month', '-000.0001 seconds')",
  1207. FilterConstant.StartOfThisMonth => "datetime(date(), 'start of month')",
  1208. FilterConstant.EndOfThisMonth => "datetime(date(), 'start of month', '+1 month', '-000.0001 seconds')",
  1209. FilterConstant.StartOfNextMonth => "datetime(date(), 'start of month', '+1 month')",
  1210. FilterConstant.EndOfNextMonth => "datetime(date(), 'start of month', '+2 months', '-000.0001 seconds')",
  1211. FilterConstant.StartOfLastCalendarYear => "datetime(date(), 'start of year', '-1 year')",
  1212. FilterConstant.EndOfLastCalendarYear => "datetime(date(), 'start of year', '-000.0001 seconds')",
  1213. FilterConstant.StartOfThisCalendarYear => "datetime(date(), 'start of year')",
  1214. FilterConstant.EndOfThisCalendarYear => "datetime(date(), 'start of year', '+1 year', '-000.0001 seconds')",
  1215. FilterConstant.StartOfNextCalendarYear => "datetime(date(), 'start of year', '+1 year')",
  1216. FilterConstant.EndOfNextCalendarYear => "datetime(date(), 'start of year', '+2 years', '-000.0001 seconds')",
  1217. FilterConstant.StartOfLastFinancialYear => "datetime(date(), '-18 months', 'start of year', '+6 months')",
  1218. FilterConstant.EndOfLastFinancialYear => "datetime(date(), '-18 months', 'start of year', '-18 months', '-000.0001 seconds')",
  1219. FilterConstant.StartOfThisFinancialYear => "datetime(date(), '-6 months', 'start of year', '+6 months')",
  1220. FilterConstant.EndOfThisFinancialYear => "datetime(date(), '-6 months', 'start of year', '+18 months', '-000.0001 seconds')",
  1221. FilterConstant.StartOfNextFinancialYear => "datetime(date(), '+6 months', 'start of year', '+6 months')",
  1222. FilterConstant.EndOfNextFinancialYear => "datetime(date(), '+6 months', 'start of year', '+18 months', '-000.0001 seconds')",
  1223. _ => throw new Exception($"FilterConstant.{constant} is not implemented!"),
  1224. };
  1225. }
  1226. private string GetFilterClauseNonGeneric(Type T, SQLiteCommand command, char prefix, IFilter? filter, List<Tuple<string, string, string, string>> tables,
  1227. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1228. {
  1229. if (filter == null || filter.Expression == null)
  1230. return "";
  1231. var result = "";
  1232. if (filter.Operator == Operator.All)
  1233. {
  1234. result = filter.IsNot ? "1 = 0" : "1 = 1";
  1235. }
  1236. else if (filter.Operator == Operator.None)
  1237. {
  1238. result = filter.IsNot ? "1 = 1" : "1 = 0";
  1239. }
  1240. else
  1241. {
  1242. string prop;
  1243. if (CoreUtils.TryFindMemberExpression(filter.Expression, out var mexp))
  1244. {
  1245. prop = CoreUtils.GetFullPropertyName(mexp, ".");
  1246. }
  1247. else
  1248. {
  1249. prop = filter.Expression.ToString();
  1250. if (prop.Contains("=>"))
  1251. prop = string.Join(".", prop.Split('.').Skip(1));
  1252. mexp = CoreUtils.GetMemberExpression(T, prop);
  1253. }
  1254. LoadFieldsandTables(command, T, prefix, fieldmap, tables, columns, prop, useparams);
  1255. if (fieldmap.ContainsKey(prop))
  1256. prop = fieldmap[prop];
  1257. if(filter.Value is CustomFilterValue)
  1258. {
  1259. throw new Exception("Custom Filter Value not able to be processed server-side!");
  1260. }
  1261. if (filter.Operator == Operator.InList || filter.Operator == Operator.NotInList)
  1262. {
  1263. // if, and only if the list contains Guids, we can safely bypass the
  1264. // 1000-parameter limit by using building the string ourselves
  1265. if (filter.Value is Guid[] list)
  1266. {
  1267. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Format("\"{0}\"", string.Join("\",\"", list)));
  1268. }
  1269. else if (filter.Value is IEnumerable enumerable)
  1270. {
  1271. var paramlist = new List<object>();
  1272. foreach (var item in enumerable)
  1273. {
  1274. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1275. command.Parameters.AddWithValue(sParam, Encode(item, mexp.Type));
  1276. paramlist.Add(sParam);
  1277. }
  1278. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Join(",", paramlist));
  1279. }
  1280. }
  1281. else if (filter.Operator == Operator.InQuery || filter.Operator == Operator.NotInQuery)
  1282. {
  1283. if(filter.Value is ISubQuery subQuery)
  1284. {
  1285. var subEntityType = subQuery.GetQueryType();
  1286. var subColumns = Columns.None(subEntityType);
  1287. var subColumn = subQuery.GetColumn();
  1288. subColumns.Add(subColumn);
  1289. var subQueryText = PrepareSelectNonGeneric(subEntityType, command, 'A',
  1290. subQuery.GetFilter(), subColumns, null,
  1291. null, null, int.MaxValue, false, useparams);
  1292. result = string.Format("(" + operators[filter.Operator] + ")", prop, subQueryText);
  1293. }
  1294. }
  1295. else
  1296. {
  1297. if (filter.Value is FilterConstant constant)
  1298. result = string.Format("(" + operators[filter.Operator] + ")", prop, GetFilterConstant(constant));
  1299. else
  1300. {
  1301. var value = Encode(filter.Value, mexp.Type);
  1302. if (IsNull(value) && ((filter.Operator == Operator.IsEqualTo) || (filter.Operator == Operator.IsNotEqualTo)))
  1303. {
  1304. result = string.Format("({0} {1} NULL)", prop,
  1305. filter.Operator == Operator.IsEqualTo
  1306. ? "IS"
  1307. : "IS NOT");
  1308. }
  1309. else
  1310. {
  1311. if (useparams)
  1312. {
  1313. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1314. if (filter.Expression.Type == typeof(string[]))
  1315. {
  1316. var bytes = Encoding.ASCII.GetBytes(value.ToString() ?? "");
  1317. value = BitConverter.ToString(bytes).Replace("-", "");
  1318. result = string.Format("(" + operators[filter.Operator] + ")", string.Format("hex({0})", prop), sParam);
  1319. }
  1320. else
  1321. {
  1322. result = string.Format("(" + operators[filter.Operator] + ")", prop, sParam);
  1323. }
  1324. command.Parameters.AddWithValue(sParam, value);
  1325. }
  1326. else
  1327. result = string.Format("(" + operators[filter.Operator] + ")", prop, EscapeValue(filter.Value));
  1328. }
  1329. }
  1330. }
  1331. if (filter.IsNot)
  1332. {
  1333. result = $"(NOT {result})";
  1334. }
  1335. }
  1336. var bChanged = false;
  1337. if (filter.Ands != null && filter.Ands.Any())
  1338. {
  1339. foreach (var and in filter.Ands)
  1340. {
  1341. var AndResult = GetFilterClauseNonGeneric(T, command, prefix, and, tables, fieldmap, columns, useparams);
  1342. if (!string.IsNullOrEmpty(AndResult))
  1343. {
  1344. result = string.Format("{0} and {1}", result, AndResult);
  1345. bChanged = true;
  1346. }
  1347. }
  1348. if (bChanged)
  1349. result = string.Format("({0})", result);
  1350. }
  1351. bChanged = false;
  1352. if (filter.Ors != null && filter.Ors.Any())
  1353. {
  1354. foreach (var or in filter.Ors)
  1355. {
  1356. var OrResult = GetFilterClauseNonGeneric(T, command, prefix, or, tables, fieldmap, columns, useparams);
  1357. if (!string.IsNullOrEmpty(OrResult))
  1358. {
  1359. result = string.Format("{0} or {1}", result, OrResult);
  1360. bChanged = true;
  1361. }
  1362. }
  1363. if (bChanged)
  1364. result = string.Format("({0})", result);
  1365. }
  1366. return result;
  1367. }
  1368. private string GetFilterClause<T>(SQLiteCommand command, char prefix, Filter<T>? filter, List<Tuple<string, string, string, string>> tables,
  1369. Dictionary<string, string> fieldmap, List<string> columns, bool useparams) where T : Entity
  1370. => GetFilterClauseNonGeneric(typeof(T), command, prefix, filter, tables, fieldmap, columns, useparams);
  1371. private string GetSortClauseNonGeneric(Type T,
  1372. SQLiteCommand command, ISortOrder? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1373. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1374. {
  1375. if (sort == null)
  1376. return "";
  1377. var result = "";
  1378. if (sort.Expression != null)
  1379. {
  1380. if (CoreUtils.TryFindMemberExpression(sort.Expression, out var mexp))
  1381. result = CoreUtils.GetFullPropertyName(mexp, ".");
  1382. else
  1383. result = sort.Expression.ToString();
  1384. var prop = CoreUtils.GetProperty(T, result);
  1385. if (prop.GetCustomAttribute<DoNotSerialize>() == null && prop.GetCustomAttribute<DoNotPersist>() == null && prop.CanWrite)
  1386. {
  1387. LoadFieldsandTables(command, T, prefix, fieldmap, tables, columns, result, useparams);
  1388. if (fieldmap.ContainsKey(result))
  1389. result = fieldmap[result];
  1390. if (sort.Expression.Type.Equals(typeof(string)))
  1391. result = string.Format("{0} COLLATE NOCASE", result);
  1392. if (sort.Direction == SortDirection.Ascending)
  1393. result = string.Format("{0} ASC", result);
  1394. else
  1395. result = string.Format("{0} DESC", result);
  1396. }
  1397. else
  1398. {
  1399. result = "";
  1400. }
  1401. }
  1402. foreach (var then in sort.Thens)
  1403. result = result + ", " + GetSortClauseNonGeneric(T, command, then, prefix, tables, fieldmap, columns, useparams);
  1404. return result;
  1405. }
  1406. private string GetSortClause<T>(SQLiteCommand command, SortOrder<T>? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1407. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1408. => GetSortClauseNonGeneric(typeof(T), command, sort, prefix, tables, fieldmap, columns, useparams);
  1409. private static string GetCalculation(AggregateAttribute attribute, string columnname)
  1410. {
  1411. return attribute.Calculation switch
  1412. {
  1413. AggregateCalculation.Sum => "SUM",
  1414. AggregateCalculation.Count => "COUNT",
  1415. AggregateCalculation.Maximum => "MAX",
  1416. AggregateCalculation.Minimum => "MIN",
  1417. AggregateCalculation.Average => "AVERAGE",
  1418. AggregateCalculation.Concat => "GROUP_CONCAT",
  1419. _ => throw new Exception(string.Format("{0}.{1} is not a valid aggregate", columnname, attribute.Calculator.GetType().Name)),
  1420. };
  1421. }
  1422. private string GetFunction(FormulaAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1423. {
  1424. if (attribute.Operator == FormulaOperator.None)
  1425. throw new Exception(string.Format("{0}.{1} is not a valid formula", columnname, attribute.Calculator.GetType().Name));
  1426. if (attribute.Operator == FormulaOperator.Constant)
  1427. return EscapeValue(attribute.Value);
  1428. if (!fieldmap.ContainsKey(attribute.Value))
  1429. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Value));
  1430. foreach (var modifier in attribute.Modifiers)
  1431. if (!fieldmap.ContainsKey(modifier))
  1432. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, modifier));
  1433. if (attribute.Operator == FormulaOperator.Add)
  1434. return string.Format("(IFNULL({0},0.00) + {1})", fieldmap[attribute.Value],
  1435. string.Join(" + ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1436. if (attribute.Operator == FormulaOperator.Subtract)
  1437. return string.Format("(IFNULL({0},0.00) - ({1}))", fieldmap[attribute.Value],
  1438. string.Join(" + ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1439. if (attribute.Operator == FormulaOperator.Multiply)
  1440. return string.Format("(IFNULL({0},0.00) * {1})", fieldmap[attribute.Value],
  1441. string.Join(" * ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1442. if (attribute.Operator == FormulaOperator.Divide)
  1443. {
  1444. var result = string.Format("IFNULL({0},0.00)", fieldmap[attribute.Value]);
  1445. foreach (var modifier in attribute.Modifiers)
  1446. result = string.Format("({0} / {1})", result, string.Format("IFNULL({0},1.00)", fieldmap[modifier]));
  1447. return result;
  1448. }
  1449. if (attribute.Operator == FormulaOperator.Maximum)
  1450. {
  1451. var parameters = attribute.Modifiers.Select(m => $"IFNULL({fieldmap[m]},0.00)");
  1452. var result = $"MAX({fieldmap[attribute.Value]}, {String.Join(", ", parameters)})";
  1453. // var result = string.Format(
  1454. // "CASE IFNULL({0},0.00) WHEN IFNULL({0},0.00) < IFNULL({1},0.00) THEN IFNULL({1},0.00) ELSE IFNULL({0},0.00) END",
  1455. // fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1456. return result;
  1457. }
  1458. if (attribute.Operator == FormulaOperator.Minumum)
  1459. {
  1460. var parameters = attribute.Modifiers.Select(m => $"IFNULL({fieldmap[m]},0.00)");
  1461. var result = $"MIN({fieldmap[attribute.Value]}, {String.Join(", ", parameters)})";
  1462. //var result = string.Format(
  1463. // "CASE IFNULL({0},0.00) WHEN IFNULL({0},0.00) > IFNULL({1},0.00) THEN IFNULL({1},0.00) ELSE IFNULL({0},0.00) END",
  1464. // fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1465. return result;
  1466. }
  1467. throw new Exception(string.Format("Calculation Type [{0}.{1}] not found", columnname, attribute.GetType().Name));
  1468. }
  1469. private string GetCondition(ConditionAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1470. {
  1471. var intf = attribute.Calculator.GetType().GetInterfaces()
  1472. .FirstOrDefault(x => x.Name.StartsWith("ICondition") && x.GenericTypeArguments.Length.Equals(3));
  1473. if (intf is null)
  1474. throw new Exception($"Attribute calculate {attribute.Calculator} is not an ICondition");
  1475. var valuetype = intf.GenericTypeArguments[1];
  1476. var defvalue = valuetype.GetDefault();
  1477. if (!fieldmap.ContainsKey(attribute.Left))
  1478. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Left));
  1479. var condition = "";
  1480. if (attribute.Condition == Condition.Equals)
  1481. condition = "=";
  1482. else if (attribute.Condition == Condition.NotEqual)
  1483. condition = "<>";
  1484. else if (attribute.Condition == Condition.GreaterThan)
  1485. condition = ">";
  1486. else if (attribute.Condition == Condition.GreaterThanOrEqualTo)
  1487. condition = ">=";
  1488. else if (attribute.Condition == Condition.LessThan)
  1489. condition = "<";
  1490. else if (attribute.Condition == Condition.LessThanOrEqualTo)
  1491. condition = "<=";
  1492. else
  1493. throw new Exception(string.Format("{0}.{1} is not a valid condition", columnname, attribute.Calculator.GetType().Name));
  1494. if (!fieldmap.ContainsKey(attribute.Right))
  1495. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Right));
  1496. if (!fieldmap.ContainsKey(attribute.True))
  1497. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.True));
  1498. if (!fieldmap.ContainsKey(attribute.False))
  1499. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.False));
  1500. return string.Format("CASE WHEN COALESCE({0},{1}) {2} {3} THEN {4} ELSE {5} END", fieldmap[attribute.Left], defvalue, condition,
  1501. fieldmap[attribute.Right], fieldmap[attribute.True], fieldmap[attribute.False]);
  1502. }
  1503. //private static List<string> Breadcrumb = new List<string>();
  1504. //Dictionary<String, Tuple<int, TimeSpan>> stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1505. //Stopwatch sw = new Stopwatch();
  1506. //private void LogReset()
  1507. //{
  1508. // stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1509. // sw = new Stopwatch();
  1510. //}
  1511. //void LogStart()
  1512. //{
  1513. // if (sw.IsRunning)
  1514. // sw.Restart();
  1515. // else
  1516. // sw.Start();
  1517. //}
  1518. //void LogStop(String msg)
  1519. //{
  1520. // TimeSpan elapsed = sw.Elapsed;
  1521. // if (Breadcrumb.Any())
  1522. // msg = String.Join(".", Breadcrumb) + "." + msg;
  1523. // if (!stopwatch.ContainsKey(msg))
  1524. // stopwatch[msg] = new Tuple<int, TimeSpan>(1,elapsed);
  1525. // else
  1526. // stopwatch[msg] = new Tuple<int, TimeSpan>(stopwatch[msg].Item1 + 1,stopwatch[msg].Item2 + elapsed);
  1527. // sw.Restart();
  1528. //}
  1529. //private void LogPrint(String header)
  1530. //{
  1531. // foreach (var keyvalue in stopwatch.ToArray())
  1532. // OnLog?.Invoke(LogType.Information, String.Format("- {0}: {1} = ({2}) {3,10:0.0000}", header, keyvalue.Key, keyvalue.Value.Item1, keyvalue.Value.Item2.TotalMilliseconds));
  1533. //}
  1534. private void LoadFieldsandTables(SQLiteCommand command, Type type, char prefix, Dictionary<string, string> fieldmap,
  1535. List<Tuple<string, string, string, string>> tables, List<string> columns, string columnname, bool useparams)
  1536. {
  1537. if (fieldmap.ContainsKey(columnname))
  1538. return;
  1539. var newprefix = (char)(prefix + 1);
  1540. // LogStart();
  1541. var property = DatabaseSchema.Property(type, columnname);
  1542. // LogStop("DatabaseSchema.Property");
  1543. if (property != null && property is CustomProperty)
  1544. {
  1545. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1546. }
  1547. else
  1548. {
  1549. var bits = columnname.Split('.');
  1550. if (bits.Length == 1)
  1551. {
  1552. var prop = type.GetProperty(columnname);
  1553. if (prop != null)
  1554. {
  1555. // LogStart();
  1556. // LogStop("GetCustomAttributes(Aggregate)");
  1557. if (prop.GetCustomAttribute<AggregateAttribute>() is AggregateAttribute agg)
  1558. {
  1559. bool internalaggregate = agg.Calculator.GetType().GetInterfaces()
  1560. .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICoreAggregate<,>));
  1561. if (internalaggregate)
  1562. {
  1563. }
  1564. else
  1565. {
  1566. var scols = new Dictionary<string, string> { { agg.Aggregate, GetCalculation(agg, columnname) } };
  1567. var siblings = columns.Where(x => !x.Equals(columnname) && x.Split('.').First().Equals(bits.First()))
  1568. .Select(x => string.Join(".", x.Split('.').Skip(1))).ToList();
  1569. var linkedtype = agg.Source;
  1570. foreach (var sibling in siblings)
  1571. {
  1572. // LogStart();
  1573. var sprop = CoreUtils.GetProperty(type, sibling);
  1574. // LogStop("GetProperty(sibling)");
  1575. // LogStart();
  1576. var sattr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  1577. // LogStop("GetCustomAttributes(Sibling.Aggregate)");
  1578. if (sattr is AggregateAttribute sagg)
  1579. {
  1580. // LogStart();
  1581. scols[sagg.Aggregate] = GetCalculation(sagg, sibling);
  1582. // LogStop("GetCalculation(Sibling)");
  1583. }
  1584. }
  1585. var subcols = Columns.None(linkedtype);
  1586. foreach (var key in agg.Links.Keys)
  1587. subcols.Add(key);
  1588. //subcols.Add(agg.Link);
  1589. foreach (var scol in scols.Keys)
  1590. subcols.Add(scol);
  1591. // LogStart();
  1592. var aggFilter = agg.Filter;
  1593. if(aggFilter is not null)
  1594. {
  1595. var ffs = new List<string>();
  1596. FilterFields(aggFilter, ffs);
  1597. //foreach (var ff in ffs)
  1598. // subcols.Add(ff);
  1599. }
  1600. var linkedtable = string.Format("({0})",
  1601. PrepareSelectNonGeneric(linkedtype, command, newprefix, aggFilter, subcols, null, scols, null, int.MaxValue, false, useparams));
  1602. var alias = tables.Count + 1;
  1603. var link = string.Join(" , ", agg.Links.Keys.Select(x => string.Format("{0}{1}.{2}", prefix, alias, x)));
  1604. var tuple = tables.FirstOrDefault(x =>
  1605. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1606. if (tuple == null)
  1607. {
  1608. var joins = new List<string>();
  1609. foreach (var key in agg.Links.Keys)
  1610. joins.Add(
  1611. string.Format("IFNULL({0}{1}.[{2}],'') = IFNULL({0}1.[{3}],'')", prefix, alias, key, agg.Links[key]));
  1612. var join = string.Format("LEFT OUTER JOIN {0} {1}{2} ON {3}", linkedtable, prefix, alias,
  1613. string.Join(" AND ", joins));
  1614. tuple = new Tuple<string, string, string, string>(linkedtable, prefix + alias.ToString(), join, link);
  1615. //tuple = new Tuple<String, String, String, String>(linkedtable, prefix + alias.ToString(), String.Format("LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[{3}] = {1}1.[ID]", linkedtable, prefix, alias, agg.Link), link);
  1616. tables.Add(tuple);
  1617. }
  1618. //if (bits.Last().Equals("ID"))
  1619. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1620. //else
  1621. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, agg.Aggregate);
  1622. //LoadFieldsandTables(command, agg.Type, newprefix, fieldmap, tables, columns, columnname);
  1623. //var linkedtable = String.Format("(SELECT [{3}],{0}([{1}]) as [{1}] from {2} group by [{3}])", GetCalculation(agg, columnname), agg.AggregateProperty, agg.Type.EntityName().Split('.').Last(), agg.LinkedProperty);
  1624. //int alias = tables.Count + 1;
  1625. //var tuple = new Tuple<String, String, String, String>(linkedtable, prefix + alias.ToString(), String.Format("LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[{3}] = {1}1.[ID]", linkedtable, prefix, alias, agg.LinkedProperty), "");
  1626. //tables.Add(tuple);
  1627. //fieldmap[columnname] = String.Format("{0}.[{1}]", tuple.Item2, agg.AggregateProperty);
  1628. }
  1629. }
  1630. else if (prop.GetCustomAttribute<FormulaAttribute>() is FormulaAttribute fnc)
  1631. {
  1632. // var functionmap = new Dictionary<string, string>();
  1633. // CheckColumn(columns, fnc.Value);
  1634. // LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, fnc.Value, useparams);
  1635. // foreach (var column in fnc.Modifiers)
  1636. // {
  1637. // CheckColumn(columns, column);
  1638. // LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, column, useparams);
  1639. // }
  1640. // fieldmap[columnname] = GetFunction(fnc, functionmap, columnname);
  1641. foreach (var field in fnc.Modifiers.Prepend(fnc.Value))
  1642. {
  1643. CheckColumn(columns, field);
  1644. LoadFieldsandTables(command, type, prefix, fieldmap, tables, columns, field, useparams);
  1645. }
  1646. fieldmap[columnname] = GetFunction(fnc, fieldmap, columnname);
  1647. }
  1648. else if(prop.GetCustomAttribute<ConditionAttribute>() is ConditionAttribute cnd)
  1649. {
  1650. var cndmap = new Dictionary<string, string>();
  1651. // LogStart();
  1652. CheckColumn(columns, cnd.Left);
  1653. // LogStop("CheckColumn(Left)");
  1654. // LogStart();
  1655. CheckColumn(columns, cnd.Right);
  1656. // LogStop("CheckColumn(Right)");
  1657. // LogStart();
  1658. CheckColumn(columns, cnd.True);
  1659. // LogStop("CheckColumn(True)");
  1660. // LogStart();
  1661. CheckColumn(columns, cnd.False);
  1662. // LogStop("CheckColumn(False)");
  1663. //// LogStart();
  1664. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Left, useparams);
  1665. //// LogStop("LoadFieldsAndTables(Left)");
  1666. //// LogStart();
  1667. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Right, useparams);
  1668. //// LogStop("LoadFieldsAndTables(Right)");
  1669. //// LogStart();
  1670. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.True, useparams);
  1671. //// LogStop("LoadFieldsAndTables(True)");
  1672. //// LogStart();
  1673. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.False, useparams);
  1674. //// LogStop("LoadFieldsAndTables(False)");
  1675. // LogStart();
  1676. fieldmap[columnname] = GetCondition(cnd, cndmap, columnname);
  1677. // LogStop("GetCondition");
  1678. }
  1679. else
  1680. {
  1681. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1682. }
  1683. }
  1684. else
  1685. {
  1686. //IProperty customprop = DataModel.Property(type, columnname);
  1687. //if (customprop != null)
  1688. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1689. //else
  1690. fieldmap[columnname] = columnname;
  1691. }
  1692. }
  1693. else
  1694. {
  1695. var prop = type.GetProperty(bits.First());
  1696. if (prop != null)
  1697. {
  1698. var combinecount = 1;
  1699. while (prop.PropertyType.HasInterface<IEnclosedEntity>())
  1700. {
  1701. combinecount++;
  1702. prop = CoreUtils.GetProperty(type, string.Join(".", bits.Take(combinecount)));
  1703. }
  1704. var entityLinkInterface = prop.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>));
  1705. if (entityLinkInterface is not null)
  1706. {
  1707. var linkedType = entityLinkInterface.GenericTypeArguments[0];
  1708. var enclosingProperty = string.Join('.', bits.Take(combinecount)) + ".";
  1709. var remoteProperty = string.Join('.', bits.Skip(combinecount));
  1710. var remote = linkedType.GetProperty(remoteProperty);
  1711. // Are there any other properties for this link? These will form the columns for our subquery
  1712. var siblings = columns.Where(x => x.StartsWith(enclosingProperty))
  1713. .Select(x => x[enclosingProperty.Length..]).ToList();
  1714. if (remote != null && !siblings.Contains(remote.Name))
  1715. siblings.Add(remote.Name);
  1716. if(prop.GetCustomAttribute<ChildEntityAttribute>() is ChildEntityAttribute child)
  1717. {
  1718. var parent = child.Calculator.ParentColumn;
  1719. if (!siblings.Contains(nameof(Entity.ID)))
  1720. siblings.Insert(0, nameof(Entity.ID));
  1721. if (!siblings.Contains(parent))
  1722. siblings.Add(parent);
  1723. var subcols = Columns.None(linkedType).Add(siblings);
  1724. var subPrefix = (char)(newprefix + 1);
  1725. var innerSQL = string.Format("({0})",
  1726. PrepareSelectNonGeneric(
  1727. linkedType,
  1728. command,
  1729. subPrefix,
  1730. child.Calculator.Filter,
  1731. subcols,
  1732. child.Calculator.Sort,
  1733. null,
  1734. null,
  1735. int.MaxValue,
  1736. false,
  1737. useparams));
  1738. var linkedTable = $"(SELECT {string.Join(", ", siblings.Select(x => $"{newprefix}1.[{x}] as [{x}]"))}"
  1739. + $" FROM {innerSQL} {newprefix}1"
  1740. + $" GROUP BY [{parent}])";
  1741. var link = string.Format("{0}.ID", prop.Name);
  1742. var tuple = tables.FirstOrDefault(x =>
  1743. x.Item1.Equals(linkedTable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1744. if (tuple is null)
  1745. {
  1746. var alias = tables.Count + 1;
  1747. tuple = new Tuple<string, string, string, string>(
  1748. linkedTable,
  1749. prefix + alias.ToString(),
  1750. string.Format(
  1751. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[{3}] = {1}1.[ID]",
  1752. linkedTable,
  1753. prefix,
  1754. alias,
  1755. parent
  1756. ),
  1757. link
  1758. );
  1759. tables.Add(tuple);
  1760. }
  1761. //if (bits.Last().Equals("ID"))
  1762. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1763. //else
  1764. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  1765. foreach (var sibling in siblings)
  1766. {
  1767. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  1768. if (!subcol.Equals(columnname))
  1769. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  1770. }
  1771. }
  1772. else
  1773. {
  1774. if (siblings.Count.Equals(1) && siblings.First().Equals("ID"))
  1775. {
  1776. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1777. }
  1778. else
  1779. {
  1780. if (!siblings.Contains("ID"))
  1781. siblings.Insert(0, "ID");
  1782. var subcols = Columns.None(linkedType).Add(siblings);
  1783. var linkedtable = string.Format("({0})",
  1784. PrepareSelectNonGeneric(linkedType, command, newprefix, null, subcols, null, null, null, int.MaxValue, false, useparams));
  1785. var link = string.Format("{0}.ID", prop.Name);
  1786. var tuple = tables.FirstOrDefault(x =>
  1787. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1788. if (tuple == null)
  1789. {
  1790. var alias = tables.Count + 1;
  1791. tuple = new Tuple<string, string, string, string>(
  1792. linkedtable,
  1793. prefix + alias.ToString(),
  1794. string.Format(
  1795. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[ID] = {1}1.[{3}.ID]",
  1796. linkedtable,
  1797. prefix,
  1798. alias,
  1799. string.Join(".", bits.Take(combinecount)) //prop.Name
  1800. ),
  1801. link
  1802. );
  1803. tables.Add(tuple);
  1804. }
  1805. //if (bits.Last().Equals("ID"))
  1806. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1807. //else
  1808. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  1809. foreach (var sibling in siblings)
  1810. {
  1811. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  1812. if (!subcol.Equals(columnname))
  1813. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  1814. }
  1815. }
  1816. }
  1817. }
  1818. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  1819. {
  1820. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1821. }
  1822. else
  1823. {
  1824. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1825. }
  1826. }
  1827. else
  1828. {
  1829. fieldmap[columnname] = columnname;
  1830. }
  1831. }
  1832. }
  1833. }
  1834. private static void CheckColumn(List<string> columns, string column)
  1835. {
  1836. if (!columns.Contains(column))
  1837. columns.Add(column);
  1838. }
  1839. public void FilterFields(IFilter? filter, List<string> fields)
  1840. {
  1841. if (filter == null)
  1842. return;
  1843. if (filter.Operator != Operator.None && filter.Operator != Operator.All)
  1844. {
  1845. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(filter.Expression), ".");
  1846. if (!fields.Contains(exp))
  1847. fields.Add(exp);
  1848. }
  1849. foreach (var and in filter.Ands)
  1850. FilterFields(and, fields);
  1851. foreach (var or in filter.Ors)
  1852. FilterFields(or, fields);
  1853. }
  1854. public void SortFields(ISortOrder? sort, List<string> fields)
  1855. {
  1856. if (sort == null)
  1857. return;
  1858. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(sort.Expression), ".");
  1859. if (!fields.Contains(exp))
  1860. fields.Add(exp);
  1861. foreach (var then in sort.Thens)
  1862. SortFields(then, fields);
  1863. }
  1864. public enum AggregateType
  1865. {
  1866. None,
  1867. Sum,
  1868. Count
  1869. }
  1870. public string PrepareSelectNonGeneric(Type T, SQLiteCommand command, char prefix,
  1871. IFilter? filter, IColumns? columns, ISortOrder? sort,
  1872. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, int top, bool distinct, bool useparams)
  1873. {
  1874. var fieldmap = new Dictionary<string, string>();
  1875. var cols = CoreUtils.GetColumns(T, columns);
  1876. var fields = new List<string>();
  1877. fields.AddRange(cols.ColumnNames());
  1878. FilterFields(filter, fields);
  1879. SortFields(sort, fields);
  1880. var tables = new List<Tuple<string, string, string, string>>();
  1881. var condition = "";
  1882. var sortorder = "";
  1883. var entityName = T.EntityName().Split('.').Last();
  1884. tables.Add(new Tuple<string, string, string, string>(
  1885. entityName,
  1886. $"{prefix}1",
  1887. $"{entityName} {prefix}1",
  1888. "")
  1889. );
  1890. foreach (var column in cols.ColumnNames())
  1891. LoadFieldsandTables(command, T, prefix, fieldmap, tables, fields, column, useparams);
  1892. var parameters = new Dictionary<string, object>();
  1893. condition = GetFilterClauseNonGeneric(T, command, prefix, filter, tables, fieldmap, fields, useparams);
  1894. sortorder = GetSortClauseNonGeneric(T, command, sort, prefix, tables, fieldmap, fields, useparams);
  1895. var combined = new SortedDictionary<string, string>();
  1896. fields.Clear();
  1897. foreach (var column in cols.ColumnNames())
  1898. if (fieldmap.TryGetValue(column, out string? value))
  1899. {
  1900. if (aggregates != null && aggregates.ContainsKey(column))
  1901. combined[constants != null ? column : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0}({1}) as [{2}]", aggregates[column], value, column);
  1902. else
  1903. combined[constants != null ? column : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0} as [{1}]", value, column);
  1904. }
  1905. if (constants != null)
  1906. {
  1907. foreach(var (column, value) in constants)
  1908. {
  1909. combined[column] = string.Format("{0} as [{1}]", EscapeValue(value), column);
  1910. }
  1911. }
  1912. var result = new List<string>();
  1913. result.Add("SELECT");
  1914. if (distinct)
  1915. result.Add("DISTINCT");
  1916. result.Add(string.Join(", ", combined.Values));
  1917. result.Add("FROM");
  1918. result.AddRange(tables.Select(x => x.Item3));
  1919. if (!string.IsNullOrWhiteSpace(condition))
  1920. {
  1921. result.Add("WHERE");
  1922. result.Add(condition);
  1923. }
  1924. if (!string.IsNullOrWhiteSpace(sortorder))
  1925. {
  1926. result.Add("ORDER BY");
  1927. result.Add(sortorder);
  1928. }
  1929. if (aggregates != null)
  1930. {
  1931. var str = string.Join(", ",
  1932. fieldmap.Where(x => cols.Contains(x.Key) && !aggregates.ContainsKey(x.Key)).Select(f => f.Value));
  1933. if (!string.IsNullOrWhiteSpace(str))
  1934. {
  1935. result.Add("GROUP BY");
  1936. result.Add(str);
  1937. }
  1938. }
  1939. if (top != int.MaxValue)
  1940. result.Add(String.Format("LIMIT {0}", top));
  1941. //Breadcrumb.Remove(Breadcrumb.Last());
  1942. return string.Join(" ", result);
  1943. }
  1944. public string PrepareSelect<T>(SQLiteCommand command, char prefix, Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort,
  1945. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, int top, bool distinct, bool useparams) where T : Entity
  1946. => PrepareSelectNonGeneric(typeof(T), command, prefix, filter, columns, sort, aggregates, constants, top, distinct, useparams);
  1947. private static void PrepareUpsertNonGeneric(Type T, SQLiteCommand command, Entity item)
  1948. {
  1949. command.CommandText = "";
  1950. command.Parameters.Clear();
  1951. if (item.ID == Guid.Empty)
  1952. item.ID = Guid.NewGuid();
  1953. var insert = item.GetValues(true);
  1954. var update = item.GetValues(false);
  1955. var insertfields = new List<string>();
  1956. var insertvalues = new List<string>();
  1957. var updatecommands = new List<string>();
  1958. var iParam = 0;
  1959. foreach (var (key, v) in insert)
  1960. {
  1961. if (v is UserProperties)
  1962. continue;
  1963. var sParam = string.Format("@p{0}", iParam++);
  1964. object? value = null;
  1965. try
  1966. {
  1967. value = Encode(v, v?.GetType());
  1968. }
  1969. catch (Exception e)
  1970. {
  1971. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1972. }
  1973. command.Parameters.AddWithValue(sParam, value);
  1974. insertfields.Add(string.Format("[{0}]", key));
  1975. insertvalues.Add(sParam);
  1976. if (update.ContainsKey(key))
  1977. if (!key.Equals("ID"))
  1978. updatecommands.Add(string.Format("[{0}]={1}", key, sParam));
  1979. }
  1980. var particles = new List<string>
  1981. {
  1982. "INSERT INTO",
  1983. T.EntityName().Split('.').Last(),
  1984. "(",
  1985. string.Join(",", insertfields),
  1986. ")",
  1987. "VALUES",
  1988. "(",
  1989. string.Join(",", insertvalues),
  1990. ")"
  1991. };
  1992. if (updatecommands.Count != 0)
  1993. particles.Add("ON CONFLICT([ID]) DO UPDATE SET " + string.Join(", ", updatecommands));
  1994. else
  1995. particles.Add("ON CONFLICT DO NOTHING");
  1996. command.CommandText = string.Join(" ", particles);
  1997. }
  1998. private void PrepareUpsert<T>(SQLiteCommand command, T item) where T : Entity
  1999. => PrepareUpsertNonGeneric(typeof(T), command, item);
  2000. public void PrepareDelete<T>(SQLiteCommand command, T item) where T : Entity
  2001. {
  2002. command.CommandText = string.Format("DELETE FROM {0} WHERE [ID] = @p0", typeof(T).EntityName().Split('.').Last());
  2003. command.Parameters.Clear();
  2004. command.Parameters.AddWithValue("@p0", Encode(item.ID, typeof(Guid)));
  2005. }
  2006. #endregion
  2007. #region CRUD Operations
  2008. public static object[] GetValues(IDataReader reader, int count)
  2009. {
  2010. var result = new object[count];
  2011. reader.GetValues(result);
  2012. return result;
  2013. }
  2014. #region Query
  2015. public IEnumerable<object[]> List<T>(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null) where T : Entity, new()
  2016. {
  2017. //Dictionary<String, TimeSpan> stopwatch = new Dictionary<string, TimeSpan>();
  2018. //Stopwatch sw = new Stopwatch();
  2019. //sw.Start();
  2020. var cols = CoreUtils.GetColumns(columns);
  2021. //stopwatch["GetColumns"] = new TimeSpan(sw.ElapsedTicks);
  2022. //sw.Restart();
  2023. var result = new List<object[]>();
  2024. //stopwatch["MakeResult"] = new TimeSpan(sw.ElapsedTicks);
  2025. //sw.Restart();
  2026. using (var access = GetReadAccess())
  2027. {
  2028. using (var command = access.CreateCommand())
  2029. {
  2030. var sortorder = sort ?? LookupFactory.DefineSort<T>();
  2031. command.CommandText = "";
  2032. command.Parameters.Clear();
  2033. command.CommandText = PrepareSelect(command, 'A', filter, cols, sortorder, null, null, int.MaxValue, false, true) + ";";
  2034. using (var reader = command.ExecuteReader())
  2035. {
  2036. foreach (var row in reader)
  2037. {
  2038. var values = GetValues(reader, cols.Count);
  2039. result.Add(values);
  2040. }
  2041. reader.Close();
  2042. }
  2043. }
  2044. }
  2045. return result;
  2046. }
  2047. private CoreTable DoQueryNonGeneric(Type T, IFilter? filter = null, IColumns? columns = null, ISortOrder? sort = null, int top = int.MaxValue, bool log = false, bool distinct = false)
  2048. {
  2049. var start = DateTime.Now;
  2050. //LogReset();
  2051. //LogStart();
  2052. //LogStop("GetColumns");
  2053. var cols = CoreUtils.GetColumns(T, columns);
  2054. var blobColumns = Columns.None(T);
  2055. foreach(var column in cols)
  2056. {
  2057. var prop = DatabaseSchema.Property(T, column.Property);
  2058. if (prop is not null && prop.HasAttribute<ExternalStorageAttribute>())
  2059. {
  2060. blobColumns.Add(column);
  2061. }
  2062. }
  2063. if(blobColumns.Count > 0)
  2064. {
  2065. cols.Add("ID");
  2066. }
  2067. var result = new CoreTable(T.EntityName());
  2068. foreach (var col in cols)
  2069. result.Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.Type });
  2070. //LogStop("MakeTable");
  2071. using (var access = GetReadAccess())
  2072. {
  2073. using (var command = access.CreateCommand())
  2074. {
  2075. var sortorder = sort ?? LookupFactory.DefineSort(T);
  2076. command.CommandText = "";
  2077. command.Parameters.Clear();
  2078. //LogStart();
  2079. var sql = PrepareSelectNonGeneric(T, command, 'A', filter, cols, sortorder, null, null, top, distinct, true) + ";";
  2080. command.CommandText = sql;
  2081. try
  2082. {
  2083. using (var reader = command.ExecuteReader())
  2084. {
  2085. if (reader.HasRows)
  2086. {
  2087. var rows = new List<CoreRow>();
  2088. while (reader.Read())
  2089. {
  2090. var row = result.NewRow();
  2091. for (var i = 0; i < reader.FieldCount; i++)
  2092. try
  2093. {
  2094. var type = result.Columns[i].DataType;
  2095. if (reader.IsDBNull(i))
  2096. {
  2097. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2098. }
  2099. else if (type.IsEnum)
  2100. {
  2101. ReadAndDecodeValue(result, reader, row, i);
  2102. }
  2103. else if (type == typeof(byte))
  2104. {
  2105. row.Values.Add(reader.GetByte(i));
  2106. }
  2107. else if (type == typeof(byte[]))
  2108. {
  2109. ReadAndDecodeValue(result, reader, row, i);
  2110. }
  2111. else if (type == typeof(bool))
  2112. {
  2113. ReadAndDecodeValue(result, reader, row, i);
  2114. }
  2115. else if (type == typeof(short))
  2116. {
  2117. row.Values.Add(reader.GetInt16(i));
  2118. }
  2119. else if (type == typeof(int))
  2120. {
  2121. row.Values.Add(reader.GetInt32(i));
  2122. }
  2123. else if (type == typeof(long))
  2124. {
  2125. row.Values.Add(reader.GetInt64(i));
  2126. }
  2127. else if (type == typeof(float))
  2128. {
  2129. row.Values.Add(reader.GetFloat(i));
  2130. }
  2131. else if (type == typeof(double))
  2132. {
  2133. row.Values.Add(reader.GetDouble(i));
  2134. }
  2135. else if (type == typeof(decimal))
  2136. {
  2137. row.Values.Add(reader.GetDecimal(i));
  2138. }
  2139. else if (type == typeof(string))
  2140. {
  2141. var value = reader.GetString(i);
  2142. row.Values.Add(value != null ? value : "");
  2143. }
  2144. else if (type == typeof(DateTime))
  2145. {
  2146. ReadAndDecodeValue(result, reader, row, i);
  2147. }
  2148. else if (type == typeof(TimeSpan))
  2149. {
  2150. ReadAndDecodeValue(result, reader, row, i);
  2151. }
  2152. else if (type == typeof(Guid))
  2153. {
  2154. row.Values.Add(reader.GetGuid(i));
  2155. }
  2156. else
  2157. {
  2158. ReadAndDecodeValue(result, reader, row, i);
  2159. }
  2160. }
  2161. catch (Exception e)
  2162. {
  2163. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2164. }
  2165. result.Rows.Add(row);
  2166. }
  2167. }
  2168. reader.Close();
  2169. }
  2170. }
  2171. catch (Exception e)
  2172. {
  2173. OnLog?.Invoke(LogType.Error, $"{e.Message}: {sql}");
  2174. }
  2175. //LogStop("ReadData");
  2176. //LogPrint(String.Format("Query{0}", typeof(T).Name));
  2177. }
  2178. }
  2179. foreach(var column in blobColumns.ColumnNames())
  2180. {
  2181. foreach(var row in result.Rows)
  2182. {
  2183. var id = row.Get<Guid>("ID");
  2184. var data = GetExternalData(T, column, id);
  2185. if(data is not null)
  2186. {
  2187. row.Set<byte[]>(column, data);
  2188. }
  2189. }
  2190. }
  2191. if (log)
  2192. {
  2193. var duration = DateTime.Now - start;
  2194. Logger.Send(LogType.Information, "",
  2195. string.Format("SQLite::Query<{0}>({1} cols) returns {2} rows in {3}ms", T.Name, cols.Count, result.Rows.Count,
  2196. duration.TotalMilliseconds));
  2197. }
  2198. return result;
  2199. }
  2200. private CoreTable DoQuery<T>(Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort, int top, bool log, bool distinct)
  2201. where T : Entity, new() => DoQueryNonGeneric(typeof(T), filter, columns, sort, top, log, distinct);
  2202. public CoreTable Query(Type type, IFilter? filter, IColumns? columns, ISortOrder? sort, int top, bool log, bool distinct)
  2203. => DoQueryNonGeneric(type, filter, columns, sort, top, log, distinct);
  2204. public CoreTable Query<T>(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, int top = int.MaxValue, bool log = false, bool distinct = false)
  2205. where T : Entity, new()
  2206. {
  2207. return DoQuery(filter, columns, sort, top, log, distinct);
  2208. }
  2209. [Obsolete]
  2210. public CoreTable QueryDeleted<T>(Deletion deletion, Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, int top = int.MaxValue, bool log = false)
  2211. where T : Entity, new()
  2212. {
  2213. if (filter != null)
  2214. filter.And(x => x.Deleted).IsEqualTo(deletion.ID);
  2215. else
  2216. filter = new Filter<T>(x => x.Deleted).IsEqualTo(deletion.ID);
  2217. return DoQuery(filter, columns, sort, top, false, false);
  2218. }
  2219. private void ReadAndDecodeValue(CoreTable result, SQLiteDataReader reader, CoreRow row, int i)
  2220. {
  2221. var value = reader.GetValue(i);
  2222. var decoded = Decode(value, result.Columns[i].DataType);
  2223. row.Values.Add(decoded);
  2224. }
  2225. public T[] Load<T>(Filter<T>? filter = null, SortOrder<T>? sort = null) where T : Entity, new()
  2226. {
  2227. var result = new List<T>();
  2228. var cols = CoreUtils.GetColumns<T>(null);
  2229. using (var access = GetReadAccess())
  2230. {
  2231. using (var command = access.CreateCommand())
  2232. {
  2233. try
  2234. {
  2235. command.CommandText = "";
  2236. command.Parameters.Clear();
  2237. command.CommandText = PrepareSelect(command, 'A', filter, cols, sort, null, null, int.MaxValue, false, true) + ";";
  2238. using (var reader = command.ExecuteReader())
  2239. {
  2240. if (reader.HasRows)
  2241. while (reader.Read())
  2242. {
  2243. var entity = new T();
  2244. entity.SetObserving(false);
  2245. for (var i = 0; i < reader.FieldCount; i++)
  2246. {
  2247. object value;
  2248. if (cols[i].Type == typeof(long) && !reader.IsDBNull(i))
  2249. value = reader.GetInt64(i);
  2250. else
  2251. value = reader.GetValue(i);
  2252. try
  2253. {
  2254. var decoded = Decode(value, cols[i].Type);
  2255. CoreUtils.SetPropertyValue(entity, cols[i].Property, decoded);
  2256. }
  2257. catch (Exception e)
  2258. {
  2259. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2260. }
  2261. }
  2262. entity.SetObserving(true);
  2263. result.Add(entity);
  2264. }
  2265. reader.Close();
  2266. }
  2267. }
  2268. catch (Exception e)
  2269. {
  2270. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2271. }
  2272. }
  2273. }
  2274. return result.ToArray();
  2275. }
  2276. #endregion
  2277. #region Save
  2278. private static readonly Dictionary<Type, IProperty[]> _externalProperties = new Dictionary<Type, IProperty[]>();
  2279. private static IProperty[] GetExternalProperties(Type T)
  2280. {
  2281. if(!_externalProperties.TryGetValue(T, out var properties))
  2282. {
  2283. properties = DatabaseSchema.Properties(T).Where(x => x.HasAttribute<ExternalStorageAttribute>()).ToArray();
  2284. _externalProperties.Add(T, properties);
  2285. }
  2286. return properties;
  2287. }
  2288. private void OnSaveNonGeneric(Type T, Entity entity)
  2289. {
  2290. var props = GetExternalProperties(T);
  2291. List<(IProperty, byte[])>? data = null;
  2292. if (props.Any())
  2293. {
  2294. data = new List<(IProperty, byte[])>();
  2295. foreach(var prop in props)
  2296. {
  2297. var value = prop.Getter()(entity) as byte[];
  2298. if(value is not null && value.Length > 0)
  2299. {
  2300. data.Add(new(prop, value));
  2301. prop.Setter()(entity, Array.Empty<byte>());
  2302. }
  2303. }
  2304. }
  2305. using var access = GetWriteAccess();
  2306. using var command = access.CreateCommand();
  2307. PrepareUpsertNonGeneric(T, command, entity);
  2308. command.ExecuteNonQuery();
  2309. if(data is not null)
  2310. {
  2311. foreach(var (prop, value) in data)
  2312. {
  2313. SaveExternalData(T, prop.Name, entity.ID, value);
  2314. prop.Setter()(entity, value);
  2315. }
  2316. }
  2317. }
  2318. private void OnSaveNonGeneric(Type T, IEnumerable<Entity> entities)
  2319. {
  2320. // Casting to IList so that we can use it multiple times.
  2321. entities = entities.AsIList();
  2322. if (!entities.Any())
  2323. return;
  2324. var props = GetExternalProperties(T);
  2325. List<(IProperty, List<(Entity, byte[])>)>? data = null;
  2326. if (props.Any())
  2327. {
  2328. data = new List<(IProperty, List<(Entity, byte[])>)>();
  2329. foreach(var prop in props)
  2330. {
  2331. var lst = new List<(Entity, byte[])>();
  2332. foreach(var entity in entities)
  2333. {
  2334. var value = prop.Getter()(entity) as byte[];
  2335. if(value is not null && value.Length > 0)
  2336. {
  2337. lst.Add((entity, value));
  2338. prop.Setter()(entity, Array.Empty<byte>());
  2339. }
  2340. }
  2341. data.Add(new(prop, lst));
  2342. }
  2343. }
  2344. using var access = GetWriteAccess();
  2345. using var transaction = access.BeginTransaction();
  2346. try
  2347. {
  2348. using var command = access.CreateCommand();
  2349. foreach (var entity in entities)
  2350. {
  2351. PrepareUpsertNonGeneric(T, command, entity);
  2352. command.ExecuteNonQuery();
  2353. }
  2354. transaction.Commit();
  2355. if(data is not null)
  2356. {
  2357. foreach(var (property, list) in data)
  2358. {
  2359. foreach(var (entity, value) in list)
  2360. {
  2361. SaveExternalData(T, property.Name, entity.ID, value);
  2362. property.Setter()(entity, value);
  2363. }
  2364. }
  2365. }
  2366. }
  2367. catch (Exception)
  2368. {
  2369. transaction.Rollback();
  2370. throw;
  2371. }
  2372. }
  2373. private void OnSave<T>(T entity) where T : Entity
  2374. => OnSaveNonGeneric(typeof(T), entity);
  2375. public static bool CanSave(Type T)
  2376. {
  2377. if (DbFactory.IsReadOnly)
  2378. {
  2379. if (T.IsAssignableTo(typeof(License)) || T.IsAssignableTo(typeof(UserTracking)))
  2380. return true;
  2381. DbFactory.LogReadOnly();
  2382. throw new DbLockedException();
  2383. }
  2384. return true;
  2385. }
  2386. public static bool CanSave<T>() => CanSave(typeof(T));
  2387. public void Save(Type type, Entity entity)
  2388. {
  2389. if (!CanSave(type))
  2390. {
  2391. return;
  2392. }
  2393. OnSaveNonGeneric(type, entity);
  2394. }
  2395. public void Save(Type type, IEnumerable<Entity> entities)
  2396. {
  2397. if (!CanSave(type))
  2398. {
  2399. return;
  2400. }
  2401. OnSaveNonGeneric(type, entities);
  2402. }
  2403. public void Save<T>(IEnumerable<T> entities) where T : Entity => Save(typeof(T), entities);
  2404. public void Save<T>(T entity) where T : Entity => Save(typeof(T), entity);
  2405. #endregion
  2406. #region Delete
  2407. public void Purge<T>(T entity) where T : Entity
  2408. {
  2409. if (!CanSave<T>()) return;
  2410. using var access = GetWriteAccess();
  2411. using var command = access.CreateCommand();
  2412. PrepareDelete(command, entity);
  2413. var rows = command.ExecuteNonQuery();
  2414. }
  2415. public void Purge<T>(IEnumerable<T> entities) where T : Entity
  2416. {
  2417. if (!CanSave<T>()) return;
  2418. // Casting to IList so that we can use it multiple times.
  2419. entities = entities.AsIList();
  2420. if (!entities.Any())
  2421. return;
  2422. using var access = GetWriteAccess();
  2423. using var transaction = access.BeginTransaction();
  2424. try
  2425. {
  2426. using (var command = access.CreateCommand())
  2427. {
  2428. foreach (var entity in entities)
  2429. {
  2430. PrepareDelete(command, entity);
  2431. var rows = command.ExecuteNonQuery();
  2432. }
  2433. }
  2434. transaction.Commit();
  2435. }
  2436. catch (Exception)
  2437. {
  2438. transaction.Rollback();
  2439. throw;
  2440. }
  2441. }
  2442. private Dictionary<Type, List<Tuple<Type, List<string>>>> _cascades = new();
  2443. private Dictionary<Type, List<Tuple<Type, List<string>>>> _setNulls = new();
  2444. private const int deleteBatchSize = 100;
  2445. private readonly MethodInfo _deleteEntitiesMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2446. .Single(x => x.Name == nameof(DeleteEntity) && x.IsGenericMethod);
  2447. private void DeleteEntity<T>(Guid[] parentIDs, List<string> parentFields, DeletionData deletionData) where T : Entity, new()
  2448. {
  2449. var columns = DeletionData.DeletionColumns<T>();
  2450. var entityIDs = new List<Guid>();
  2451. for (int i = 0; i < parentIDs.Length; i += deleteBatchSize)
  2452. {
  2453. var items = new ArraySegment<Guid>(parentIDs, i, Math.Min(deleteBatchSize, parentIDs.Length - i));
  2454. var ids = items.ToArray();
  2455. var filter = new Filters<T>();
  2456. foreach(var field in parentFields)
  2457. {
  2458. filter.Add(new Filter<T>(field).InList(ids));
  2459. }
  2460. var entities = Query(filter.CombineOr(), columns);
  2461. foreach (var row in entities.Rows)
  2462. {
  2463. deletionData.DeleteEntity<T>(row);
  2464. entityIDs.Add(row.Get<T, Guid>(x => x.ID));
  2465. }
  2466. }
  2467. CascadeDelete(typeof(T), entityIDs.ToArray(), deletionData);
  2468. }
  2469. private void DeleteEntity(Type T, Guid[] parentIDs, List<string> parentFields, DeletionData deletionData)
  2470. {
  2471. _deleteEntitiesMethod.MakeGenericMethod(T).Invoke(this, new object?[] { parentIDs, parentFields, deletionData });
  2472. }
  2473. private readonly MethodInfo _setNullEntityMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2474. .Single(x => x.Name == nameof(SetNullEntity) && x.IsGenericMethod);
  2475. private void SetNullEntity<T>(List<string> properties, Guid[] parentIDs, DeletionData deletionData) where T : Entity, new()
  2476. {
  2477. foreach(var property in properties)
  2478. {
  2479. var columns = Columns.None<T>().Add(x => x.ID).Add(property);
  2480. for(int i = 0; i < parentIDs.Length; i += deleteBatchSize)
  2481. {
  2482. var items = new ArraySegment<Guid>(parentIDs, i, Math.Min(deleteBatchSize, parentIDs.Length - i));
  2483. var entities = Query(new Filter<T>(property).InList(items.ToArray()), columns);
  2484. foreach (var row in entities.Rows)
  2485. {
  2486. deletionData.SetNullEntity<T>(row.Get<T, Guid>(x => x.ID), property, row.Get<Guid>(property));
  2487. }
  2488. }
  2489. }
  2490. }
  2491. private void SetNullEntity(Type T, List<string> properties, Guid[] parentIDs, DeletionData deletionData)
  2492. {
  2493. _setNullEntityMethod.MakeGenericMethod(T).Invoke(this, new object?[] { properties, parentIDs, deletionData });
  2494. }
  2495. private void CascadeDelete(Type type, Guid[] parentIDs, DeletionData deletionData)
  2496. {
  2497. if(parentIDs.Length == 0)
  2498. {
  2499. return;
  2500. }
  2501. if (_cascades.TryGetValue(type, out var cascades))
  2502. {
  2503. foreach (var cascade in cascades)
  2504. {
  2505. DeleteEntity(cascade.Item1, parentIDs, cascade.Item2, deletionData);
  2506. }
  2507. }
  2508. if(_setNulls.TryGetValue(type, out var setNulls))
  2509. {
  2510. foreach(var setNull in setNulls)
  2511. {
  2512. SetNullEntity(setNull.Item1, setNull.Item2, parentIDs, deletionData);
  2513. }
  2514. }
  2515. }
  2516. public void Delete<T>(T entity, string userID) where T : Entity, new()
  2517. {
  2518. if (!CanSave<T>())
  2519. {
  2520. return;
  2521. }
  2522. if (typeof(T).HasAttribute<UnrecoverableAttribute>())
  2523. {
  2524. Purge(entity);
  2525. var props = GetExternalProperties(typeof(T));
  2526. foreach(var prop in props)
  2527. {
  2528. DeleteExternalData(typeof(T), prop.Name, entity.ID);
  2529. }
  2530. }
  2531. else
  2532. {
  2533. entity = DoQuery(
  2534. new Filter<T>(x => x.ID).IsEqualTo(entity.ID),
  2535. DeletionData.DeletionColumns<T>(),
  2536. null,
  2537. int.MaxValue,
  2538. false,
  2539. false
  2540. ).Rows.First().ToObject<T>();
  2541. var deletionData = new DeletionData();
  2542. deletionData.DeleteEntity(entity);
  2543. CascadeDelete(typeof(T), new Guid[] { entity.ID }, deletionData);
  2544. var tableName = typeof(T).Name;
  2545. var deletion = new Deletion()
  2546. {
  2547. DeletionDate = DateTime.Now,
  2548. HeadTable = tableName,
  2549. Description = entity.ToString() ?? "",
  2550. DeletedBy = userID,
  2551. Data = Serialization.Serialize(deletionData)
  2552. };
  2553. OnSave(deletion);
  2554. Purge(entity);
  2555. }
  2556. }
  2557. public void Delete<T>(IEnumerable<T> entities, string userID) where T : Entity, new()
  2558. {
  2559. if (!CanSave<T>())
  2560. {
  2561. return;
  2562. }
  2563. entities = entities.AsIList();
  2564. if (!entities.Any())
  2565. return;
  2566. if (typeof(T).HasAttribute<UnrecoverableAttribute>())
  2567. {
  2568. Purge(entities);
  2569. var props = GetExternalProperties(typeof(T));
  2570. foreach(var prop in props)
  2571. {
  2572. foreach(var entity in entities)
  2573. {
  2574. DeleteExternalData(typeof(T), prop.Name, entity.ID);
  2575. }
  2576. }
  2577. }
  2578. else
  2579. {
  2580. var ids = entities.Select(x => x.ID).ToArray();
  2581. var entityList = Query(
  2582. new Filter<T>(x => x.ID).InList(ids),
  2583. DeletionData.DeletionColumns<T>()).Rows.Select(x => x.ToObject<T>()).ToList();
  2584. if (!entityList.Any())
  2585. return;
  2586. var deletionData = new DeletionData();
  2587. foreach (var entity in entityList)
  2588. {
  2589. deletionData.DeleteEntity(entity);
  2590. }
  2591. CascadeDelete(typeof(T), ids, deletionData);
  2592. var tableName = typeof(T).Name;
  2593. var deletion = new Deletion()
  2594. {
  2595. DeletionDate = DateTime.Now,
  2596. HeadTable = tableName,
  2597. Description = $"Deleted {entityList.Count} entries",
  2598. DeletedBy = userID,
  2599. Data = Serialization.Serialize(deletionData)
  2600. };
  2601. OnSave(deletion);
  2602. Purge(entities);
  2603. }
  2604. }
  2605. private void AddDeletionType(Type type, List<Type> deletions)
  2606. {
  2607. deletions.Add(type);
  2608. if (!_cascades.TryGetValue(type, out var cascades))
  2609. return;
  2610. foreach (var cascade in cascades)
  2611. {
  2612. AddDeletionType(cascade.Item1, deletions);
  2613. }
  2614. }
  2615. private Dictionary<Type, List<Type>> _allCascades = new();
  2616. private List<Type> GetDeletionTypes(Type type)
  2617. {
  2618. if(_allCascades.TryGetValue(type, out var cascades))
  2619. {
  2620. return cascades;
  2621. }
  2622. var deletionTypes = new List<Type>();
  2623. AddDeletionType(type, deletionTypes);
  2624. _allCascades[type] = deletionTypes;
  2625. return deletionTypes;
  2626. }
  2627. public void Purge(Deletion deletion)
  2628. {
  2629. if (!CanSave<Deletion>())
  2630. {
  2631. return;
  2632. }
  2633. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  2634. if(data is not null)
  2635. {
  2636. foreach(var (entityName, cascade) in data.Cascades)
  2637. {
  2638. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2639. var props = GetExternalProperties(entityType);
  2640. foreach(var prop in props)
  2641. {
  2642. foreach(var entity in cascade.ToObjects(entityType).Cast<Entity>())
  2643. {
  2644. DeleteExternalData(entityType, prop.Name, entity.ID);
  2645. }
  2646. }
  2647. }
  2648. }
  2649. Purge<Deletion>(deletion);
  2650. }
  2651. public void Recover(Deletion deletion)
  2652. {
  2653. if (!CanSave<Deletion>())
  2654. {
  2655. return;
  2656. }
  2657. if (deletion.ID == Guid.Empty)
  2658. {
  2659. Logger.Send(LogType.Error, "", "Empty Deletion ID; Recovery cancelled");
  2660. return;
  2661. }
  2662. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  2663. if (data is null)
  2664. {
  2665. Logger.Send(LogType.Error, "", "Deletion Data deserialisation failed; Recovery cancelled");
  2666. return;
  2667. }
  2668. foreach (var (entityName, setNulls) in data.SetNulls)
  2669. {
  2670. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2671. var saves = new List<Entity>();
  2672. foreach(var setNull in setNulls)
  2673. {
  2674. var row = DoQueryNonGeneric(
  2675. entityType,
  2676. Filter.Create<Entity>(entityType, x => x.ID).IsEqualTo(setNull.EntityID),
  2677. Columns.None(entityType)
  2678. .Add<Entity>(x => x.ID)
  2679. .Add(setNull.Property),
  2680. null,
  2681. 1,
  2682. false,
  2683. false
  2684. ).Rows.FirstOrDefault();
  2685. if (row is null) continue;
  2686. var entity = (row.ToObject(entityType) as Entity)!;
  2687. CoreUtils.SetPropertyValue(entity, setNull.Property, setNull.ParentID);
  2688. saves.Add(entity);
  2689. }
  2690. OnSaveNonGeneric(entityType, saves);
  2691. }
  2692. foreach(var (entityName, cascade) in data.Cascades)
  2693. {
  2694. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2695. OnSaveNonGeneric(entityType, cascade.ToObjects(entityType).Cast<Entity>());
  2696. }
  2697. Purge<Deletion>(deletion);
  2698. }
  2699. public List<Type> GetDeletionTypes(Deletion deletion)
  2700. {
  2701. var entityType = CoreUtils.Entities.First(x => x.Name == deletion.HeadTable);
  2702. return GetDeletionTypes(entityType);
  2703. }
  2704. #endregion
  2705. #endregion
  2706. #region External Data Storage
  2707. private string ExternalDataFolder(Type T, string columnName, string idString)
  2708. {
  2709. return Path.Combine(
  2710. Path.GetDirectoryName(URL) ?? "",
  2711. $"{Path.GetFileName(URL)}.data",
  2712. T.Name,
  2713. columnName,
  2714. idString.Substring(0, 2));
  2715. }
  2716. private byte[]? GetExternalData(Type T, string columnName, Guid id)
  2717. {
  2718. var idString = id.ToString();
  2719. var filename = Path.Combine(ExternalDataFolder(T, columnName, idString), idString);
  2720. try
  2721. {
  2722. return File.ReadAllBytes(filename);
  2723. }
  2724. catch(Exception e)
  2725. {
  2726. //Logger.Send(LogType.Error, "", $"Could not load external {T.Name}.{columnName}: {e.Message}");
  2727. return null;
  2728. }
  2729. }
  2730. private void SaveExternalData(Type T, string columnName, Guid id, byte[] data)
  2731. {
  2732. var idString = id.ToString();
  2733. var directory = ExternalDataFolder(T, columnName, idString);
  2734. Directory.CreateDirectory(directory);
  2735. var filename = Path.Combine(directory, idString);
  2736. File.WriteAllBytes(filename, data);
  2737. }
  2738. private void DeleteExternalData(Type T, string columnName, Guid id)
  2739. {
  2740. var idString = id.ToString();
  2741. var directory = ExternalDataFolder(T, columnName, idString);
  2742. Directory.CreateDirectory(directory);
  2743. var filename = Path.Combine(directory, idString);
  2744. if (File.Exists(filename))
  2745. {
  2746. File.Delete(filename);
  2747. }
  2748. }
  2749. #endregion
  2750. }
  2751. }