SQLiteProvider.cs 148 KB

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