SQLiteProvider.cs 155 KB

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