convert and format to Sequelize Model Type.
432431
function getType(type, len, name) {

                if(!type) return undefined;
                type = type.split('(')[0];

                if(map[type]){
                    var tmp = map[type];
                    if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
                    else len = '';
                    type = tmp.replace('[LEN]', len);
                }

                return type;
            }
956357
def restore_type(self, type):
        

        # All dialects
        mapping = {
            ARRAY: 'array',
            sa.Boolean: 'boolean',
            sa.Date: 'date',
            sa.DateTime: 'datetime',
            sa.Float: 'number',
            sa.Integer: 'integer',
            JSONB: 'object',
            JSON: 'object',
            sa.Numeric: 'number',
            sa.Text: 'string',
            sa.Time: 'time',
            sa.VARCHAR: 'string',
            UUID: 'string',
        }

        # Get field type
        field_type = None
        for key, value in mapping.items():
            if isinstance(type, key):
                field_type = value

        # Not supported
        if field_type is None:
            message = 'Type "%s" is not supported'
            raise tableschema.exceptions.StorageError(message % type)

        return field_type
851214
function load(PATH, sequelize, opts) {
  var files = fs.readdirSync(PATH),
    models = {};
  opts = opts || {};

  if (opts.exclude) {
    removeAll(opts.exclude, files);
  }

  files.forEach(function (file) {
    if (fs.statSync(path.join(PATH, file)).isDirectory()) {
      models[file] = load(path.join(PATH, file), sequelize, opts);
    } else {
      file = file.split('.')[0];
      var model = sequelize.import(path.join(PATH, file))
      models[model.name] = model;
    }
  });
  return models;
}
1181727
function generateModel(path, modelName, modelFields, generateMethod, ts, cb) {
    var fields = formatTools.getFieldsForModelTemplate(modelFields);
    var schemaName = modelName + 'Schema';

    var extension = (ts) ? 'ts' : 'js';
    var model = ft.loadTemplateSync('model.' + extension);
    model = model.replace(/{modelName}/, modelName);
    model = model.replace(/{schemaName}/g, schemaName);
    model = model.replace(/{fields}/, fields);

    if (generateMethod === 't') {
        ft.createDirIfIsNotDefined(path, 'models', function () {
            ft.writeFile(path + '/models/' + modelName + 'Model.' + extension, model, null, cb);
        });
    } else {
        ft.createDirIfIsNotDefined(path, modelName, function () {
            ft.writeFile(path + '/' + modelName + '/' + modelName + 'Model.' + extension, model, null, cb);
        });
    }
}
863798
def parse_to_type(self,**kwargs):
        """"""
        indexes = self.selectedIndexes()
        if not indexes: return
        for index in indexes:
            self.model().parse_data_type(index, **kwargs)
660825
function mongoType(
  typeStr,
  options
) {
  const required = typeStr.match(/^(\S+)!$/);
  const list = typeStr.match(/^\[(\S+)]$/);

  if (required) {
    const innerType = required[1];
    if (_.includes(SCALARS, innerType)) {
      options.required = true;
    }
    return mongoType(innerType);
  } else if (list) {
    return [ mongoType(list[1]) ];
  }
  switch (typeStr) {
    case 'String':
      return String;
    case 'Int':
    case 'Float':
      return Number;
    case 'Boolean':
      return Boolean;
    case 'DateTime':
      return Date;
    case 'ID':
      return mongoose.Schema.Types.ObjectId;
    case 'JSON':
      return mongoose.Schema.Types.Mixed;
    default:
      throw new Error(typeStr);
  }
}
231094
function modelsToTypes(models) {
  let typeMap = models.filter(model => {
    if (_typeMap[model.modelName]) return false;
    return true;
  }).reduce((map, model) => {
    return (0, _assign2.default)(map, { [model.modelName]: toType(model) });
  }, {});
  _typeMap = (0, _assign2.default)(_typeMap, typeMap);

  // Deal with ref after all types are defined
  (0, _entries2.default)(typeMap).forEach(_ref => {
    var _ref2 = (0, _slicedToArray3.default)(_ref, 2);

    let modelName = _ref2[0];
    let type = _ref2[1];

    const originFileds = type._typeConfig.fields();
    const newTypeFileds = (0, _entries2.default)(originFileds).map(_ref3 => {
      var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);

      let path = _ref4[0];
      let pathValue = _ref4[1];

      let newPathValue = (0, _assign2.default)({}, pathValue);
      if (newPathValue.ref) {
        const ref = newPathValue.ref;
        if (!_typeMap[ref]) throw TypeError(`${ref} is not a model`);
        const model = models.find(m => m.modelName === ref);
        const refModelType = _typeMap[ref];
        if (newPathValue.type instanceof _graphql.GraphQLList) {
          newPathValue = (0, _assign2.default)({}, newPathValue, {
            type: new _graphql.GraphQLList(refModelType),
            resolve: (() => {
              var _ref5 = (0, _asyncToGenerator3.default)(function* (instance) {
                // TODO: args filter
                return yield model.find({ _id: { $in: instance[path] } });
              });

              return function resolve(_x) {
                return _ref5.apply(this, arguments);
              };
            })()
          });
        } else {
          newPathValue = (0, _assign2.default)({}, newPathValue, {
            type: refModelType,
            resolve: (() => {
              var _ref6 = (0, _asyncToGenerator3.default)(function* (instance) {
                return yield model.findById(instance[path]);
              });

              return function resolve(_x2) {
                return _ref6.apply(this, arguments);
              };
            })()
          });
        }
      }
      return { [path]: newPathValue };
    }).reduce((typeField, path) => (0, _assign2.default)(typeField, path), {});

    typeMap[modelName]._typeConfig.fields = () => newTypeFileds;
  });

  _typeMap = (0, _assign2.default)(_typeMap, typeMap);
  return _typeMap;
}
1013554
def model_to_document(model)
      document = model.attributes.dup.except(:key, :rev)

      handle_embedded_models(model, document)
      handle_related_models(document)

      document
    end
50712
function replaceVirtualFields(options, model) {
		if (options.attributes) {
			for (var i = 0; i < options.attributes.length; i++) { // not using _.forEach as array is altered during looping
				var fieldName = options.attributes[i],
					field = model.attributes[fieldName];

				if (!field) throw new Sequelize.VirtualFieldsError("Field '" + model.name + '.' + fieldName + "' referenced in a virtual field does not exist");

				if (!(field.type instanceof Sequelize.VIRTUAL)) continue;

				// field is virtual - add attributes & includes from virtualField
				addVirtualFieldOptions(options, field, fieldName);

				// delete virtual attribute
				options.attributes.splice(i, 1);
				i--;
			}
		} else {
			// no attributes specified - all attributes of model will load so check all virtualFields
			_.forIn(model.attributes, function(field, fieldName) {
				// add attributes & includes from virtual field
				if (field.type instanceof Sequelize.VIRTUAL) addVirtualFieldOptions(options, field, fieldName);
			});
		}

		// repeat process for all includes recursively
		var includes = options.include;
		if (includes) {
			_.forEach(includes, function(include, index) {
				// if include given as model with no attributes/include, convert to {model: model} notation
				if (patches.isModel(include)) include = includes[index] = {model: include};

				// recurse through this include
				replaceVirtualFields(include, include.model);
			});
		}
	}
1118626
private Object convertParameter(Object value) {
        if (entityInstanceManager.isInstance(value)) {
            return entityInstanceManager.getDatastoreType(value);
        } else if (relationInstanceManager.isInstance(value)) {
            return relationInstanceManager.getDatastoreType(value);
        } else if (value instanceof Collection) {
            Collection collection = (Collection) value;
            List<Object> values = new ArrayList<>();
            for (Object o : collection) {
                values.add(convertParameter(o));
            }
            return values;
        }
        return value;
    }
541357
function mapRelation(rel, modelName, relName) {
    let acceptingParams = Object.assign({}, {
        filter: {
            generated: false,
            type: 'JSON'
        }
    }, connectionArgs);
    types[modelName].meta.fields[relName] = {
        generated: true,
        meta: {
            relation: true,
            connection: true,
            relationType: rel.type,
            isMany: isManyRelation(rel.type),
            embed: rel.embed,
            type: rel.modelTo.modelName,
            args: acceptingParams,
        },
        resolve: (obj, args, context, info) => {

            const ctxOptions = { accessToken: context.req.accessToken }
            const modelId = args && args.id;

            const method = rel.modelTo.sharedClass.findMethodByName('find');
            // TODO: ...
            return new Promise((resolve, reject) => { resolve(true) }).then(() => {
                let params = {};

                _.forEach(acceptingParams, (param, name) => {
                    if (typeof args[name] !== 'undefined' && Object.keys(args[name]).length > 0) {
                        _.merge(params, _.cloneDeep(args[name]));
                    }
                });

                if (isManyRelation(rel.type) === true) {
                    return connectionFromPromisedArray(findRelatedMany(rel, obj, params, context), args, rel.modelTo);
                } else {
                    return findRelatedOne(rel, obj, params, context);
                }

                // let wrap = promisify(model[method.name](...params, ctxOptions));

                // if (typeObj.list) {
                //     return connectionFromPromisedArray(wrap, args, model);
                // } else {
                //     return wrap;
                // }


            }).catch((err) => {
                throw err;
            });
        }
    };
}
289181
def _format_object(obj, format_type=None):
    """"""

    if json_api_settings.FORMAT_KEYS is not None:
        return format_keys(obj, format_type)

    return format_field_names(obj, format_type)
964697
def import_model(self, source):
        """"""
        if not hasattr(source, 'read'):  # Not a File-like object
            with open(self._resolve_source(source), 'r') as f:
                return self._import(f)
        else:
            return self._import(source)
1128133
function(){
         var attributes = {
            model: {
               type: Sequelize.TEXT,
               allowNull: false
            },
            documentId: {
               type: Sequelize.UUID,
               allowNull: false
            },
            revision: {
               type: Sequelize.INTEGER,
               allowNull: false
            },
            document: {
               type: Sequelize.JSON,
               allowNull: false
            }
         };
         if(options.UUID){
            attributes.id = {
               primaryKey: true,
               type: Sequelize.UUID,
               defaultValue: Sequelize.UUIDV4
            };
            attributes.documentId.type = Sequelize.UUID;
         }
         // Revision model
         var Revision = sequelize.define(options.revisionModel, attributes);

         attributes = {
            path: {
               type: Sequelize.TEXT,
               allowNull: false
            },
            document: {
               type: Sequelize.JSON,
               allowNull: false
            },
            diff: {
               type: Sequelize.JSON,
               allowNull: false
            }
         };
         if(options.UUID){
            attributes.id = {
               primaryKey: true,
               type: Sequelize.UUID,
               defaultValue: Sequelize.UUIDV4
            };
         }

         // RevisionChange model
         var RevisionChange = sequelize.define(options.revisionChangeModel, attributes);
         // Set associations
         Revision.hasMany(RevisionChange, {
            foreignKey: "revisionId",
            constraints: true,
            as: "changes"
         });
         // Associate with user if necessary
         if (options.userModel) {
            Revision.belongsTo(sequelize.model(options.userModel), {
               foreignKey: "userId",
               constraints: true,
               as: "user"
            });
         }
         return Revision;
      }
411124
function buildSchema(models, typeMap) {
  let type;

  var _models$map$reduce = models.map(model => {
    type = typeMap[model.modelName];
    return {
      query: (0, _buildQuery2.default)(model, type),
      mutation: (0, _buildMutation2.default)(model, type)
    };
  }).reduce((fields, modelField) => {
    fields.query = (0, _assign2.default)({}, fields.query, modelField.query);
    fields.mutation = (0, _assign2.default)({}, fields.mutation, modelField.mutation);
    return fields;
  }, { query: {}, mutation: {} });

  const query = _models$map$reduce.query;
  const mutation = _models$map$reduce.mutation;


  return {
    query: query,
    mutation: mutation
  };
}
373901
function replaceTableNames(sql, identifiers, sequelize) {
	const {queryInterface} = sequelize;
	_.forIn(identifiers, (model, identifier) => {
		const tableName = model.getTableName();
		sql = sql.replace(
			new RegExp(`\\*${identifier}(?![a-zA-Z0-9_])`, 'g'),
			tableName.schema ? tableName.toString() : queryInterface.quoteIdentifier(tableName)
		);
	});
	return sql;
}
339035
def convert(self, value):
        """"""
        try:
            return convert_to_format(value, self._format)
        except (ValueError, TypeError):
            return value