SQLiteProvider.cs 152 KB

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