SQLiteProvider.cs 125 KB

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