SQLiteProvider.cs 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866
  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. if (childprops.Any() && childtype == type)
  550. {
  551. }
  552. foreach (var childprop in childprops)
  553. {
  554. var fieldname = string.Format("[{0}.ID]", childprop.Name);
  555. var attr = childprop.GetCustomAttributes(typeof(EntityRelationshipAttribute), true).FirstOrDefault();
  556. if (attr != null && ((EntityRelationshipAttribute)attr).Action.Equals(DeleteAction.Cascade))
  557. {
  558. fields.Clear();
  559. bDelete = true;
  560. fields.Add(fieldname);
  561. break;
  562. }
  563. fields.Add(fieldname);
  564. //actions[childtype] = String.Format("UPDATE {1} SET [{0}.ID] = NULL WHERE [id] = old.[ID];", tablename)
  565. }
  566. if (fields.Any())
  567. {
  568. if (bDelete)
  569. actions.Add(string.Format("DELETE FROM {0} WHERE {1} = old.ID;", tablename, fields.First()));
  570. else
  571. foreach (var field in fields)
  572. actions.Add(string.Format("UPDATE {0} SET {1} = NULL WHERE {1} = old.ID;", tablename, field));
  573. }
  574. }
  575. if (actions.Any())
  576. result.Add(string.Format("CREATE TRIGGER {0}_BEFOREDELETE BEFORE DELETE ON {0} FOR EACH ROW BEGIN {1} END",
  577. type.EntityName().Split('.').Last(), string.Join(" ", actions)));
  578. return result;
  579. }
  580. public void ForceRecreateViews()
  581. {
  582. var ordered = new List<Type>();
  583. foreach (var type in Types)
  584. LoadType(type, ordered);
  585. var customproperties = Load<CustomProperty>();
  586. var metadata = LoadMetaData();
  587. foreach (var type in ordered)
  588. {
  589. var view = type.GetCustomAttribute<AutoEntity>();
  590. if (view?.Generator != null)
  591. {
  592. var table = type.EntityName().Split('.').Last();
  593. if (!metadata.ContainsKey(table))
  594. {
  595. OnLog?.Invoke(LogType.Information, "Creating Table: " + type.EntityName().Split('.').Last());
  596. using (var access = GetWriteAccess())
  597. {
  598. CreateTable(access, type, true, customproperties);
  599. }
  600. }
  601. else
  602. {
  603. var type_fields = new Dictionary<string, string>();
  604. LoadFields(view.Generator.Definition, type_fields, null, customproperties);
  605. using (var access = GetWriteAccess())
  606. {
  607. RebuildTable(access, type, metadata[table].Item1, type_fields, customproperties);
  608. }
  609. }
  610. }
  611. }
  612. }
  613. private void CreateTable(SQLiteWriteAccessor access, Type type, bool includeconstraints, CustomProperty[] customproperties)
  614. {
  615. var ddl = new List<string>();
  616. AutoEntity view = type.GetCustomAttribute<AutoEntity>();
  617. if (view != null)
  618. {
  619. using (var command = access.CreateCommand())
  620. {
  621. //command.CommandText = String.Format("select name from sqlite_master where type='trigger' and tbl_name='{0}' and sql is not null;", table);
  622. command.CommandText = "select name from sqlite_master where type='table' and name='" + type.EntityName().Split('.').Last() +
  623. "' and sql is not null;";
  624. using (var reader = command.ExecuteReader())
  625. {
  626. if (reader.HasRows)
  627. while (reader.Read())
  628. ExecuteSQL(access,string.Format("DROP VIEW {0}", reader.GetString(0)));
  629. }
  630. }
  631. ddl.Add("CREATE VIEW");
  632. ddl.Add(type.EntityName().Split('.').Last());
  633. ddl.Add("AS");
  634. var union = view.Generator as IAutoEntityUnionGenerator;
  635. if (union != null)
  636. {
  637. var viewfields = new Dictionary<string, string>();
  638. LoadFields(union.Definition, viewfields, null, new CustomProperty[] { });
  639. var fields = viewfields.Keys.Select(x => String.Format("[{0}]", x)).ToList();
  640. if (!fields.Contains("[ID]"))
  641. fields.Add(String.Format("NULL as [ID]"));
  642. if (!fields.Contains("[Deleted]"))
  643. fields.Add(String.Format("NULL as [Deleted]"));
  644. if (!fields.Contains("[Created]"))
  645. fields.Add(String.Format("NULL as [Created]"));
  646. if (!fields.Contains("[CreatedBy]"))
  647. fields.Add(String.Format("NULL as [CreatedBy]"));
  648. if (!fields.Contains("[LastUpdate]"))
  649. fields.Add(String.Format("NULL as [LastUpdate]"));
  650. if (!fields.Contains("[LastUpdateBy]"))
  651. fields.Add(String.Format("NULL as [LastUpdateBy]"));
  652. List<String> queries = new List<String>();
  653. foreach (var entity in union.Entities)
  654. queries.Add(String.Format("SELECT {0} {1} FROM {2} WHERE [Deleted] is NULL",
  655. union.Distinct ? "DISTINCT" : "",
  656. String.Join(", ", fields),
  657. entity.EntityName().Split('.').Last())
  658. );
  659. ddl.Add(String.Join(" UNION ", queries));
  660. }
  661. else
  662. {
  663. var cross = view.Generator as IAutoEntityCrossGenerator;
  664. if (cross != null)
  665. {
  666. String query = String.Format(
  667. "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}]",
  668. cross.Distinct ? "DISTINCT" : "",
  669. cross.LeftEntity(),
  670. cross.LeftProperty(),
  671. cross.LeftMapping(),
  672. cross.RightEntity(),
  673. cross.RightProperty(),
  674. cross.RightMapping(),
  675. cross.LeftLink(),
  676. cross.RightLink()
  677. );
  678. ddl.Add(query);
  679. }
  680. }
  681. ddl.Add(";");
  682. var viewstatement = string.Join(" ", ddl);
  683. }
  684. else
  685. {
  686. ddl.Add("CREATE TABLE");
  687. ddl.Add(type.EntityName().Split('.').Last());
  688. ddl.Add("(");
  689. var fields = new Dictionary<string, string>();
  690. var constraints = new List<string>();
  691. var indexes = new List<string>();
  692. LoadFields(type, fields, null, customproperties);
  693. var defs = new List<string>();
  694. foreach (var key in fields.Keys)
  695. defs.Add(string.Format("[{0}] {1}", key, fields[key]));
  696. if (includeconstraints)
  697. defs.AddRange(constraints);
  698. ddl.Add(string.Join(", ", defs));
  699. ddl.Add(");");
  700. }
  701. var statement = string.Join(" ", ddl);
  702. try
  703. {
  704. ExecuteSQL(access, statement);
  705. }
  706. catch (Exception e)
  707. {
  708. OnLog?.Invoke(LogType.Error, "Unable to Create Table: " + e.Message);
  709. throw e;
  710. }
  711. }
  712. private void RebuildTable(SQLiteWriteAccessor access, Type type, Dictionary<string, string> table_fields,
  713. Dictionary<string, string> type_fields,
  714. CustomProperty[] customproperties)
  715. {
  716. var table = type.EntityName().Split('.').Last();
  717. if (type.GetCustomAttribute<AutoEntity>() != null)
  718. {
  719. OnLog?.Invoke(LogType.Information, "Recreating View: " + table);
  720. try
  721. {
  722. String drop = "";
  723. using (var command = access.CreateCommand())
  724. {
  725. command.CommandText = "select type from sqlite_master where name='" + table + "' and sql is not null;";
  726. using (var reader = command.ExecuteReader())
  727. {
  728. if (reader.HasRows)
  729. while (reader.Read())
  730. drop = reader.GetString(0).ToUpper();
  731. }
  732. }
  733. if (!String.IsNullOrWhiteSpace(drop))
  734. ExecuteSQL(access, string.Format("DROP {0} {1};", drop, table));
  735. CreateTable(access, type, true, customproperties);
  736. }
  737. catch (Exception e)
  738. {
  739. OnLog?.Invoke(LogType.Error, string.Format("RebuildTable({0}) [VIEW] failed: {1}\n{2}", table, e.Message, e.StackTrace));
  740. throw e;
  741. }
  742. }
  743. else
  744. {
  745. OnLog?.Invoke(LogType.Information, "Rebuilding Table: " + table);
  746. try
  747. {
  748. ExecuteSQL(access, "PRAGMA foreign_keys = off;");
  749. using (var transaction = access.Connection.BeginTransaction())
  750. {
  751. var drops = new List<string>();
  752. using (var command = access.CreateCommand())
  753. {
  754. //command.CommandText = String.Format("select name from sqlite_master where type='trigger' and tbl_name='{0}' and sql is not null;", table);
  755. command.CommandText = "select name from sqlite_master where type='view' and sql is not null;";
  756. using (var reader = command.ExecuteReader())
  757. {
  758. if (reader.HasRows)
  759. while (reader.Read())
  760. drops.Add(string.Format("DROP VIEW {0}", reader.GetString(0)));
  761. }
  762. //command.CommandText = String.Format("select name from sqlite_master where type='trigger' and tbl_name='{0}' and sql is not null;", table);
  763. command.CommandText = "select name from sqlite_master where type='trigger' and sql is not null;";
  764. using (var reader = command.ExecuteReader())
  765. {
  766. if (reader.HasRows)
  767. while (reader.Read())
  768. drops.Add(string.Format("DROP TRIGGER {0}", reader.GetString(0)));
  769. }
  770. command.CommandText = string.Format(
  771. "select name from sqlite_master where type='index' and tbl_name='{0}' and sql is not null;",
  772. table);
  773. using (var reader = command.ExecuteReader())
  774. {
  775. if (reader.HasRows)
  776. while (reader.Read())
  777. drops.Add(string.Format("DROP INDEX {0}", reader.GetString(0)));
  778. }
  779. }
  780. foreach (var drop in drops)
  781. ExecuteSQL(access, drop);
  782. ExecuteSQL(access, string.Format("ALTER TABLE {0} RENAME TO _{0}_old;", table));
  783. CreateTable(access, type, true, customproperties);
  784. var fields = new List<string>();
  785. foreach (var field in type_fields.Keys)
  786. if (table_fields.ContainsKey(field))
  787. fields.Add("[" + field + "]");
  788. ExecuteSQL(access, string.Format("INSERT INTO {0} ({1}) SELECT {1} FROM _{0}_old;", table, string.Join(", ", fields)));
  789. ExecuteSQL(access, string.Format("DROP TABLE _{0}_old;", table));
  790. transaction.Commit();
  791. }
  792. ExecuteSQL(access, "PRAGMA foreign_keys = on;");
  793. }
  794. catch (Exception e)
  795. {
  796. OnLog?.Invoke(LogType.Error, string.Format("RebuildTable({0}) [TABLE] failed: {1}\n{2}", table, e.Message, e.StackTrace));
  797. throw e;
  798. }
  799. }
  800. }
  801. private void CheckFields(SQLiteWriteAccessor access, Type type, Dictionary<string, string> current_fields, CustomProperty[] customproperties)
  802. {
  803. var type_fields = new Dictionary<string, string>();
  804. var view = type.GetCustomAttribute<AutoEntity>();
  805. if ((view != null) && (view.Generator != null))
  806. LoadFields(view.Generator.Definition, type_fields, null, customproperties);
  807. else
  808. LoadFields(type, type_fields, null, customproperties);
  809. var bRebuild = false;
  810. foreach (var field in type_fields.Keys)
  811. {
  812. try
  813. {
  814. Type tType = null;
  815. var cprop = customproperties.FirstOrDefault(x => string.Equals(x.Name, field));
  816. if (cprop != null)
  817. tType = cprop.PropertyType;
  818. else
  819. tType = CoreUtils.GetProperty(type, field).PropertyType;
  820. if (tType == typeof(TimeSpan) && current_fields.ContainsKey(field) && !current_fields[field].Equals(type_fields[field]))
  821. {
  822. var sql = string.Format(
  823. "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 \"%:%:%\"",
  824. type.Name, field);
  825. ExecuteSQL(access, sql);
  826. }
  827. }
  828. catch (Exception e)
  829. {
  830. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  831. }
  832. if (!current_fields.ContainsKey(field) || (!String.IsNullOrWhiteSpace(current_fields[field])) && (current_fields[field] != type_fields[field]))
  833. bRebuild = true;
  834. }
  835. foreach (var field in current_fields.Keys)
  836. if (!type_fields.ContainsKey(field))
  837. bRebuild = true;
  838. if (bForceRebuild || bRebuild)
  839. RebuildTable(access, type, current_fields, type_fields, customproperties);
  840. }
  841. private void CheckIndexes(SQLiteWriteAccessor access, Type type, Dictionary<string, string> db_indexes)
  842. {
  843. var type_indexes = LoadIndexes(type);
  844. foreach (var index in db_indexes.Keys)
  845. if (!type_indexes.Contains(db_indexes[index]))
  846. ExecuteSQL(access, string.Format("DROP INDEX {0}", index));
  847. foreach (var index in type_indexes)
  848. if (!db_indexes.ContainsValue(index))
  849. ExecuteSQL(access, index);
  850. }
  851. private void CheckTriggers(SQLiteWriteAccessor access, Type type, Dictionary<string, string> db_triggers)
  852. {
  853. #if PURGE
  854. foreach (var trigger in db_triggers.Keys)
  855. ExecuteSQL(access, string.Format("DROP TRIGGER {0}", trigger));
  856. #else
  857. var type_triggers = LoadTriggers(type);
  858. foreach (var trigger in db_triggers.Keys)
  859. if (!type_triggers.Contains(db_triggers[trigger]))
  860. ExecuteSQL(access, string.Format("DROP TRIGGER {0}", trigger));
  861. foreach (var trigger in type_triggers)
  862. if (!db_triggers.ContainsValue(trigger))
  863. ExecuteSQL(access, trigger);
  864. #endif
  865. }
  866. // private void CheckViews(SQLiteWriteAccessor access, Type type, Dictionary<String, String> db_views)
  867. // {
  868. // var type_view = LoadView(type);
  869. //
  870. //
  871. // if (!type_triggers.Contains(db_triggers[viewname]))
  872. // ExecuteSQL(access, string.Format("DROP TRIGGER {0}", trigger));
  873. //
  874. // if (!db_views.ContainsValue(type_view))
  875. // ExecuteSQL(access, type_view);
  876. // }
  877. #endregion
  878. #region CRUD Operations
  879. private bool IsNull(object o)
  880. {
  881. return o == null || o is DBNull;
  882. }
  883. public object Decode(object o, Type type)
  884. {
  885. if (IsNull(o))
  886. return type == typeof(string) ? "" : type.GetDefault();
  887. if (type == typeof(string[]))
  888. {
  889. if (!IsNull(o))
  890. {
  891. var array = o as byte[];
  892. if (o is byte[])
  893. using (var ms = new MemoryStream((byte[])o))
  894. {
  895. var deser = new BinaryFormatter().Deserialize(ms);
  896. return deser as string[];
  897. }
  898. return new string[] { };
  899. }
  900. return new string[] { };
  901. }
  902. if (type.GetInterfaces().Contains(typeof(IPackable)))
  903. {
  904. var packable = Activator.CreateInstance(type) as IPackable;
  905. if (!IsNull(o))
  906. {
  907. var array = o as byte[];
  908. if (o is byte[])
  909. packable.Unpack(new FastBinaryReader((byte[])o));
  910. }
  911. return packable;
  912. }
  913. if (type == typeof(DateTime))
  914. return IsNull(o) || string.IsNullOrEmpty(o.ToString()) ? DateTime.MinValue : DateTime.Parse(o.ToString());
  915. if (type == typeof(TimeSpan))
  916. {
  917. if (IsNull(o))
  918. return TimeSpan.MinValue;
  919. if (double.TryParse(o.ToString(), out var hrs))
  920. return TimeSpan.FromHours(hrs);
  921. if (o.ToString().Contains(":"))
  922. return TimeSpan.Parse(o.ToString());
  923. }
  924. if (type == typeof(Guid))
  925. return IsNull(o) ? Guid.Empty : Guid.Parse(o.ToString());
  926. if (type == typeof(bool))
  927. return IsNull(o) ? false : o.ToString().Equals("1") || o.ToString().ToUpper().Equals("TRUE");
  928. if (type.IsEnum)
  929. return Enum.Parse(type, o.ToString());
  930. if (IsNull(o))
  931. return null;
  932. if (type == typeof(long))
  933. return o;
  934. var result = CoreUtils.ChangeType(o, type);
  935. return result;
  936. }
  937. public object Encode(object o, Type type)
  938. {
  939. if (IsNull(o))
  940. return DBNull.Value;
  941. if (type == typeof(DateTime) && o.GetType() == typeof(string))
  942. o = DateTime.Parse(o.ToString());
  943. if (type == typeof(double) && o.GetType() == typeof(string))
  944. o = double.Parse(o.ToString());
  945. if (type == typeof(float) && o.GetType() == typeof(string))
  946. o = float.Parse(o.ToString());
  947. if (type == typeof(long) && o.GetType() == typeof(string))
  948. o = long.Parse(o.ToString());
  949. if (type.IsEnum && o.GetType() == typeof(string))
  950. o = Enum.Parse(type, o.ToString());
  951. if (type == typeof(TimeSpan) && o.GetType() == typeof(string))
  952. {
  953. if (o.ToString().Contains(":"))
  954. {
  955. if (TimeSpan.TryParse(o.ToString(), out var time))
  956. o = time;
  957. }
  958. else if (double.TryParse(o.ToString(), out var hrs))
  959. {
  960. o = TimeSpan.FromHours(hrs);
  961. }
  962. }
  963. if (type == typeof(bool))
  964. {
  965. if (o.GetType() == typeof(string))
  966. o = bool.Parse(o.ToString());
  967. if (o.Equals(false))
  968. return DBNull.Value;
  969. return o;
  970. }
  971. if (type == typeof(string) && string.IsNullOrEmpty(o.ToString()))
  972. return DBNull.Value;
  973. if (type == typeof(Guid) && o.GetType() == typeof(string))
  974. o = Guid.Parse(o.ToString());
  975. if (o is string[])
  976. using (var ms = new MemoryStream())
  977. {
  978. new BinaryFormatter().Serialize(ms, o);
  979. return ms.GetBuffer();
  980. }
  981. if (o is IPackable)
  982. using (var writer = new FastBinaryWriter())
  983. {
  984. ((IPackable)o).Pack(writer);
  985. return writer.GetBuffer();
  986. }
  987. if (o.GetType() == typeof(double) && o.Equals(default(double)))
  988. return DBNull.Value;
  989. if (o.GetType() == typeof(float) && o.Equals(default(float)))
  990. return DBNull.Value;
  991. if (o.GetType() == typeof(int) && o.Equals(default(int)))
  992. return DBNull.Value;
  993. if (o.GetType() == typeof(long) && o.Equals(default(long)))
  994. return DBNull.Value;
  995. if (o.GetType() == typeof(DateTime))
  996. {
  997. if ((DateTime)o <= DateTime.MinValue.AddDays(1))
  998. return DBNull.Value;
  999. return string.Format("{0:yyyy-MM-dd HH:mm:ss.FFFFFFF}", o);
  1000. }
  1001. if (o.GetType() == typeof(TimeSpan))
  1002. {
  1003. if (((TimeSpan)o).Ticks == 0L)
  1004. return DBNull.Value;
  1005. return ((TimeSpan)o).TotalHours;
  1006. }
  1007. if (o.GetType() == typeof(Guid))
  1008. {
  1009. if (o.Equals(Guid.Empty))
  1010. return DBNull.Value;
  1011. return o.ToString();
  1012. }
  1013. if (type == typeof(double) && o.GetType() == typeof(string))
  1014. if (double.TryParse((string)o, out var value))
  1015. o = value;
  1016. if (o.GetType().IsEnum)
  1017. return o.ToString();
  1018. return o;
  1019. }
  1020. private static readonly Dictionary<Operator, string> operators = new()
  1021. {
  1022. { Operator.IsEqualTo, "{0} = {1}" },
  1023. { Operator.IsNotEqualTo, "{0} != {1}" },
  1024. { Operator.IsGreaterThan, "{0} > {1}" },
  1025. { Operator.IsGreaterThanOrEqualTo, "{0} >= {1}" },
  1026. { Operator.IsLessThan, "{0} < {1}" },
  1027. { Operator.IsLessThanOrEqualTo, "{0} <= {1}" },
  1028. { Operator.BeginsWith, "{0} LIKE {1} || '%'" },
  1029. { Operator.Contains, "{0} LIKE '%' || {1} || '%'" },
  1030. { Operator.EndsWith, "{0} LIKE '%' || {1}" },
  1031. { Operator.InList, "{0} IN ({1})" },
  1032. { Operator.NotInList, "{0} NOT IN ({1})" },
  1033. { Operator.InQuery, "{0} IN ({1})" }
  1034. };
  1035. private string GetFilterClause<T>(SQLiteCommand command, char prefix, Filter<T> filter, List<Tuple<string, string, string, string>> tables,
  1036. Dictionary<string, string> fieldmap, List<string> columns) where T : Entity
  1037. {
  1038. if (filter == null || filter.Expression == null)
  1039. return "";
  1040. var result = "";
  1041. if (filter.Operator == Operator.All)
  1042. {
  1043. result = "1 = 1";
  1044. }
  1045. else if(filter.Operator == Operator.None)
  1046. {
  1047. result = "1 = 0";
  1048. }
  1049. else
  1050. {
  1051. var prop = "";
  1052. MemberExpression mexp = null;
  1053. if (CoreUtils.TryFindMemberExpression(filter.Expression, out mexp))
  1054. {
  1055. prop = CoreUtils.GetFullPropertyName(mexp, ".");
  1056. }
  1057. else
  1058. {
  1059. prop = filter.Expression.ToString();
  1060. if (prop.Contains("=>"))
  1061. prop = string.Join(".", prop.Split('.').Skip(1));
  1062. mexp = CoreUtils.GetMemberExpression(typeof(T), prop);
  1063. }
  1064. LoadFieldsandTables(command, typeof(T), prefix, fieldmap, tables, columns, prop);
  1065. if (fieldmap.ContainsKey(prop))
  1066. prop = fieldmap[prop];
  1067. if (filter.Operator == Operator.InList || filter.Operator == Operator.NotInList)
  1068. {
  1069. // if, and only if the list contains Guids, we can safely bypass the
  1070. // 1000-parameter limit by using building the string ourselves
  1071. if (filter.Value is Guid[])
  1072. {
  1073. var list = filter.Value as Guid[];
  1074. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Format("\"{0}\"", string.Join("\",\"", list)));
  1075. }
  1076. else if (filter.Value is IEnumerable)
  1077. {
  1078. var list = filter.Value as IEnumerable;
  1079. var paramlist = new List<object>();
  1080. foreach (var item in list)
  1081. {
  1082. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1083. command.Parameters.AddWithValue(sParam, Encode(item, mexp.Type));
  1084. paramlist.Add(sParam);
  1085. }
  1086. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Join(",", paramlist));
  1087. }
  1088. }
  1089. else if (filter.Operator == Operator.InQuery)
  1090. {
  1091. var subQuery = filter.Value;
  1092. var subEntityType = subQuery.GetType().GenericTypeArguments[0];
  1093. var selectFnc = typeof(SQLiteProvider).GetMethod("PrepareSelect").MakeGenericMethod(subEntityType);
  1094. var columnsType = typeof(Columns<>).MakeGenericType(subEntityType);
  1095. var subColumns = Activator.CreateInstance(columnsType);
  1096. var subColumn = subQuery.GetType().GetProperty("Column").GetValue(subQuery);
  1097. var arr = Array.CreateInstance(subColumn.GetType(), 1);
  1098. arr.SetValue(subColumn, 0);
  1099. columnsType.GetProperty("Items").SetValue(subColumns, arr);
  1100. var subQueryText = selectFnc.Invoke(this, new[]
  1101. {
  1102. command,
  1103. 'A',
  1104. subQuery.GetType().GetProperty("Filter").GetValue(subQuery),
  1105. subColumns,
  1106. null,
  1107. null,
  1108. int.MaxValue,
  1109. false
  1110. }) as string;
  1111. result = string.Format("(" + operators[filter.Operator] + ")", prop, subQueryText);
  1112. }
  1113. else
  1114. {
  1115. var value = Encode(filter.Value, mexp.Type);
  1116. if (IsNull(value))
  1117. {
  1118. result = string.Format("({0} {1} NULL)", prop,
  1119. filter.Operator == Operator.IsEqualTo || filter.Operator == Operator.IsLessThan ||
  1120. filter.Operator == Operator.IsLessThanOrEqualTo
  1121. ? "IS"
  1122. : "IS NOT");
  1123. }
  1124. else
  1125. {
  1126. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1127. if (filter.Expression.Type == typeof(string[]))
  1128. {
  1129. var bytes = Encoding.ASCII.GetBytes(value.ToString());
  1130. value = BitConverter.ToString(bytes).Replace("-", string.Empty);
  1131. result = string.Format("(" + operators[filter.Operator] + ")", string.Format("hex({0})", prop), sParam);
  1132. }
  1133. else
  1134. {
  1135. result = string.Format("(" + operators[filter.Operator] + ")", prop, sParam);
  1136. }
  1137. command.Parameters.AddWithValue(sParam, value);
  1138. }
  1139. }
  1140. }
  1141. var bChanged = false;
  1142. if (filter.Ands != null && filter.Ands.Count > 0)
  1143. {
  1144. foreach (var and in filter.Ands)
  1145. {
  1146. var AndResult = GetFilterClause(command, prefix, and, tables, fieldmap, columns);
  1147. if (!string.IsNullOrEmpty(AndResult))
  1148. {
  1149. result = string.Format("{0} and {1}", result, AndResult);
  1150. bChanged = true;
  1151. }
  1152. }
  1153. if (bChanged)
  1154. result = string.Format("({0})", result);
  1155. }
  1156. bChanged = false;
  1157. if (filter.Ors != null && filter.Ors.Count > 0)
  1158. {
  1159. foreach (var or in filter.Ors)
  1160. {
  1161. var OrResult = GetFilterClause(command, prefix, or, tables, fieldmap, columns);
  1162. if (!string.IsNullOrEmpty(OrResult))
  1163. {
  1164. result = string.Format("{0} or {1}", result, OrResult);
  1165. bChanged = true;
  1166. }
  1167. }
  1168. if (bChanged)
  1169. result = string.Format("({0})", result);
  1170. }
  1171. return result;
  1172. }
  1173. private string GetSortClause<T>(SQLiteCommand command, SortOrder<T> sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1174. Dictionary<string, string> fieldmap, List<string> columns) where T : Entity
  1175. {
  1176. if (sort == null)
  1177. return "";
  1178. var result = "";
  1179. if (sort.Expression != null)
  1180. {
  1181. MemberExpression mexp = null;
  1182. if (CoreUtils.TryFindMemberExpression(sort.Expression, out mexp))
  1183. result = CoreUtils.GetFullPropertyName(mexp, ".");
  1184. else
  1185. result = sort.Expression.ToString();
  1186. var prop = CoreUtils.GetProperty(typeof(T), result);
  1187. if (prop.GetCustomAttribute<DoNotSerialize>() == null && prop.GetCustomAttribute<DoNotPersist>() == null && prop.CanWrite)
  1188. {
  1189. LoadFieldsandTables(command, typeof(T), prefix, fieldmap, tables, columns, result);
  1190. if (fieldmap.ContainsKey(result))
  1191. result = fieldmap[result];
  1192. if (sort.Expression.Type.Equals(typeof(string)))
  1193. result = string.Format("{0} COLLATE NOCASE", result);
  1194. if (sort.Direction == SortDirection.Ascending)
  1195. result = string.Format("{0} ASC", result);
  1196. else
  1197. result = string.Format("{0} DESC", result);
  1198. }
  1199. else
  1200. {
  1201. result = "";
  1202. }
  1203. }
  1204. foreach (var then in sort.Thens)
  1205. result = result + ", " + GetSortClause(command, then, prefix, tables, fieldmap, columns);
  1206. return result;
  1207. }
  1208. private string GetCalculation(AggregateAttribute attribute, string columnname)
  1209. {
  1210. switch (attribute.Calculation)
  1211. {
  1212. case AggregateCalculation.Sum:
  1213. return "TOTAL";
  1214. case AggregateCalculation.Count:
  1215. return "COUNT";
  1216. case AggregateCalculation.Maximum:
  1217. return "MAX";
  1218. case AggregateCalculation.Minimum:
  1219. return "MIN";
  1220. case AggregateCalculation.Average:
  1221. return "AVERAGE";
  1222. }
  1223. throw new Exception(string.Format("{0}.{1} is not a valid aggregate", columnname, attribute.Calculator.GetType().Name));
  1224. }
  1225. private string GetFunction(FormulaAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1226. {
  1227. if (attribute.Operator == FormulaOperator.None)
  1228. throw new Exception(string.Format("{0}.{1} is not a valid formula", columnname, attribute.Calculator.GetType().Name));
  1229. if (!fieldmap.ContainsKey(attribute.Value))
  1230. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Value));
  1231. foreach (var modifier in attribute.Modifiers)
  1232. if (!fieldmap.ContainsKey(modifier))
  1233. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, modifier));
  1234. if (attribute.Operator == FormulaOperator.Add)
  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.Subtract)
  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.Multiply)
  1241. return string.Format("(IFNULL({0},0.00) * {1})", fieldmap[attribute.Value],
  1242. string.Join(" * ", attribute.Modifiers.Select(x => string.Format("IFNULL({0},0.00)", fieldmap[x]))));
  1243. if (attribute.Operator == FormulaOperator.Divide)
  1244. {
  1245. var result = string.Format("IFNULL({0},0.00)", fieldmap[attribute.Value]);
  1246. foreach (var modifier in attribute.Modifiers)
  1247. result = string.Format("({0} / {1})", result, string.Format("IFNULL({0},1.00)", fieldmap[modifier]));
  1248. return result;
  1249. }
  1250. if (attribute.Operator == FormulaOperator.Maximum)
  1251. {
  1252. var result = string.Format(
  1253. "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",
  1254. fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1255. return result;
  1256. }
  1257. if (attribute.Operator == FormulaOperator.Minumum)
  1258. {
  1259. var result = string.Format(
  1260. "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",
  1261. fieldmap[attribute.Value], fieldmap[attribute.Modifiers.First()]);
  1262. return result;
  1263. }
  1264. throw new Exception(string.Format("Calculation Type [{0}.{1}] not found", columnname, attribute.GetType().Name));
  1265. }
  1266. private string GetCondition(ConditionAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1267. {
  1268. var intf = attribute.Calculator.GetType().GetInterfaces()
  1269. .FirstOrDefault(x => x.Name.StartsWith("ICondition") && x.GenericTypeArguments.Length.Equals(3));
  1270. var valuetype = intf.GenericTypeArguments[1];
  1271. var defvalue = valuetype.GetDefault();
  1272. if (!fieldmap.ContainsKey(attribute.Left))
  1273. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Left));
  1274. var condition = "";
  1275. if (attribute.Condition == Condition.Equals)
  1276. condition = "=";
  1277. else if (attribute.Condition == Condition.NotEqual)
  1278. condition = "<>";
  1279. else if (attribute.Condition == Condition.GreaterThan)
  1280. condition = ">";
  1281. else if (attribute.Condition == Condition.GreaterThanOrEqualTo)
  1282. condition = ">=";
  1283. else if (attribute.Condition == Condition.LessThan)
  1284. condition = "<";
  1285. else if (attribute.Condition == Condition.LessThanOrEqualTo)
  1286. condition = "<=";
  1287. else
  1288. throw new Exception(string.Format("{0}.{1} is not a valid condition", columnname, attribute.Calculator.GetType().Name));
  1289. if (!fieldmap.ContainsKey(attribute.Right))
  1290. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Right));
  1291. if (!fieldmap.ContainsKey(attribute.True))
  1292. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.True));
  1293. if (!fieldmap.ContainsKey(attribute.False))
  1294. throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.False));
  1295. return string.Format("CASE WHEN COALESCE({0},{1}) {2} {3} THEN {4} ELSE {5} END", fieldmap[attribute.Left], defvalue, condition,
  1296. fieldmap[attribute.Right], fieldmap[attribute.True], fieldmap[attribute.False]);
  1297. }
  1298. //private static List<string> Breadcrumb = new List<string>();
  1299. //Dictionary<String, Tuple<int, TimeSpan>> stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1300. //Stopwatch sw = new Stopwatch();
  1301. //private void LogReset()
  1302. //{
  1303. // stopwatch = new Dictionary<string, Tuple<int, TimeSpan>>();
  1304. // sw = new Stopwatch();
  1305. //}
  1306. //void LogStart()
  1307. //{
  1308. // if (sw.IsRunning)
  1309. // sw.Restart();
  1310. // else
  1311. // sw.Start();
  1312. //}
  1313. //void LogStop(String msg)
  1314. //{
  1315. // TimeSpan elapsed = sw.Elapsed;
  1316. // if (Breadcrumb.Any())
  1317. // msg = String.Join(".", Breadcrumb) + "." + msg;
  1318. // if (!stopwatch.ContainsKey(msg))
  1319. // stopwatch[msg] = new Tuple<int, TimeSpan>(1,elapsed);
  1320. // else
  1321. // stopwatch[msg] = new Tuple<int, TimeSpan>(stopwatch[msg].Item1 + 1,stopwatch[msg].Item2 + elapsed);
  1322. // sw.Restart();
  1323. //}
  1324. //private void LogPrint(String header)
  1325. //{
  1326. // foreach (var keyvalue in stopwatch.ToArray())
  1327. // OnLog?.Invoke(LogType.Information, String.Format("- {0}: {1} = ({2}) {3,10:0.0000}", header, keyvalue.Key, keyvalue.Value.Item1, keyvalue.Value.Item2.TotalMilliseconds));
  1328. //}
  1329. private void LoadFieldsandTables(SQLiteCommand command, Type type, char prefix, Dictionary<string, string> fieldmap,
  1330. List<Tuple<string, string, string, string>> tables, List<string> columns, string columnname)
  1331. {
  1332. if (fieldmap.ContainsKey(columnname))
  1333. return;
  1334. var newprefix = (char)(prefix + 1);
  1335. // LogStart();
  1336. var property = DatabaseSchema.Property(type, columnname);
  1337. // LogStop("DatabaseSchema.Property");
  1338. if (property != null && property is CustomProperty)
  1339. {
  1340. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1341. }
  1342. else
  1343. {
  1344. var bits = columnname.Split('.');
  1345. if (bits.Length == 1)
  1346. {
  1347. var prop = type.GetProperty(columnname);
  1348. if (prop != null)
  1349. {
  1350. // LogStart();
  1351. var attr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  1352. // LogStop("GetCustomAttributes(Aggregate)");
  1353. if (attr != null)
  1354. {
  1355. var agg = attr as AggregateAttribute;
  1356. bool internalaggregate = agg.Calculator.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition()== typeof(ICoreAggregate<,>));
  1357. if (internalaggregate)
  1358. {
  1359. }
  1360. else
  1361. {
  1362. var scols = new Dictionary<string, string> { { agg.Aggregate, GetCalculation(agg, columnname) } };
  1363. var siblings = columns.Where(x => !x.Equals(columnname) && x.Split('.').First().Equals(bits.First()))
  1364. .Select(x => string.Join(".", x.Split('.').Skip(1))).ToList();
  1365. var linkedtype = agg.Source;
  1366. foreach (var sibling in siblings)
  1367. {
  1368. // LogStart();
  1369. var sprop = CoreUtils.GetProperty(type, sibling);
  1370. // LogStop("GetProperty(sibling)");
  1371. // LogStart();
  1372. var sattr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  1373. // LogStop("GetCustomAttributes(Sibling.Aggregate)");
  1374. if (sattr != null)
  1375. {
  1376. // LogStart();
  1377. var sagg = sattr as AggregateAttribute;
  1378. scols[sagg.Aggregate] = GetCalculation(sagg, sibling);
  1379. // LogStop("GetCalculation(Sibling)");
  1380. }
  1381. }
  1382. // LogStart();
  1383. var subcoltype = typeof(Columns<>).MakeGenericType(linkedtype);
  1384. // LogStop("Columns<>.MakeGnericType");
  1385. // LogStart();
  1386. var subcols = Activator.CreateInstance(subcoltype) as IColumns;
  1387. // LogStop("Columns<>.CreateInstance");
  1388. foreach (var key in agg.Links.Keys)
  1389. subcols.Add(key);
  1390. //subcols.Add(agg.Link);
  1391. foreach (var scol in scols.Keys)
  1392. subcols.Add(scol);
  1393. // LogStart();
  1394. var preparemethod = GetType().GetMethod("PrepareSelect").MakeGenericMethod(linkedtype);
  1395. // LogStop("PrepareSelect<>.MakeGenericMethod");
  1396. var filter = Activator.CreateInstance(typeof(Filter<>).MakeGenericType(linkedtype), "Deleted") as IFilter;
  1397. filter!.Operator = Operator.IsEqualTo;
  1398. filter.Value = Guid.Empty;
  1399. if(agg.Filter is IFilter aggFilter)
  1400. {
  1401. var filterfields = this.GetType().GetMethod("FilterFields").MakeGenericMethod(linkedtype);
  1402. List<String> ffs = new List<string>();
  1403. filterfields.Invoke(this, new object[] { aggFilter, ffs });
  1404. foreach (var ff in ffs)
  1405. subcols.Add(ff);
  1406. filter.And(aggFilter);
  1407. }
  1408. // LogStart();
  1409. var linkedtable = string.Format("({0})",
  1410. preparemethod.Invoke(this, new object[] { command, newprefix, filter, subcols, null, scols, int.MaxValue, false }));
  1411. // LogStop("PrepareSelect<>.Invoke");
  1412. var alias = tables.Count + 1;
  1413. var link = string.Join(" , ", agg.Links.Keys.Select(x => string.Format("{0}{1}.{2}", prefix, alias, x)));
  1414. var tuple = tables.FirstOrDefault(x =>
  1415. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1416. if (tuple == null)
  1417. {
  1418. var joins = new List<string>();
  1419. foreach (var key in agg.Links.Keys)
  1420. joins.Add(
  1421. string.Format("IFNULL({0}{1}.[{2}],'') = IFNULL({0}1.[{3}],'')", prefix, alias, key, agg.Links[key]));
  1422. var join = string.Format("LEFT OUTER JOIN {0} {1}{2} ON {3}", linkedtable, prefix, alias,
  1423. string.Join(" AND ", joins));
  1424. tuple = new Tuple<string, string, string, string>(linkedtable, prefix + alias.ToString(), join, link);
  1425. //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);
  1426. tables.Add(tuple);
  1427. }
  1428. //if (bits.Last().Equals("ID"))
  1429. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1430. //else
  1431. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, agg.Aggregate);
  1432. //LoadFieldsandTables(command, agg.Type, newprefix, fieldmap, tables, columns, columnname);
  1433. //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);
  1434. //int alias = tables.Count + 1;
  1435. //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), "");
  1436. //tables.Add(tuple);
  1437. //fieldmap[columnname] = String.Format("{0}.[{1}]", tuple.Item2, agg.AggregateProperty);
  1438. }
  1439. }
  1440. else
  1441. {
  1442. // LogStart();
  1443. attr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(FormulaAttribute)));
  1444. // LogStop("GetAttribute(Formula)");
  1445. if (attr != null)
  1446. {
  1447. var fnc = attr as FormulaAttribute;
  1448. var functionmap = new Dictionary<string, string>();
  1449. // LogStart();
  1450. CheckColumn(columns, fnc.Value);
  1451. // LogStop("Formula.CheckColumn");
  1452. //// LogStart();
  1453. LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, fnc.Value);
  1454. //// LogStop("Formula.LoadFieldsAndTables");
  1455. foreach (var column in fnc.Modifiers)
  1456. {
  1457. // LogStart();
  1458. CheckColumn(columns, column);
  1459. // LogStop("Formula.Modifiers.CheckColumn");
  1460. //// LogStart();
  1461. LoadFieldsandTables(command, type, prefix, functionmap, tables, columns, column);
  1462. //// LogStop("Formula.Modifiers.LoadFieldsAndTables");
  1463. }
  1464. fieldmap[columnname] = GetFunction(fnc, functionmap, columnname);
  1465. }
  1466. else
  1467. {
  1468. // LogStart();
  1469. attr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(ConditionAttribute)));
  1470. // LogStop("GetAttribute(Condition)");
  1471. if (attr != null)
  1472. {
  1473. var cnd = attr as ConditionAttribute;
  1474. var cndmap = new Dictionary<string, string>();
  1475. // LogStart();
  1476. CheckColumn(columns, cnd.Left);
  1477. // LogStop("CheckColumn(Left)");
  1478. // LogStart();
  1479. CheckColumn(columns, cnd.Right);
  1480. // LogStop("CheckColumn(Right)");
  1481. // LogStart();
  1482. CheckColumn(columns, cnd.True);
  1483. // LogStop("CheckColumn(True)");
  1484. // LogStart();
  1485. CheckColumn(columns, cnd.False);
  1486. // LogStop("CheckColumn(False)");
  1487. //// LogStart();
  1488. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Left);
  1489. //// LogStop("LoadFieldsAndTables(Left)");
  1490. //// LogStart();
  1491. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.Right);
  1492. //// LogStop("LoadFieldsAndTables(Right)");
  1493. //// LogStart();
  1494. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.True);
  1495. //// LogStop("LoadFieldsAndTables(True)");
  1496. //// LogStart();
  1497. LoadFieldsandTables(command, type, prefix, cndmap, tables, columns, cnd.False);
  1498. //// LogStop("LoadFieldsAndTables(False)");
  1499. // LogStart();
  1500. fieldmap[columnname] = GetCondition(cnd, cndmap, columnname);
  1501. // LogStop("GetCondition");
  1502. }
  1503. else
  1504. {
  1505. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1506. }
  1507. }
  1508. }
  1509. }
  1510. else
  1511. {
  1512. //IProperty customprop = DataModel.Property(type, columnname);
  1513. //if (customprop != null)
  1514. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1515. //else
  1516. fieldmap[columnname] = columnname;
  1517. }
  1518. }
  1519. else
  1520. {
  1521. var prop = type.GetProperty(bits.First());
  1522. if (prop != null)
  1523. {
  1524. var combinecount = 1;
  1525. while (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  1526. {
  1527. combinecount++;
  1528. prop = CoreUtils.GetProperty(type, string.Join(".", bits.Take(combinecount)));
  1529. }
  1530. if (prop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  1531. {
  1532. var linkedtype = prop.PropertyType.GetInheritedGenericTypeArguments().First();
  1533. var remote = linkedtype.GetProperty(bits.Last());
  1534. // Are there any other properties for this link? These will form the columns for our subquery
  1535. var siblings = columns.Where(x => x.Split('.').First().Equals(bits.First()))
  1536. .Select(x => string.Join(".", x.Split('.').Skip(combinecount))).ToList();
  1537. if (remote != null && !siblings.Contains(remote.Name))
  1538. siblings.Add(remote.Name);
  1539. if (siblings.Count.Equals(1) && siblings.First().Equals("ID"))
  1540. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1541. // Hmmm.. there must have been a reason why we do this, but...
  1542. // Deleted is not part of parent tables (only ID is), so the same
  1543. // shortcut that limits joining when we are only selecting ID's does
  1544. // not work if we are selecting Deleted's.
  1545. //else if (siblings.Count.Equals(2) && siblings.Skip(1).First().Equals("Deleted"))
  1546. // fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1547. else
  1548. {
  1549. if (!siblings.Contains("ID"))
  1550. siblings.Insert(0, "ID");
  1551. if (!siblings.Contains("Deleted"))
  1552. siblings.Insert(1, "Deleted");
  1553. // LogStart();
  1554. var subcoltype = typeof(Columns<>).MakeGenericType(linkedtype);
  1555. // LogStop("Columns<>.MakeGenericType");
  1556. // LogStart();
  1557. var subcols = Activator.CreateInstance(subcoltype) as IColumns;
  1558. // LogStop("Columns<>.CreateInstance");
  1559. foreach (var sibling in siblings)
  1560. subcols.Add(sibling);
  1561. // LogStart();
  1562. var preparemethod = GetType().GetMethod("PrepareSelect").MakeGenericMethod(linkedtype);
  1563. // LogStop("PrepareSelect<>.MakeGenericMethod");
  1564. var filter = Activator.CreateInstance(typeof(Filter<>).MakeGenericType(linkedtype), "Deleted") as IFilter;
  1565. filter!.Operator = Operator.IsEqualTo;
  1566. filter.Value = Guid.Empty;
  1567. // LogStart();
  1568. var linkedtable = string.Format("({0})",
  1569. preparemethod.Invoke(this, new object[] { command, newprefix, filter, subcols, null, null, int.MaxValue, false }));
  1570. // LogStop("PrepareSelect<>.Invoke");
  1571. //String linkedtable = linkedtype.EntityName().Split('.').Last();
  1572. var link = string.Format("{0}.ID", prop.Name);
  1573. var tuple = tables.FirstOrDefault(x =>
  1574. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1575. if (tuple == null)
  1576. {
  1577. var alias = tables.Count + 1;
  1578. tuple = new Tuple<string, string, string, string>(
  1579. linkedtable,
  1580. prefix + alias.ToString(),
  1581. string.Format(
  1582. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[ID] = {1}1.[{3}.ID]",
  1583. linkedtable,
  1584. prefix,
  1585. alias,
  1586. string.Join(".", bits.Take(combinecount)) //prop.Name
  1587. ),
  1588. link
  1589. );
  1590. tables.Add(tuple);
  1591. }
  1592. //if (bits.Last().Equals("ID"))
  1593. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  1594. //else
  1595. fieldmap[columnname] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  1596. foreach (var sibling in siblings)
  1597. {
  1598. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  1599. if (!subcol.Equals(columnname))
  1600. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  1601. }
  1602. }
  1603. }
  1604. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  1605. {
  1606. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1607. }
  1608. else
  1609. {
  1610. fieldmap[columnname] = string.Format("{0}1.[{1}]", prefix, columnname);
  1611. }
  1612. }
  1613. else
  1614. {
  1615. fieldmap[columnname] = columnname;
  1616. }
  1617. }
  1618. }
  1619. }
  1620. private static void CheckColumn(List<string> columns, string column)
  1621. {
  1622. if (!columns.Contains(column))
  1623. columns.Add(column);
  1624. }
  1625. public void FilterFields<T>(Filter<T> filter, List<string> fields)
  1626. {
  1627. if (filter == null)
  1628. return;
  1629. if (filter.Operator != Operator.None && filter.Operator != Operator.All)
  1630. {
  1631. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(filter.Expression), ".");
  1632. if (!fields.Contains(exp))
  1633. fields.Add(exp);
  1634. }
  1635. foreach (var and in filter.Ands)
  1636. FilterFields(and, fields);
  1637. foreach (var or in filter.Ors)
  1638. FilterFields(or, fields);
  1639. }
  1640. public void SortFields<T>(SortOrder<T> sort, List<string> fields)
  1641. {
  1642. if (sort == null)
  1643. return;
  1644. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(sort.Expression), ".");
  1645. if (!fields.Contains(exp))
  1646. fields.Add(exp);
  1647. foreach (var then in sort.Thens)
  1648. SortFields(then, fields);
  1649. }
  1650. public enum AggregateType
  1651. {
  1652. None,
  1653. Sum,
  1654. Count
  1655. }
  1656. public string PrepareSelect<T>(SQLiteCommand command, char prefix, Filter<T> filter, Columns<T> columns, SortOrder<T> sort,
  1657. Dictionary<string, string> aggregates, int top = int.MaxValue, bool distinct = false) where T : Entity
  1658. {
  1659. //Breadcrumb.Add(typeof(T).Name);
  1660. var fieldmap = new Dictionary<string, string>();
  1661. //LogStart();
  1662. var cols = CoreUtils.GetColumns(columns);
  1663. //LogStop("PrepareSelect.GetColumns");
  1664. var fields = new List<string>();
  1665. fields.AddRange(cols.ColumnNames());
  1666. //LogStart();
  1667. FilterFields(filter, fields);
  1668. //LogStop("PrepareSelect.FilterFields");
  1669. //LogStart();
  1670. SortFields(sort, fields);
  1671. //LogStop("PrepareSelect.SortFields");
  1672. var tables = new List<Tuple<string, string, string, string>>();
  1673. var condition = "";
  1674. var sortorder = "";
  1675. tables.Add(new Tuple<string, string, string, string>(
  1676. typeof(T).EntityName().Split('.').Last(),
  1677. string.Format("{0}1", prefix),
  1678. string.Format("{0} {1}1", typeof(T).EntityName().Split('.').Last(), prefix),
  1679. "")
  1680. );
  1681. foreach (var column in cols.Items) LoadFieldsandTables(command, typeof(T), prefix, fieldmap, tables, fields, column.Property);
  1682. var parameters = new Dictionary<string, object>();
  1683. //LogStart();
  1684. condition = GetFilterClause(command, prefix, filter, tables, fieldmap, fields);
  1685. //LogStop("PrepareSelect.GetFilterClause");
  1686. //LogStart();
  1687. sortorder = GetSortClause(command, sort, prefix, tables, fieldmap, fields);
  1688. //LogStop("PrepareSelect.GetSortClause");
  1689. fields.Clear();
  1690. foreach (var column in cols.Items)
  1691. if (fieldmap.ContainsKey(column.Property))
  1692. {
  1693. if (aggregates != null && aggregates.ContainsKey(column.Property))
  1694. fields.Add(string.Format("{0}({1}) as [{2}]", aggregates[column.Property], fieldmap[column.Property], column.Property));
  1695. else
  1696. fields.Add(string.Format("{0} as [{1}]", fieldmap[column.Property], column.Property));
  1697. }
  1698. var result = new List<string>();
  1699. result.Add("SELECT");
  1700. if (distinct)
  1701. result.Add("DISTINCT");
  1702. result.Add(string.Join(", ", fields));
  1703. result.Add("FROM");
  1704. result.AddRange(tables.Select(x => x.Item3));
  1705. if (!string.IsNullOrWhiteSpace(condition))
  1706. {
  1707. result.Add("WHERE");
  1708. result.Add(condition);
  1709. }
  1710. if (!string.IsNullOrWhiteSpace(sortorder))
  1711. {
  1712. result.Add("ORDER BY");
  1713. result.Add(sortorder);
  1714. }
  1715. if (aggregates != null)
  1716. {
  1717. var str = string.Join(", ",
  1718. fieldmap.Where(x => cols.Items.Any(c => c.Property.Equals(x.Key)) && !aggregates.ContainsKey(x.Key)).Select(f => f.Value));
  1719. if (!string.IsNullOrWhiteSpace(str))
  1720. {
  1721. result.Add("GROUP BY");
  1722. result.Add(str);
  1723. }
  1724. }
  1725. if (top != int.MaxValue)
  1726. result.Add(String.Format("LIMIT {0}", top));
  1727. //Breadcrumb.Remove(Breadcrumb.Last());
  1728. return string.Join(" ", result);
  1729. }
  1730. private void PrepareUpsert<T>(SQLiteCommand command, T item, bool addDelete = false) where T : Entity
  1731. {
  1732. command.CommandText = "";
  1733. command.Parameters.Clear();
  1734. if (item.ID == Guid.Empty)
  1735. item.ID = Guid.NewGuid();
  1736. Dictionary<string, object> insert = item.GetValues(true);
  1737. Dictionary<string, object> update = item.GetValues(false);
  1738. if (addDelete)
  1739. {
  1740. insert.Add("Deleted", item.Deleted);
  1741. if (item.HasOriginalValue("Deleted"))
  1742. update.Add("Deleted", item.Deleted);
  1743. }
  1744. var insertfields = new List<string>();
  1745. var insertvalues = new List<string>();
  1746. var updatecommands = new List<string>();
  1747. var iParam = 0;
  1748. foreach (var key in insert.Keys)
  1749. {
  1750. if (insert[key] is UserProperties)
  1751. continue;
  1752. var sParam = string.Format("@p{0}", iParam++);
  1753. object value = null;
  1754. try
  1755. {
  1756. value = Encode(insert[key], insert[key]?.GetType());
  1757. }
  1758. catch (Exception e)
  1759. {
  1760. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1761. }
  1762. command.Parameters.AddWithValue(sParam, value);
  1763. insertfields.Add(string.Format("[{0}]", key));
  1764. insertvalues.Add(sParam);
  1765. if (update.ContainsKey(key))
  1766. if (!key.Equals("ID"))
  1767. updatecommands.Add(string.Format("[{0}]={1}", key, sParam));
  1768. }
  1769. var particles = new List<string>();
  1770. particles.Add("INSERT INTO");
  1771. particles.Add(typeof(T).EntityName().Split('.').Last());
  1772. particles.Add("(");
  1773. particles.Add(string.Join(",", insertfields));
  1774. particles.Add(")");
  1775. particles.Add("VALUES");
  1776. particles.Add("(");
  1777. particles.Add(string.Join(",", insertvalues));
  1778. particles.Add(")");
  1779. if (updatecommands.Any())
  1780. particles.Add("ON CONFLICT([ID]) DO UPDATE SET " + string.Join(", ", updatecommands));
  1781. else
  1782. particles.Add("ON CONFLICT DO NOTHING");
  1783. command.CommandText = string.Join(" ", particles);
  1784. }
  1785. public void PrepareDelete<T>(SQLiteCommand command, T item) where T : Entity
  1786. {
  1787. command.CommandText = string.Format("DELETE FROM {0} WHERE [ID] = @p0", typeof(T).EntityName().Split('.').Last());
  1788. command.Parameters.Clear();
  1789. command.Parameters.AddWithValue("@p0", Encode(item.ID, typeof(Guid)));
  1790. }
  1791. #endregion
  1792. #region Schema Handling
  1793. public Dictionary<string, Type> GetSchema()
  1794. {
  1795. var result = new Dictionary<string, Type>();
  1796. return result;
  1797. }
  1798. public void CreateSchema(params Type[] types)
  1799. {
  1800. }
  1801. public void SaveSchema(Dictionary<string, Type> schema)
  1802. {
  1803. }
  1804. public void UpgradeSchema(params Type[] types)
  1805. {
  1806. }
  1807. #endregion
  1808. #region CRUD Operations
  1809. public object[] GetValues(IDataReader reader, int count)
  1810. {
  1811. var result = new object[count];
  1812. reader.GetValues(result);
  1813. return result;
  1814. }
  1815. public IEnumerable<object[]> List<T>(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null) where T : Entity, new()
  1816. {
  1817. var newFilter = new Filter<T>(x => x.Deleted).IsEqualTo(Guid.Empty);
  1818. if (filter != null)
  1819. newFilter.And(filter);
  1820. filter = newFilter;
  1821. //Dictionary<String, TimeSpan> stopwatch = new Dictionary<string, TimeSpan>();
  1822. //Stopwatch sw = new Stopwatch();
  1823. //sw.Start();
  1824. var cols = CoreUtils.GetColumns(columns);
  1825. //stopwatch["GetColumns"] = new TimeSpan(sw.ElapsedTicks);
  1826. //sw.Restart();
  1827. var result = new List<object[]>();
  1828. //stopwatch["MakeResult"] = new TimeSpan(sw.ElapsedTicks);
  1829. //sw.Restart();
  1830. using (var access = GetReadAccess())
  1831. {
  1832. using (var command = access.CreateCommand())
  1833. {
  1834. var sortorder = sort == null ? LookupFactory.DefineSort<T>() : sort;
  1835. command.CommandText = "";
  1836. command.Parameters.Clear();
  1837. command.CommandText = PrepareSelect(command, 'A', filter, cols, sortorder, null, int.MaxValue) + ";";
  1838. //stopwatch["PrepareSelect"] = new TimeSpan(sw.ElapsedTicks);
  1839. //sw.Restart();
  1840. using (var reader = command.ExecuteReader())
  1841. {
  1842. //stopwatch["QueryDatabase"] = new TimeSpan(sw.ElapsedTicks);
  1843. //sw.Restart();
  1844. foreach (var row in reader)
  1845. {
  1846. var values = GetValues(reader, cols.Items.Length);
  1847. result.Add(values);
  1848. }
  1849. //yield return GetValues(reader, cols.Items.Length);
  1850. //stopwatch["ReadData"] = new TimeSpan(sw.ElapsedTicks);
  1851. //sw.Restart();
  1852. reader.Close();
  1853. //stopwatch["Close"] = new TimeSpan(sw.ElapsedTicks);
  1854. //sw.Restart();
  1855. }
  1856. //foreach (var key in stopwatch.Keys)
  1857. // OnLog?.Invoke(String.Format("List{0}: {1} = {2,10:0.0000}", typeof(T).EntityName().Split('.').Last(), key, stopwatch[key].TotalMilliseconds), false);
  1858. }
  1859. }
  1860. return result;
  1861. }
  1862. private CoreTable DoQuery<T>(Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort, int top, bool log, bool distinct)
  1863. where T : Entity, new()
  1864. {
  1865. var start = DateTime.Now;
  1866. //LogReset();
  1867. //LogStart();
  1868. var cols = CoreUtils.GetColumns(columns);
  1869. //LogStop("GetColumns");
  1870. var result = new CoreTable();
  1871. result.TableName = typeof(T).EntityName();
  1872. foreach (var col in cols.Items)
  1873. result.Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.ExpressionType() });
  1874. //LogStop("MakeTable");
  1875. using (var access = GetReadAccess())
  1876. {
  1877. using (var command = access.CreateCommand())
  1878. {
  1879. var sortorder = sort == null ? LookupFactory.DefineSort<T>() : sort;
  1880. command.CommandText = "";
  1881. command.Parameters.Clear();
  1882. //LogStart();
  1883. String sql = PrepareSelect(command, 'A', filter, cols, sortorder, null, top, distinct) + ";";
  1884. command.CommandText = sql;
  1885. //LogStop("PrepareSelect");
  1886. try
  1887. {
  1888. using (var reader = command.ExecuteReader())
  1889. {
  1890. if (reader.HasRows)
  1891. {
  1892. var rows = new List<CoreRow>();
  1893. while (reader.Read())
  1894. {
  1895. var row = result.NewRow();
  1896. for (var i = 0; i < reader.FieldCount; i++)
  1897. try
  1898. {
  1899. var type = result.Columns[i].DataType;
  1900. if (reader.IsDBNull(i))
  1901. {
  1902. row.Values.Add(result.Columns[i].DataType.GetDefault());
  1903. }
  1904. else if (type.IsEnum)
  1905. {
  1906. ReadAndDecodeValue(result, reader, row, i);
  1907. }
  1908. else if (type == typeof(byte))
  1909. {
  1910. row.Values.Add(reader.GetByte(i));
  1911. }
  1912. else if (type == typeof(byte[]))
  1913. {
  1914. ReadAndDecodeValue(result, reader, row, i);
  1915. }
  1916. else if (type == typeof(bool))
  1917. {
  1918. ReadAndDecodeValue(result, reader, row, i);
  1919. }
  1920. else if (type == typeof(short))
  1921. {
  1922. row.Values.Add(reader.GetInt16(i));
  1923. }
  1924. else if (type == typeof(int))
  1925. {
  1926. row.Values.Add(reader.GetInt32(i));
  1927. }
  1928. else if (type == typeof(long))
  1929. {
  1930. row.Values.Add(reader.GetInt64(i));
  1931. }
  1932. else if (type == typeof(float))
  1933. {
  1934. row.Values.Add(reader.GetFloat(i));
  1935. }
  1936. else if (type == typeof(double))
  1937. {
  1938. row.Values.Add(reader.GetDouble(i));
  1939. }
  1940. else if (type == typeof(decimal))
  1941. {
  1942. row.Values.Add(reader.GetDecimal(i));
  1943. }
  1944. else if (type == typeof(string))
  1945. {
  1946. var value = reader.GetString(i);
  1947. row.Values.Add(value != null ? value : "");
  1948. }
  1949. else if (type == typeof(DateTime))
  1950. {
  1951. ReadAndDecodeValue(result, reader, row, i);
  1952. }
  1953. else if (type == typeof(TimeSpan))
  1954. {
  1955. ReadAndDecodeValue(result, reader, row, i);
  1956. }
  1957. else if (type == typeof(Guid))
  1958. {
  1959. row.Values.Add(reader.GetGuid(i));
  1960. }
  1961. else
  1962. {
  1963. ReadAndDecodeValue(result, reader, row, i);
  1964. }
  1965. }
  1966. catch (Exception e)
  1967. {
  1968. row.Values.Add(result.Columns[i].DataType.GetDefault());
  1969. }
  1970. result.Rows.Add(row);
  1971. }
  1972. }
  1973. reader.Close();
  1974. }
  1975. }
  1976. catch (Exception e)
  1977. {
  1978. OnLog?.Invoke(LogType.Error, e.Message);
  1979. }
  1980. //LogStop("ReadData");
  1981. //LogPrint(String.Format("Query{0}", typeof(T).Name));
  1982. }
  1983. }
  1984. if (log)
  1985. {
  1986. var duration = DateTime.Now - start;
  1987. Logger.Send(LogType.Information, "",
  1988. string.Format("SQLite::Query<{0}>({1} cols) returns {2} rows in {3}ms", typeof(T).Name, cols.Items.Length, result.Rows.Count,
  1989. duration.TotalMilliseconds));
  1990. }
  1991. return result;
  1992. }
  1993. 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)
  1994. where T : Entity, new()
  1995. {
  1996. var newFilter = new Filter<T>(x => x.Deleted).IsEqualTo(Guid.Empty);
  1997. if (filter != null)
  1998. newFilter.And(filter);
  1999. return DoQuery(newFilter, columns, sort, top, log, distinct);
  2000. }
  2001. public CoreTable QueryDeleted<T>(Deletion deletion, Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, int top = int.MaxValue)
  2002. where T : Entity, new()
  2003. {
  2004. if (filter != null)
  2005. filter.And(x => x.Deleted).IsEqualTo(deletion.ID);
  2006. else
  2007. filter = new Filter<T>(x => x.Deleted).IsEqualTo(deletion.ID);
  2008. return DoQuery(filter, columns, sort, top, true, false);
  2009. }
  2010. private void ReadAndDecodeValue(CoreTable result, SQLiteDataReader reader, CoreRow row, int i)
  2011. {
  2012. var value = reader.GetValue(i);
  2013. var decoded = Decode(value, result.Columns[i].DataType);
  2014. row.Values.Add(decoded);
  2015. }
  2016. public T[] Load<T>(Filter<T>? filter = null, SortOrder<T>? sort = null) where T : Entity, new()
  2017. {
  2018. var newFilter = new Filter<T>(x => x.Deleted).IsEqualTo(Guid.Empty);
  2019. if (filter != null)
  2020. newFilter.And(filter);
  2021. filter = newFilter;
  2022. var result = new List<T>();
  2023. var cols = CoreUtils.GetColumns<T>(null);
  2024. using (var access = GetReadAccess())
  2025. {
  2026. using (var command = access.CreateCommand())
  2027. {
  2028. try
  2029. {
  2030. command.CommandText = "";
  2031. command.Parameters.Clear();
  2032. command.CommandText = PrepareSelect(command, 'A', filter, cols, sort, null, int.MaxValue) + ";";
  2033. using (var reader = command.ExecuteReader())
  2034. {
  2035. if (reader.HasRows)
  2036. while (reader.Read())
  2037. {
  2038. var entity = new T();
  2039. entity.SetObserving(false);
  2040. for (var i = 0; i < reader.FieldCount; i++)
  2041. {
  2042. object value = null;
  2043. if (cols.Items[i].Expression.Type == typeof(long) && !reader.IsDBNull(i))
  2044. value = reader.GetInt64(i);
  2045. else
  2046. value = reader.GetValue(i);
  2047. try
  2048. {
  2049. var decoded = Decode(value, cols.Items[i].Expression.Type);
  2050. CoreUtils.SetPropertyValue(entity, cols.Items[i].Property, decoded);
  2051. }
  2052. catch (Exception e)
  2053. {
  2054. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2055. }
  2056. }
  2057. entity.SetObserving(true);
  2058. result.Add(entity);
  2059. }
  2060. reader.Close();
  2061. }
  2062. }
  2063. catch (Exception e)
  2064. {
  2065. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2066. }
  2067. }
  2068. }
  2069. return result.ToArray();
  2070. }
  2071. private void OnSave<T>(IEnumerable<T> entities, bool addDelete = false) where T : Entity
  2072. {
  2073. if (!entities.Any())
  2074. return;
  2075. using (var access = GetWriteAccess())
  2076. {
  2077. Exception? error = null;
  2078. using (var transaction = access.BeginTransaction())
  2079. {
  2080. try
  2081. {
  2082. using (var command = access.CreateCommand())
  2083. {
  2084. foreach (var entity in entities)
  2085. {
  2086. PrepareUpsert(command, entity, addDelete);
  2087. command.ExecuteNonQuery();
  2088. }
  2089. transaction.Commit();
  2090. }
  2091. }
  2092. catch (Exception e)
  2093. {
  2094. error = e;
  2095. transaction.Rollback();
  2096. }
  2097. }
  2098. if (error != null)
  2099. throw error;
  2100. }
  2101. }
  2102. public static bool CanSave<T>()
  2103. {
  2104. if (DbFactory.IsReadOnly)
  2105. {
  2106. if (typeof(T).IsAssignableTo(typeof(License)))
  2107. {
  2108. return true;
  2109. }
  2110. DbFactory.LogReadOnly();
  2111. return false;
  2112. }
  2113. return true;
  2114. }
  2115. public void Save<T>(IEnumerable<T> entities) where T : Entity
  2116. {
  2117. if (!CanSave<T>())
  2118. {
  2119. return;
  2120. }
  2121. OnSave(entities, false);
  2122. }
  2123. private void OnSave<T>(T entity, bool addDelete = false) where T : Entity
  2124. {
  2125. Exception? error = null;
  2126. using (var access = GetWriteAccess())
  2127. {
  2128. using (var command = access.CreateCommand())
  2129. {
  2130. try
  2131. {
  2132. PrepareUpsert(command, entity, addDelete);
  2133. command.ExecuteNonQuery();
  2134. }
  2135. catch (Exception e)
  2136. {
  2137. error = e;
  2138. }
  2139. }
  2140. }
  2141. if (error != null)
  2142. throw error;
  2143. }
  2144. public void Save<T>(T entity) where T : Entity
  2145. {
  2146. if (!CanSave<T>())
  2147. {
  2148. return;
  2149. }
  2150. OnSave(entity, false);
  2151. }
  2152. public void Purge<T>(T entity) where T : Entity
  2153. {
  2154. using (var access = GetWriteAccess())
  2155. {
  2156. using (var command = access.CreateCommand())
  2157. {
  2158. PrepareDelete(command, entity);
  2159. var rows = command.ExecuteNonQuery();
  2160. }
  2161. }
  2162. }
  2163. public void Purge<T>(IEnumerable<T> entities) where T : Entity
  2164. {
  2165. if (!entities.Any())
  2166. return;
  2167. Exception? error = null;
  2168. using (var access = GetWriteAccess())
  2169. {
  2170. using (var transaction = access.BeginTransaction())
  2171. {
  2172. try
  2173. {
  2174. using (var command = access.CreateCommand())
  2175. {
  2176. foreach (var entity in entities)
  2177. {
  2178. PrepareDelete(command, entity);
  2179. var rows = command.ExecuteNonQuery();
  2180. }
  2181. }
  2182. transaction.Commit();
  2183. }
  2184. catch (Exception e)
  2185. {
  2186. transaction.Rollback();
  2187. error = e;
  2188. }
  2189. }
  2190. }
  2191. if (error != null)
  2192. throw error;
  2193. }
  2194. private Dictionary<Type, List<Tuple<Type, string>>> _cascades = new();
  2195. private Dictionary<Type, List<Tuple<Type, List<string>>>> _setNulls = new();
  2196. private void LoadDeletions(Type type)
  2197. {
  2198. // Get the EntityLink that is associated with this class
  2199. var linkclass = CoreUtils.TypeList(
  2200. new[] { type.Assembly },
  2201. x => typeof(IEntityLink).GetTypeInfo().IsAssignableFrom(x) && x.GetInheritedGenericTypeArguments().FirstOrDefault() == type
  2202. ).FirstOrDefault();
  2203. // if The entitylink does not exist, we don't need to do anything
  2204. if (linkclass == null)
  2205. return;
  2206. var cascades = new List<Tuple<Type, string>>();
  2207. var setNulls = new List<Tuple<Type, List<string>>>();
  2208. var childtypes = Types.Where(x => x.IsSubclassOf(typeof(Entity)));
  2209. foreach (var childtype in childtypes)
  2210. {
  2211. // Get all registered types for this entitylink
  2212. var fields = new List<string>();
  2213. var bDelete = false;
  2214. // Find any IEntityLink<> properties that refer back to this class
  2215. var childprops = CoreUtils.PropertyList(childtype, x => x.PropertyType == linkclass);
  2216. foreach (var childprop in childprops)
  2217. {
  2218. var fieldname = string.Format("{0}.ID", childprop.Name);
  2219. var attr = childprop.GetCustomAttributes(typeof(EntityRelationshipAttribute), true).FirstOrDefault();
  2220. if (attr != null && ((EntityRelationshipAttribute)attr).Action.Equals(DeleteAction.Cascade))
  2221. {
  2222. cascades.Add(new(childtype, fieldname));
  2223. bDelete = true;
  2224. break;
  2225. }
  2226. fields.Add(fieldname);
  2227. }
  2228. if(!bDelete && fields.Any())
  2229. {
  2230. setNulls.Add(new(childtype, fields));
  2231. }
  2232. }
  2233. if(cascades.Count > 0)
  2234. {
  2235. _cascades[type] = cascades;
  2236. }
  2237. if(setNulls.Count > 0)
  2238. {
  2239. _setNulls[type] = setNulls;
  2240. }
  2241. }
  2242. private MethodInfo _deleteEntitiesMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  2243. .Single(x => x.Name == nameof(DeleteEntity) && x.IsGenericMethod);
  2244. private void DeleteEntity<T>(Guid parentID, string parentField, Deletion deletion) where T : Entity, new()
  2245. {
  2246. var entities = Query(new Filter<T>(parentField).IsEqualTo(parentID), new Columns<T>(x => x.ID))
  2247. .Rows.Select(x => x.ToObject<T>()).ToList();
  2248. foreach(var entity in entities)
  2249. {
  2250. entity.Deleted = deletion.ID;
  2251. }
  2252. OnSave(entities, true);
  2253. foreach (var entity in entities)
  2254. {
  2255. CascadeDelete(typeof(T), entity.ID, deletion);
  2256. }
  2257. }
  2258. private void DeleteEntity(Type T, Guid parentID, string parentField, Deletion deletion)
  2259. {
  2260. _deleteEntitiesMethod.MakeGenericMethod(T).Invoke(this, new object?[] { parentID, parentField, deletion });
  2261. }
  2262. private void CascadeDelete(Type type, Guid parentID, Deletion deletion)
  2263. {
  2264. if (!_cascades.TryGetValue(type, out var cascades))
  2265. return;
  2266. foreach(var cascade in cascades)
  2267. {
  2268. DeleteEntity(cascade.Item1, parentID, cascade.Item2, deletion);
  2269. }
  2270. }
  2271. public void Delete<T>(T entity, string userID) where T : Entity, new()
  2272. {
  2273. #if PURGE
  2274. if (!CanSave<T>())
  2275. {
  2276. return;
  2277. }
  2278. entity = DoQuery(
  2279. new Filter<T>(x => x.ID).IsEqualTo(entity.ID),
  2280. null,
  2281. null,
  2282. int.MaxValue,
  2283. true,
  2284. false
  2285. ).Rows.First().ToObject<T>();
  2286. var tableName = typeof(T).Name;
  2287. var deletion = new Deletion() {
  2288. DeletionDate = DateTime.Now,
  2289. HeadTable = tableName,
  2290. Description = entity.ToString() ?? "",
  2291. DeletedBy = userID
  2292. };
  2293. OnSave(deletion);
  2294. entity.Deleted = deletion.ID;
  2295. OnSave(entity, true);
  2296. CascadeDelete(typeof(T), entity.ID, deletion);
  2297. #else
  2298. Purge(entity);
  2299. #endif
  2300. }
  2301. public void Delete<T>(IEnumerable<T> entities, string userID) where T : Entity, new()
  2302. {
  2303. #if PURGE
  2304. if (!CanSave<T>())
  2305. {
  2306. return;
  2307. }
  2308. if (!entities.Any())
  2309. return;
  2310. var ids = entities.Select(x => x.ID).ToArray();
  2311. var entityList = Query(new Filter<T>(x => x.ID).InList(ids)).Rows.Select(x => x.ToObject<T>()).ToList();
  2312. if (!entityList.Any())
  2313. return;
  2314. var tableName = typeof(T).Name;
  2315. var deletion = new Deletion() {
  2316. DeletionDate = DateTime.Now,
  2317. HeadTable = tableName,
  2318. Description = $"Deleted {entityList.Count} entries",
  2319. DeletedBy = userID
  2320. };
  2321. OnSave(deletion);
  2322. foreach(var entity in entityList)
  2323. {
  2324. entity.Deleted = deletion.ID;
  2325. OnSave(entity, true);
  2326. CascadeDelete(typeof(T), entity.ID, deletion);
  2327. }
  2328. #else
  2329. Purge(entities);
  2330. #endif
  2331. }
  2332. private void AddDeletionType(Type type, List<Type> deletions)
  2333. {
  2334. deletions.Add(type);
  2335. if (!_cascades.TryGetValue(type, out var cascades))
  2336. return;
  2337. foreach (var cascade in cascades)
  2338. {
  2339. AddDeletionType(cascade.Item1, deletions);
  2340. }
  2341. }
  2342. private Dictionary<Type, List<Type>> _allCascades = new();
  2343. private List<Type> GetDeletionTypes(Type type)
  2344. {
  2345. if(_allCascades.TryGetValue(type, out var cascades))
  2346. {
  2347. return cascades;
  2348. }
  2349. var deletionTypes = new List<Type>();
  2350. AddDeletionType(type, deletionTypes);
  2351. _allCascades[type] = deletionTypes;
  2352. return deletionTypes;
  2353. }
  2354. private void DoSetNull<TChild>(string field, Guid[] parentIDs) where TChild : Entity, new()
  2355. {
  2356. var columns = new Columns<TChild>(x => x.ID);
  2357. columns.Add(field);
  2358. var children = DoQuery(
  2359. new Filter<TChild>(field).InList(parentIDs),
  2360. columns,
  2361. null,
  2362. int.MaxValue,
  2363. true,
  2364. false
  2365. ).Rows.Select(x => x.ToObject<TChild>()).ToList();
  2366. foreach(var child in children)
  2367. {
  2368. CoreUtils.SetPropertyValue(child, field, Guid.Empty);
  2369. }
  2370. OnSave(children);
  2371. }
  2372. private void PurgeEntityType<T>(Deletion deletion) where T : Entity, new()
  2373. {
  2374. var entities = QueryDeleted(deletion, null, new Columns<T>(x => x.ID)).Rows.Select(x => x.ToObject<T>()).ToList();
  2375. if (_setNulls.TryGetValue(typeof(T), out var setNulls))
  2376. {
  2377. var ids = entities.Select(x => x.ID).ToArray();
  2378. var setNullMethod = typeof(SQLiteProvider).GetMethod(nameof(DoSetNull), BindingFlags.NonPublic | BindingFlags.Instance)!;
  2379. foreach (var (childType, childFields) in setNulls)
  2380. {
  2381. var method = setNullMethod.MakeGenericMethod(childType);
  2382. foreach(var childField in childFields)
  2383. {
  2384. method.Invoke(this, new object[] { childField, ids });
  2385. }
  2386. }
  2387. }
  2388. Purge(entities);
  2389. }
  2390. private void RecoverEntityType<T>(Deletion deletion) where T : Entity, new()
  2391. {
  2392. var entities = QueryDeleted(deletion, null, new Columns<T>(x => x.ID, x => x.Deleted)).Rows.Select(x => x.ToObject<T>()).ToList();
  2393. foreach (var entity in entities)
  2394. {
  2395. entity.Deleted = Guid.Empty;
  2396. }
  2397. OnSave(entities, true);
  2398. }
  2399. public void Purge(Deletion deletion)
  2400. {
  2401. if(deletion.ID == Guid.Empty)
  2402. {
  2403. Logger.Send(LogType.Error, "", "Empty Deletion ID; Purge cancelled");
  2404. return;
  2405. }
  2406. var entityType = CoreUtils.Entities.FirstOrDefault(x => x.Name == deletion.HeadTable);
  2407. var deletionTypes = GetDeletionTypes(entityType);
  2408. var purgeMethod = typeof(SQLiteProvider).GetMethod(nameof(PurgeEntityType), BindingFlags.NonPublic | BindingFlags.Instance)!;
  2409. foreach(var type in deletionTypes)
  2410. {
  2411. purgeMethod.MakeGenericMethod(type).Invoke(this, new object[] { deletion });
  2412. }
  2413. Purge<Deletion>(deletion);
  2414. }
  2415. public void Recover(Deletion deletion)
  2416. {
  2417. if (deletion.ID == Guid.Empty)
  2418. {
  2419. Logger.Send(LogType.Error, "", "Empty Deletion ID; Recovery cancelled");
  2420. return;
  2421. }
  2422. var entityType = CoreUtils.Entities.FirstOrDefault(x => x.Name == deletion.HeadTable);
  2423. var deletionTypes = GetDeletionTypes(entityType);
  2424. var recoveryMethod = typeof(SQLiteProvider).GetMethod(nameof(RecoverEntityType), BindingFlags.NonPublic | BindingFlags.Instance)!;
  2425. foreach (var type in deletionTypes)
  2426. {
  2427. recoveryMethod.MakeGenericMethod(type).Invoke(this, new object[] { deletion });
  2428. }
  2429. Purge<Deletion>(deletion);
  2430. }
  2431. public List<Type> GetDeletionTypes(Deletion deletion)
  2432. {
  2433. var entityType = CoreUtils.Entities.First(x => x.Name == deletion.HeadTable);
  2434. return GetDeletionTypes(entityType);
  2435. }
  2436. #endregion
  2437. }
  2438. }