public string ToString(ISqlDialect dialect) { var sql = new StringBuilder(); sql.AppendFormat("delete from {0}", table); if (where != Exp.Empty) sql.AppendFormat(" where {0}", where.ToString(dialect)); return sql.ToString(); }
public ICreateSessionFactory ForConnection(string connectionName, ISqlDialect sqlDialect, IDbDriver dbDriver) { if (connectionName == null) { throw new ArgumentNullException("connectionName"); } if (sqlDialect == null) { throw new ArgumentNullException("sqlDialect"); } if (dbDriver == null) { throw new ArgumentNullException("dbDriver"); } var configSection = ConfigurationManager.ConnectionStrings[connectionName]; if (configSection == null) { throw new ConfigurationException(ExceptionMessages.FluentConfiguration_ConnectionNotFound.FormatWith(connectionName)); } this.chosenConnectionName = configSection.Name; this.chosenSqlDialect = sqlDialect; this.chosenDbDriver = dbDriver; this.chosenDbDriver.ConnectionString = configSection.ConnectionString; this.chosenDbDriver.DbProviderFactory = DbProviderFactories.GetFactory(configSection.ProviderName); return this; }
public DropTableWriter(ISqlDialect dialect) { if (dialect == null) { throw new ArgumentNullException("dialect"); } this.dialect = dialect; }
public static string ToSql(this DateTime value, ISqlDialect dialect = null) { if (value.Date == value) return value.ToString((dialect ?? SqlSettings.DefaultDialect).DateFormat, Invariants.DateTimeFormat); return value.ToString((dialect ?? SqlSettings.DefaultDialect).DateTimeFormat, Invariants.DateTimeFormat); }
public void Append(StringBuilder stringBuilder, ISqlDialect dialect) { if (this.Node != null) { stringBuilder.Append(this.Node.Alias).Append("."); } dialect.AppendQuotedName(stringBuilder, this.columnName); }
public static string Dump(string sql, IDictionary<string, object> parameters, ISqlDialect dialect = null) { if (parameters == null) return sql; var param = parameters.ToList(); for (var i = 0; i < param.Count; i++) { var name = param[i].Key; if (!name.StartsWith("@")) param[i] = new KeyValuePair<string,object>("@" + name, param[i].Value); } param.Sort((x, y) => y.Key.Length.CompareTo(x.Key.Length)); var sb = new StringBuilder(sql); foreach (var pair in param) sb.Replace(pair.Key, DumpParameterValue(pair.Value, dialect)); var text = DatabaseCaretReferences.Replace(sb.ToString()); dialect = dialect ?? SqlSettings.DefaultDialect; var openBracket = dialect.OpenQuote; if (openBracket != '[') text = BracketLocator.ReplaceBrackets(text, dialect); var paramPrefix = dialect.ParameterPrefix; if (paramPrefix != '@') text = ParamPrefixReplacer.Replace(text, paramPrefix); return text; }
public ScheduleRepository(ScheduleRepositoryConfiguration configuration, IEasyNetQLogger log, Func<DateTime> now) { this.configuration = configuration; this.log = log; this.now = now; this.dialect = SqlDialectResolver.Resolve(configuration.ProviderName); }
public override string ToString(ISqlDialect dialect) { return string.Format("{0} {1} {2}", column1.ToString(dialect), Not ? "<>" : "=", column2.ToString(dialect)); }
public IEnumerable<IMap> ReverseEngineer( DatabaseSchema schema, ISqlDialect sqlDialect, IEnumerable<string> tablesToIgnore, IAnswerProvider answerProvider, bool fixOneToOnes) { if (tablesToIgnore == null) { tablesToIgnore = new string[0]; } var maps = new List<IMap>(); this.configuration = new Configuration(sqlDialect); foreach (var table in schema.Tables.Where(t => !tablesToIgnore.Contains(t.Name))) { maps.Add(this.MapTable(table)); } // go back through and add indexes and foreign keys foreach (var map in maps) { GetIndexesAndForeignKeys(schema.Tables.First(t => t.Name == map.Table), map); } // go back through and try to spot one-to-one columns if (fixOneToOnes) { foreach (var map in maps) { FindOneToOnes(map, answerProvider); } } return maps; }
public static string ToSql(this string value, ISqlDialect dialect = null) { if (value == null) return Null; return (dialect ?? SqlSettings.DefaultDialect).QuoteUnicodeString(value); }
public DelimitedDbStatement( ISqlDialect dialect, TransactionScope scope, IDbConnection connection, IDbTransaction transaction) : base(dialect, scope, connection, transaction) {}
public InheritedSqlPersistenceEngine( IConnectionFactory connectionFactory, ISqlDialect dialect, ISerialize serializer, TransactionScopeOption scopeOption, int pageSize) : base(connectionFactory, dialect, serializer, scopeOption, pageSize) {}
internal SessionFactory(string connectionName, IDbDriver dbDriver, ISqlDialect sqlDialect) { this.connectionName = connectionName; this.dbDriver = dbDriver; this.sqlDialect = sqlDialect; this.sessionListeners = new SessionListeners(Listener.DeleteListeners, Listener.InsertListener, Listener.UpdateListeners); }
public FirebirdDbStatement( ISqlDialect dialect, IDbConnection connection, IDbTransaction transaction, params IDisposable[] resources) : base(dialect, connection, transaction, resources) { }
/// <summary> /// Creates a new DynamicSQLinqJoinExpression instance /// </summary> /// <param name="tableName">The database Table / View to Join</param> /// <param name="joinOperator">The JOIN operator</param> /// <param name="clause">The Join clause</param> /// <param name="parameters">Any parameter values necessary for the Join clause</param> public DynamicSQLinqJoinExpression(ISqlDialect dialect, string tableName, DynamicSQLinqJoinOperator joinOperator, string clause, object[] parameters) { this.Dialect = dialect; this.Table = tableName; this.JoinOperator = joinOperator; this.Clause = clause; this.Parameters = parameters; }
public CustomSqlPersistenceFactory(IConnectionFactory factory, ISerialize serializer, ISqlDialect dialect, TransactionScopeOption scopeOption, int pageSize) : base(factory, serializer, dialect, scopeOption, pageSize) { this.factory = factory; this.serializer = serializer; this.dialect = dialect; this.scopeOption = scopeOption; this.pageSize = pageSize; }
/// <summary> /// Creates a new DynamicSQLinqSubQueryJoinExpression instance /// </summary> /// <param name="query">The sub-query that will be joined</param> /// <param name="alias">The Alias to give the sub-query within the main query</param> /// <param name="joinOperator">The JOIN operator</param> /// <param name="clause">The Join clause</param> /// <param name="parameters">Any parameters necessary for the Join clause</param> public DynamicSQLinqSubQueryJoinExpression(ISqlDialect dialect, ISQLinq query, string alias, DynamicSQLinqJoinOperator joinOperator, string clause, params object[] parameters) { this.Dialect = dialect; this.Query = query; this.Alias = alias; this.JoinOperator = joinOperator; this.Clause = clause; this.Parameters = parameters; }
protected DrapperManager(ISqlGenerator generator, IDbConnection dbConnection, ISqlDialect dialect) { Dialect = dialect; Generator = generator; DbConnection = dbConnection; Database = new Database(dbConnection, generator); Init(); }
public SqlDumper(ISqlOutputStream stream, IDatabaseFactory factory, SqlFormatProperties props) { m_stream = stream; m_props = props; m_factory = factory; m_DDA = m_factory.CreateDataAdapter(); m_formatterState.DDA = m_DDA; m_dialect = m_factory.CreateDialect(); }
public AbsoluteOrderingSqlPersistenceEngine(IConnectionFactory connectionFactory, ISqlDialect dialect, IPipelineStoreSqlDialect pipelineStoreSqlDialect, ISerialize serializer, bool transactional) : base(connectionFactory, dialect, serializer) { _dialect = pipelineStoreSqlDialect; _transactional = transactional; _serializer = serializer; }
public static HashSetEx<string> InvokeGetKeywords(ISqlDialect dialect) { if (GetKeywords == null) return null; var args = new GetKeyboardsEventArgs { Dialect = dialect, }; GetKeywords(args); return args.Keywords; }
public override string ToString(ISqlDialect dialect) { string format = exp1 is JunctionExp && ((JunctionExp) exp1).and != and ? "({0})" : "{0}"; format += " {1} "; format += exp2 is JunctionExp && ((JunctionExp) exp2).and != and ? "({2})" : "{2}"; return Not ? string.Format(format, (!exp1).ToString(dialect), and ? "or" : "and", (!exp2).ToString(dialect)) : string.Format(format, exp1.ToString(dialect), and ? "and" : "or", exp2.ToString(dialect)); }
public Migrator( ISqlDialect dialect, ICreateTableWriter createTableWriter, IAlterTableWriter alterTableWriter, IDropTableWriter dropTableWriter, IStatisticsProvider statisticsProvider) { this.dialect = dialect; this.statisticsProvider = statisticsProvider; this.createTableWriter = createTableWriter; this.dropTableWriter = dropTableWriter; this.alterTableWriter = alterTableWriter; }
public static string GenerateInsertStatements(IDataReader reader, string table, ISqlDialect dialect = null) { StringBuilder sbAll = new StringBuilder(); while (reader.Read()) { var sb = new StringBuilder(); sb.Append("INSERT INTO "); sb.Append(table); sb.Append(" ("); for (var i = 0; i < reader.FieldCount; i++) { if (i > 0) sb.Append(", "); sb.Append(reader.GetName(i)); } sb.Append(")\r\nVALUES ("); for (var i = 0; i < reader.FieldCount; i++) { if (i > 0) sb.Append(", "); sb.Append("/*"); sb.Append(reader.GetName(i)); sb.Append(":*/ "); var value = reader.GetValue(i); if (value == null || value == DBNull.Value) sb.Append("NULL"); else if (value is DateTime) sb.Append(((DateTime)value).ToSql(dialect)); else if (value is Int32 || value is Int16 || value is Boolean || value is Int64) sb.Append(Serenity.Invariants.ToInvariant(Convert.ToInt64(value))); else if (value is Double || value is Decimal || value is float) sb.Append(Serenity.Invariants.ToInvariant(Convert.ToDecimal(value))); else if (value is String) sb.Append(((string)value).ToSql(dialect)); else sb.Append(value.ToString().ToSql(dialect)); } sb.Append(");"); sbAll.AppendLine(sb.ToString()); sbAll.AppendLine(); } return sbAll.ToString(); }
public string ToString(ISqlDialect dialect) { var sql = new StringBuilder(); sql.AppendFormat("update {0} set ", table.ToString(dialect)); foreach (var set in sets) { sql.AppendFormat("{0} = {1}, ", set.Key, set.Value is ISqlInstruction ? ((ISqlInstruction)set.Value).ToString(dialect) : "?"); } expressions.ForEach(expression => sql.AppendFormat("{0}, ", expression)); sql.Remove(sql.Length - 2, 2); if (where != Exp.Empty) sql.AppendFormat(" where {0}", where.ToString(dialect)); return sql.ToString(); }
public CommonDbStatement( ISqlDialect dialect, TransactionScope scope, IDbConnection connection, IDbTransaction transaction) { Parameters = new Dictionary<string, Tuple<object, DbType?>>(); _dialect = dialect; _scope = scope; _connection = connection; _transaction = transaction; }
public CommonDbStatement( ISqlDialect dialect, TransactionScope scope, IDbConnection connection, IDbTransaction transaction) { this.Parameters = new Dictionary<string, object>(); this.dialect = dialect; this.scope = scope; this.connection = connection; this.transaction = transaction; }
public SqlPersistenceFactory( IConnectionFactory factory, ISerialize serializer, ISqlDialect dialect, TransactionScopeOption scopeOption, int pageSize) : this(serializer, scopeOption, pageSize) { if (dialect == null) throw new ArgumentNullException("dialect"); this.connectionFactory = factory; this.dialect = dialect; }
private static string DumpParameterValue(object value, ISqlDialect dialect = null) { if (value == null || value == DBNull.Value) return "NULL"; var str = value as string; if (str != null) return str.ToSql(dialect); if (value is char || value is char[]) return value.ToString().ToSql(dialect); if (value is bool) return ((bool)value) ? "1" : "0"; if (value is DateTime) { var date = (DateTime)value; if (date.Date == date) return date.ToSqlDate(dialect); else return ((DateTime)value).ToSql(dialect); } if (value is DateTimeOffset) return "'" + ((DateTimeOffset)value).ToString("o") + "'"; if (value is Guid) return ((Guid)value).ToString(); if (value is MemoryStream) value = ((MemoryStream)value).ToArray(); if (value is byte[]) { var data = (byte[])value; var sb = new StringBuilder("0x"); for (var i = 0; i < data.Length; i++) sb.Append(data[i].ToString("h2")); return sb.ToString(); } if (value is IFormattable) return ((IFormattable)value).ToString(null, CultureInfo.InvariantCulture); return value.ToString(); }
public static string WrapWithQuotes(this ISqlDialect target, string phrase) { return($"{target.OpenQuote}{phrase}{target.CloseQuote}"); }
public EfzQuerySplitter(ISqlDialect dialect) : base(dialect) { }
public SQLinqUpdateResult(ISqlDialect dialect) { this.Dialect = dialect; }
private ExpressionAttribute GetBestMatchingExpression(IEnumerable <ExpressionAttribute> expressions, ref string dialectServerType, ref string dialectTypeName) { if (!expressions.Any(x => !string.IsNullOrEmpty(x.Dialect))) { return(expressions.FirstOrDefault()); } if (dialectTypeName == null) { ISqlDialect dialect = null; if (!string.IsNullOrEmpty(connectionKey)) { var csi = SqlConnections.TryGetConnectionString(connectionKey); if (csi != null) { dialect = csi.Dialect; } } dialect = dialect ?? SqlSettings.DefaultDialect; dialectServerType = dialect.ServerType; dialectTypeName = dialect.GetType().Name; } var st = dialectServerType; var tn = dialectTypeName; Func <string, bool> isMatch = s => { return(st.StartsWith(s, StringComparison.OrdinalIgnoreCase) || tn.StartsWith(s, StringComparison.OrdinalIgnoreCase)); }; Dictionary <ExpressionAttribute, int> weight = null; var bestMatch = expressions.Where(x => { if (string.IsNullOrEmpty(x.Dialect)) { return(true); } if (x.Dialect.IndexOf(',') < 0) { return(isMatch(x.Dialect)); } var best = x.Dialect.Split(comma, StringSplitOptions.RemoveEmptyEntries) .Select(z => z.Trim()) .Where(z => isMatch(z)) .OrderByDescending(z => z.Length) .FirstOrDefault(); if (best != null) { if (weight == null) { weight = new Dictionary <ExpressionAttribute, int>(); } weight[x] = best.Length; return(true); } return(false); }) .OrderByDescending(x => { if (string.IsNullOrEmpty(x.Dialect)) { return(0); } int w; if (weight != null && weight.TryGetValue(x, out w)) { return(w); } return(x.Dialect.Length); }) .FirstOrDefault(); return(bestMatch); }
/// <summary> /// 处理 /// where(x=>x.name==null) /// where(x=>x.name.contains("")) /// where(x=>(x.age/20)>9) /// order(x=>x.xx) /// select(x=>x.name) /// select(x=>new {x.name,x.age}) /// </summary> /// <param name="expr"></param> /// <param name="func"></param> /// <returns></returns> public static string Transform(Expression expr, ISqlDialect db, ref ExpressionParsedResult model) { switch (expr.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.ArrayIndex: case ExpressionType.Assign: case ExpressionType.Coalesce: case ExpressionType.Divide: case ExpressionType.Equal: case ExpressionType.ExclusiveOr: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LeftShift: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Modulo: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.NotEqual: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.Power: case ExpressionType.RightShift: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.MultiplyAssignChecked: case ExpressionType.SubtractAssignChecked: return(TransformX((BinaryExpression)expr, db, ref model)); case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: case ExpressionType.Decrement: case ExpressionType.Increment: case ExpressionType.IsFalse: case ExpressionType.IsTrue: case ExpressionType.Throw: case ExpressionType.Unbox: case ExpressionType.OnesComplement: return(TransformX((UnaryExpression)expr, db, ref model)); case ExpressionType.Call: return(TransformX((MethodCallExpression)expr, db, ref model)); case ExpressionType.Lambda: return(TransformX((LambdaExpression)expr, db, ref model)); case ExpressionType.ListInit: return(TransformX((ListInitExpression)expr, db, ref model)); case ExpressionType.MemberAccess: return(TransformX((MemberExpression)expr, db, ref model)); case ExpressionType.MemberInit: return(TransformX((MemberInitExpression)expr, db, ref model)); case ExpressionType.New: return(TransformX((NewExpression)expr, db, ref model)); case ExpressionType.NewArrayBounds: return(TransformX((NewArrayExpression)expr, db, ref model)); case ExpressionType.NewArrayInit: return(TransformX((NewArrayExpression)expr, db, ref model)); case ExpressionType.TypeEqual: case ExpressionType.ArrayLength: case ExpressionType.PreIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PostDecrementAssign: case ExpressionType.Conditional: case ExpressionType.Invoke: case ExpressionType.TypeIs: case ExpressionType.Block: case ExpressionType.DebugInfo: case ExpressionType.Default: case ExpressionType.Constant: case ExpressionType.Parameter: case ExpressionType.Dynamic: case ExpressionType.Goto: case ExpressionType.Index: case ExpressionType.Label: case ExpressionType.RuntimeVariables: case ExpressionType.Loop: case ExpressionType.Switch: case ExpressionType.Try: case ExpressionType.Extension: break; } throw new NotSupportedException($"不支持的表达式类型:{expr.NodeType}"); }
private static void CreateDatabaseIfNotExists(ConnectionStringSettings connectionStringSettings, DbProviderFactory factory, ISqlDialect dialect) { using (new TimedOperation("-- Checking for Existence of Database...")) { var connectionStringManipulator = new ConnectionStringManipulator(connectionStringSettings.ToSystem()); using (var connection = factory.CreateConnection()) { connection.ConnectionString = connectionStringManipulator.GetRootConnectionString().ConnectionString; connection.Open(); var databaseName = connectionStringManipulator.GetDatabaseName(); Trace("Looking for {0}", databaseName); if (!connection.Query(dialect.CheckDatabaseExists(databaseName)).Any()) { Trace("Not Found"); Trace("Creating"); connection.Execute(dialect.CreateDatabase(databaseName)); Trace("Created"); } else { Trace("Found!"); } } } }
public static Dnc.Extensions.Dapper.DapperSql ParseToDapperSql <T>(this BaseSearch <T> search, ISqlDialect dialect, string tableAlias = null) { if (search == null) { return(null); } tableAlias = string.IsNullOrEmpty(tableAlias) ? "" : tableAlias + "."; List <string> sqls = new List <string>(); Dictionary <string, object> allParameters = new Dictionary <string, object>(); foreach (PropertyInfo p in search.GetType().GetProperties()) { (string sql, Dictionary <string, object> parameters) = ParseProperty(search, p, dialect, tableAlias); if (sql != null) { sqls.Add(sql); allParameters.TryConcat(parameters); } } var allSql = string.Join(" AND ", sqls.ToArray()); return(new Dnc.Extensions.Dapper.DapperSql(allSql, allParameters)); }
public SqlPersistenceFactory(string connectionName, ISerialize serializer, ISqlDialect dialect = null) : this(serializer, TransactionScopeOption.Suppress, DefaultPageSize) { _connectionFactory = new ConfigurationConnectionFactory(connectionName); _dialect = dialect ?? ResolveDialect(new ConfigurationConnectionFactory(connectionName).Settings); }
public abstract string ToSqlString(ISqlDialect dialect, bool ignoreOrderBy = false);
public static string OrderBy(this ISqlDialect dialect, IList <Tuple <string, string, bool> > columns) { return(StringBuilderPool.Scoped(sb => { AppendOrderBy(sb, dialect, columns); })); }
public DapperExtensionConfiguration(Type defaultMapper, IList <Assembly> mappingAssemblies, ISqlDialect sqlDialect) { this.DefaultMapper = defaultMapper; this.MappingAssemblies = mappingAssemblies ?? new List <Assembly>(); this.Dialect = sqlDialect; }
/// <summary> /// Initializes a new instance of the <see cref="QueryWithParams"/> class. /// </summary> public QueryWithParams() { dialect = SqlSettings.DefaultDialect; }
public static string Select(this ISqlDialect d, string table, string schema = "") { return(StringBuilderPool.Scoped(sb => { sb.Append("SELECT * FROM ").AppendTable(d, table, schema); })); }
public SqlEditorAnalyser(ITokenStream input, ISqlDialect dialect) { m_input = input; m_dialect = dialect; m_tokens = dialect.GetAntlrTokens(); }
static string TransformX(Expression e, ISqlDialect db, ref ExpressionParsedResult nn) { throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the <see cref="ConstantCriteria"/> class. /// </summary> /// <param name="value">The value.</param> /// <param name="dialect">The dialect.</param> public ConstantCriteria(string value, ISqlDialect dialect = null) : base(value.ToSql(dialect)) { }
public CountWriter(ISqlDialect dialect, IConfiguration configuration) : base(dialect, configuration) { }
public override string ToString(ISqlDialect dialect) { return(string.Format("{0} {1}between ? and ?", column, Not ? "not " : string.Empty)); }
public override async Task ExecuteAsync(DbConnection connection, DbTransaction transaction, ISqlDialect dialect, ILogger logger) { var documentTable = CollectionHelper.Current.GetPrefixedName(Store.DocumentTable); var sql = Inserts(_index, dialect, _tableName) + " " + dialect.IdentitySelectString + " " + dialect.QuoteForColumnName("Id"); logger.LogTrace(sql); var IndexId = await connection.ExecuteScalarAsync <int>(sql, null, transaction); var command = "update " + dialect.QuoteForTableName(_tablePrefix + _tableName) + " set " + dialect.QuoteForColumnName("DocumentId") + " = @mapid where " + dialect.QuoteForColumnName("Id") + " = @Id"; logger.LogTrace(command); await connection.ExecuteAsync(command, new { mapid = Document.Id, Id = IndexId }, transaction); }
/// <summary> /// Configure DapperExtensions extension methods. /// </summary> /// <param name="defaultMapper"></param> /// <param name="mappingAssemblies"></param> /// <param name="sqlDialect"></param> public static void Configure(this Type defaultMapper, IList <Assembly> mappingAssemblies, ISqlDialect sqlDialect) { Configure(new DapperExtensionsConfiguration(defaultMapper, mappingAssemblies, sqlDialect)); }
protected AssigmentOperationBase(string name, [NotNull] ISqlDialect dialect, [NotNull] INameConverter nameConverter) { Name = name; _nameConverter = nameConverter ?? throw new ArgumentNullException(nameof(nameConverter)); Dialect = dialect ?? throw new ArgumentNullException(nameof(dialect)); }
public SqlBuilder(string tablePrefix, ISqlDialect dialect) { _tablePrefix = tablePrefix; _dialect = dialect; }
public override Task ExecuteAsync(DbConnection connection, DbTransaction transaction, ISqlDialect dialect, ILogger logger) { var documentTable = _tableNameConvention.GetDocumentTable(Collection); var insertCmd = $"insert into {dialect.QuoteForTableName(_tablePrefix + documentTable)} ({dialect.QuoteForColumnName("Id")}, {dialect.QuoteForColumnName("Type")}, {dialect.QuoteForColumnName("Content")}, {dialect.QuoteForColumnName("Version")}) values (@Id, @Type, @Content, @Version);"; logger.LogTrace(insertCmd); return(connection.ExecuteAsync(insertCmd, Document, transaction)); }
public static string Format(ISqlDialect dialect, SqlFormatProperties props, SqlFormatterState state, string format, params object[] args) { IDialectDataAdapter dda = null; if (state != null) { dda = state.DDA; } if (dda == null) { dda = dialect.CreateDataAdapter(); } int argindex = 0; StringBuilder sb = new StringBuilder(); int i = 0; while (i < format.Length) { char c = format[i]; switch (c) { case '^': // SQL keyword { i++; SymbolPosition original = null; if (format[i] == ':') { original = (SymbolPosition)args[argindex]; argindex++; i++; } DumpSeparatorIfNeeded(sb, props, state, original); while (i < format.Length && (Char.IsLetter(format, i) || format[i] == '_')) { sb.Append(GetCasedChar(format[i], props.SqlCommandCase)); i++; } DataDumped(state); } break; case '&': // indentation & spacing { i++; c = format[i]; i++; char level = '0'; if (c == '1' || c == '2' || c == '3' || c == '5') { level = c; c = format[i]; i++; } if (level != '0') { // indentation levels if (props.IndentationLevel == SqlIndentationLevel.Original || props.IndentationLevel == SqlIndentationLevel.SingleLine) { if (c == 'n' || c == 's') { if (state != null) { state.SeparatorNeeded = true; } else { sb.Append(" "); } } // when original indentation is used, don't use our separators break; } bool valid = (props.IndentationLevel == SqlIndentationLevel.Compact && (level == '2' || level == '5')) || (props.IndentationLevel == SqlIndentationLevel.Large && (level == '3' || level == '5')); if (!valid) { break; // mark is not for this indentation level } } switch (c) { case '&': sb.Append("&"); break; case 'n': if (state == null) { DumpEoln(sb, props, state); } else { state.LineFeedNeeded = true; } break; case '>': if (state != null) { state.IndentLevel++; } break; case '<': if (state != null) { state.IndentLevel--; } break; case 's': if (state != null) { state.SeparatorNeeded = true; } else { sb.Append(" "); } break; default: throw new InternalError("DAE-00041 Unknown & formatting instruction:" + c); } } break; case '%': // format parameter { i++; c = format[i]; if (c == '%') { sb.Append('%'); i++; } else if (c == ',') // comma separated list { i++; c = format[i]; bool ok = false; if (args[argindex] is IEnumerable) { ok = true; } if (args[argindex] is IBedRecord && c == 'v') { ok = true; } if (!ok) { throw new InternalError("DAE-00042 List must be of type Enumerable"); } bool was = false; if (args[argindex] is IEnumerable) { foreach (object item in (IEnumerable)args[argindex]) { if (was) { sb.Append(", "); } WriteFormattedValue(dialect, props, sb, item, c, null, state, dda); was = true; } } else { var rec = (IBedRecord)args[argindex]; for (int x = 0; x < rec.FieldCount; x++) { if (was) { sb.Append(", "); } rec.ReadValue(x); sb.Append(GetSqlLiteral(props, dda, state, rec)); was = true; } } argindex++; i++; } else if (c == ':') { object orig = args[argindex]; argindex++; i++; c = format[i]; object arg = args[argindex]; argindex++; i++; WriteFormattedValue(dialect, props, sb, arg, c, orig, state, dda); } else { WriteFormattedValue(dialect, props, sb, args[argindex], c, null, state, dda); argindex++; i++; } } break; default: { if (Char.IsWhiteSpace(c)) { if (state != null) { state.SeparatorNeeded = false; } } else { DumpSeparatorIfNeeded(sb, props, state, null); } sb.Append(c); i++; } break; } } return(sb.ToString()); }
public override async Task ExecuteAsync(DbConnection connection, DbTransaction transaction, ISqlDialect dialect, ILogger logger) { var type = Index.GetType(); var name = type.Name; var documentTable = _store.Configuration.TableNameConvention.GetDocumentTable(Collection); var bridgeTableName = _store.Configuration.TableNameConvention.GetIndexTable(type, Collection) + "_" + documentTable; var bridgeSql = "delete from " + dialect.QuoteForTableName(_store.Configuration.TablePrefix + bridgeTableName) + " where " + dialect.QuoteForColumnName(name + "Id") + " = @Id"; logger.LogTrace(bridgeSql); await connection.ExecuteAsync(bridgeSql, new { Id = Index.Id }, transaction); var command = "delete from " + dialect.QuoteForTableName(_store.Configuration.TablePrefix + _store.Configuration.TableNameConvention.GetIndexTable(type, Collection)) + " where " + dialect.QuoteForColumnName("Id") + " = @Id"; logger.LogTrace(command); await connection.ExecuteAsync(command, new { Id = Index.Id }, transaction); }
private static void WriteFormattedValue(ISqlDialect dialect, SqlFormatProperties props, StringBuilder sb, object val, char fmt, object orig, SqlFormatterState state, IDialectDataAdapter dda) { switch (fmt) { case 'i': // quote identifier DumpSeparatorIfNeeded(sb, props, state, (SymbolPosition)orig); if (val is string) { sb.Append(QuoteIdentifier(dialect, props, (string)val, (SymbolPosition)orig)); } else if (val is IColumnReference) { sb.Append(QuoteIdentifier(dialect, props, ((IColumnReference)val).ColumnName, (SymbolPosition)orig)); } else { throw new InternalError("DAE-00043 Identifier must be of type string or IColumnReference"); } DataDumped(state); break; case 'f': // quote full name DumpSeparatorIfNeeded(sb, props, state, (SymbolPosition)orig); if (val is NameWithSchema) { sb.Append(QuoteFullName(dialect, props, (NameWithSchema)val)); } else if (val is IFullNamedObject) { sb.Append(QuoteFullName(dialect, props, ((IFullNamedObject)val).FullName)); } else { throw new InternalError("DAE-00044 Full name must be of type NameWithSchema or IFullNamedObject"); } DataDumped(state); break; case 's': // string - copy character data if (val != null) { DumpSeparatorIfNeeded(sb, props, state, (SymbolPosition)orig); sb.Append(val.ToString()); DataDumped(state); } break; case 'k': // keyword DumpSeparatorIfNeeded(sb, props, state, (SymbolPosition)orig); if (!(val is string)) { throw new InternalError("DAE-00045 Identifier must be of type string"); } if (props.SqlCommandCase == CharacterCase.Original && orig != null) { sb.Append(((SymbolPosition)orig).GetOriginalToken()); } else { foreach (char c2 in (string)val) { sb.Append(GetCasedChar(c2, props.SqlCommandCase)); } } DataDumped(state); break; case 'K': // multi-word keyword if (!(val is IEnumerable <string>)) { throw new InternalError("DAE-00046 Identifier must be of type string"); } if (orig != null) { foreach (var sym in ((IEnumerable <SymbolPosition>)orig)) { DumpSeparatorIfNeeded(sb, props, state, sym); sb.Append(GetCasedString(sym.GetOriginalToken(), props.SqlCommandCase)); if (state != null) { state.SeparatorNeeded = true; } else { sb.Append(" "); } DataDumped(state); } } else { foreach (string s in ((IEnumerable <string>)val)) { DumpSeparatorIfNeeded(sb, props, state, null); sb.Append(GetCasedString(s, props.SqlCommandCase)); if (state != null) { state.SeparatorNeeded = true; } else { sb.Append(" "); } DataDumped(state); } } break; case 'v': // value - copy character data DumpSeparatorIfNeeded(sb, props, state, (SymbolPosition)orig); if (props.UseOriginalValues && orig != null) { sb.Append(((SymbolPosition)orig).GetOriginalToken()); } else { var vth = val as ValueTypeHolder; if (vth != null) { sb.Append(GetSqlLiteralAndRead(props, dda, state, vth.Value, vth.DbType)); } else { sb.Append(GetSqlLiteralAndRead(props, dda, state, val)); } } DataDumped(state); break; case 't': // version test if (val != null && !props.OmitVersionTests) { sb.Append(val.ToString()); } break; default: throw new InternalError("DAE-00047 Unknown format character: " + fmt); } }
private ISqlDialect GetDialect() { return(dialect ?? (dialect = DbRegistry.GetSqlDialect(DatabaseId))); }
public static string Format(ISqlDialect dialect, string format, params object[] args) { return(Format(dialect, SqlFormatProperties.Default, null, format, args)); }
/// <summary> /// Initializes a new instance of the <see cref="ConstantCriteria"/> class. /// </summary> /// <param name="values">The values.</param> /// <param name="dialect">The dialect.</param> public ConstantCriteria(IEnumerable <string> values, ISqlDialect dialect = null) : base(string.Join(",", values.Select(x => x.ToSql(dialect)))) { }
public MySqlSqlBuilder(string tablePrefix, ISqlDialect dialect) : base(tablePrefix, dialect) { }
public SqlPersistenceFactory( IConnectionFactory factory, ISerialize serializer, ISqlDialect dialect, TransactionScopeOption scopeOption) { this.connectionFactory = factory; this.serializer = serializer; this.dialect = dialect; this.scopeOption = scopeOption; }