+ $flags &= (self::SAVE_INSERT_MISSING | self::SAVE_UPDATE_EXISTING | self::SAVE_IGNORE_DUPLICATE);
+ Platal::assert($flags != 0, "Hey, the flags ($flags) here are so stupid, don't know what to do");
+ if ($flags == self::SAVE_UPDATE_EXISTING) {
+ $values = array();
+ foreach ($this->mutableFields as $field) {
+ if ($entry->hasChanged($field)) {
+ $values[] = XDB::format($field . ' = {?}', $entry->$field);
+ }
+ }
+ if (count($values) > 0) {
+ XDB::rawExecute('UPDATE ' . $this->table . '
+ SET ' . implode(', ', $values) . '
+ WHERE ' . $this->buildKeyCondition($entry, false));
+ }
+ } else {
+ $values = array();
+ foreach ($this->schema as $field=>$type) {
+ if ($entry->hasChanged($field)) {
+ $values[$field] = XDB::escape($entry->$field);
+ }
+ }
+ if (count($values) > 0) {
+ $query = $this->table . ' (' . implode(', ', array_keys($values)) . ')
+ VALUES (' . implode(', ', $values) . ')';
+ if (($flags & self::SAVE_UPDATE_EXISTING)) {
+ $update = array();
+ foreach ($this->mutableFields as $field) {
+ if (isset($values[$field])) {
+ $update[] = "$field = VALUES($field)";
+ }
+ }
+ if (count($update) > 0) {
+ $query = 'INSERT ' . $query;
+ $query .= "\n ON DUPLICATE KEY UPDATE " . implode(', ', $update);
+ } else {
+ $query = 'INSERT IGNORE ' . $query;
+ }
+ } else if (($flags & self::SAVE_IGNORE_DUPLICATE)) {
+ $query = 'INSERT IGNORE ' . $query;
+ } else {
+ $query = 'INSERT ' . $query;
+ }
+ XDB::rawExecute($query);
+ $id = XDB::insertId();
+ if ($id) {
+ foreach ($this->keyFields as $field) {
+ if ($this->schema[$field]->autoIncrement) {
+ $entry->$field = $id;
+ break;
+ }
+ }
+ }