SQLiteProvider.cs 158 KB

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