예제 #1
0
        private static IReadOnlySchemaOptions ExecuteSchemaConfiguration(
            SchemaContext context,
            Action <ISchemaConfiguration> configure,
            List <SchemaError> errors)
        {
            try
            {
                // configure resolvers, custom types and type mappings.
                SchemaConfiguration configuration = new SchemaConfiguration(
                    context.ServiceManager.RegisterServiceProvider,
                    context.Types);
                configure(configuration);

                TypeFinalizer typeFinalizer = new TypeFinalizer(configuration);
                typeFinalizer.FinalizeTypes(context);
                errors.AddRange(typeFinalizer.Errors);

                return(new ReadOnlySchemaOptions(configuration.Options));
            }
            catch (Exception ex)
            {
                throw new SchemaException(new[]
                {
                    new SchemaError(ex.Message, null, ex)
                });
            }
        }
 public KeyStorageContext(DbContextOptions <KeyStorageContext> options,
                          Action <ISchemaConfigurationEditable> config = null)
     : base(options)
 {
     _configuration = new SchemaConfiguration();
     config?.Invoke(_configuration);
 }
        public KeyRepository(string connectionString, string schema = "public", bool useDefaultSchema = true)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            if (string.IsNullOrWhiteSpace(schema))
            {
                throw new ArgumentNullException(nameof(schema));
            }

            if (!ValidateSqlIdentifier(schema))
            {
                throw new ArgumentException($"Provided schema name: '{schema}' is invalid.", nameof(schema));
            }

            _connectionString = connectionString;
            _schema           = schema;
            _configuration    = new SchemaConfiguration(useDefaultSchema);

            if (!ValidateSqlIdentifier(_configuration.Table))
            {
                throw new ArgumentException($"Provided table name: '{_configuration.Table}' is invalid.",
                                            nameof(_configuration.Table));
            }

            CreateTable();
            MaybeCreateFriendlyNameIndex();
        }
예제 #4
0
        public void CreateIncludeDirective()
        {
            // arrange
            SchemaContext       schemaContext       = SchemaContextFactory.Create();
            SchemaConfiguration schemaConfiguration =
                new SchemaConfiguration(sp => { }, schemaContext.Types);
            TypeFinalizer typeFinalizer = new TypeFinalizer(schemaConfiguration);

            typeFinalizer.FinalizeTypes(schemaContext, null);

            // assert
            Directive directive = schemaContext.Directives
                                  .GetDirectives().FirstOrDefault(t => t.Name == "include");

            // assert
            Assert.NotNull(directive);
            Assert.IsType <IncludeDirective>(directive);
            Assert.Equal("include", directive.Name);
            Assert.Collection(directive.Arguments,
                              t =>
            {
                Assert.Equal("if", t.Name);
                Assert.IsType <NonNullType>(t.Type);
                Assert.IsType <BooleanType>(((NonNullType)t.Type).Type);
            });
            Assert.Collection(directive.Locations,
                              t => Assert.Equal(DirectiveLocation.Field, t),
                              t => Assert.Equal(DirectiveLocation.FragmentSpread, t),
                              t => Assert.Equal(DirectiveLocation.InlineFragment, t));
        }
예제 #5
0
        /// <summary>
        /// Add GraphQL services to the specified <see cref="IServiceCollection">IServiceCollection</see>.
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configure">Action to configure the default schema.</param>
        /// <returns></returns>
        public static IGraphQlBuilder AddGraphQl(this IServiceCollection services, Action <SchemaConfiguration> configure)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            // commented out because of https://github.com/graphql-dotnet/graphql-dotnet/issues/478
            // to use it, uncomment the line in Program.cs
            // services.AddScoped<DocumentExecuter>();
            services.AddSingleton <DocumentExecuter>();

            var builder = new GraphQlBuilder(services);

            var schema = new SchemaConfiguration(null);

            configure(schema);

            return(builder.AddSchema(schema));
        }
예제 #6
0
        public void should_create_context_with_preconfigured_schema()
        {
            var schema = new SchemaConfiguration(c =>
            {
                c.FriendlyNameColumn = "Name";
                c.IdColumn           = "KeyId";
                c.Table     = "DataKeys";
                c.XmlColumn = "KeyXml";
            });

            _context = new KeyStorageContext(_builder.Options, schema);

            var dataProtectionKeyEntity = _context.Model.FindEntityType(typeof(DataProtectionKey));

            dataProtectionKeyEntity.ShouldNotBeNull();
            dataProtectionKeyEntity.GetTableName().ShouldEqual("DataKeys");

            var expectedProperties = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("FriendlyName", "Name"),
                new KeyValuePair <string, string>("Id", "KeyId"),
                new KeyValuePair <string, string>("Xml", "KeyXml")
            };

            should_have_correct_properties(dataProtectionKeyEntity, expectedProperties);
        }
예제 #7
0
        public void CreateUnion()
        {
            // arrange
            DocumentNode document = Parser.Default.Parse(
                "union X = A | B");
            UnionTypeDefinitionNode unionTypeDefinition = document
                                                          .Definitions.OfType <UnionTypeDefinitionNode>().First();

            var context       = new SchemaContext();
            var configuration = new SchemaConfiguration(
                context.RegisterServiceProvider,
                context.Types);

            configuration.RegisterType(new ObjectType(d =>
                                                      d.Name("A").Field("a").Type <StringType>()));
            configuration.RegisterType(new ObjectType(d =>
                                                      d.Name("B").Field("a").Type <StringType>()));

            // act
            var       factory   = new UnionTypeFactory();
            UnionType unionType = factory.Create(unionTypeDefinition);

            configuration.RegisterType(unionType);

            var typeFinalizer = new TypeFinalizer(configuration);

            typeFinalizer.FinalizeTypes(context, null);

            // assert
            Assert.Equal("X", unionType.Name);
            Assert.Equal(2, unionType.Types.Count);
            Assert.Equal("A", unionType.Types.First().Key);
            Assert.Equal("B", unionType.Types.Last().Key);
        }
예제 #8
0
        private static IReadOnlySchemaOptions ExecuteSchemaConfiguration(
            SchemaContext context,
            Action <ISchemaConfiguration> configure,
            List <SchemaError> errors)
        {
            try
            {
                // configure resolvers, custom types and type mappings.
                var configuration = new SchemaConfiguration(
                    context.RegisterServiceProvider,
                    context.Types,
                    context.Resolvers,
                    context.Directives);

                configuration.RegisterCustomContext <IResolverCache>(
                    ExecutionScope.Global,
                    s => new ResolverCache());

                configure(configuration);

                var options       = new ReadOnlySchemaOptions(configuration.Options);
                var typeFinalizer = new TypeFinalizer(configuration);
                typeFinalizer.FinalizeTypes(context, options.QueryTypeName);
                errors.AddRange(typeFinalizer.Errors);

                return(options);
            }
            catch (Exception ex)
            {
                throw new SchemaException(new[]
                {
                    new SchemaError(ex.Message, null, ex)
                });
            }
        }
예제 #9
0
        public void CreateEnum()
        {
            // arrange
            DocumentNode document = Parser.Default.Parse(
                "enum Abc { A B C }");
            EnumTypeDefinitionNode typeDefinition = document
                                                    .Definitions.OfType <EnumTypeDefinitionNode>().First();

            var context       = new SchemaContext();
            var configuration = new SchemaConfiguration(
                context.RegisterServiceProvider,
                context.Types);

            // act
            var      factory  = new EnumTypeFactory();
            EnumType enumType = factory.Create(typeDefinition);

            configuration.RegisterType(enumType);

            var typeFinalizer = new TypeFinalizer(configuration);

            typeFinalizer.FinalizeTypes(context, null);

            // assert
            Assert.Equal("Abc", enumType.Name);
            Assert.Collection(enumType.Values,
                              t => Assert.Equal("A", t.Name),
                              t => Assert.Equal("B", t.Name),
                              t => Assert.Equal("C", t.Name));
        }
예제 #10
0
        private static SchemaBuilder CreateSchemaBuilder(
            Action <ISchemaConfiguration> configure)
        {
            var configuration = new SchemaConfiguration();

            configure(configuration);

            return(configuration.CreateBuilder());
        }
예제 #11
0
        public void should_create_schema_config_with_default_values()
        {
            var config = new SchemaConfiguration();

            config.FriendlyNameColumn.ShouldEqual(RepositorySchemaConstants.DefaultFriendlyNameColumn);
            config.IdColumn.ShouldEqual(RepositorySchemaConstants.DefaultIdColumn);
            config.Schema.ShouldEqual(RepositorySchemaConstants.Schema);
            config.Table.ShouldEqual(RepositorySchemaConstants.DefaultTable);
            config.XmlColumn.ShouldEqual(RepositorySchemaConstants.DefaultXmlColumn);
            should_not_contain_string("_",
                                      new[] { config.FriendlyNameColumn, config.IdColumn, config.Schema, config.Table, config.XmlColumn });
        }
예제 #12
0
        public void should_create_schema_config_with_pgsql_formatted_values()
        {
            var config = new SchemaConfiguration(false);

            config.FriendlyNameColumn.ShouldEqual(RepositorySchemaConstants.PgsqlFriendlyNameColumn);
            config.IdColumn.ShouldEqual(RepositorySchemaConstants.PgsqlIdColumn);
            config.Schema.ShouldEqual(RepositorySchemaConstants.Schema);
            config.Table.ShouldEqual(RepositorySchemaConstants.PgsqlTable);
            config.XmlColumn.ShouldEqual(RepositorySchemaConstants.PgsqlXmlColumn);
            should_contain_string("_", new[] { config.Table, config.FriendlyNameColumn });
            should_be_lower_case(new[]
                                 { config.FriendlyNameColumn, config.IdColumn, config.Schema, config.Table, config.XmlColumn });
        }
예제 #13
0
        /// <summary>
        /// Alters the declaration options of the schema to ensure no fields or types are altered
        /// or have their names changed from the casing declared in the source code.
        /// </summary>
        /// <param name="schema">The schema.</param>
        public static void SetNoAlterationConfiguration(this ISchema schema)
        {
            var declarationOptions = new SchemaDeclarationConfiguration();

            declarationOptions.Merge(schema.Configuration.DeclarationOptions);
            declarationOptions.GraphNamingFormatter = new GraphNameFormatter(GraphNameFormatStrategy.NoChanges);

            var config = new SchemaConfiguration(
                declarationOptions,
                schema.Configuration.ExecutionOptions,
                schema.Configuration.ResponseOptions,
                schema.Configuration.QueryCacheOptions);

            schema.Configuration.Merge(config);
        }
예제 #14
0
        /// <summary>
        /// Adds a GraphQL middleware to the <see cref="IApplicationBuilder"/> request execution pipeline with the specified options.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="path"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseGraphQl(this IApplicationBuilder builder,
                                                     PathString path, GraphQlMiddlewareOptions options)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var schemaProvider = SchemaConfiguration.GetSchemaProvider(options.SchemaName, builder.ApplicationServices);

            return(builder.Map(path, branch => branch.UseMiddleware <GraphQlMiddleware>(schemaProvider, options)));
        }
예제 #15
0
        public void should_contain_custom_values()
        {
            var tableName = "Keys";
            var idColumn  = "KeyId";

            var config = new SchemaConfiguration(c =>
            {
                c.IdColumn = idColumn;
                c.Table    = tableName;
            });

            config.FriendlyNameColumn.ShouldEqual(RepositorySchemaConstants.DefaultFriendlyNameColumn);
            config.IdColumn.ShouldEqual(idColumn);
            config.Schema.ShouldEqual(RepositorySchemaConstants.Schema);
            config.Table.ShouldEqual(tableName);
            config.XmlColumn.ShouldEqual(RepositorySchemaConstants.DefaultXmlColumn);
            should_not_contain_string("_",
                                      new[] { config.FriendlyNameColumn, config.IdColumn, config.Schema, config.Table, config.XmlColumn });
        }
예제 #16
0
        private DirectiveType CreateDirective <T>(T directiveType)
            where T : DirectiveType
        {
            var schemaContext = new SchemaContext();

            schemaContext.Types.RegisterType(new StringType());
            schemaContext.Directives.RegisterDirectiveType(directiveType);

            var schemaConfiguration = new SchemaConfiguration(
                sp => { },
                schemaContext.Types,
                schemaContext.Directives);

            var typeFinalizer = new TypeFinalizer(schemaConfiguration);

            typeFinalizer.FinalizeTypes(schemaContext, null);

            return(schemaContext.Directives.GetDirectiveTypes().Single());
        }
예제 #17
0
        /// <summary>
        /// Add GraphQL services to the specified <see cref="IServiceCollection">IServiceCollection</see>.
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configure">Action to configure the default schema.</param>
        /// <returns></returns>
        public static IGraphQlBuilder AddGraphQl(this IServiceCollection services, Action <SchemaConfiguration> configure)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            var builder = new GraphQlBuilder(services);

            var schema = new SchemaConfiguration(null);

            configure(schema);

            return(builder.AddSchema(schema));
        }
예제 #18
0
        public void CreateCostDirective()
        {
            // arrange
            SchemaContext schemaContext = SchemaContextFactory.Create();

            var schemaConfiguration = new SchemaConfiguration(
                sp => { },
                schemaContext.Types,
                schemaContext.Resolvers,
                schemaContext.Directives);

            var typeFinalizer = new TypeFinalizer(schemaConfiguration);

            typeFinalizer.FinalizeTypes(schemaContext, null);

            // assert
            DirectiveType directive = schemaContext.Directives
                                      .GetDirectiveTypes()
                                      .FirstOrDefault(t => t.Name == "cost");

            // assert
            Assert.NotNull(directive);
            Assert.IsType <CostDirectiveType>(directive);
            Assert.Equal("cost", directive.Name);
            Assert.Collection(directive.Arguments,
                              t =>
            {
                Assert.Equal("complexity", t.Name);
                Assert.IsType <IntType>(
                    Assert.IsType <NonNullType>(t.Type).Type);
            },
                              t =>
            {
                Assert.Equal("multipliers", t.Name);
                Assert.IsType <MultiplierPathType>(
                    Assert.IsType <NonNullType>(
                        Assert.IsType <ListType>(t.Type).ElementType).Type);
            });
            Assert.Collection(directive.Locations,
                              t => Assert.Equal(DirectiveLocation.FieldDefinition, t));
        }
예제 #19
0
        private static Schema CreateSchema(
            IServiceProvider services,
            SchemaContext context,
            SchemaNames names,
            Action <ISchemaConfiguration> configure,
            bool strict)
        {
            List <SchemaError> errors = new List <SchemaError>();

            // setup introspection fields
            IntrospectionFields introspectionFields =
                new IntrospectionFields(context, e => errors.Add(e));

            SchemaNames internalNames = names;

            try
            {
                // configure resolvers, custom types and type mappings.
                SchemaConfiguration configuration = new SchemaConfiguration(services);
                configure(configuration);
                errors.AddRange(configuration.RegisterTypes(context));
                configuration.RegisterResolvers(context);
                errors.AddRange(context.CompleteTypes());

                string queryTypeName        = configuration.QueryTypeName ?? names.QueryTypeName;
                string mutationTypeName     = configuration.MutationTypeName ?? names.MutationTypeName;
                string subscriptionTypeName = configuration.SubscriptionTypeName ?? names.SubscriptionTypeName;

                internalNames = new SchemaNames(queryTypeName, mutationTypeName, subscriptionTypeName);
            }
            catch (ArgumentException ex)
            {
                // TODO : maybe we should throw a more specific
                // argument exception that at least contains the config object.
                throw new SchemaException(new[]
                {
                    new SchemaError(ex.Message, null)
                });
            }

            if (strict && errors.Any())
            {
                throw new SchemaException(errors);
            }

            internalNames = string.IsNullOrEmpty(names.QueryTypeName)
                ? new SchemaNames(null, null, null)
                : names;

            if (strict && !context.Types.TryGetType <ObjectType>(
                    internalNames.QueryTypeName, out ObjectType ot))
            {
                throw new SchemaException(new SchemaError(
                                              "Schema is missing the mandatory `Query` type."));
            }

            return(new Schema(
                       services,
                       SchemaTypes.Create(
                           context.Types.GetTypes(),
                           context.Types.GetTypeBindings(),
                           internalNames),
                       introspectionFields));
        }
 public KeyStorageContext(DbContextOptions <KeyStorageContext> options, bool useDefaultSchema = true)
     : base(options)
 {
     _configuration = new SchemaConfiguration(useDefaultSchema);
 }
 public KeyStorageContext(DbContextOptions <KeyStorageContext> options,
                          SchemaConfiguration configuration)
     : base(options)
 {
     _configuration = configuration;
 }
 public KeyStorageContext(DbContextOptions <KeyStorageContext> options)
     : base(options)
 {
     _configuration = new SchemaConfiguration();
 }