Skip to content
This repository has been archived by the owner on May 28, 2021. It is now read-only.

Commit

Permalink
Partially working example2
Browse files Browse the repository at this point in the history
  • Loading branch information
nielssp committed May 17, 2016
1 parent 14e65a6 commit 3f11f7c
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 33 deletions.
36 changes: 14 additions & 22 deletions examples/example2.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
)
)));

class User extends \Jivoo\Data\ModelBase {

class User {
public static function getDefinition() {
$def = new \Jivoo\Data\DefinitionBuilder();
$def->addAutoIncrementId(); // Autoincrementing INT id
Expand All @@ -34,17 +33,6 @@ public static function getDefinition() {
}
}

// Schema for a a user table
class UserSchema extends SchemaBuilder {
protected function createSchema() {
$this->addAutoIncrementId(); // Autoincrementing INT id
$this->username = DataType::string(255); // Username VARCHAR(255)
$this->password = DataType::string(255); // Password VARCHAR(255)
$this->addtimeStamps(); // Timestamps: 'created' and 'updated'
$this->addUnique('username', 'username'); // A unique index on the username field
}
}

// Log database queries to output
$logger = new Logger();
$logger->addHandler(new CallbackHandler(function (array $record) {
Expand All @@ -55,47 +43,51 @@ protected function createSchema() {
$loader->setLogger($logger);

// Create schema for database using the above user table schema
$schema = new DatabaseDefinitionBuilder(array(new UserSchema));
$schema = new DatabaseDefinitionBuilder([
'User' => User::getDefinition()
]);

// Connect to "default":
$db = $loader->connect('default', $schema);

echo '<pre>';

// Delete table if it exists
if ($db->tableExists('User')) {
$db->dropTable('User');
if ($db->User->exists()) {
$db->User->drop();
}

// Create table
$db->createTable('User');
$db->User->create();

$schema = new Jivoo\Data\Database\DatabaseSchema($db);

// Insert a user (array style)
$db->User->insert(array(
$schema->User->insert(array(
'username' => 'root',
'password' => 'secret',
'created' => time(),
'updated' => time()
));

// Insert a user (active record style)
$user = $db->User->create();
$user = $schema->User->create();
$user->username = 'guest';
$user->password = 'secret';
$user->created = time();
$user->updated = time();
$user->save();

// Get data for root user:
print_r($db->User->where('username = %s', 'root')->first()->getData());
print_r($schema->User->where('username = %s', 'root')->first()->getData());

// List names of users created after 2015-01-01
$users = $db->User
$users = $schema->User
->where('created > %d', '2015-01-01') // Converts date using strtotime()
->orderBy('created');

foreach ($users as $user) {
echo h($user->username) . PHP_EOL;
echo $user->username . PHP_EOL;
}

echo '</pre>';
4 changes: 2 additions & 2 deletions src/Database/Common/SqlTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected function getType($field)
return $this->definition->getType($field);
}

protected function getAiPrimaryKey()
protected function getSerialPrimaryKey()
{
$pk = $this->definition->getPrimaryKey();
if (count($pk) == 1) {
Expand Down Expand Up @@ -391,7 +391,7 @@ public function insertMultiple(array $records, $replace = false)
$tuples[] = $tupleSql;
}
$sqlString .= implode(', ', $tuples);
return $this->owner->insert($sqlString, $this->getAiPrimaryKey());
return $this->owner->insert($sqlString, $this->getSerialPrimaryKey());
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/Database/InvalidTableException.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
namespace Jivoo\Data\Database;

/**
* Thrown when method is undefined.
* Thrown table is undefined.
*/
class InvalidTableException extends \RuntimeException implements \Jivoo\Exception
class InvalidTableException extends \UnexpectedValueException implements \Jivoo\Exception
{
}
1 change: 0 additions & 1 deletion src/Database/LoadableDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,6 @@ public function createTable($table, \Jivoo\Data\Definition $definition = null)
}
$this->migrationAdapter->createTable($table, $definition);
$this->definition->addDefinition($table, $definition);
$table = $definition->getName();
$this->tableNames[] = $table;
$this->tables[$table] = $this->getTable($table);
}
Expand Down
13 changes: 13 additions & 0 deletions src/Database/QueryException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Data\Database;

/**
* Thrown when a database query fails.
*/
class QueryException extends \RuntimeException implements \Jivoo\Exception
{
}
18 changes: 17 additions & 1 deletion src/Query/Builders/ReadSelectionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,21 @@ public function count()
*/
public function rowNumber(Record $record)
{
return $this->source->rowNumberSelection($this, $record);
if (! count($this->ordering)) {
throw new \Jivoo\InvalidArgumentException('Can\'t find row number in selection without ordering');
}
// TODO: undefined method
$definition = $this->source->getDefinition();
$selection = $this;
foreach ($this->ordering as $column) {
$type = $definition->getType($column[0]);
if ($column[1]) {
$selection = $selection->and('%c > %_', $column[0], $type, $record->$column);
} else {
$selection = $selection->and('%c < %_', $column[0], $type, $record->$column);
}
}
return $selection->count() + 1;
}

/**
Expand All @@ -364,6 +378,8 @@ public function toArray()
*/
public function getIterator()
{
// TODO: openSelection is on RecordSource not DataSource...
// return $this->source->openSelection($this);
return $this->source->readSelection($this);
}
}
2 changes: 1 addition & 1 deletion src/Query/SelectableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function __call($method, $args)
$selection = new SelectionBuilder($this->getSource());
return call_user_func_array([$selection, $method . 'Where'], $args);
}
throw new InvalidMethodException('Invalid method: ' . $method);
throw new \Jivoo\InvalidMethodException('Invalid method: ' . $method);
}

/**
Expand Down
11 changes: 7 additions & 4 deletions src/RecordBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public function getModel()
/**
* {@inheritdoc}
*/
public function addData($data, $allowedFields = null)
public function addData(array $data, $allowedFields = null)
{
if (! is_array($data)) {
return;
Expand Down Expand Up @@ -249,9 +249,12 @@ public function save()
}
if ($this->new) {
$insertId = $this->model->insert($this->data);
$pk = $this->model->getAiPrimaryKey();
if (isset($pk)) {
$this->data[$pk] = $insertId;
$pk = $this->model->getDefinition()->getPrimaryKey();
if (count($pk) == 1) {
$pk = $pk[0];
if ($this->model->getDefinition()->getType($pk)->serial) {
$this->data[$pk] = $insertId;
}
}
$this->new = false;
} elseif (count($this->updatedData) > 0) {
Expand Down

0 comments on commit 3f11f7c

Please sign in to comment.