SQLiteProvider.cs 128 KB

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