SQLiteProvider.cs 124 KB

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