SQLiteProvider.cs 154 KB

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