SQLiteProvider.cs 127 KB

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