SQLiteProvider.cs 127 KB

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