SQLiteProvider.cs 154 KB

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