SQLiteProvider.cs 157 KB

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