Persist d into the db

        schema -- Schema()
        fields -- dict -- the values to persist

        return -- int -- the primary key of the row just inserted
439109
def insert(self, schema, fields, **kwargs):
        
        r = 0

        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            try:
                with self.transaction(**kwargs):
                    r = self._insert(schema, fields, **kwargs)

            except Exception as e:
                exc_info = sys.exc_info()
                if self.handle_error(schema, e, **kwargs):
                    r = self._insert(schema, fields, **kwargs)
                else:
                    self.raise_error(e, exc_info)

        return r
1109659
def update(self, *objs):
        
        keys = self.keys()
        new_keys = get_objs_columns(objs, self.realfieldb)

        modified = False
        for v in new_keys:
            if v in keys:    #the id has been existed, so don't insert new record
                keys.remove(v)
            else:
                d = {self.fielda:self.valuea, self.fieldb:v}
                if self.before_save:
                    self.before_save(d)
                if self.through_model:
                    obj = self.through_model(**d)
                    obj.save()
                else:
                    self.do_(self.table.insert().values(**d))
                modified = True
                
        if keys: #if there are still keys, so delete them
            self.clear(*keys)
            modified = True
        
        #cache [] to _STORED_attr_name
        setattr(self.instance, self.store_key, new_keys)
        
        return modified
975501
public String insert(Object obj) {
    PersistMeta meta = EntityUtil.getMeta(obj.getClass());
    StringBuilder names = new StringBuilder(), values = new StringBuilder();
    int i = 0;
    for (Map.Entry<String, Field> kv : meta.getColumns().entrySet()) {
      if (isNull(kv.getValue(), obj)) {
        continue;
      }

      if (i++ != 0) {
        names.append(',');
        values.append(',');
      }

      names.append('`').append(kv.getKey()).append('`');
      values.append("#{").append(kv.getValue().getName()).append('}');
    }

    return new SQL().INSERT_INTO(getTableName(meta, obj)).VALUES(names.toString(), values.toString()).toString();
  }
1037083
def insert(self, row):
        
        self._check_dropped()
        res = self.engine.execute(self.table.insert(row))
        if len(res.inserted_primary_key) > 0:
            return res.inserted_primary_key[0]
984247
def db_value(self, value):
        
        # Everything is encoded being before being surfaced
        value = flask.json.dumps(value)

        return super(JSONField, self).db_value(value)
1268350
def _setID(self, id):
        
        if type(id) in (types.ListType, types.TupleType):
            try:
                for key in self._sqlPrimary:
                    value = id[0]
                    self.__dict__[key] = value
                    id = id[1:] # rest, go revursive
            except IndexError:
                raise 'Not enough id fields, required: %s' % len(self._sqlPrimary)
        elif len(self._sqlPrimary) <= 1:
            # It's a simple value
            key = self._sqlPrimary[0]
            self.__dict__[key] = id
        else:
            raise 'Not enough id fields, required: %s' % len(self._sqlPrimary)
        self._new = False
278828
def fields(self):
        
        return {k:getattr(self, k, None) for k in self.schema.fields}
780412
def schema(self):
        
        if self.status == "DELETING":
            return ""
        parts = ["GLOBAL", self.index_type, "INDEX"]
        parts.append("('%s', %s," % (self.name, self.hash_key.name))
        if self.range_key:
            parts.append("%s," % self.range_key.name)
        if self.includes:
            parts.append("[%s]," % ", ".join(("'%s'" % i for i in self.includes)))

        parts.append(
            "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput)
        )
        return " ".join(parts)
351040
def schema(self):
        
        attrs = self.attrs.copy()
        parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema]
        del attrs[self.hash_key.name]
        if self.range_key:
            parts.append(self.range_key.schema + ",")
            del attrs[self.range_key.name]
        if attrs:
            attr_def = ", ".join([attr.schema for attr in itervalues(attrs)])
            parts.append(attr_def + ",")

        parts.append(
            "THROUGHPUT (%d, %d))" % (self.read_throughput, self.write_throughput)
        )
        parts.extend([g.schema for g in itervalues(self.global_indexes)])
        return " ".join(parts) + ";"
207555
def table_schema(self):
        
        if self.__dict__.get('_table_schema') is None:
            self._table_schema = None
            table_schema = {}
            for row in self.query_schema():
                name, default, dtype = self.db().lexicon.column_info(row)
                if isinstance(default, str):
                    json_matches = re.findall(r"^\'(.*)\'::jsonb$", default)
                    if len(json_matches) > 0:
                        default = json.loads(json_matches[0])
                if name == self.primary_key:
                    default = None
                table_schema[name] = {'default': default, 'type': dtype}
            if len(table_schema):
                self._table_schema = table_schema
        return self._table_schema
158218
def persist(conditions = nil)
      run_callbacks(:save) do
        self.hash_key = SecureRandom.uuid if hash_key.blank?

        # Add an exists check to prevent overwriting existing records with new ones
        if new_record?
          conditions ||= {}
          (conditions[:unless_exists] ||= []) << self.class.hash_key
        end

        # Add an optimistic locking check if the lock_version column exists
        if self.class.attributes[:lock_version]
          conditions ||= {}
          self.lock_version = (lock_version || 0) + 1
          # Uses the original lock_version value from ActiveModel::Dirty in case user changed lock_version manually
          (conditions[:if] ||= {})[:lock_version] = changes[:lock_version][0] if changes[:lock_version][0]
        end

        attributes_dumped = Dumping.dump_attributes(attributes, self.class.attributes)

        begin
          Dynamoid.adapter.write(self.class.table_name, attributes_dumped, conditions)
          @new_record = false
          true
        rescue Dynamoid::Errors::ConditionalCheckFailedException => e
          if new_record?
            raise Dynamoid::Errors::RecordNotUnique.new(e, self)
          else
            raise Dynamoid::Errors::StaleObjectError.new(self, 'persist')
          end
        end
      end
    end
1237891
def save(self):
        
        pk_field = self._fields[self._primary_key]
        if not self._data.get(self._primary_key):
            setattr(self, self._primary_key, pk_field._generate_key())
            require_delete = False
        else:
            require_delete = True

        if require_delete:
            self.delete(for_update=True)

        data = self._get_data_dict()
        hash_obj = self.to_hash()
        hash_obj.clear()
        hash_obj.update(data)

        all_index = self._query.all_index()
        all_index.add(self.get_hash_id())

        for field in self._indexes:
            for index in field.get_indexes():
                index.save(self)
427597
function persistObject(target, schema) {
    var model = createModel(schema);
    serializr_1.setDefaultModelSchema(target, model);
    return target;
}
319820
def restore_descriptor(self, dataframe):
        

        # Prepare
        fields = []
        primary_key = None

        # Primary key
        if dataframe.index.name:
            field_type = self.restore_type(dataframe.index.dtype)
            field = {
                'name': dataframe.index.name,
                'type': field_type,
                'constraints': {'required': True},
            }
            fields.append(field)
            primary_key = dataframe.index.name

        # Fields
        for column, dtype in dataframe.dtypes.iteritems():
            sample = dataframe[column].iloc[0] if len(dataframe) else None
            field_type = self.restore_type(dtype, sample=sample)
            field = {'name': column, 'type': field_type}
            # TODO: provide better required indication
            # if dataframe[column].isnull().sum() == 0:
            #     field['constraints'] = {'required': True}
            fields.append(field)

        # Descriptor
        descriptor = {}
        descriptor['fields'] = fields
        if primary_key:
            descriptor['primaryKey'] = primary_key

        return descriptor
475789
def get_db_prep_save(self, value):
        
        if not value:
            return super(JSONField, self).get_db_prep_save("")
        else:
            return super(JSONField, self).get_db_prep_save(dumps(value))
837737
def key_value(self, **kwargs):
        
        field_name = self.name
        new_df = copy_df(self)
        new_df._perform_operation(op.FieldKVConfigOperation({field_name: KVConfig(**kwargs)}))
        return new_df
495689
def update(self, table_name, primary_key, instance):
        
        assert isinstance(primary_key, dict)
        assert isinstance(instance, BaseDocument)
        collection = self._db[table_name]

        # work with a copy of the document, as the direct type change of the _id field
        # is later negated by the `BaseDocument.to_json` method
        document = instance.document
        if '_id' in document:
            document['_id'] = ObjectId(document['_id'])

        update_result = collection.replace_one(filter=primary_key, replacement=document, upsert=True)
        if update_result.upserted_id:
            instance['_id'] = update_result.upserted_id
        return update_result.upserted_id