SQLiteProvider.cs 137 KB

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