SQLiteProvider.cs 154 KB

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