SQLiteProvider.cs 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031
  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. {
  991. using (var ms = new MemoryStream(array))
  992. packable.Unpack(new BinaryReader(ms));
  993. }
  994. }
  995. return packable;
  996. }
  997. if (type == typeof(DateTime))
  998. return IsNull(o) || string.IsNullOrEmpty(o.ToString()) ? DateTime.MinValue : DateTime.Parse(o.ToString() ?? "");
  999. if (type == typeof(TimeSpan))
  1000. {
  1001. if (IsNull(o))
  1002. return TimeSpan.MinValue;
  1003. var oStr = o.ToString() ?? "";
  1004. if (double.TryParse(oStr, out var hrs))
  1005. return TimeSpan.FromHours(hrs);
  1006. if (oStr.Contains(':'))
  1007. return TimeSpan.Parse(oStr);
  1008. }
  1009. if (type == typeof(Guid))
  1010. return IsNull(o) ? Guid.Empty : Guid.Parse(o.ToString() ?? "");
  1011. if (type == typeof(bool))
  1012. {
  1013. var oStr = o.ToString() ?? "";
  1014. return !IsNull(o) && (oStr.Equals("1") || oStr.ToUpper().Equals("TRUE"));
  1015. }
  1016. if (type.IsEnum)
  1017. return Enum.Parse(type, o.ToString() ?? "");
  1018. if (IsNull(o))
  1019. return null;
  1020. if (type == typeof(long))
  1021. return o;
  1022. var result = CoreUtils.ChangeType(o, type);
  1023. return result;
  1024. }
  1025. public static object Encode(object? o, Type? type)
  1026. {
  1027. if (IsNull(o) || type is null)
  1028. return DBNull.Value;
  1029. if (type == typeof(DateTime) && o.GetType() == typeof(string))
  1030. o = DateTime.Parse(o.ToString() ?? "");
  1031. if (type == typeof(double) && o.GetType() == typeof(string))
  1032. o = double.Parse(o.ToString() ?? "");
  1033. if (type == typeof(float) && o.GetType() == typeof(string))
  1034. o = float.Parse(o.ToString() ?? "");
  1035. if (type == typeof(long) && o.GetType() == typeof(string))
  1036. o = long.Parse(o.ToString() ?? "");
  1037. if (type.IsEnum && o.GetType() == typeof(string))
  1038. o = Enum.Parse(type, o.ToString() ?? "");
  1039. if (type == typeof(TimeSpan) && o.GetType() == typeof(string))
  1040. {
  1041. if (o.ToString()?.Contains(':') == true)
  1042. {
  1043. if (TimeSpan.TryParse(o.ToString(), out var time))
  1044. o = time;
  1045. }
  1046. else if (double.TryParse(o.ToString(), out var hrs))
  1047. {
  1048. o = TimeSpan.FromHours(hrs);
  1049. }
  1050. }
  1051. if (type == typeof(bool))
  1052. {
  1053. if (o.GetType() == typeof(string))
  1054. o = bool.Parse(o.ToString() ?? "");
  1055. if (o.Equals(false))
  1056. return DBNull.Value;
  1057. return o;
  1058. }
  1059. if (type == typeof(string) && string.IsNullOrEmpty(o.ToString()))
  1060. return DBNull.Value;
  1061. if (type == typeof(Guid) && o.GetType() == typeof(string))
  1062. o = Guid.Parse(o.ToString() ?? "");
  1063. if (o is string[])
  1064. using (var ms = new MemoryStream())
  1065. {
  1066. new BinaryFormatter().Serialize(ms, o);
  1067. return ms.GetBuffer();
  1068. }
  1069. if (o is IPackable pack)
  1070. {
  1071. using var ms = new MemoryStream();
  1072. using var writer = new BinaryWriter(ms);
  1073. pack.Pack(writer);
  1074. return ms.ToArray();
  1075. }
  1076. if (o.GetType() == typeof(double) && o.Equals(default(double)))
  1077. return DBNull.Value;
  1078. if (o.GetType() == typeof(float) && o.Equals(default(float)))
  1079. return DBNull.Value;
  1080. if (o.GetType() == typeof(int) && o.Equals(default(int)))
  1081. return DBNull.Value;
  1082. if (o.GetType() == typeof(long) && o.Equals(default(long)))
  1083. return DBNull.Value;
  1084. if (o.GetType() == typeof(DateTime))
  1085. {
  1086. if ((DateTime)o <= DateTime.MinValue.AddDays(1))
  1087. return DBNull.Value;
  1088. return string.Format("{0:yyyy-MM-dd HH:mm:ss.FFFFFFF}", o);
  1089. }
  1090. if (o.GetType() == typeof(TimeSpan))
  1091. {
  1092. if (((TimeSpan)o).Ticks == 0L)
  1093. return DBNull.Value;
  1094. return ((TimeSpan)o).TotalHours;
  1095. }
  1096. if (o.GetType() == typeof(Guid))
  1097. {
  1098. if (o.Equals(Guid.Empty))
  1099. return DBNull.Value;
  1100. return o.ToString() ?? "";
  1101. }
  1102. if (type == typeof(double) && o.GetType() == typeof(string))
  1103. if (double.TryParse((string)o, out var value))
  1104. o = value;
  1105. if (o.GetType().IsEnum)
  1106. return o.ToString() ?? "";
  1107. return o;
  1108. }
  1109. private static readonly Dictionary<Operator, string> operators = new()
  1110. {
  1111. { Operator.IsEqualTo, "{0} = {1}" },
  1112. { Operator.IsNotEqualTo, "{0} != {1}" },
  1113. { Operator.IsGreaterThan, "{0} > {1}" },
  1114. { Operator.IsGreaterThanOrEqualTo, "{0} >= {1}" },
  1115. { Operator.IsLessThan, "{0} < {1}" },
  1116. { Operator.IsLessThanOrEqualTo, "{0} <= {1}" },
  1117. { Operator.BeginsWith, "{0} LIKE {1} || '%'" },
  1118. { Operator.Contains, "{0} LIKE '%' || {1} || '%'" },
  1119. { Operator.EndsWith, "{0} LIKE '%' || {1}" },
  1120. { Operator.InList, "{0} IN ({1})" },
  1121. { Operator.NotInList, "{0} NOT IN ({1})" },
  1122. { Operator.InQuery, "{0} IN ({1})" }
  1123. };
  1124. private static string EscapeValue(object? value)
  1125. {
  1126. if (IsNull(value))
  1127. return "NULL";
  1128. if ((value is string) || (value is Enum) || (value is Guid))
  1129. return string.Format("\'" + "{0}" + "\'", value.ToString()?.Replace("\'", "\'\'"));
  1130. if (value is string[])
  1131. return string.Format("hex({0})", BitConverter.ToString(Encoding.ASCII.GetBytes(value.ToString() ?? "")).Replace("-", string.Empty));
  1132. if (value is IColumn col)
  1133. return $"[{col.Property}]";
  1134. return value.ToString() ?? "";
  1135. }
  1136. private static string GetFilterConstant(FilterConstant constant)
  1137. {
  1138. return constant switch
  1139. {
  1140. FilterConstant.Now => "datetime()",
  1141. FilterConstant.Today => "strftime('%Y-%m-%d 00:00:00')",
  1142. _ => throw new Exception($"FilterConstant.{constant} is not implemented!"),
  1143. };
  1144. }
  1145. private string GetFilterClauseNonGeneric(Type T, SQLiteCommand command, char prefix, IFilter? filter, List<Tuple<string, string, string, string>> tables,
  1146. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1147. {
  1148. if (filter == null || filter.Expression == null)
  1149. return "";
  1150. var result = "";
  1151. if (filter.Operator == Operator.All)
  1152. {
  1153. result = "1 = 1";
  1154. }
  1155. else if (filter.Operator == Operator.None)
  1156. {
  1157. result = "1 = 0";
  1158. }
  1159. else
  1160. {
  1161. string prop;
  1162. if (CoreUtils.TryFindMemberExpression(filter.Expression, out var mexp))
  1163. {
  1164. prop = CoreUtils.GetFullPropertyName(mexp, ".");
  1165. }
  1166. else
  1167. {
  1168. prop = filter.Expression.ToString();
  1169. if (prop.Contains("=>"))
  1170. prop = string.Join(".", prop.Split('.').Skip(1));
  1171. mexp = CoreUtils.GetMemberExpression(T, prop);
  1172. }
  1173. LoadFieldsandTables(command, T, prefix, fieldmap, tables, columns, prop, useparams);
  1174. if (fieldmap.ContainsKey(prop))
  1175. prop = fieldmap[prop];
  1176. if (filter.Operator == Operator.InList || filter.Operator == Operator.NotInList)
  1177. {
  1178. // if, and only if the list contains Guids, we can safely bypass the
  1179. // 1000-parameter limit by using building the string ourselves
  1180. if (filter.Value is Guid[] list)
  1181. {
  1182. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Format("\"{0}\"", string.Join("\",\"", list)));
  1183. }
  1184. else if (filter.Value is IEnumerable enumerable)
  1185. {
  1186. var paramlist = new List<object>();
  1187. foreach (var item in enumerable)
  1188. {
  1189. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1190. command.Parameters.AddWithValue(sParam, Encode(item, mexp.Type));
  1191. paramlist.Add(sParam);
  1192. }
  1193. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Join(",", paramlist));
  1194. }
  1195. }
  1196. else if (filter.Operator == Operator.InQuery)
  1197. {
  1198. if(filter.Value is ISubQuery subQuery)
  1199. {
  1200. var subEntityType = subQuery.GetQueryType();
  1201. var subColumns = Columns.Create(subEntityType);
  1202. var subColumn = subQuery.GetColumn();
  1203. subColumns.Add(subColumn);
  1204. var subQueryText = PrepareSelectNonGeneric(subEntityType, command, 'A',
  1205. subQuery.GetFilter(), subColumns, null,
  1206. null, null, int.MaxValue, false, useparams);
  1207. result = string.Format("(" + operators[filter.Operator] + ")", prop, subQueryText);
  1208. }
  1209. }
  1210. else
  1211. {
  1212. if (filter.Value is FilterConstant constant)
  1213. result = string.Format("(" + operators[filter.Operator] + ")", prop, GetFilterConstant(constant));
  1214. else
  1215. {
  1216. var value = Encode(filter.Value, mexp.Type);
  1217. if (IsNull(value) && ((filter.Operator == Operator.IsEqualTo) || (filter.Operator == Operator.IsNotEqualTo)))
  1218. {
  1219. result = string.Format("({0} {1} NULL)", prop,
  1220. filter.Operator == Operator.IsEqualTo
  1221. ? "IS"
  1222. : "IS NOT");
  1223. }
  1224. else
  1225. {
  1226. if (useparams)
  1227. {
  1228. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1229. if (filter.Expression.Type == typeof(string[]))
  1230. {
  1231. var bytes = Encoding.ASCII.GetBytes(value.ToString() ?? "");
  1232. value = BitConverter.ToString(bytes).Replace("-", string.Empty);
  1233. result = string.Format("(" + operators[filter.Operator] + ")", string.Format("hex({0})", prop), sParam);
  1234. }
  1235. else
  1236. {
  1237. result = string.Format("(" + operators[filter.Operator] + ")", prop, sParam);
  1238. }
  1239. command.Parameters.AddWithValue(sParam, value);
  1240. }
  1241. else
  1242. result = string.Format("(" + operators[filter.Operator] + ")", prop, EscapeValue(filter.Value));
  1243. }
  1244. }
  1245. }
  1246. }
  1247. var bChanged = false;
  1248. if (filter.Ands != null && filter.Ands.Count() > 0)
  1249. {
  1250. foreach (var and in filter.Ands)
  1251. {
  1252. var AndResult = GetFilterClauseNonGeneric(T, command, prefix, and, tables, fieldmap, columns, useparams);
  1253. if (!string.IsNullOrEmpty(AndResult))
  1254. {
  1255. result = string.Format("{0} and {1}", result, AndResult);
  1256. bChanged = true;
  1257. }
  1258. }
  1259. if (bChanged)
  1260. result = string.Format("({0})", result);
  1261. }
  1262. bChanged = false;
  1263. if (filter.Ors != null && filter.Ors.Count() > 0)
  1264. {
  1265. foreach (var or in filter.Ors)
  1266. {
  1267. var OrResult = GetFilterClauseNonGeneric(T, command, prefix, or, tables, fieldmap, columns, useparams);
  1268. if (!string.IsNullOrEmpty(OrResult))
  1269. {
  1270. result = string.Format("{0} or {1}", result, OrResult);
  1271. bChanged = true;
  1272. }
  1273. }
  1274. if (bChanged)
  1275. result = string.Format("({0})", result);
  1276. }
  1277. return result;
  1278. }
  1279. private string GetFilterClause<T>(SQLiteCommand command, char prefix, Filter<T>? filter, List<Tuple<string, string, string, string>> tables,
  1280. Dictionary<string, string> fieldmap, List<string> columns, bool useparams) where T : Entity
  1281. => GetFilterClauseNonGeneric(typeof(T), command, prefix, filter, tables, fieldmap, columns, useparams);
  1282. private string GetSortClauseNonGeneric(Type T,
  1283. SQLiteCommand command, ISortOrder? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1284. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1285. {
  1286. if (sort == null)
  1287. return "";
  1288. var result = "";
  1289. if (sort.Expression != null)
  1290. {
  1291. if (CoreUtils.TryFindMemberExpression(sort.Expression, out var mexp))
  1292. result = CoreUtils.GetFullPropertyName(mexp, ".");
  1293. else
  1294. result = sort.Expression.ToString();
  1295. var prop = CoreUtils.GetProperty(T, result);
  1296. if (prop.GetCustomAttribute<DoNotSerialize>() == null && prop.GetCustomAttribute<DoNotPersist>() == null && prop.CanWrite)
  1297. {
  1298. LoadFieldsandTables(command, T, prefix, fieldmap, tables, columns, result, useparams);
  1299. if (fieldmap.ContainsKey(result))
  1300. result = fieldmap[result];
  1301. if (sort.Expression.Type.Equals(typeof(string)))
  1302. result = string.Format("{0} COLLATE NOCASE", result);
  1303. if (sort.Direction == SortDirection.Ascending)
  1304. result = string.Format("{0} ASC", result);
  1305. else
  1306. result = string.Format("{0} DESC", result);
  1307. }
  1308. else
  1309. {
  1310. result = "";
  1311. }
  1312. }
  1313. foreach (var then in sort.Thens)
  1314. result = result + ", " + GetSortClauseNonGeneric(T, command, then, prefix, tables, fieldmap, columns, useparams);
  1315. return result;
  1316. }
  1317. private string GetSortClause<T>(SQLiteCommand command, SortOrder<T>? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1318. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1319. => GetSortClauseNonGeneric(typeof(T), command, sort, prefix, tables, fieldmap, columns, useparams);
  1320. private static string GetCalculation(AggregateAttribute attribute, string columnname)
  1321. {
  1322. return attribute.Calculation switch
  1323. {
  1324. AggregateCalculation.Sum => "TOTAL",
  1325. AggregateCalculation.Count => "COUNT",
  1326. AggregateCalculation.Maximum => "MAX",
  1327. AggregateCalculation.Minimum => "MIN",
  1328. AggregateCalculation.Average => "AVERAGE",
  1329. _ => throw new Exception(string.Format("{0}.{1} is not a valid aggregate", columnname, attribute.Calculator.GetType().Name)),
  1330. };
  1331. }
  1332. private string GetFunction(FormulaAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1333. {
  1334. if (attribute.Operator == FormulaOperator.None)
  1335. throw new Exception(string.Format("{0}.{1} is not a valid formula", columnname, attribute.Calculator.GetType().Name));
  1336. if (!fieldmap.ContainsKey(attribute.Value))
  1337. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Value));
  1338. foreach (var modifier in attribute.Modifiers)
  1339. if (!fieldmap.ContainsKey(modifier))
  1340. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, modifier));
  1341. if (attribute.Operator == FormulaOperator.Add)
  1342. return string.Format("(IFNULL({0},0.00) + {1})", fieldmap[attribute.Value],
  1343. string.Join(" + ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1344. if (attribute.Operator == FormulaOperator.Subtract)
  1345. return string.Format("(IFNULL({0},0.00) - ({1}))", fieldmap[attribute.Value],
  1346. string.Join(" + ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1347. if (attribute.Operator == FormulaOperator.Multiply)
  1348. return string.Format("(IFNULL({0},0.00) * {1})", fieldmap[attribute.Value],
  1349. string.Join(" * ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1350. if (attribute.Operator == FormulaOperator.Divide)
  1351. {
  1352. var result = string.Format("IFNULL({0},0.00)", fieldmap[attribute.Value]);
  1353. foreach (var modifier in attribute.Modifiers)
  1354. result = string.Format("({0} / {1})", result, string.Format("IFNULL({0},1.00)", fieldmap[modifier]));
  1355. return result;
  1356. }
  1357. if (attribute.Operator == FormulaOperator.Maximum)
  1358. {
  1359. var parameters = attribute.Modifiers.Select(m => $"IFNULL({fieldmap[m]},0.00)");
  1360. var result = $"MAX({fieldmap[attribute.Value]}, {String.Join(", ", parameters)})";
  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. if (attribute.Operator == FormulaOperator.Minumum)
  1367. {
  1368. var parameters = attribute.Modifiers.Select(m => $"IFNULL({fieldmap[m]},0.00)");
  1369. var result = $"MIN({fieldmap[attribute.Value]}, {String.Join(", ", parameters)})";
  1370. //var result = string.Format(
  1371. // "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",
  1372. // fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1373. return result;
  1374. }
  1375. throw new Exception(string.Format("Calculation Type [{0}.{1}] not found", columnname, attribute.GetType().Name));
  1376. }
  1377. private string GetCondition(ConditionAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1378. {
  1379. var intf = attribute.Calculator.GetType().GetInterfaces()
  1380. .FirstOrDefault(x => x.Name.StartsWith("ICondition") && x.GenericTypeArguments.Length.Equals(3));
  1381. if (intf is null)
  1382. throw new Exception($"Attribute calculate {attribute.Calculator} is not an ICondition");
  1383. var valuetype = intf.GenericTypeArguments[1];
  1384. var defvalue = valuetype.GetDefault();
  1385. if (!fieldmap.ContainsKey(attribute.Left))
  1386. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Left));
  1387. var condition = "";
  1388. if (attribute.Condition == Condition.Equals)
  1389. condition = "=";
  1390. else if (attribute.Condition == Condition.NotEqual)
  1391. condition = "<>";
  1392. else if (attribute.Condition == Condition.GreaterThan)
  1393. condition = ">";
  1394. else if (attribute.Condition == Condition.GreaterThanOrEqualTo)
  1395. condition = ">=";
  1396. else if (attribute.Condition == Condition.LessThan)
  1397. condition = "<";
  1398. else if (attribute.Condition == Condition.LessThanOrEqualTo)
  1399. condition = "<=";
  1400. else
  1401. throw new Exception(string.Format("{0}.{1} is not a valid condition", columnname, attribute.Calculator.GetType().Name));
  1402. if (!fieldmap.ContainsKey(attribute.Right))
  1403. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Right));
  1404. if (!fieldmap.ContainsKey(attribute.True))
  1405. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.True));
  1406. if (!fieldmap.ContainsKey(attribute.False))
  1407. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.False));
  1408. return string.Format("CASE WHEN COALESCE({0},{1}) {2} {3} THEN {4} ELSE {5} END", fieldmap[attribute.Left], defvalue, condition,
  1409. fieldmap[attribute.Right], fieldmap[attribute.True], fieldmap[attribute.False]);
  1410. }
  1411. //private static List<string> Breadcrumb = new List<string>();
  1412. //Dictionary<String, Tuple<int, TimeSpan>> stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1413. //Stopwatch sw = new Stopwatch();
  1414. //private void LogReset()
  1415. //{
  1416. // stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1417. // sw = new Stopwatch();
  1418. //}
  1419. //void LogStart()
  1420. //{
  1421. // if (sw.IsRunning)
  1422. // sw.Restart();
  1423. // else
  1424. // sw.Start();
  1425. //}
  1426. //void LogStop(String msg)
  1427. //{
  1428. // TimeSpan elapsed = sw.Elapsed;
  1429. // if (Breadcrumb.Any())
  1430. // msg = String.Join(".", Breadcrumb) + "." + msg;
  1431. // if (!stopwatch.ContainsKey(msg))
  1432. // stopwatch[msg] = new Tuple<int, TimeSpan>(1,elapsed);
  1433. // else
  1434. // stopwatch[msg] = new Tuple<int, TimeSpan>(stopwatch[msg].Item1 + 1,stopwatch[msg].Item2 + elapsed);
  1435. // sw.Restart();
  1436. //}
  1437. //private void LogPrint(String header)
  1438. //{
  1439. // foreach (var keyvalue in stopwatch.ToArray())
  1440. // OnLog?.Invoke(LogType.Information, String.Format("- {0}: {1} = ({2}) {3,10:0.0000}", header, keyvalue.Key, keyvalue.Value.Item1, keyvalue.Value.Item2.TotalMilliseconds));
  1441. //}
  1442. private void LoadFieldsandTables(SQLiteCommand command, Type type, char prefix, Dictionary<string, string> fieldmap,
  1443. List<Tuple<string, string, string, string>> tables, List<string> columns, string columnname, bool useparams)
  1444. {
  1445. if (fieldmap.ContainsKey(columnname))
  1446. return;
  1447. var newprefix = (char)(prefix + 1);
  1448. // LogStart();
  1449. var property = DatabaseSchema.Property(type, columnname);
  1450. // LogStop("DatabaseSchema.Property");
  1451. if (property != null && property is CustomProperty)
  1452. {
  1453. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1454. }
  1455. else
  1456. {
  1457. var bits = columnname.Split('.');
  1458. if (bits.Length == 1)
  1459. {
  1460. var prop = type.GetProperty(columnname);
  1461. if (prop != null)
  1462. {
  1463. // LogStart();
  1464. var attr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  1465. // LogStop("GetCustomAttributes(Aggregate)");
  1466. if (attr is AggregateAttribute agg)
  1467. {
  1468. bool internalaggregate = agg.Calculator.GetType().GetInterfaces()
  1469. .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICoreAggregate<,>));
  1470. if (internalaggregate)
  1471. {
  1472. }
  1473. else
  1474. {
  1475. var scols = new Dictionary<string, string> { { agg.Aggregate, GetCalculation(agg, columnname) } };
  1476. var siblings = columns.Where(x => !x.Equals(columnname) && x.Split('.').First().Equals(bits.First()))
  1477. .Select(x => string.Join(".", x.Split('.').Skip(1))).ToList();
  1478. var linkedtype = agg.Source;
  1479. foreach (var sibling in siblings)
  1480. {
  1481. // LogStart();
  1482. var sprop = CoreUtils.GetProperty(type, sibling);
  1483. // LogStop("GetProperty(sibling)");
  1484. // LogStart();
  1485. var sattr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  1486. // LogStop("GetCustomAttributes(Sibling.Aggregate)");
  1487. if (sattr is AggregateAttribute sagg)
  1488. {
  1489. // LogStart();
  1490. scols[sagg.Aggregate] = GetCalculation(sagg, sibling);
  1491. // LogStop("GetCalculation(Sibling)");
  1492. }
  1493. }
  1494. var subcols = Columns.Create(linkedtype);
  1495. foreach (var key in agg.Links.Keys)
  1496. subcols.Add(key);
  1497. //subcols.Add(agg.Link);
  1498. foreach (var scol in scols.Keys)
  1499. subcols.Add(scol);
  1500. // LogStart();
  1501. var filter = Activator.CreateInstance(typeof(Filter<>).MakeGenericType(linkedtype), "Deleted") as IFilter;
  1502. filter!.Operator = Operator.IsEqualTo;
  1503. filter.Value = Guid.Empty;
  1504. var aggFilter = agg.Filter;
  1505. if(aggFilter is not null)
  1506. {
  1507. List<String> ffs = new List<string>();
  1508. FilterFields(aggFilter, ffs);
  1509. //foreach (var ff in ffs)
  1510. // subcols.Add(ff);
  1511. filter.And(aggFilter);
  1512. }
  1513. var linkedtable = string.Format("({0})",
  1514. PrepareSelectNonGeneric(linkedtype, command, newprefix, filter, subcols, null, scols, null, int.MaxValue, false, useparams));
  1515. var alias = tables.Count + 1;
  1516. var link = string.Join(" , ", agg.Links.Keys.Select(x => string.Format("{0}{1}.{2}", prefix, alias, x)));
  1517. var tuple = tables.FirstOrDefault(x =>
  1518. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1519. if (tuple == null)
  1520. {
  1521. var joins = new List<string>();
  1522. foreach (var key in agg.Links.Keys)
  1523. joins.Add(
  1524. string.Format("IFNULL({0}{1}.[{2}],'') = IFNULL({0}1.[{3}],'')", prefix, alias, key, agg.Links[key]));
  1525. var join = string.Format("LEFT OUTER JOIN {0} {1}{2} ON {3}", linkedtable, prefix, alias,
  1526. string.Join(" AND ", joins));
  1527. tuple = new Tuple<string, string, string, string>(linkedtable, prefix + alias.ToString(), join, link);
  1528. //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);
  1529. tables.Add(tuple);
  1530. }
  1531. //if (bits.Last().Equals("ID"))
  1532. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1533. //else
  1534. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, agg.Aggregate);
  1535. //LoadFieldsandTables(command, agg.Type, newprefix, fieldmap, tables, columns, columnname);
  1536. //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);
  1537. //int alias = tables.Count + 1;
  1538. //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), "");
  1539. //tables.Add(tuple);
  1540. //fieldmap[columnname] = String.Format("{0}.[{1}]", tuple.Item2, agg.AggregateProperty);
  1541. }
  1542. }
  1543. else
  1544. {
  1545. // LogStart();
  1546. attr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(FormulaAttribute)));
  1547. // LogStop("GetAttribute(Formula)");
  1548. if (attr is FormulaAttribute fnc)
  1549. {
  1550. // var functionmap = new Dictionary<string, string>();
  1551. // CheckColumn(columns, fnc.Value);
  1552. // LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, fnc.Value, useparams);
  1553. // foreach (var column in fnc.Modifiers)
  1554. // {
  1555. // CheckColumn(columns, column);
  1556. // LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, column, useparams);
  1557. // }
  1558. // fieldmap[columnname] = GetFunction(fnc, functionmap, columnname);
  1559. foreach (var field in fnc.Modifiers.Prepend(fnc.Value))
  1560. {
  1561. CheckColumn(columns, field);
  1562. LoadFieldsandTables(command, type, prefix, fieldmap, tables, columns, field, useparams);
  1563. }
  1564. fieldmap[columnname] = GetFunction(fnc, fieldmap, columnname);
  1565. }
  1566. else
  1567. {
  1568. // LogStart();
  1569. attr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(ConditionAttribute)));
  1570. // LogStop("GetAttribute(Condition)");
  1571. if (attr is ConditionAttribute cnd)
  1572. {
  1573. var cndmap = new Dictionary<string, string>();
  1574. // LogStart();
  1575. CheckColumn(columns, cnd.Left);
  1576. // LogStop("CheckColumn(Left)");
  1577. // LogStart();
  1578. CheckColumn(columns, cnd.Right);
  1579. // LogStop("CheckColumn(Right)");
  1580. // LogStart();
  1581. CheckColumn(columns, cnd.True);
  1582. // LogStop("CheckColumn(True)");
  1583. // LogStart();
  1584. CheckColumn(columns, cnd.False);
  1585. // LogStop("CheckColumn(False)");
  1586. //// LogStart();
  1587. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Left, useparams);
  1588. //// LogStop("LoadFieldsAndTables(Left)");
  1589. //// LogStart();
  1590. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Right, useparams);
  1591. //// LogStop("LoadFieldsAndTables(Right)");
  1592. //// LogStart();
  1593. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.True, useparams);
  1594. //// LogStop("LoadFieldsAndTables(True)");
  1595. //// LogStart();
  1596. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.False, useparams);
  1597. //// LogStop("LoadFieldsAndTables(False)");
  1598. // LogStart();
  1599. fieldmap[columnname] = GetCondition(cnd, cndmap, columnname);
  1600. // LogStop("GetCondition");
  1601. }
  1602. else
  1603. {
  1604. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1605. }
  1606. }
  1607. }
  1608. }
  1609. else
  1610. {
  1611. //IProperty customprop = DataModel.Property(type, columnname);
  1612. //if (customprop != null)
  1613. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1614. //else
  1615. fieldmap[columnname] = columnname;
  1616. }
  1617. }
  1618. else
  1619. {
  1620. var prop = type.GetProperty(bits.First());
  1621. if (prop != null)
  1622. {
  1623. var combinecount = 1;
  1624. while (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  1625. {
  1626. combinecount++;
  1627. prop = CoreUtils.GetProperty(type, string.Join(".", bits.Take(combinecount)));
  1628. }
  1629. if (prop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  1630. {
  1631. var linkedtype = prop.PropertyType.GetInheritedGenericTypeArguments().First();
  1632. var remote = linkedtype.GetProperty(bits.Last());
  1633. // Are there any other properties for this link? These will form the columns for our subquery
  1634. var siblings = columns.Where(x => x.Split('.').First().Equals(bits.First()))
  1635. .Select(x => string.Join(".", x.Split('.').Skip(combinecount))).ToList();
  1636. if (remote != null && !siblings.Contains(remote.Name))
  1637. siblings.Add(remote.Name);
  1638. if (siblings.Count.Equals(1) && siblings.First().Equals("ID"))
  1639. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1640. // Hmmm.. there must have been a reason why we do this, but...
  1641. // Deleted is not part of parent tables (only ID is), so the same
  1642. // shortcut that limits joining when we are only selecting ID's does
  1643. // not work if we are selecting Deleted's.
  1644. //else if (siblings.Count.Equals(2) && siblings.Skip(1).First().Equals("Deleted"))
  1645. // fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1646. else
  1647. {
  1648. if (!siblings.Contains("ID"))
  1649. siblings.Insert(0, "ID");
  1650. if (!siblings.Contains("Deleted"))
  1651. siblings.Insert(1, "Deleted");
  1652. var subcols = Columns.Create(linkedtype);
  1653. foreach (var sibling in siblings)
  1654. subcols.Add(sibling);
  1655. var filter = Activator.CreateInstance(typeof(Filter<>).MakeGenericType(linkedtype), "Deleted") as IFilter;
  1656. filter!.Operator = Operator.IsEqualTo;
  1657. filter.Value = Guid.Empty;
  1658. var linkedtable = string.Format("({0})",
  1659. PrepareSelectNonGeneric(linkedtype, command, newprefix, filter, subcols, null, null, null, int.MaxValue, false, useparams));
  1660. var link = string.Format("{0}.ID", prop.Name);
  1661. var tuple = tables.FirstOrDefault(x =>
  1662. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1663. if (tuple == null)
  1664. {
  1665. var alias = tables.Count + 1;
  1666. tuple = new Tuple<string, string, string, string>(
  1667. linkedtable,
  1668. prefix + alias.ToString(),
  1669. string.Format(
  1670. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[ID] = {1}1.[{3}.ID]",
  1671. linkedtable,
  1672. prefix,
  1673. alias,
  1674. string.Join(".", bits.Take(combinecount)) //prop.Name
  1675. ),
  1676. link
  1677. );
  1678. tables.Add(tuple);
  1679. }
  1680. //if (bits.Last().Equals("ID"))
  1681. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1682. //else
  1683. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  1684. foreach (var sibling in siblings)
  1685. {
  1686. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  1687. if (!subcol.Equals(columnname))
  1688. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  1689. }
  1690. }
  1691. }
  1692. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  1693. {
  1694. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1695. }
  1696. else
  1697. {
  1698. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1699. }
  1700. }
  1701. else
  1702. {
  1703. fieldmap[columnname] = columnname;
  1704. }
  1705. }
  1706. }
  1707. }
  1708. private static void CheckColumn(List<string> columns, string column)
  1709. {
  1710. if (!columns.Contains(column))
  1711. columns.Add(column);
  1712. }
  1713. public void FilterFields(IFilter? filter, List<string> fields)
  1714. {
  1715. if (filter == null)
  1716. return;
  1717. if (filter.Operator != Operator.None && filter.Operator != Operator.All)
  1718. {
  1719. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(filter.Expression), ".");
  1720. if (!fields.Contains(exp))
  1721. fields.Add(exp);
  1722. }
  1723. foreach (var and in filter.Ands)
  1724. FilterFields(and, fields);
  1725. foreach (var or in filter.Ors)
  1726. FilterFields(or, fields);
  1727. }
  1728. public void SortFields(ISortOrder? sort, List<string> fields)
  1729. {
  1730. if (sort == null)
  1731. return;
  1732. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(sort.Expression), ".");
  1733. if (!fields.Contains(exp))
  1734. fields.Add(exp);
  1735. foreach (var then in sort.Thens)
  1736. SortFields(then, fields);
  1737. }
  1738. public enum AggregateType
  1739. {
  1740. None,
  1741. Sum,
  1742. Count
  1743. }
  1744. public string PrepareSelectNonGeneric(Type T, SQLiteCommand command, char prefix,
  1745. IFilter? filter, IColumns? columns, ISortOrder? sort,
  1746. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, int top, bool distinct, bool useparams)
  1747. {
  1748. var fieldmap = new Dictionary<string, string>();
  1749. var cols = CoreUtils.GetColumns(T, columns);
  1750. var fields = new List<string>();
  1751. fields.AddRange(cols.ColumnNames());
  1752. FilterFields(filter, fields);
  1753. SortFields(sort, fields);
  1754. var tables = new List<Tuple<string, string, string, string>>();
  1755. var condition = "";
  1756. var sortorder = "";
  1757. var entityName = T.EntityName().Split('.').Last();
  1758. tables.Add(new Tuple<string, string, string, string>(
  1759. entityName,
  1760. $"{prefix}1",
  1761. $"{entityName} {prefix}1",
  1762. "")
  1763. );
  1764. foreach (var column in cols.ColumnNames())
  1765. LoadFieldsandTables(command, T, prefix, fieldmap, tables, fields, column, useparams);
  1766. var parameters = new Dictionary<string, object>();
  1767. condition = GetFilterClauseNonGeneric(T, command, prefix, filter, tables, fieldmap, fields, useparams);
  1768. sortorder = GetSortClauseNonGeneric(T, command, sort, prefix, tables, fieldmap, fields, useparams);
  1769. var combined = new SortedDictionary<string, string>();
  1770. fields.Clear();
  1771. foreach (var column in cols.ColumnNames())
  1772. if (fieldmap.ContainsKey(column))
  1773. {
  1774. if (aggregates != null && aggregates.ContainsKey(column))
  1775. combined[constants != null ? column : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0}({1}) as [{2}]", aggregates[column], fieldmap[column], column);
  1776. else
  1777. combined[constants != null ? column : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0} as [{1}]", fieldmap[column], column);
  1778. }
  1779. if (constants != null)
  1780. {
  1781. foreach(var (column, value) in constants)
  1782. {
  1783. combined[column] = string.Format("{0} as [{1}]", EscapeValue(value), column);
  1784. }
  1785. }
  1786. var result = new List<string>();
  1787. result.Add("SELECT");
  1788. if (distinct)
  1789. result.Add("DISTINCT");
  1790. result.Add(string.Join(", ", combined.Values));
  1791. result.Add("FROM");
  1792. result.AddRange(tables.Select(x => x.Item3));
  1793. if (!string.IsNullOrWhiteSpace(condition))
  1794. {
  1795. result.Add("WHERE");
  1796. result.Add(condition);
  1797. }
  1798. if (!string.IsNullOrWhiteSpace(sortorder))
  1799. {
  1800. result.Add("ORDER BY");
  1801. result.Add(sortorder);
  1802. }
  1803. if (aggregates != null)
  1804. {
  1805. var str = string.Join(", ",
  1806. fieldmap.Where(x => cols.ColumnNames().Contains(x.Key) && !aggregates.ContainsKey(x.Key)).Select(f => f.Value));
  1807. if (!string.IsNullOrWhiteSpace(str))
  1808. {
  1809. result.Add("GROUP BY");
  1810. result.Add(str);
  1811. }
  1812. }
  1813. if (top != int.MaxValue)
  1814. result.Add(String.Format("LIMIT {0}", top));
  1815. //Breadcrumb.Remove(Breadcrumb.Last());
  1816. return string.Join(" ", result);
  1817. }
  1818. public string PrepareSelect<T>(SQLiteCommand command, char prefix, Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort,
  1819. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, int top, bool distinct, bool useparams) where T : Entity
  1820. => PrepareSelectNonGeneric(typeof(T), command, prefix, filter, columns, sort, aggregates, constants, top, distinct, useparams);
  1821. private static void PrepareUpsertNonGeneric(Type T, SQLiteCommand command, Entity item, bool addDelete = false)
  1822. {
  1823. command.CommandText = "";
  1824. command.Parameters.Clear();
  1825. if (item.ID == Guid.Empty)
  1826. item.ID = Guid.NewGuid();
  1827. Dictionary<string, object> insert = item.GetValues(true);
  1828. Dictionary<string, object> update = item.GetValues(false);
  1829. if (addDelete)
  1830. {
  1831. insert.Add("Deleted", item.Deleted);
  1832. if (item.HasOriginalValue("Deleted"))
  1833. update.Add("Deleted", item.Deleted);
  1834. }
  1835. var insertfields = new List<string>();
  1836. var insertvalues = new List<string>();
  1837. var updatecommands = new List<string>();
  1838. var iParam = 0;
  1839. foreach (var key in insert.Keys)
  1840. {
  1841. if (insert[key] is UserProperties)
  1842. continue;
  1843. var sParam = string.Format("@p{0}", iParam++);
  1844. object? value = null;
  1845. try
  1846. {
  1847. value = Encode(insert[key], insert[key]?.GetType());
  1848. }
  1849. catch (Exception e)
  1850. {
  1851. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1852. }
  1853. command.Parameters.AddWithValue(sParam, value);
  1854. insertfields.Add(string.Format("[{0}]", key));
  1855. insertvalues.Add(sParam);
  1856. if (update.ContainsKey(key))
  1857. if (!key.Equals("ID"))
  1858. updatecommands.Add(string.Format("[{0}]={1}", key, sParam));
  1859. }
  1860. var particles = new List<string>();
  1861. particles.Add("INSERT INTO");
  1862. particles.Add(T.EntityName().Split('.').Last());
  1863. particles.Add("(");
  1864. particles.Add(string.Join(",", insertfields));
  1865. particles.Add(")");
  1866. particles.Add("VALUES");
  1867. particles.Add("(");
  1868. particles.Add(string.Join(",", insertvalues));
  1869. particles.Add(")");
  1870. if (updatecommands.Any())
  1871. particles.Add("ON CONFLICT([ID]) DO UPDATE SET " + string.Join(", ", updatecommands));
  1872. else
  1873. particles.Add("ON CONFLICT DO NOTHING");
  1874. command.CommandText = string.Join(" ", particles);
  1875. }
  1876. private void PrepareUpsert<T>(SQLiteCommand command, T item, bool addDelete = false) where T : Entity
  1877. => PrepareUpsertNonGeneric(typeof(T), command, item, addDelete);
  1878. public void PrepareDelete<T>(SQLiteCommand command, T item) where T : Entity
  1879. {
  1880. command.CommandText = string.Format("DELETE FROM {0} WHERE [ID] = @p0", typeof(T).EntityName().Split('.').Last());
  1881. command.Parameters.Clear();
  1882. command.Parameters.AddWithValue("@p0", Encode(item.ID, typeof(Guid)));
  1883. }
  1884. #endregion
  1885. #region Schema Handling
  1886. public Dictionary<string, Type> GetSchema()
  1887. {
  1888. var result = new Dictionary<string, Type>();
  1889. return result;
  1890. }
  1891. public void CreateSchema(params Type[] types)
  1892. {
  1893. }
  1894. public void SaveSchema(Dictionary<string, Type> schema)
  1895. {
  1896. }
  1897. public void UpgradeSchema(params Type[] types)
  1898. {
  1899. }
  1900. #endregion
  1901. #region CRUD Operations
  1902. public object[] GetValues(IDataReader reader, int count)
  1903. {
  1904. var result = new object[count];
  1905. reader.GetValues(result);
  1906. return result;
  1907. }
  1908. #region Query
  1909. public IEnumerable<object[]> List<T>(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null) where T : Entity, new()
  1910. {
  1911. var newFilter = new Filter<T>(x => x.Deleted).IsEqualTo(Guid.Empty);
  1912. if (filter != null)
  1913. newFilter.And(filter);
  1914. filter = newFilter;
  1915. //Dictionary<String, TimeSpan> stopwatch = new Dictionary<string, TimeSpan>();
  1916. //Stopwatch sw = new Stopwatch();
  1917. //sw.Start();
  1918. var cols = CoreUtils.GetColumns(columns);
  1919. //stopwatch["GetColumns"] = new TimeSpan(sw.ElapsedTicks);
  1920. //sw.Restart();
  1921. var result = new List<object[]>();
  1922. //stopwatch["MakeResult"] = new TimeSpan(sw.ElapsedTicks);
  1923. //sw.Restart();
  1924. using (var access = GetReadAccess())
  1925. {
  1926. using (var command = access.CreateCommand())
  1927. {
  1928. var sortorder = sort == null ? LookupFactory.DefineSort<T>() : sort;
  1929. command.CommandText = "";
  1930. command.Parameters.Clear();
  1931. command.CommandText = PrepareSelect(command, 'A', filter, cols, sortorder, null, null, int.MaxValue, false, true) + ";";
  1932. using (var reader = command.ExecuteReader())
  1933. {
  1934. foreach (var row in reader)
  1935. {
  1936. var values = GetValues(reader, cols.Items.Length);
  1937. result.Add(values);
  1938. }
  1939. reader.Close();
  1940. }
  1941. }
  1942. }
  1943. return result;
  1944. }
  1945. private CoreTable DoQueryNonGeneric(Type T, IFilter? filter = null, IColumns? columns = null, ISortOrder? sort = null, int top = int.MaxValue, bool log = true, bool distinct = false)
  1946. {
  1947. var start = DateTime.Now;
  1948. //LogReset();
  1949. //LogStart();
  1950. var cols = CoreUtils.GetColumns(T, columns);
  1951. //LogStop("GetColumns");
  1952. var result = new CoreTable(T.EntityName());
  1953. foreach (var col in cols.GetColumns())
  1954. result.Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.Type });
  1955. //LogStop("MakeTable");
  1956. using (var access = GetReadAccess())
  1957. {
  1958. using (var command = access.CreateCommand())
  1959. {
  1960. var sortorder = sort ?? LookupFactory.DefineSort(T);
  1961. command.CommandText = "";
  1962. command.Parameters.Clear();
  1963. //LogStart();
  1964. var sql = PrepareSelectNonGeneric(T, command, 'A', filter, cols, sortorder, null, null, top, distinct, true) + ";";
  1965. command.CommandText = sql;
  1966. try
  1967. {
  1968. using (var reader = command.ExecuteReader())
  1969. {
  1970. if (reader.HasRows)
  1971. {
  1972. var rows = new List<CoreRow>();
  1973. while (reader.Read())
  1974. {
  1975. var row = result.NewRow();
  1976. for (var i = 0; i < reader.FieldCount; i++)
  1977. try
  1978. {
  1979. var type = result.Columns[i].DataType;
  1980. if (reader.IsDBNull(i))
  1981. {
  1982. row.Values.Add(result.Columns[i].DataType.GetDefault());
  1983. }
  1984. else if (type.IsEnum)
  1985. {
  1986. ReadAndDecodeValue(result, reader, row, i);
  1987. }
  1988. else if (type == typeof(byte))
  1989. {
  1990. row.Values.Add(reader.GetByte(i));
  1991. }
  1992. else if (type == typeof(byte[]))
  1993. {
  1994. ReadAndDecodeValue(result, reader, row, i);
  1995. }
  1996. else if (type == typeof(bool))
  1997. {
  1998. ReadAndDecodeValue(result, reader, row, i);
  1999. }
  2000. else if (type == typeof(short))
  2001. {
  2002. row.Values.Add(reader.GetInt16(i));
  2003. }
  2004. else if (type == typeof(int))
  2005. {
  2006. row.Values.Add(reader.GetInt32(i));
  2007. }
  2008. else if (type == typeof(long))
  2009. {
  2010. row.Values.Add(reader.GetInt64(i));
  2011. }
  2012. else if (type == typeof(float))
  2013. {
  2014. row.Values.Add(reader.GetFloat(i));
  2015. }
  2016. else if (type == typeof(double))
  2017. {
  2018. row.Values.Add(reader.GetDouble(i));
  2019. }
  2020. else if (type == typeof(decimal))
  2021. {
  2022. row.Values.Add(reader.GetDecimal(i));
  2023. }
  2024. else if (type == typeof(string))
  2025. {
  2026. var value = reader.GetString(i);
  2027. row.Values.Add(value != null ? value : "");
  2028. }
  2029. else if (type == typeof(DateTime))
  2030. {
  2031. ReadAndDecodeValue(result, reader, row, i);
  2032. }
  2033. else if (type == typeof(TimeSpan))
  2034. {
  2035. ReadAndDecodeValue(result, reader, row, i);
  2036. }
  2037. else if (type == typeof(Guid))
  2038. {
  2039. row.Values.Add(reader.GetGuid(i));
  2040. }
  2041. else
  2042. {
  2043. ReadAndDecodeValue(result, reader, row, i);
  2044. }
  2045. }
  2046. catch (Exception)
  2047. {
  2048. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2049. }
  2050. result.Rows.Add(row);
  2051. }
  2052. }
  2053. reader.Close();
  2054. }
  2055. }
  2056. catch (Exception e)
  2057. {
  2058. OnLog?.Invoke(LogType.Error, e.Message);
  2059. }
  2060. //LogStop("ReadData");
  2061. //LogPrint(String.Format("Query{0}", typeof(T).Name));
  2062. }
  2063. }
  2064. if (log)
  2065. {
  2066. var duration = DateTime.Now - start;
  2067. Logger.Send(LogType.Information, "",
  2068. string.Format("SQLite::Query<{0}>({1} cols) returns {2} rows in {3}ms", T.Name, cols.Count, result.Rows.Count,
  2069. duration.TotalMilliseconds));
  2070. }
  2071. return result;
  2072. }
  2073. private CoreTable DoQuery<T>(Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort, int top, bool log, bool distinct)
  2074. where T : Entity, new() => DoQueryNonGeneric(typeof(T), filter, columns, sort, top, log, distinct);
  2075. 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)
  2076. where T : Entity, new()
  2077. {
  2078. var newFilter = new Filter<T>(x => x.Deleted).IsEqualTo(Guid.Empty);
  2079. if (filter != null)
  2080. newFilter.And(filter);
  2081. return DoQuery(newFilter, columns, sort, top, log, distinct);
  2082. }
  2083. public CoreTable QueryDeleted<T>(Deletion deletion, Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, int top = int.MaxValue)
  2084. where T : Entity, new()
  2085. {
  2086. if (filter != null)
  2087. filter.And(x => x.Deleted).IsEqualTo(deletion.ID);
  2088. else
  2089. filter = new Filter<T>(x => x.Deleted).IsEqualTo(deletion.ID);
  2090. return DoQuery(filter, columns, sort, top, true, false);
  2091. }
  2092. private void ReadAndDecodeValue(CoreTable result, SQLiteDataReader reader, CoreRow row, int i)
  2093. {
  2094. var value = reader.GetValue(i);
  2095. var decoded = Decode(value, result.Columns[i].DataType);
  2096. row.Values.Add(decoded);
  2097. }
  2098. public T[] Load<T>(Filter<T>? filter = null, SortOrder<T>? sort = null) where T : Entity, new()
  2099. {
  2100. var newFilter = new Filter<T>(x => x.Deleted).IsEqualTo(Guid.Empty);
  2101. if (filter != null)
  2102. newFilter.And(filter);
  2103. filter = newFilter;
  2104. var result = new List<T>();
  2105. var cols = CoreUtils.GetColumns<T>(null);
  2106. using (var access = GetReadAccess())
  2107. {
  2108. using (var command = access.CreateCommand())
  2109. {
  2110. try
  2111. {
  2112. command.CommandText = "";
  2113. command.Parameters.Clear();
  2114. command.CommandText = PrepareSelect(command, 'A', filter, cols, sort, null, null, int.MaxValue, false, true) + ";";
  2115. using (var reader = command.ExecuteReader())
  2116. {
  2117. if (reader.HasRows)
  2118. while (reader.Read())
  2119. {
  2120. var entity = new T();
  2121. entity.SetObserving(false);
  2122. for (var i = 0; i < reader.FieldCount; i++)
  2123. {
  2124. object value;
  2125. if (cols.Items[i].Expression.Type == typeof(long) && !reader.IsDBNull(i))
  2126. value = reader.GetInt64(i);
  2127. else
  2128. value = reader.GetValue(i);
  2129. try
  2130. {
  2131. var decoded = Decode(value, cols.Items[i].Expression.Type);
  2132. CoreUtils.SetPropertyValue(entity, cols.Items[i].Property, decoded);
  2133. }
  2134. catch (Exception e)
  2135. {
  2136. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2137. }
  2138. }
  2139. entity.SetObserving(true);
  2140. result.Add(entity);
  2141. }
  2142. reader.Close();
  2143. }
  2144. }
  2145. catch (Exception e)
  2146. {
  2147. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2148. }
  2149. }
  2150. }
  2151. return result.ToArray();
  2152. }
  2153. #endregion
  2154. #region Save
  2155. private void OnSaveNonGeneric(Type T, IEnumerable<Entity> entities, bool addDelete = false)
  2156. {
  2157. if (!entities.Any())
  2158. return;
  2159. using (var access = GetWriteAccess())
  2160. {
  2161. Exception? error = null;
  2162. using (var transaction = access.BeginTransaction())
  2163. {
  2164. try
  2165. {
  2166. using (var command = access.CreateCommand())
  2167. {
  2168. foreach (var entity in entities)
  2169. {
  2170. PrepareUpsertNonGeneric(T, command, entity, addDelete);
  2171. command.ExecuteNonQuery();
  2172. }
  2173. transaction.Commit();
  2174. }
  2175. }
  2176. catch (Exception e)
  2177. {
  2178. error = e;
  2179. transaction.Rollback();
  2180. }
  2181. }
  2182. if (error != null)
  2183. throw error;
  2184. }
  2185. }
  2186. private void OnSave<T>(IEnumerable<T> entities, bool addDelete = false) where T : Entity
  2187. => OnSaveNonGeneric(typeof(T), entities, addDelete);
  2188. public static bool CanSave<T>()
  2189. {
  2190. if (DbFactory.IsReadOnly)
  2191. {
  2192. if (typeof(T).IsAssignableTo(typeof(License)))
  2193. {
  2194. return true;
  2195. }
  2196. DbFactory.LogReadOnly();
  2197. return false;
  2198. }
  2199. return true;
  2200. }
  2201. public void Save<T>(IEnumerable<T> entities) where T : Entity
  2202. {
  2203. if (!CanSave<T>())
  2204. {
  2205. return;
  2206. }
  2207. OnSave(entities, false);
  2208. }
  2209. private void OnSaveNonGeneric(Type T, Entity entity, bool addDelete = false)
  2210. {
  2211. Exception? error = null;
  2212. using (var access = GetWriteAccess())
  2213. {
  2214. using (var command = access.CreateCommand())
  2215. {
  2216. try
  2217. {
  2218. PrepareUpsertNonGeneric(T, command, entity, addDelete);
  2219. command.ExecuteNonQuery();
  2220. }
  2221. catch (Exception e)
  2222. {
  2223. error = e;
  2224. }
  2225. }
  2226. }
  2227. if (error != null)
  2228. throw error;
  2229. }
  2230. private void OnSave<T>(T entity, bool addDelete = false) where T : Entity
  2231. => OnSaveNonGeneric(typeof(T), entity, addDelete);
  2232. public void Save<T>(T entity) where T : Entity
  2233. {
  2234. if (!CanSave<T>())
  2235. {
  2236. return;
  2237. }
  2238. OnSave(entity, false);
  2239. }
  2240. #endregion
  2241. #region Delete
  2242. public void Purge<T>(T entity) where T : Entity
  2243. {
  2244. using (var access = GetWriteAccess())
  2245. {
  2246. using (var command = access.CreateCommand())
  2247. {
  2248. PrepareDelete(command, entity);
  2249. var rows = command.ExecuteNonQuery();
  2250. }
  2251. }
  2252. }
  2253. public void Purge<T>(IEnumerable<T> entities) where T : Entity
  2254. {
  2255. if (!entities.Any())
  2256. return;
  2257. Exception? error = null;
  2258. using (var access = GetWriteAccess())
  2259. {
  2260. using (var transaction = access.BeginTransaction())
  2261. {
  2262. try
  2263. {
  2264. using (var command = access.CreateCommand())
  2265. {
  2266. foreach (var entity in entities)
  2267. {
  2268. PrepareDelete(command, entity);
  2269. var rows = command.ExecuteNonQuery();
  2270. }
  2271. }
  2272. transaction.Commit();
  2273. }
  2274. catch (Exception e)
  2275. {
  2276. transaction.Rollback();
  2277. error = e;
  2278. }
  2279. }
  2280. }
  2281. if (error != null)
  2282. throw error;
  2283. }
  2284. private Dictionary<Type, List<Tuple<Type, string>>> _cascades = new();
  2285. private Dictionary<Type, List<Tuple<Type, List<string>>>> _setNulls = new();
  2286. private void LoadDeletions(Type type)
  2287. {
  2288. // Get the EntityLink that is associated with this class
  2289. var linkclass = CoreUtils.TypeList(
  2290. new[] { type.Assembly },
  2291. x => typeof(IEntityLink).GetTypeInfo().IsAssignableFrom(x) && x.GetInheritedGenericTypeArguments().FirstOrDefault() == type
  2292. ).FirstOrDefault();
  2293. // if The entitylink does not exist, we don't need to do anything
  2294. if (linkclass == null)
  2295. return;
  2296. var cascades = new List<Tuple<Type, string>>();
  2297. var setNulls = new List<Tuple<Type, List<string>>>();
  2298. var childtypes = Types.Where(x => x.IsSubclassOf(typeof(Entity)) && x.GetCustomAttribute<AutoEntity>() == null);
  2299. foreach (var childtype in childtypes)
  2300. {
  2301. // Get all registered types for this entitylink
  2302. var fields = new List<string>();
  2303. var bDelete = false;
  2304. // Find any IEntityLink<> properties that refer back to this class
  2305. var childprops = CoreUtils.PropertyList(childtype, x => x.PropertyType == linkclass);
  2306. foreach (var childprop in childprops)
  2307. {
  2308. var fieldname = string.Format("{0}.ID", childprop.Name);
  2309. var attr = childprop.GetCustomAttributes(typeof(EntityRelationshipAttribute), true).FirstOrDefault();
  2310. if (attr != null && ((EntityRelationshipAttribute)attr).Action.Equals(DeleteAction.Cascade))
  2311. {
  2312. cascades.Add(new(childtype, fieldname));
  2313. bDelete = true;
  2314. break;
  2315. }
  2316. fields.Add(fieldname);
  2317. }
  2318. if(!bDelete && fields.Any())
  2319. {
  2320. setNulls.Add(new(childtype, fields));
  2321. }
  2322. }
  2323. if(cascades.Count > 0)
  2324. {
  2325. _cascades[type] = cascades;
  2326. }
  2327. if(setNulls.Count > 0)
  2328. {
  2329. _setNulls[type] = setNulls;
  2330. }
  2331. }
  2332. private MethodInfo _deleteEntitiesMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2333. .Single(x => x.Name == nameof(DeleteEntity) && x.IsGenericMethod);
  2334. private void DeleteEntity<T>(Guid parentID, string parentField, DeletionData deletionData) where T : Entity, new()
  2335. {
  2336. var columns = DeletionData.DeletionColumns<T>();
  2337. var entities = Query(new Filter<T>(parentField).IsEqualTo(parentID), columns);
  2338. foreach(var row in entities.Rows)
  2339. {
  2340. deletionData.DeleteEntity<T>(row);
  2341. CascadeDelete(typeof(T), row.Get<T, Guid>(x => x.ID), deletionData);
  2342. }
  2343. }
  2344. private void DeleteEntity(Type T, Guid parentID, string parentField, DeletionData deletionData)
  2345. {
  2346. _deleteEntitiesMethod.MakeGenericMethod(T).Invoke(this, new object?[] { parentID, parentField, deletionData });
  2347. }
  2348. private MethodInfo _setNullEntityMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2349. .Single(x => x.Name == nameof(SetNullEntity) && x.IsGenericMethod);
  2350. private void SetNullEntity<T>(List<string> properties, Guid parentID, DeletionData deletionData) where T : Entity, new()
  2351. {
  2352. foreach(var property in properties)
  2353. {
  2354. var entities = Query(new Filter<T>(property).IsEqualTo(parentID), new Columns<T>(x => x.ID));
  2355. foreach (var row in entities.Rows)
  2356. {
  2357. deletionData.SetNullEntity<T>(row.Get<T, Guid>(x => x.ID), property, parentID);
  2358. }
  2359. }
  2360. }
  2361. private void SetNullEntity(Type T, List<string> properties, Guid parentID, DeletionData deletionData)
  2362. {
  2363. _setNullEntityMethod.MakeGenericMethod(T).Invoke(this, new object?[] { properties, parentID, deletionData });
  2364. }
  2365. private void CascadeDelete(Type type, Guid parentID, DeletionData deletionData)
  2366. {
  2367. if (_cascades.TryGetValue(type, out var cascades))
  2368. {
  2369. foreach (var cascade in cascades)
  2370. {
  2371. DeleteEntity(cascade.Item1, parentID, cascade.Item2, deletionData);
  2372. }
  2373. }
  2374. if(_setNulls.TryGetValue(type, out var setNulls))
  2375. {
  2376. foreach(var setNull in setNulls)
  2377. {
  2378. SetNullEntity(setNull.Item1, setNull.Item2, parentID, deletionData);
  2379. }
  2380. }
  2381. }
  2382. public void Delete<T>(T entity, string userID) where T : Entity, new()
  2383. {
  2384. //#if PURGE
  2385. if (!CanSave<T>())
  2386. {
  2387. return;
  2388. }
  2389. entity = DoQuery(
  2390. new Filter<T>(x => x.ID).IsEqualTo(entity.ID),
  2391. DeletionData.DeletionColumns<T>(),
  2392. null,
  2393. int.MaxValue,
  2394. true,
  2395. false
  2396. ).Rows.First().ToObject<T>();
  2397. var deletionData = new DeletionData();
  2398. deletionData.DeleteEntity(entity);
  2399. CascadeDelete(typeof(T), entity.ID, deletionData);
  2400. var tableName = typeof(T).Name;
  2401. var deletion = new Deletion()
  2402. {
  2403. DeletionDate = DateTime.Now,
  2404. HeadTable = tableName,
  2405. Description = entity.ToString() ?? "",
  2406. DeletedBy = userID,
  2407. Data = Serialization.Serialize(deletionData)
  2408. };
  2409. OnSave(deletion);
  2410. //#else
  2411. Purge(entity);
  2412. //#endif
  2413. }
  2414. public void Delete<T>(IEnumerable<T> entities, string userID) where T : Entity, new()
  2415. {
  2416. //#if PURGE
  2417. if (!CanSave<T>())
  2418. {
  2419. return;
  2420. }
  2421. if (!entities.Any())
  2422. return;
  2423. var ids = entities.Select(x => x.ID).ToArray();
  2424. var entityList = Query(
  2425. new Filter<T>(x => x.ID).InList(ids),
  2426. DeletionData.DeletionColumns<T>()).Rows.Select(x => x.ToObject<T>()).ToList();
  2427. if (!entityList.Any())
  2428. return;
  2429. var deletionData = new DeletionData();
  2430. foreach (var entity in entityList)
  2431. {
  2432. deletionData.DeleteEntity(entity);
  2433. CascadeDelete(typeof(T), entity.ID, deletionData);
  2434. }
  2435. var tableName = typeof(T).Name;
  2436. var deletion = new Deletion()
  2437. {
  2438. DeletionDate = DateTime.Now,
  2439. HeadTable = tableName,
  2440. Description = $"Deleted {entityList.Count} entries",
  2441. DeletedBy = userID,
  2442. Data = Serialization.Serialize(deletionData)
  2443. };
  2444. OnSave(deletion);
  2445. //#else
  2446. Purge(entities);
  2447. //#endif
  2448. }
  2449. private void AddDeletionType(Type type, List<Type> deletions)
  2450. {
  2451. deletions.Add(type);
  2452. if (!_cascades.TryGetValue(type, out var cascades))
  2453. return;
  2454. foreach (var cascade in cascades)
  2455. {
  2456. AddDeletionType(cascade.Item1, deletions);
  2457. }
  2458. }
  2459. private Dictionary<Type, List<Type>> _allCascades = new();
  2460. private List<Type> GetDeletionTypes(Type type)
  2461. {
  2462. if(_allCascades.TryGetValue(type, out var cascades))
  2463. {
  2464. return cascades;
  2465. }
  2466. var deletionTypes = new List<Type>();
  2467. AddDeletionType(type, deletionTypes);
  2468. _allCascades[type] = deletionTypes;
  2469. return deletionTypes;
  2470. }
  2471. /*private void DoSetNull<TChild>(string field, Guid[] parentIDs) where TChild : Entity, new()
  2472. {
  2473. var columns = new Columns<TChild>(x => x.ID);
  2474. columns.Add(field);
  2475. var children = DoQuery(
  2476. new Filter<TChild>(field).InList(parentIDs),
  2477. columns,
  2478. null,
  2479. int.MaxValue,
  2480. true,
  2481. false
  2482. ).Rows.Select(x => x.ToObject<TChild>()).ToList();
  2483. foreach(var child in children)
  2484. {
  2485. CoreUtils.SetPropertyValue(child, field, Guid.Empty);
  2486. }
  2487. OnSave(children);
  2488. }*/
  2489. /*private void PurgeEntityType<T>(Deletion deletion) where T : Entity, new()
  2490. {
  2491. var entities = QueryDeleted(deletion, null, new Columns<T>(x => x.ID)).Rows.Select(x => x.ToObject<T>()).ToList();
  2492. if (_setNulls.TryGetValue(typeof(T), out var setNulls))
  2493. {
  2494. var ids = entities.Select(x => x.ID).ToArray();
  2495. var setNullMethod = typeof(SQLiteProvider).GetMethod(nameof(DoSetNull), BindingFlags.NonPublic | BindingFlags.Instance)!;
  2496. foreach (var (childType, childFields) in setNulls)
  2497. {
  2498. var method = setNullMethod.MakeGenericMethod(childType);
  2499. foreach(var childField in childFields)
  2500. {
  2501. method.Invoke(this, new object[] { childField, ids });
  2502. }
  2503. }
  2504. }
  2505. Purge(entities);
  2506. }*/
  2507. /*private void RecoverEntityType<T>(Deletion deletion) where T : Entity, new()
  2508. {
  2509. var entities = QueryDeleted(deletion, null, new Columns<T>(x => x.ID, x => x.Deleted)).Rows.Select(x => x.ToObject<T>()).ToList();
  2510. foreach (var entity in entities)
  2511. {
  2512. entity.Deleted = Guid.Empty;
  2513. }
  2514. OnSave(entities, true);
  2515. }*/
  2516. public void Purge(Deletion deletion)
  2517. {
  2518. /*if(deletion.ID == Guid.Empty)
  2519. {
  2520. Logger.Send(LogType.Error, "", "Empty Deletion ID; Purge cancelled");
  2521. return;
  2522. }
  2523. var entityType = CoreUtils.Entities.FirstOrDefault(x => x.Name == deletion.HeadTable);
  2524. if(entityType is null)
  2525. {
  2526. Logger.Send(LogType.Error, "", $"Entity {deletion.HeadTable} does not exist; Purge cancelled");
  2527. return;
  2528. }
  2529. var deletionTypes = GetDeletionTypes(entityType);
  2530. var purgeMethod = typeof(SQLiteProvider).GetMethod(nameof(PurgeEntityType), BindingFlags.NonPublic | BindingFlags.Instance)!;
  2531. foreach(var type in deletionTypes)
  2532. {
  2533. purgeMethod.MakeGenericMethod(type).Invoke(this, new object[] { deletion });
  2534. }
  2535. */
  2536. Purge<Deletion>(deletion);
  2537. }
  2538. public void Recover(Deletion deletion)
  2539. {
  2540. if (deletion.ID == Guid.Empty)
  2541. {
  2542. Logger.Send(LogType.Error, "", "Empty Deletion ID; Recovery cancelled");
  2543. return;
  2544. }
  2545. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  2546. if (data is null)
  2547. {
  2548. Logger.Send(LogType.Error, "", "Deletion Data deserialisation failed; Recovery cancelled");
  2549. return;
  2550. }
  2551. foreach (var (entityName, setNulls) in data.SetNulls)
  2552. {
  2553. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2554. var saves = new List<Entity>();
  2555. foreach(var setNull in setNulls)
  2556. {
  2557. var row = DoQueryNonGeneric(entityType,
  2558. Filter.Create<Entity>(entityType, x => x.ID).IsEqualTo(setNull.EntityID),
  2559. Columns.Create(entityType).Add<Entity>(x => x.ID).Add(setNull.Property)).Rows.FirstOrDefault();
  2560. if (row is null) continue;
  2561. var entity = (row.ToObject(entityType) as Entity)!;
  2562. CoreUtils.SetPropertyValue(entity, setNull.Property, setNull.ParentID);
  2563. saves.Add(entity);
  2564. }
  2565. OnSaveNonGeneric(entityType, saves);
  2566. }
  2567. foreach(var (entityName, cascade) in data.Cascades)
  2568. {
  2569. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2570. OnSaveNonGeneric(entityType, cascade.ToObjects(entityType).Cast<Entity>());
  2571. }
  2572. Purge<Deletion>(deletion);
  2573. }
  2574. public List<Type> GetDeletionTypes(Deletion deletion)
  2575. {
  2576. var entityType = CoreUtils.Entities.First(x => x.Name == deletion.HeadTable);
  2577. return GetDeletionTypes(entityType);
  2578. }
  2579. #endregion
  2580. #endregion
  2581. }
  2582. }