SQLiteProvider.cs 149 KB

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