protected override Expression VisitConstant(ConstantExpression c) { Type type = TableType(c.Value); if (type != null) { if (typeof(Entity).IsAssignableFrom(type)) { return(new MetaProjectorExpression(c.Type, new MetaExpression(type, new CleanMeta(Implementations.By(type), PropertyRoute.Root(type))))); } if (type.IsInstantiationOf(typeof(MListElement <,>))) { var parentType = type.GetGenericArguments()[0]; ISignumTable st = (ISignumTable)c.Value; TableMList rt = (TableMList)st.Table; PropertyRoute element = rt.PropertyRoute.Add("Item"); return(new MetaProjectorExpression(c.Type, new MetaMListExpression(type, new CleanMeta(Implementations.By(parentType), PropertyRoute.Root(rt.PropertyRoute.RootType)), new CleanMeta(element.TryGetImplementations(), element)))); } } return(MakeVoidMeta(c.Type)); }
public static IDisposable DisableIdentity <T, V>(Expression <Func <T, MList <V> > > mListField) where T : Entity { TableMList table = ((FieldMList)Schema.Current.Field(mListField)).TableMList; return(DisableIdentity(table.Name)); }
protected virtual int CopyTableBasic(ITable table, DatabaseName newDatabaseName, SqlPreCommandSimple?filter) { ObjectName newTableName = table.Name.OnDatabase(newDatabaseName); var isPostgres = Schema.Current.Settings.IsPostgres; string command = @"INSERT INTO {0} ({2}) SELECT {3} from {1} as [table]".FormatWith( newTableName, table.Name, table.Columns.Keys.ToString(a => a.SqlEscape(isPostgres), ", "), table.Columns.Keys.ToString(a => "[table]." + a.SqlEscape(isPostgres), ", ")); if (filter != null) { if (table is Table) { command += "\r\nWHERE [table].Id in ({0})".FormatWith(filter.Sql); } else { TableMList rt = (TableMList)table; command += "\r\nJOIN {0} [masterTable] on [table].{1} = [masterTable].Id".FormatWith(rt.BackReference.ReferenceTable.Name, rt.BackReference.Name.SqlEscape(isPostgres)) + "\r\nWHERE [masterTable].Id in ({0})".FormatWith(filter.Sql); } } string fullCommand = !table.PrimaryKey.Identity ? command : ("SET IDENTITY_INSERT {0} ON\r\n".FormatWith(newTableName) + command + "\r\n" + "SET IDENTITY_INSERT {0} OFF\r\n".FormatWith(newTableName)); return(Executor.ExecuteNonQuery(fullCommand, filter?.Parameters)); }
public TableIndex AddIndexMList <T, V>(Expression <Func <T, MList <V> > > toMList, Expression <Func <MListElement <T, V>, object> > fields, Expression <Func <MListElement <T, V>, bool> >?where = null, Expression <Func <MListElement <T, V>, object> >?includeFields = null) where T : Entity { TableMList table = ((FieldMList)Schema.FindField(Schema.Table(typeof(T)), Reflector.GetMemberList(toMList))).TableMList; IColumn[] columns = IndexKeyColumns.Split(table, fields); var index = AddIndex(table, columns); if (where != null) { index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table); } if (includeFields != null) { index.IncludeColumns = IndexKeyColumns.Split(table, includeFields); if (table.SystemVersioned != null) { index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray(); } } return(index); }
public MListExpression(Type type, PrimaryKeyExpression backID, IntervalExpression?externalPeriod, TableMList tr) : base(DbExpressionType.MList, type) { this.BackID = backID; this.ExternalPeriod = externalPeriod; this.TableMList = tr; }
public MListElementExpression(PrimaryKeyExpression rowId, EntityExpression parent, Expression order, Expression element, TableMList table) : base(DbExpressionType.MListElement, typeof(MListElement <,>).MakeGenericType(parent.Type, element.Type)) { this.RowId = rowId; this.Parent = parent; this.Order = order; this.Element = element; this.Table = table; }
public MListElementExpression(PrimaryKeyExpression rowId, EntityExpression parent, Expression?order, Expression element, IntervalExpression?systemPeriod, TableMList table, Alias alias) : base(DbExpressionType.MListElement, typeof(MListElement <,>).MakeGenericType(parent.Type, element.Type)) { this.RowId = rowId; this.Parent = parent; this.Order = order; this.Element = element; this.TablePeriod = systemPeriod; this.Table = table; this.Alias = alias; }
public CachedTableMList(ICacheLogicController controller, TableMList table, AliasGenerator aliasGenerator, string lastPartialJoin, string remainingJoins) : base(controller) { this.table = table; CachedTableConstructor ctr = this.Constructor = new CachedTableConstructor(this, aliasGenerator); //Query using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true })) { string select = "SELECT\r\n{0}\r\nFROM {1} {2}\r\n".FormatWith( ctr.table.Columns.Values.ToString(c => ctr.currentAlias + "." + c.Name.SqlEscape(), ",\r\n"), table.Name.ToString(), ctr.currentAlias.ToString()); ctr.remainingJoins = lastPartialJoin + ctr.currentAlias + "." + table.BackReference.Name.SqlEscape() + "\r\n" + remainingJoins; query = new SqlPreCommandSimple(select); } //Reader { rowReader = ctr.GetRowReader(); } //Completer { List <Expression> instructions = new List <Expression> { Expression.Assign(ctr.origin, Expression.Convert(CachedTableConstructor.originObject, ctr.tupleType)), Expression.Assign(result, ctr.MaterializeField(table.Field)) }; var ci = typeof(MList <T> .RowIdElement).GetConstructor(new [] { typeof(T), typeof(PrimaryKey), typeof(int?) }); var order = table.Order == null?Expression.Constant(null, typeof(int?)) : ctr.GetTupleProperty(table.Order).Nullify(); instructions.Add(Expression.New(ci, result, CachedTableConstructor.NewPrimaryKey(ctr.GetTupleProperty(table.PrimaryKey)), order)); var block = Expression.Block(typeof(MList <T> .RowIdElement), new[] { ctr.origin, result }, instructions); activatorExpression = Expression.Lambda <Func <object, IRetriever, MList <T> .RowIdElement> >(block, CachedTableConstructor.originObject, CachedTableConstructor.retriever); activator = activatorExpression.Compile(); parentIdGetter = ctr.GetPrimaryKeyGetter(table.BackReference); rowIdGetter = ctr.GetPrimaryKeyGetter(table.PrimaryKey); } relationalRows = new ResetLazy <Dictionary <PrimaryKey, Dictionary <PrimaryKey, object> > >(() => { CacheLogic.AssertSqlDependencyStarted(); var connector = (SqlConnector)Connector.Current; var subConnector = connector.ForDatabase(table.Name.Schema?.Database); Dictionary <PrimaryKey, Dictionary <PrimaryKey, object> > result = new Dictionary <PrimaryKey, Dictionary <PrimaryKey, object> >(); using (MeasureLoad()) using (Connector.Override(subConnector)) using (Transaction tr = Transaction.ForceNew(IsolationLevel.ReadCommitted)) { if (CacheLogic.LogWriter != null) { CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName())); } ((SqlConnector)Connector.Current).ExecuteDataReaderOptionalDependency(query, OnChange, fr => { object obj = rowReader(fr); PrimaryKey parentId = parentIdGetter(obj); var dic = result.TryGetC(parentId); if (dic == null) { result[parentId] = dic = new Dictionary <PrimaryKey, object>(); } dic[rowIdGetter(obj)] = obj; }); tr.Commit(); } return(result); }, mode: LazyThreadSafetyMode.ExecutionAndPublication); }
public MListExpression(Type type, Expression backID, TableMList tr) : base(DbExpressionType.MList, type) { this.BackID = backID; this.TableMList = tr; }
protected virtual SqlPreCommandSimple DeleteUpdatedRelationalTableScript(DisconnectedMachineEntity machine, Table table, TableMList rt, DatabaseName newDatabaseName) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var delete = new SqlPreCommandSimple(@"DELETE {0} FROM {0} INNER JOIN {1} as [table] ON {0}.{2} = [table].{3}".FormatWith( rt.Name, table.Name.OnDatabase(newDatabaseName), rt.BackReference.Name.SqlEscape(), table.PrimaryKey.Name.SqlEscape()) + GetUpdateWhere(table), new List <DbParameter> { pb.CreateParameter("@machineId", machine.Id.Object, machine.Id.Object.GetType()) }); return(delete); }
protected virtual SqlPreCommandSimple InsertUpdatedRelationalTableScript(DisconnectedMachineEntity machine, Table table, TableMList rt, DatabaseName newDatabaseName) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var insert = new SqlPreCommandSimple(@"INSERT INTO {0} ({1}) SELECT {2} FROM {3} as [relationalTable] INNER JOIN {4} as [table] ON [relationalTable].{5} = [table].{6}".FormatWith( rt.Name, rt.Columns.Values.ToString(c => c.Name.SqlEscape(), ", "), rt.Columns.Values.ToString(c => "[relationalTable]." + c.Name.SqlEscape(), ", "), rt.Name.OnDatabase(newDatabaseName), table.Name.OnDatabase(newDatabaseName), rt.BackReference.Name.SqlEscape(), table.PrimaryKey.Name.SqlEscape()) + GetUpdateWhere(table), new List <DbParameter> { pb.CreateParameter("@machineId", machine.Id.Object, machine.Id.Object.GetType()) }); return(insert); }
protected virtual SqlPreCommandSimple InsertRelationalTableScript(Table table, DatabaseName newDatabaseName, TableMList rt) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var created = table.Mixins[typeof(DisconnectedCreatedMixin)].Columns().Single(); string command = @"INSERT INTO {0} ({1}) SELECT {2} FROM {3} as [relationalTable] JOIN {4} [table] on [relationalTable].{5} = [table].{6} WHERE [table].{7} = 1".FormatWith( rt.Name, rt.Columns.Values.ToString(c => c.Name.SqlEscape(), ", "), rt.Columns.Values.ToString(c => "[relationalTable]." + c.Name.SqlEscape(), ", "), rt.Name.OnDatabase(newDatabaseName), table.Name.OnDatabase(newDatabaseName), rt.BackReference.Name.SqlEscape(), table.PrimaryKey.Name.SqlEscape(), created.Name.SqlEscape()); var sql = new SqlPreCommandSimple(command); return(sql); }
public static void SynchronizeRoles(XDocument doc) { Table table = Schema.Current.Table(typeof(RoleEntity)); TableMList relationalTable = table.TablesMList().Single(); Dictionary <string, XElement> rolesXml = doc.Root.Element("Roles").Elements("Role").ToDictionary(x => x.Attribute("Name").Value); { Dictionary <string, RoleEntity> rolesDic = Database.Query <RoleEntity>().ToDictionary(a => a.ToString()); Replacements replacements = new Replacements(); replacements.AskForReplacements(rolesDic.Keys.ToHashSet(), rolesXml.Keys.ToHashSet(), "Roles"); rolesDic = replacements.ApplyReplacementsToOld(rolesDic, "Roles"); Console.WriteLine("Part 1: Syncronize roles without relationships"); var roleInsertsDeletes = Synchronizer.SynchronizeScript(Spacing.Double, rolesXml, rolesDic, createNew: (name, xelement) => table.InsertSqlSync(new RoleEntity { Name = name }, includeCollections: false), removeOld: (name, role) => SqlPreCommand.Combine(Spacing.Simple, new SqlPreCommandSimple("DELETE {0} WHERE {1} = {2} --{3}" .FormatWith(relationalTable.Name, ((IColumn)relationalTable.Field).Name.SqlEscape(), role.Id, role.Name)), table.DeleteSqlSync(role)), mergeBoth: (name, xElement, role) => { var oldName = role.Name; role.Name = name; role.MergeStrategy = xElement.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum <MergeStrategy>()) ?? MergeStrategy.Union; return(table.UpdateSqlSync(role, includeCollections: false, comment: oldName)); }); if (roleInsertsDeletes != null) { SqlPreCommand.Combine(Spacing.Triple, new SqlPreCommandSimple("-- BEGIN ROLE SYNC SCRIPT"), new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())), roleInsertsDeletes, new SqlPreCommandSimple("-- END ROLE SYNC SCRIPT")).OpenSqlFileRetry(); Console.WriteLine("Press [Enter] when executed..."); Console.ReadLine(); } else { SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized"); } } { Console.WriteLine("Part 2: Syncronize roles relationships"); Dictionary <string, RoleEntity> rolesDic = Database.Query <RoleEntity>().ToDictionary(a => a.ToString()); var roleRelationships = Synchronizer.SynchronizeScript(Spacing.Double, rolesXml, rolesDic, createNew: (name, xelement) => { throw new InvalidOperationException("No new roles should be at this stage. Did you execute the script?"); }, removeOld: (name, role) => { throw new InvalidOperationException("No old roles should be at this stage. Did you execute the script?"); }, mergeBoth: (name, xElement, role) => { var should = xElement.Attribute("Contains").Value.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); var current = role.Roles.Select(a => a.ToString()); if (should.OrderBy().SequenceEqual(current.OrderBy())) { return(null); } role.Roles = should.Select(rs => rolesDic.GetOrThrow(rs).ToLite()).ToMList(); return(table.UpdateSqlSync(role)); }); if (roleRelationships != null) { SqlPreCommand.Combine(Spacing.Triple, new SqlPreCommandSimple("-- BEGIN ROLE SYNC SCRIPT"), new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())), roleRelationships, new SqlPreCommandSimple("-- END ROLE SYNC SCRIPT")).OpenSqlFileRetry(); Console.WriteLine("Press [Enter] when executed..."); Console.ReadLine(); } else { SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized"); } } }
protected virtual SqlPreCommandSimple InsertRelationalTableScript(Table table, DatabaseName newDatabaseName, TableMList rt) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var created = table.Mixins ![typeof(DisconnectedCreatedMixin)].Columns().Single();