SQLiteProvider.cs 131 KB

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