SQLiteProvider.cs 138 KB

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