/** * Constructor * * @param mixed $table The table name or an instance of mr_db_table * @param mixed $default The default record data - just setting this will not trigger a save * @param boolean $trustcolumns If true, then checks for column exists are bypassed. * Only use when performance is an issue (EG: processing hundreds * of thousands) and that you KNOW all columns are correct */ public function __construct($table, $default = NULL, $trustcolumns = false) { if ($table instanceof mr_db_table) { $this->_table = $table; } else { $this->_table = new mr_db_table($table); } $this->_change = new stdClass(); $this->_record = new stdClass(); $this->trustcolumns = $trustcolumns; // Apply default to _record if (!is_null($default)) { if (is_array($default)) { $default = (object) $default; } $this->_record = $default; if (!$this->trustcolumns) { // Remove ID field if it is invalid if (empty($this->_record->id) or !is_number($this->_record->id)) { unset($this->_record->id); } // Remove values that are not in the table $columns = $this->_table->get_metacolumns(); foreach ($this->_record as $name => $value) { if (!array_key_exists($name, $columns)) { unset($this->_record->{$name}); } } } } }
/** * Flushes inserts * * @param string $table The table to flush * @throws coding_exception * @return void */ protected function _flush_inserts($table) { global $CFG, $DB; if (empty($this->inserts[$table])) { return; } $columns = $this->inserts[$table]['columns']; $records = $this->inserts[$table]['records']; // We clear the queue now so if there is an error, we don't try to // clear again on the __destruct() unset($this->inserts[$table]); $mrtable = new mr_db_table($table); $metacolumns = $mrtable->get_metacolumns(); if (!empty($columns)) { $values = array(); // Holds our CSVs $params = array(); $filler = array_fill(0, count($columns), '?'); $filler = implode(',', $filler); foreach ($records as $record) { // Get the record values in order of our columns foreach ($columns as $column) { if (!array_key_exists($column, $metacolumns)) { throw new coding_exception("Using an non-existant column ({$column}) for table ({$table})"); } else { if (isset($record->{$column})) { $params[] = $this->normalise_value($mrtable, $metacolumns[$column], $record->{$column}); } else { // Not set, use field's default - lookup in meta data $params[] = $mrtable->get_column_default($metacolumns[$column]); } } } $values[] = $filler; } if (!empty($values)) { $columns = implode(',', $columns); $values = implode('),(', $values); $DB->execute("INSERT INTO {$CFG->prefix}{$table} ({$columns}) VALUES ({$values})", $params); } } }