SQLiteProvider.cs 146 KB

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