SQLiteProvider.cs 149 KB

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