SQLiteProvider.cs 129 KB

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