SQLiteProvider.cs 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958
  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 == typeof(DateTime) && o.GetType() == typeof(string))
  1474. o = DateTime.Parse(o.ToString() ?? "");
  1475. if (type == typeof(double) && o.GetType() == typeof(string))
  1476. o = double.Parse(o.ToString() ?? "");
  1477. if (type == typeof(float) && o.GetType() == typeof(string))
  1478. o = float.Parse(o.ToString() ?? "");
  1479. if (type == typeof(long) && o.GetType() == typeof(string))
  1480. o = long.Parse(o.ToString() ?? "");
  1481. if (type.IsEnum && o.GetType() == typeof(string))
  1482. o = Enum.Parse(type, o.ToString() ?? "");
  1483. if (type == typeof(TimeSpan) && o.GetType() == typeof(string))
  1484. {
  1485. if (o.ToString()?.Contains(':') == true)
  1486. {
  1487. if (TimeSpan.TryParse(o.ToString(), out var time))
  1488. o = time;
  1489. }
  1490. else if (double.TryParse(o.ToString(), out var hrs))
  1491. {
  1492. o = TimeSpan.FromHours(hrs);
  1493. }
  1494. }
  1495. if (type == typeof(bool))
  1496. {
  1497. if (o.GetType() == typeof(string))
  1498. o = bool.Parse(o.ToString() ?? "");
  1499. if (o.Equals(false))
  1500. return DBNull.Value;
  1501. return o;
  1502. }
  1503. if (type == typeof(string) && string.IsNullOrEmpty(o.ToString()))
  1504. return DBNull.Value;
  1505. if (type == typeof(Guid) && o.GetType() == typeof(string))
  1506. o = Guid.Parse(o.ToString() ?? "");
  1507. if (o is string[] sArray)
  1508. {
  1509. if (sArray.Length > 0 && !String.IsNullOrWhiteSpace(sArray[0]))
  1510. {
  1511. using (var ms = new MemoryStream())
  1512. {
  1513. #pragma warning disable SYSLIB0011
  1514. new BinaryFormatter().Serialize(ms, sArray);
  1515. #pragma warning restore SYSLIB0011
  1516. return ms.GetBuffer();
  1517. }
  1518. }
  1519. return DBNull.Value;
  1520. }
  1521. if (o is IPackable pack)
  1522. {
  1523. using var ms = new MemoryStream();
  1524. using var writer = new BinaryWriter(ms);
  1525. pack.Pack(writer);
  1526. return ms.ToArray();
  1527. }
  1528. if (o.GetType() == typeof(double) && o.Equals(default(double)))
  1529. return DBNull.Value;
  1530. if (o.GetType() == typeof(float) && o.Equals(default(float)))
  1531. return DBNull.Value;
  1532. if (o.GetType() == typeof(int) && o.Equals(default(int)))
  1533. return DBNull.Value;
  1534. if (o.GetType() == typeof(long) && o.Equals(default(long)))
  1535. return DBNull.Value;
  1536. if (o.GetType() == typeof(DateTime))
  1537. {
  1538. if ((DateTime)o == DateTime.MinValue)
  1539. return DBNull.Value;
  1540. return string.Format("{0:yyyy-MM-dd HH:mm:ss.FFFFFFF}", o);
  1541. }
  1542. if (o.GetType() == typeof(TimeSpan))
  1543. {
  1544. if (((TimeSpan)o).Ticks == 0L)
  1545. return DBNull.Value;
  1546. return ((TimeSpan)o).TotalHours;
  1547. }
  1548. if (o.GetType() == typeof(Guid))
  1549. {
  1550. if (o.Equals(Guid.Empty))
  1551. return DBNull.Value;
  1552. return o.ToString() ?? "";
  1553. }
  1554. if (type == typeof(double) && o.GetType() == typeof(string))
  1555. if (double.TryParse((string)o, out var value))
  1556. o = value;
  1557. if (o.GetType().IsEnum)
  1558. return o.ToString() ?? "";
  1559. return o;
  1560. }
  1561. private static readonly Dictionary<Operator, string> operators = new()
  1562. {
  1563. { Operator.IsEqualTo, "{0} = {1}" },
  1564. { Operator.IsNotEqualTo, "{0} != {1}" },
  1565. { Operator.IsGreaterThan, "{0} > {1}" },
  1566. { Operator.IsGreaterThanOrEqualTo, "{0} >= {1}" },
  1567. { Operator.IsLessThan, "{0} < {1}" },
  1568. { Operator.IsLessThanOrEqualTo, "{0} <= {1}" },
  1569. { Operator.BeginsWith, "IFNULL({0},'') LIKE {1} || '%'" },
  1570. { Operator.Contains, "IFNULL({0},'') LIKE '%' || {1} || '%'" },
  1571. { Operator.EndsWith, "IFNULL({0},'') LIKE '%' || {1}" },
  1572. { Operator.InList, "{0} IN ({1})" },
  1573. { Operator.NotInList, "{0} NOT IN ({1})" },
  1574. { Operator.InQuery, "{0} IN ({1})" },
  1575. { Operator.NotInQuery, "{0} NOT IN ({1})" },
  1576. { Operator.Regex, "{0} REGEXP {1}" },
  1577. { Operator.Resembles, "RESEMBLES({0},{1})"}
  1578. };
  1579. internal static string EscapeValue(object? value)
  1580. {
  1581. if (IsNull(value))
  1582. return "NULL";
  1583. if ((value is string) || (value is Enum) || (value is Guid))
  1584. return string.Format("\'" + "{0}" + "\'", value.ToString()?.Replace("\'", "\'\'"));
  1585. if (value is string[])
  1586. return string.Format("hex({0})", BitConverter.ToString(Encoding.ASCII.GetBytes(value.ToString() ?? "")).Replace("-", ""));
  1587. if (value is IColumn col)
  1588. return $"[{col.Property}]";
  1589. if (value is DateTime)
  1590. return $"'{((DateTime)value):yyyy-MM-dd HH:mm:ss.FFFFFFF}'";
  1591. return value.ToString() ?? "";
  1592. }
  1593. internal static string EscapeValue(string? value, Type type)
  1594. {
  1595. if (type == typeof(string) || type.IsEnum || (type == typeof(Guid)))
  1596. return "\'" + $"{value?.Replace("\'", "\'\'")}" + "\'";
  1597. if (type == typeof(string[]))
  1598. return string.Format("hex({0})", BitConverter.ToString(Encoding.ASCII.GetBytes(value.ToString() ?? "")).Replace("-", ""));
  1599. if (type.GetInterface(nameof(IColumn)) != null)
  1600. return $"[{value}]";
  1601. if (type == typeof(DateTime))
  1602. return DateTime.TryParse(value, out DateTime _value)
  1603. ? $"'{_value:yyyy-MM-dd HH:mm:ss.FFFFFFF}'"
  1604. : $"'{DateTime.MinValue:yyyy-MM-dd HH:mm:ss.FFFFFFF}'";
  1605. return value.ToString() ?? "";
  1606. }
  1607. private static string GetFilterConstant(FilterConstant constant)
  1608. {
  1609. return constant switch
  1610. {
  1611. FilterConstant.Null => "NULL",
  1612. FilterConstant.Now => "datetime()",
  1613. FilterConstant.Today => "datetime(date())",
  1614. FilterConstant.Zero => "0",
  1615. // These figures are based around today
  1616. FilterConstant.OneWeekAgo => "datetime(date(),'-7 days')",
  1617. FilterConstant.OneWeekAhead => "datetime(date(),'+7 days')",
  1618. FilterConstant.OneMonthAgo => "datetime(date(),'-1 month')",
  1619. FilterConstant.OneMonthAhead => "datetime(date(),'+1 month')",
  1620. FilterConstant.ThreeMonthsAgo => "datetime(date(),'-3 months')",
  1621. FilterConstant.ThreeMonthsAhead => "datetime(date(),'+3 months')",
  1622. FilterConstant.SixMonthsAgo => "datetime(date(),'-6 months')",
  1623. FilterConstant.SixMonthsAhead => "datetime(date(),'+6 months')",
  1624. FilterConstant.OneYearAgo => "datetime(date(),'-1 year')",
  1625. FilterConstant.OneYearAhead => "datetime(date(),'+1 year')",
  1626. // Relative Week values run from Monday thru Sunday
  1627. FilterConstant.StartOfLastWeek => "datetime(date(), 'weekday 0', '-13 days')",
  1628. FilterConstant.EndOfLastWeek => "datetime(date(), 'weekday 0', '-6 days', '-000.0001 seconds')",
  1629. FilterConstant.StartOfThisWeek => "datetime(date(), 'weekday 0', '-6 days')",
  1630. FilterConstant.EndOfThisWeek => "datetime(date(), 'weekday 0', '+1 day', '-000.0001 seconds')",
  1631. FilterConstant.StartOfNextWeek => "datetime(date(), 'weekday 0', '+1 days')",
  1632. FilterConstant.EndOfNextWeek => "datetime(date(), 'weekday 0', '+8 days', '-000.0001 seconds')",
  1633. FilterConstant.StartOfLastMonth => "datetime(date(), 'start of month', '-1 month')",
  1634. FilterConstant.EndOfLastMonth => "datetime(date(), 'start of month', '-000.0001 seconds')",
  1635. FilterConstant.StartOfThisMonth => "datetime(date(), 'start of month')",
  1636. FilterConstant.EndOfThisMonth => "datetime(date(), 'start of month', '+1 month', '-000.0001 seconds')",
  1637. FilterConstant.StartOfNextMonth => "datetime(date(), 'start of month', '+1 month')",
  1638. FilterConstant.EndOfNextMonth => "datetime(date(), 'start of month', '+2 months', '-000.0001 seconds')",
  1639. FilterConstant.StartOfLastCalendarYear => "datetime(date(), 'start of year', '-1 year')",
  1640. FilterConstant.EndOfLastCalendarYear => "datetime(date(), 'start of year', '-000.0001 seconds')",
  1641. FilterConstant.StartOfThisCalendarYear => "datetime(date(), 'start of year')",
  1642. FilterConstant.EndOfThisCalendarYear => "datetime(date(), 'start of year', '+1 year', '-000.0001 seconds')",
  1643. FilterConstant.StartOfNextCalendarYear => "datetime(date(), 'start of year', '+1 year')",
  1644. FilterConstant.EndOfNextCalendarYear => "datetime(date(), 'start of year', '+2 years', '-000.0001 seconds')",
  1645. FilterConstant.StartOfLastFinancialYear => "datetime(date(), '-18 months', 'start of year', '+6 months')",
  1646. FilterConstant.EndOfLastFinancialYear => "datetime(date(), '-18 months', 'start of year', '-18 months', '-000.0001 seconds')",
  1647. FilterConstant.StartOfThisFinancialYear => "datetime(date(), '-6 months', 'start of year', '+6 months')",
  1648. FilterConstant.EndOfThisFinancialYear => "datetime(date(), '-6 months', 'start of year', '+18 months', '-000.0001 seconds')",
  1649. FilterConstant.StartOfNextFinancialYear => "datetime(date(), '+6 months', 'start of year', '+6 months')",
  1650. FilterConstant.EndOfNextFinancialYear => "datetime(date(), '+6 months', 'start of year', '+18 months', '-000.0001 seconds')",
  1651. _ => throw new Exception($"FilterConstant.{constant} is not implemented!"),
  1652. };
  1653. }
  1654. public string GetFilterClauseNonGeneric(Type T, SQLiteCommand command, char prefix, IFilter? filter, List<Tuple<string, string, string, string>> tables,
  1655. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1656. {
  1657. if (filter == null)
  1658. return "";
  1659. var result = "";
  1660. if (filter.Operator == Operator.All)
  1661. {
  1662. result = filter.IsNot ? "1 = 0" : "1 = 1";
  1663. }
  1664. else if (filter.Operator == Operator.None)
  1665. {
  1666. result = filter.IsNot ? "1 = 1" : "1 = 0";
  1667. }
  1668. else
  1669. {
  1670. var prop = filter.Property;
  1671. LoadFieldsAndTables(command, T, prefix, fieldmap, tables, columns, Column.Create(T, prop), useparams);
  1672. if (fieldmap.ContainsKey(prop))
  1673. prop = fieldmap[prop];
  1674. if(filter.Value is CustomFilterValue)
  1675. {
  1676. throw new Exception("Custom Filter Value not able to be processed server-side!");
  1677. }
  1678. if (filter.Operator == Operator.InList || filter.Operator == Operator.NotInList)
  1679. {
  1680. if(filter.Value is Array arr && arr.Length == 0)
  1681. {
  1682. result = filter.Operator == Operator.InList ? "1 = 0" : "1 = 1";
  1683. }
  1684. else
  1685. {
  1686. // if, and only if the list contains Guids, we can safely bypass the
  1687. // 1000-parameter limit by using building the string ourselves
  1688. if (filter.Value is Guid[] list)
  1689. {
  1690. result = string.Format("(" + operators[filter.Operator] + ")",
  1691. prop,
  1692. string.Join(',', list.Where(x => x != Guid.Empty).Select(x => $"'{x}'")));
  1693. if (list.Contains(Guid.Empty))
  1694. {
  1695. result = $"({result} or ({prop} IS NULL))";
  1696. }
  1697. }
  1698. else if (filter.Value is IEnumerable enumerable)
  1699. {
  1700. var paramlist = new List<object>();
  1701. foreach (var item in enumerable)
  1702. {
  1703. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1704. command.Parameters.AddWithValue(sParam, Encode(item, filter.Type));
  1705. paramlist.Add(sParam);
  1706. }
  1707. result = string.Format("(" + operators[filter.Operator] + ")", prop, string.Join(",", paramlist));
  1708. }
  1709. }
  1710. }
  1711. else if (filter.Operator == Operator.InQuery || filter.Operator == Operator.NotInQuery)
  1712. {
  1713. if(filter.Value is ISubQuery subQuery)
  1714. {
  1715. var subEntityType = subQuery.GetQueryType();
  1716. var subColumns = Columns.None(subEntityType);
  1717. var subColumn = subQuery.GetColumn();
  1718. subColumns.Add(subColumn);
  1719. var subQueryText = PrepareSelectNonGeneric(subEntityType, command, 'A',
  1720. subQuery.GetFilter(), subColumns.Columns(), null,
  1721. null, null, null, false, useparams);
  1722. result = string.Format("(" + operators[filter.Operator] + ")", prop, subQueryText);
  1723. }
  1724. }
  1725. else
  1726. {
  1727. if (filter.Value is FilterConstant constant)
  1728. {
  1729. if (constant == FilterConstant.Null)
  1730. {
  1731. result = string.Format("({0} {1} NULL)", prop,
  1732. filter.Operator == Operator.IsEqualTo
  1733. ? "IS"
  1734. : "IS NOT");
  1735. }
  1736. else
  1737. result = string.Format("(" + operators[filter.Operator] + ")", prop,
  1738. GetFilterConstant(constant));
  1739. }
  1740. else
  1741. {
  1742. var value = Encode(filter.Value, filter.Type);
  1743. if (IsNull(value) && ((filter.Operator == Operator.IsEqualTo) || (filter.Operator == Operator.IsNotEqualTo)))
  1744. {
  1745. result = string.Format("({0} {1} NULL)", prop,
  1746. filter.Operator == Operator.IsEqualTo
  1747. ? "IS"
  1748. : "IS NOT");
  1749. }
  1750. else
  1751. {
  1752. if (useparams)
  1753. {
  1754. var sParam = string.Format("@p{0}", command.Parameters.Count);
  1755. if (filter.Type == typeof(string[]))
  1756. {
  1757. var bytes = Encoding.ASCII.GetBytes(value.ToString() ?? "");
  1758. value = BitConverter.ToString(bytes).Replace("-", "");
  1759. result = string.Format("(" + operators[filter.Operator] + ")", string.Format("hex({0})", prop), sParam);
  1760. }
  1761. else
  1762. {
  1763. result = string.Format("(" + operators[filter.Operator] + ")", prop, sParam);
  1764. }
  1765. command.Parameters.AddWithValue(sParam, value);
  1766. }
  1767. else
  1768. result = string.Format("(" + operators[filter.Operator] + ")", prop, EscapeValue(filter.Value));
  1769. }
  1770. }
  1771. }
  1772. if (filter.IsNot)
  1773. {
  1774. result = $"(NOT {result})";
  1775. }
  1776. }
  1777. var bChanged = false;
  1778. if (filter.Ands != null && filter.Ands.Any())
  1779. {
  1780. foreach (var and in filter.Ands)
  1781. {
  1782. var AndResult = GetFilterClauseNonGeneric(T, command, prefix, and, tables, fieldmap, columns, useparams);
  1783. if (!string.IsNullOrEmpty(AndResult))
  1784. {
  1785. result = string.Format("{0} and {1}", result, AndResult);
  1786. bChanged = true;
  1787. }
  1788. }
  1789. if (bChanged)
  1790. result = string.Format("({0})", result);
  1791. }
  1792. bChanged = false;
  1793. if (filter.Ors != null && filter.Ors.Any())
  1794. {
  1795. foreach (var or in filter.Ors)
  1796. {
  1797. var OrResult = GetFilterClauseNonGeneric(T, command, prefix, or, tables, fieldmap, columns, useparams);
  1798. if (!string.IsNullOrEmpty(OrResult))
  1799. {
  1800. result = string.Format("{0} or {1}", result, OrResult);
  1801. bChanged = true;
  1802. }
  1803. }
  1804. if (bChanged)
  1805. result = string.Format("({0})", result);
  1806. }
  1807. return result;
  1808. }
  1809. private string GetFilterClause<T>(SQLiteCommand command, char prefix, Filter<T>? filter, List<Tuple<string, string, string, string>> tables,
  1810. Dictionary<string, string> fieldmap, List<string> columns, bool useparams) where T : Entity
  1811. => GetFilterClauseNonGeneric(typeof(T), command, prefix, filter, tables, fieldmap, columns, useparams);
  1812. private string GetSortClauseNonGeneric(Type T,
  1813. SQLiteCommand command, ISortOrder? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1814. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1815. {
  1816. if (sort == null)
  1817. return "";
  1818. var result = "";
  1819. if (sort.Expression != null)
  1820. {
  1821. if (CoreUtils.TryFindMemberExpression(sort.Expression, out var mexp))
  1822. result = CoreUtils.GetFullPropertyName(mexp, ".");
  1823. else
  1824. result = sort.Expression.ToString();
  1825. var prop = CoreUtils.GetProperty(T, result);
  1826. if (prop.GetCustomAttribute<DoNotSerialize>() == null && prop.GetCustomAttribute<DoNotPersist>() == null && prop.CanWrite)
  1827. {
  1828. LoadFieldsAndTables(command, T, prefix, fieldmap, tables, columns, Column.Create(T, result), useparams);
  1829. if (fieldmap.ContainsKey(result))
  1830. result = fieldmap[result];
  1831. if (sort.Expression.Type.Equals(typeof(string)))
  1832. result = string.Format("{0} COLLATE NOCASE", result);
  1833. if (sort.Direction == SortDirection.Ascending)
  1834. result = string.Format("{0} ASC", result);
  1835. else
  1836. result = string.Format("{0} DESC", result);
  1837. }
  1838. else
  1839. {
  1840. result = "";
  1841. }
  1842. }
  1843. foreach (var then in sort.Thens)
  1844. result = result + ", " + GetSortClauseNonGeneric(T, command, then, prefix, tables, fieldmap, columns, useparams);
  1845. return result;
  1846. }
  1847. private string GetSortClause<T>(SQLiteCommand command, SortOrder<T>? sort, char prefix, List<Tuple<string, string, string, string>> tables,
  1848. Dictionary<string, string> fieldmap, List<string> columns, bool useparams)
  1849. => GetSortClauseNonGeneric(typeof(T), command, sort, prefix, tables, fieldmap, columns, useparams);
  1850. private static string GetCalculation(AggregateCalculation calculation, string columnname, Type TResult)
  1851. {
  1852. return calculation switch
  1853. {
  1854. AggregateCalculation.Sum => TResult == typeof(decimal) ? "DECIMAL_SUM({0})" : "SUM({0})",
  1855. AggregateCalculation.Count => "COUNT({0})",
  1856. AggregateCalculation.Maximum => "MAX({0})",
  1857. AggregateCalculation.Minimum => "MIN({0})",
  1858. AggregateCalculation.Average => "AVERAGE({0})",
  1859. AggregateCalculation.Concat => "GROUP_CONCAT(DISTINCT {0})",
  1860. _ => throw new Exception(string.Format("{0}.{1} is not a valid aggregate", columnname, calculation)),
  1861. };
  1862. }
  1863. private string GetFunction(FormulaAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1864. {
  1865. if (attribute.Operator == FormulaOperator.None)
  1866. throw new Exception(string.Format("{0}.{1} is not a valid formula", columnname, attribute.Calculator.GetType().Name));
  1867. if (attribute.Operator == FormulaOperator.Constant)
  1868. return EscapeValue(attribute.Value);
  1869. // Crashes when value is a constant, and therefore not a field in the table
  1870. // if (!fieldmap.ContainsKey(attribute.Value))
  1871. // throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Value));
  1872. // Crashes when modifier is a constant, and therefore not a field in the table
  1873. // foreach (var modifier in attribute.Modifiers)
  1874. // if (!fieldmap.ContainsKey(modifier))
  1875. // throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, modifier));
  1876. if (attribute.Operator == FormulaOperator.Format)
  1877. {
  1878. var fmt = fieldmap.TryGetValue(attribute.Value, out var _value) ? _value : attribute.Value;
  1879. var others = attribute.Modifiers.Select(x => fieldmap.TryGetValue(x, out var _value) ? _value : $"\"\"");
  1880. var result = $"printf(\"{fmt}\", {string.Join(", ", others)}";
  1881. return result;
  1882. }
  1883. if (attribute.Operator == FormulaOperator.Add)
  1884. return string.Format("(IFNULL({0},0.00) + {1})",
  1885. fieldmap.TryGetValue(attribute.Value, out var _value) ? _value : attribute.Value,
  1886. string.Join(" + ", attribute.Modifiers.Select(x => fieldmap.TryGetValue(x, out var _value) ? $"IFNULL({_value},0.00)" : $"{x}")));
  1887. if (attribute.Operator == FormulaOperator.Subtract)
  1888. return string.Format("(IFNULL({0},0.00) - ({1}))",
  1889. fieldmap.TryGetValue(attribute.Value, out var _value) ? _value : attribute.Value,
  1890. string.Join(" + ", attribute.Modifiers.Select(x => fieldmap.TryGetValue(x, out var _value) ? $"IFNULL({_value},0.00)" : $"{x}")));
  1891. if (attribute.Operator == FormulaOperator.Multiply)
  1892. return string.Format("(IFNULL({0},0.00) * {1})",
  1893. fieldmap.TryGetValue(attribute.Value, out var _value) ? _value : attribute.Value,
  1894. string.Join(" * ", attribute.Modifiers.Select(x => fieldmap.TryGetValue(x, out var _value) ? $"IFNULL({_value},0.00)" : $"{x}")));
  1895. if (attribute.Operator == FormulaOperator.Divide)
  1896. {
  1897. var result = string.Format("IFNULL({0},0.00)", fieldmap.TryGetValue(attribute.Value, out var _v) ? _v : attribute.Value);
  1898. foreach (var modifier in attribute.Modifiers)
  1899. result = string.Format("({0} / {1})", result, fieldmap.TryGetValue(modifier, out var _value) ? $"IFNULL({_value},1.00)" : $"{modifier}");
  1900. return result;
  1901. }
  1902. if (attribute.Operator == FormulaOperator.Maximum)
  1903. {
  1904. var parameters = attribute.Modifiers.Select(m => fieldmap.TryGetValue(m, out var _value) ? $"IFNULL({_value},0.00)" : $"{m}");
  1905. var primary = fieldmap.TryGetValue(attribute.Value, out var _v) ? _v : attribute.Value;
  1906. var result = $"MAX({primary}, {String.Join(", ", parameters)})";
  1907. return result;
  1908. }
  1909. if (attribute.Operator == FormulaOperator.Minumum)
  1910. {
  1911. var parameters = attribute.Modifiers.Select(m => fieldmap.TryGetValue(m, out var _value) ? $"IFNULL({_value},0.00)" : $"{m}");
  1912. var primary = fieldmap.TryGetValue(attribute.Value, out var _v) ? _v : attribute.Value;
  1913. var result = $"MIN({primary}, {String.Join(", ", parameters)})";
  1914. return result;
  1915. }
  1916. throw new Exception(string.Format("Calculation Type [{0}.{1}] not found", columnname, attribute.GetType().Name));
  1917. }
  1918. private string GetCondition(ConditionAttribute attribute, Dictionary<string, string> fieldmap, string columnname)
  1919. {
  1920. var intf = attribute.Calculator.GetType().GetInterfaces()
  1921. .FirstOrDefault(x => x.Name.StartsWith("ICondition") && x.GenericTypeArguments.Length.Equals(3));
  1922. if (intf is null)
  1923. throw new Exception($"Attribute calculate {attribute.Calculator} is not an ICondition");
  1924. var valuetype = intf.GenericTypeArguments[1];
  1925. var defvalue = valuetype.GetDefault();
  1926. var _left = fieldmap.TryGetValue(attribute.Left, out var _leftvalue)
  1927. ? _leftvalue
  1928. : EscapeValue(attribute.Left, valuetype);
  1929. //throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Left));
  1930. var condition = "";
  1931. if (attribute.Condition == Condition.Equals)
  1932. condition = "=";
  1933. else if (attribute.Condition == Condition.NotEqual)
  1934. condition = "<>";
  1935. else if (attribute.Condition == Condition.GreaterThan)
  1936. condition = ">";
  1937. else if (attribute.Condition == Condition.GreaterThanOrEqualTo)
  1938. condition = ">=";
  1939. else if (attribute.Condition == Condition.LessThan)
  1940. condition = "<";
  1941. else if (attribute.Condition == Condition.LessThanOrEqualTo)
  1942. condition = "<=";
  1943. else
  1944. throw new Exception(string.Format("{0}.{1} is not a valid condition", columnname, attribute.Calculator.GetType().Name));
  1945. //if (!fieldmap.ContainsKey(attribute.Right))
  1946. // throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.Right));
  1947. var _right = fieldmap.TryGetValue(attribute.Right, out var _rightvalue)
  1948. ? _rightvalue
  1949. : EscapeValue(attribute.Right, valuetype);
  1950. //if (!fieldmap.ContainsKey(attribute.True))
  1951. // throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.True));
  1952. var _true = fieldmap.TryGetValue(attribute.True, out var _truevalue)
  1953. ? _truevalue
  1954. : EscapeValue(attribute.True, valuetype);
  1955. //if (!fieldmap.ContainsKey(attribute.False))
  1956. // throw new Exception(string.Format("{0}.{1} -> {2} does not exist", columnname, attribute.GetType().Name, attribute.False));
  1957. var _false = fieldmap.TryGetValue(attribute.False, out var _falsevalue)
  1958. ? _falsevalue
  1959. : EscapeValue(attribute.False, valuetype);
  1960. return string.Format("CASE WHEN COALESCE({0},{1}) {2} {3} THEN {4} ELSE {5} END", _left, defvalue, condition,
  1961. _right, _true, _false);
  1962. }
  1963. 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)
  1964. {
  1965. switch(node)
  1966. {
  1967. case IComplexFormulaAggregateNode agg:
  1968. var expr = agg.GetExpression();
  1969. var links = agg.GetLinks();
  1970. var aggCol = "$AGGREGATE_0";
  1971. var subCols = new List<IBaseColumn>
  1972. {
  1973. expr.ToColumn(aggCol)
  1974. };
  1975. foreach (var key in links.Keys)
  1976. subCols.Add(Column.Create(agg.TAggregate, key));
  1977. var aggregates = new Dictionary<string, string>
  1978. {
  1979. { aggCol, GetCalculation(agg.GetCalculation(), aggCol, agg.TResult) }
  1980. };
  1981. var subquery = string.Format("({0})",
  1982. PrepareSelectNonGeneric(agg.TAggregate,
  1983. command,
  1984. (char)(prefix + 1),
  1985. agg.GetFilter(),
  1986. subCols,
  1987. sort: null,
  1988. aggregates,
  1989. null, null, false, useparams));
  1990. var alias = tables.Count + 1;
  1991. var linkList = string.Join(" , ", links.Keys.Select(x => string.Format("{0}{1}.{2}", prefix, alias, x)));
  1992. // Don't add the same table with equivalent SQL twice.
  1993. var tuple = tables.FirstOrDefault(x =>
  1994. x.Item1.Equals(subquery) && x.Item4.Equals(linkList) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  1995. if (tuple == null)
  1996. {
  1997. var joins = new List<string>();
  1998. foreach (var (key, link) in links)
  1999. joins.Add(string.Format("IFNULL({0}{1}.[{2}],'') = IFNULL({0}1.[{3}],'')", prefix, alias, key, link));
  2000. var join = string.Format("LEFT OUTER JOIN {0} {1}{2} ON {3}", subquery, prefix, alias,
  2001. string.Join(" AND ", joins));
  2002. tuple = new Tuple<string, string, string, string>(subquery, prefix + alias.ToString(), join, linkList);
  2003. tables.Add(tuple);
  2004. }
  2005. return string.Format("{0}.[{1}]", tuple.Item2, aggCol);
  2006. case IComplexFormulaConstantNode constantNode:
  2007. var constant = constantNode.GetConstant();
  2008. if (constant is FilterConstant filterConstant)
  2009. {
  2010. return GetFilterConstant(filterConstant);
  2011. }
  2012. else
  2013. {
  2014. if (useparams)
  2015. {
  2016. var encoded = Encode(constant, type);
  2017. var sParam = string.Format("@p{0}", command.Parameters.Count);
  2018. command.Parameters.AddWithValue(sParam, encoded);
  2019. return sParam;
  2020. }
  2021. else
  2022. {
  2023. return EscapeValue(constant);
  2024. }
  2025. }
  2026. case IComplexFormulaFieldNode field:
  2027. var col = Column.Create(type, field.GetField());
  2028. CheckColumn(type, columns, col.Property);
  2029. LoadFieldsAndTables(command, type, prefix, fieldmap, tables, columns, col, useparams);
  2030. return fieldmap[col.Name];
  2031. case IComplexFormulaFormulaNode formula:
  2032. var operands = new List<string>();
  2033. var op = formula.GetOperator();
  2034. bool bFirst = true;
  2035. foreach (var field in formula.GetOperands())
  2036. {
  2037. var operand = LoadComplexFormula(command, type, prefix, fieldmap, tables, columns, field, useparams);
  2038. if (op == FormulaOperator.Divide)
  2039. operands.Add($"IFNULL({operand}, {(bFirst ? 0.00 : 1.00)})");
  2040. else if (op == FormulaOperator.Format)
  2041. operands.Add(operand);
  2042. else
  2043. operands.Add($"IFNULL({operand}, 0.00)");
  2044. bFirst = true;
  2045. }
  2046. switch (op)
  2047. {
  2048. case FormulaOperator.Format:
  2049. var fmt = operands.First();
  2050. var others = operands.Skip(1);
  2051. var result = $"printf({fmt}, {string.Join(", ", others)})";
  2052. return result;
  2053. case FormulaOperator.Add:
  2054. if(formula.TResult == typeof(decimal))
  2055. {
  2056. return $"DECIMAL_ADD({string.Join(',', operands)})";
  2057. }
  2058. else
  2059. {
  2060. if(operands.Count == 0)
  2061. {
  2062. return "0.00";
  2063. }
  2064. {
  2065. return $"({string.Join('+', operands)})";
  2066. }
  2067. }
  2068. case FormulaOperator.Subtract:
  2069. if (formula.TResult == typeof(decimal))
  2070. {
  2071. return $"DECIMAL_SUB({string.Join(',', operands)})";
  2072. }
  2073. else
  2074. {
  2075. if (operands.Count == 0)
  2076. {
  2077. return "0.00";
  2078. }
  2079. else if (operands.Count == 1)
  2080. {
  2081. return $"(-{operands[0]})";
  2082. }
  2083. else
  2084. {
  2085. return $"({string.Join('-', operands)})";
  2086. }
  2087. }
  2088. case FormulaOperator.Multiply:
  2089. if (formula.TResult == typeof(decimal))
  2090. {
  2091. return $"DECIMAL_MUL({string.Join(',', operands)})";
  2092. }
  2093. else
  2094. {
  2095. if (operands.Count == 0)
  2096. {
  2097. return "1.00";
  2098. }
  2099. else
  2100. {
  2101. return $"({string.Join('*', operands)})";
  2102. }
  2103. }
  2104. case FormulaOperator.Divide:
  2105. if (formula.TResult == typeof(decimal))
  2106. {
  2107. return $"DECIMAL_DIV({string.Join(',', operands)})";
  2108. }
  2109. else
  2110. {
  2111. if (operands.Count == 0)
  2112. {
  2113. return "1.00";
  2114. }
  2115. else if (operands.Count == 1)
  2116. {
  2117. return $"(1.00 / {operands[0]})";
  2118. }
  2119. else
  2120. {
  2121. return $"({string.Join('/', operands)})";
  2122. }
  2123. }
  2124. case FormulaOperator.Maximum:
  2125. return $"MAX({string.Join(',', operands)})";
  2126. case FormulaOperator.Minumum:
  2127. return $"MIN({string.Join(',', operands)})";
  2128. case FormulaOperator.None:
  2129. case FormulaOperator.Constant:
  2130. default:
  2131. throw new Exception($"Invalid formula of type {op}.");
  2132. }
  2133. case IComplexFormulaConditionNode condition:
  2134. var left = LoadComplexFormula(command, type, prefix, fieldmap, tables, columns, condition.Left, useparams);
  2135. var right = LoadComplexFormula(command, type, prefix, fieldmap, tables, columns, condition.Right, useparams);
  2136. var trueVal = LoadComplexFormula(command, type, prefix, fieldmap, tables, columns, condition.True, useparams);
  2137. var falseVal = LoadComplexFormula(command, type, prefix, fieldmap, tables, columns, condition.False, useparams);
  2138. var coalesce = condition.Coalesce != null
  2139. ? EscapeValue(condition.Coalesce)
  2140. : EscapeValue(condition.TCondition.GetDefault());
  2141. var conditionOp = condition.Condition switch
  2142. {
  2143. Condition.Equals => "=",
  2144. Condition.NotEqual => "<>",
  2145. Condition.GreaterThan => ">",
  2146. Condition.GreaterThanOrEqualTo => ">=",
  2147. Condition.LessThan => "<",
  2148. Condition.LessThanOrEqualTo => "<=",
  2149. _ => throw new Exception($"{condition.Condition} is not a valid condition")
  2150. };
  2151. return $"(CASE WHEN COALESCE({left}, {coalesce}) {conditionOp} {right} THEN " +
  2152. $" {trueVal} ELSE {falseVal} END)";
  2153. default:
  2154. throw new Exception($"Unknown ComplexFormula type {node.GetType()}");
  2155. }
  2156. }
  2157. private void LoadFieldsAndTables(SQLiteCommand command, Type type, char prefix, Dictionary<string, string> fieldmap,
  2158. List<Tuple<string, string, string, string>> tables, List<string> columns, IBaseColumn baseCol, bool useparams)
  2159. {
  2160. if (fieldmap.ContainsKey(baseCol.Name))
  2161. return;
  2162. var newprefix = (char)(prefix + 1);
  2163. switch (baseCol)
  2164. {
  2165. case IComplexColumn complexCol:
  2166. fieldmap[baseCol.Name] = LoadComplexFormula(command, type, prefix, fieldmap, tables, columns, complexCol.Formula, false);
  2167. break;
  2168. case IColumn col:
  2169. var property = DatabaseSchema.Property(type, col.Property);
  2170. if(property is CustomProperty)
  2171. {
  2172. fieldmap[baseCol.Name] = $"{prefix}1.[{col.Property}]";
  2173. }
  2174. else if(property is StandardProperty)
  2175. {
  2176. if(property.Parent is null)
  2177. {
  2178. if(property.GetAttribute<ComplexFormulaAttribute>() is ComplexFormulaAttribute form)
  2179. {
  2180. var formula = form.Generator.GetFormula();
  2181. LoadFieldsAndTables(command, type, prefix, fieldmap, tables, columns, formula.ToColumn(baseCol.Name), useparams);
  2182. }
  2183. else if (property.GetAttribute<AggregateAttribute>() is AggregateAttribute agg)
  2184. {
  2185. bool internalaggregate = agg.Calculator.GetType().GetInterfaces()
  2186. .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICoreAggregate<,>));
  2187. if (!internalaggregate)
  2188. {
  2189. var scols = new Dictionary<string, string> { { agg.Aggregate, GetCalculation(agg.Calculation, baseCol.Name, baseCol.Type) } };
  2190. var linkedtype = agg.Source;
  2191. /*var siblings = columns.Where(x => !x.Equals(baseCol.Name) && x.Split('.').First().Equals(bits.First()))
  2192. .Select(x => string.Join(".", x.Split('.').Skip(1))).ToList();
  2193. foreach (var sibling in siblings)
  2194. {
  2195. var sprop = CoreUtils.GetProperty(type, sibling);
  2196. var sattr = prop.GetCustomAttributes().FirstOrDefault(x => x.GetType().Equals(typeof(AggregateAttribute)));
  2197. if (sattr is AggregateAttribute sagg)
  2198. {
  2199. scols[sagg.Aggregate] = GetCalculation(sagg, sibling);
  2200. }
  2201. }*/
  2202. var subcols = Columns.None(linkedtype);
  2203. foreach (var key in agg.Links.Keys)
  2204. subcols.Add(key);
  2205. foreach (var scol in scols.Keys)
  2206. subcols.Add(scol);
  2207. var aggFilter = agg.Filter;
  2208. var linkedtable = string.Format("({0})",
  2209. PrepareSelectNonGeneric(linkedtype, command, newprefix, aggFilter, subcols.Columns(), null, scols, null, null, false, useparams));
  2210. var alias = tables.Count + 1;
  2211. var link = string.Join(" , ", agg.Links.Keys.Select(x => string.Format("{0}{1}.{2}", prefix, alias, x)));
  2212. var tuple = tables.FirstOrDefault(x =>
  2213. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  2214. if (tuple == null)
  2215. {
  2216. var joins = new List<string>();
  2217. foreach (var key in agg.Links.Keys)
  2218. joins.Add(
  2219. string.Format("IFNULL({0}{1}.[{2}],'') = IFNULL({0}1.[{3}],'')", prefix, alias, key, agg.Links[key]));
  2220. var join = string.Format("LEFT OUTER JOIN {0} {1}{2} ON {3}", linkedtable, prefix, alias,
  2221. string.Join(" AND ", joins));
  2222. tuple = new Tuple<string, string, string, string>(linkedtable, prefix + alias.ToString(), join, link);
  2223. //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);
  2224. tables.Add(tuple);
  2225. }
  2226. //if (bits.Last().Equals("ID"))
  2227. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  2228. //else
  2229. fieldmap[baseCol.Name] = string.Format("{0}.[{1}]", tuple.Item2, agg.Aggregate);
  2230. //LoadFieldsandTables(command, agg.Type, newprefix, fieldmap, tables, columns, columnname);
  2231. //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);
  2232. //int alias = tables.Count + 1;
  2233. //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), "");
  2234. //tables.Add(tuple);
  2235. //fieldmap[columnname] = String.Format("{0}.[{1}]", tuple.Item2, agg.AggregateProperty);
  2236. }
  2237. }
  2238. else if (property.GetAttribute<FormulaAttribute>() is FormulaAttribute fnc)
  2239. {
  2240. foreach (var field in fnc.Modifiers.Prepend(fnc.Value))
  2241. {
  2242. if (CoreUtils.TryGetProperty(type,field,out var _))
  2243. {
  2244. CheckColumn(type, columns, field);
  2245. LoadFieldsAndTables(command, type, prefix, fieldmap, tables, columns,
  2246. Column.Create(type, field), useparams);
  2247. }
  2248. }
  2249. fieldmap[baseCol.Name] = GetFunction(fnc, fieldmap, baseCol.Name);
  2250. }
  2251. else if(property.GetAttribute<ConditionAttribute>() is ConditionAttribute cnd)
  2252. {
  2253. var cndmap = new Dictionary<string, string>();
  2254. if (CheckColumn(type, columns, cnd.Left))
  2255. LoadFieldsAndTables(command, type, prefix, cndmap, tables, columns, Column.Create(type, cnd.Left), useparams);
  2256. if (CheckColumn(type, columns, cnd.Right))
  2257. LoadFieldsAndTables(command, type, prefix, cndmap, tables, columns, Column.Create(type, cnd.Right), useparams);
  2258. if (CheckColumn(type, columns, cnd.True))
  2259. LoadFieldsAndTables(command, type, prefix, cndmap, tables, columns, Column.Create(type, cnd.True), useparams);
  2260. if (CheckColumn(type, columns, cnd.False))
  2261. LoadFieldsAndTables(command, type, prefix, cndmap, tables, columns, Column.Create(type, cnd.False), useparams);
  2262. fieldmap[baseCol.Name] = GetCondition(cnd, cndmap, baseCol.Name);
  2263. }
  2264. else
  2265. {
  2266. fieldmap[baseCol.Name] = string.Format("{0}1.[{1}]", prefix, baseCol.Name);
  2267. }
  2268. }
  2269. else
  2270. {
  2271. var bits = property.Name.Split('.');
  2272. var prop = type.GetProperty(bits.First());
  2273. if (prop != null)
  2274. {
  2275. var combinecount = 1;
  2276. while (prop.PropertyType.HasInterface<IEnclosedEntity>())
  2277. {
  2278. combinecount++;
  2279. prop = CoreUtils.GetProperty(type, string.Join(".", bits.Take(combinecount)));
  2280. }
  2281. var entityLinkInterface = prop.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>));
  2282. if (entityLinkInterface is not null)
  2283. {
  2284. var linkedType = entityLinkInterface.GenericTypeArguments[0];
  2285. var enclosingProperty = string.Join('.', bits.Take(combinecount)) + ".";
  2286. var remoteProperty = string.Join('.', bits.Skip(combinecount));
  2287. var remote = linkedType.GetProperty(remoteProperty);
  2288. // Are there any other properties for this link? These will form the columns for our subquery
  2289. var siblings = columns.Where(x => x.StartsWith(enclosingProperty))
  2290. .Select(x => x[enclosingProperty.Length..]).ToList();
  2291. if (remote != null && !siblings.Contains(remote.Name))
  2292. siblings.Add(remote.Name);
  2293. if(prop.GetCustomAttribute<ChildEntityAttribute>() is ChildEntityAttribute child)
  2294. {
  2295. var parent = child.Calculator.ParentColumn;
  2296. if (!siblings.Contains(nameof(Entity.ID)))
  2297. siblings.Insert(0, nameof(Entity.ID));
  2298. if (!siblings.Contains(parent))
  2299. siblings.Add(parent);
  2300. var subcols = Columns.None(linkedType).Add(siblings);
  2301. var subPrefix = (char)(newprefix + 1);
  2302. var innerSQL = string.Format("({0})",
  2303. PrepareSelectNonGeneric(
  2304. linkedType,
  2305. command,
  2306. subPrefix,
  2307. child.Calculator.Filter,
  2308. subcols.Columns(),
  2309. child.Calculator.Sort,
  2310. null,
  2311. null,
  2312. null,
  2313. false,
  2314. useparams));
  2315. var linkedTable = $"(SELECT {string.Join(", ", siblings.Select(x => $"{newprefix}1.[{x}] as [{x}]"))}"
  2316. + $" FROM {innerSQL} {newprefix}1"
  2317. + $" GROUP BY [{parent}])";
  2318. var link = string.Format("{0}.ID", prop.Name);
  2319. var tuple = tables.FirstOrDefault(x =>
  2320. x.Item1.Equals(linkedTable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  2321. if (tuple is null)
  2322. {
  2323. var alias = tables.Count + 1;
  2324. tuple = new Tuple<string, string, string, string>(
  2325. linkedTable,
  2326. prefix + alias.ToString(),
  2327. string.Format(
  2328. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[{3}] = {1}1.[ID]",
  2329. linkedTable,
  2330. prefix,
  2331. alias,
  2332. parent
  2333. ),
  2334. link
  2335. );
  2336. tables.Add(tuple);
  2337. }
  2338. //if (bits.Last().Equals("ID"))
  2339. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  2340. //else
  2341. fieldmap[baseCol.Name] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  2342. foreach (var sibling in siblings)
  2343. {
  2344. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  2345. if (!subcol.Equals(baseCol.Name))
  2346. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  2347. }
  2348. }
  2349. else
  2350. {
  2351. if (siblings.Count.Equals(1) && siblings.First().Equals("ID"))
  2352. {
  2353. fieldmap[baseCol.Name] = string.Format("{0}1.[{1}]", prefix, baseCol.Name);
  2354. }
  2355. else
  2356. {
  2357. if (!siblings.Contains("ID"))
  2358. siblings.Insert(0, "ID");
  2359. var subcols = Columns.None(linkedType).Add(siblings);
  2360. var linkedtable = string.Format("({0})",
  2361. PrepareSelectNonGeneric(linkedType, command, newprefix, null, subcols.Columns(), null, null, null, null, false, useparams));
  2362. var link = string.Format("{0}.ID", prop.Name);
  2363. var tuple = tables.FirstOrDefault(x =>
  2364. x.Item1.Equals(linkedtable) && x.Item4.Equals(link) && !x.Item2.Equals(string.Format("{0}1", prefix)));
  2365. if (tuple == null)
  2366. {
  2367. var alias = tables.Count + 1;
  2368. tuple = new Tuple<string, string, string, string>(
  2369. linkedtable,
  2370. prefix + alias.ToString(),
  2371. string.Format(
  2372. "LEFT OUTER JOIN {0} {1}{2} ON {1}{2}.[ID] = {1}1.[{3}.ID]",
  2373. linkedtable,
  2374. prefix,
  2375. alias,
  2376. string.Join(".", bits.Take(combinecount)) //prop.Name
  2377. ),
  2378. link
  2379. );
  2380. tables.Add(tuple);
  2381. }
  2382. //if (bits.Last().Equals("ID"))
  2383. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  2384. //else
  2385. fieldmap[baseCol.Name] = string.Format("{0}.[{1}]", tuple.Item2, string.Join(".", bits.Skip(combinecount)));
  2386. foreach (var sibling in siblings)
  2387. {
  2388. var subcol = string.Format("{0}.{1}", string.Join(".", bits.Take(combinecount)), sibling);
  2389. if (!subcol.Equals(baseCol.Name))
  2390. fieldmap[subcol] = string.Format("{0}.[{1}]", tuple.Item2, sibling);
  2391. }
  2392. }
  2393. }
  2394. }
  2395. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  2396. {
  2397. fieldmap[baseCol.Name] = string.Format("{0}1.[{1}]", prefix, baseCol.Name);
  2398. }
  2399. else
  2400. {
  2401. fieldmap[baseCol.Name] = string.Format("{0}1.[{1}]", prefix, baseCol.Name);
  2402. }
  2403. }
  2404. else
  2405. {
  2406. fieldmap[baseCol.Name] = baseCol.Name;
  2407. }
  2408. }
  2409. }
  2410. else
  2411. {
  2412. //IProperty customprop = DataModel.Property(type, columnname);
  2413. //if (customprop != null)
  2414. // fieldmap[columnname] = String.Format("{0}1.[{1}]", prefix, columnname);
  2415. //else
  2416. fieldmap[baseCol.Name] = baseCol.Name;
  2417. }
  2418. break;
  2419. }
  2420. }
  2421. private static bool CheckColumn(Type type, List<string> columns, string column)
  2422. {
  2423. if (CoreUtils.TryGetProperty(type, column, out _) && !columns.Contains(column))
  2424. {
  2425. columns.Add(column);
  2426. return true;
  2427. }
  2428. return false;
  2429. }
  2430. public void AddFilterFields(IFilter? filter, List<string> fields)
  2431. {
  2432. if (filter == null)
  2433. return;
  2434. if (filter.Operator != Operator.None && filter.Operator != Operator.All)
  2435. {
  2436. if (!fields.Contains(filter.Property))
  2437. fields.Add(filter.Property);
  2438. }
  2439. foreach (var and in filter.Ands)
  2440. AddFilterFields(and, fields);
  2441. foreach (var or in filter.Ors)
  2442. AddFilterFields(or, fields);
  2443. }
  2444. public void AddSortFields(ISortOrder? sort, List<string> fields)
  2445. {
  2446. if (sort == null)
  2447. return;
  2448. var exp = CoreUtils.GetFullPropertyName(CoreUtils.ExtractMemberExpression(sort.Expression), ".");
  2449. if (!fields.Contains(exp))
  2450. fields.Add(exp);
  2451. foreach (var then in sort.Thens)
  2452. AddSortFields(then, fields);
  2453. }
  2454. public enum AggregateType
  2455. {
  2456. None,
  2457. Sum,
  2458. Count
  2459. }
  2460. public string PrepareSelectNonGeneric(
  2461. Type T,
  2462. SQLiteCommand command,
  2463. char prefix,
  2464. IFilter? filter,
  2465. IEnumerable<IBaseColumn>? columns,
  2466. ISortOrder? sort,
  2467. Dictionary<string, string>? aggregates,
  2468. Dictionary<string, object?>? constants,
  2469. CoreRange? range,
  2470. bool distinct,
  2471. bool useparams)
  2472. {
  2473. var fieldmap = new Dictionary<string, string>();
  2474. var cols = (columns ?? CoreUtils.GetColumns(T, null).Columns()).AsIList();
  2475. // Contains every columns we need to load from the database, including for filters, columns and sortorders.
  2476. var fields = new List<string>();
  2477. fields.AddRange(cols.OfType<IColumn>().Select(x => x.Property));
  2478. AddFilterFields(filter, fields);
  2479. AddSortFields(sort, fields);
  2480. var tables = new List<Tuple<string, string, string, string>>();
  2481. var condition = "";
  2482. var sortorder = "";
  2483. var entityName = T.EntityName().Split('.').Last();
  2484. tables.Add(new Tuple<string, string, string, string>(
  2485. entityName,
  2486. $"{prefix}1",
  2487. $"{entityName} {prefix}1",
  2488. "")
  2489. );
  2490. foreach (var column in cols)
  2491. {
  2492. LoadFieldsAndTables(command, T, prefix, fieldmap, tables, fields, column, useparams);
  2493. }
  2494. var parameters = new Dictionary<string, object>();
  2495. condition = GetFilterClauseNonGeneric(T, command, prefix, filter, tables, fieldmap, fields, useparams);
  2496. sortorder = GetSortClauseNonGeneric(T, command, sort, prefix, tables, fieldmap, fields, useparams);
  2497. var combined = new SortedDictionary<string, string>();
  2498. fields.Clear();
  2499. foreach (var column in cols)
  2500. if (fieldmap.TryGetValue(column.Name, out string? value))
  2501. {
  2502. if (aggregates != null && aggregates.TryGetValue(column.Name, out var aggregateFnc))
  2503. {
  2504. var _col = string.Format(aggregateFnc, value);
  2505. combined[constants != null ? column.Name : String.Format("{0:D8}", combined.Keys.Count)] =
  2506. string.Format("{0} as [{1}]", _col, column.Name);
  2507. }
  2508. else
  2509. combined[constants != null ? column.Name : String.Format("{0:D8}", combined.Keys.Count)] = string.Format("{0} as [{1}]", value, column.Name);
  2510. }
  2511. if (constants != null)
  2512. {
  2513. foreach(var (column, value) in constants)
  2514. {
  2515. combined[column] = string.Format("{0} as [{1}]", EscapeValue(value), column);
  2516. }
  2517. }
  2518. var result = new List<string>();
  2519. result.Add("SELECT");
  2520. if (distinct)
  2521. result.Add("DISTINCT");
  2522. result.Add(string.Join(", ", combined.Values));
  2523. result.Add("FROM");
  2524. result.AddRange(tables.Select(x => x.Item3));
  2525. if (range?.Type == CoreRangeType.Database && range.Offset != 0)
  2526. {
  2527. var subColumns = Columns.None(T).Add("ID");
  2528. var subQuery = PrepareSelectNonGeneric(T, command, 'A', filter, subColumns.Columns(), sort, null, null, CoreRange.Database(range.Offset), false, useparams);
  2529. var idColumn = $"{prefix}1.[ID]";
  2530. var offsetCondition = $"({idColumn} NOT IN ({subQuery}))";
  2531. if (!condition.IsNullOrWhiteSpace())
  2532. {
  2533. condition = $"({offsetCondition} and {condition})";
  2534. }
  2535. else
  2536. {
  2537. condition = offsetCondition;
  2538. }
  2539. }
  2540. if (!string.IsNullOrWhiteSpace(condition))
  2541. {
  2542. result.Add("WHERE");
  2543. result.Add(condition);
  2544. }
  2545. if (!string.IsNullOrWhiteSpace(sortorder))
  2546. {
  2547. result.Add("ORDER BY");
  2548. result.Add(sortorder);
  2549. }
  2550. if (aggregates != null)
  2551. {
  2552. var str = string.Join(", ",
  2553. fieldmap.Where(x => cols.Any(y => y.Name.Equals(x.Key)) && !aggregates.ContainsKey(x.Key)).Select(f => f.Value));
  2554. if (!string.IsNullOrWhiteSpace(str))
  2555. {
  2556. result.Add("GROUP BY");
  2557. result.Add(str);
  2558. }
  2559. }
  2560. if (range?.Type == CoreRangeType.Database)
  2561. {
  2562. if (range.Limit != int.MaxValue)
  2563. result.Add($"LIMIT {range.Limit}");
  2564. //if (range.Offset != 0)
  2565. // result.Add($"OFFSET {range.Offset}");
  2566. }
  2567. return string.Join(" ", result);
  2568. }
  2569. public string PrepareSelect<T>(SQLiteCommand command, char prefix, Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort,
  2570. Dictionary<string, string>? aggregates, Dictionary<string, object?>? constants, CoreRange? range, bool distinct, bool useparams) where T : Entity
  2571. => PrepareSelectNonGeneric(typeof(T), command, prefix, filter, columns, sort, aggregates, constants, range, distinct, useparams);
  2572. private void PrepareUpsertNonGeneric(Type T, SQLiteCommand command, Entity item)
  2573. {
  2574. command.CommandText = "";
  2575. command.Parameters.Clear();
  2576. if (item.ID == Guid.Empty)
  2577. item.ID = Guid.NewGuid();
  2578. var insert = item.GetValues(true);
  2579. var update = item.GetValues(false);
  2580. var insertfields = new List<string>();
  2581. var insertvalues = new List<string>();
  2582. var updatecommands = new List<string>();
  2583. var iParam = 0;
  2584. foreach (var (key, v) in insert)
  2585. {
  2586. if (v is UserProperties)
  2587. continue;
  2588. var sParam = string.Format("@p{0}", iParam++);
  2589. object? value = null;
  2590. try
  2591. {
  2592. value = Encode(v, v?.GetType());
  2593. }
  2594. catch (Exception e)
  2595. {
  2596. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2597. }
  2598. command.Parameters.AddWithValue(sParam, value);
  2599. insertfields.Add(string.Format("[{0}]", key));
  2600. insertvalues.Add(sParam);
  2601. if (update.ContainsKey(key))
  2602. if (!key.Equals("ID"))
  2603. updatecommands.Add(string.Format("[{0}]={1}", key, sParam));
  2604. }
  2605. var particles = new List<string>
  2606. {
  2607. "INSERT INTO",
  2608. T.EntityName().Split('.').Last(),
  2609. "(",
  2610. string.Join(",", insertfields),
  2611. ")",
  2612. "VALUES",
  2613. "(",
  2614. string.Join(",", insertvalues),
  2615. ")"
  2616. };
  2617. if (updatecommands.Count != 0)
  2618. particles.Add("ON CONFLICT([ID]) DO UPDATE SET " + string.Join(", ", updatecommands));
  2619. else
  2620. particles.Add("ON CONFLICT DO NOTHING");
  2621. command.CommandText = string.Join(" ", particles);
  2622. }
  2623. private void PrepareUpsert<T>(SQLiteCommand command, T item) where T : Entity
  2624. => PrepareUpsertNonGeneric(typeof(T), command, item);
  2625. public void PrepareDelete<T>(SQLiteCommand command, T item) where T : Entity
  2626. {
  2627. command.CommandText = string.Format("DELETE FROM {0} WHERE [ID] = @p0", typeof(T).EntityName().Split('.').Last());
  2628. command.Parameters.Clear();
  2629. command.Parameters.AddWithValue("@p0", Encode(item.ID, typeof(Guid)));
  2630. }
  2631. #endregion
  2632. #region CRUD Operations
  2633. public static object[] GetValues(IDataReader reader, int count)
  2634. {
  2635. var result = new object[count];
  2636. reader.GetValues(result);
  2637. return result;
  2638. }
  2639. #region List
  2640. public IEnumerable<object[]> List<T>(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, CoreRange? range = null) where T : Entity, new()
  2641. {
  2642. //Dictionary<String, TimeSpan> stopwatch = new Dictionary<string, TimeSpan>();
  2643. //Stopwatch sw = new Stopwatch();
  2644. //sw.Start();
  2645. var cols = CoreUtils.GetColumns(columns);
  2646. //stopwatch["GetColumns"] = new TimeSpan(sw.ElapsedTicks);
  2647. //sw.Restart();
  2648. var result = new List<object[]>();
  2649. //stopwatch["MakeResult"] = new TimeSpan(sw.ElapsedTicks);
  2650. //sw.Restart();
  2651. using (var access = GetReadAccess())
  2652. {
  2653. using (var command = access.CreateCommand())
  2654. {
  2655. var sortorder = sort ?? LookupFactory.DefineSort<T>();
  2656. command.CommandText = "";
  2657. command.Parameters.Clear();
  2658. command.CommandText = PrepareSelect(command, 'A', filter, cols, sortorder, null, null, range, false, true) + ";";
  2659. using (var reader = command.ExecuteReader())
  2660. {
  2661. foreach (var row in reader)
  2662. {
  2663. var values = GetValues(reader, cols.Count);
  2664. result.Add(values);
  2665. }
  2666. reader.Close();
  2667. }
  2668. }
  2669. }
  2670. return result;
  2671. }
  2672. #endregion
  2673. #region Query
  2674. public string CreateSQL<T>(
  2675. Filter<T>? filter,
  2676. Columns<T>? columns,
  2677. SortOrder<T>? sort = null,
  2678. CoreRange? range = null,
  2679. bool distinct = false)
  2680. {
  2681. using (var access = GetReadAccess())
  2682. {
  2683. using (var command = access.CreateCommand())
  2684. {
  2685. command.CommandText = "";
  2686. command.Parameters.Clear();
  2687. var sql = PrepareSelectNonGeneric(typeof(T), command, 'A', filter, columns, sort, null, null,
  2688. range, distinct, true) + ";";
  2689. return sql;
  2690. }
  2691. }
  2692. }
  2693. private CoreTable DoQueryNonGeneric(Type T, IFilter? filter = null, IColumns? columns = null, ISortOrder? sort = null, CoreRange? range = null, bool log = false, bool distinct = false)
  2694. {
  2695. var start = DateTime.Now;
  2696. //LogReset();
  2697. //LogStart();
  2698. //LogStop("GetColumns");
  2699. var cols = CoreUtils.GetColumns(T, columns);
  2700. var blobColumns = Columns.None(T);
  2701. foreach(var column in cols)
  2702. {
  2703. var prop = DatabaseSchema.Property(T, column.Property);
  2704. if (prop is not null && prop.HasAttribute<ExternalStorageAttribute>())
  2705. {
  2706. blobColumns.Add(column);
  2707. }
  2708. }
  2709. if(blobColumns.Count > 0)
  2710. {
  2711. cols.Add("ID");
  2712. }
  2713. var result = new CoreTable(T.EntityName());
  2714. if (range?.Type == CoreRangeType.Paged)
  2715. result.Offset = range.Offset;
  2716. foreach (var col in cols)
  2717. result.Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.Type });
  2718. //LogStop("MakeTable");
  2719. using (var access = GetReadAccess())
  2720. {
  2721. using (var command = access.CreateCommand())
  2722. {
  2723. var sortorder = sort ?? LookupFactory.DefineSort(T);
  2724. command.CommandText = "";
  2725. command.Parameters.Clear();
  2726. //LogStart();
  2727. var sql = PrepareSelectNonGeneric(T, command, 'A', filter, cols.Columns(), sortorder, null, null, range, distinct, true) + ";";
  2728. command.CommandText = sql;
  2729. try
  2730. {
  2731. using (var reader = command.ExecuteReader())
  2732. {
  2733. if (reader.HasRows)
  2734. {
  2735. var rows = new List<CoreRow>();
  2736. int iRow = 0;
  2737. while (reader.Read())
  2738. {
  2739. // casting to long here to prevent integer overflows
  2740. bool exclude = range?.Type == CoreRangeType.Paged &&
  2741. ((iRow < range.Offset) || (iRow >= ((long)range.Offset + (long)range.Limit)));
  2742. if (!exclude)
  2743. {
  2744. var row = result.NewRow();
  2745. for (var i = 0; i < reader.FieldCount; i++)
  2746. try
  2747. {
  2748. var type = result.Columns[i].DataType;
  2749. if (reader.IsDBNull(i))
  2750. {
  2751. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2752. }
  2753. else if (type.IsEnum)
  2754. {
  2755. ReadAndDecodeValue(result, reader, row, i);
  2756. }
  2757. else if (type == typeof(byte))
  2758. {
  2759. row.Values.Add(reader.GetByte(i));
  2760. }
  2761. else if (type == typeof(byte[]))
  2762. {
  2763. ReadAndDecodeValue(result, reader, row, i);
  2764. }
  2765. else if (type == typeof(bool))
  2766. {
  2767. ReadAndDecodeValue(result, reader, row, i);
  2768. }
  2769. else if (type == typeof(short))
  2770. {
  2771. row.Values.Add(reader.GetInt16(i));
  2772. }
  2773. else if (type == typeof(int))
  2774. {
  2775. row.Values.Add(reader.GetInt32(i));
  2776. }
  2777. else if (type == typeof(long))
  2778. {
  2779. row.Values.Add(reader.GetInt64(i));
  2780. }
  2781. else if (type == typeof(float))
  2782. {
  2783. row.Values.Add(reader.GetFloat(i));
  2784. }
  2785. else if (type == typeof(double))
  2786. {
  2787. row.Values.Add(reader.GetDouble(i));
  2788. }
  2789. else if (type == typeof(decimal))
  2790. {
  2791. row.Values.Add(reader.GetDecimal(i));
  2792. }
  2793. else if (type == typeof(string))
  2794. {
  2795. var value = reader.GetString(i);
  2796. row.Values.Add(value != null ? value : "");
  2797. }
  2798. else if (type == typeof(DateTime))
  2799. {
  2800. ReadAndDecodeValue(result, reader, row, i);
  2801. }
  2802. else if (type == typeof(TimeSpan))
  2803. {
  2804. ReadAndDecodeValue(result, reader, row, i);
  2805. }
  2806. else if (type == typeof(Guid))
  2807. {
  2808. row.Values.Add(reader.GetGuid(i));
  2809. }
  2810. else
  2811. {
  2812. ReadAndDecodeValue(result, reader, row, i);
  2813. }
  2814. }
  2815. catch
  2816. {
  2817. row.Values.Add(result.Columns[i].DataType.GetDefault());
  2818. }
  2819. result.Rows.Add(row);
  2820. }
  2821. iRow++;
  2822. }
  2823. result.TotalRecords = iRow;
  2824. }
  2825. reader.Close();
  2826. }
  2827. }
  2828. catch (Exception e)
  2829. {
  2830. Logger.Error($"{e.Message}: {sql}");
  2831. }
  2832. //LogStop("ReadData");
  2833. //LogPrint(String.Format("Query{0}", typeof(T).Name));
  2834. }
  2835. }
  2836. foreach(var column in blobColumns.ColumnNames())
  2837. {
  2838. foreach(var row in result.Rows)
  2839. {
  2840. var id = row.Get<Guid>("ID");
  2841. var data = GetExternalData(T, column, id);
  2842. if(data is not null)
  2843. {
  2844. row.Set<byte[]>(column, data);
  2845. }
  2846. }
  2847. }
  2848. if (log)
  2849. {
  2850. var duration = DateTime.Now - start;
  2851. Logger.Send(LogType.Information, "",
  2852. string.Format("SQLite::Query<{0}>({1} cols) returns {2} rows in {3}ms", T.Name, cols.Count, result.Rows.Count,
  2853. duration.TotalMilliseconds));
  2854. }
  2855. return result;
  2856. }
  2857. private CoreTable DoQuery<T>(Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort, CoreRange? range, bool log, bool distinct)
  2858. where T : Entity, new() => DoQueryNonGeneric(typeof(T), filter, columns, sort, range, log, distinct);
  2859. public CoreTable Query(Type type, IFilter? filter, IColumns? columns, ISortOrder? sort, CoreRange? range, bool log, bool distinct)
  2860. => DoQueryNonGeneric(type, filter, columns, sort, range, log, distinct);
  2861. 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)
  2862. where T : Entity, new()
  2863. {
  2864. return DoQuery(filter, columns, sort, range, log, distinct);
  2865. }
  2866. [Obsolete]
  2867. public CoreTable QueryDeleted<T>(Deletion deletion, Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null, CoreRange? range = null, bool log = false)
  2868. where T : Entity, new()
  2869. {
  2870. if (filter != null)
  2871. filter.And(x => x.Deleted).IsEqualTo(deletion.ID);
  2872. else
  2873. filter = new Filter<T>(x => x.Deleted).IsEqualTo(deletion.ID);
  2874. return DoQuery(filter, columns, sort, range, false, false);
  2875. }
  2876. private void ReadAndDecodeValue(CoreTable result, SQLiteDataReader reader, CoreRow row, int i)
  2877. {
  2878. var value = reader.GetValue(i);
  2879. var decoded = Decode(value, result.Columns[i].DataType);
  2880. row.Values.Add(decoded);
  2881. }
  2882. public T[] Load<T>(Filter<T>? filter = null, SortOrder<T>? sort = null, CoreRange? range = null) where T : Entity, new()
  2883. {
  2884. var result = new List<T>();
  2885. var cols = CoreUtils.GetColumns<T>(null);
  2886. using (var access = GetReadAccess())
  2887. {
  2888. using (var command = access.CreateCommand())
  2889. {
  2890. try
  2891. {
  2892. command.CommandText = "";
  2893. command.Parameters.Clear();
  2894. command.CommandText = PrepareSelect(command, 'A', filter, cols, sort, null, null, range, false, true) + ";";
  2895. using (var reader = command.ExecuteReader())
  2896. {
  2897. if (reader.HasRows)
  2898. while (reader.Read())
  2899. {
  2900. var entity = new T();
  2901. entity.SetObserving(false);
  2902. for (var i = 0; i < reader.FieldCount; i++)
  2903. {
  2904. object value;
  2905. if (cols[i].Type == typeof(long) && !reader.IsDBNull(i))
  2906. value = reader.GetInt64(i);
  2907. else
  2908. value = reader.GetValue(i);
  2909. try
  2910. {
  2911. var decoded = Decode(value, cols[i].Type);
  2912. CoreUtils.SetPropertyValue(entity, cols[i].Property, decoded);
  2913. }
  2914. catch (Exception e)
  2915. {
  2916. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2917. }
  2918. }
  2919. entity.SetObserving(true);
  2920. result.Add(entity);
  2921. }
  2922. reader.Close();
  2923. }
  2924. }
  2925. catch (Exception e)
  2926. {
  2927. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2928. }
  2929. }
  2930. }
  2931. return result.ToArray();
  2932. }
  2933. #endregion
  2934. #region Save
  2935. private static readonly Dictionary<Type, IProperty[]> _externalProperties = new Dictionary<Type, IProperty[]>();
  2936. private static IProperty[] GetExternalProperties(Type T)
  2937. {
  2938. if(!_externalProperties.TryGetValue(T, out var properties))
  2939. {
  2940. lock (_externalProperties)
  2941. {
  2942. properties = DatabaseSchema.Properties(T).Where(x => x.HasAttribute<ExternalStorageAttribute>()).ToArray();
  2943. _externalProperties.TryAdd(T, properties);
  2944. }
  2945. }
  2946. return properties;
  2947. }
  2948. private void OnSaveNonGeneric(Type T, Entity entity)
  2949. {
  2950. var props = GetExternalProperties(T);
  2951. List<(IProperty, byte[])>? data = null;
  2952. if (props.Any())
  2953. {
  2954. data = new List<(IProperty, byte[])>();
  2955. foreach(var prop in props)
  2956. {
  2957. var value = prop.Getter()(entity) as byte[];
  2958. if(value is not null && value.Length > 0)
  2959. {
  2960. data.Add(new(prop, value));
  2961. prop.Setter()(entity, Array.Empty<byte>());
  2962. }
  2963. }
  2964. }
  2965. using var access = GetWriteAccess();
  2966. using var command = access.CreateCommand();
  2967. PrepareUpsertNonGeneric(T, command, entity);
  2968. command.ExecuteNonQuery();
  2969. if(data is not null)
  2970. {
  2971. foreach(var (prop, value) in data)
  2972. {
  2973. SaveExternalData(T, prop.Name, entity.ID, value);
  2974. prop.Setter()(entity, value);
  2975. }
  2976. }
  2977. }
  2978. private void OnSaveNonGeneric(Type T, IEnumerable<Entity> entities)
  2979. {
  2980. // Casting to IList so that we can use it multiple times.
  2981. entities = entities.AsIList();
  2982. if (!entities.Any())
  2983. return;
  2984. var props = GetExternalProperties(T);
  2985. List<(IProperty, List<(Entity, byte[])>)>? data = null;
  2986. if (props.Any())
  2987. {
  2988. data = new List<(IProperty, List<(Entity, byte[])>)>();
  2989. foreach(var prop in props)
  2990. {
  2991. var lst = new List<(Entity, byte[])>();
  2992. foreach(var entity in entities)
  2993. {
  2994. var value = prop.Getter()(entity) as byte[];
  2995. if(value is not null && value.Length > 0)
  2996. {
  2997. lst.Add((entity, value));
  2998. prop.Setter()(entity, Array.Empty<byte>());
  2999. }
  3000. }
  3001. data.Add(new(prop, lst));
  3002. }
  3003. }
  3004. using var access = GetWriteAccess();
  3005. using var transaction = access.BeginTransaction();
  3006. try
  3007. {
  3008. using var command = access.CreateCommand();
  3009. foreach (var entity in entities)
  3010. {
  3011. PrepareUpsertNonGeneric(T, command, entity);
  3012. command.ExecuteNonQuery();
  3013. }
  3014. transaction.Commit();
  3015. if(data is not null)
  3016. {
  3017. foreach(var (property, list) in data)
  3018. {
  3019. foreach(var (entity, value) in list)
  3020. {
  3021. SaveExternalData(T, property.Name, entity.ID, value);
  3022. property.Setter()(entity, value);
  3023. }
  3024. }
  3025. }
  3026. }
  3027. catch (Exception)
  3028. {
  3029. transaction.Rollback();
  3030. throw;
  3031. }
  3032. }
  3033. private void OnSave<T>(T entity) where T : Entity
  3034. => OnSaveNonGeneric(typeof(T), entity);
  3035. public static bool CanSave(Type T)
  3036. {
  3037. if (DbFactory.IsReadOnly)
  3038. {
  3039. if (T.IsAssignableTo(typeof(License)) || T.IsAssignableTo(typeof(UserTracking)))
  3040. return true;
  3041. DbFactory.LogReadOnly();
  3042. throw new DbLockedException();
  3043. }
  3044. return true;
  3045. }
  3046. public static bool CanSave<T>() => CanSave(typeof(T));
  3047. public void Save(Type type, Entity entity)
  3048. {
  3049. if (!CanSave(type))
  3050. {
  3051. return;
  3052. }
  3053. OnSaveNonGeneric(type, entity);
  3054. }
  3055. public void Save(Type type, IEnumerable<Entity> entities)
  3056. {
  3057. if (!CanSave(type))
  3058. {
  3059. return;
  3060. }
  3061. OnSaveNonGeneric(type, entities);
  3062. }
  3063. public void Save<T>(IEnumerable<T> entities) where T : Entity => Save(typeof(T), entities);
  3064. public void Save<T>(T entity) where T : Entity => Save(typeof(T), entity);
  3065. #endregion
  3066. #region Delete
  3067. public void Purge<T>(T entity) where T : Entity
  3068. {
  3069. if (!CanSave<T>()) return;
  3070. using var access = GetWriteAccess();
  3071. using var command = access.CreateCommand();
  3072. PrepareDelete(command, entity);
  3073. var rows = command.ExecuteNonQuery();
  3074. }
  3075. public void Purge<T>(IEnumerable<T> entities) where T : Entity
  3076. {
  3077. if (!CanSave<T>()) return;
  3078. // Casting to IList so that we can use it multiple times.
  3079. entities = entities.AsIList();
  3080. if (!entities.Any())
  3081. return;
  3082. using var access = GetWriteAccess();
  3083. using var transaction = access.BeginTransaction();
  3084. try
  3085. {
  3086. using (var command = access.CreateCommand())
  3087. {
  3088. foreach (var entity in entities)
  3089. {
  3090. PrepareDelete(command, entity);
  3091. var rows = command.ExecuteNonQuery();
  3092. }
  3093. }
  3094. transaction.Commit();
  3095. }
  3096. catch (Exception)
  3097. {
  3098. transaction.Rollback();
  3099. throw;
  3100. }
  3101. }
  3102. private const int deleteBatchSize = 100;
  3103. private readonly MethodInfo _deleteEntitiesMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  3104. .Single(x => x.Name == nameof(DeleteEntity) && x.IsGenericMethod);
  3105. private void DeleteEntity<T>(Guid[] parentIDs, List<string> parentFields, DeletionData deletionData) where T : Entity, new()
  3106. {
  3107. var columns = DeletionData.DeletionColumns<T>();
  3108. var entityIDs = new List<Guid>();
  3109. for (int i = 0; i < parentIDs.Length; i += deleteBatchSize)
  3110. {
  3111. var items = new ArraySegment<Guid>(parentIDs, i, Math.Min(deleteBatchSize, parentIDs.Length - i));
  3112. var ids = items.ToArray();
  3113. var filter = new Filters<T>();
  3114. foreach(var field in parentFields)
  3115. {
  3116. filter.Add(new Filter<T>(field).InList(ids));
  3117. }
  3118. var entities = Query(filter.CombineOr(), columns);
  3119. foreach (var row in entities.Rows)
  3120. {
  3121. deletionData.DeleteEntity<T>(row);
  3122. entityIDs.Add(row.Get<T, Guid>(x => x.ID));
  3123. }
  3124. }
  3125. CascadeDelete(typeof(T), entityIDs.ToArray(), deletionData);
  3126. }
  3127. private void DeleteEntity(Type T, Guid[] parentIDs, List<string> parentFields, DeletionData deletionData)
  3128. {
  3129. _deleteEntitiesMethod.MakeGenericMethod(T).Invoke(this, new object?[] { parentIDs, parentFields, deletionData });
  3130. }
  3131. private readonly MethodInfo _setNullEntityMethod = typeof(SQLiteProvider).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  3132. .Single(x => x.Name == nameof(SetNullEntity) && x.IsGenericMethod);
  3133. private void SetNullEntity<T>(List<string> properties, Guid[] parentIDs, DeletionData deletionData) where T : Entity, new()
  3134. {
  3135. foreach(var property in properties)
  3136. {
  3137. var columns = Columns.None<T>().Add(x => x.ID).Add(property);
  3138. for(int i = 0; i < parentIDs.Length; i += deleteBatchSize)
  3139. {
  3140. var items = new ArraySegment<Guid>(parentIDs, i, Math.Min(deleteBatchSize, parentIDs.Length - i));
  3141. var entities = Query(new Filter<T>(property).InList(items.ToArray()), columns);
  3142. foreach (var row in entities.Rows)
  3143. {
  3144. deletionData.SetNullEntity<T>(row.Get<T, Guid>(x => x.ID), property, row.Get<Guid>(property));
  3145. }
  3146. }
  3147. }
  3148. }
  3149. private void SetNullEntity(Type T, List<string> properties, Guid[] parentIDs, DeletionData deletionData)
  3150. {
  3151. _setNullEntityMethod.MakeGenericMethod(T).Invoke(this, new object?[] { properties, parentIDs, deletionData });
  3152. }
  3153. private void CascadeDelete(Type type, Guid[] parentIDs, DeletionData deletionData)
  3154. {
  3155. if(parentIDs.Length == 0)
  3156. {
  3157. return;
  3158. }
  3159. if (Factory._cascades.TryGetValue(type, out var cascades))
  3160. {
  3161. foreach (var cascade in cascades)
  3162. {
  3163. DeleteEntity(cascade.Item1, parentIDs, cascade.Item2, deletionData);
  3164. }
  3165. }
  3166. if(Factory._setNulls.TryGetValue(type, out var setNulls))
  3167. {
  3168. foreach(var setNull in setNulls)
  3169. {
  3170. SetNullEntity(setNull.Item1, setNull.Item2, parentIDs, deletionData);
  3171. }
  3172. }
  3173. }
  3174. public void Delete<T>(T entity, string userID) where T : Entity, new()
  3175. {
  3176. if (!CanSave<T>())
  3177. {
  3178. return;
  3179. }
  3180. if (typeof(T).HasAttribute<UnrecoverableAttribute>())
  3181. {
  3182. Purge(entity);
  3183. var props = GetExternalProperties(typeof(T));
  3184. foreach(var prop in props)
  3185. {
  3186. DeleteExternalData(typeof(T), prop.Name, entity.ID);
  3187. }
  3188. }
  3189. else
  3190. {
  3191. entity = DoQuery(
  3192. new Filter<T>(x => x.ID).IsEqualTo(entity.ID),
  3193. DeletionData.DeletionColumns<T>(),
  3194. null,
  3195. null,
  3196. false,
  3197. false
  3198. ).Rows.First().ToObject<T>();
  3199. var deletionData = new DeletionData();
  3200. deletionData.DeleteEntity(entity);
  3201. CascadeDelete(typeof(T), new Guid[] { entity.ID }, deletionData);
  3202. var tableName = typeof(T).Name;
  3203. var deletion = new Deletion()
  3204. {
  3205. DeletionDate = DateTime.Now,
  3206. HeadTable = tableName,
  3207. Description = entity.ToString() ?? "",
  3208. DeletedBy = userID,
  3209. Data = Serialization.Serialize(deletionData)
  3210. };
  3211. OnSave(deletion);
  3212. Purge(entity);
  3213. }
  3214. }
  3215. public void Delete<T>(IEnumerable<T> entities, string userID) where T : Entity, new()
  3216. {
  3217. if (!CanSave<T>())
  3218. {
  3219. return;
  3220. }
  3221. entities = entities.AsIList();
  3222. if (!entities.Any())
  3223. return;
  3224. if (typeof(T).HasAttribute<UnrecoverableAttribute>())
  3225. {
  3226. Purge(entities);
  3227. var props = GetExternalProperties(typeof(T));
  3228. foreach(var prop in props)
  3229. {
  3230. foreach(var entity in entities)
  3231. {
  3232. DeleteExternalData(typeof(T), prop.Name, entity.ID);
  3233. }
  3234. }
  3235. }
  3236. else
  3237. {
  3238. var ids = entities.Select(x => x.ID).ToArray();
  3239. var entityList = Query(
  3240. new Filter<T>(x => x.ID).InList(ids),
  3241. DeletionData.DeletionColumns<T>()).Rows.Select(x => x.ToObject<T>()).ToList();
  3242. if (!entityList.Any())
  3243. return;
  3244. var deletionData = new DeletionData();
  3245. foreach (var entity in entityList)
  3246. {
  3247. deletionData.DeleteEntity(entity);
  3248. }
  3249. CascadeDelete(typeof(T), ids, deletionData);
  3250. var tableName = typeof(T).Name;
  3251. var deletion = new Deletion()
  3252. {
  3253. DeletionDate = DateTime.Now,
  3254. HeadTable = tableName,
  3255. Description = $"Deleted {entityList.Count} entries",
  3256. DeletedBy = userID,
  3257. Data = Serialization.Serialize(deletionData)
  3258. };
  3259. OnSave(deletion);
  3260. Purge(entities);
  3261. }
  3262. }
  3263. private void AddDeletionType(Type type, List<Type> deletions)
  3264. {
  3265. deletions.Add(type);
  3266. if (!Factory._cascades.TryGetValue(type, out var cascades))
  3267. return;
  3268. foreach (var cascade in cascades)
  3269. {
  3270. AddDeletionType(cascade.Item1, deletions);
  3271. }
  3272. }
  3273. private Dictionary<Type, List<Type>> _allCascades = new();
  3274. private List<Type> GetDeletionTypes(Type type)
  3275. {
  3276. if(_allCascades.TryGetValue(type, out var cascades))
  3277. {
  3278. return cascades;
  3279. }
  3280. var deletionTypes = new List<Type>();
  3281. AddDeletionType(type, deletionTypes);
  3282. _allCascades[type] = deletionTypes;
  3283. return deletionTypes;
  3284. }
  3285. public void Purge(Deletion deletion)
  3286. {
  3287. if (!CanSave<Deletion>())
  3288. {
  3289. return;
  3290. }
  3291. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  3292. if(data is not null)
  3293. {
  3294. foreach(var (entityName, cascade) in data.Cascades)
  3295. {
  3296. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  3297. var props = GetExternalProperties(entityType);
  3298. foreach(var prop in props)
  3299. {
  3300. foreach(var entity in cascade.ToObjects(entityType).Cast<Entity>())
  3301. {
  3302. DeleteExternalData(entityType, prop.Name, entity.ID);
  3303. }
  3304. }
  3305. }
  3306. }
  3307. Purge<Deletion>(deletion);
  3308. }
  3309. public void Recover(Deletion deletion)
  3310. {
  3311. if (!CanSave<Deletion>())
  3312. {
  3313. return;
  3314. }
  3315. if (deletion.ID == Guid.Empty)
  3316. {
  3317. Logger.Send(LogType.Error, "", "Empty Deletion ID; Recovery cancelled");
  3318. return;
  3319. }
  3320. var data = Serialization.Deserialize<DeletionData>(deletion.Data);
  3321. if (data is null)
  3322. {
  3323. Logger.Send(LogType.Error, "", "Deletion Data deserialisation failed; Recovery cancelled");
  3324. return;
  3325. }
  3326. foreach (var (entityName, setNulls) in data.SetNulls)
  3327. {
  3328. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  3329. var saves = new List<Entity>();
  3330. foreach(var setNull in setNulls)
  3331. {
  3332. var row = DoQueryNonGeneric(
  3333. entityType,
  3334. Filter.Create<Entity>(entityType, x => x.ID).IsEqualTo(setNull.EntityID),
  3335. Columns.None(entityType)
  3336. .Add<Entity>(x => x.ID)
  3337. .Add(setNull.Property),
  3338. null,
  3339. CoreRange.Database(1),
  3340. false,
  3341. false
  3342. ).Rows.FirstOrDefault();
  3343. if (row is null) continue;
  3344. var entity = (row.ToObject(entityType) as Entity)!;
  3345. CoreUtils.SetPropertyValue(entity, setNull.Property, setNull.ParentID);
  3346. saves.Add(entity);
  3347. }
  3348. OnSaveNonGeneric(entityType, saves);
  3349. }
  3350. foreach(var (entityName, cascade) in data.Cascades)
  3351. {
  3352. if (!CoreUtils.TryGetEntity(entityName, out var entityType)) continue;
  3353. OnSaveNonGeneric(entityType, cascade.ToObjects(entityType).Cast<Entity>());
  3354. }
  3355. Purge<Deletion>(deletion);
  3356. }
  3357. public List<Type> GetDeletionTypes(Deletion deletion)
  3358. {
  3359. var entityType = CoreUtils.Entities.First(x => x.Name == deletion.HeadTable);
  3360. return GetDeletionTypes(entityType);
  3361. }
  3362. #endregion
  3363. #endregion
  3364. #region External Data Storage
  3365. private string ExternalDataFolder(Type T, string columnName, string idString)
  3366. {
  3367. return Path.Combine(
  3368. Path.GetDirectoryName(Factory.URL) ?? "",
  3369. $"{Path.GetFileName(Factory.URL)}.data",
  3370. T.Name,
  3371. columnName,
  3372. idString.Substring(0, 2));
  3373. }
  3374. private byte[]? GetExternalData(Type T, string columnName, Guid id)
  3375. {
  3376. var idString = id.ToString();
  3377. var filename = Path.Combine(ExternalDataFolder(T, columnName, idString), idString);
  3378. try
  3379. {
  3380. return File.ReadAllBytes(filename);
  3381. }
  3382. catch
  3383. {
  3384. //Logger.Send(LogType.Error, "", $"Could not load external {T.Name}.{columnName}: {e.Message}");
  3385. return null;
  3386. }
  3387. }
  3388. private void SaveExternalData(Type T, string columnName, Guid id, byte[] data)
  3389. {
  3390. var idString = id.ToString();
  3391. var directory = ExternalDataFolder(T, columnName, idString);
  3392. Directory.CreateDirectory(directory);
  3393. var filename = Path.Combine(directory, idString);
  3394. File.WriteAllBytes(filename, data);
  3395. }
  3396. private void DeleteExternalData(Type T, string columnName, Guid id)
  3397. {
  3398. var idString = id.ToString();
  3399. var directory = ExternalDataFolder(T, columnName, idString);
  3400. Directory.CreateDirectory(directory);
  3401. var filename = Path.Combine(directory, idString);
  3402. if (File.Exists(filename))
  3403. {
  3404. File.Delete(filename);
  3405. }
  3406. }
  3407. #endregion
  3408. }