SQLiteProvider.cs 150 KB

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