SQLiteProvider.cs 152 KB

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