SQLiteProvider.cs 150 KB

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