SQLiteProvider.cs 124 KB

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