Receives the reference to the model class to seed.
 Seeds only when there are no records in the table
 or if the +force+ option is set to true.
 Also optionally it can receive the +file_name+ to use.
499692
def seed_model(model_class, options={})
      if model_class.count == 0 or options[:force]
        table_name = options[:file_name] || model_class.table_name
        puts "Seeding #{model_class.to_s.pluralize}..."
        csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true)
        seed_from_csv(model_class, csv_file)
      end
    end
942311
def fetch_object(self, model_id):
        """"""
        pk_field_instance = getattr(self.object_class, self.pk_field)
        qs = self.object_class.query.filter(pk_field_instance == model_id)
        model = qs.one_or_none()
        if not model:
            raise ReferenceNotFoundError
        return model
928963
void checkReferencedRows(Session session, Table table, int[] rowColArray) {

        Index           mainIndex = getMainIndex();
        PersistentStore store     = session.sessionData.getRowStore(table);
        RowIterator     it        = table.rowIterator(session);

        while (true) {
            Row row = it.getNextRow();

            if (row == null) {
                break;
            }

            Object[] rowData = row.getData();

            if (ArrayUtil.hasNull(rowData, rowColArray)) {
                if (core.matchType == OpTypes.MATCH_SIMPLE) {
                    continue;
                }
            } else if (mainIndex.exists(session, store, rowData,
                                        rowColArray)) {
                continue;
            }

            if (ArrayUtil.hasAllNull(rowData, rowColArray)) {
                continue;
            }

            String colValues = "";

            for (int i = 0; i < rowColArray.length; i++) {
                Object o = rowData[rowColArray[i]];

                colValues += table.getColumnTypes()[i].convertToString(o);
                colValues += ",";
            }

            String[] info = new String[] {
                getName().name, getMain().getName().name
            };

            throw Error.error(ErrorCode.X_23502, ErrorCode.CONSTRAINT, info);
        }
    }
812530
def load_seed
      seed_file = paths["db/seeds.rb"].existent.first
      return unless seed_file

      if config.try(:active_job)&.queue_adapter == :async
        with_inline_jobs { load(seed_file) }
      else
        load(seed_file)
      end
    end
469404
def load_model(
            self, the_metamodel, filename, is_main_model, encoding='utf-8',
            add_to_local_models=True):
        

        if not self.local_models.has_model(filename):
            if self.all_models.has_model(filename):
                new_model = self.all_models.filename_to_model[filename]
            else:
                # print("LOADING {}".format(filename))
                # all models loaded here get their references resolved from the
                # root model
                new_model = the_metamodel.internal_model_from_file(
                    filename, pre_ref_resolution_callback=lambda
                    other_model: self.pre_ref_resolution_callback(other_model),
                    is_main_model=is_main_model, encoding=encoding)
                self.all_models.filename_to_model[filename] = new_model
            # print("ADDING {}".format(filename))
            if add_to_local_models:
                self.local_models.filename_to_model[filename] = new_model
        assert self.all_models.has_model(filename)  # to be sure...
        return self.all_models.filename_to_model[filename]
1330960
def get_resource(self):
        """"""
        references = {"resource_id": None, "parent_id": None,
                      "grandparent_id": None}
        for model_cls, regexp in self._regexp.iteritems():
            match = regexp.search(self.resource_ref)
            if match is not None:
                references.update(match.groupdict())
                return model_cls.get(**references)

        raise exception.NotFound("No model available for %(resource_ref)r",
                                 resource_ref=self.resource_ref)
410513
def _attach_to_model(self, model):
        
        super(RelatedFieldMixin, self)._attach_to_model(model)

        if model.abstract:
            # do not manage the relation if it's an abstract model
            return

        # now, check related_name and save the relation in the database

        # get related parameters to identify the relation
        self.related_name = self._get_related_name()
        self.related_to = self._get_related_model_name()

        # create entry for the model in the _relations list of the database
        if not hasattr(self.database, '_relations'):
            self.database._relations = {}
        self.database._relations.setdefault(self.related_to, [])

        # check unicity of related name for related model
        self._assert_relation_does_not_exists()

        # the relation didn't exists, we can save it
        relation = (self._model._name, self.name, self.related_name)
        self.database._relations[self.related_to].append(relation)
731949
def model_post_save(sender, instance, created=False, **kwargs):
    

    if sender._meta.app_label == 'rest_framework_reactive':
        # Ignore own events.
        return

    def notify():
        table = sender._meta.db_table
        if created:
            notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk)
        else:
            notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk)

    transaction.on_commit(notify)
674088
public function table($table_name)
    {
        $table_name = trim($table_name);

        if (is_null($table_name)) {
            $this->throwFailsCommand('Specify the seeder table name', 'help seed');
        }

        if (!file_exists($this->setting->getSeederDirectory()."/{$table_name}_seeder.php")) {
            echo Color::red("Seeder $table_name not exists.");

            exit(1);
        }

        $this->make([
            $this->setting->getSeederDirectory()."/{$table_name}_seeder.php"
        ]);
    }
1356600
def handle(self):
        
        if not self.confirm_to_proceed(
            "<question>Are you sure you want to seed the database?:</question> "
        ):
            return

        self.resolver.set_default_connection(self.option("database"))

        self._get_seeder().run()

        self.info("Database seeded!")
778522
async def reseed(self, seed: str = None) -> None:
        

        LOGGER.debug('BaseAnchor.reseed >>> seed: [SEED]')

        verkey = await self.wallet.reseed_init(seed)
        req_json = await ledger.build_nym_request(
            self.did,
            self.did,
            verkey,
            self.name,
            (await self.get_nym_role()).token())
        await self._sign_submit(req_json)
        await self.wallet.reseed_apply()

        LOGGER.debug('BaseAnchor.reseed <<<')
704877
def set_name_with_model(self, model):
        
        table_name = model._meta.db_table
        column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]
        column_names_with_order = [
            (('-%s' if order else '%s') % column_name)
            for column_name, (field_name, order) in zip(column_names, self.fields_orders)
        ]
        # The length of the parts of the name is based on the default max
        # length of 30 characters.
        hash_data = [table_name] + column_names_with_order + [self.suffix] + self.name_hash_extra_data()
        self.name = '%s_%s_%s' % (
            table_name[:11],
            column_names[0][:7],
            '%s_%s' % (self._hash_generator(*hash_data), self.suffix),
        )
        assert len(self.name) <= self.max_name_length, (
            'Index too long for multiple database support. Is self.suffix '
            'longer than 3 characters?'
        )
        self.check_name()
224230
def _ReferenceFromPairs(pairs, reference=None, app=None, namespace=None):
  
  if reference is None:
    reference = entity_pb.Reference()
  path = reference.mutable_path()
  last = False
  for kind, idorname in pairs:
    if last:
      raise datastore_errors.BadArgumentError(
          'Incomplete Key entry must be last')
    t = type(kind)
    if t is str:
      pass
    elif t is unicode:
      kind = kind.encode('utf8')
    else:
      if issubclass(t, type):
        # Late import to avoid cycles.
        from .model import Model
        modelclass = kind
        if not issubclass(modelclass, Model):
          raise TypeError('Key kind must be either a string or subclass of '
                          'Model; received %r' % modelclass)
        kind = modelclass._get_kind()
        t = type(kind)
      if t is str:
        pass
      elif t is unicode:
        kind = kind.encode('utf8')
      elif issubclass(t, str):
        pass
      elif issubclass(t, unicode):
        kind = kind.encode('utf8')
      else:
        raise TypeError('Key kind must be either a string or subclass of Model;'
                        ' received %r' % kind)
    # pylint: disable=superfluous-parens
    if not (1 <= len(kind) <= _MAX_KEYPART_BYTES):
      raise ValueError('Key kind string must be a non-empty string up to %i'
                       'bytes; received %s' %
                       (_MAX_KEYPART_BYTES, kind))
    elem = path.add_element()
    elem.set_type(kind)
    t = type(idorname)
    if t is int or t is long:
      # pylint: disable=superfluous-parens
      if not (1 <= idorname < _MAX_LONG):
        raise ValueError('Key id number is too long; received %i' % idorname)
      elem.set_id(idorname)
    elif t is str:
      # pylint: disable=superfluous-parens
      if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
        raise ValueError('Key name strings must be non-empty strings up to %i '
                         'bytes; received %s' %
                         (_MAX_KEYPART_BYTES, idorname))
      elem.set_name(idorname)
    elif t is unicode:
      idorname = idorname.encode('utf8')
      # pylint: disable=superfluous-parens
      if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
        raise ValueError('Key name unicode strings must be non-empty strings up'
                         ' to %i bytes; received %s' %
                         (_MAX_KEYPART_BYTES, idorname))
      elem.set_name(idorname)
    elif idorname is None:
      last = True
    elif issubclass(t, (int, long)):
      # pylint: disable=superfluous-parens
      if not (1 <= idorname < _MAX_LONG):
        raise ValueError('Key id number is too long; received %i' % idorname)
      elem.set_id(idorname)
    elif issubclass(t, basestring):
      if issubclass(t, unicode):
        idorname = idorname.encode('utf8')
      # pylint: disable=superfluous-parens
      if not (1 <= len(idorname) <= _MAX_KEYPART_BYTES):
        raise ValueError('Key name strings must be non-empty strings up to %i '
                         'bytes; received %s' % (_MAX_KEYPART_BYTES, idorname))
      elem.set_name(idorname)
    else:
      raise TypeError('id must be either a numeric id or a string name; '
                      'received %r' % idorname)
  # An empty app id means to use the default app id.
  if not app:
    app = _DefaultAppId()
  # Always set the app id, since it is mandatory.
  reference.set_app(app)
  # An empty namespace overrides the default namespace.
  if namespace is None:
    namespace = _DefaultNamespace()
  # Only set the namespace if it is not empty.
  if namespace:
    reference.set_name_space(namespace)
  return reference
1223711
def create_model_table(self, model):
        
        try:
            return db_model_factory(self.Base, model, self.models)
        except Exception as exc:
            raise ModelError(
                model.name,
                message="failed to create in-memory table.",
                orig_exc=exc,
                context=self.error_context
            )
371661
private function seed()
    {
        $action = $this->arg->getParameter('action');

        if (!in_array($action, ['all', 'table'])) {
            $this->throwFailsCommand('This action is not exists', 'help seed');
        }

        if ($action == 'all') {
            if ($this->arg->getParameter('target') != null) {
                $this->throwFailsAction('Bad command usage', 'help seed');
            }
        }

        // Set command for understand
        $command = $action;

        $this->command->call(
            $command,
            'seeder',
            $this->arg->getParameter('target')
        );
    }
102980
def get_class(name) #:nodoc:
      raise ArgumentError, "class name is blank" if blank?(name)

      response = call_server(:method => :get, :uri => "class/#{@database}/#{name}")
      rslt = process_response(response) do
        raise NotFoundError, 'class not found' if response.body =~ /Invalid class/
      end

      classes = [rslt]
      decorate_classes_with_model(classes)
      clazz = classes[0]
      clazz.extend Orientdb4r::HashExtension
      clazz.extend Orientdb4r::OClass
      unless clazz['properties'].nil? # there can be a class without properties
        clazz.properties.each do |prop|
          prop.extend Orientdb4r::HashExtension
          prop.extend Orientdb4r::Property
        end
      end

      clazz
    end
310236
def db_for_read(self, model, **hints):
        
        if model._meta.app_label in self._apps:
            return getattr(model, '_db_alias', model._meta.app_label)
        return None