This method is based on the following two methods
   ActiveRecord::Schema#define
   ActiveRecord::ConnectionAdapters::SchemaStatements
     #assume_migrated_upto_version
322813
def define(info)
      DataMigrate::DataMigrator.assure_data_schema_table

      return if info[:version].blank?

      version = info[:version].to_i

      unless migrated.include?(version)
        execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
      end

      insert(version)
    end
161438
function ActiveRecord(name) {

    var cfg = {};
    
    var ext = {
        format:'txt',
        location:'database'
    };

    function buildFileName(name) {
        return ext.location + '/' + name + '.' + ext.format;
    }

    ActiveRecord._config &&
    _.extend(cfg, ActiveRecord._config);

    cfg.format &&
    (ext.format = cfg.format) &&
    (delete cfg.format);

    cfg.location &&
    (ext.location = cfg.location) &&
    (delete cfg.location);

    if(name) {
        cfg.filename = buildFileName(name);
    } else {
        throw new Error("Required parameter 'name' is not defined!");
    }

    var db = new DB(cfg);

    !cfg.autoload && db.loadDatabase();

    var flow = new Flow();

    /**
     * The exported class is responsible for a specific collection
     *
     * @param params
     * @constructor
     */
    function F(params) {
        params && (_.extend(this, params));
        generateId(this);
    }

    F.prototype.save = function() {
        var buffer = _.clone(this),
            refreshBuffer = function() {
                this.createdAt &&
                (buffer.createdAt = this.createdAt);
            },
            syncData = function(data){
                return _.isArray(data) &&
                    _.extend(this, data[1]) || data;
            };

        return F.pre(refreshBuffer.bind(this))
            .update({_id: this._id}, buffer, { upsert: true })
            .then(syncData.bind(this));
    };

    F.prototype.remove = function() {
        return F.remove({_id: this._id}, {});
    };

    /**
     * Cursor for methods: find, findOne or count
     *
     * @param dbCursor
     * @constructor
     */
    function C(dbCursor) {
        var chain = dbCursor;

        _.each(['sort', 'skip', 'limit', 'projection'], function(fName) {
            this[fName] = function() {
                chain = chain[fName].apply(chain, arguments);
                return this;
            }
        }.bind(this));

        this.exec = function(){
            return convertToPromise(chain, 'exec', [], function(data) {
                if(_.isArray(data)) return dbCallbacks.find(data);
                if(_.isObject(data)) return dbCallbacks.findOne(data);
                return data;
            });
        };
    }

    function generateId(o){
        o && !o._id && (o._id = db.createNewId());
    }

    /**
     * Generator of functions using Cursor API: sort, limit, skip, projection
     *
     * @example {$$sort:{planet: 1}, $$skip:1, $$limit:2, $$projection: { planet: 1, system: 1 }, $not: { planet: 'Earth' }}
     * @param fnName
     * @returns {*}
     */
    function generateCursorApi(fnName) {
        return function (query, projections) {
            var cursorOptions = _.pick(query, '$$sort', '$$skip', '$$limit', '$$projection');
            query = _.omit.apply(_, _.flatten([query, _.keys(cursorOptions)]));

            if (_.keys(cursorOptions).length || projections) {
                projections && (cursorOptions.$$projection = projections);

                var cursor = new C(db[fnName](query));
                _.reduce(_.keys(cursorOptions), function (c, method) {
                    return c[method.replace('$$','')](cursorOptions[method]);
                }, cursor);

                return cursor.exec();
            }

            return convertToPromise(db, fnName, arguments,
                (fnName === 'find' ? dbCallbacks.find : (fnName === 'findOne' ? dbCallbacks.findOne : null)));
        };
    }

    function convertToPromise(ctx, method, args, success) {
        return flow.execute(function(){
            var promise = Q.nfapply(ctx[method].bind(ctx), args);
            return success
                ? promise.then(success)
                : promise;
        });
    }

    function createRecord(doc) {
        return doc ? new F(doc) : null;
    }

    var dbCallbacks = {
        insert: function(docs){
            return _.isArray(docs)
                ? _.map(docs, createRecord)
                : createRecord(docs);
        },

        find: function(docs) {
            return _.map(docs, createRecord);
        },

        findOne: function(doc) {
            return createRecord(doc);
        },

        update: function(data) {
            _.isArray(data) &&
            (data[1] = createRecord(data[1]));
            return data;
        }
    };

    F.pre = function(fn) {
        return flow.execute(fn) && F;
    };

    F.update = function(){
        return convertToPromise(db, 'update', arguments, dbCallbacks.update);
    };

    F.insert = function(){
        return convertToPromise(db, 'insert', arguments, dbCallbacks.insert);
    };

    F.remove = function(){
        return convertToPromise(db, 'remove', arguments);
    };

    F.ensureIndex = function(){
        return convertToPromise(db, 'ensureIndex', arguments);
    };

    F.removeIndex = function(){
        return convertToPromise(db, 'removeIndex', arguments);
    };

    F.find = generateCursorApi('find');

    F.count = generateCursorApi('count');

    F.findOne = generateCursorApi('findOne');

    return F;
}
1313784
def method_missing(name, *args)
      groupname = (args[0] or raise "Database configuration group not specified for #{name}")
      dbname = (args[1] or raise "Database entry name not specified for #{name}")
      n = name.to_s
      begin
        unseparated_yaml(n => self[groupname, dbname])
      rescue Bcdatabase::Error => e
        if ENV['RAILS_ENV'] == n
          raise e
        else
          # Not using that configuration right now, so return a dummy instead
          # of throwing an exception
          unseparated_yaml(n => { 'error' => e.message })
        end
      end
    end
1156538
protected void migrateSchema() {

        try {

            Connection connection = dataSource.getConnection();
            try {

                beforeSchemaMigration(connection);

                SchemaUpdater updater = new SchemaUpdater(connection, tableName, serializer);
                if (!updater.doesTableExist()) {
                    updater.migrateToVersion1();
                }
                if (updater.isSchemaVersion1()) {
                    updater.migrateToVersion2();
                }

                afterSchemaMigration(connection);


            } finally {
                DbUtils.closeQuietly(connection);
            }

        } catch (SQLException e) {
            throw new IllegalStateException("Failed to migrate the database schema", e);
        }

    }
1356141
def migrate(engine, database, module, **kwargs):
    '''
    
    '''
    validate_args(engine, database, module)

    options = {
        'direction': kwargs.get('direction', 'up'),
        'fake': kwargs.get('fake', False),
        'force': kwargs.get('force', False),
        'migration': kwargs.get('migration', None),
        'transaction': kwargs.get('transaction', True),
    }

    Migration._meta.database = database
    migrator = DATABASE_MAP[engine](database, module, **options)
    migrator.run()
645496
def migrate(ctx,):
    
    adapter = ctx.obj['adapter']
    
    start_time = datetime.now()
    
    nr_updated = migrate_database(adapter)
    
    LOG.info("All variants updated, time to complete migration: {}".format(
        datetime.now() - start_time))
    LOG.info("Nr variants that where updated: %s", nr_updated)
610809
def _validate_version(connection, dsn):
    
    try:
        version = get_stored_version(connection)
    except VersionIsNotStored:
        logger.debug('Version not stored in the db: assuming new database creation.')
        version = SCHEMA_VERSION
        _update_version(connection, version)
    assert isinstance(version, int)

    if version > 10 and version < 100:
        raise DatabaseError('You are trying to open an old SQLite database.')

    if _migration_required(connection):
        migrate(connection, dsn)
888920
def schema
      return @schema if @schema

      manifest = self

      @schema = Class.new do
        include Virtus.model
        include ActiveModel::Validations
        include TranslatableAttributes

        cattr_accessor :manifest

        def self.model_name
          ActiveModel::Name.new(self, nil, "Settings")
        end

        def manifest
          self.class.manifest
        end

        manifest.attributes.each do |name, attribute|
          if attribute.translated?
            translatable_attribute name, attribute.type_class, default: attribute.default_value
            validates name, translatable_presence: true if attribute.required
          else
            attribute name, attribute.type_class, default: attribute.default_value
            validates name, presence: true if attribute.required
          end
        end
      end

      @schema.manifest = self
      @schema
    end
346806
def run_on_changes(paths)
      if paths.any? { |path| path.match(%r{^db/migrate/(\d+).+\.rb}) } || reset?
        migrations = paths.map { |path| Migration.new(path) }
        migrate(migrations)
      elsif paths.any? { |path| path.match(%r{^db/seeds\.rb$}) }
        seed_only
      end
    end
560543
def database_current_migration(self):
        
        # If the table doesn't even exist, return None.
        if not self.migration_table.exists(self.session.bind):
            return None

        # Also return None if self.migration_data is None.
        if self.migration_data is None:
            return None

        return self.migration_data.version
1337974
function lookup(version, migrations) {
  var regex = RegExp('^' + version + '.*$');
  for (var m in migrations)
    if (migrations.hasOwnProperty(m) && m.match(regex)) return m;
  return null;
}
56216
@SafeVarargs
    static QueryMeta buildFindAllSql(ActiveRecord activeRecord, Supplier<ConditionEnum>... conditions) {

        QueryMeta queryMeta = new QueryMeta();

        String        initSql = parseFieldsSql(activeRecord.getTableName(), conditions);
        StringBuilder sqlBuf  = new StringBuilder(initSql);

        int[]        pos  = {1};
        List<Object> list = parseWhere(activeRecord, pos, sqlBuf);
        List<Object> temp = andWhere(activeRecord, pos, sqlBuf);
        if (null != temp) {
            list.addAll(temp);
        }

        String sql     = sqlFilter(sqlBuf.toString());
        String orderBy = parseOrderBySql(conditions);
        if (null != orderBy) {
            sql += orderBy;
        }
        String limit = parseLimitSql(conditions);
        if (null != limit) {
            sql += limit;
        }
        PageRow pageRow = Base.pageLocal.get();
        sql = appendPageParams(sql, pageRow);

        Object[] args = list.toArray();

        queryMeta.setSql(sql);
        queryMeta.setParams(args);
        mapping(queryMeta, activeRecord.getClass());
        return queryMeta;
    }
21862
def inspect_attributes
      if active_record.abstract_class?
        Traits::AttributeList.new([])
      else
        columns = active_record.columns_hash.values

        if features.try(:translates_with_globalize?)
          globalize       = features.globalize
          tr_class        = globalize.model_class_for_translations
          tr_columns_hash = tr_class.columns_hash

          columns += globalize.translated_attribute_names.map do |el|
            tr_columns_hash[el.to_s]
          end
        end

        list = columns.map do |column|
          Traits::Attribute.new(active_record, column)
        end

        Traits::AttributeList.new(list)
      end
    end
57880
def migrate_database(adapter):
    
    
    all_variants = adapter.get_variants()
    nr_variants = all_variants.count()
    nr_updated = 0
    with progressbar(all_variants, label="Updating variants", length=nr_variants) as bar:
        for variant in bar:
            # Do not update if the variants have the correct format
            if 'chrom' in variant:
                continue
            nr_updated += 1
            splitted_id = variant['_id'].split('_')
            
            chrom = splitted_id[0]
            start = int(splitted_id[1])
            ref = splitted_id[2]
            alt = splitted_id[3]
            
            # Calculate end
            end = start + (max(len(ref), len(alt)) - 1)
            
            adapter.db.variant.find_one_and_update(
                {'_id': variant['_id']},
                {
                    '$set': {
                        'chrom': chrom,
                        'start': start,
                        'end': end
                    }
                }
            )
    
    return nr_updated
735765
def default_hash(env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s)
      default = find_db_config(env)
      default.config if default
    end
26583
def allow_migrate(self, db, model):
        
        if db != 'old_nodeshot' or model._meta.app_label != 'oldimporter':
            return False
        return True
1252665
def allow_migrate(self, db, model):
        
        if db == DUAS_DB_ROUTE_PREFIX:
            return model._meta.app_label == 'duashttp'
        elif model._meta.app_label == 'duashttp':
            return False
        return None