SQLiteProvider.cs 131 KB

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