SQLiteProvider.cs 148 KB

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