/** * real implementation of Charcoal_SmartGateway::save() * * @param Charcoal_String|string $comment comment text * @param Charcoal_QueryTarget $query_target description about target model, alias, or joins * @param Charcoal_DTO $data associative DTO object to insert * * @return int last inserted id */ public function save($comment, $query_target, $data) { Charcoal_ParamTrait::validateString(1, $comment, TRUE); Charcoal_ParamTrait::validateIsA(2, 'Charcoal_QueryTarget', $query_target); Charcoal_ParamTrait::validateDTO(3, $data); $new_id = 0; try { $model = $this->getModel($query_target->getModelName()); $alias = $query_target->getAlias(); // primary key $pk = $model->getPrimaryKey(); // validate primary key value $valid = $model->validatePrimaryKeyValue($data); if ($valid) { // find entity $obj = self::findById($comment, $query_target, $data->{$pk}); // if not found, dto is regarded as a new entity $is_new = empty($obj); } else { // if promary key value is invalid, dto id rebgarded as a new entity $is_new = true; } // build SQL if (!$is_new) { // UPDATE $data_id = $data[$pk]; $where = "{$pk} = ?"; $params = array(ui($data_id)); $criteria = new Charcoal_SQLCriteria($where, $params); list($sql, $params) = $this->sql_builder->buildUpdateSQL($model, $alias, $data, $criteria); } else { // INSERT list($sql, $params) = $this->sql_builder->buildInsertSQL($model, $alias, $data); $is_new = TRUE; } $sql = !empty($comment) ? $this->sql_builder->prependComment($sql, $comment) : $sql; $this->data_source->prepareExecute($sql, $params); if ($is_new) { $sql = $this->sql_builder->buildLastIdSQL(); $result = $this->data_source->prepareExecute($sql); $row = $this->data_source->fetchArray($result); $new_id = $row[0]; } else { $new_id = $data[$pk]; } log_debug("debug,smart_gateway,sql", "new_id:{$new_id}", self::TAG); } catch (Exception $e) { _catch($e); _throw(new Charcoal_DBException(__METHOD__ . " Failed.", $e)); } return $new_id; }