Пример #1
0
        public bool Equals(NamingStrategy other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;

            return Equals(other.strategy, strategy);
        }
 /// <inheritdoc />
 public override OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy)
 {
     return(this.PayloadVisit(dataType: "string", dataFormat: "date-time"));
 }
Пример #3
0
        /// <inheritdoc />
        public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var instance = acceptor as OpenApiSchemaAcceptor;

            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Gets the schema for the underlying type.
            var underlyingType = type.Value.GetUnderlyingType();
            var types          = new Dictionary <string, Type>()
            {
                { type.Key, underlyingType }
            };
            var schemas = new Dictionary <string, OpenApiSchema>();

            var subAcceptor = new OpenApiSchemaAcceptor()
            {
                Types   = types,
                Schemas = schemas,
            };

            subAcceptor.Accept(this.VisitorCollection, namingStrategy);

            // Adds the schema for the underlying type.
            var name   = subAcceptor.Schemas.First().Key;
            var schema = subAcceptor.Schemas.First().Value;

            schema.Nullable = true;

            // Adds the visibility property.
            if (attributes.Any())
            {
                var visibilityAttribute = attributes.OfType <OpenApiSchemaVisibilityAttribute>().SingleOrDefault();
                if (!visibilityAttribute.IsNullOrDefault())
                {
                    var extension = new OpenApiString(visibilityAttribute.Visibility.ToDisplayName());

                    schema.Extensions.Add("x-ms-visibility", extension);
                }
            }

            instance.Schemas.Add(name, schema);
        }
Пример #4
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();

            foreach (var fieldDef in modelDef.FieldDefinitionsArray)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef))
                {
                    continue;
                }

                //insertFields contains Property "Name" of fields to insert ( that's how expressions work )
                if (insertFields != null && !insertFields.Contains(fieldDef.Name, StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (SupportsSequences(fieldDef))
                    {
                        sbColumnValues.Append("NEXT VALUE FOR " + Sequence(NamingStrategy.GetSchemaName(modelDef), fieldDef.Sequence));
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning    = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            cmd.CommandText = $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
                              strReturning +
                              $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})";
        }
Пример #5
0
 public EntitySerializer(ISerializerProvider serializerProvider, NamingStrategy namingStrategy, IUrlProvider urlProvider)
     : base(serializerProvider, namingStrategy)
 {
     UrlProvider = urlProvider;
 }
 public JObjectConverter(NamingStrategy namingStrategy)
 {
     this.NamingStrategy = namingStrategy ?? throw new ArgumentNullException(nameof(namingStrategy));
 }
Пример #7
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef) && !fieldDef.AutoId)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (SupportsSequences(fieldDef))
                    {
                        sbColumnValues.Append("NEXT VALUE FOR " + Sequence(NamingStrategy.GetSchemaName(modelDef), fieldDef.Sequence));
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            foreach (var fieldDef in modelDef.AutoIdFields) // need to include any AutoId fields that weren't included
            {
                if (fieldDefs.Contains(fieldDef))
                {
                    continue;
                }

                if (sbReturningColumns.Length > 0)
                {
                    sbReturningColumns.Append(",");
                }
                sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning    = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            cmd.CommandText = sbColumnNames.Length > 0
                ? $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) {strReturning}" +
                              $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})"
                : $"INSERT INTO {GetQuotedTableName(modelDef)}{strReturning} DEFAULT VALUES";
        }
Пример #8
0
 private string Sequence(string modelName, string fieldName, string sequence)
 {
     return(sequence.IsNullOrEmpty()
         ? Quote(NamingStrategy.GetSequenceName(modelName, fieldName))
         : Quote(sequence));
 }
        public override string ToInsertRowStatement(IDbCommand dbCommand, object objWithProperties, ICollection <string> insertFields = null)
        {
            if (insertFields == null)
            {
                insertFields = new List <string>();
            }

            var sbColumnNames  = new StringBuilder();
            var sbColumnValues = new StringBuilder();

            var tableType = objWithProperties.GetType();
            var modelDef  = GetModel(tableType);

            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
                if (fieldDef.IsComputed)
                {
                    continue;
                }
                if (insertFields.Count > 0 && !insertFields.Contains(fieldDef.Name))
                {
                    continue;
                }

                if ((fieldDef.AutoIncrement || !string.IsNullOrEmpty(fieldDef.Sequence) ||
                     fieldDef.Name == OrmLiteConfig.IdField) &&
                    dbCommand != null)
                {
                    if (fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))
                    {
                        fieldDef.Sequence = Sequence(
                            (modelDef.IsInSchema
                                                                ? modelDef.Schema + "_" + NamingStrategy.GetTableName(modelDef.ModelName)
                                                                : NamingStrategy.GetTableName(modelDef.ModelName)),
                            fieldDef.FieldName, fieldDef.Sequence);
                    }

                    PropertyInfo pi = tableType.GetProperty(fieldDef.Name,
                                                            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);

                    var result = GetNextValue(dbCommand.Connection, fieldDef.Sequence, pi.GetValue(objWithProperties, new object[] { }));
                    if (pi.PropertyType == typeof(String))
                    {
                        pi.SetProperty(objWithProperties, result.ToString());
                    }
                    else if (pi.PropertyType == typeof(Int16))
                    {
                        pi.SetProperty(objWithProperties, Convert.ToInt16(result));
                    }
                    else if (pi.PropertyType == typeof(Int32))
                    {
                        pi.SetProperty(objWithProperties, Convert.ToInt32(result));
                    }
                    else if (pi.PropertyType == typeof(Guid))
                    {
                        pi.SetProperty(objWithProperties, result);
                    }
                    else
                    {
                        pi.SetProperty(objWithProperties, Convert.ToInt64(result));
                    }
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(string.Format("{0}", GetQuotedColumnName(fieldDef.FieldName)));
                    if (!string.IsNullOrEmpty(fieldDef.Sequence) && dbCommand == null)
                    {
                        sbColumnValues.Append(string.Format("@{0}", fieldDef.Name));
                    }
                    else
                    {
                        sbColumnValues.Append(fieldDef.GetQuotedValue(objWithProperties));
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            var sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2}) ",
                                    GetQuotedTableName(modelDef), sbColumnNames, sbColumnValues);

            return(sql);
        }
Пример #10
0
        private static IReadOnlyCollection <Error> FromModelState(ModelStateDictionary modelState, Type resourceType,
                                                                  bool includeExceptionStackTraceInErrors, NamingStrategy namingStrategy)
        {
            List <Error> errors = new List <Error>();

            foreach (var(propertyName, entry) in modelState.Where(x => x.Value.Errors.Any()))
            {
                string attributeName = GetDisplayNameForProperty(propertyName, resourceType, namingStrategy);

                foreach (var modelError in entry.Errors)
                {
                    if (modelError.Exception is JsonApiException jsonApiException)
                    {
                        errors.Add(jsonApiException.Error);
                    }
                    else
                    {
                        errors.Add(FromModelError(modelError, attributeName, includeExceptionStackTraceInErrors));
                    }
                }
            }

            return(errors);
        }
Пример #11
0
 protected string GetTableName(string name)
 {
     return(NamingStrategy.TableName(name));
 }
Пример #12
0
 protected string GetColumnName(string name)
 {
     return(NamingStrategy.ColumnName(name));
 }
Пример #13
0
        public override string ToCreateTableStatement(Type tableType)
        {
            var sbColumns     = new StringBuilder();
            var sbConstraints = new StringBuilder();
            var sbPk          = new StringBuilder();

            var modelDef = GetModel(tableType);

            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
                if (fieldDef.IsPrimaryKey)
                {
                    sbPk.AppendFormat(sbPk.Length != 0 ? ",{0}" : "{0}", GetQuotedColumnName(fieldDef.FieldName));
                }

                if (sbColumns.Length != 0)
                {
                    sbColumns.Append(", \n  ");
                }

                var columnDefinition = GetColumnDefinition(
                    fieldDef.FieldName,
                    fieldDef.ColumnType,
                    fieldDef.IsPrimaryKey,
                    fieldDef.AutoIncrement,
                    fieldDef.IsNullable,
                    fieldDef.IsRowVersion,
                    fieldDef.FieldLength,
                    fieldDef.Scale,
                    GetDefaultValue(fieldDef),
                    fieldDef.CustomFieldDefinition);

                sbColumns.Append(columnDefinition);

                if (fieldDef.ForeignKey == null)
                {
                    continue;
                }

                var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);

                var fkName = NamingStrategy.ApplyNameRestrictions(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef)).ToLower();
                sbConstraints.AppendFormat(", \n\n  CONSTRAINT {0} FOREIGN KEY ({1}) REFERENCES {2} ({3})",
                                           GetQuotedName(fkName),
                                           GetQuotedColumnName(fieldDef.FieldName),
                                           GetQuotedTableName(refModelDef),
                                           GetQuotedColumnName(refModelDef.PrimaryKey.FieldName));

                sbConstraints.Append(GetForeignKeyOnDeleteClause(fieldDef.ForeignKey));
                sbConstraints.Append(GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
            }

            if (sbPk.Length != 0)
            {
                sbColumns.AppendFormat(", \n  PRIMARY KEY({0})", sbPk);
            }

            var sql = new StringBuilder(string.Format(
                                            "CREATE TABLE {0} \n(\n  {1}{2} \n); \n",
                                            GetQuotedTableName(modelDef),
                                            sbColumns,
                                            sbConstraints));

            return(sql.ToString());
        }
Пример #14
0
 protected override string GetIndexName(bool isUnique, string modelName, string fieldName)
 {
     return(NamingStrategy.ApplyNameRestrictions(
                $"{(isUnique ? "u" : "")}idx_{modelName}_{fieldName}".ToLower()));
 }
Пример #15
0
        public override string ToChangeColumnNameStatement(Type modelType, FieldDefinition fieldDef, string oldColumnName)
        {
            var objectName = $"{NamingStrategy.GetTableName(GetModel(modelType).ModelName)}.{oldColumnName}";

            return($"sp_rename ({GetQuotedValue(objectName)}, {GetQuotedValue(fieldDef.FieldName)}, {GetQuotedValue("COLUMN")});");
        }
 private static INamingStrategy SetNamingStrategy(NamingStrategy namingStrategy)
 {
     logger.Message("Naming Strategy: " + namingStrategy.ToString());
     switch (namingStrategy)
     {
         case NamingStrategy.None:
             return new NoNamingStrategy();
         case NamingStrategy.Districts:
             return new DistrictNamingStrategy();
         case NamingStrategy.London:
             return new LondonNamingStrategy();
         default:
             logger.Error("unknown naming strategy");
             return new NoNamingStrategy();
     }
 }
Пример #17
0
 public override string GetQuotedColumnName(string fieldName)
 {
     return(Quote(NamingStrategy.GetColumnName(fieldName)));
 }
 public override string GetQuotedTableName(string tableName)
 {
     return(Quote(NamingStrategy.GetTableName(tableName)));
 }
Пример #19
0
 public AlwaysProcessExtensionDataNamingStrategyWrapper(NamingStrategy namingStrategy)
 {
     _namingStrategy = namingStrategy ?? new DefaultNamingStrategy();
 }
 /// <inheritdoc />
 public override OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy)
 {
     return(this.PayloadVisit(dataType: "integer", dataFormat: "int32"));
 }
Пример #21
0
 /// <inheritdoc />
 public override OpenApiSchema ParameterVisit(Type type, NamingStrategy namingStrategy)
 {
     return(this.ParameterVisit(dataType: "string", dataFormat: "uri"));
 }
Пример #22
0
 public override string GetQuotedTableName(ModelDefinition modelDef)
 {
     return(string.Format("`{0}`", NamingStrategy.GetTableName(modelDef.ModelName)));
 }
 /// <inheritdoc />
 public override OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy)
 {
     return(this.PayloadVisit(dataType: "boolean", dataFormat: null));
 }
Пример #24
0
 public override string GetQuotedTableName(string tableName)
 {
     return(string.Format("`{0}`", NamingStrategy.GetTableName(tableName)));
 }
Пример #25
0
 public RenamingRewriter(Script script, NamingStrategy namingStrategy, ISlotAllocator slotAllocator)
 {
     _renameTable = new RenameTable(script, namingStrategy, slotAllocator);
 }
Пример #26
0
 /// <summary>Gets quoted column name.</summary>
 /// <param name="columnName">Name of the column.</param>
 /// <returns>The quoted column name.</returns>
 public override string GetQuotedColumnName(string columnName)
 {
     return(string.Format("`{0}`", NamingStrategy.GetColumnName(columnName)));
 }
 public void Init()
 {
     this._visitorCollection = new VisitorCollection();
     this._visitor           = new FakeTypeVisitor(this._visitorCollection);
     this._strategy          = new CamelCaseNamingStrategy();
 }
        private void ProcessProperties(IOpenApiSchemaAcceptor instance, string schemaName, Dictionary <string, PropertyInfo> properties, NamingStrategy namingStrategy)
        {
            var schemas = new Dictionary <string, OpenApiSchema>();

            var subAcceptor = new OpenApiSchemaAcceptor()
            {
                Properties  = properties,
                RootSchemas = instance.RootSchemas,
                Schemas     = schemas,
            };

            subAcceptor.Accept(this.VisitorCollection, namingStrategy);

            // Add required properties to schema.
            var jsonPropertyAttributes = properties.Where(p => !p.Value.GetCustomAttribute <JsonPropertyAttribute>(inherit: false).IsNullOrDefault())
                                         .Select(p => new KeyValuePair <string, JsonPropertyAttribute>(p.Key, p.Value.GetCustomAttribute <JsonPropertyAttribute>(inherit: false)))
                                         .Where(p => p.Value.Required == Required.Always || p.Value.Required == Required.DisallowNull);

            foreach (var attribute in jsonPropertyAttributes)
            {
                instance.Schemas[schemaName].Required.Add(attribute.Key);
            }

            var jsonRequiredAttributes = properties.Where(p => !p.Value.GetCustomAttribute <JsonRequiredAttribute>(inherit: false).IsNullOrDefault())
                                         .Select(p => new KeyValuePair <string, JsonRequiredAttribute>(p.Key, p.Value.GetCustomAttribute <JsonRequiredAttribute>(inherit: false)));

            foreach (var attribute in jsonRequiredAttributes)
            {
                var attributeName = namingStrategy.GetPropertyName(attribute.Key, hasSpecifiedName: false);
                if (instance.Schemas[schemaName].Required.Contains(attributeName))
                {
                    continue;
                }

                instance.Schemas[schemaName].Required.Add(attributeName);
            }

            instance.Schemas[schemaName].Properties = subAcceptor.Schemas;

            // Adds schemas to the root.
            var schemasToBeAdded = subAcceptor.Schemas
                                   .Where(p => !instance.Schemas.Keys.Contains(p.Key))
                                   .Where(p => p.Value.Type == "object" &&
                                          p.Value.Format.IsNullOrWhiteSpace() &&
                                          p.Value.Items.IsNullOrDefault() &&
                                          p.Value.AdditionalProperties.IsNullOrDefault())
                                   .ToDictionary(p => p.Value.Title, p => p.Value);

            foreach (var schema in schemasToBeAdded.Where(p => p.Key != "jObject" && p.Key != "jToken"))
            {
                if (instance.RootSchemas.ContainsKey(schema.Key))
                {
                    continue;
                }

                instance.RootSchemas.Add(schema.Key, schema.Value);
            }

            // Removes title of each property.
            var subSchemas = instance.Schemas[schemaName].Properties;

            subSchemas = subSchemas.Select(p =>
            {
                p.Value.Title = null;
                return(new KeyValuePair <string, OpenApiSchema>(p.Key, p.Value));
            })
                         .ToDictionary(p => p.Key, p => p.Value);

            instance.Schemas[schemaName].Properties = subSchemas;
        }
 /// <inheritdoc />
 public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
 {
     this.Visit(acceptor, name: type.Key, title: null, dataType: "string", dataFormat: "date-time", attributes: attributes);
 }
        /// <inheritdoc />
        public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var title = namingStrategy.GetPropertyName(type.Value.Name, hasSpecifiedName: false);
            var name  = this.Visit(acceptor, name: type.Key, title: title, dataType: "object", dataFormat: null, attributes: attributes);

            if (name.IsNullOrWhiteSpace())
            {
                return;
            }

            if (!this.IsNavigatable(type.Value))
            {
                return;
            }

            var instance = acceptor as OpenApiSchemaAcceptor;

            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Processes non-recursive properties
            var properties = type.Value
                             .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                             .Where(p => !p.ExistsCustomAttribute <JsonIgnoreAttribute>())
                             .Where(p => p.PropertyType != type.Value)
                             .ToDictionary(p => p.GetJsonPropertyName(namingStrategy), p => p);

            this.ProcessProperties(instance, name, properties, namingStrategy);

            // Processes recursive properties
            var recursiveProperties = type.Value
                                      .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                      .Where(p => !p.ExistsCustomAttribute <JsonIgnoreAttribute>())
                                      .Where(p => p.PropertyType == type.Value)
                                      .ToDictionary(p => p.GetJsonPropertyName(namingStrategy), p => p);
            var recursiveSchemas = recursiveProperties.ToDictionary(p => p.Key,
                                                                    p => new OpenApiSchema()
            {
                Type      = "object",
                Reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id   = p.Value.PropertyType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
                }
            });

            foreach (var recursiveSchema in recursiveSchemas)
            {
                instance.Schemas[name].Properties.Add(recursiveSchema);
            }

            // Adds the reference.
            var reference = new OpenApiReference()
            {
                Type = ReferenceType.Schema,
                Id   = type.Value.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
            };

            instance.Schemas[name].Reference = reference;
        }
Пример #31
0
        public ResourceNameFormatter(IJsonApiOptions options)
        {
            var contractResolver = (DefaultContractResolver)options.SerializerSettings.ContractResolver;

            _namingStrategy = contractResolver.NamingStrategy;
        }
Пример #32
0
 protected override string GetIndexName(bool isUnique, string modelName, string fieldName)
 {
     return(NamingStrategy.ApplyNameRestrictions(
                string.Format("{0}idx_{1}_{2}", isUnique ? "u" : "", modelName, fieldName).ToLower()));
 }