/** * Primary method that handles the processing of insert queries. * * Before a save is executed, a `preSave` and `preCreate` event will be triggered. * This event allows data to be modified before saving via references. * If this event returns a falsey value, the save will exit early and * return a 0. This allows behaviors and events to cease save operations. * * Before the driver is queried, the connection context will be set to `write`. * * After the query has executed, and no rows have been affected, the method * will exit early with a 0 response. Otherwise, a `postSave` and `postCreate` event will be triggered. * * @param \Titon\Db\Query $query * @param mixed $options { * @type bool $before Will trigger before callbacks * @type bool $after Will trigger after callbacks * } * @return int * - The ID of the record if successful * - 0 if save operation failed */ protected function _processCreate(Query $query, array $options = []) { $data = $query->getData(); $options = $options + ['before' => true, 'after' => true]; if ($options['before']) { foreach (['db.preSave', 'db.preCreate'] as $event) { $event = $this->emit($event, [$query, null, &$data]); if (!$event->getState()) { return 0; } } } // Reset the modified data $query->data($data); // Update the connection context $driver = $this->getDriver(); $driver->setContext('write'); // Execute the query $count = $driver->executeQuery($query)->save(); // Exit early if save failed if ($count === false) { return 0; } $id = $driver->getLastInsertID($this); if ($options['after']) { $this->emit('db.postSave db.postCreate', [$id, $count]); } return $this->id = $id; }
public function testResolveParamsMultiInsert() { $time = time(); $query = new Query(Query::MULTI_INSERT, $this->table); $query->data([['username' => 'foo', 'age' => 16, 'created' => null], ['username' => 'bar', 'age' => 33, 'created' => new \DateTime()]]); $this->assertEquals([['foo', PDO::PARAM_STR], [16, PDO::PARAM_INT], [null, PDO::PARAM_NULL], ['bar', PDO::PARAM_STR], [33, PDO::PARAM_INT], [date('Y-m-d H:i:s', $time), PDO::PARAM_STR]], $this->object->resolveParams($query)); }
public function testFormatValues() { $query = new Query(Query::INSERT, new User()); $query->data(['id' => 1, 'username' => 'miles', 'email' => '*****@*****.**']); $this->assertEquals('(?, ?, ?)', $this->object->formatValues($query)); }