Return relationship fields of a schema

    :param Schema schema: a marshmallow schema
    :param list: list of relationship fields of a schema
343735
def get_relationships(schema, model_field=False):
    
    relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)]

    if model_field is True:
        relationships = [get_model_field(schema, key) for key in relationships]

    return relationships
546120
def list_schemas(repo):
    
    schema_files = glob.glob(
        os.path.join(repo.working_dir, '_schemas', '*.avsc'))
    schemas = {}
    for schema_file in schema_files:
        with open(schema_file, 'r') as fp:
            schema = json.load(fp)
            schemas['%(namespace)s.%(name)s' % schema] = schema
    return schemas
1036643
def derive_fields(self):
        
        if self.fields:
            return self.fields

        else:
            fields = []
            for field in self.object_list.model._meta.fields:
                if field.name != 'id':
                    fields.append(field.name)
            return fields
926817
public static List<TableFieldSchema> getSchemaFromString(String fields) {
    logger.atFine().log("getSchemaFromString('%s')", fields);

    // Parse the output schema for Json from fields.
    JsonParser jsonParser = new JsonParser();
    JsonArray json = jsonParser.parse(fields).getAsJsonArray();
    List<TableFieldSchema> fieldsList = new ArrayList<>();

    // For each item in the list of fields.
    for (JsonElement jsonElement : json) {
      checkArgument(
          jsonElement.isJsonObject(), "Expected JsonObject for element, got '%s'.", jsonElement);
      JsonObject jsonObject = jsonElement.getAsJsonObject();

      // Set the name and type.
      checkArgument(
          jsonObject.get("name") != null,
          "Expected non-null entry for key 'name' in JsonObject '%s'", jsonObject);
      checkArgument(
          jsonObject.get("type") != null,
          "Expected non-null entry for key 'type' in JsonObject '%s'", jsonObject);
      TableFieldSchema fieldDef = new TableFieldSchema();
      fieldDef.setName(jsonObject.get("name").getAsString());
      fieldDef.setType(jsonObject.get("type").getAsString());

      // If mode is not null, set mode.
      if (jsonObject.get("mode") != null) {
        fieldDef.setMode(jsonObject.get("mode").getAsString());
      }

      // If the type is RECORD set the fields.
      if (jsonObject.get("type").getAsString().equals("RECORD")) {
        checkArgument(
            jsonObject.get("fields") != null,
            "Expected non-null entry for key 'fields' in JsonObject of type RECORD: '%s'",
            jsonObject);
        fieldDef.setFields(getSchemaFromString(jsonObject.get("fields").toString()));
      }

      fieldsList.add(fieldDef);
    }
    // Return list of TableFieldSchema.
    return fieldsList;
  }
367435
def attach(obj, schema):
  """"""

  # We have a silly exception for lists, since they have no 'attach_schema'
  # method, and I don't feel like making a subclass for List just to add it.
  # So, we recursively search the list for tuples and attach the schema in
  # there.
  if framework.is_list(obj) and isinstance(schema, ListSchema):
    for x in obj:
      attach(x, schema.element_schema)
    return

  # Otherwise, the object should be able to handle its own schema attachment.
  getattr(obj, 'attach_schema', nop)(schema)
902964
def get_fields_frame(schema):
    '''
    
    '''
    fields = []

    def get_field_record(i, key, value, parents):
        if value.get('private') or 'default' not in value:
            raise Skip
        field = (len(parents) - 1, i, tuple(parents[:-1]), parents[-1],
                 value['type'], value['default'])
        return fields.append(field)

    # Fill fields list.
    get_types(schema['properties'], get_field_record)

    # Order by level, then explicit index.
    df_fields = pd.DataFrame(sorted(fields), columns=['level_i', 'field_i',
                                                      'parents', 'field',
                                                      'field_type', 'default'])

    df_fields['attributes'] = df_fields.apply(lambda row:
                                              get_nested_item(row, schema
                                                              ['properties'],
                                                              row.parents +
                                                              (row.field, )),
                                              axis=1)
    return df_fields
1103040
@BetaApi
  public static FieldValueList of(List<FieldValue> row, Field... schema) {
    return of(row, schema.length > 0 ? FieldList.of(schema) : null);
  }
987552
def swagger_schema(self, request):
        """"""
        if self.parent is None:
            return {}

        spec = APISpec(
            self.parent.name, self.parent.cfg.get('VERSION', ''),
            plugins=['apispec.ext.marshmallow'], basePatch=self.prefix
        )

        for paths, handler in self.handlers.items():
            spec.add_tag({
                'name': handler.name,
                'description': utils.dedent(handler.__doc__ or ''),
            })
            for path in paths:
                operations = {}
                for http_method in handler.methods:
                    method = getattr(handler, http_method.lower())
                    operation = OrderedDict({
                        'tags': [handler.name],
                        'summary': method.__doc__,
                        'produces': ['application/json'],
                        'responses': {200: {'schema': {'$ref': {'#/definitions/' + handler.name}}}}
                    })
                    operation.update(utils.load_yaml_from_docstring(method.__doc__) or {})
                    operations[http_method.lower()] = operation

                spec.add_path(self.prefix + path, operations=operations)

            if getattr(handler, 'Schema', None):
                kwargs = {}
                if getattr(handler.meta, 'model', None):
                    kwargs['description'] = utils.dedent(handler.meta.model.__doc__ or '')
                spec.definition(handler.name, schema=handler.Schema, **kwargs)

        return deepcopy(spec.to_dict())
174236
def schemata(self) -> list:
        

        LOGGER.debug('SchemaCache.schemata >>>')

        LOGGER.debug('SchemaCache.schemata <<<')
        return [self._schema_key2schema[seq_no] for seq_no in self._schema_key2schema]
1153592
def get_field(self, schema):
        
        type = schema.get_type(self.schema_type)
        logger.debug('Found schema type %s; base type %s, restricted values %s' % \
                     (self.schema_type, type.base_type(), type.restricted_values))
        kwargs = {}
        if type.restricted_values:
            # field has a restriction with enumerated values - pass as choices to field
            # - empty value at beginning of list for unset value; for required fields,
            #   will force user to select a value, rather than first item being default
            choices = []
            choices.extend(type.restricted_values)
            # restricted values could include a blank
            # if it's there, remove it so we don't get two
            if '' in choices:
                choices.remove('')
            choices.insert(0, '')   # add blank choice at the beginning of the list
            kwargs['choices'] = choices

        # TODO: possibly also useful to look for pattern restrictions

        basetype = type.base_type()
        if basetype == 'string':
            newfield = StringField(self.xpath, required=self.required, **kwargs)
            # copy original creation counter to newly created field
            # to preserve declaration order
            newfield.creation_counter = self.creation_counter
            return newfield
        else:
            raise Exception("basetype %s is not yet supported by SchemaField" % basetype)
692009
def getSchema(cls):
        
        schema = []
        for name, atr in cls.__attributes__:
            atr = atr.__get__(None, cls)
            if isinstance(atr, SQLAttribute):
                schema.append((name, atr))
        cls.getSchema = staticmethod(lambda schema=schema: schema)
        return schema
1119433
def get_schema_from_list(table_name, frum):
    
    columns = UniqueIndex(keys=("name",))
    _get_schema_from_list(frum, ".", parent=".", nested_path=ROOT_PATH, columns=columns)
    return Schema(table_name=table_name, columns=list(columns))
487421
def dtypes(self):
        
        return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
521762
def wordrelationships(relationshiplist):
    ''''''
    # Default list of relationships
    # FIXME: using string hack instead of making element
    #relationships = makeelement('Relationships', nsprefix='pr')
    relationships = etree.fromstring(
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006'
        '/relationships"></Relationships>')
    count = 0
    for relationship in relationshiplist:
        # Relationship IDs (rId) start at 1.
        rel_elm = makeelement('Relationship', nsprefix=None,
                              attributes={'Id':     'rId'+str(count+1),
                                          'Type':   relationship[0],
                                          'Target': relationship[1]}
                              )
        relationships.append(rel_elm)
        count += 1
    return relationships
176752
def fields(self, fields):
        

        if not isinstance(fields, list):
            raise InvalidUsage('fields must be of type `list`')

        self._sysparms['sysparm_fields'] = ",".join(fields)
842539
def _get_schema_from_list(frum, table_name, parent, nested_path, columns):
    

    for d in frum:
        row_type = python_type_to_json_type[d.__class__]

        if row_type != "object":
            # EXPECTING PRIMITIVE VALUE
            full_name = parent
            column = columns[full_name]
            if not column:
                column = Column(
                    name=concat_field(table_name, full_name),
                    es_column=full_name,
                    es_index=".",
                    es_type=d.__class__.__name__,
                    jx_type=None,  # WILL BE SET BELOW
                    last_updated=Date.now(),
                    nested_path=nested_path,
                )
                columns.add(column)
            column.es_type = _merge_python_type(column.es_type, d.__class__)
            column.jx_type = python_type_to_json_type[column.es_type]
        else:
            for name, value in d.items():
                full_name = concat_field(parent, name)
                column = columns[full_name]
                if not column:
                    column = Column(
                        name=concat_field(table_name, full_name),
                        es_column=full_name,
                        es_index=".",
                        es_type=value.__class__.__name__,
                        jx_type=None,  # WILL BE SET BELOW
                        last_updated=Date.now(),
                        nested_path=nested_path,
                    )
                    columns.add(column)
                if is_container(value):  # GET TYPE OF MULTIVALUE
                    v = list(value)
                    if len(v) == 0:
                        this_type = none_type.__name__
                    elif len(v) == 1:
                        this_type = v[0].__class__.__name__
                    else:
                        this_type = reduce(
                            _merge_python_type, (vi.__class__.__name__ for vi in value)
                        )
                else:
                    this_type = value.__class__.__name__
                column.es_type = _merge_python_type(column.es_type, this_type)
                column.jx_type = python_type_to_json_type[column.es_type]

                if this_type in {"object", "dict", "Mapping", "Data"}:
                    _get_schema_from_list(
                        [value], table_name, full_name, nested_path, columns
                    )
                elif this_type in {"list", "FlatList"}:
                    np = listwrap(nested_path)
                    newpath = unwraplist([join_field(split_field(np[0]) + [name])] + np)
                    _get_schema_from_list(
                        value, table_name, full_name, newpath, columns
                    )
481128
def get_indexes(self, schema, **kwargs):
        
        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            return self._get_indexes(schema, **kwargs)