SQLiteProvider.cs 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286
  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.Now => "datetime()",
  1212. FilterConstant.Today => "datetime(date())",
  1213. FilterConstant.Zero => "0",
  1214. // These figures are based around today
  1215. FilterConstant.OneWeekAgo => "datetime(date(),'-7 days')",
  1216. FilterConstant.OneWeekAhead => "datetime(date(),'+7 days')",
  1217. FilterConstant.OneMonthAgo => "datetime(date(),'-1 month')",
  1218. FilterConstant.OneMonthAhead => "datetime(date(),'+1 month')",
  1219. FilterConstant.ThreeMonthsAgo => "datetime(date(),'-3 months')",
  1220. FilterConstant.ThreeMonthsAhead => "datetime(date(),'+3 months')",
  1221. FilterConstant.SixMonthsAgo => "datetime(date(),'-6 months')",
  1222. FilterConstant.SixMonthsAhead => "datetime(date(),'+6 months')",
  1223. FilterConstant.OneYearAgo => "datetime(date(),'-1 year')",
  1224. FilterConstant.OneYearAhead => "datetime(date(),'+1 year')",
  1225. // Relative Week values run from Monday thru Sunday
  1226. FilterConstant.StartOfLastWeek => "datetime(date(), 'weekday 0', '-13 days')",
  1227. FilterConstant.EndOfLastWeek => "datetime(date(), 'weekday 0', '-6 days', '-000.0001 seconds')",
  1228. FilterConstant.StartOfThisWeek => "datetime(date(), 'weekday 0', '-6 days')",
  1229. FilterConstant.EndOfThisWeek => "datetime(date(), 'weekday 0', '+1 day', '-000.0001 seconds')",
  1230. FilterConstant.StartOfNextWeek => "datetime(date(), 'weekday 0', '+1 days')",
  1231. FilterConstant.EndOfNextWeek => "datetime(date(), 'weekday 0', '+8 days', '-000.0001 seconds')",
  1232. FilterConstant.StartOfLastMonth => "datetime(date(), 'start of month', '-1 month')",
  1233. FilterConstant.EndOfLastMonth => "datetime(date(), 'start of month', '-000.0001 seconds')",
  1234. FilterConstant.StartOfThisMonth => "datetime(date(), 'start of month')",
  1235. FilterConstant.EndOfThisMonth => "datetime(date(), 'start of month', '+1 month', '-000.0001 seconds')",
  1236. FilterConstant.StartOfNextMonth => "datetime(date(), 'start of month', '+1 month')",
  1237. FilterConstant.EndOfNextMonth => "datetime(date(), 'start of month', '+2 months', '-000.0001 seconds')",
  1238. FilterConstant.StartOfLastCalendarYear => "datetime(date(), 'start of year', '-1 year')",
  1239. FilterConstant.EndOfLastCalendarYear => "datetime(date(), 'start of year', '-000.0001 seconds')",
  1240. FilterConstant.StartOfThisCalendarYear => "datetime(date(), 'start of year')",
  1241. FilterConstant.EndOfThisCalendarYear => "datetime(date(), 'start of year', '+1 year', '-000.0001 seconds')",
  1242. FilterConstant.StartOfNextCalendarYear => "datetime(date(), 'start of year', '+1 year')",
  1243. FilterConstant.EndOfNextCalendarYear => "datetime(date(), 'start of year', '+2 years', '-000.0001 seconds')",
  1244. FilterConstant.StartOfLastFinancialYear => "datetime(date(), '-18 months', 'start of year', '+6 months')",
  1245. FilterConstant.EndOfLastFinancialYear => "datetime(date(), '-18 months', 'start of year', '-18 months', '-000.0001 seconds')",
  1246. FilterConstant.StartOfThisFinancialYear => "datetime(date(), '-6 months', 'start of year', '+6 months')",
  1247. FilterConstant.EndOfThisFinancialYear => "datetime(date(), '-6 months', 'start of year', '+18 months', '-000.0001 seconds')",
  1248. FilterConstant.StartOfNextFinancialYear => "datetime(date(), '+6 months', 'start of year', '+6 months')",
  1249. FilterConstant.EndOfNextFinancialYear => "datetime(date(), '+6 months', 'start of year', '+18 months', '-000.0001 seconds')",
  1250. _ => throw new Exception($"FilterConstant.{constant} is not implemented!"),
  1251. };
  1252. }
  1253. private string GetFilterClauseNonGeneric(Type T, SQLiteCommand command, char prefix, IFilter? filter, List<Tuple<string, string, string, string>> tables,
  1254. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1255. {
  1256. if (filter == null || filter.Expression == null)
  1257. return "";
  1258. var result = "";
  1259. if (filter.Operator == Operator.All)
  1260. {
  1261. result = filter.IsNot ? "1 = 0" : "1 = 1";
  1262. }
  1263. else if (filter.Operator == Operator.None)
  1264. {
  1265. result = filter.IsNot ? "1 = 1" : "1 = 0";
  1266. }
  1267. else
  1268. {
  1269. string prop;
  1270. if (CoreUtils.TryFindMemberExpression(filter.Expression, out var mexp))
  1271. {
  1272. prop = CoreUtils.GetFullPropertyName(mexp, ".");
  1273. }
  1274. else
  1275. {
  1276. prop = filter.Expression.ToString();
  1277. if (prop.Contains("=>"))
  1278. prop = string.Join(".", prop.Split('.').Skip(1));
  1279. mexp = CoreUtils.GetMemberExpression(T, prop);
  1280. }
  1281. LoadFieldsandTables(command, T, prefix, fieldmap, tables, columns, prop, useparams);
  1282. if (fieldmap.ContainsKey(prop))
  1283. prop = fieldmap[prop];
  1284. if(filter.Value is CustomFilterValue)
  1285. {
  1286. throw new Exception("Custom Filter Value not able to be processed server-side!");
  1287. }
  1288. if (filter.Operator == Operator.InList || filter.Operator == Operator.NotInList)
  1289. {
  1290. // if, and only if the list contains Guids, we can safely bypass the
  1291. // 1000-parameter limit by using building the string ourselves
  1292. if (filter.Value is Guid[] list)
  1293. {
  1294. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Format("\"{0}\"", string.Join("\",\"", list)));
  1295. }
  1296. else if (filter.Value is IEnumerable enumerable)
  1297. {
  1298. var paramlist = new List<object>();
  1299. foreach (var item in enumerable)
  1300. {
  1301. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1302. command.Parameters.AddWithValue(sParam, Encode(item, mexp.Type));
  1303. paramlist.Add(sParam);
  1304. }
  1305. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Join(",", paramlist));
  1306. }
  1307. }
  1308. else if (filter.Operator == Operator.InQuery || filter.Operator == Operator.NotInQuery)
  1309. {
  1310. if(filter.Value is ISubQuery subQuery)
  1311. {
  1312. var subEntityType = subQuery.GetQueryType();
  1313. var subColumns = Columns.None(subEntityType);
  1314. var subColumn = subQuery.GetColumn();
  1315. subColumns.Add(subColumn);
  1316. var subQueryText = PrepareSelectNonGeneric(subEntityType, command, 'A',
  1317. subQuery.GetFilter(), subColumns, null,
  1318. null, null, null, false, useparams);
  1319. result = string.Format("(" + operators[filter.Operator] + ")", prop, subQueryText);
  1320. }
  1321. }
  1322. else
  1323. {
  1324. if (filter.Value is FilterConstant constant)
  1325. result = string.Format("(" + operators[filter.Operator] + ")", prop, GetFilterConstant(constant));
  1326. else
  1327. {
  1328. var value = Encode(filter.Value, mexp.Type);
  1329. if (IsNull(value) && ((filter.Operator == Operator.IsEqualTo) || (filter.Operator == Operator.IsNotEqualTo)))
  1330. {
  1331. result = string.Format("({0} {1} NULL)", prop,
  1332. filter.Operator == Operator.IsEqualTo
  1333. ? "IS"
  1334. : "IS NOT");
  1335. }
  1336. else
  1337. {
  1338. if (useparams)
  1339. {
  1340. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1341. if (filter.Expression.Type == typeof(string[]))
  1342. {
  1343. var bytes = Encoding.ASCII.GetBytes(value.ToString() ?? "");
  1344. value = BitConverter.ToString(bytes).Replace("-", "");
  1345. result = string.Format("(" + operators[filter.Operator] + ")", string.Format("hex({0})", prop), sParam);
  1346. }
  1347. else
  1348. {
  1349. result = string.Format("(" + operators[filter.Operator] + ")", prop, sParam);
  1350. }
  1351. command.Parameters.AddWithValue(sParam, value);
  1352. }
  1353. else
  1354. result = string.Format("(" + operators[filter.Operator] + ")", prop, EscapeValue(filter.Value));
  1355. }
  1356. }
  1357. }
  1358. if (filter.IsNot)
  1359. {
  1360. result = $"(NOT {result})";
  1361. }
  1362. }
  1363. var bChanged = false;
  1364. if (filter.Ands != null && filter.Ands.Any())
  1365. {
  1366. foreach (var and in filter.Ands)
  1367. {
  1368. var AndResult = GetFilterClauseNonGeneric(T, command, prefix, and, tables, fieldmap, columns, useparams);
  1369. if (!string.IsNullOrEmpty(AndResult))
  1370. {
  1371. result = string.Format("{0} and {1}", result, AndResult);
  1372. bChanged = true;
  1373. }
  1374. }
  1375. if (bChanged)
  1376. result = string.Format("({0})", result);
  1377. }
  1378. bChanged = false;
  1379. if (filter.Ors != null && filter.Ors.Any())
  1380. {
  1381. foreach (var or in filter.Ors)
  1382. {
  1383. var OrResult = GetFilterClauseNonGeneric(T, command, prefix, or, tables, fieldmap, columns, useparams);
  1384. if (!string.IsNullOrEmpty(OrResult))
  1385. {
  1386. result = string.Format("{0} or {1}", result, OrResult);
  1387. bChanged = true;
  1388. }
  1389. }
  1390. if (bChanged)
  1391. result = string.Format("({0})", result);
  1392. }
  1393. return result;
  1394. }
  1395. private string GetFilterClause<T>(SQLiteCommand command, char prefix, Filter<T>? filter, List<Tuple<string, string, string, string>> tables,
  1396. Dictionary<string, string> fieldmap, List<string> columns, bool useparams) where T : Entity
  1397. => GetFilterClauseNonGeneric(typeof(T), command, prefix, filter, tables, fieldmap, columns, useparams);
  1398. private string GetSortClauseNonGeneric(Type T,
  1399. SQLiteCommand command, ISortOrder? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1400. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1401. {
  1402. if (sort == null)
  1403. return "";
  1404. var result = "";
  1405. if (sort.Expression != null)
  1406. {
  1407. if (CoreUtils.TryFindMemberExpression(sort.Expression, out var mexp))
  1408. result = CoreUtils.GetFullPropertyName(mexp, ".");
  1409. else
  1410. result = sort.Expression.ToString();
  1411. var prop = CoreUtils.GetProperty(T, result);
  1412. if (prop.GetCustomAttribute<DoNotSerialize>() == null && prop.GetCustomAttribute<DoNotPersist>() == null && prop.CanWrite)
  1413. {
  1414. LoadFieldsandTables(command, T, prefix, fieldmap, tables, columns, result, useparams);
  1415. if (fieldmap.ContainsKey(result))
  1416. result = fieldmap[result];
  1417. if (sort.Expression.Type.Equals(typeof(string)))
  1418. result = string.Format("{0} COLLATE NOCASE", result);
  1419. if (sort.Direction == SortDirection.Ascending)
  1420. result = string.Format("{0} ASC", result);
  1421. else
  1422. result = string.Format("{0} DESC", result);
  1423. }
  1424. else
  1425. {
  1426. result = "";
  1427. }
  1428. }
  1429. foreach (var then in sort.Thens)
  1430. result = result + ", " + GetSortClauseNonGeneric(T, command, then, prefix, tables, fieldmap, columns, useparams);
  1431. return result;
  1432. }
  1433. private string GetSortClause<T>(SQLiteCommand command, SortOrder<T>? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1434. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1435. => GetSortClauseNonGeneric(typeof(T), command, sort, prefix, tables, fieldmap, columns, useparams);
  1436. private static string GetCalculation(AggregateAttribute attribute, string columnname)
  1437. {
  1438. return attribute.Calculation switch
  1439. {
  1440. AggregateCalculation.Sum => "SUM",
  1441. AggregateCalculation.Count => "COUNT",
  1442. AggregateCalculation.Maximum => "MAX",
  1443. AggregateCalculation.Minimum => "MIN",
  1444. AggregateCalculation.Average => "AVERAGE",
  1445. AggregateCalculation.Concat => "GROUP_CONCAT",
  1446. _ => throw new Exception(string.Format("{0}.{1} is not a valid aggregate", columnname, attribute.Calculator.GetType().Name)),
  1447. };
  1448. }
  1449. private string GetFunction(FormulaAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1450. {
  1451. if (attribute.Operator == FormulaOperator.None)
  1452. throw new Exception(string.Format("{0}.{1} is not a valid formula", columnname, attribute.Calculator.GetType().Name));
  1453. if (attribute.Operator == FormulaOperator.Constant)
  1454. return EscapeValue(attribute.Value);
  1455. if (!fieldmap.ContainsKey(attribute.Value))
  1456. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Value));
  1457. foreach (var modifier in attribute.Modifiers)
  1458. if (!fieldmap.ContainsKey(modifier))
  1459. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, modifier));
  1460. if (attribute.Operator == FormulaOperator.Add)
  1461. return string.Format("(IFNULL({0},0.00) + {1})", fieldmap[attribute.Value],
  1462. string.Join(" + ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1463. if (attribute.Operator == FormulaOperator.Subtract)
  1464. return string.Format("(IFNULL({0},0.00) - ({1}))", fieldmap[attribute.Value],
  1465. string.Join(" + ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1466. if (attribute.Operator == FormulaOperator.Multiply)
  1467. return string.Format("(IFNULL({0},0.00) * {1})", fieldmap[attribute.Value],
  1468. string.Join(" * ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1469. if (attribute.Operator == FormulaOperator.Divide)
  1470. {
  1471. var result = string.Format("IFNULL({0},0.00)", fieldmap[attribute.Value]);
  1472. foreach (var modifier in attribute.Modifiers)
  1473. result = string.Format("({0} / {1})", result, string.Format("IFNULL({0},1.00)", fieldmap[modifier]));
  1474. return result;
  1475. }
  1476. if (attribute.Operator == FormulaOperator.Maximum)
  1477. {
  1478. var parameters = attribute.Modifiers.Select(m => $"IFNULL({fieldmap[m]},0.00)");
  1479. var result = $"MAX({fieldmap[attribute.Value]}, {String.Join(", ", parameters)})";
  1480. // var result = string.Format(
  1481. // "CASE IFNULL({0},0.00) WHEN IFNULL({0},0.00) < IFNULL({1},0.00) THEN IFNULL({1},0.00) ELSE IFNULL({0},0.00) END",
  1482. // fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1483. return result;
  1484. }
  1485. if (attribute.Operator == FormulaOperator.Minumum)
  1486. {
  1487. var parameters = attribute.Modifiers.Select(m => $"IFNULL({fieldmap[m]},0.00)");
  1488. var result = $"MIN({fieldmap[attribute.Value]}, {String.Join(", ", parameters)})";
  1489. //var result = string.Format(
  1490. // "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",
  1491. // fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1492. return result;
  1493. }
  1494. throw new Exception(string.Format("Calculation Type [{0}.{1}] not found", columnname, attribute.GetType().Name));
  1495. }
  1496. private string GetCondition(ConditionAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1497. {
  1498. var intf = attribute.Calculator.GetType().GetInterfaces()
  1499. .FirstOrDefault(x => x.Name.StartsWith("ICondition") && x.GenericTypeArguments.Length.Equals(3));
  1500. if (intf is null)
  1501. throw new Exception($"Attribute calculate {attribute.Calculator} is not an ICondition");
  1502. var valuetype = intf.GenericTypeArguments[1];
  1503. var defvalue = valuetype.GetDefault();
  1504. if (!fieldmap.ContainsKey(attribute.Left))
  1505. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Left));
  1506. var condition = "";
  1507. if (attribute.Condition == Condition.Equals)
  1508. condition = "=";
  1509. else if (attribute.Condition == Condition.NotEqual)
  1510. condition = "<>";
  1511. else if (attribute.Condition == Condition.GreaterThan)
  1512. condition = ">";
  1513. else if (attribute.Condition == Condition.GreaterThanOrEqualTo)
  1514. condition = ">=";
  1515. else if (attribute.Condition == Condition.LessThan)
  1516. condition = "<";
  1517. else if (attribute.Condition == Condition.LessThanOrEqualTo)
  1518. condition = "<=";
  1519. else
  1520. throw new Exception(string.Format("{0}.{1} is not a valid condition", columnname, attribute.Calculator.GetType().Name));
  1521. if (!fieldmap.ContainsKey(attribute.Right))
  1522. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Right));
  1523. if (!fieldmap.ContainsKey(attribute.True))
  1524. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.True));
  1525. if (!fieldmap.ContainsKey(attribute.False))
  1526. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.False));
  1527. return string.Format("CASE WHEN COALESCE({0},{1}) {2} {3} THEN {4} ELSE {5} END", fieldmap[attribute.Left], defvalue, condition,
  1528. fieldmap[attribute.Right], fieldmap[attribute.True], fieldmap[attribute.False]);
  1529. }
  1530. //private static List<string> Breadcrumb = new List<string>();
  1531. //Dictionary<String, Tuple<int, TimeSpan>> stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1532. //Stopwatch sw = new Stopwatch();
  1533. //private void LogReset()
  1534. //{
  1535. // stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1536. // sw = new Stopwatch();
  1537. //}
  1538. //void LogStart()
  1539. //{
  1540. // if (sw.IsRunning)
  1541. // sw.Restart();
  1542. // else
  1543. // sw.Start();
  1544. //}
  1545. //void LogStop(String msg)
  1546. //{
  1547. // TimeSpan elapsed = sw.Elapsed;
  1548. // if (Breadcrumb.Any())
  1549. // msg = String.Join(".", Breadcrumb) + "." + msg;
  1550. // if (!stopwatch.ContainsKey(msg))
  1551. // stopwatch[msg] = new Tuple<int, TimeSpan>(1,elapsed);
  1552. // else
  1553. // stopwatch[msg] = new Tuple<int, TimeSpan>(stopwatch[msg].Item1 + 1,stopwatch[msg].Item2 + elapsed);
  1554. // sw.Restart();
  1555. //}
  1556. //private void LogPrint(String header)
  1557. //{
  1558. // foreach (var keyvalue in stopwatch.ToArray())
  1559. // Log(LogType.Information, String.Format("- {0}: {1} = ({2}) {3,10:0.0000}", header, keyvalue.Key, keyvalue.Value.Item1, keyvalue.Value.Item2.TotalMilliseconds));
  1560. //}
  1561. private void LoadFieldsandTables(SQLiteCommand command, Type type, char prefix, Dictionary<string, string> fieldmap,
  1562. List<Tuple<string, string, string, string>> tables, List<string> columns, string columnname, bool useparams)
  1563. {
  1564. if (fieldmap.ContainsKey(columnname))
  1565. return;
  1566. var newprefix = (char)(prefix + 1);
  1567. // LogStart();
  1568. var property = DatabaseSchema.Property(type, columnname);
  1569. // LogStop("DatabaseSchema.Property");
  1570. if (property != null && property is CustomProperty)
  1571. {
  1572. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1573. }
  1574. else
  1575. {
  1576. var bits = columnname.Split('.');
  1577. if (bits.Length == 1)
  1578. {
  1579. var prop = type.GetProperty(columnname);
  1580. if (prop != null)
  1581. {
  1582. // LogStart();
  1583. // LogStop("GetCustomAttributes(Aggregate)");
  1584. if (prop.GetCustomAttribute<AggregateAttribute>() is AggregateAttribute agg)
  1585. {
  1586. bool internalaggregate = agg.Calculator.GetType().GetInterfaces()
  1587. .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICoreAggregate<,>));
  1588. if (internalaggregate)
  1589. {
  1590. }
  1591. else
  1592. {
  1593. var scols = new Dictionary<string, string> { { agg.Aggregate, GetCalculation(agg, columnname) } };
  1594. var siblings = columns.Where(x => !x.Equals(columnname) && x.Split('.').First().Equals(bits.First()))
  1595. .Select(x => string.Join(".", x.Split('.').Skip(1))).ToList();
  1596. var linkedtype = agg.Source;
  1597. foreach (var sibling in siblings)
  1598. {
  1599. // LogStart();
  1600. var sprop = CoreUtils.GetProperty(type, sibling);
  1601. // LogStop("GetProperty(sibling)");
  1602. // LogStart();
  1603. var sattr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  1604. // LogStop("GetCustomAttributes(Sibling.Aggregate)");
  1605. if (sattr is AggregateAttribute sagg)
  1606. {
  1607. // LogStart();
  1608. scols[sagg.Aggregate] = GetCalculation(sagg, sibling);
  1609. // LogStop("GetCalculation(Sibling)");
  1610. }
  1611. }
  1612. var subcols = Columns.None(linkedtype);
  1613. foreach (var key in agg.Links.Keys)
  1614. subcols.Add(key);
  1615. //subcols.Add(agg.Link);
  1616. foreach (var scol in scols.Keys)
  1617. subcols.Add(scol);
  1618. // LogStart();
  1619. var aggFilter = agg.Filter;
  1620. if(aggFilter is not null)
  1621. {
  1622. var ffs = new List<string>();
  1623. FilterFields(aggFilter, ffs);
  1624. //foreach (var ff in ffs)
  1625. // subcols.Add(ff);
  1626. }
  1627. var linkedtable = string.Format("({0})",
  1628. PrepareSelectNonGeneric(linkedtype, command, newprefix, aggFilter, subcols, null, scols, null, null, false, useparams));
  1629. var alias = tables.Count + 1;
  1630. var link = string.Join(" , ", agg.Links.Keys.Select(x => string.Format("{0}{1}.{2}", prefix, alias, x)));
  1631. var tuple = tables.FirstOrDefault(x =>
  1632. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1633. if (tuple == null)
  1634. {
  1635. var joins = new List<string>();
  1636. foreach (var key in agg.Links.Keys)
  1637. joins.Add(
  1638. string.Format("IFNULL({0}{1}.[{2}],'') = IFNULL({0}1.[{3}],'')", prefix, alias, key, agg.Links[key]));
  1639. var join = string.Format("LEFT OUTER JOIN {0} {1}{2} ON {3}", linkedtable, prefix, alias,
  1640. string.Join(" AND ", joins));
  1641. tuple = new Tuple<string, string, string, string>(linkedtable, prefix + alias.ToString(), join, link);
  1642. //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);
  1643. tables.Add(tuple);
  1644. }
  1645. //if (bits.Last().Equals("ID"))
  1646. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1647. //else
  1648. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, agg.Aggregate);
  1649. //LoadFieldsandTables(command, agg.Type, newprefix, fieldmap, tables, columns, columnname);
  1650. //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);
  1651. //int alias = tables.Count + 1;
  1652. //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), "");
  1653. //tables.Add(tuple);
  1654. //fieldmap[columnname] = String.Format("{0}.[{1}]", tuple.Item2, agg.AggregateProperty);
  1655. }
  1656. }
  1657. else if (prop.GetCustomAttribute<FormulaAttribute>() is FormulaAttribute fnc)
  1658. {
  1659. // var functionmap = new Dictionary<string, string>();
  1660. // CheckColumn(columns, fnc.Value);
  1661. // LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, fnc.Value, useparams);
  1662. // foreach (var column in fnc.Modifiers)
  1663. // {
  1664. // CheckColumn(columns, column);
  1665. // LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, column, useparams);
  1666. // }
  1667. // fieldmap[columnname] = GetFunction(fnc, functionmap, columnname);
  1668. foreach (var field in fnc.Modifiers.Prepend(fnc.Value))
  1669. {
  1670. CheckColumn(columns, field);
  1671. LoadFieldsandTables(command, type, prefix, fieldmap, tables, columns, field, useparams);
  1672. }
  1673. fieldmap[columnname] = GetFunction(fnc, fieldmap, columnname);
  1674. }
  1675. else if(prop.GetCustomAttribute<ConditionAttribute>() is ConditionAttribute cnd)
  1676. {
  1677. var cndmap = new Dictionary<string, string>();
  1678. // LogStart();
  1679. CheckColumn(columns, cnd.Left);
  1680. // LogStop("CheckColumn(Left)");
  1681. // LogStart();
  1682. CheckColumn(columns, cnd.Right);
  1683. // LogStop("CheckColumn(Right)");
  1684. // LogStart();
  1685. CheckColumn(columns, cnd.True);
  1686. // LogStop("CheckColumn(True)");
  1687. // LogStart();
  1688. CheckColumn(columns, cnd.False);
  1689. // LogStop("CheckColumn(False)");
  1690. //// LogStart();
  1691. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Left, useparams);
  1692. //// LogStop("LoadFieldsAndTables(Left)");
  1693. //// LogStart();
  1694. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Right, useparams);
  1695. //// LogStop("LoadFieldsAndTables(Right)");
  1696. //// LogStart();
  1697. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.True, useparams);
  1698. //// LogStop("LoadFieldsAndTables(True)");
  1699. //// LogStart();
  1700. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.False, useparams);
  1701. //// LogStop("LoadFieldsAndTables(False)");
  1702. // LogStart();
  1703. fieldmap[columnname] = GetCondition(cnd, cndmap, columnname);
  1704. // LogStop("GetCondition");
  1705. }
  1706. else
  1707. {
  1708. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1709. }
  1710. }
  1711. else
  1712. {
  1713. //IProperty customprop = DataModel.Property(type, columnname);
  1714. //if (customprop != null)
  1715. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1716. //else
  1717. fieldmap[columnname] = columnname;
  1718. }
  1719. }
  1720. else
  1721. {
  1722. var prop = type.GetProperty(bits.First());
  1723. if (prop != null)
  1724. {
  1725. var combinecount = 1;
  1726. while (prop.PropertyType.HasInterface<IEnclosedEntity>())
  1727. {
  1728. combinecount++;
  1729. prop = CoreUtils.GetProperty(type, string.Join(".", bits.Take(combinecount)));
  1730. }
  1731. var entityLinkInterface = prop.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>));
  1732. if (entityLinkInterface is not null)
  1733. {
  1734. var linkedType = entityLinkInterface.GenericTypeArguments[0];
  1735. var enclosingProperty = string.Join('.', bits.Take(combinecount)) + ".";
  1736. var remoteProperty = string.Join('.', bits.Skip(combinecount));
  1737. var remote = linkedType.GetProperty(remoteProperty);
  1738. // Are there any other properties for this link? These will form the columns for our subquery
  1739. var siblings = columns.Where(x => x.StartsWith(enclosingProperty))
  1740. .Select(x => x[enclosingProperty.Length..]).ToList();
  1741. if (remote != null && !siblings.Contains(remote.Name))
  1742. siblings.Add(remote.Name);
  1743. if(prop.GetCustomAttribute<ChildEntityAttribute>() is ChildEntityAttribute child)
  1744. {
  1745. var parent = child.Calculator.ParentColumn;
  1746. if (!siblings.Contains(nameof(Entity.ID)))
  1747. siblings.Insert(0, nameof(Entity.ID));
  1748. if (!siblings.Contains(parent))
  1749. siblings.Add(parent);
  1750. var subcols = Columns.None(linkedType).Add(siblings);
  1751. var subPrefix = (char)(newprefix + 1);
  1752. var innerSQL = string.Format("({0})",
  1753. PrepareSelectNonGeneric(
  1754. linkedType,
  1755. command,
  1756. subPrefix,
  1757. child.Calculator.Filter,
  1758. subcols,
  1759. child.Calculator.Sort,
  1760. null,
  1761. null,
  1762. null,
  1763. false,
  1764. useparams));
  1765. var linkedTable = $"(SELECT {string.Join(", ", siblings.Select(x => $"{newprefix}1.[{x}] as [{x}]"))}"
  1766. + $" FROM {innerSQL} {newprefix}1"
  1767. + $" GROUP BY [{parent}])";
  1768. var link = string.Format("{0}.ID", prop.Name);
  1769. var tuple = tables.FirstOrDefault(x =>
  1770. x.Item1.Equals(linkedTable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1771. if (tuple is null)
  1772. {
  1773. var alias = tables.Count + 1;
  1774. tuple = new Tuple<string, string, string, string>(
  1775. linkedTable,
  1776. prefix + alias.ToString(),
  1777. string.Format(
  1778. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[{3}] = {1}1.[ID]",
  1779. linkedTable,
  1780. prefix,
  1781. alias,
  1782. parent
  1783. ),
  1784. link
  1785. );
  1786. tables.Add(tuple);
  1787. }
  1788. //if (bits.Last().Equals("ID"))
  1789. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1790. //else
  1791. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  1792. foreach (var sibling in siblings)
  1793. {
  1794. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  1795. if (!subcol.Equals(columnname))
  1796. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  1797. }
  1798. }
  1799. else
  1800. {
  1801. if (siblings.Count.Equals(1) && siblings.First().Equals("ID"))
  1802. {
  1803. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1804. }
  1805. else
  1806. {
  1807. if (!siblings.Contains("ID"))
  1808. siblings.Insert(0, "ID");
  1809. var subcols = Columns.None(linkedType).Add(siblings);
  1810. var linkedtable = string.Format("({0})",
  1811. PrepareSelectNonGeneric(linkedType, command, newprefix, null, subcols, null, null, null, null, false, useparams));
  1812. var link = string.Format("{0}.ID", prop.Name);
  1813. var tuple = tables.FirstOrDefault(x =>
  1814. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1815. if (tuple == null)
  1816. {
  1817. var alias = tables.Count + 1;
  1818. tuple = new Tuple<string, string, string, string>(
  1819. linkedtable,
  1820. prefix + alias.ToString(),
  1821. string.Format(
  1822. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[ID] = {1}1.[{3}.ID]",
  1823. linkedtable,
  1824. prefix,
  1825. alias,
  1826. string.Join(".", bits.Take(combinecount)) //prop.Name
  1827. ),
  1828. link
  1829. );
  1830. tables.Add(tuple);
  1831. }
  1832. //if (bits.Last().Equals("ID"))
  1833. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1834. //else
  1835. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  1836. foreach (var sibling in siblings)
  1837. {
  1838. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  1839. if (!subcol.Equals(columnname))
  1840. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  1841. }
  1842. }
  1843. }
  1844. }
  1845. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  1846. {
  1847. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1848. }
  1849. else
  1850. {
  1851. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1852. }
  1853. }
  1854. else
  1855. {
  1856. fieldmap[columnname] = columnname;
  1857. }
  1858. }
  1859. }
  1860. }
  1861. private static void CheckColumn(List<string> columns, string column)
  1862. {
  1863. if (!columns.Contains(column))
  1864. columns.Add(column);
  1865. }
  1866. public void FilterFields(IFilter? filter, List<string> fields)
  1867. {
  1868. if (filter == null)
  1869. return;
  1870. if (filter.Operator != Operator.None && filter.Operator != Operator.All)
  1871. {
  1872. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(filter.Expression), ".");
  1873. if (!fields.Contains(exp))
  1874. fields.Add(exp);
  1875. }
  1876. foreach (var and in filter.Ands)
  1877. FilterFields(and, fields);
  1878. foreach (var or in filter.Ors)
  1879. FilterFields(or, fields);
  1880. }
  1881. public void SortFields(ISortOrder? sort, List<string> fields)
  1882. {
  1883. if (sort == null)
  1884. return;
  1885. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(sort.Expression), ".");
  1886. if (!fields.Contains(exp))
  1887. fields.Add(exp);
  1888. foreach (var then in sort.Thens)
  1889. SortFields(then, fields);
  1890. }
  1891. public enum AggregateType
  1892. {
  1893. None,
  1894. Sum,
  1895. Count
  1896. }
  1897. public string PrepareSelectNonGeneric(Type T, SQLiteCommand command, char prefix,
  1898. IFilter? filter, IColumns? columns, ISortOrder? sort,
  1899. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, CoreRange? range, bool distinct, bool useparams)
  1900. {
  1901. var fieldmap = new Dictionary<string, string>();
  1902. var cols = CoreUtils.GetColumns(T, columns);
  1903. var fields = new List<string>();
  1904. fields.AddRange(cols.ColumnNames());
  1905. FilterFields(filter, fields);
  1906. SortFields(sort, fields);
  1907. var tables = new List<Tuple<string, string, string, string>>();
  1908. var condition = "";
  1909. var sortorder = "";
  1910. var entityName = T.EntityName().Split('.').Last();
  1911. tables.Add(new Tuple<string, string, string, string>(
  1912. entityName,
  1913. $"{prefix}1",
  1914. $"{entityName} {prefix}1",
  1915. "")
  1916. );
  1917. foreach (var column in cols.ColumnNames())
  1918. LoadFieldsandTables(command, T, prefix, fieldmap, tables, fields, column, useparams);
  1919. var parameters = new Dictionary<string, object>();
  1920. condition = GetFilterClauseNonGeneric(T, command, prefix, filter, tables, fieldmap, fields, useparams);
  1921. sortorder = GetSortClauseNonGeneric(T, command, sort, prefix, tables, fieldmap, fields, useparams);
  1922. var combined = new SortedDictionary<string, string>();
  1923. fields.Clear();
  1924. foreach (var column in cols.ColumnNames())
  1925. if (fieldmap.TryGetValue(column, out string? value))
  1926. {
  1927. if (aggregates != null && aggregates.ContainsKey(column))
  1928. combined[constants != null ? column : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0}({1}) as [{2}]", aggregates[column], value, column);
  1929. else
  1930. combined[constants != null ? column : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0} as [{1}]", value, column);
  1931. }
  1932. if (constants != null)
  1933. {
  1934. foreach(var (column, value) in constants)
  1935. {
  1936. combined[column] = string.Format("{0} as [{1}]", EscapeValue(value), column);
  1937. }
  1938. }
  1939. var result = new List<string>();
  1940. result.Add("SELECT");
  1941. if (distinct)
  1942. result.Add("DISTINCT");
  1943. result.Add(string.Join(", ", combined.Values));
  1944. result.Add("FROM");
  1945. result.AddRange(tables.Select(x => x.Item3));
  1946. if (range?.Type == CoreRangeType.Database && range.Offset != 0)
  1947. {
  1948. var subColumns = Columns.None(T).Add("ID");
  1949. var subQuery = PrepareSelectNonGeneric(T, command, 'A', filter, subColumns, sort, null, null, CoreRange.Database(range.Offset), false, useparams);
  1950. var idColumn = $"{prefix}1.[ID]";
  1951. var offsetCondition = $"({idColumn} NOT IN ({subQuery}))";
  1952. if (!condition.IsNullOrWhiteSpace())
  1953. {
  1954. condition = $"({offsetCondition} and {condition})";
  1955. }
  1956. else
  1957. {
  1958. condition = offsetCondition;
  1959. }
  1960. }
  1961. if (!string.IsNullOrWhiteSpace(condition))
  1962. {
  1963. result.Add("WHERE");
  1964. result.Add(condition);
  1965. }
  1966. if (!string.IsNullOrWhiteSpace(sortorder))
  1967. {
  1968. result.Add("ORDER BY");
  1969. result.Add(sortorder);
  1970. }
  1971. if (aggregates != null)
  1972. {
  1973. var str = string.Join(", ",
  1974. fieldmap.Where(x => cols.Contains(x.Key) && !aggregates.ContainsKey(x.Key)).Select(f => f.Value));
  1975. if (!string.IsNullOrWhiteSpace(str))
  1976. {
  1977. result.Add("GROUP BY");
  1978. result.Add(str);
  1979. }
  1980. }
  1981. if (range?.Type == CoreRangeType.Database)
  1982. {
  1983. if (range.Limit != int.MaxValue)
  1984. result.Add($"LIMIT {range.Limit}");
  1985. //if (range.Offset != 0)
  1986. // result.Add($"OFFSET {range.Offset}");
  1987. }
  1988. return string.Join(" ", result);
  1989. }
  1990. public string PrepareSelect<T>(SQLiteCommand command, char prefix, Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort,
  1991. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, CoreRange? range, bool distinct, bool useparams) where T : Entity
  1992. => PrepareSelectNonGeneric(typeof(T), command, prefix, filter, columns, sort, aggregates, constants, range, distinct, useparams);
  1993. private void PrepareUpsertNonGeneric(Type T, SQLiteCommand command, Entity item)
  1994. {
  1995. command.CommandText = "";
  1996. command.Parameters.Clear();
  1997. if (item.ID == Guid.Empty)
  1998. item.ID = Guid.NewGuid();
  1999. var insert = item.GetValues(true);
  2000. var update = item.GetValues(false);
  2001. var insertfields = new List<string>();
  2002. var insertvalues = new List<string>();
  2003. var updatecommands = new List<string>();
  2004. var iParam = 0;
  2005. foreach (var (key, v) in insert)
  2006. {
  2007. if (v is UserProperties)
  2008. continue;
  2009. var sParam = string.Format("@p{0}", iParam++);
  2010. object? value = null;
  2011. try
  2012. {
  2013. value = Encode(v, v?.GetType());
  2014. }
  2015. catch (Exception e)
  2016. {
  2017. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2018. }
  2019. command.Parameters.AddWithValue(sParam, value);
  2020. insertfields.Add(string.Format("[{0}]", key));
  2021. insertvalues.Add(sParam);
  2022. if (update.ContainsKey(key))
  2023. if (!key.Equals("ID"))
  2024. updatecommands.Add(string.Format("[{0}]={1}", key, sParam));
  2025. }
  2026. var particles = new List<string>
  2027. {
  2028. "INSERT INTO",
  2029. T.EntityName().Split('.').Last(),
  2030. "(",
  2031. string.Join(",", insertfields),
  2032. ")",
  2033. "VALUES",
  2034. "(",
  2035. string.Join(",", insertvalues),
  2036. ")"
  2037. };
  2038. if (updatecommands.Count != 0)
  2039. particles.Add("ON CONFLICT([ID]) DO UPDATE SET " + string.Join(", ", updatecommands));
  2040. else
  2041. particles.Add("ON CONFLICT DO NOTHING");
  2042. command.CommandText = string.Join(" ", particles);
  2043. }
  2044. private void PrepareUpsert<T>(SQLiteCommand command, T item) where T : Entity
  2045. => PrepareUpsertNonGeneric(typeof(T), command, item);
  2046. public void PrepareDelete<T>(SQLiteCommand command, T item) where T : Entity
  2047. {
  2048. command.CommandText = string.Format("DELETE FROM {0} WHERE [ID] = @p0", typeof(T).EntityName().Split('.').Last());
  2049. command.Parameters.Clear();
  2050. command.Parameters.AddWithValue("@p0", Encode(item.ID, typeof(Guid)));
  2051. }
  2052. #endregion
  2053. #region CRUD Operations
  2054. public static object[] GetValues(IDataReader reader, int count)
  2055. {
  2056. var result = new object[count];
  2057. reader.GetValues(result);
  2058. return result;
  2059. }
  2060. #region Query
  2061. public IEnumerable<object[]> List<T>(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, CoreRange? range = null) where T : Entity, new()
  2062. {
  2063. //Dictionary<String, TimeSpan> stopwatch = new Dictionary<string, TimeSpan>();
  2064. //Stopwatch sw = new Stopwatch();
  2065. //sw.Start();
  2066. var cols = CoreUtils.GetColumns(columns);
  2067. //stopwatch["GetColumns"] = new TimeSpan(sw.ElapsedTicks);
  2068. //sw.Restart();
  2069. var result = new List<object[]>();
  2070. //stopwatch["MakeResult"] = new TimeSpan(sw.ElapsedTicks);
  2071. //sw.Restart();
  2072. using (var access = GetReadAccess())
  2073. {
  2074. using (var command = access.CreateCommand())
  2075. {
  2076. var sortorder = sort ?? LookupFactory.DefineSort<T>();
  2077. command.CommandText = "";
  2078. command.Parameters.Clear();
  2079. command.CommandText = PrepareSelect(command, 'A', filter, cols, sortorder, null, null, range, false, true) + ";";
  2080. using (var reader = command.ExecuteReader())
  2081. {
  2082. foreach (var row in reader)
  2083. {
  2084. var values = GetValues(reader, cols.Count);
  2085. result.Add(values);
  2086. }
  2087. reader.Close();
  2088. }
  2089. }
  2090. }
  2091. return result;
  2092. }
  2093. private CoreTable DoQueryNonGeneric(Type T, IFilter? filter = null, IColumns? columns = null, ISortOrder? sort = null, CoreRange? range = null, bool log = false, bool distinct = false)
  2094. {
  2095. var start = DateTime.Now;
  2096. //LogReset();
  2097. //LogStart();
  2098. //LogStop("GetColumns");
  2099. var cols = CoreUtils.GetColumns(T, columns);
  2100. var blobColumns = Columns.None(T);
  2101. foreach(var column in cols)
  2102. {
  2103. var prop = DatabaseSchema.Property(T, column.Property);
  2104. if (prop is not null && prop.HasAttribute<ExternalStorageAttribute>())
  2105. {
  2106. blobColumns.Add(column);
  2107. }
  2108. }
  2109. if(blobColumns.Count > 0)
  2110. {
  2111. cols.Add("ID");
  2112. }
  2113. var result = new CoreTable(T.EntityName());
  2114. if (range?.Type == CoreRangeType.Paged)
  2115. result.Offset = range.Offset;
  2116. foreach (var col in cols)
  2117. result.Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.Type });
  2118. //LogStop("MakeTable");
  2119. using (var access = GetReadAccess())
  2120. {
  2121. using (var command = access.CreateCommand())
  2122. {
  2123. var sortorder = sort ?? LookupFactory.DefineSort(T);
  2124. command.CommandText = "";
  2125. command.Parameters.Clear();
  2126. //LogStart();
  2127. var sql = PrepareSelectNonGeneric(T, command, 'A', filter, cols, sortorder, null, null, range, distinct, true) + ";";
  2128. command.CommandText = sql;
  2129. try
  2130. {
  2131. using (var reader = command.ExecuteReader())
  2132. {
  2133. if (reader.HasRows)
  2134. {
  2135. var rows = new List<CoreRow>();
  2136. int iRow = 0;
  2137. while (reader.Read())
  2138. {
  2139. // casting to long here to prevent integer overflows
  2140. bool exclude = range?.Type == CoreRangeType.Paged &&
  2141. ((iRow < range.Offset) || (iRow >= ((long)range.Offset + (long)range.Limit)));
  2142. if (!exclude)
  2143. {
  2144. var row = result.NewRow();
  2145. for (var i = 0; i < reader.FieldCount; i++)
  2146. try
  2147. {
  2148. var type = result.Columns[i].DataType;
  2149. if (reader.IsDBNull(i))
  2150. {
  2151. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2152. }
  2153. else if (type.IsEnum)
  2154. {
  2155. ReadAndDecodeValue(result, reader, row, i);
  2156. }
  2157. else if (type == typeof(byte))
  2158. {
  2159. row.Values.Add(reader.GetByte(i));
  2160. }
  2161. else if (type == typeof(byte[]))
  2162. {
  2163. ReadAndDecodeValue(result, reader, row, i);
  2164. }
  2165. else if (type == typeof(bool))
  2166. {
  2167. ReadAndDecodeValue(result, reader, row, i);
  2168. }
  2169. else if (type == typeof(short))
  2170. {
  2171. row.Values.Add(reader.GetInt16(i));
  2172. }
  2173. else if (type == typeof(int))
  2174. {
  2175. row.Values.Add(reader.GetInt32(i));
  2176. }
  2177. else if (type == typeof(long))
  2178. {
  2179. row.Values.Add(reader.GetInt64(i));
  2180. }
  2181. else if (type == typeof(float))
  2182. {
  2183. row.Values.Add(reader.GetFloat(i));
  2184. }
  2185. else if (type == typeof(double))
  2186. {
  2187. row.Values.Add(reader.GetDouble(i));
  2188. }
  2189. else if (type == typeof(decimal))
  2190. {
  2191. row.Values.Add(reader.GetDecimal(i));
  2192. }
  2193. else if (type == typeof(string))
  2194. {
  2195. var value = reader.GetString(i);
  2196. row.Values.Add(value != null ? value : "");
  2197. }
  2198. else if (type == typeof(DateTime))
  2199. {
  2200. ReadAndDecodeValue(result, reader, row, i);
  2201. }
  2202. else if (type == typeof(TimeSpan))
  2203. {
  2204. ReadAndDecodeValue(result, reader, row, i);
  2205. }
  2206. else if (type == typeof(Guid))
  2207. {
  2208. row.Values.Add(reader.GetGuid(i));
  2209. }
  2210. else
  2211. {
  2212. ReadAndDecodeValue(result, reader, row, i);
  2213. }
  2214. }
  2215. catch (Exception e)
  2216. {
  2217. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2218. }
  2219. result.Rows.Add(row);
  2220. }
  2221. iRow++;
  2222. }
  2223. result.TotalRecords = iRow;
  2224. }
  2225. reader.Close();
  2226. }
  2227. }
  2228. catch (Exception e)
  2229. {
  2230. Logger.Error($"{e.Message}: {sql}");
  2231. }
  2232. //LogStop("ReadData");
  2233. //LogPrint(String.Format("Query{0}", typeof(T).Name));
  2234. }
  2235. }
  2236. foreach(var column in blobColumns.ColumnNames())
  2237. {
  2238. foreach(var row in result.Rows)
  2239. {
  2240. var id = row.Get<Guid>("ID");
  2241. var data = GetExternalData(T, column, id);
  2242. if(data is not null)
  2243. {
  2244. row.Set<byte[]>(column, data);
  2245. }
  2246. }
  2247. }
  2248. if (log)
  2249. {
  2250. var duration = DateTime.Now - start;
  2251. Logger.Send(LogType.Information, "",
  2252. string.Format("SQLite::Query<{0}>({1} cols) returns {2} rows in {3}ms", T.Name, cols.Count, result.Rows.Count,
  2253. duration.TotalMilliseconds));
  2254. }
  2255. return result;
  2256. }
  2257. private CoreTable DoQuery<T>(Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort, CoreRange? range, bool log, bool distinct)
  2258. where T : Entity, new() => DoQueryNonGeneric(typeof(T), filter, columns, sort, range, log, distinct);
  2259. public CoreTable Query(Type type, IFilter? filter, IColumns? columns, ISortOrder? sort, CoreRange? range, bool log, bool distinct)
  2260. => DoQueryNonGeneric(type, filter, columns, sort, range, log, distinct);
  2261. 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)
  2262. where T : Entity, new()
  2263. {
  2264. return DoQuery(filter, columns, sort, range, log, distinct);
  2265. }
  2266. [Obsolete]
  2267. public CoreTable QueryDeleted<T>(Deletion deletion, Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, CoreRange? range = null, bool log = false)
  2268. where T : Entity, new()
  2269. {
  2270. if (filter != null)
  2271. filter.And(x => x.Deleted).IsEqualTo(deletion.ID);
  2272. else
  2273. filter = new Filter<T>(x => x.Deleted).IsEqualTo(deletion.ID);
  2274. return DoQuery(filter, columns, sort, range, false, false);
  2275. }
  2276. private void ReadAndDecodeValue(CoreTable result, SQLiteDataReader reader, CoreRow row, int i)
  2277. {
  2278. var value = reader.GetValue(i);
  2279. var decoded = Decode(value, result.Columns[i].DataType);
  2280. row.Values.Add(decoded);
  2281. }
  2282. public T[] Load<T>(Filter<T>? filter = null, SortOrder<T>? sort = null, CoreRange? range = null) where T : Entity, new()
  2283. {
  2284. var result = new List<T>();
  2285. var cols = CoreUtils.GetColumns<T>(null);
  2286. using (var access = GetReadAccess())
  2287. {
  2288. using (var command = access.CreateCommand())
  2289. {
  2290. try
  2291. {
  2292. command.CommandText = "";
  2293. command.Parameters.Clear();
  2294. command.CommandText = PrepareSelect(command, 'A', filter, cols, sort, null, null, range, false, true) + ";";
  2295. using (var reader = command.ExecuteReader())
  2296. {
  2297. if (reader.HasRows)
  2298. while (reader.Read())
  2299. {
  2300. var entity = new T();
  2301. entity.SetObserving(false);
  2302. for (var i = 0; i < reader.FieldCount; i++)
  2303. {
  2304. object value;
  2305. if (cols[i].Type == typeof(long) && !reader.IsDBNull(i))
  2306. value = reader.GetInt64(i);
  2307. else
  2308. value = reader.GetValue(i);
  2309. try
  2310. {
  2311. var decoded = Decode(value, cols[i].Type);
  2312. CoreUtils.SetPropertyValue(entity, cols[i].Property, decoded);
  2313. }
  2314. catch (Exception e)
  2315. {
  2316. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2317. }
  2318. }
  2319. entity.SetObserving(true);
  2320. result.Add(entity);
  2321. }
  2322. reader.Close();
  2323. }
  2324. }
  2325. catch (Exception e)
  2326. {
  2327. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2328. }
  2329. }
  2330. }
  2331. return result.ToArray();
  2332. }
  2333. #endregion
  2334. #region Save
  2335. private static readonly Dictionary<Type, IProperty[]> _externalProperties = new Dictionary<Type, IProperty[]>();
  2336. private static IProperty[] GetExternalProperties(Type T)
  2337. {
  2338. if(!_externalProperties.TryGetValue(T, out var properties))
  2339. {
  2340. properties = DatabaseSchema.Properties(T).Where(x => x.HasAttribute<ExternalStorageAttribute>()).ToArray();
  2341. _externalProperties.Add(T, properties);
  2342. }
  2343. return properties;
  2344. }
  2345. private void OnSaveNonGeneric(Type T, Entity entity)
  2346. {
  2347. var props = GetExternalProperties(T);
  2348. List<(IProperty, byte[])>? data = null;
  2349. if (props.Any())
  2350. {
  2351. data = new List<(IProperty, byte[])>();
  2352. foreach(var prop in props)
  2353. {
  2354. var value = prop.Getter()(entity) as byte[];
  2355. if(value is not null && value.Length > 0)
  2356. {
  2357. data.Add(new(prop, value));
  2358. prop.Setter()(entity, Array.Empty<byte>());
  2359. }
  2360. }
  2361. }
  2362. using var access = GetWriteAccess();
  2363. using var command = access.CreateCommand();
  2364. PrepareUpsertNonGeneric(T, command, entity);
  2365. command.ExecuteNonQuery();
  2366. if(data is not null)
  2367. {
  2368. foreach(var (prop, value) in data)
  2369. {
  2370. SaveExternalData(T, prop.Name, entity.ID, value);
  2371. prop.Setter()(entity, value);
  2372. }
  2373. }
  2374. }
  2375. private void OnSaveNonGeneric(Type T, IEnumerable<Entity> entities)
  2376. {
  2377. // Casting to IList so that we can use it multiple times.
  2378. entities = entities.AsIList();
  2379. if (!entities.Any())
  2380. return;
  2381. var props = GetExternalProperties(T);
  2382. List<(IProperty, List<(Entity, byte[])>)>? data = null;
  2383. if (props.Any())
  2384. {
  2385. data = new List<(IProperty, List<(Entity, byte[])>)>();
  2386. foreach(var prop in props)
  2387. {
  2388. var lst = new List<(Entity, byte[])>();
  2389. foreach(var entity in entities)
  2390. {
  2391. var value = prop.Getter()(entity) as byte[];
  2392. if(value is not null && value.Length > 0)
  2393. {
  2394. lst.Add((entity, value));
  2395. prop.Setter()(entity, Array.Empty<byte>());
  2396. }
  2397. }
  2398. data.Add(new(prop, lst));
  2399. }
  2400. }
  2401. using var access = GetWriteAccess();
  2402. using var transaction = access.BeginTransaction();
  2403. try
  2404. {
  2405. using var command = access.CreateCommand();
  2406. foreach (var entity in entities)
  2407. {
  2408. PrepareUpsertNonGeneric(T, command, entity);
  2409. command.ExecuteNonQuery();
  2410. }
  2411. transaction.Commit();
  2412. if(data is not null)
  2413. {
  2414. foreach(var (property, list) in data)
  2415. {
  2416. foreach(var (entity, value) in list)
  2417. {
  2418. SaveExternalData(T, property.Name, entity.ID, value);
  2419. property.Setter()(entity, value);
  2420. }
  2421. }
  2422. }
  2423. }
  2424. catch (Exception)
  2425. {
  2426. transaction.Rollback();
  2427. throw;
  2428. }
  2429. }
  2430. private void OnSave<T>(T entity) where T : Entity
  2431. => OnSaveNonGeneric(typeof(T), entity);
  2432. public static bool CanSave(Type T)
  2433. {
  2434. if (DbFactory.IsReadOnly)
  2435. {
  2436. if (T.IsAssignableTo(typeof(License)) || T.IsAssignableTo(typeof(UserTracking)))
  2437. return true;
  2438. DbFactory.LogReadOnly();
  2439. throw new DbLockedException();
  2440. }
  2441. return true;
  2442. }
  2443. public static bool CanSave<T>() => CanSave(typeof(T));
  2444. public void Save(Type type, Entity entity)
  2445. {
  2446. if (!CanSave(type))
  2447. {
  2448. return;
  2449. }
  2450. OnSaveNonGeneric(type, entity);
  2451. }
  2452. public void Save(Type type, IEnumerable<Entity> entities)
  2453. {
  2454. if (!CanSave(type))
  2455. {
  2456. return;
  2457. }
  2458. OnSaveNonGeneric(type, entities);
  2459. }
  2460. public void Save<T>(IEnumerable<T> entities) where T : Entity => Save(typeof(T), entities);
  2461. public void Save<T>(T entity) where T : Entity => Save(typeof(T), entity);
  2462. #endregion
  2463. #region Delete
  2464. public void Purge<T>(T entity) where T : Entity
  2465. {
  2466. if (!CanSave<T>()) return;
  2467. using var access = GetWriteAccess();
  2468. using var command = access.CreateCommand();
  2469. PrepareDelete(command, entity);
  2470. var rows = command.ExecuteNonQuery();
  2471. }
  2472. public void Purge<T>(IEnumerable<T> entities) where T : Entity
  2473. {
  2474. if (!CanSave<T>()) return;
  2475. // Casting to IList so that we can use it multiple times.
  2476. entities = entities.AsIList();
  2477. if (!entities.Any())
  2478. return;
  2479. using var access = GetWriteAccess();
  2480. using var transaction = access.BeginTransaction();
  2481. try
  2482. {
  2483. using (var command = access.CreateCommand())
  2484. {
  2485. foreach (var entity in entities)
  2486. {
  2487. PrepareDelete(command, entity);
  2488. var rows = command.ExecuteNonQuery();
  2489. }
  2490. }
  2491. transaction.Commit();
  2492. }
  2493. catch (Exception)
  2494. {
  2495. transaction.Rollback();
  2496. throw;
  2497. }
  2498. }
  2499. private const int deleteBatchSize = 100;
  2500. private readonly MethodInfo _deleteEntitiesMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2501. .Single(x => x.Name == nameof(DeleteEntity) && x.IsGenericMethod);
  2502. private void DeleteEntity<T>(Guid[] parentIDs, List<string> parentFields, DeletionData deletionData) where T : Entity, new()
  2503. {
  2504. var columns = DeletionData.DeletionColumns<T>();
  2505. var entityIDs = new List<Guid>();
  2506. for (int i = 0; i < parentIDs.Length; i += deleteBatchSize)
  2507. {
  2508. var items = new ArraySegment<Guid>(parentIDs, i, Math.Min(deleteBatchSize, parentIDs.Length - i));
  2509. var ids = items.ToArray();
  2510. var filter = new Filters<T>();
  2511. foreach(var field in parentFields)
  2512. {
  2513. filter.Add(new Filter<T>(field).InList(ids));
  2514. }
  2515. var entities = Query(filter.CombineOr(), columns);
  2516. foreach (var row in entities.Rows)
  2517. {
  2518. deletionData.DeleteEntity<T>(row);
  2519. entityIDs.Add(row.Get<T, Guid>(x => x.ID));
  2520. }
  2521. }
  2522. CascadeDelete(typeof(T), entityIDs.ToArray(), deletionData);
  2523. }
  2524. private void DeleteEntity(Type T, Guid[] parentIDs, List<string> parentFields, DeletionData deletionData)
  2525. {
  2526. _deleteEntitiesMethod.MakeGenericMethod(T).Invoke(this, new object?[] { parentIDs, parentFields, deletionData });
  2527. }
  2528. private readonly MethodInfo _setNullEntityMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2529. .Single(x => x.Name == nameof(SetNullEntity) && x.IsGenericMethod);
  2530. private void SetNullEntity<T>(List<string> properties, Guid[] parentIDs, DeletionData deletionData) where T : Entity, new()
  2531. {
  2532. foreach(var property in properties)
  2533. {
  2534. var columns = Columns.None<T>().Add(x => x.ID).Add(property);
  2535. for(int i = 0; i < parentIDs.Length; i += deleteBatchSize)
  2536. {
  2537. var items = new ArraySegment<Guid>(parentIDs, i, Math.Min(deleteBatchSize, parentIDs.Length - i));
  2538. var entities = Query(new Filter<T>(property).InList(items.ToArray()), columns);
  2539. foreach (var row in entities.Rows)
  2540. {
  2541. deletionData.SetNullEntity<T>(row.Get<T, Guid>(x => x.ID), property, row.Get<Guid>(property));
  2542. }
  2543. }
  2544. }
  2545. }
  2546. private void SetNullEntity(Type T, List<string> properties, Guid[] parentIDs, DeletionData deletionData)
  2547. {
  2548. _setNullEntityMethod.MakeGenericMethod(T).Invoke(this, new object?[] { properties, parentIDs, deletionData });
  2549. }
  2550. private void CascadeDelete(Type type, Guid[] parentIDs, DeletionData deletionData)
  2551. {
  2552. if(parentIDs.Length == 0)
  2553. {
  2554. return;
  2555. }
  2556. if (Factory._cascades.TryGetValue(type, out var cascades))
  2557. {
  2558. foreach (var cascade in cascades)
  2559. {
  2560. DeleteEntity(cascade.Item1, parentIDs, cascade.Item2, deletionData);
  2561. }
  2562. }
  2563. if(Factory._setNulls.TryGetValue(type, out var setNulls))
  2564. {
  2565. foreach(var setNull in setNulls)
  2566. {
  2567. SetNullEntity(setNull.Item1, setNull.Item2, parentIDs, deletionData);
  2568. }
  2569. }
  2570. }
  2571. public void Delete<T>(T entity, string userID) where T : Entity, new()
  2572. {
  2573. if (!CanSave<T>())
  2574. {
  2575. return;
  2576. }
  2577. if (typeof(T).HasAttribute<UnrecoverableAttribute>())
  2578. {
  2579. Purge(entity);
  2580. var props = GetExternalProperties(typeof(T));
  2581. foreach(var prop in props)
  2582. {
  2583. DeleteExternalData(typeof(T), prop.Name, entity.ID);
  2584. }
  2585. }
  2586. else
  2587. {
  2588. entity = DoQuery(
  2589. new Filter<T>(x => x.ID).IsEqualTo(entity.ID),
  2590. DeletionData.DeletionColumns<T>(),
  2591. null,
  2592. null,
  2593. false,
  2594. false
  2595. ).Rows.First().ToObject<T>();
  2596. var deletionData = new DeletionData();
  2597. deletionData.DeleteEntity(entity);
  2598. CascadeDelete(typeof(T), new Guid[] { entity.ID }, deletionData);
  2599. var tableName = typeof(T).Name;
  2600. var deletion = new Deletion()
  2601. {
  2602. DeletionDate = DateTime.Now,
  2603. HeadTable = tableName,
  2604. Description = entity.ToString() ?? "",
  2605. DeletedBy = userID,
  2606. Data = Serialization.Serialize(deletionData)
  2607. };
  2608. OnSave(deletion);
  2609. Purge(entity);
  2610. }
  2611. }
  2612. public void Delete<T>(IEnumerable<T> entities, string userID) where T : Entity, new()
  2613. {
  2614. if (!CanSave<T>())
  2615. {
  2616. return;
  2617. }
  2618. entities = entities.AsIList();
  2619. if (!entities.Any())
  2620. return;
  2621. if (typeof(T).HasAttribute<UnrecoverableAttribute>())
  2622. {
  2623. Purge(entities);
  2624. var props = GetExternalProperties(typeof(T));
  2625. foreach(var prop in props)
  2626. {
  2627. foreach(var entity in entities)
  2628. {
  2629. DeleteExternalData(typeof(T), prop.Name, entity.ID);
  2630. }
  2631. }
  2632. }
  2633. else
  2634. {
  2635. var ids = entities.Select(x => x.ID).ToArray();
  2636. var entityList = Query(
  2637. new Filter<T>(x => x.ID).InList(ids),
  2638. DeletionData.DeletionColumns<T>()).Rows.Select(x => x.ToObject<T>()).ToList();
  2639. if (!entityList.Any())
  2640. return;
  2641. var deletionData = new DeletionData();
  2642. foreach (var entity in entityList)
  2643. {
  2644. deletionData.DeleteEntity(entity);
  2645. }
  2646. CascadeDelete(typeof(T), ids, deletionData);
  2647. var tableName = typeof(T).Name;
  2648. var deletion = new Deletion()
  2649. {
  2650. DeletionDate = DateTime.Now,
  2651. HeadTable = tableName,
  2652. Description = $"Deleted {entityList.Count} entries",
  2653. DeletedBy = userID,
  2654. Data = Serialization.Serialize(deletionData)
  2655. };
  2656. OnSave(deletion);
  2657. Purge(entities);
  2658. }
  2659. }
  2660. private void AddDeletionType(Type type, List<Type> deletions)
  2661. {
  2662. deletions.Add(type);
  2663. if (!Factory._cascades.TryGetValue(type, out var cascades))
  2664. return;
  2665. foreach (var cascade in cascades)
  2666. {
  2667. AddDeletionType(cascade.Item1, deletions);
  2668. }
  2669. }
  2670. private Dictionary<Type, List<Type>> _allCascades = new();
  2671. private List<Type> GetDeletionTypes(Type type)
  2672. {
  2673. if(_allCascades.TryGetValue(type, out var cascades))
  2674. {
  2675. return cascades;
  2676. }
  2677. var deletionTypes = new List<Type>();
  2678. AddDeletionType(type, deletionTypes);
  2679. _allCascades[type] = deletionTypes;
  2680. return deletionTypes;
  2681. }
  2682. public void Purge(Deletion deletion)
  2683. {
  2684. if (!CanSave<Deletion>())
  2685. {
  2686. return;
  2687. }
  2688. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  2689. if(data is not null)
  2690. {
  2691. foreach(var (entityName, cascade) in data.Cascades)
  2692. {
  2693. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2694. var props = GetExternalProperties(entityType);
  2695. foreach(var prop in props)
  2696. {
  2697. foreach(var entity in cascade.ToObjects(entityType).Cast<Entity>())
  2698. {
  2699. DeleteExternalData(entityType, prop.Name, entity.ID);
  2700. }
  2701. }
  2702. }
  2703. }
  2704. Purge<Deletion>(deletion);
  2705. }
  2706. public void Recover(Deletion deletion)
  2707. {
  2708. if (!CanSave<Deletion>())
  2709. {
  2710. return;
  2711. }
  2712. if (deletion.ID == Guid.Empty)
  2713. {
  2714. Logger.Send(LogType.Error, "", "Empty Deletion ID; Recovery cancelled");
  2715. return;
  2716. }
  2717. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  2718. if (data is null)
  2719. {
  2720. Logger.Send(LogType.Error, "", "Deletion Data deserialisation failed; Recovery cancelled");
  2721. return;
  2722. }
  2723. foreach (var (entityName, setNulls) in data.SetNulls)
  2724. {
  2725. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2726. var saves = new List<Entity>();
  2727. foreach(var setNull in setNulls)
  2728. {
  2729. var row = DoQueryNonGeneric(
  2730. entityType,
  2731. Filter.Create<Entity>(entityType, x => x.ID).IsEqualTo(setNull.EntityID),
  2732. Columns.None(entityType)
  2733. .Add<Entity>(x => x.ID)
  2734. .Add(setNull.Property),
  2735. null,
  2736. CoreRange.Database(1),
  2737. false,
  2738. false
  2739. ).Rows.FirstOrDefault();
  2740. if (row is null) continue;
  2741. var entity = (row.ToObject(entityType) as Entity)!;
  2742. CoreUtils.SetPropertyValue(entity, setNull.Property, setNull.ParentID);
  2743. saves.Add(entity);
  2744. }
  2745. OnSaveNonGeneric(entityType, saves);
  2746. }
  2747. foreach(var (entityName, cascade) in data.Cascades)
  2748. {
  2749. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  2750. OnSaveNonGeneric(entityType, cascade.ToObjects(entityType).Cast<Entity>());
  2751. }
  2752. Purge<Deletion>(deletion);
  2753. }
  2754. public List<Type> GetDeletionTypes(Deletion deletion)
  2755. {
  2756. var entityType = CoreUtils.Entities.First(x => x.Name == deletion.HeadTable);
  2757. return GetDeletionTypes(entityType);
  2758. }
  2759. #endregion
  2760. #endregion
  2761. #region External Data Storage
  2762. private string ExternalDataFolder(Type T, string columnName, string idString)
  2763. {
  2764. return Path.Combine(
  2765. Path.GetDirectoryName(Factory.URL) ?? "",
  2766. $"{Path.GetFileName(Factory.URL)}.data",
  2767. T.Name,
  2768. columnName,
  2769. idString.Substring(0, 2));
  2770. }
  2771. private byte[]? GetExternalData(Type T, string columnName, Guid id)
  2772. {
  2773. var idString = id.ToString();
  2774. var filename = Path.Combine(ExternalDataFolder(T, columnName, idString), idString);
  2775. try
  2776. {
  2777. return File.ReadAllBytes(filename);
  2778. }
  2779. catch(Exception e)
  2780. {
  2781. //Logger.Send(LogType.Error, "", $"Could not load external {T.Name}.{columnName}: {e.Message}");
  2782. return null;
  2783. }
  2784. }
  2785. private void SaveExternalData(Type T, string columnName, Guid id, byte[] data)
  2786. {
  2787. var idString = id.ToString();
  2788. var directory = ExternalDataFolder(T, columnName, idString);
  2789. Directory.CreateDirectory(directory);
  2790. var filename = Path.Combine(directory, idString);
  2791. File.WriteAllBytes(filename, data);
  2792. }
  2793. private void DeleteExternalData(Type T, string columnName, Guid id)
  2794. {
  2795. var idString = id.ToString();
  2796. var directory = ExternalDataFolder(T, columnName, idString);
  2797. Directory.CreateDirectory(directory);
  2798. var filename = Path.Combine(directory, idString);
  2799. if (File.Exists(filename))
  2800. {
  2801. File.Delete(filename);
  2802. }
  2803. }
  2804. #endregion
  2805. }
  2806. }