SQLiteProvider.cs 148 KB

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