Save an entry in the database
549617
function (soajs, combo, cb) {
        soajs.mongoDb.update(combo.collection, combo.condition, combo.whattoupdate, cb);
    }
644205
public function save() :bool {
		
		// if an id already exists
		if($this->_['id']) {
			// we can update and return the number of affected rows (0 on error, 1 on success)
			return (bool) self::_update()
				->set($this->__toArray(true, true))
				->where(['id'=>$this->_['id']])
				->execute();
		}
		// this is a new record
		else {
			// try to insert it
			$inserted_object = self::create($this->__toArray(true, true));
			// if insertion succeeded, return true
			if($inserted_object) {
				// clone ourselves with what the database returneds, a full fledged object
				$this->replicate($inserted_object);
				// return success
				return true;
			}
			// didnt insert
			else {
				// failure feedback
				return false;
			}
		}
		
	}
567264
public function save ()
    {
        $Statement = $this->dbTable->getSql()->prepareStatementForSqlObject($this->sqlInsert);
        $Statement->execute();
        $this->id = $this->dbTable->getAdapter()->getDriver()->getConnection()->getLastGeneratedValue();
    }
1194309
def _saveDB(self):
        
        # We're a "fresh" copy now
        self._updated = time.time()
        if self._new:
            operation = 'INSERT'
            if not self._validID():
                self._setID(self._nextSequence())
            # Note that we assign this ID to our self
            # BEFORE possibly saving any of our attribute
            # objects that might be new as well. This means
            # that they might have references to us, as long
            # as the database does not require our existence
            # yet.
            #
            # Since mysql does not have Sequences, this will
            # not work as smoothly there. See class
            # MysqlForgetter below.
        else:
            operation = 'UPDATE'
        (sql, fields) = self._prepareSQL(operation)
        values = []
        for field in fields:
            value = getattr(self, field)
            # First some dirty datatype hacks
            if DateTime and type(value) == DateTime.DateTimeType:
                # stupid psycopg does not support it's own return type..
                # lovely..
                value = str(value)
            if DateTime and type(value) == DateTime.DateTimeDeltaType:
                # Format delta as days, hours, minutes seconds
                # NOTE: includes value.second directly to get the
                # whole floating number
                value = value.strftime("%d %H:%M:") + str(value.second)
            if value is True or value is False:
                # We must store booleans as 't' and 'f' ...
                value = value and 't' or 'f'
            if isinstance(value, Forgetter):
                # It's another object, we store only the ID
                if value._new:
                    # It's a new object too, it must be saved!
                    value.save()
                try:
                    (value,) = value._getID()
                except:
                    raise "Unsupported: Can't reference multiple-primary-key: %s" % value
            values.append(value)
        cursor = self.cursor()
        cursor.execute(sql, values)
        # cursor.commit()
        cursor.close()
        self._new = False
        self._changed = None
883558
public function save()
    {
        $di = DI::getDefault();

        $database = $di->getService( "database" );

        /**
         * Decide if we should update or insert
         * (if we know the record exists in the database...)
         */
        if ( $this->_exists_in_db )
        {
            /**
             * Retrieve a query from the query builder
             */
            $query = $database->buildQuery( $this->_table_name, "update", array("columns" => $this->_columns) );
            
            /**
             * Create an array with the model attributes (binding parameters)
             */
            $attributes = $this->getAttributes();
            
            /**
             * Add "snap_" prefix to the snapshot in order to not get index conflict when we merge attributes and snapshot
             */
            $snapshot = array();
            
            foreach ( $this->_snapshot as $key => $value )
            {
                $snapshot["snap_" . $key] = $value;
            }
            
            /**
             * Merge our binding parameters.
             * Bind the parameters to the query and return the result.
             */
            return $query->execute( array_merge($attributes, $snapshot) );
        }
        else
        {
            /**
             * Retrieve a query from the query builder
             */
            $query = $database->buildQuery( $this->_table_name, "insert", array("columns" => $this->_columns) );
            
            /**
             * Create an array with the model attributes (binding parameters)
             */
            $attributes = $this->getAttributes();
            
            /**
             * Bind the parameters and return the result
             */
            return $query->execute( $attributes );
        }
    }
999990
public function save()
	{
		$this->db->begin();
		foreach($this->data as $item)
		{
			$this->db->insert($this->tableName,$item);
		}
		$this->db->commit();
		return true;
	}
831830
def save(self, obj):
        
        session = self.get_db_session()
        session.add(obj)
        session.commit()

        return obj
801079
public function save()
    {
        $entries = $this->logBuffer->getEntries();

        $entrySkeleton = [
            'ts'    => $this->ts,
            'month' => $this->month,
            'year'  => $this->year
        ];

        $dimensionSkeleton = [
            'ts'    => $this->ts,
            'month' => $this->month,
            'year'  => $this->year
        ];

        /**
         * @var $e LogEntry
         */
        foreach ($entries as $e) {
            // build entry
            $entry = $entrySkeleton;
            $entry['entity'] = $e->getName();
            $entry['ref'] = $e->getRef();

            // check if we have attributes defined
            if (count($e->getAttributes()) > 0) {
                $entry['attributes'] = $e->getAttributes();
            }

            // insert or update the DAILY stat
            $this->mongo->update(self::ADB_STATS_DAILY, // match
                [
                    'entity' => $e->getName(),
                    'ref'    => $e->getRef(),
                    'ts'     => $this->ts
                ], // update
                [
                    '$inc'         => ['count' => $e->getIncrement()],
                    '$setOnInsert' => $entry
                ], // options
                ['upsert' => true]);

            // insert or update the MONTHLY stat
            unset($entry['ts']);
            $entry['month'] = $this->month;
            $entry['year'] = $this->year;
            $this->mongo->update(self::ADB_STATS_MONTHLY, // match
                [
                    'entity' => $e->getName(),
                    'ref'    => $e->getRef(),
                    'ts'     => $this->monthTs
                ], // update
                [
                    '$inc'         => ['count' => $e->getIncrement()],
                    '$setOnInsert' => $entry
                ], // options
                ['upsert' => true]);

            // insert dimensions for the entry
            $dimEntry = $dimensionSkeleton;
            $dimEntry['entity'] = $e->getName();

            /**
             * @var $dim LogDimension
             */
            foreach ($e->getDimensions() as $dim) {
                $dimEntry['name'] = $dim->getName();
                $dimEntry['value'] = $dim->getValue();

                $this->mongo->update(self::ADB_DIMS, // match
                    [
                        'name'   => $dim->getName(),
                        'value'  => $dim->getValue(),
                        'entity' => $e->getName(),
                        'ts'     => $this->ts
                    ], // update
                    [
                        '$inc'         => [
                            'count.' . $e->getRef() => $dim->getIncrement(),
                            'total'                 => $dim->getIncrement()
                        ],
                        '$setOnInsert' => $dimEntry
                    ], // options
                    ['upsert' => true]);
            }
        }

        // clear buffer
        $this->logBuffer = new LogBuffer();
    }
710592
public void doOpen() throws DBException
    {
        super.doOpen();
        try   {
            m_pTable.open(this);
        } catch (DBException ex)    {
            throw DatabaseException.toDatabaseException(ex);
        }
    }
1336337
public function save()
    {
        $builder = static::query();

        /**
         * Get the current primary key value
         */
        $primary_key_value = $this->getKeyValue();

        /**
         * If primary key value is null, we are going to start the creation of new
         * row
         */
        if ($primary_key_value == null) {
            /**
             * Insert information in the database
             */
            $r = $builder->insert($this->attributes);

            /**
             * We get a last insertion id value
             */
            $primary_key_value = $builder->getLastInsertId();

            /**
             * Transtype value to the define primary key type
             */
            if ($this->primary_key_type == 'int') {
                $primary_key_value = (int) $primary_key_value;
            } elseif ($this->primary_key_type == 'float') {
                $primary_key_value = (float) $primary_key_value;
            } elseif ($this->primary_key_type == 'double') {
                $primary_key_value = (double) $primary_key_value;
            } else {
                $primary_key_value = (string) $primary_key_value;
            }

            /**
             * Set the primary key value
             */
            $this->attributes[$this->primary_key] = $primary_key_value;

            $this->original = $this->attributes;

            if ($r == 1) {
                $this->fireEvent('oncreated');
            }

            return $r;
        }

        if (!$builder->exists($this->primary_key, $primary_key_value)) {
            return 0;
        }

        $this->original[$this->primary_key] = $primary_key_value;

        $update_data = [];

        foreach ($this->attributes as $key => $value) {
            if (!isset($this->original[$key])
                || $this->original[$key] != $value) {
                $update_data[$key] = $value;
            }
        }

        $r = $builder
            ->where($this->primary_key, $primary_key_value)
            ->update($update_data);

        if ($r == 1) {
            $this->fireEvent('onupdate');
        }

        return $r;
    }
304663
def save(self, output=None):
        
        if output is None:
            if self.dbfile is None:
                return
            output = self.dbfile

        with open(output, 'w') as f:
            f.write(self._dump())
884536
def save(self, directory=None):
        
        from subprocess import call

        # If user did not supply a new directory, use the one loaded (default: tabledata)
        if isinstance(directory, type(None)):
            directory = self.directory

        # Create the .sql file is it doesn't exist, i.e. if the Database class called a .db file initially
        if not os.path.isfile(self.sqlpath):
            self.sqlpath = self.dbpath.replace('.db', '.sql')
            os.system('touch {}'.format(self.sqlpath))

        # # Write the data to the .sql file
        # with open(self.sqlpath, 'w') as f:
        #     for line in self.conn.iterdump():
        #         f.write('%s\n' % line)

        # Alternatively...
        # Write the schema
        os.system("echo '.output {}\n.schema' | sqlite3 {}".format(self.sqlpath, self.dbpath))

        # Write the table files to the tabledata directory
        os.system("mkdir -p {}".format(directory))
        tables = self.query("select tbl_name from sqlite_master where type='table'")['tbl_name']
        tablepaths = [self.sqlpath]
        for table in tables:
            print('Generating {}...'.format(table))
            tablepath = '{0}/{1}.sql'.format(directory, table)
            tablepaths.append(tablepath)
            with open(tablepath, 'w') as f:
                for line in self.conn.iterdump():
                    line = line.strip()
                    if line.startswith('INSERT INTO "{}"'.format(table)):
                        if sys.version_info.major == 2:
                            f.write(u'{}\n'.format(line).encode('utf-8'))
                        else:
                            f.write(u'{}\n'.format(line))

        print("Tables saved to directory {}/".format(directory))
        print("""=======================================================================================
You can now run git to commit and push these changes, if needed.
For example, if on the master branch you can do the following:
  git add {0} {1}/*.sql
  git commit -m "COMMIT MESSAGE HERE"
  git push origin master
You can then issue a pull request on GitHub to have these changes reviewed and accepted
======================================================================================="""
              .format(self.sqlpath, directory))
67364
function runProgramLogic() {
  var entries = db.getCollection("entries");
  var entryCount = entries.count();
  var now = new Date();

  console.log("old number of entries in database : " + entryCount);

  entries.insert({ x: now.getTime(), y: 100 - entryCount });
  entryCount = entries.count();

  console.log("new number of entries in database : " + entryCount);
  console.log("");
  
  // manually save
  db.saveDatabase(function(err) {
    if (err) {
      console.log(err);
    }
    else {
      console.log("saved... it can now be loaded or reloaded with up to date data");
    }
  });
}
1135090
protected function createEntry()
    {
        $arrColumns = $this->getTableColumns();
        $arrColumnNames = [];
        $arrColumnTypes = [];
        
        foreach ($arrColumns as $column) {
            $arrColumnNames[] = $column['Field'];
            $arrColumnTypes[] = $column['Type'];
        }
        
        $sql = 'INSERT INTO `'.$this->tableName.'` '
            . '(`'.implode('`, `', $arrColumnNames).'`) '
            . 'VALUES '
            . '(:'.implode(', :', $arrColumnNames).')';
        
        $arrInsert = [];
        for ($i = 0; $i < count($arrColumnNames); $i++) {
            $name = $arrColumnNames[$i];
            $value = isset($this->$name)?$this->$name:"";
            if (substr($arrColumnTypes[$i], 0, 3) == 'int') {
                $value = (int) $value;
            } elseif ($arrColumnTypes[$i] == 'datetime') {
                $value = strftime("%Y-%m-%d %H:%M:%S", strtotime($value));
            }
            $arrInsert[':'.$name] = $value;
        }
        
        
        $this->db->beginTransaction();
        $stmt = $this->db->prepare($sql);
        
        try {
            $stmt->execute($arrInsert);
            $this->db->commit();
        } catch (PDOException $ex) {
            $this->db->rollBack();
            $this->log->critical(
                "Could not save to mysql".PHP_EOL
                .$sql.PHP_EOL
                .print_r($arrInsert, true).PHP_EOL
                .$ex->getMessage()
            );
        }
    }
298501
async def save(self, db=None):
        '''
        
        '''
        self._db = db or self.db
        data = self.prepare_data()
        # validate object
        self.validate()
        # connect to DB to save the model
        for i in self.connection_retries():
            try:
                created = False if '_id' in data else True
                result = await self.db[self.get_collection_name()].insert_one(data)
                self._id = result.inserted_id
                # emit post save
                asyncio.ensure_future(post_save.send(
                    sender=self.__class__,
                    db=self.db,
                    instance=self,
                    created=created)
                )
                break
            except ConnectionFailure as ex:
                exceed = await self.check_reconnect_tries_and_wait(i, 'save')
                if exceed:
                    raise ex
273969
def pre_save(self, instance, add):
        """"""
        slug = self.value_from_object(instance)

        # We don't want to change slug defined by user.
        predefined_slug = bool(slug)

        if not slug and self.populate_from:
            slug = self._get_populate_from_value(instance)

        if slug:
            slug = slugify(slug)

        if not slug:
            slug = None

            if not self.blank:
                slug = instance._meta.model_name  # pylint: disable=protected-access
            elif not self.null:
                slug = ''

        if slug:
            # Make sure that auto generated slug with added sequence
            # won't excede maximal length.
            # Validation of predefined slugs is handled by Django.
            if not predefined_slug:
                slug = slug[:(self.max_length - MAX_SLUG_SEQUENCE_DIGITS - 1)]

            constraints_placeholder, constraints_values = self._get_unique_constraints(instance)

            instance_pk_name = instance._meta.pk.name  # pylint: disable=protected-access

            # Safe values - make sure that there is no chance of SQL injection.
            query_params = {
                'constraints_placeholder': constraints_placeholder,
                'slug_column': connection.ops.quote_name(self.column),
                'slug_len': len(slug),
                'table_name': connection.ops.quote_name(self.model._meta.db_table),  # pylint: disable=protected-access
                'pk_neq_placeholder': 'AND {} != %(instance_pk)s'.format(instance_pk_name) if instance.pk else ''
            }

            # SQL injection unsafe values - will be escaped.
            # Keys prefixed with `unique_` are reserved for `constraints_values` dict.
            query_escape_params = {
                'slug': slug,
                'slug_regex': '^{}(-[0-9]*)?$'.format(slug),
            }
            query_escape_params.update(constraints_values)
            if instance.pk:
                query_escape_params['instance_pk'] = instance.pk

            with connection.cursor() as cursor:
                # TODO: Slowest part of this query is `MAX` function. It can
                #       be optimized by indexing slug column by slug sequence.
                #       https://www.postgresql.org/docs/9.4/static/indexes-expressional.html
                cursor.execute(
                    """
                    SELECT
                        CASE
                            WHEN (
                                EXISTS(
                                    SELECT 1 FROM {table_name} WHERE (
                                        {slug_column} = %(slug)s
                                        {pk_neq_placeholder}
                                        {constraints_placeholder}
                                    )
                                )
                            ) THEN MAX(slug_sequence) + 1
                            ELSE NULL
                        END
                    FROM (
                        SELECT COALESCE(
                            NULLIF(
                                RIGHT({slug_column}, -{slug_len}-1),
                                ''
                            ),
                            '1'
                        )::text::integer AS slug_sequence
                        FROM {table_name} WHERE (
                            {slug_column} ~ %(slug_regex)s
                            {pk_neq_placeholder}
                            {constraints_placeholder}
                        )
                    ) AS tmp
                    """.format(**query_params),
                    params=query_escape_params
                )
                result = cursor.fetchone()[0]

            if result is not None:
                if predefined_slug:
                    raise SlugError(
                        "Slug '{}' (version {}) is already taken.".format(slug, instance.version)
                    )

                if len(str(result)) > MAX_SLUG_SEQUENCE_DIGITS:
                    raise SlugError(
                        "Auto-generated slug sequence too long - please choose a different slug."
                    )

                slug = '{}-{}'.format(slug, result)

            # Make the updated slug available as instance attribute.
            setattr(instance, self.name, slug)

        return slug
779941
def entry():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'action', help='Action to take',
        choices=['from_hex', 'to_rgb', 'to_hex'],
    )
    parser.add_argument(
        'value', help='Value for the action',
    )
    parsed = parser.parse_args()
    if parsed.action != "from_hex":
        try:
            parsed.value = int(parsed.value)
        except ValueError:
            raise argparse.ArgumentError(
                "Value for this action should be an integer",
            )
    print(globals()[parsed.action](parsed.value))