SQLiteProvider.cs 149 KB

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