Begin Refactor

This commit is contained in:
color.diff=auto
2021-03-21 13:47:29 -06:00
parent 7622dc0d02
commit 018931d7ae
197 changed files with 47799 additions and 6 deletions

View File

@@ -0,0 +1,130 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
/**
* Bigint
*
* Tests handling of bigint type columns for primary key IDs,
* can we use bigint primary keys without issues ?
* These tests should be able to detect incorrect intval
* casts for instance.
*
* @file RedUNIT/Mysql/Bigint.php
* @desc Tests support for BIGINT primary keys.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Bigint extends Mysql
{
/**
* Test BIG INT primary key support.
*
* @return void
*/
public function testBigIntSupport()
{
R::nuke();
$createPageTableSQL = '
CREATE TABLE
`page`
(
id BIGINT(20) UNSIGNED NOT NULL,
book_id BIGINT(20) UNSIGNED NOT NULL,
magazine_id BIGINT(20) UNSIGNED NULL,
title VARCHAR(255),
PRIMARY KEY ( id )
)
ENGINE = InnoDB DEFAULT
CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci
AUTO_INCREMENT = 1223372036854775808';
$createBookTableSQL = '
CREATE TABLE
`book`
(
id BIGINT(20) UNSIGNED NOT NULL,
title VARCHAR(255),
PRIMARY KEY ( id )
)
ENGINE = InnoDB DEFAULT
CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci
AUTO_INCREMENT = 2223372036854775808';
$createPagePageTableSQL = '
CREATE TABLE
`page_page`
(
id BIGINT(20) UNSIGNED NOT NULL,
page_id BIGINT(20) UNSIGNED NOT NULL,
page2_id BIGINT(20) UNSIGNED NOT NULL,
PRIMARY KEY ( id )
)
ENGINE = InnoDB DEFAULT
CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci
AUTO_INCREMENT = 3223372036854775808';
R::exec( $createBookTableSQL );
R::exec( $createPageTableSQL );
R::exec( $createPagePageTableSQL );
//insert some records
$book1ID = '2223372036854775808';
$book2ID = '2223372036854775809';
$page1ID = '1223372036854775808';
$page2ID = '1223372036854775809';
$page3ID = '1223372036854775890';
$pagePage1ID = '3223372036854775808';
$insertBook1SQL = "
INSERT INTO book (id, title) VALUES( '$book1ID', 'book 1' );
";
$insertBook2SQL = "
INSERT INTO book (id, title) VALUES( '$book2ID', 'book 2' );
";
$insertPage1SQL = "
INSERT INTO page (id, book_id, title, magazine_id) VALUES( '$page1ID', '$book1ID', 'page 1 of book 1', '$book2ID' );
";
$insertPage2SQL = "
INSERT INTO page (id, book_id, title) VALUES( '$page2ID', '$book1ID', 'page 2 of book 1' );
";
$insertPage3SQL = "
INSERT INTO page (id, book_id, title) VALUES( '$page3ID', '$book2ID', 'page 1 of book 2' );
";
$insertPagePage1SQL = "
INSERT INTO page_page (id, page_id, page2_id) VALUES( '$pagePage1ID', '$page2ID', '$page3ID' );
";
R::exec( $insertBook1SQL );
R::exec( $insertBook2SQL );
R::exec( $insertPage1SQL );
R::exec( $insertPage2SQL );
R::exec( $insertPage3SQL );
R::exec( $insertPagePage1SQL );
//basic tour of basic functions....
$book1 = R::load( 'book', $book1ID );
asrt( $book1->id, $book1ID );
asrt( $book1->title, 'book 1' );
$book2 = R::load( 'book', $book2ID );
asrt( $book2->id, $book2ID );
asrt( $book2->title, 'book 2' );
asrt( count( $book1->ownPage ), 2 );
asrt( count( $book1->fresh()->with( 'LIMIT 1' )->ownPage ), 1 );
asrt( count( $book1->fresh()->withCondition( ' title = ? ', array('page 2 of book 1'))->ownPage ), 1 );
asrt( count($book2->ownPage), 1 );
asrt( $book2->fresh()->countOwn( 'page' ), 1 );
$page1 = R::load( 'page', $page1ID );
asrt( count( $page1->sharedPage ), 0 );
asrt( $page1->fetchAs( 'book' )->magazine->id, $book2ID );
$page2 = R::load( 'page', $page2ID );
asrt( count($page2->sharedPage), 1 );
asrt( $page2->fresh()->countShared( 'page' ), 1 );
$page3 = R::findOne( 'page', ' title = ? ', array( 'page 1 of book 2' ) );
asrt( $page3->id, $page3ID );
asrt( $page3->book->id, $book2ID );
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
/**
* Double
*
* Tests whether double precision values are correctly stored and
* preserved.
*
* @file RedUNIT/Mysql/Double.php
* @desc Tests handling of double precision values.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Double extends Mysql
{
/**
* Test storage of doubles.
*
* @return void
*/
public function testDouble()
{
$toolbox = R::getToolBox();
$adapter = $toolbox->getDatabaseAdapter();
$writer = $toolbox->getWriter();
$redbean = $toolbox->getRedBean();
$pdo = $adapter->getDatabase();
$largeDouble = 999999888889999922211111; //8.88889999922211e+17;
$page = $redbean->dispense( "page" );
$page->weight = $largeDouble;
$id = $redbean->store( $page );
$cols = $writer->getColumns( 'page' );
asrt( $cols['weight'], 'double' );
$page = $redbean->load( 'page', $id );
$page->name = 'dont change the numbers!';
$redbean->store( $page );
$page = $redbean->load( 'page', $id );
$cols = $writer->getColumns( 'page' );
asrt( $cols['weight'], 'double' );
}
}

View File

@@ -0,0 +1,342 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
/**
* Foreignkeys
*
* Tests creation and validity of foreign keys,
* foreign key constraints and indexes in Mysql/MariaDB.
* Also tests whether the correct contraint action has been selected.
*
* @file RedUNIT/Mysql/Foreignkeys.php
* @desc Tests creation of foreign keys.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Foreignkeys extends Mysql
{
/**
* Test whether we can use foreign keys with keywords.
*
* @return void
*/
public function testKWConflicts()
{
R::nuke();
$metrics = R::dispense( 'metrics' );
$constraint = R::dispense( 'constraint' );
$constraint->xownMetrics[] = $metrics;
R::store( $constraint );
asrt( 1, R::count( 'metrics' ) );
R::trash($constraint);
asrt( 0, R::count( 'metrics') );
}
/**
* Basic FK tests.
*
* @return void
*/
public function testFKS()
{
$book = R::dispense( 'book' );
$page = R::dispense( 'page' );
$cover = R::dispense( 'cover' );
list( $g1, $g2 ) = R::dispense( 'genre', 2 );
$g1->name = '1';
$g2->name = '2';
$book->ownPage = array( $page );
$book->cover = $cover;
$book->sharedGenre = array( $g1, $g2 );
R::store( $book );
$fkbook = R::getAll( 'describe book' );
$fkgenre = R::getAll( 'describe book_genre' );
$fkpage = R::getAll( 'describe cover' );
$j = json_encode( R::getAll( 'SELECT
ke.referenced_table_name parent,
ke.table_name child,
ke.constraint_name
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
AND ke.CONSTRAINT_SCHEMA="oodb"
ORDER BY
constraint_name;' ) );
$json = '[
{
"parent": "genre",
"child": "book_genre",
"constraint_name": "c_fk_book_genre_genre_id"
},
{
"parent": "book",
"child": "book_genre",
"constraint_name": "c_fk_book_genre_book_id"
},
{
"parent": "cover",
"child": "book",
"constraint_name": "c_fk_book_cover_id"
},
{
"parent": "book",
"child": "page",
"constraint_name": "c_fk_page_book_id"
}
]';
$j1 = json_decode( $j, TRUE );
$j2 = json_decode( $json, TRUE );
foreach ( $j1 as $jrow ) {
$s = json_encode( $jrow );
$found = 0;
foreach ( $j2 as $k => $j2row ) {
if ( json_encode( $j2row ) === $s ) {
pass();
unset( $j2[$k] );
$found = 1;
break;
}
}
if ( !$found ) fail();
}
}
/**
* Test widen for constraint.
*
* @return void
*/
public function testWideningColumnForConstraint()
{
testpack( 'widening column for constraint' );
$bean1 = R::dispense( 'project' );
$bean2 = R::dispense( 'invoice' );
$bean3 = R::getRedBean()->dispense( 'invoice_project' );
$bean3->project_id = FALSE;
$bean3->invoice_id = TRUE;
R::store( $bean3 );
$cols = R::getColumns( 'invoice_project' );
asrt( $cols['project_id'], "int(11) unsigned" );
asrt( $cols['invoice_id'], "int(11) unsigned" );
}
/**
* Test adding of constraints directly by invoking
* the writer method.
*
* @return void
*/
public function testContrain()
{
R::nuke();
$sql = '
CREATE TABLE book (
id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$sql = '
CREATE TABLE page (
id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$sql = '
CREATE TABLE book_page (
id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT,
book_id INT( 11 ) UNSIGNED NOT NULL,
page_id INT( 11 ) UNSIGNED NOT NULL,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "book_page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 0 );
$writer = R::getWriter();
$writer->addFK( 'book_page', 'book', 'book_id', 'id', TRUE );
$writer->addFK( 'book_page', 'page', 'page_id', 'id', TRUE );
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "book_page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 2 );
$writer->addFK( 'book_page', 'book', 'book_id', 'id', TRUE );
$writer->addFK( 'book_page', 'page', 'page_id', 'id', TRUE );
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "book_page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 2 );
}
/**
* Test adding foreign keys.
*
* @return void
*/
public function testAddingForeignKey()
{
R::nuke();
$sql = '
CREATE TABLE book (
id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$sql = '
CREATE TABLE page (
id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT,
book_id INT( 11 ) UNSIGNED NOT NULL,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 0 );
$writer = R::getWriter();
//Can we add a foreign key with cascade?
$writer->addFK('page', 'book', 'book_id', 'id', TRUE);
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 1 );
//dont add it twice
$writer->addFK('page', 'book', 'book_id', 'id', TRUE);
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 1 );
//even if different
$writer->addFK('page', 'book', 'book_id', 'id', FALSE);
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" ');
asrt( (int) $numOfFKS, 1 );
//Now add non-dep key
R::nuke();
$sql = '
CREATE TABLE book (
id INT( 11 ) UNSIGNED AUTO_INCREMENT,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$sql = '
CREATE TABLE page (
id INT( 11 ) UNSIGNED AUTO_INCREMENT,
book_id INT( 11 ) UNSIGNED NULL,
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 0 );
//even if different
$writer->addFK('page', 'book', 'book_id', 'id', FALSE);
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" AND DELETE_RULE = "CASCADE"');
asrt( (int) $numOfFKS, 0 );
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" AND DELETE_RULE = "SET NULL"');
asrt( (int) $numOfFKS, 1 );
$writer->addFK('page', 'book', 'book_id', 'id', TRUE);
$numOfFKS = R::getCell('
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME = "page" ');
}
/**
* Test whether we can manually create indexes.
*
* @return void
*/
public function testAddingIndex()
{
R::nuke();
$sql = '
CREATE TABLE song (
id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT,
album_id INT( 11 ) UNSIGNED NOT NULL,
category VARCHAR( 255 ),
PRIMARY KEY ( id )
)
ENGINE = InnoDB
';
R::exec( $sql );
$sql = 'SHOW INDEX FROM song';
$indexes = R::getAll( $sql );
asrt( count( $indexes ), 1 );
asrt( $indexes[0]['Table'], 'song' );
asrt( $indexes[0]['Key_name'], 'PRIMARY' );
$writer = R::getWriter();
$writer->addIndex('song', 'index1', 'album_id');
$indexes = R::getAll( 'SHOW INDEX FROM song' );
asrt( count( $indexes ), 2 );
asrt( $indexes[0]['Table'], 'song' );
asrt( $indexes[0]['Key_name'], 'PRIMARY' );
asrt( $indexes[1]['Table'], 'song' );
asrt( $indexes[1]['Key_name'], 'index1' );
//Cant add the same index twice
$writer->addIndex('song', 'index2', 'category');
$indexes = R::getAll( 'SHOW INDEX FROM song' );
asrt( count( $indexes ), 3 );
//Dont fail, just dont
try {
$writer->addIndex('song', 'index3', 'nonexistant');
pass();
} catch( \Exception $e ) {
fail();
}
asrt( count( $indexes ), 3 );
try {
$writer->addIndex('nonexistant', 'index4', 'nonexistant');
pass();
} catch( \Exception $e ) {
fail();
}
asrt( count( $indexes ), 3 );
try {
$writer->addIndex('nonexistant', '', 'nonexistant');
pass();
} catch( \Exception $e ) {
fail();
}
asrt( count( $indexes ), 3 );
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
use RedBeanPHP\AssociationManager as AssociationManager;
use RedBeanPHP\RedException\SQL as SQL;
/**
* Freeze
*
* Tests whether database schema remains unmodified in frozen
* mode.
*
* @file RedUNIT/Mysql/Freeze.php
* @desc Tests freezing of databases for production environments.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Freeze extends Mysql
{
/**
* Tests freezing the database.
* After freezing the database, schema modifications are no longer
* allowed and referring to missing columns will now cause exceptions.
*
* @return void
*/
public function testFreezer()
{
$toolbox = R::getToolBox();
$adapter = $toolbox->getDatabaseAdapter();
$writer = $toolbox->getWriter();
$redbean = $toolbox->getRedBean();
$pdo = $adapter->getDatabase();
$a = new AssociationManager( $toolbox );
$post = $redbean->dispense( 'post' );
$post->title = 'title';
$redbean->store( $post );
$page = $redbean->dispense( 'page' );
$page->name = 'title';
$redbean->store( $page );
$page = $redbean->dispense( "page" );
$page->name = "John's page";
$idpage = $redbean->store( $page );
$page2 = $redbean->dispense( "page" );
$page2->name = "John's second page";
$idpage2 = $redbean->store( $page2 );
$a->associate( $page, $page2 );
$redbean->freeze( TRUE );
$page = $redbean->dispense( "page" );
$page->sections = 10;
$page->name = "half a page";
try {
$id = $redbean->store( $page );
fail();
} catch ( SQL $e ) {
pass();
}
$post = $redbean->dispense( "post" );
$post->title = "existing table";
try {
$id = $redbean->store( $post );
pass();
} catch ( SQL $e ) {
fail();
}
asrt( in_array( "name", array_keys( $writer->getColumns( "page" ) ) ), TRUE );
asrt( in_array( "sections", array_keys( $writer->getColumns( "page" ) ) ), FALSE );
$newtype = $redbean->dispense( "newtype" );
$newtype->property = 1;
try {
$id = $redbean->store( $newtype );
fail();
} catch ( SQL $e ) {
pass();
}
$logger = R::debug( TRUE, 1 );
// Now log and make sure no 'describe SQL' happens
$page = $redbean->dispense( "page" );
$page->name = "just another page that has been frozen...";
$id = $redbean->store( $page );
$page = $redbean->load( "page", $id );
$page->name = "just a frozen page...";
$redbean->store( $page );
$page2 = $redbean->dispense( "page" );
$page2->name = "an associated frozen page";
$a->associate( $page, $page2 );
$a->related( $page, "page" );
$a->unassociate( $page, $page2 );
$a->clearRelations( $page, "page" );
$items = $redbean->find( "page", array(), array( "1" ) );
$redbean->trash( $page );
$redbean->freeze( FALSE );
asrt( count( $logger->grep( "SELECT" ) ) > 0, TRUE );
asrt( count( $logger->grep( "describe" ) ) < 1, TRUE );
asrt( is_array( $logger->getLogs() ), TRUE );
R::debug( FALSE );
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
/**
* Issue 411
*
* InnoDB has a maximum index length of 767 bytes, so with utf8mb4
* you can only store 191 characters. This means that when you
* subsequently add an index to the column you get a
* (not-so-obvious) MySQL-error. That's why we limit the varchar to
* 191 chars and then switch to TEXT type.
*
* @file RedUNIT/Mysql/Issue411.php
* @desc Tests intermediate varchar 191 type for MySQL utf8mb4.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Issue411 extends Mysql
{
/**
* Test varchar 191 condition.
*
* @return void
*/
public function testInnoDBIndexLimit()
{
R::nuke();
$book = R::dispense( 'book' );
$book->text = 'abcd';
R::store( $book );
$columns = R::inspect( 'book' );
asrt( isset( $columns['text'] ), TRUE );
asrt( $columns['text'], 'varchar(191)' );
$book = $book->fresh();
$book->text = str_repeat( 'x', 190 );
R::store( $book );
$columns = R::inspect( 'book' );
asrt( isset( $columns['text'] ), TRUE );
asrt( $columns['text'], 'varchar(191)' );
$book = $book->fresh();
$book->text = str_repeat( 'x', 191 );
R::store( $book );
$columns = R::inspect( 'book' );
asrt( isset( $columns['text'] ), TRUE );
asrt( $columns['text'], 'varchar(191)' );
$book = $book->fresh();
$book->text = str_repeat( 'x', 192 );
R::store( $book );
$columns = R::inspect( 'book' );
asrt( isset( $columns['text'] ), TRUE );
asrt( $columns['text'], 'varchar(255)' );
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
use RedBeanPHP\RedException\SQL as SQL;
/**
* Parambind
*
* Tests the parameter binding functionality in RedBeanPHP.
* These test scenarios include for instance: NULL handling,
* binding parameters in LIMIT clauses and so on.
*
* @file RedUNIT/Mysql/Parambind.php
* @desc Tests\PDO parameter binding.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Parambind extends Mysql
{
/**
* Test parameter binding with\PDO.
*
* @return void
*/
public function testPDOParameterBinding()
{
$toolbox = R::getToolBox();
$adapter = $toolbox->getDatabaseAdapter();
$writer = $toolbox->getWriter();
$redbean = $toolbox->getRedBean();
$pdo = $adapter->getDatabase();
R::getDatabaseAdapter()->getDatabase()->setUseStringOnlyBinding( TRUE );
try {
R::getAll( "select * from job limit ? ", array( 1 ) );
fail();
} catch (\Exception $e ) {
pass();
}
try {
R::getAll( "select * from job limit :l ", array( ":l" => 1 ) );
fail();
} catch (\Exception $e ) {
pass();
}
try {
R::exec( "select * from job limit ? ", array( 1 ) );
fail();
} catch (\Exception $e ) {
pass();
}
try {
R::exec( "select * from job limit :l ", array( ":l" => 1 ) );
fail();
} catch (\Exception $e ) {
pass();
}
R::getDatabaseAdapter()->getDatabase()->setUseStringOnlyBinding( FALSE );
try {
R::getAll( "select * from job limit ? ", array( 1 ) );
pass();
} catch (\Exception $e ) {
fail();
}
try {
R::getAll( "select * from job limit :l ", array( ":l" => 1 ) );
pass();
} catch (\Exception $e ) {
fail();
}
try {
R::exec( "select * from job limit ? ", array( 1 ) );
pass();
} catch (\Exception $e ) {
fail();
}
try {
R::exec( "select * from job limit :l ", array( ":l" => 1 ) );
pass();
} catch (\Exception $e ) {
fail();
}
testpack( "Test findOrDispense" );
$person = R::findOrDispense( "person", " job = ? ", array( "developer" ) );
asrt( ( count( $person ) > 0 ), TRUE );
$person = R::findOrDispense( "person", " job = ? ", array( "musician" ) );
asrt( ( count( $person ) > 0 ), TRUE );
$musician = array_pop( $person );
asrt( intval( $musician->id ), 0 );
try {
$adapter->exec( "an invalid query" );
fail();
} catch ( SQL $e ) {
pass();
}
asrt( (int) $adapter->getCell( "SELECT 123" ), 123 );
asrt( (int) $adapter->getCell( "SELECT ?", array( "987" ) ), 987 );
asrt( (int) $adapter->getCell( "SELECT ?+?", array( "987", "2" ) ), 989 );
asrt( (int) $adapter->getCell( "SELECT :numberOne+:numberTwo", array(
":numberOne" => 42, ":numberTwo" => 50 ) ), 92 );
$pair = $adapter->getAssoc( "SELECT 'thekey','thevalue' " );
asrt( is_array( $pair ), TRUE );
asrt( count( $pair ), 1 );
asrt( isset( $pair["thekey"] ), TRUE );
asrt( $pair["thekey"], "thevalue" );
testpack( 'Test whether we can properly bind and receive NULL values' );
asrt( $adapter->getCell( 'SELECT :nil ', array( ':nil' => 'NULL' ) ), 'NULL' );
asrt( $adapter->getCell( 'SELECT :nil ', array( ':nil' => NULL ) ), NULL );
asrt( $adapter->getCell( 'SELECT ? ', array( 'NULL' ) ), 'NULL' );
asrt( $adapter->getCell( 'SELECT ? ', array( NULL ) ), NULL );
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
use RedBeanPHP\AssociationManager as AssociationManager;
/**
* Preexist
*
* Tests whether RedBeanPHP can work with existing
* MySQL schemas.
*
* @file RedUNIT/Mysql/Preexist.php
* @desc Tests integration with pre-existing schemas.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Preexist extends Mysql
{
/**
* Test integration with pre-existing schemas.
*
* @return void
*/
public function testPlaysNiceWithPreExitsingSchema()
{
$toolbox = R::getToolBox();
$adapter = $toolbox->getDatabaseAdapter();
$writer = $toolbox->getWriter();
$redbean = $toolbox->getRedBean();
$pdo = $adapter->getDatabase();
$a = new AssociationManager( $toolbox );
$page = $redbean->dispense( "page" );
$page->name = "John's page";
$idpage = $redbean->store( $page );
$page2 = $redbean->dispense( "page" );
$page2->name = "John's second page";
$idpage2 = $redbean->store( $page2 );
$a->associate( $page, $page2 );
$adapter->exec( "ALTER TABLE " . $writer->esc( 'page' ) . "
CHANGE " . $writer->esc( 'name' ) . " " . $writer->esc( 'name' ) . "
VARCHAR( 254 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL " );
$page = $redbean->dispense( "page" );
$page->name = "Just Another Page In a Table";
$cols = $writer->getColumns( "page" );
asrt( $cols["name"], "varchar(254)" );
$redbean->store( $page );
pass(); // No crash?
$cols = $writer->getColumns( "page" );
asrt( $cols["name"], "varchar(254)" ); //must still be same
}
}

View File

@@ -0,0 +1,160 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
/**
* Setget
*
* This class has been designed to test set/get operations
* for a specific Query Writer / Adapter. Since RedBeanPHP
* creates columns based on values it's essential that you
* get back the 'same' value as you put in - or - if that's
* not the case, that there are at least very clear rules
* about what to expect. Examples of possible issues tested in
* this class include:
*
* - Test whether booleans are returned correctly (they will become integers)
* - Test whether large numbers are preserved
* - Test whether floating point numbers are preserved
* - Test whether date/time values are preserved
* and so on...
*
* @file RedUNIT/Mysql/Setget.php
* @desc Tests whether values are stored correctly.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Setget extends Mysql
{
/**
* Test whether we can store DateTime objects and get them back
* as 'date-time' strings representing the same date and time.
*
* @return void
*/
public function testDateObject()
{
$dt = new \DateTime();
$dt->setTimeZone( new \DateTimeZone( 'Europe/Amsterdam' ) );
$dt->setDate( 1981, 5, 1 );
$dt->setTime( 3, 13, 13 );
asrt( setget( $dt ), '1981-05-01 03:13:13' );
$bean = R::dispense( 'bean' );
$bean->dt = $dt;
}
/**
* Tests R::getInsertID convenience method.
*
* @return void
*/
public function testGetInsertID()
{
R::nuke();
$id = R::store( R::dispense( 'book' ) );
$id2 = R::getInsertID();
asrt( $id, $id2 );
}
/**
* Test numbers.
*
* @return void
*/
public function testNumbers()
{
asrt( setget( "-1" ), "-1" );
asrt( setget( -1 ), "-1" );
asrt( setget( "-0.25" ), "-0.25" );
asrt( setget( -0.25 ), "-0.25" );
asrt( setget( "1.0" ), "1" );
asrt( setget( 1.0 ), "1" );
asrt( setget( "3.20" ), "3.20" );
asrt( setget( "13.20" ), "13.20" );
asrt( setget( "134.20" ), "134.20" );
asrt( setget( 3.21 ), '3.21' );
asrt( setget( "0.12345678" ), "0.12345678" );
asrt( setget( 0.12345678 ), "0.12345678" );
asrt( setget( "-0.12345678" ), "-0.12345678" );
asrt( setget( -0.12345678 ), "-0.12345678" );
asrt( setget( "2147483647" ), "2147483647" );
asrt( setget( 2147483647 ), "2147483647" );
asrt( setget( -2147483647 ), "-2147483647" );
asrt( setget( "-2147483647" ), "-2147483647" );
asrt( setget( -4294967295 ), "-4294967295" );
asrt( setget( "-4294967295" ), "-4294967295" );
asrt( setget( 4294967295 ), "4294967295" );
asrt( setget( "4294967295" ), "4294967295" );
asrt( setget( "2147483648" ), "2147483648" );
asrt( setget( "-2147483648" ), "-2147483648" );
asrt( setget( "199936710040730" ), "199936710040730" );
asrt( setget( "-199936710040730" ), "-199936710040730" );
//Architecture dependent... only test this if you are sure what arch
//asrt(setget("2147483647123456"),"2.14748364712346e+15");
//asrt(setget(2147483647123456),"2.14748364712e+15");
}
/**
* Test dates.
*
* @return void
*/
public function testDates()
{
asrt( setget( "2010-10-11" ), "2010-10-11" );
asrt( setget( "2010-10-11 12:10" ), "2010-10-11 12:10" );
asrt( setget( "2010-10-11 12:10:11" ), "2010-10-11 12:10:11" );
asrt( setget( "x2010-10-11 12:10:11" ), "x2010-10-11 12:10:11" );
}
/**
* Test strings.
*
* @return void
*/
public function testStrings()
{
asrt( setget( "a" ), "a" );
asrt( setget( "." ), "." );
asrt( setget( "\"" ), "\"" );
asrt( setget( "just some text" ), "just some text" );
}
/**
* Test booleans.
*
* @return void
*/
public function testBool()
{
asrt( setget( TRUE ), "1" );
asrt( setget( FALSE ), "0" );
asrt( setget( "TRUE" ), "TRUE" );
asrt( setget( "FALSE" ), "FALSE" );
}
/**
* Test NULL.
*
* @return void
*/
public function testNull()
{
asrt( setget( "NULL" ), "NULL" );
asrt( setget( "NULL" ), "NULL" );
asrt( setget( "0123" ), "0123" );
asrt( setget( "0000123" ), "0000123" );
asrt( setget( NULL ), NULL );
asrt( ( setget( 0 ) == 0 ), TRUE );
asrt( ( setget( 1 ) == 1 ), TRUE );
asrt( ( setget( TRUE ) == TRUE ), TRUE );
asrt( ( setget( FALSE ) == FALSE ), TRUE );
}
}

View File

@@ -0,0 +1,291 @@
<?php
namespace RedUNIT\Mysql;
use RedUNIT\Mysql as Mysql;
use RedBeanPHP\Facade as R;
use RedBeanPHP\BeanHelper\SimpleFacadeBeanHelper as SimpleFacadeBeanHelper;
use RedBeanPHP\OODB as OODB;
use RedBeanPHP\OODBBean as OODBBean;
use RedBeanPHP\ToolBox as ToolBox;
/**
* UUID
*
* Tests whether we can use UUIDs with MySQL/MariaDB, to this
* end we use a reference implementation of a UUID MySQL Writer:
* UUIDWriterMySQL, however this class is not part of the code base,
* it should be considered a reference or example implementation.
* These tests focus on whether UUIDs in general do not cause any
* unexpected issues.
*
* @file RedUNIT/Mysql/Uuid.php
* @desc Tests read support for UUID tables.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Uuid extends Mysql
{
/**
* Test Read-support.
*
* @return void
*/
public function testUUIDReadSupport()
{
R::nuke();
$createPageTableSQL = '
CREATE TABLE
`page`
(
id CHAR( 40 ),
book_id CHAR( 40 ),
magazine_id CHAR( 40 ),
title VARCHAR(255),
PRIMARY KEY ( id )
)
ENGINE = InnoDB DEFAULT
CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci ';
$createBookTableSQL = '
CREATE TABLE
`book`
(
id CHAR( 40 ),
title VARCHAR(255),
PRIMARY KEY ( id )
)
ENGINE = InnoDB DEFAULT
CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci ';
$createPagePageTableSQL = '
CREATE TABLE
`page_page`
(
id CHAR( 40 ),
page_id CHAR( 40 ),
page2_id CHAR( 40 ),
PRIMARY KEY ( id )
)
ENGINE = InnoDB DEFAULT
CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci ';
R::exec( $createBookTableSQL );
R::exec( $createPageTableSQL );
R::exec( $createPagePageTableSQL );
//insert some records
$book1ID = '6ccd780c-baba-1026-9564-0040f4311e21';
$book2ID = '6ccd780c-baba-1026-9564-0040f4311e22';
$page1ID = '6ccd780c-baba-1026-9564-0040f4311e23';
$page2ID = '6ccd780c-baba-1026-9564-0040f4311e24';
$page3ID = '6ccd780c-baba-1026-9564-0040f4311e25';
$pagePage1ID = '6ccd780c-baba-1026-9564-0040f4311e26';
$insertBook1SQL = "
INSERT INTO book (id, title) VALUES( '$book1ID', 'book 1' );
";
$insertBook2SQL = "
INSERT INTO book (id, title) VALUES( '$book2ID', 'book 2' );
";
$insertPage1SQL = "
INSERT INTO page (id, book_id, title, magazine_id) VALUES( '$page1ID', '$book1ID', 'page 1 of book 1', '$book2ID' );
";
$insertPage2SQL = "
INSERT INTO page (id, book_id, title) VALUES( '$page2ID', '$book1ID', 'page 2 of book 1' );
";
$insertPage3SQL = "
INSERT INTO page (id, book_id, title) VALUES( '$page3ID', '$book2ID', 'page 1 of book 2' );
";
$insertPagePage1SQL = "
INSERT INTO page_page (id, page_id, page2_id) VALUES( '$pagePage1ID', '$page2ID', '$page3ID' );
";
R::exec( $insertBook1SQL );
R::exec( $insertBook2SQL );
R::exec( $insertPage1SQL );
R::exec( $insertPage2SQL );
R::exec( $insertPage3SQL );
R::exec( $insertPagePage1SQL );
//basic tour of basic functions....
$book1 = R::load( 'book', $book1ID );
asrt( $book1->id, $book1ID );
asrt( $book1->title, 'book 1' );
$book2 = R::load( 'book', $book2ID );
asrt( $book2->id, $book2ID );
asrt( $book2->title, 'book 2' );
asrt( count( $book1->ownPage ), 2 );
asrt( count( $book1->fresh()->with( 'LIMIT 1' )->ownPage ), 1 );
asrt( count( $book1->fresh()->withCondition( ' title = ? ', array('page 2 of book 1'))->ownPage ), 1 );
asrt( count($book2->ownPage), 1 );
asrt( $book2->fresh()->countOwn( 'page' ), 1 );
$page1 = R::load( 'page', $page1ID );
asrt( count( $page1->sharedPage ), 0 );
asrt( $page1->fetchAs( 'book' )->magazine->id, $book2ID );
$page2 = R::load( 'page', $page2ID );
asrt( count($page2->sharedPage), 1 );
asrt( $page2->fresh()->countShared( 'page' ), 1 );
$page3 = R::findOne( 'page', ' title = ? ', array( 'page 1 of book 2' ) );
asrt( $page3->id, $page3ID );
asrt( $page3->book->id, $book2ID );
}
/**
* Test Full fluid UUID support.
*
* @return void
*/
public function testFullSupport()
{
R::nuke();
//Rewire objects to support UUIDs.
$oldToolBox = R::getToolBox();
$oldAdapter = $oldToolBox->getDatabaseAdapter();
$uuidWriter = new \UUIDWriterMySQL( $oldAdapter );
$newRedBean = new OODB( $uuidWriter );
$newToolBox = new ToolBox( $newRedBean, $oldAdapter, $uuidWriter );
R::configureFacadeWithToolbox( $newToolBox );
list( $mansion, $rooms, $ghosts, $key ) = R::dispenseAll( 'mansion,room*3,ghost*4,key' );
$mansion->name = 'Haunted Mansion';
$mansion->xownRoomList = $rooms;
$rooms[0]->name = 'Green Room';
$rooms[1]->name = 'Red Room';
$rooms[2]->name = 'Blue Room';
$ghosts[0]->name = 'zero';
$ghosts[1]->name = 'one';
$ghosts[2]->name = 'two';
$ghosts[3]->name = 'three';
$rooms[0]->sharedGhostList = array( $ghosts[0], $ghosts[1] );
$rooms[1]->sharedGhostList = array( $ghosts[0], $ghosts[2] );
$rooms[2]->sharedGhostList = array( $ghosts[1], $ghosts[3], $ghosts[2] );
$rooms[2]->xownKey = array( $key );
//Can we store a bean hierachy with UUIDs?
$id = R::store( $mansion );
asrt( is_string( $id ), TRUE );
asrt( strlen( $id ), 36 );
$haunted = R::load( 'mansion', $id );
asrt( $haunted->name, 'Haunted Mansion' );
asrt( is_string( $haunted->id ), TRUE );
asrt( strlen( $haunted->id ), 36 );
asrt( is_array( $haunted->xownRoomList ), TRUE );
asrt( count( $haunted->ownRoom ), 3 );
$rooms = $haunted->xownRoomList;
//Do some counting...
$greenRoom = NULL;
foreach( $rooms as $room ) {
if ( $room->name === 'Green Room' ) {
$greenRoom = $room;
break;
}
}
asrt( !is_null( $greenRoom ), TRUE );
asrt( is_array( $greenRoom->with(' ORDER BY id ')->sharedGhostList ), TRUE );
asrt( count( $greenRoom->sharedGhostList ), 2 );
$names = array();
foreach( $greenRoom->sharedGhost as $ghost ) $names[] = $ghost->name;
sort($names);
$names = implode(',', $names);
asrt($names, 'one,zero');
$rooms = $haunted->xownRoomList;
$blueRoom = NULL;
foreach( $rooms as $room ) {
if ( $room->name === 'Blue Room' ) {
$blueRoom = $room;
break;
}
}
asrt( !is_null( $blueRoom ), TRUE );
asrt( is_array( $blueRoom->sharedGhostList ), TRUE );
asrt( count( $blueRoom->sharedGhostList ), 3 );
$names = array();
foreach( $blueRoom->sharedGhost as $ghost ) $names[] = $ghost->name;
sort($names);
$names = implode(',', $names);
asrt($names, 'one,three,two');
$rooms = $haunted->xownRoomList;
$redRoom = NULL;
foreach( $rooms as $room ) {
if ( $room->name === 'Red Room' ) {
$redRoom = $room; break;
}
}
$names = array();
foreach( $redRoom->sharedGhost as $ghost ) $names[] = $ghost->name;
sort($names);
$names = implode(',', $names);
asrt($names, 'two,zero');
asrt( !is_null( $redRoom ), TRUE );
asrt( is_array( $redRoom->sharedGhostList ), TRUE );
asrt( count( $redRoom->sharedGhostList ), 2 );
//Can we repaint a room?
$redRoom->name = 'Yellow Room';
$id = R::store($redRoom);
$yellowRoom = R::load( 'room', $id );
asrt( $yellowRoom->name, 'Yellow Room');
asrt( !is_null( $yellowRoom ), TRUE );
asrt( is_array( $yellowRoom->sharedGhostList ), TRUE );
asrt( count( $yellowRoom->sharedGhostList ), 2 );
//Can we throw one ghost out?
array_pop( $yellowRoom->sharedGhost );
R::store( $yellowRoom );
$yellowRoom = $yellowRoom->fresh();
asrt( $yellowRoom->name, 'Yellow Room');
asrt( !is_null( $yellowRoom ), TRUE );
asrt( is_array( $yellowRoom->sharedGhostList ), TRUE );
asrt( count( $yellowRoom->sharedGhostList ), 1 );
//can we remove one of the rooms?
asrt( R::count('key'), 1);
$list = $mansion->withCondition(' `name` = ? ', array('Blue Room'))->xownRoomList;
$room = reset($list);
unset($mansion->xownRoomList[$room->id]);
R::store($mansion);
asrt(R::count('room'), 2);
//and what about its dependent beans?
asrt(R::count('key'), 0);
asrt(R::count('ghost_room'), 3);
//and can we find ghosts?
$ghosts = R::find('ghost');
asrt(count($ghosts), 4);
$ghosts = R::findAll('ghost', 'ORDER BY id');
asrt(count($ghosts), 4);
$ghosts = R::findAll('ghost', 'ORDER BY id LIMIT 2');
asrt(count($ghosts), 2);
$ghostZero = R::findOne('ghost', ' `name` = ? ', array( 'zero' ) );
asrt( ($ghostZero instanceof OODBBean), TRUE );
//can we create link properties on existing tables?
$blackRoom = R::dispense( 'room' );
$blackRoom->name = 'Black Room';
$ghostZero->link('ghost_room', array('mood'=>'grumpy'))->room = $blackRoom;
R::store($ghostZero);
$ghostZero = $ghostZero->fresh();
$list = $ghostZero->sharedRoomList;
asrt(count($list), 3);
$ghostZero = $ghostZero->fresh();
$list = $ghostZero->withCondition(' ghost_room.mood = ? ', array('grumpy'))->sharedRoomList;
asrt(count($list), 1);
//can we load a batch?
$ids = R::getCol('SELECT id FROM ghost');
$ghosts = R::batch('ghost', $ids);
asrt(count($ghosts), 4);
//can we do an aggregation?
$ghosts = $greenRoom->aggr('ownGhostRoom', 'ghost', 'ghost');
asrt(count($ghosts), 2);
//can we duplicate the mansion?
asrt(R::count('mansion'), 1);
asrt(R::count('room'), 3);
asrt(R::count('ghost'), 4);
$copy = R::dup($mansion);
R::store($copy);
asrt(R::count('mansion'), 2);
asrt(R::count('room'), 5); //black room does not belong to mansion 1
asrt(R::count('ghost'), 4);
//can we do some counting using the list?
asrt( $copy->countOwn('room'), 2);
$rooms = $copy->withCondition(' `name` = ? ', array('Green Room'))->xownRoomList;
$room = reset($rooms);
asrt($room->countShared('ghost'), 2);
//Finally restore old toolbox
R::configureFacadeWithToolbox( $oldToolBox );
}
}

View File

@@ -0,0 +1,744 @@
<?php
namespace RedUNIT\Mysql;
use RedBeanPHP\Facade as R;
use RedBeanPHP\AssociationManager as AssociationManager;
use RedBeanPHP\QueryWriter as QueryWriter;
use RedBeanPHP\QueryWriter\MySQL as MySQL;
use RedBeanPHP\QueryWriter\AQueryWriter as AQueryWriter;
use RedBeanPHP\RedException\SQL as SQL;
use RedBeanPHP\RedException as RedException;
/**
* Writer
*
* Tests for MySQL and MariaDB Query Writer.
* This test class contains Query Writer specific tests.
* Use this class to add tests to test Query Writer specific
* behaviours, quirks and issues.
*
* @file RedUNIT/Mysql/Writer.php
* @desc A collection of database specific writer functions.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license New BSD/GPLv2
*
* (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the New BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Writer extends \RedUNIT\Mysql
{
/**
* Test whether optimizations do not have effect on Writer query outcomes.
*
* @return void
*/
public function testWriterSpeedUp()
{
R::nuke();
$id = R::store( R::dispense( 'book' ) );
$writer = R::getWriter();
$count1 = $writer->queryRecordCount( 'book', array( 'id' => $id ), ' id = :id ', array( ':id' => $id ) );
$count2 = $writer->queryRecordCount( 'book', array( ), ' id = :id ', array( ':id' => $id ) );
$count3 = $writer->queryRecordCount( 'book', NULL, ' id = :id ', array( ':id' => $id ) );
$count4 = $writer->queryRecordCount( 'book', array( 'id' => $id ) );
asrt( $count1, $count2 );
asrt( $count2, $count3 );
asrt( $count3, $count4 );
R::nuke();
$books = R::dispenseAll( 'book*4' );
$ids = R::storeAll( $books[0] );
$writer->deleteRecord( 'book', array( 'id' => $ids[0] ) );
$writer->deleteRecord( 'book', array( 'id' => $ids[1] ), ' id = :id ', array( ':id' => $ids[1] ) );
$writer->deleteRecord( 'book', NULL, ' id = :id ', array( ':id' => $ids[2] ) );
$writer->deleteRecord( 'book', array(), ' id = :id ', array( ':id' => $ids[3] ) );
asrt( R::count( 'book' ), 0 );
R::nuke();
$id = R::store( R::dispense( 'book' ) );
$record = $writer->queryRecord( 'book', array( 'id' => $id ) );
asrt( is_array( $record ), TRUE );
asrt( is_array( $record[0] ), TRUE );
asrt( isset( $record[0]['id'] ), TRUE );
asrt( (int) $record[0]['id'], $id );
$record = $writer->queryRecord( 'book', array( 'id' => $id ), ' id = :id ', array( ':id' => $id ) );
asrt( is_array( $record ), TRUE );
asrt( is_array( $record[0] ), TRUE );
asrt( isset( $record[0]['id'] ), TRUE );
asrt( (int) $record[0]['id'], $id );
$record = $writer->queryRecord( 'book', NULL, ' id = :id ', array( ':id' => $id ) );
asrt( is_array( $record ), TRUE );
asrt( is_array( $record[0] ), TRUE );
asrt( isset( $record[0]['id'] ), TRUE );
asrt( (int) $record[0]['id'], $id );
$record = $writer->queryRecord( 'book', array(), ' id = :id ', array( ':id' => $id ) );
asrt( is_array( $record ), TRUE );
asrt( is_array( $record[0] ), TRUE );
asrt( isset( $record[0]['id'] ), TRUE );
asrt( (int) $record[0]['id'], $id );
}
/**
* Tests wheter we can write a deletion query
* for MySQL using NO conditions but only an
* additional SQL snippet.
*
* @return void
*/
public function testWriteDeleteQuery()
{
$queryWriter = R::getWriter();
asrt( ( $queryWriter instanceof MySQL ), TRUE );
R::nuke();
$bean = R::dispense( 'bean' );
$bean->name = 'a';
$id = R::store( $bean );
asrt( R::count( 'bean' ), 1 );
$queryWriter->deleteRecord( 'bean', array(), $addSql = ' id = :id ', $bindings = array( ':id' => $id ) );
asrt( R::count( 'bean' ), 0 );
}
/**
* Tests wheter we can write a counting query
* for MySQL using conditions and an additional SQL snippet.
*
* @return void
*/
public function testWriteCountQuery()
{
$queryWriter = R::getWriter();
asrt( ( $queryWriter instanceof MySQL ), TRUE );
R::nuke();
$bean = R::dispense( 'bean' );
$bean->name = 'a';
R::store( $bean );
$bean = R::dispense( 'bean' );
$bean->name = 'b';
R::store( $bean );
$bean = R::dispense( 'bean' );
$bean->name = 'b';
R::store( $bean );
$count = $queryWriter->queryRecordCount( 'bean', array( 'name' => 'b' ), $addSql = ' id > :id ', $bindings = array( ':id' => 0 ) );
asrt( $count, 2 );
}
/**
* Tests whether we can write a MySQL join and
* whether the correct exception is thrown in case
* of an invalid join.
*
* @return void
*/
public function testWriteJoinSnippets()
{
$queryWriter = R::getWriter();
asrt( ( $queryWriter instanceof MySQL ), TRUE );
$snippet = $queryWriter->writeJoin( 'book', 'page' ); //default must be LEFT
asrt( is_string( $snippet ), TRUE );
asrt( ( strlen( $snippet ) > 0 ), TRUE );
asrt( ' LEFT JOIN `page` ON `page`.id = `book`.page_id ', $snippet );
$snippet = $queryWriter->writeJoin( 'book', 'page', 'LEFT' );
asrt( is_string( $snippet ), TRUE );
asrt( ( strlen( $snippet ) > 0 ), TRUE );
asrt( ' LEFT JOIN `page` ON `page`.id = `book`.page_id ', $snippet );
$snippet = $queryWriter->writeJoin( 'book', 'page', 'RIGHT' );
asrt( is_string( $snippet ), TRUE );
asrt( ( strlen( $snippet ) > 0 ), TRUE );
asrt( ' RIGHT JOIN `page` ON `page`.id = `book`.page_id ', $snippet );
$snippet = $queryWriter->writeJoin( 'book', 'page', 'INNER' );
asrt( ' INNER JOIN `page` ON `page`.id = `book`.page_id ', $snippet );
$exception = NULL;
try {
$snippet = $queryWriter->writeJoin( 'book', 'page', 'MIDDLE' );
}
catch(\Exception $e) {
$exception = $e;
}
asrt( ( $exception instanceof RedException ), TRUE );
$errorMessage = $exception->getMessage();
asrt( is_string( $errorMessage ), TRUE );
asrt( ( strlen( $errorMessage ) > 0 ), TRUE );
asrt( $errorMessage, 'Invalid JOIN.' );
}
/**
* Test whether we can store JSON as a JSON column
* and whether this plays well with the other data types.
*/
public function testSetGetJSON()
{
/* a stub test in case full test cannot be performed, see below */
R::useJSONFeatures( TRUE );
asrt( R::getWriter()->scanType( '[1,2,3]', TRUE ), MySQL::C_DATATYPE_SPECIAL_JSON );
R::useJSONFeatures( FALSE );
global $travis;
if ($travis) return;
/* does not work on MariaDB */
$version = strtolower( R::getCell('select version()') );
if ( strpos( $version, 'mariadb' ) !== FALSE ) return;
// Check if database platform is MariaDB < 10.2
$selectVersion = R::getDatabaseAdapter()->getCol( 'SELECT VERSION()' );
list ( $version, $dbPlatform ) = explode( '-', reset ( $selectVersion ) );
list( $versionMajor, $versionMinor, $versionPatch ) = explode( '.', $version );
if ( $dbPlatform == "MariaDB" && $versionMajor <= 10 && $versionMinor < 2 ) {
// No support for JSON columns, abort test
return;
}
R::nuke();
$bean = R::dispense('bean');
$message = json_encode( array( 'message' => 'hello', 'type' => 'greeting' ) );
$bean->data = $message;
R::store( $bean );
$columns = R::inspect('bean');
asrt( array_key_exists( 'data', $columns ), TRUE );
asrt( ( $columns['data'] !== 'json' ), TRUE );
R::useJSONFeatures( TRUE );
R::nuke();
$bean = R::dispense('bean');
$message = array( 'message' => 'hello', 'type' => 'greeting' );
$bean->data = $message;
R::store( $bean );
$columns = R::inspect('bean');
asrt( array_key_exists( 'data', $columns ), TRUE );
asrt( $columns['data'], 'json' );
$bean = $bean->fresh();
$message = json_decode( $bean->data, TRUE );
asrt( $message['message'], 'hello' );
asrt( $message['type'], 'greeting' );
$message['message'] = 'hi';
$bean->data = $message;
R::store( $bean );
pass();
$bean = R::findOne( 'bean' );
$message = json_decode( $bean->data );
asrt( $message->message, 'hi' );
$book = R::dispense( 'book' );
$book->page = 'lorem ipsum';
R::store( $book );
$book = $book->fresh();
asrt( $book->page, 'lorem ipsum' );
$book2 = R::dispense( 'book' );
$book2->page = array( 'chapter' => '1' );
R::store( $book2 );
pass(); //should not try to modify column and trigger exception
$book = $book->fresh();
asrt( $book->page, 'lorem ipsum' );
$columns = R::inspect('book');
asrt( ( $columns['page'] !== 'json' ), TRUE );
$building = R::dispense( 'building' );
$building->year = 'MLXXVIII';
R::store( $building );
$shop = R::dispense( 'building' );
$shop->year = '2010-01-01';
R::store( $shop );
$building = R::load( 'building', $building->id );
asrt( $building->year, 'MLXXVIII' );
$columns = R::inspect( 'building' );
asrt( strpos( strtolower( $columns['year'] ), 'date' ), FALSE );
$shop->anno = '2010-01-01';
R::store( $shop );
$columns = R::inspect( 'building' );
asrt( $columns['anno'], 'date' );
R::useJSONFeatures( FALSE );
}
/**
* Test Facade bind function method.
* Test for MySQL WKT spatial format.
*/
public function testFunctionFilters()
{
R::nuke();
R::bindFunc( 'read', 'location.point', 'asText' );
R::bindFunc( 'write', 'location.point', 'GeomFromText' );
R::store(R::dispense('location'));
R::freeze( TRUE );
try {
R::find('location');
fail();
} catch( SQL $exception ) {
pass();
}
R::freeze( FALSE );
try {
R::find('location');
pass();
} catch( SQL $exception ) {
fail();
}
$location = R::dispense( 'location' );
$location->point = 'POINT(14 6)';
R::store($location);
$columns = R::inspect( 'location' );
asrt( $columns['point'], 'point' );
$location = $location->fresh();
asrt( $location->point, 'POINT(14 6)' );
R::nuke();
$location = R::dispense( 'location' );
$location->point = 'LINESTRING(0 0,1 1,2 2)';
R::store($location);
$columns = R::inspect( 'location' );
asrt( $columns['point'], 'linestring' );
$location->bustcache = 2;
R::store($location);
$location = $location->fresh();
asrt( $location->point, 'LINESTRING(0 0,1 1,2 2)' );
R::nuke();
$location = R::dispense( 'location' );
$location->point = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7,5 5))';
R::store($location);
$columns = R::inspect( 'location' );
asrt( $columns['point'], 'polygon' );
$location->bustcache = 4;
R::store($location);
$location = $location->fresh();
asrt( $location->point, 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7,5 5))' );
R::bindFunc( 'read', 'location.point', NULL );
$location->bustcache = 1;
R::store($location);
$location = $location->fresh();
asrt( ( $location->point === 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7,5 5))' ), FALSE );
$filters = AQueryWriter::getSQLFilters();
asrt( is_array( $filters ), TRUE );
asrt( count( $filters ), 2 );
asrt( isset( $filters[ QueryWriter::C_SQLFILTER_READ] ), TRUE );
asrt( isset( $filters[ QueryWriter::C_SQLFILTER_WRITE] ), TRUE );
R::bindFunc( 'read', 'place.point', 'asText' );
R::bindFunc( 'write', 'place.point', 'GeomFromText' );
R::bindFunc( 'read', 'place.line', 'asText' );
R::bindFunc( 'write', 'place.line', 'GeomFromText' );
R::nuke();
$place = R::dispense( 'place' );
$place->point = 'POINT(13.2 666.6)';
$place->line = 'LINESTRING(9.2 0,3 1.33)';
R::store( $place );
$columns = R::inspect( 'place' );
asrt( $columns['point'], 'point' );
asrt( $columns['line'], 'linestring' );
$place = R::findOne('place');
asrt( $place->point, 'POINT(13.2 666.6)' );
asrt( $place->line, 'LINESTRING(9.2 0,3 1.33)' );
R::bindFunc( 'read', 'place.point', NULL );
R::bindFunc( 'write', 'place.point', NULL );
R::bindFunc( 'read', 'place.line', NULL );
R::bindFunc( 'write', 'place.line', NULL );
}
/**
* Test scanning and coding of values.
*
* @return void
*/
public function testScanningAndCoding()
{
$toolbox = R::getToolBox();
$adapter = $toolbox->getDatabaseAdapter();
$writer = $toolbox->getWriter();
$redbean = $toolbox->getRedBean();
$pdo = $adapter->getDatabase();
$a = new AssociationManager( $toolbox );
$adapter->exec( "DROP TABLE IF EXISTS testtable" );
asrt( in_array( "testtable", $adapter->getCol( "show tables" ) ), FALSE );
$writer->createTable( "testtable" );
asrt( in_array( "testtable", $adapter->getCol( "show tables" ) ), TRUE );
asrt( count( array_diff( $writer->getTables(), $adapter->getCol( "show tables" ) ) ), 0 );
asrt( count( array_keys( $writer->getColumns( "testtable" ) ) ), 1 );
asrt( in_array( "id", array_keys( $writer->getColumns( "testtable" ) ) ), TRUE );
asrt( in_array( "c1", array_keys( $writer->getColumns( "testtable" ) ) ), FALSE );
$writer->addColumn( "testtable", "c1", MySQL::C_DATATYPE_UINT32 );
asrt( count( array_keys( $writer->getColumns( "testtable" ) ) ), 2 );
asrt( in_array( "c1", array_keys( $writer->getColumns( "testtable" ) ) ), TRUE );
foreach ( $writer->sqltype_typeno as $key => $type ) {
if ( $type < 100 ) {
asrt( $writer->code( $key, TRUE ), $type );
} else {
asrt( $writer->code( $key, TRUE ), MySQL::C_DATATYPE_SPECIFIED );
}
}
asrt( $writer->code( MySQL::C_DATATYPE_SPECIAL_DATETIME ), MySQL::C_DATATYPE_SPECIFIED );
asrt( $writer->code( "unknown" ), MySQL::C_DATATYPE_SPECIFIED );
asrt( $writer->scanType( FALSE ), MySQL::C_DATATYPE_BOOL );
asrt( $writer->scanType( TRUE ), MySQL::C_DATATYPE_BOOL );
asrt( $writer->scanType( 0 ), MySQL::C_DATATYPE_BOOL );
asrt( $writer->scanType( 1 ), MySQL::C_DATATYPE_BOOL );
asrt( $writer->scanType( INF ), MySQL::C_DATATYPE_TEXT7 );
asrt( $writer->scanType( NULL ), MySQL::C_DATATYPE_BOOL );
asrt( $writer->scanType( 2 ), MySQL::C_DATATYPE_UINT32 );
asrt( $writer->scanType( 255 ), MySQL::C_DATATYPE_UINT32 ); //no more uint8
asrt( $writer->scanType( 256 ), MySQL::C_DATATYPE_UINT32 );
asrt( $writer->scanType( -1 ), MySQL::C_DATATYPE_DOUBLE );
asrt( $writer->scanType( 1.5 ), MySQL::C_DATATYPE_DOUBLE );
asrt( $writer->scanType( "abc" ), MySQL::C_DATATYPE_TEXT7 );
asrt( $writer->scanType( str_repeat( 'abcd', 100000 ) ), MySQL::C_DATATYPE_TEXT32 );
asrt( $writer->scanType( "2001-10-10", TRUE ), MySQL::C_DATATYPE_SPECIAL_DATE );
asrt( $writer->scanType( "2001-10-10 10:00:00", TRUE ), MySQL::C_DATATYPE_SPECIAL_DATETIME );
asrt( $writer->scanType( "2001-10-10" ), MySQL::C_DATATYPE_TEXT7 );
asrt( $writer->scanType( "2001-10-10 10:00:00" ), MySQL::C_DATATYPE_TEXT7 );
asrt( $writer->scanType( "1.23", TRUE ), MySQL::C_DATATYPE_SPECIAL_MONEY );
asrt( $writer->scanType( "12.23", TRUE ), MySQL::C_DATATYPE_SPECIAL_MONEY );
asrt( $writer->scanType( "124.23", TRUE ), MySQL::C_DATATYPE_SPECIAL_MONEY );
asrt( $writer->scanType( str_repeat( "lorem ipsum", 100 ) ), MySQL::C_DATATYPE_TEXT16 );
$writer->widenColumn( "testtable", "c1", MySQL::C_DATATYPE_UINT32 );
$writer->addColumn( "testtable", "special", MySQL::C_DATATYPE_SPECIAL_DATE );
$cols = $writer->getColumns( "testtable" );
asrt( $writer->code( $cols['special'], TRUE ), MySQL::C_DATATYPE_SPECIAL_DATE );
asrt( $writer->code( $cols['special'], FALSE ), MySQL::C_DATATYPE_SPECIFIED );
$writer->addColumn( "testtable", "special2", MySQL::C_DATATYPE_SPECIAL_DATETIME );
$cols = $writer->getColumns( "testtable" );
asrt( $writer->code( $cols['special2'], TRUE ), MySQL::C_DATATYPE_SPECIAL_DATETIME );
asrt( $writer->code( $cols['special'], FALSE ), MySQL::C_DATATYPE_SPECIFIED );
$cols = $writer->getColumns( "testtable" );
asrt( $writer->code( $cols["c1"] ), MySQL::C_DATATYPE_UINT32 );
$writer->widenColumn( "testtable", "c1", MySQL::C_DATATYPE_DOUBLE );
$cols = $writer->getColumns( "testtable" );
asrt( $writer->code( $cols["c1"] ), MySQL::C_DATATYPE_DOUBLE );
$writer->widenColumn( "testtable", "c1", MySQL::C_DATATYPE_TEXT7 );
$cols = $writer->getColumns( "testtable" );
asrt( $writer->code( $cols["c1"] ), MySQL::C_DATATYPE_TEXT7 );
$writer->widenColumn( "testtable", "c1", MySQL::C_DATATYPE_TEXT8 );
$cols = $writer->getColumns( "testtable" );
asrt( $writer->code( $cols["c1"] ), MySQL::C_DATATYPE_TEXT8 );
$id = $writer->updateRecord( "testtable", array( array( "property" => "c1", "value" => "lorem ipsum" ) ) );
$row = $writer->queryRecord( "testtable", array( "id" => array( $id ) ) );
asrt( $row[0]["c1"], "lorem ipsum" );
$writer->updateRecord( "testtable", array( array( "property" => "c1", "value" => "ipsum lorem" ) ), $id );
$row = $writer->queryRecord( "testtable", array( "id" => array( $id ) ) );
asrt( $row[0]["c1"], "ipsum lorem" );
$writer->deleteRecord( "testtable", array( "id" => array( $id ) ) );
$row = $writer->queryRecord( "testtable", array( "id" => array( $id ) ) );
asrt( empty( $row ), TRUE );
$writer->addColumn( "testtable", "c2", MySQL::C_DATATYPE_UINT32 );
}
/**
* (FALSE should be stored as 0 not as '')
*
* @return void
*/
public function testZeroIssue()
{
testpack( "Zero issue" );
$toolbox = R::getToolBox();
$redbean = $toolbox->getRedBean();
$adapter = $toolbox->getDatabaseAdapter();
$writer = $toolbox->getWriter();
$pdo = $adapter->getDatabase();
$pdo->Execute( "DROP TABLE IF EXISTS `zero`" );
$bean = $redbean->dispense( "zero" );
$bean->zero = FALSE;
$bean->title = "bla";
$redbean->store( $bean );
asrt( count( $redbean->find( "zero", array(), " zero = 0 " ) ), 1 );
R::store( R::dispense( 'hack' ) );
testpack( "Test RedBean Security - bean interface " );
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
$bean = $redbean->load( "page", "13; drop table hack" );
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
try {
$bean = $redbean->load( "page where 1; drop table hack", 1 );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
$bean = $redbean->dispense( "page" );
$evil = "; drop table hack";
$bean->id = $evil;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
unset( $bean->id );
$bean->name = "\"" . $evil;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
$bean->name = "'" . $evil;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
$bean->$evil = 1;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
unset( $bean->$evil );
$bean->id = 1;
$bean->name = "\"" . $evil;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
$bean->name = "'" . $evil;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
$bean->$evil = 1;
try {
$redbean->store( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
try {
$redbean->trash( $bean );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
try {
$redbean->find( "::", array(), "" );
} catch (\Exception $e ) {
pass();
}
$adapter->exec( "drop table if exists sometable" );
testpack( "Test RedBean Security - query writer" );
try {
$writer->createTable( "sometable` ( `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ; drop table hack; --" );
} catch (\Exception $e ) {
}
asrt( in_array( "hack", $adapter->getCol( "show tables" ) ), TRUE );
testpack( "Test ANSI92 issue in clearrelations" );
$pdo->Execute( "DROP TABLE IF EXISTS book_group" );
$pdo->Execute( "DROP TABLE IF EXISTS author_book" );
$pdo->Execute( "DROP TABLE IF EXISTS book" );
$pdo->Execute( "DROP TABLE IF EXISTS author" );
$redbean = $toolbox->getRedBean();
$a = new AssociationManager( $toolbox );
$book = $redbean->dispense( "book" );
$author1 = $redbean->dispense( "author" );
$author2 = $redbean->dispense( "author" );
$book->title = "My First Post";
$author1->name = "Derek";
$author2->name = "Whoever";
set1toNAssoc( $a, $book, $author1 );
set1toNAssoc( $a, $book, $author2 );
pass();
$pdo->Execute( "DROP TABLE IF EXISTS book_group" );
$pdo->Execute( "DROP TABLE IF EXISTS book_author" );
$pdo->Execute( "DROP TABLE IF EXISTS author_book" );
$pdo->Execute( "DROP TABLE IF EXISTS book" );
$pdo->Execute( "DROP TABLE IF EXISTS author" );
$redbean = $toolbox->getRedBean();
$a = new AssociationManager( $toolbox );
$book = $redbean->dispense( "book" );
$author1 = $redbean->dispense( "author" );
$author2 = $redbean->dispense( "author" );
$book->title = "My First Post";
$author1->name = "Derek";
$author2->name = "Whoever";
$a->associate( $book, $author1 );
$a->associate( $book, $author2 );
pass();
testpack( "Test Association Issue Group keyword (Issues 9 and 10)" );
$pdo->Execute( "DROP TABLE IF EXISTS `book_group`" );
$pdo->Execute( "DROP TABLE IF EXISTS `group`" );
$group = $redbean->dispense( "group" );
$group->name = "mygroup";
$redbean->store( $group );
try {
$a->associate( $group, $book );
pass();
} catch ( SQL $e ) {
fail();
}
// Test issue SQL error 23000
try {
$a->associate( $group, $book );
pass();
} catch ( SQL $e ) {
fail();
}
asrt( (int) $adapter->getCell( "select count(*) from book_group" ), 1 ); //just 1 rec!
$pdo->Execute( "DROP TABLE IF EXISTS book_group" );
$pdo->Execute( "DROP TABLE IF EXISTS author_book" );
$pdo->Execute( "DROP TABLE IF EXISTS book" );
$pdo->Execute( "DROP TABLE IF EXISTS author" );
$redbean = $toolbox->getRedBean();
$a = new AssociationManager( $toolbox );
$book = $redbean->dispense( "book" );
$author1 = $redbean->dispense( "author" );
$author2 = $redbean->dispense( "author" );
$book->title = "My First Post";
$author1->name = "Derek";
$author2->name = "Whoever";
$a->unassociate( $book, $author1 );
$a->unassociate( $book, $author2 );
pass();
$redbean->trash( $redbean->dispense( "bla" ) );
pass();
$bean = $redbean->dispense( "bla" );
$bean->name = 1;
$bean->id = 2;
$redbean->trash( $bean );
pass();
}
/**
* Test special data types.
*
* @return void
*/
public function testTypes()
{
testpack( 'Special data types' );
$bean = R::dispense( 'bean' );
$bean->date = 'someday';
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['date'], 'varchar(191)' );
$bean = R::dispense( 'bean' );
$bean->date = '2011-10-10';
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['date'], 'varchar(191)' );
}
/**
* Test date types.
*
* @return void
*/
public function testTypesDates()
{
$bean = R::dispense( 'bean' );
$bean->date = '2011-10-10';
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['date'], 'date' );
}
/**
* Test money types.
*
* @return void
*/
public function testTypesMon()
{
$bean = R::dispense( 'bean' );
$bean->amount = '22.99';
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['amount'], 'decimal(10,2)' );
R::nuke();
$bean = R::dispense( 'bean' );
$bean->amount = '-22.99';
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['amount'], 'decimal(10,2)' );
}
/**
* Date-time
*
* @return void
*/
public function testTypesDateTimes()
{
$bean = R::dispense( 'bean' );
$bean->date = '2011-10-10 10:00:00';
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['date'], 'datetime' );
$bean = R::dispense( 'bean' );
try {
$bean = R::dispense( 'bean' );
$bean->title = 123;
$bean->setMeta( 'cast.title', 'invalid' );
R::store( $bean );
fail();
} catch ( RedException $e ) {
pass();
} catch (\Exception $e ) {
fail();
}
$bean = R::dispense( 'bean' );
$bean->title = 123;
$bean->setMeta( 'cast.title', 'text' );
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['title'], 'text' );
R::nuke();
$bean = R::dispense( 'bean' );
$bean->title = 123;
$bean->setMeta( 'cast.title', 'string' );
R::store( $bean );
$cols = R::getColumns( 'bean' );
asrt( $cols['title'], 'varchar(191)' );
}
/**
* Stored and reloads spatial data to see if the
* value is preserved correctly.
*
* @return void
*/
protected function setGetSpatial( $data )
{
R::nuke();
$place = R::dispense( 'place' );
$place->location = $data;
R::store( $place );
asrt( R::getCell( 'SELECT AsText(location) FROM place LIMIT 1' ), $data );
}
/**
* Can we manually add a MySQL time column?
*
* @return void
*/
public function testTime()
{
R::nuke();
$clock = R::dispense('clock');
$clock->time = '10:00:00';
$clock->setMeta('cast.time', 'time');
R::store( $clock );
$columns = R::inspect('clock');
asrt( $columns['time'], 'time' );
$clock = R::findOne('clock');
$clock->time = '12';
R::store($clock);
$clock = R::findOne('clock');
$time = $clock->time;
asrt( ( strpos( $time, ':' ) > 0 ), TRUE );
}
/**
* Can we use the 'ignoreDisplayWidth'-feature for MySQL 8
* compatibility?
*
* @return void
*/
public function testWriterFeature()
{
$adapter = R::getToolBox()->getDatabaseAdapter();
$writer = new \RedBeanPHP\QueryWriter\MySQL( $adapter );
$writer->useFeature('ignoreDisplayWidth');
asrt($writer->typeno_sqltype[MySQL::C_DATATYPE_BOOL],' TINYINT UNSIGNED ');
asrt($writer->typeno_sqltype[MySQL::C_DATATYPE_UINT32],' INT UNSIGNED ');
asrt($writer->sqltype_typeno['tinyint unsigned'],MySQL::C_DATATYPE_BOOL);
asrt($writer->sqltype_typeno['int unsigned'],MySQL::C_DATATYPE_UINT32);
//Can we also pass invalid features without errors?
$writer->useFeature('nonsense');
pass();
}
/**
* Can we pass an options array to Writer Constructor?
*
* @return void
*/
public function testWriterOptions()
{
$adapter = R::getToolBox()->getDatabaseAdapter();
$writer = new \RedBeanPHP\QueryWriter\MySQL( $adapter, array('noInitcode'=>TRUE) );
pass();
}
}