/** * @param array|\DibiRow $article * @return bool */ public function save(&$article) { if (!isset($article['id'])) { $this->database->insert(self::TABLE, $article)->execute(); $article['id'] = $this->database->getInsertId(); } else { $this->database->update(self::TABLE, $article)->where(self::TABLE, '.id = %i', $article['id'])->execute(); } return $this->database->getAffectedRows() == 1; }
public function testFindByPrimary() { // find by primary // insert new article $this->db->insert("pages", array("name" => "Find test", "description" => "Find by primary", "text" => "Nějaký text.", "allowed" => true))->execute(); $id = $this->db->getInsertId(); $o = $this->object->find($id); $this->assertType("Page", $o); $this->assertEquals("Find test", $o->name); }
/** * @param object $instance * @param ClassMetadata $entityAttributes * @throws \RuntimeException * @return \DibiResult|int */ private function insertItem($instance, ClassMetadata $entityAttributes) { if ($entityAttributes->hasBeforeCreateEvent()) { $instance->beforeCreateEvent($this); } $values = $this->getInstanceValueMap($instance, $entityAttributes); $this->dibiConnection->insert($entityAttributes->getTable(), $values)->execute(); $insertId = NULL; if ($entityAttributes->getAutoIncrementFieldName()) { $insertId = $this->dibiConnection->getInsertId(); if (!$insertId) { throw new \RuntimeException('Entity has set autoIncrement flag but no incremented values was returned from DB.'); } DataHelperLoader::setPropertyValue($instance, $entityAttributes->getAutoIncrementFieldName(), $insertId); } // Unset origin class hash and set new one by primary key $hash = spl_object_hash($instance); if (array_key_exists($hash, $this->managedClasses)) { unset($this->managedClasses[$hash]); } $classKey = $this->getEntityClassHashKey($instance, $entityAttributes); $this->managedClasses[$classKey]['instance'] = $instance; $this->managedClasses[$classKey]['flag'] = self::FLAG_INSTANCE_UPDATE; $this->managedClasses[$classKey]['valueHash'] = $this->getInstanceValuesHash($instance, $entityAttributes); return $insertId; }
/** * Store authorization code * @param IAuthorizationCode $authorizationCode * @throws InvalidScopeException */ public function store(IAuthorizationCode $authorizationCode) { $this->context->insert($this->getTable(), array('authorization_code' => $authorizationCode->getAuthorizationCode(), 'client_id' => $authorizationCode->getClientId(), 'user_id' => $authorizationCode->getUserId(), 'expires_at' => $authorizationCode->getExpires()))->execute(); $this->context->begin(); try { foreach ($authorizationCode->getScope() as $scope) { $this->context->insert($this->getScopeTable(), array('authorization_code' => $authorizationCode->getAuthorizationCode(), 'scope_name' => $scope))->execute(); } } catch (\PDOException $e) { // MySQL error 1452 - Cannot add or update a child row: a foreign key constraint fails if (in_array(1452, $e->errorInfo)) { throw new InvalidScopeException(); } throw $e; } $this->context->commit(); }
public function createInsert($table, array $values, $primaryName = null) { $query = new Query($this->connection->insert($table, $values)); $query->resultCallback = function (Query $query) { $query->fluent->execute(); return $this->connection->getInsertId(); }; return $query; }
/** * Creates new preshared secret * * @param string|NULL note * @param DateTime|NULL expiration date * @return string[16] * @throws Nette\InvalidArgumentException if invalid expiration date */ public function createPsk($expiration = NULL, $note = NULL) { if ($expiration !== NULL && !$expiration instanceof \DateTime) { throw new Nette\InvalidArgumentException("Expected NULL or DateTime instance"); } while (true) { $psk = Strings::randomHumanToken(16); $values = array($this->fieldName[self::PSK] => $psk, $this->fieldName[self::EXPIRATION] => $expiration, $this->fieldName[self::NOTE] => $note); try { $this->db->insert($this->tableName, $values)->execute(); break; } catch (\DibiException $e) { if ($e->getCode() != 1062) { throw $e; } } } return $psk; }
/** * Inserts topic * * @access public * @param \Nette\ArrayHash $data data * @param int $topicId topic ID to reply * @return void * @uses getTopic() * @since 1.0.0 */ public function insert(\Nette\ArrayHash $data, $topicId) { $data->id_forum = $this->forumId; $this->connection->query('LOCK TABLES [' . $this->tThreads . '] WRITE'); $re = $this->getTopic($topicId); if ($topicId && $re !== FALSE) { $re = $this->connection->select('MIN([sequence]) - 1')->as('new_sequence')->select('%i + %i', $re->depth, 1)->as('new_depth')->from($this->tThreads)->where('[id_forum] = %i', $this->forumId)->and('[sequence] > %i', $re->sequence)->and('[depth] <= %i', $re->depth)->fetch(); if ($re->new_sequence) { $this->connection->query('UPDATE [' . $this->tThreads . '] SET [sequence] = [sequence] + %i WHERE [id_forum] = %i AND [sequence] > %i', 1, $this->forumId, $re->new_sequence); } else { $re = $this->connection->select('MAX([sequence])')->as('new_sequence')->select('%i', $re->new_depth)->as('new_depth')->from($this->tThreads)->where('[id_forum] = %i', $this->forumId)->fetch(); } } else { $re = $this->connection->select('MAX([sequence])')->as('new_sequence')->select('%i', 0)->as('new_depth')->from($this->tThreads)->where('[id_forum] = %i', $this->forumId)->fetch(); } $data->sequence = $re->new_sequence + 1; $data->depth = $re->new_depth; $this->connection->insert($this->tThreads, $data)->execute(); $this->connection->query('UNLOCK TABLES'); }
/** * Creates IIdentity object from obtained user data * * @param mixed user data * @param IAuthenticator authenticator * * @return IIdentity */ public function createIdentity($userData, $authenticator) { $uid = NULL; $roles = array(); $profile = array(); // --------------------------------------------------------------------- // DB Password if ($authenticator instanceof Authenticators\DatabasePasswordAuthenticator) { $uid = (int) $userData->{$authenticator->getColumn($authenticator::ID)}; $profile = $userData; } elseif ($authenticator instanceof Authenticators\LdapBindAuthenticator) { $ldapData = (array) $userData; $idCol = 'id'; $tableName = 'security_users'; // LDAP Binding // DB column name -> ldap array key (or callable) $binding = array(array('username' => function ($ldapData) use($authenticator) { return mb_substr($ldapData['dn'], mb_strlen($authenticator->getQueryPrefix()), 0 - mb_strlen($authenticator->getQuerySuffix())); }), array('name' => 'givenName', 'surname' => 'sn', 'email' => function ($ldapData) use(&$binding) { $username = $binding[0]['username']($ldapData); $tokens = Strings::splitWithEscape($ldapData['dn'], ',dc='); array_shift($tokens); return $username . '@' . implode($tokens, '.'); })); // Prepare data based on LDAP binding $boundData = $this->bindValues($ldapData, $binding[0]); $this->db->query('LOCK TABLES %n WRITE', $tableName); $ds = $this->db->select('*')->from($tableName); foreach ($boundData as $key => $value) { $ds->where('%n = %s', $key, $value); } $profile = $ds->fetch(); // If profile does not exist yet if ($profile === FALSE) { $boundData = array_merge($boundData, $this->bindValues($ldapData, $binding[1])); $this->db->insert($tableName, $boundData)->execute(); $boundData[$idCol] = $uid = (int) $this->db->getInsertId(); $profile = $boundData; } else { $uid = (int) $profile[$idCol]; } $this->db->query('UNLOCK TABLES'); // TODO: configurable $groupsDn = NULL; if ($groupsDn == NULL) { $dnTokens = array_reverse($userData->getParsedDn()); foreach ($dnTokens as $k => $v) { if (!Strings::startsWith($v, 'dc=')) { array_splice($dnTokens, $k, count($dnTokens), array('ou=groups')); break; } } $groupDn = implode(array_reverse($dnTokens), ','); } $username = str_replace(array('\\', ')'), array('\\\\', '\\)'), $boundData['username']); $userGid = intval($userData->gidNumber); $filter = "(&(objectClass=posixGroup)(|(gidNumber={$userGid})(memberUid={$username})))"; $result = $authenticator->ldapConnection->search($groupsDn, $filter); foreach ($result as $record) { $roles[] = $record->cn; } } elseif ($authenticator instanceof Authenticators\DatabasePSKAuthenticator) { $uid = Strings::intoParameterizedString('psk', array($userData->key)); $roles[] = $uid; $profile = $userData; // Other authenticators } else { throw new Nette\NotSupportedException("Authenticator " . get_class($authenticator) . " not supported yet"); } // --------------------------------------------------------------------- // Remove duplicit roles $roles = array_unique($roles); // Sanity check if (!is_scalar($uid) || $uid == "") { throw new Nette\InvalidStateException("User ID has to be non-empty string or number"); } // --------------------------------------------------------------------- // Query roles from DB if it's not PSK (has user id) if (is_int($uid)) { $roles = array_merge($this->getUserRoles($uid), $roles); } // --------------------------------------------------------------------- // Identity $identity = new Nette\Security\Identity($uid, $roles, $profile); return $identity; }
public function insert() { $this->db->insert($this->table, $this->data)->execute(); return $this->db->insertId; }
public function insert(array $data) { return $this->connection->insert($this->table, $data)->execute(dibi::IDENTIFIER); }
public function addGroup($values) { $columnArray['name%s'] = $values->name; $columnArray['desc%s'] = $values->desc; $this->database->insert(self::TABLE, $columnArray)->execute(); }
/** * Store refresh token * @param IRefreshToken $refreshToken */ public function store(IRefreshToken $refreshToken) { $this->context->insert($this->getTable(), array('refresh_token' => $refreshToken->getRefreshToken(), 'client_id' => $refreshToken->getClientId(), 'user_id' => $refreshToken->getUserId(), 'expires_at' => $refreshToken->getExpires()))->execute(); }