SQLiteProvider.cs 140 KB

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