/// <summary> /// 串联多个参数化查询对象 /// </summary> /// <param name="firstQuery">第一个参数化查询对象</param> /// <param name="otherQueries">要串联的其他参数化查询对象</param> /// <returns>串联后的参数化查询对象</returns> public static ParameterizedQuery Concat( this ParameterizedQuery firstQuery, params ParameterizedQuery[] otherQueries ) { var builder = new ParameterizedQueryBuilder(); firstQuery.AppendTo( builder ); foreach ( var query in otherQueries ) { if ( query == null || string.IsNullOrEmpty( query.TextTemplate ) ) continue; if ( !builder.IsEndWithWhiteSpace() && !query.IsStartWithWhiteSpace() && Db.AddWhiteSpaceOnConcat ) builder.Append( ' ' ); query.AppendTo( builder ); } return builder.CreateQuery(); }
/// <summary> /// 解析查询模板 /// </summary> /// <param name="builder">参数化查询构建器</param> /// <param name="templateText">模板文本</param> /// <param name="args">模板参数</param> /// <returns>解析结果</returns> public static ParameterizedQuery ParseTemplate( ParameterizedQueryBuilder builder, string templateText, object[] args ) { if ( args == null ) throw new ArgumentNullException( "parameters" ); lock ( builder.SyncRoot ) { for ( var i = 0; i < templateText.Length; i++ ) { var ch = templateText[i]; if ( ch == '{' ) { if ( i == templateText.Length - 1 ) throw FormatError( templateText, i ); if ( templateText[i + 1] == '{' ) { i++; builder.Append( '{' ); continue; } Match match = null; do { match = numberRegex.Match( templateText, i ); if ( match.Success ) { int parameterIndex; if ( !int.TryParse( match.Groups["index"].Value, out parameterIndex ) ) throw FormatError( templateText, i ); AddParameter( builder, args[parameterIndex] ); break; } match = rangeRegex.Match( templateText, i ); if ( match.Success ) { int begin, end; if ( !int.TryParse( match.Groups["begin"].Value, out begin ) ) throw FormatError( templateText, i ); if ( match.Groups["end"] != null ) { if ( !int.TryParse( match.Groups["end"].Value, out end ) ) throw FormatError( templateText, i ); } else end = args.Length - 1; if ( begin > end || end >= args.Length ) throw FormatError( templateText, i ); AddParameters( builder, args, begin, end ); break; } match = allRegex.Match( templateText, i ); if ( match.Success ) { AddParameters( builder, args, 0, args.Length - 1 ); break; } } while ( false ); if ( match == null || !match.Success ) throw FormatError( templateText, i ); i += match.Length - 1; } else if ( ch == '}' ) { if ( i == templateText.Length - 1 ) throw FormatError( templateText, i ); if ( templateText[i + 1] == '}' ) { i++; builder.Append( '}' ); continue; } } else builder.Append( ch ); } return builder.CreateQuery(); } }