SQLiteProvider.cs 148 KB

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