SQLiteProvider.cs 138 KB

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