SQLiteProvider.cs 140 KB

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