SQLiteProvider.cs 119 KB

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