SQLiteProvider.cs 150 KB

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