SQLiteProvider.cs 128 KB

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