SQLiteProvider.cs 149 KB

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