public virtual ProjectionExpression AddOuterJoinTest(ProjectionExpression proj) { var test = this.GetOuterJoinTest(proj.Select); var select = proj.Select; ColumnExpression testCol = null; // look to see if test expression exists in columns already foreach (var col in select.Columns) { if (test.Equals(col.Expression)) { var colType = SqlType.Get(test.Type); testCol = new ColumnExpression(test.Type, colType, select.Alias, col.Name); break; } } if (testCol == null) { // add expression to projection testCol = test as ColumnExpression; string colName = (testCol != null) ? testCol.Name : "Test"; colName = proj.Select.Columns.GetAvailableColumnName(colName); var colType = SqlType.Get(test.Type); select = select.AddColumn(new ColumnDeclaration(colName, test, colType)); testCol = new ColumnExpression(test.Type, colType, select.Alias, colName); } var newProjector = new OuterJoinedExpression(testCol, proj.Projector); return new ProjectionExpression(select, newProjector, proj.Aggregator); }
protected override Expression VisitIn(InExpression expression) { if (!ShouldRewrite(expression)) { return base.VisitIn(expression); } Array array = expression.Values.OfType<ConstantExpression>().Select(item => item.Value).Distinct().ToArray(); var vfpDataXml = new ArrayXmlToCursor(array); var tableAlias = new TableAlias(); var columnType = _language.TypeSystem.GetColumnType(vfpDataXml.ItemType); var columnExpression = new ColumnExpression(vfpDataXml.ItemType, columnType, tableAlias, ArrayXmlToCursor.ColumnName); var columns = new List<ColumnDeclaration> { new ColumnDeclaration(string.Empty, columnExpression, columnType) }; var xml = Expression.Constant(vfpDataXml.Xml); var cursorName = Expression.Constant("curTemp_" + DateTime.Now.ToString("ddHHssmm")); var check = Expression.GreaterThan(new XmlToCursorExpression(xml, cursorName), Expression.Constant(0)); var from = Expression.Condition(check, cursorName, Expression.Constant(string.Empty)); var select = new SelectExpression(tableAlias, columns, from, null); return new InExpression(expression.Expression, select); }
protected override Expression VisitColumn(ColumnExpression column) { TableAlias mapped; if (this.map.TryGetValue(column.Alias, out mapped)) { return new ColumnExpression(column.Type, column.QueryType, mapped, column.Name); } return column; }
protected override Expression VisitColumn(ColumnExpression column) { if (!this.columns.ContainsKey(column.Name)) { this.columns.Add(column.Name, column); } return column; }
protected ColumnAssignment UpdateColumnAssignment(ColumnAssignment ca, ColumnExpression c, Expression e) { if (c != ca.Column || e != ca.Expression) { return new ColumnAssignment(c, e); } return ca; }
protected override Expression VisitColumn(ColumnExpression column) { ColumnExpression mapped; if (this.map.TryGetValue(column, out mapped)) { return mapped; } return column; }
public GroupByExpression(ColumnExpression simpleGroup, Expression keyExpression) : base(ExpressionType, simpleGroup.Table) { SimpleGroup = simpleGroup; HasKey = false; KeyExpression = keyExpression; Table = SimpleGroup.Table; }
protected override Expression VisitColumn(ColumnExpression column) { if (this.oldAliases.Contains(column.Alias)) { return new ColumnExpression(column.Type, column.SqlType, this.newAlias, column.Name); } return column; }
protected override Expression VisitColumn(ColumnExpression column) { TableAlias newAlias; if (this.map.TryGetValue(column.Alias, out newAlias)) { return new ColumnExpression(column.Type, newAlias, column.Name); } return column; }
protected override Expression VisitColumn(ColumnExpression column) { if (column.Alias != null) { sb.AppendFormat("`{0}`", GetAliasName(column.Alias)); sb.Append("."); } sb.AppendFormat("`{0}`", column.Name); return column; }
protected override Expression VisitColumn(ColumnExpression column) { Dictionary<string, Expression> nameMap; if (this.map.TryGetValue(column.Alias, out nameMap)) { Expression expr; if (nameMap.TryGetValue(column.Name, out expr)) { return this.Visit(expr); } throw new Exception("Reference to undefined column"); } return column; }
protected override Expression VisitColumn(ColumnExpression column) { if (column.Alias != null) { sb.AppendFormat("{0}", GetAliasName(column.Alias)); sb.Append("."); //MAA,20091127: remove quotes in column names //sb.Append(".\""); } sb.AppendFormat("{0}", column.Name); //sb.Append("\"");//MAA,20091127: remove quotes in column names return column; }
internal bool TryGetValue(ColumnExpression column, out ParameterExpression fieldReader, out int ordinal) { for (Scope s = this; s != null; s = s.outer) { if (column.Alias == s.Alias && this.nameMap.TryGetValue(column.Name, out ordinal)) { fieldReader = this.fieldReader; return true; } } fieldReader = null; ordinal = 0; return false; }
protected override Expression VisitColumn(ColumnExpression column) { if (column.Alias == this.outerAlias) { NamedValueExpression nv; if (!this.map.TryGetValue(column, out nv)) { string name = "@__Param__" + (this.parameterCounter++) + "__"; nv = new NamedValueExpression(name, column.QueryType, column); this.map.Add(column, nv); } return nv; } return column; }
protected override Expression VisitSelect(SelectExpression select) { select = (SelectExpression)base.VisitSelect(select); if (select.Skip != null) { SelectExpression newSelect = select.SetSkip(null).SetTake(null); bool canAddColumn = !select.IsDistinct && (select.GroupBy == null || select.GroupBy.Count == 0); if (!canAddColumn) { newSelect = newSelect.AddRedundantSelect(new TableAlias()); } var colType = DbTypeSystem.GetColumnType(typeof(int)); newSelect = newSelect.AddColumn(new ColumnDeclaration(columnName, new RowNumberExpression(select.OrderBy), colType)); // add layer for WHERE clause that references new rownum column newSelect = newSelect.AddRedundantSelect(new TableAlias()); newSelect = newSelect.RemoveColumn(newSelect.Columns.Single(c => c.Name == columnName)); var newAlias = ((SelectExpression)newSelect.From).Alias; ColumnExpression rnCol = new ColumnExpression(typeof(int), colType, newAlias, columnName); Expression where; if (select.Take != null) { where = new BetweenExpression( rnCol, Expression.Add(select.Skip, Expression.Constant(1)), Expression.Add(select.Skip, select.Take)); } else { where = rnCol.GreaterThan(select.Skip); } if (newSelect.Where != null) { where = newSelect.Where.And(where); } newSelect = newSelect.SetWhere(where); select = newSelect; } return select; }
public override bool WriteColumnExpression(ColumnExpression node) { if (ResolveNames) { Expression ex = node.FindDescendant<Expression>(); WriteNode(ex); if (!String.IsNullOrEmpty(node.ColumnReference.ColumnAlias)) { Writer.Write(" AS {0}", QuoteIdentifier(node.ColumnReference.ColumnAlias)); } return false; } else { return true; } }
protected override Expression VisitSelect(SelectExpression select) { select = (SelectExpression) base.VisitSelect(select); // look for redundant column declarations List<ColumnDeclaration> cols = select.Columns.OrderBy(c => c.Name).ToList(); BitArray removed = new BitArray(select.Columns.Count); bool anyRemoved = false; for (int i = 0, n = cols.Count; i < n - 1; i++) { ColumnDeclaration ci = cols[i]; ColumnExpression cix = ci.Expression as ColumnExpression; QueryType qt = cix != null ? cix.QueryType : ci.QueryType; ColumnExpression cxi = new ColumnExpression(ci.Expression.Type, qt, select.Alias, ci.Name); for (int j = i + 1; j < n; j++) { if (!removed.Get(j)) { ColumnDeclaration cj = cols[j]; if (SameExpression(ci.Expression, cj.Expression)) { // any reference to 'j' should now just be a reference to 'i' ColumnExpression cxj = new ColumnExpression(cj.Expression.Type, qt, select.Alias, cj.Name); this.map.Add(cxj, cxi); removed.Set(j, true); anyRemoved = true; } } } } if (anyRemoved) { List<ColumnDeclaration> newDecls = new List<ColumnDeclaration>(); for (int i = 0, n = cols.Count; i < n; i++) { if (!removed.Get(i)) { newDecls.Add(cols[i]); } } select = select.SetColumns(newDecls); } return select; }
private Expression MakeSubquery(Expression expression) { var newAlias = new TableAlias(); var aliases = DeclaredAliasGatherer.Gather(expression); var decls = new List<ColumnDeclaration>(); foreach (var ta in aliases) { foreach (var col in this.columns[ta]) { string name = decls.GetAvailableColumnName(col.Name); var decl = new ColumnDeclaration(name, col, col.QueryType); decls.Add(decl); var newCol = new ColumnExpression(col.Type, col.QueryType, newAlias, col.Name); this.map.Add(col, newCol); } } return new SelectExpression(newAlias, decls, expression, null); }
protected override Expression VisitSelect(SelectExpression select) { select = (SelectExpression)base.VisitSelect(select); if (select.Skip != null) { var newSelect = select.SetSkip(null).SetTake(null).AddRedundantSelect(_language, new TableAlias()); _hasRowNumberExpression = true; var colType = _language.TypeSystem.GetColumnType(typeof(int)); newSelect = newSelect.AddColumn(new ColumnDeclaration("rownum", new RowNumberExpression(select.OrderBy), colType)); // add layer for WHERE clause that references new rownum column newSelect = newSelect.AddRedundantSelect(_language, new TableAlias()); newSelect = newSelect.RemoveColumn(newSelect.Columns.Single(c => c.Name == "rownum")); var newAlias = ((SelectExpression)newSelect.From).Alias; var rowNumberColumn = new ColumnExpression(typeof(int), colType, newAlias, "rownum"); Expression where; if (select.Take != null) { where = new BetweenExpression(rowNumberColumn, Expression.Add(select.Skip, Expression.Constant(1)), Expression.Add(select.Skip, select.Take)); } else { where = rowNumberColumn.GreaterThan(select.Skip); } if (newSelect.Where != null) { where = newSelect.Where.And(where); } newSelect = newSelect.SetWhere(where); select = newSelect; } return select; }
private ColumnExpression ResolveColumn(ColumnExpression ce, SelectExpression select) { if (ce.Alias == select.Alias) { var cd = select.Columns.SingleEx(a => a.Name == ce.Name); var result = cd.Expression as ColumnExpression; if(result == null) return ce; TableExpression table = (TableExpression)select.From; if (table.Alias == result.Alias) { return new ColumnExpression(result.Type, aliasGenerator.Table(table.Name), result.Name); } return result; } return ce; }
protected override Expression VisitColumn(ColumnExpression column) { Expression result; if (CurrentScope.TryGetValue(column, out result)) return result ?? column; else { CurrentScope[column] = null; return column; } }
private ReadOnlyCollection<ColumnDeclaration> AnswerAndExpand(ReadOnlyCollection<ColumnDeclaration> columns, Alias currentAlias, Dictionary<ColumnExpression, Expression> askedColumns) { ColumnGenerator cg = new ColumnGenerator(columns); foreach (var col in askedColumns.Keys.ToArray()) { if (col.Alias == currentAlias) { Expression expr = columns.SingleEx(cd => (cd.Name ?? "-") == col.Name).Expression; askedColumns[col] = expr.NodeType == (ExpressionType)DbExpressionType.SqlConstant? expr: col; } else { Expression expr = CurrentScope[col]; ColumnExpression colExp = expr as ColumnExpression; if (colExp != null) { ColumnDeclaration cd = cg.Columns.FirstOrDefault(c => c.Expression.Equals(colExp)); if (cd == null) { cd = cg.MapColumn(colExp); } askedColumns[col] = new ColumnExpression(col.Type, currentAlias, cd.Name); } else { askedColumns[col] = expr; } } } if (columns.Count != cg.Columns.Count()) return cg.Columns.ToReadOnly(); return columns; }
protected internal override Expression VisitColumn(ColumnExpression column) { externals.Add(column.Alias); return base.VisitColumn(column); }
protected override Expression VisitColumn(ColumnExpression column) { if (column.Alias != null && !this.HideColumnAliases) { this.WriteAliasName(GetAliasName(column.Alias)); this.Write("."); } this.WriteColumnName(column.Name); return column; }
protected override Expression VisitColumn(ColumnExpression column) { MarkColumnAsUsed(column.Alias, column.Name); return column; }
// make a variable declaration / initialization for dependent generated values private CommandExpression GetDependentGeneratedVariableDeclaration(MappingEntity entity, MappingTable table, List<MemberInfo> members, Expression instance, Dictionary<MemberInfo, Expression> map) { // first make command that retrieves the generated ids if any DeclarationCommand genIdCommand = null; var generatedIds = this.mapping.GetMappedMembers(entity).Where(m => this.mapping.IsPrimaryKey(entity, m) && this.mapping.IsGenerated(entity, m)).ToList(); if (generatedIds.Count > 0) { genIdCommand = this.GetGeneratedIdCommand(entity, members, map); // if that's all there is then just return the generated ids if (members.Count == generatedIds.Count) { return genIdCommand; } } // next make command that retrieves the generated members // only consider members that were not generated ids members = members.Except(generatedIds).ToList(); var tableAlias = new TableAlias(); var tex = new TableExpression(tableAlias, entity, this.mapping.GetTableName(table)); Expression where = null; if (generatedIds.Count > 0) { where = generatedIds.Select((m, i) => this.GetMemberExpression(tex, entity, m).Equal(map[m]) ).Aggregate((x, y) => x.And(y)); } else { where = this.GetIdentityCheck(tex, entity, instance); } TableAlias selectAlias = new TableAlias(); var columns = new List<ColumnDeclaration>(); var variables = new List<VariableDeclaration>(); foreach (var mi in members) { ColumnExpression col = (ColumnExpression)this.GetMemberExpression(tex, entity, mi); columns.Add(new ColumnDeclaration(this.mapping.GetColumnName(entity, mi), col, col.QueryType)); ColumnExpression vcol = new ColumnExpression(col.Type, col.QueryType, selectAlias, col.Name); variables.Add(new VariableDeclaration(mi.Name, col.QueryType, vcol)); map.Add(mi, new VariableExpression(mi.Name, col.Type, col.QueryType)); } var genMembersCommand = new DeclarationCommand(variables, new SelectExpression(selectAlias, columns, tex, where)); if (genIdCommand != null) { return new BlockCommand(genIdCommand, genMembersCommand); } return genMembersCommand; }
public static IInsertStatement SetVarParam(this IInsertStatement insert, ColumnExpression column, string param = null) { return(SetVarParam(insert, column as IColumnExpression, param)); }
public static IInsertStatement SetVarCustomer(this IInsertStatement insert, ColumnExpression column, string customer) { return(SetVarCustomer(insert, column as IColumnExpression, customer)); }
private Expression BindAnyAll(Expression source, MethodInfo method, LambdaExpression predicate, bool isRoot) { bool isAll = method.Name.Equals("All", StringComparison.InvariantCultureIgnoreCase); ConstantExpression constSource = source as ConstantExpression; if (constSource != null && !IsQuery(constSource)) { System.Diagnostics.Debug.Assert(!isRoot); Expression where = null; foreach (object value in (IEnumerable)constSource.Value) { Expression expr = Expression.Invoke(predicate, Expression.Constant(value, predicate.Parameters[0].Type)); if (where == null) { where = expr; } else if (isAll) { where = where.And(expr); } else { where = where.Or(expr); } } return(this.Visit(where)); } else { if (isAll) { predicate = Expression.Lambda(Expression.Not(predicate.Body), predicate.Parameters.ToArray()); } if (predicate != null) { source = Expression.Call(typeof(Enumerable), "Where", method.GetGenericArguments(), source, predicate); } ProjectionExpression projection = this.VisitSequence(source); Expression result = new ExistsExpression(projection.Select); if (isAll) { result = Expression.Not(result); } if (isRoot) { if (this.language.AllowSubqueryInSelectWithoutFrom) { return(GetSingletonSequence(result, "SingleOrDefault")); } else { // use count aggregate instead of exists //var colType = this.language.TypeSystem.GetColumnType(typeof(int)); var newSelect = projection.Select.SetColumns(new[] { new ColumnDeclaration("value", new AggregateExpression(typeof(int), "Count", null, false)) }); var colx = new ColumnExpression(typeof(int), newSelect.Alias, "value"); var exp = isAll ? colx.Equal(Expression.Constant(0)) : colx.GreaterThan(Expression.Constant(0)); return(new ProjectionExpression(newSelect, exp, Aggregator.GetAggregator(typeof(bool), typeof(IEnumerable <bool>)))); } } return(result); } }
public static OrderExpression Desc(ColumnExpression column) { return(new OrderExpression(column, OrderEnum.Desc)); }
/// <summary> /// Visits the children of the column expression. /// </summary> /// <param name="columnExpression">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; otherwise, returns the original expression.</returns> protected abstract Expression VisitColumn(ColumnExpression columnExpression);
public static OrderExpression Asc(ColumnExpression column) { return(new OrderExpression(column)); }
public override ProjectionExpression GetQueryExpression(MappingEntity entity) { var tables = this.mapping.GetTables(entity); if (tables.Count <= 1) { return base.GetQueryExpression(entity); } var aliases = new Dictionary<string, TableAlias>(); MappingTable rootTable = tables.Single(ta => !this.mapping.IsExtensionTable(ta)); var tex = new TableExpression(new TableAlias(), entity, this.mapping.GetTableName(rootTable)); aliases.Add(this.mapping.GetAlias(rootTable), tex.Alias); Expression source = tex; foreach (MappingTable table in tables.Where(t => this.mapping.IsExtensionTable(t))) { TableAlias joinedTableAlias = new TableAlias(); string extensionAlias = this.mapping.GetAlias(table); aliases.Add(extensionAlias, joinedTableAlias); List<string> keyColumns = this.mapping.GetExtensionKeyColumnNames(table).ToList(); List<MemberInfo> relatedMembers = this.mapping.GetExtensionRelatedMembers(table).ToList(); string relatedAlias = this.mapping.GetExtensionRelatedAlias(table); TableAlias relatedTableAlias; aliases.TryGetValue(relatedAlias, out relatedTableAlias); TableExpression joinedTex = new TableExpression(joinedTableAlias, entity, this.mapping.GetTableName(table)); Expression cond = null; for (int i = 0, n = keyColumns.Count; i < n; i++) { var memberType = TypeHelper.GetMemberType(relatedMembers[i]); var colType = this.GetColumnType(entity, relatedMembers[i]); var relatedColumn = new ColumnExpression(memberType, colType, relatedTableAlias, this.mapping.GetColumnName(entity, relatedMembers[i])); var joinedColumn = new ColumnExpression(memberType, colType, joinedTableAlias, keyColumns[i]); var eq = joinedColumn.Equal(relatedColumn); cond = (cond != null) ? cond.And(eq) : eq; } source = new JoinExpression(JoinType.SingletonLeftOuter, source, joinedTex, cond); } var columns = new List<ColumnDeclaration>(); this.GetColumns(entity, aliases, columns); SelectExpression root = new SelectExpression(new TableAlias(), columns, source, null); var existingAliases = aliases.Values.ToArray(); Expression projector = this.GetEntityExpression(root, entity); var selectAlias = new TableAlias(); var pc = ColumnProjector.ProjectColumns(this.Translator.Linguist.Language, projector, null, selectAlias, root.Alias); var proj = new ProjectionExpression( new SelectExpression(selectAlias, pc.Columns, root, null), pc.Projector ); return (ProjectionExpression)this.Translator.Police.ApplyPolicy(proj, entity.ElementType); }
private void GetColumns(MappingEntity entity, Dictionary<string, TableAlias> aliases, List<ColumnDeclaration> columns) { foreach (MemberInfo mi in this.mapping.GetMappedMembers(entity)) { if (!this.mapping.IsAssociationRelationship(entity, mi)) { if (this.mapping.IsNestedEntity(entity, mi)) { this.GetColumns(this.mapping.GetRelatedEntity(entity, mi), aliases, columns); } else if (this.mapping.IsColumn(entity, mi)) { string name = this.mapping.GetColumnName(entity, mi); string aliasName = this.mapping.GetAlias(entity, mi); TableAlias alias; aliases.TryGetValue(aliasName, out alias); var colType = this.GetColumnType(entity, mi); ColumnExpression ce = new ColumnExpression(TypeHelper.GetMemberType(mi), colType, alias, name); ColumnDeclaration cd = new ColumnDeclaration(name, ce, colType); columns.Add(cd); } } } }
public static IInsertStatement Set(this IInsertStatement insert, ColumnExpression column, object value) { return(Set(insert, column as IColumnExpression, value)); }
private Expression GetIdentityCheck(TableExpression root, MappingEntity entity, Expression instance, MappingTable table) { if (this.mapping.IsExtensionTable(table)) { var keyColNames = this.mapping.GetExtensionKeyColumnNames(table).ToArray(); var relatedMembers = this.mapping.GetExtensionRelatedMembers(table).ToArray(); Expression where = null; for (int i = 0, n = keyColNames.Length; i < n; i++) { var relatedMember = relatedMembers[i]; var cex = new ColumnExpression(TypeHelper.GetMemberType(relatedMember), this.GetColumnType(entity, relatedMember), root.Alias, keyColNames[n]); var nex = this.GetMemberExpression(instance, entity, relatedMember); var eq = cex.Equal(nex); where = (where != null) ? where.And(eq) : where; } return where; } else { return base.GetIdentityCheck(root, entity, instance); } }
private Expression VisitSelectExpression(SelectExpression selectExpression) { base.Visit(selectExpression); if (!RequiresRowNumberPaging(selectExpression)) { return(selectExpression); } var subQuery = selectExpression.PushDownSubquery(); foreach (var projection in subQuery.Projection) { var alias = projection as AliasExpression; var column = projection as ColumnExpression; if (column != null) { column = new ColumnExpression(column.Name, column.Property, subQuery); selectExpression.AddToProjection(column); continue; } column = alias?.TryGetColumnExpression(); if (column != null) { column = new ColumnExpression(column.Name, column.Property, subQuery); alias = new AliasExpression(alias.Alias, column); selectExpression.AddToProjection(alias); } else { column = new ColumnExpression(alias.Alias, alias.Expression.Type, subQuery); selectExpression.AddToProjection(column); } } if (subQuery.OrderBy.Count == 0) { subQuery.AddToOrderBy( new Ordering(new SqlFunctionExpression("@@RowCount", typeof(int)), OrderingDirection.Asc)); } var columnExpression = new ColumnExpression(RowNumberColumnName, typeof(int), subQuery); var rowNumber = new RowNumberExpression(columnExpression, subQuery.OrderBy); subQuery.ClearOrderBy(); subQuery.AddToProjection(rowNumber, false); Expression predicate = null; var offset = subQuery.Offset ?? 0; if (subQuery.Offset.HasValue) { predicate = Expression.GreaterThan(columnExpression, Expression.Constant(offset)); } if (subQuery.Limit.HasValue) { var exp = Expression.LessThanOrEqual(columnExpression, Expression.Constant(offset + subQuery.Limit.Value)); if (predicate != null) { exp = Expression.AndAlso(predicate, exp); } predicate = exp; } selectExpression.Predicate = predicate; return(selectExpression); }
protected virtual Expression VisitColumn(ColumnExpression column) { int iAlias; string aliasName = this.aliasMap.TryGetValue(column.Alias, out iAlias) ? "A" + iAlias : "A" + (column.Alias != null ? column.Alias.GetHashCode().ToString() : "") + "?"; this.Write(aliasName); this.Write("."); this.Write("Column(\""); this.Write(column.Name); this.Write("\")"); return column; }
protected override Expression VisitColumn(ColumnExpression columnExpression) { return(ApplyConversion(columnExpression, condition: false)); }
/// <summary> /// Initializes a new instance of the <see cref="ColumnAssignment"/> class. /// </summary> /// <param name="column">The column.</param> /// <param name="expression">The expression.</param> public ColumnAssignment(ColumnExpression column, Expression expression) { this.Column = column; this.Expression = expression; }
protected override Expression VisitColumn(ColumnExpression column) { _aliases.Add(column.Alias); return(column); }