/// <summary> /// SQL文を生成する /// </summary> /// <param name="context">生成先のコンテキスト</param> public void ToElementCode(ElementCode context) { var delayedCode = new DelayedCodeGenerator((wb) => { var ec = new ElementCode(); ec.BeginParenthesize(); ec.Add(SqlKeyword.Values); var list = this.List; for (int i = 0, n = list.Count; i < n; i++) { if (i != 0) { ec.AddComma(); } ec.BeginParenthesize(); ec.AddValues <TColumns>(list[i]); ec.EndParenthesize(); } ec.EndParenthesize(); ec.Add(this); ec.BeginParenthesize(); ec.AddColumns(this.ColumnMap, column => ec.Concat(column.Name)); ec.EndParenthesize(); ec.Build(wb); }); context.Add(delayedCode); context.RegisterBuildHandler(this, (item, wb) => { // delayedCode 内でエイリアス名付与するので、既存の処理をオーバーライドし何もしないようにする }); }
/// <summary> /// 同一値が存在しない場合のみ挿入するように判定を追加する /// </summary> /// <param name="columnCountToWhere">NOT EXISTS (SELECT * FROM t WHERE t.Name = "test") の部分で判定に使用する列数、0が指定されたら全て使用する</param> public void IfNotExists(int columnCountToWhere = 0) { var valueSetter = this.ValueNode as ValueSetter; if (valueSetter != null) { if (columnCountToWhere <= 0 || this.ColumnMap.Count < columnCountToWhere) { columnCountToWhere = this.ColumnMap.Count; } // WHERE NOT EXISTS部作成 var notExistsSelectFrom = new ElementCode(); var columnMap = this.ColumnMap; notExistsSelectFrom.Add(SqlKeyword.NotExists); notExistsSelectFrom.BeginParenthesize(); notExistsSelectFrom.Add(SqlKeyword.Select, SqlKeyword.Asterisk, SqlKeyword.From); notExistsSelectFrom.Add(this.Table); notExistsSelectFrom.Add(SqlKeyword.Where); for (int i = 0; i < columnCountToWhere; i++) { if (i != 0) { notExistsSelectFrom.Add(SqlKeyword.And); } notExistsSelectFrom.Add(columnMap[i]); notExistsSelectFrom.Concat("="); notExistsSelectFrom.Add(valueSetter.ColumnMap[i].Source); } notExistsSelectFrom.EndParenthesize(); valueSetter.Where(notExistsSelectFrom); } }
public void NotExistsSelect <TColumns>(TColumns columns, Expression <Func <TColumns, bool> > selectWhereExpression) { var expression = new ElementCode(selectWhereExpression, this.Owner.AllColumns, columns); var table = expression.FindTables().FirstOrDefault(); if (table == null) { throw new ApplicationException(); } var whereExpression = new ElementCode(); whereExpression.Add(SqlKeyword.NotExists); whereExpression.BeginParenthesize(); whereExpression.Add(SqlKeyword.Select, SqlKeyword.Asterisk, SqlKeyword.From); whereExpression.Add(table); whereExpression.Add(SqlKeyword.Where); whereExpression.Add(expression); whereExpression.EndParenthesize(); this.Expression = whereExpression; }