SQLiteProvider.cs 139 KB

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