SQLiteProvider.cs 150 KB

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