SQLiteProvider.cs 131 KB

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