SQLiteProvider.cs 125 KB

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