SQLiteProvider.cs 137 KB

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