SQLiteProvider.cs 137 KB

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