SQLiteProvider.cs 154 KB

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