SQLiteProvider.cs 124 KB

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