Beispiel #1
0
        public void PrintSchema_DoesntPrintSchemaOfCommonNames()
        {
            this.schema = new GraphQLSchema();

            var query = new TestObjectType("Query", this.schema);

            query.Field("foo", () => default(string));
            this.schema.Query(query);

            var mutation = new TestMutationType("Mutation", this.schema);

            mutation.Field("foo", () => default(int));
            this.schema.Mutation(mutation);

            var subscription = new TestSubscriptionType("Subscription", this.schema);

            subscription.Field("foo", () => default(ID));
            this.schema.Subscription(subscription);

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            type Mutation {
              foo: Int!
            }

            type Query {
              foo: String
            }

            type Subscription {
              foo: ID!
            }", result);
        }
Beispiel #2
0
        public void LoadTables()
        {
            var leafLevel = 1;

            SchemaTables = SchemaUtils.ReadSchemaTables(out leafLevel);
            LeafLevel    = leafLevel;

            Task.Factory.StartNew(() =>
            {
                foreach (var table in SchemaTables)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            LoadColumn(table);

                            SchemaUtils.GetRefColumns(table);
                            foreach (var col in table.Columns)
                            {
                                if (!string.IsNullOrEmpty(col.RefColumns))
                                {
                                    LogUtils.Logs.Log("Table: {0}, refCols :{1}", col.Name, col.RefColumns);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            LogUtils.Logs.Error(e.Message);
                        }
                    });
                }
            });
        }
Beispiel #3
0
        public void PrintSchema_PrintsDeprecated()
        {
            new TestInputObjectType <Foo>("Input", this.schema)
            .Field("int", e => default(int?))
            .IsDeprecated("because reasons");
            this.root
            .Field("dep1", () => default(string))
            .IsDeprecated();
            this.root
            .Field("dep2", () => default(string))
            .IsDeprecated("");

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }
            
            input Input {
              int: Int @deprecated(reason: ""because reasons"")
            }

            type Root {
              dep1: String @deprecated
              dep2: String @deprecated
            }", result);
        }
Beispiel #4
0
        public void PrintSchema_PrintsInterface()
        {
            new TestInterfaceType <IFoo>("Foo", this.schema)
            .Field("str", e => default(string));
            new TestObjectType <BarIFoo>("Bar", this.schema)
            .Field("str", () => default(string));
            this.root
            .Field("bar", () => default(BarIFoo));

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Bar implements Foo {
              str: String
            }

            interface Foo {
              str: String
            }

            type Root {
              bar: Bar
            }", result);
        }
Beispiel #5
0
        private void CheckIn(Document doc)
        {
            ActiveDoc = doc;

            var settings = SchemaUtils.LoadSchema(doc);

            AppSettings.Instance.StoredSettings = settings ?? new StoredSettings();
        }
Beispiel #6
0
 void LoadColumn(Table table)
 {
     Log("Start load schema for table: {0}", table.Name);
     table.Status  = 1;
     table.Columns = SchemaUtils.ReadSchemaColumn(table.Name);
     table.Status  = 2;
     Log("End load schema for table: {0}, columns: {1}, total row: {2}", table.Name, table.Columns.Count, Sql.GetRowCount(table.Name));
 }
Beispiel #7
0
        protected static void GetProperties(DynamicParameters parameters, object item, string suffix)
        {
            var type = item.GetType();

            foreach (var property in TypePropertiesCache(type))
            {
                var accessor = PropertyAccessors.GetOrAdd(property, p => new PropertyInfoAccessor(p));
                parameters.Add(property.Name + suffix, accessor.Get(item), SchemaUtils.ToDbType(property.PropertyType));
            }
        }
Beispiel #8
0
        /// <summary>Creates a column with the name of TBaseRecordProperty_Id. This follows the standard orchard conventions.</summary>
        /// <typeparam name="TForeignRecord">The Record-Type of the virtual property.</typeparam>
        /// <typeparam name="TBaseRecord">The ContentPartRecord holding the virtual property pointing to the foreign record.</typeparam>
        /// <param name="self">A CreateTableCommand</param>
        /// <param name="expression">An expression to get the virtual property.</param>
        /// <param name="column">Actions to alter the column further.</param>
        /// <returns>The CreateTableCommand</returns>
        public static CreateTableCommand ColumnForForeignKey <TForeignRecord, TBaseRecord>(this CreateTableCommand self, Expression <Func <TBaseRecord, TForeignRecord> > expression, Action <CreateColumnCommand> column = null)
        {
            var dbType = SchemaUtils.ToDbType(typeof(int));

            var property = ReflectOn <TBaseRecord> .NameOf(expression);

            var columnName = string.Format("{0}_Id", property);

            return(self.Column(columnName, dbType, column));
        }
        private static ResultWithErrors <ResourceTypeSchema[]> BuildSchemaCacheFromFilePaths(IEnumerable <string> filePaths)
        {
            var schemasByPath = filePaths
                                .Select(File.ReadAllText)
                                .Select(JObject.Parse)
                                .ToInsensitiveDictionary(
                keySelector: schema => GetRelativeSchemaPath(schema["id"].ToObject <string>()),
                elementSelector: schema => schema as JToken);

            var externalReferenceSchemasResult = SchemaUtils.GetExternalReferenceSchemas(schemasByPath, SchemaUtils.ExternalReferenceWhitelist.ToArray());

            if (externalReferenceSchemasResult.Errors.Any())
            {
                throw new InvalidOperationException($"Failed to initialize the offline schemas cache");
            }

            var schemaRefsByFile = SchemaUtils.TopLevelReferenceSchemas
                                   .SelectMany(schemaPath => SchemaUtils.GetExternalReferences(schemasByPath[schemaPath]))
                                   .Select(property => property.Value.ToObject <string>())
                                   .ToLookupOrdinalInsensitively(SchemaUtils.GetFilePathFromUri);

            var schemaKeysFound = schemaRefsByFile
                                  .Select(grouping => grouping.Key)
                                  .Where(filePath => !SchemaUtils.ExternalReferenceWhitelist.Contains(filePath))
                                  .Where(filePath => schemasByPath.ContainsKey(filePath))
                                  .ToArray();

            var schemaGroups = schemaKeysFound.GroupByInsensitively(keySelector: schemaKey => SchemaUtils.GetSchemaGroupKey(schemaKey));

            var schemaNormalizationResults = schemaGroups
                                             .Select(schemaGroup => schemaGroup.ToInsensitiveDictionary(keySelector: schemaKey => schemaKey, elementSelector: schemaKey => schemasByPath[schemaKey]))
                                             .SelectMany(schemaGroup => SchemaUtils.NormalizeAndFilterSchemaGroup(
                                                             schemaGroup: schemaGroup,
                                                             externalReferenceSchemas: externalReferenceSchemasResult.Value,
                                                             schemaRefsByFile: schemaRefsByFile))
                                             .ToInsensitiveDictionary(
                keySelector: normalizationResult => normalizationResult.Key,
                elementSelector: normalizationResult => normalizationResult.Value);

            var resourceTypeSchemasResults = schemaNormalizationResults
                                             .Where(kvp => kvp.Value.Value != null)
                                             .Select(kvp => new OfflineSchema(
                                                         providerNamespace: SchemaUtils.GetProviderNamespaceFromSchemaKey(kvp.Key),
                                                         apiVersion: SchemaUtils.GetVersionFromSchemaKey(kvp.Key),
                                                         schemaContent: kvp.Value.Value))
                                             .Select(schema => schema.GetResourceTypeSchemasResult());

            return(new ResultWithErrors <ResourceTypeSchema[]>
            {
                Value = resourceTypeSchemasResults.CollectValues().ToArray(),
                Errors = schemaNormalizationResults.Values.CollectErrors()
                         .ConcatArray(resourceTypeSchemasResults.CollectErrors()),
            });
        }
 public virtual string ColumnToConstraintsSql(string tableName, Column column)
 {
     if (column.IsPrimaryKey)
     {
         return(String.Format("CONSTRAINT PK_{0}_{1} PRIMARY KEY (\"{1}\")", SchemaUtils.Normalize(tableName), SchemaUtils.Normalize(column.Name)));
     }
     else if (column.IsUnique)
     {
         return(String.Format("CONSTRAINT UK_{0}_{1} UNIQUE (\"{1}\" ASC)", SchemaUtils.Normalize(tableName), SchemaUtils.Normalize(column.Name)));
     }
     return(null);
 }
Beispiel #11
0
        public static CreateTableCommand Column <TModel, TProperty>(
            this CreateTableCommand command,
            Expression <Func <TModel, TProperty> > propertySelector,
            Action <CreateColumnCommand> column = null,
            bool isPrefixWithModelType          = false)
        {
            var columnName   = GetColumnName(propertySelector, isPrefixWithModelType);
            var propertyType = GetPropertyType <TProperty>();
            var dbType       = SchemaUtils.ToDbType(propertyType);

            return(command.Column(columnName, dbType, column));
        }
Beispiel #12
0
            public async Task FooTask()
            {
                IConfigurationRoot config = ConfigBuilder.Default
                                            .Alter("App:EnableInvitationCreateEndpoint", "true")
                                            .Build();

                TestServer testServer = TestServerBuilder
                                        .BuildServer <Startup>(config);

                HttpClient client = await testServer
                                    .LoginAndGetAuthorizedClientAsync();

                HttpResponseMessage response = await client
                                               .PutJsonAsync("/invitations", new
                {
                    Email = "invited@localhost",
                    // Target client, is mostly one with GUI
                    ClientId = "mvc.hybrid"
                });

                response.EnsureSuccessStatusCode();


                var schema = SchemaUtils.GenerateSchema <InvitationsPutResultModel>();

                response.AssertSchema(@"{
                      'type': 'object',
                      'additionalProperties' : false,
                      'properties': {
                        'id': {
                          'type': [
                            'string',
                            'null'
                          ]
                        },
                        'error': {},
                        'stackTrace': {
                          'type': [
                            'string',
                            'null'
                          ]
                        }
                      },
                      'required': [
                        'type',
                        'error',
                        'stackTrace'
                      ]
                    }");
            }
Beispiel #13
0
        public void PrintSchema_PrintsStringFieldWithNonNullIntArg()
        {
            this.root
            .Field("singleField", (int argOne) => default(string));

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Root {
              singleField(argOne: Int!): String
            }", result);
        }
Beispiel #14
0
        public void PrintSchema_PrintsStringFieldWithMultipleArgs()
        {
            this.root
            .Field("singleField", (int?argOne, string argTwo) => default(string));

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Root {
              singleField(argOne: Int, argTwo: String): String
            }", result);
        }
        public void WriteSchema(object obj, Type type)
        {
            FieldInfo[] fields = SchemaUtils.GetSchemaMembers(type);

            for (int i = 0; i < fields.Length; i++)
            {
                var field = fields[i];
                if (field.Attributes.HasFlag(FieldAttributes.NotSerialized))
                {
                    continue;
                }
                var dataType = field.FieldType;
                var value    = field.GetValue(obj);

                Write(value, dataType);
            }
        }
Beispiel #16
0
        public void PrintSchema_PrintsStringFieldWithIntArgWithDefaultNull()
        {
            this.root
            .Field("singleField", (int?argOne) => default(string))
            .WithDefaultValue("argOne", null);

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Root {
              singleField(argOne: Int = null): String
            }", result);
        }
Beispiel #17
0
        public void PrintSchema_PrintsStringFieldWithMultipleArgsLastIsDefault()
        {
            this.root
            .Field("singleField", (int?argOne, string argTwo, bool?argThree) => default(string))
            .WithDefaultValue("argThree", false);

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Root {
              singleField(argOne: Int, argTwo: String, argThree: Boolean = false): String
            }", result);
        }
Beispiel #18
0
        private static void OnDocumentSaving(object sender, DocumentSavingEventArgs e)
        {
            var doc = e.Document;

            if (doc == null)
            {
                return;
            }

            try
            {
                SchemaUtils.SaveSchema(doc);
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex);
            }
        }
Beispiel #19
0
        public void PrintSchema_PrintsCustomScalar()
        {
            new TestCustomScalarType(this.schema);

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }
 
            scalar Odd
 
            type Root {

            }
            ", result);
        }
        public object ReadSchema(Type type)
        {
            FieldInfo[] fields = SchemaUtils.GetSchemaMembers(type);
            object      obj    = Activator.CreateInstance(type);

            for (int i = 0; i < fields.Length; i++)
            {
                var field = fields[i];
                if (field.Attributes.HasFlag(FieldAttributes.NotSerialized))
                {
                    continue;
                }
                var dataType = field.FieldType;

                field.SetValue(obj, Read(dataType));
            }

            return(obj);
        }
Beispiel #21
0
        public void FieldColumn(string fieldName, string fieldTypeName, Action <CreateColumnCommand> column = null)
        {
            var type = _dynamicAssemblyBuilder.GetFieldType(fieldTypeName);

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = Nullable.GetUnderlyingType(type);
            }
            var dbType  = SchemaUtils.ToDbType(type);
            var command = new CreateColumnCommand(_tableCommand.Name, fieldName);

            command.WithType(dbType);

            if (column != null)
            {
                column(command);
            }
            _tableCommand.TableCommands.Add(command);
        }
        protected internal override ISchemaReader <IGenericRecord> LoadReader(BytesSchemaVersion schemaVersion)
        {
            var schemaInfo = GetSchemaInfoByVersion(schemaVersion.Get());

            if (schemaInfo != null)
            {
                //LOG.info("Load schema reader for version({}), schema is : {}", SchemaUtils.GetStringSchemaVersion(schemaVersion.Get()), schemaInfo);
                var writerSchema = SchemaUtils.ParseAvroSchema(schemaInfo.SchemaDefinition);
                var readerSchema = useProvidedSchemaAsReaderSchema ? ReaderSchema : writerSchema;
                //readerSchema.GetProperty.addProp(GenericAvroSchema.OFFSET_PROP, schemaInfo.Properties.GetOrDefault(GenericAvroSchema.OFFSET_PROP, "0"));

                return(new GenericAvroReader(writerSchema, readerSchema, schemaVersion.Get()));
            }
            else
            {
                //LOG.warn("No schema found for version({}), use latest schema : {}", SchemaUtils.getStringSchemaVersion(schemaVersion.get()), this.readerSchema);
                return(providerSchemaReader);
            }
        }
Beispiel #23
0
        private static void OnDocumentSynchronizingWithCentral(object sender, DocumentSynchronizingWithCentralEventArgs e)
        {
            FailureProcessor.IsSynchronizing = true;

            var doc = e.Document;

            if (doc == null)
            {
                return;
            }

            try
            {
                SchemaUtils.SaveSchema(doc);
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex);
            }
        }
Beispiel #24
0
        public void CreateColumn(string tableName, string columnName, string columnType)
        {
            string formatedTableName = string.Format(TableFormat, tableName);
            bool   result            = CheckTableColumnExists(formatedTableName, columnName);

            if (result)
            {
                return;
            }
            var type = _dynamicAssemblyBuilder.GetFieldType(columnType);

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = Nullable.GetUnderlyingType(type);
            }
            var dbType = SchemaUtils.ToDbType(type);

            _schemaBuilder.AlterTable(string.Format(TableFormat, tableName),
                                      table => table.AddColumn(columnName, dbType));
            GenerationDynmicAssembly();
        }
Beispiel #25
0
        public void PrintSchema_PrintsUnions()
        {
            new TestObjectType <Foo>("Foo", this.schema)
            .Field("bool", () => default(bool?));
            new TestObjectType <Bar>("Bar", this.schema)
            .Field("str", () => default(string));
            this.schema
            .AddKnownType(new TestSingleUnionType());
            this.schema
            .AddKnownType(new TestMultipleUnionType());
            this.root
            .Field("single", () => default(object)).ResolveWithUnion <TestSingleUnionType>();
            this.root
            .Field("multiple", () => default(object)).ResolveWithUnion <TestMultipleUnionType>();

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Bar {
              str: String
            }

            type Foo {
              bool: Boolean
            }

            union MultipleUnion = Foo | Bar

            type Root {
              single: SingleUnion
              multiple: MultipleUnion
            }

            union SingleUnion = Foo
            ", result);
        }
Beispiel #26
0
        public void PrintSchema_PrintsOperationDefinitions()
        {
            this.schema = new GraphQLSchema();

            var query = new TestObjectType("QueryRoot", this.schema);

            query.Field("foo", () => default(string));
            this.schema.Query(query);

            var mutation = new TestMutationType("MutationRoot", this.schema);

            mutation.Field("foo", () => default(int));
            this.schema.Mutation(mutation);

            var subscription = new TestSubscriptionType("SubscriptionRoot", this.schema);

            subscription.Field("foo", () => default(ID));
            this.schema.Subscription(subscription);

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: QueryRoot
              mutation: MutationRoot
              subscription: SubscriptionRoot
            }

            type MutationRoot {
              foo: Int!
            }

            type QueryRoot {
              foo: String
            }

            type SubscriptionRoot {
              foo: ID!
            }", result);
        }
Beispiel #27
0
        public void PrintSchema_PrintsObjectField()
        {
            new TestObjectType <Foo>("Foo", this.schema)
            .Field("str", () => default(string));
            this.root
            .Field("foo", () => default(Foo));

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            type Foo {
              str: String
            }

            type Root {
              foo: Foo
            }", result);
        }
 /// <summary>
 /// Implementation of SchemaSpiOp
 /// </summary>
 /// <returns></returns>
 public Schema Schema()
 {
     try {
         LOGGER_API.TraceEvent(TraceEventType.Information, CAT_DEFAULT, "Exchange.Schema method");
         if (_schema != null)
         {
             LOGGER_API.TraceEvent(TraceEventType.Information, CAT_DEFAULT, "Returning cached schema");
         }
         else
         {
             _schema = SchemaUtils.BuildSchema(this,
                                               GetSupportedObjectClasses,
                                               GetObjectClassInfo,
                                               GetSupportedOperations,
                                               GetUnSupportedOperations);
             LOGGER_API.TraceEvent(TraceEventType.Information, CAT_DEFAULT, "Returning newly created schema");
         }
         return(_schema);
     } catch (Exception e) {
         LOGGER.TraceEvent(TraceEventType.Error, CAT_DEFAULT, "Exception while executing Schema operation: {0}", e);
         throw;
     }
 }
 /// <summary>
 /// Implementation of SchemaSpiOp
 /// </summary>
 /// <returns></returns>
 public Schema Schema()
 {
     try {
         LOG.Info("Exchange.Schema method");
         if (_schema != null)
         {
             LOG.Info("Returning cached schema");
         }
         else
         {
             _schema = SchemaUtils.BuildSchema(this,
                                               GetSupportedObjectClasses,
                                               GetObjectClassInfo,
                                               GetSupportedOperations,
                                               GetUnSupportedOperations);
             LOG.Info("Returning newly created schema");
         }
         return(_schema);
     } catch (Exception e) {
         LOG.Error(e, "Exception while executing Schema operation: {0}");
         throw;
     }
 }
Beispiel #30
0
        public void PrintSchema_PrintsInputType()
        {
            new TestInputObjectType <Foo>("InputType", this.schema)
            .Field("int", e => default(int?));
            this.root
            .Field("str", (Foo argOne) => default(string));

            var result = SchemaUtils.PrintSchema(this.schema);

            this.AreEqual(@"
            schema {
              query: Root
            }

            input InputType {
              int: Int
            }

            type Root {
              str(argOne: InputType): String
            }
            ", result);
        }