Creates DBO-descendant objects from a given db connection configuration
Inheritance: extends DataSource
Exemplo n.º 1
0
 /**
  * testRealQueries method
  *
  * @access public
  * @return void
  */
 public function testRealQueries()
 {
     $this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag', 'Sample', 'ArticlesTag');
     $Apple = ClassRegistry::init('Apple');
     $Article = ClassRegistry::init('Article');
     $result = $this->Dbo->rawQuery('SELECT color, name FROM ' . $this->Dbo->fullTableName('apples'));
     $this->assertTrue(!empty($result));
     $result = $this->Dbo->fetchRow($result);
     $expected = array($this->Dbo->fullTableName('apples', false) => array('color' => 'Red 1', 'name' => 'Red Apple 1'));
     $this->assertEqual($expected, $result);
     $result = $this->Dbo->fetchAll('SELECT name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
     $expected = array(array($this->Dbo->fullTableName('apples', false) => array('name' => 'Red Apple 1')), array($this->Dbo->fullTableName('apples', false) => array('name' => 'Bright Red Apple')), array($this->Dbo->fullTableName('apples', false) => array('name' => 'green blue')), array($this->Dbo->fullTableName('apples', false) => array('name' => 'Test Name')), array($this->Dbo->fullTableName('apples', false) => array('name' => 'Blue Green')), array($this->Dbo->fullTableName('apples', false) => array('name' => 'My new apple')), array($this->Dbo->fullTableName('apples', false) => array('name' => 'Some odd color')));
     $this->assertEqual($expected, $result);
     $result = $this->Dbo->field($this->Dbo->fullTableName('apples', false), 'SELECT color, name FROM ' . $this->Dbo->fullTableName('apples') . ' ORDER BY id');
     $expected = array('color' => 'Red 1', 'name' => 'Red Apple 1');
     $this->assertEqual($expected, $result);
     $Apple->unbindModel(array(), false);
     $result = $this->Dbo->read($Apple, array('fields' => array($Apple->escapeField('name')), 'conditions' => null, 'recursive' => -1));
     $expected = array(array('Apple' => array('name' => 'Red Apple 1')), array('Apple' => array('name' => 'Bright Red Apple')), array('Apple' => array('name' => 'green blue')), array('Apple' => array('name' => 'Test Name')), array('Apple' => array('name' => 'Blue Green')), array('Apple' => array('name' => 'My new apple')), array('Apple' => array('name' => 'Some odd color')));
     $this->assertEqual($expected, $result);
     $result = $this->Dbo->read($Article, array('fields' => array('id', 'user_id', 'title'), 'conditions' => null, 'recursive' => 1));
     $this->assertTrue(Set::matches('/Article[id=1]', $result));
     $this->assertTrue(Set::matches('/Comment[id=1]', $result));
     $this->assertTrue(Set::matches('/Comment[id=2]', $result));
     $this->assertFalse(Set::matches('/Comment[id=10]', $result));
 }
Exemplo n.º 2
0
 /**
  * Test isConnected
  *
  * @return void
  */
 public function testIsConnected()
 {
     $this->Dbo->disconnect();
     $this->assertFalse($this->Dbo->isConnected(), 'Not connected now.');
     $this->Dbo->connect();
     $this->assertTrue($this->Dbo->isConnected(), 'Should be connected.');
 }
 /**
  * TestRenameField method
  *
  * @return void
  */
 public function testRenameField()
 {
     $this->loadFixtures('User', 'Post');
     $Model = new Model(array('table' => 'posts', 'ds' => 'test'));
     $Migration = new TestPrecheckCakeMigration(array('up' => array('rename_field' => array('posts' => array('updated' => 'renamed_updated'))), 'down' => array('rename_field' => array('posts' => array('renamed_updated' => 'updated'))), 'precheck' => 'Migrations.PrecheckCondition'));
     $Migration->initDb();
     $fields = $this->db->describe($Model);
     $this->assertTrue(isset($fields['updated']));
     $this->assertFalse(isset($fields['renamed_updated']));
     $this->assertTrue($Migration->Precheck->beforeAction($Migration, 'rename_field', array('table' => $this->db->fullTableName('posts', false, false), 'old_name' => 'updated', 'new_name' => 'renamed_updated')));
     $this->assertTrue($Migration->run('up'));
     $fields = $this->db->describe($Model);
     $this->assertFalse(isset($fields['updated']));
     $this->assertTrue(isset($fields['renamed_updated']));
     $this->assertFalse($Migration->Precheck->beforeAction($Migration, 'rename_field', array('table' => $this->db->fullTableName('posts', false, false), 'old_name' => 'updated', 'new_name' => 'renamed_updated')));
     $this->assertTrue($Migration->Precheck->beforeAction($Migration, 'rename_field', array('table' => $this->db->fullTableName('posts', false, false), 'old_name' => 'renamed_updated', 'new_name' => 'updated')));
     try {
         $Migration->run('up');
     } catch (MigrationException $e) {
         $this->fail('Exception triggered ' . $e->getMessage());
     }
     $this->assertTrue($Migration->run('down'));
     $fields = $this->db->describe($Model);
     $this->assertTrue(isset($fields['updated']));
     $this->assertFalse(isset($fields['renamed_updated']));
     $this->assertTrue($Migration->Precheck->beforeAction($Migration, 'rename_field', array('table' => $this->db->fullTableName('posts', false, false), 'old_name' => 'updated', 'new_name' => 'renamed_updated')));
     $this->assertFalse($Migration->Precheck->beforeAction($Migration, 'rename_field', array('table' => $this->db->fullTableName('posts', false, false), 'old_name' => 'renamed_updated', 'new_name' => 'updated')));
     try {
         $Migration->run('down');
     } catch (MigrationException $e) {
         $this->fail('Exception triggered ' . $e->getMessage());
     }
 }
Exemplo n.º 4
0
/**
 * test that describe does not corrupt UUID primary keys
 *
 * @return void
 */
	public function testDescribeWithUuidPrimaryKey() {
		$tableName = 'uuid_tests';
		$this->Dbo->query("CREATE TABLE {$tableName} (id VARCHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)");
		$Model = new Model(array('name' => 'UuidTest', 'ds' => 'test', 'table' => 'uuid_tests'));
		$result = $this->Dbo->describe($Model);
		$expected = array(
			'type' => 'string',
			'length' => 36,
			'null' => false,
			'default' => null,
			'key' => 'primary',
		);
		$this->assertEqual($result['id'], $expected);
		$this->Dbo->query('DROP TABLE ' . $tableName);

		$tableName = 'uuid_tests';
		$this->Dbo->query("CREATE TABLE {$tableName} (id CHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)");
		$Model = new Model(array('name' => 'UuidTest', 'ds' => 'test', 'table' => 'uuid_tests'));
		$result = $this->Dbo->describe($Model);
		$expected = array(
			'type' => 'string',
			'length' => 36,
			'null' => false,
			'default' => null,
			'key' => 'primary',
		);
		$this->assertEqual($result['id'], $expected);
		$this->Dbo->query('DROP TABLE ' . $tableName);
	}
Exemplo n.º 5
0
 /**
  * Test nested transaction
  *
  * @return void
  */
 public function testNestedTransaction()
 {
     $nested = $this->Dbo->useNestedTransactions;
     $this->Dbo->useNestedTransactions = true;
     if ($this->Dbo->nestedTransactionSupported() === false) {
         $this->Dbo->useNestedTransactions = $nested;
         $this->skipIf(true, 'The MySQL server do not support nested transaction');
     }
     $this->loadFixtures('Inno');
     $model = ClassRegistry::init('Inno');
     $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
     $model->cacheQueries = false;
     $this->Dbo->cacheMethods = false;
     $this->assertTrue($this->Dbo->begin());
     $this->assertNotEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->begin());
     $this->assertTrue($model->delete(1));
     $this->assertEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->rollback());
     $this->assertNotEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->begin());
     $this->assertTrue($model->delete(1));
     $this->assertEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->commit());
     $this->assertEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->rollback());
     $this->assertNotEmpty($model->read(null, 1));
     $this->Dbo->useNestedTransactions = $nested;
 }
 public function add()
 {
     //var_dump($this->request->data);
     $this->loadModel('User');
     $us = $this->User->find('all');
     //var_dump($us['0']);
     if (!empty($this->data)) {
         $this->loadModel('User');
         $this->User->create();
         //$this->request->data['User']['ip'] = $this->request->clientIp();
         $m = $this->request->data['User']['dob']['month'];
         $d = $this->request->data['User']['dob']['day'];
         $y = $this->request->data['User']['dob']['year'];
         $dob = $m . '-' . $d . '-' . $y;
         //$mem = $this->request->data['User']['member'];
         //var_dump($mem);
         $this->request->data['User']['dob'] = $dob;
         //$this->request->data['User']['mem'] = 'User';
         //$this->request->data['login_attempt']['login_times'] = 1;
         $this->request->data['User']['register_date'] = DboSource::expression('NOW()');
         if ($this->User->save($this->request->data)) {
             //echo "<div id='footer_a_link'>";
             $this->Session->setFlash('You are registered successfully. Please log in.');
             // $this->redirect(array('action' => 'login', 'controller' => 'Users'));
         } else {
             $this->Session->setFlash('Not Registered');
         }
     }
 }
 public function create_concert()
 {
     $this->loadModel('Taste');
     $load_taste = $this->Taste->find('all');
     $this->set(compact('load_taste', 'load_taste'));
     //var_dump($this->request->data);
     $this->loadModel('Band');
     $load_band = $this->Band->find('all');
     $this->set(compact('load_band', 'load_band'));
     $this->loadModel('Concert');
     //var_dump($this->request->data);
     if (!empty($this->data)) {
         $this->Concert->create();
         //$this->request->data['User']['ip'] = $this->request->clientIp();
         $this->request->data['Concert']['concert_name'] = $this->request->data['Concerts']['concert_name'];
         $this->request->data['Concert']['concert_place'] = $this->request->data['Concerts']['concert_place'];
         $this->request->data['Concert']['concert_time'] = $this->request->data['Concerts']['concert_time'];
         $this->request->data['Concert']['concert_ticket_price'] = $this->request->data['Concerts']['concert_ticket_price'];
         $this->request->data['Concert']['concert_band'] = $this->request->data['concert_band'] + 1;
         $this->request->data['Concert']['concert_taste'] = $this->request->data['concert_taste'] + 1;
         //$this->request->data['Concert']['band_name'] = $this->request->data['Bands']['band_name'];
         //$this->request->data['login_attempt']['login_times'] = 1;
         $this->request->data['Concert']['concert_creation_date'] = DboSource::expression('NOW()');
         if ($this->Concert->save($this->request->data)) {
             //echo "<div id='footer_a_link'>";
             $this->Session->setFlash('Concert has been registered successfully.');
             //$this->redirect(array('action' => 'index', 'controller' => 'Bands'));
         } else {
             $this->Session->setFlash('Not Registered');
         }
     }
 }
Exemplo n.º 8
0
 public function process()
 {
     $c = new CakeEmail('default');
     //grab 50 emails
     $emails = $this->EmailMessage->find("all", array("conditions" => array("EmailMessage.processed" => 0, "EmailMessage.to !=" => '', "NOT" => array("EmailMessage.to" => null)), "contain" => array()));
     $total_emails = count($emails);
     $this->out("emails to processes: " . $total_emails);
     SysMsg::add(array("category" => "Emailer", "from" => "MailerShell", "crontab" => 1, "title" => "Emails to processes: " . $total_emails));
     foreach ($emails as $email) {
         $e = $email['EmailMessage'];
         $c->reset();
         $c->config('default');
         $c->to($e['to']);
         $c->subject($e['subject']);
         $c->template($e['template']);
         $c->viewVars(array("msg" => $email));
         if ($c->send()) {
             $this->EmailMessage->create();
             $this->EmailMessage->id = $e['id'];
             $this->EmailMessage->save(array("processed" => 1, "sent_date" => DboSource::expression('NOW()')));
             $total_emails--;
             $this->out("Email:" . $e['to'] . " Template: " . $e['template']);
         } else {
             $this->out("Email failed: " . $e['id']);
             SysMsg::add(array("category" => "Emailer", "from" => "MailerShell", "crontab" => 1, "title" => "Email Failed: " . $e['id']));
         }
     }
 }
Exemplo n.º 9
0
 /**
  * Test that value() quotes set values even when numeric.
  *
  * @return void
  */
 public function testSetValue()
 {
     $column = "set('a','b','c')";
     $result = $this->Dbo->value('1', $column);
     $this->assertEquals("'1'", $result);
     $result = $this->Dbo->value(1, $column);
     $this->assertEquals("'1'", $result);
     $result = $this->Dbo->value('a', $column);
     $this->assertEquals("'a'", $result);
 }
Exemplo n.º 10
0
 /**
  * Test that fields are parsed out in a reasonable fashion.
  *
  * @return void
  */
 public function testFetchRowColumnParsing()
 {
     $this->loadFixtures('User');
     $sql = 'SELECT "User"."id", "User"."user", "User"."password", "User"."created", (1 + 1) AS "two" ' . 'FROM "users" AS "User" WHERE ' . '"User"."id" IN (SELECT MAX("id") FROM "users") ' . 'OR "User.id" IN (5, 6, 7, 8)';
     $result = $this->Dbo->fetchRow($sql);
     $expected = array('User' => array('id' => 4, 'user' => 'garrett', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:22:23'), 0 => array('two' => 2));
     $this->assertEquals($expected, $result);
     $sql = 'SELECT "User"."id", "User"."user" ' . 'FROM "users" AS "User" WHERE "User"."id" = 4 ' . 'UNION ' . 'SELECT "User"."id", "User"."user" ' . 'FROM "users" AS "User" WHERE "User"."id" = 3';
     $result = $this->Dbo->fetchRow($sql);
     $expected = array('User' => array('id' => 3, 'user' => 'larry'));
     $this->assertEquals($expected, $result);
 }
Exemplo n.º 11
0
 /**
  * Test deletes with a mock.
  *
  * @return void
  */
 public function testDeleteStatements()
 {
     $this->loadFixtures('Article', 'User');
     $test = ConnectionManager::getDatasource('test');
     $this->Dbo = $this->getMock('Mysql', array('execute'), array($test->config));
     $this->Dbo->expects($this->at(0))->method('execute')->with("DELETE  FROM `articles`  WHERE 1 = 1");
     $this->Dbo->expects($this->at(1))->method('execute')->with("DELETE `Article` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" . "  WHERE 1 = 1");
     $this->Dbo->expects($this->at(2))->method('execute')->with("DELETE `Article` FROM `articles` AS `Article` LEFT JOIN `users` AS `User` ON (`Article`.`user_id` = `User`.`id`)" . "  WHERE 2=2");
     $Article = new Article();
     $this->Dbo->delete($Article);
     $this->Dbo->delete($Article, true);
     $this->Dbo->delete($Article, '2=2');
 }
Exemplo n.º 12
0
 /**
  * Test parsing more complex field names.
  *
  * @return void
  */
 public function testFetchColumnRowParsingMoreComplex()
 {
     $this->loadFixtures('User');
     $sql = 'SELECT
   COUNT(*) AS User__count,
   COUNT(CASE id WHEN 2 THEN 1 ELSE NULL END) as User__case,
   AVG(CAST("User"."id" AS BIGINT)) AS User__bigint
   FROM "users" AS "User"
   WHERE "User"."id" > 0';
     $result = $this->Dbo->fetchRow($sql);
     $expected = array('0' => array('User__count' => '4', 'User__case' => '1', 'User__bigint' => '2.5'));
     $this->assertEquals($expected, $result);
 }
Exemplo n.º 13
0
 public function delete($id = null)
 {
     if (!$id) {
         $this->Session - setFlash('Tarea inv&aacute;lida');
         $this->redirect(array('action' => 'index', 'pendiente'), null, true);
     }
     $this->Tarea->id = $id;
     $this->request->data['Tarea']['estado'] = 1;
     $this->request->data['Tarea']['finalizado'] = DboSource::expression('NOW()');
     if ($this->Tarea->save($this->request->data)) {
         $this->Session->setFlash('Tarea #' . $id . ' Terminada');
         $this->redirect(array('action' => 'index', 'pendiente'), null, true);
     }
 }
Exemplo n.º 14
0
 public function beforeSave($options = array())
 {
     $key = $this->alias;
     $update_time = @DboSource::expression('NOW()');
     //update columns
     if (empty($this->id)) {
         if (empty($this->data[$key]['created'])) {
             $this->data[$key]['created'] = $update_time;
         }
     }
     if (empty($this->data[$key]['modified'])) {
         $this->data[$key]['modified'] = $update_time;
     }
     return true;
 }
Exemplo n.º 15
0
 function admin_add()
 {
     if (!empty($this->request->data) && $this->request->is('post')) {
         $this->User->create();
         $this->request->data['User']['user_added_date'] = @DboSource::expression('NOW()');
         $this->request->data['User']['password'] = md5($this->request->data['User']['password']);
         if ($this->User->save($this->request->data)) {
             $this->Session->setFlash(__('The user added successfully', true), 'default', array('class' => 'success'));
             $this->redirect(array('action' => 'index'));
         } else {
             $this->Session->setFlash(__('The user could not be saved. Please, try again.', true), 'default', array('class' => 'error'));
         }
     }
     $roles = $this->UserRole->find('all', array('conditions' => array('status' => 'Active'), 'order' => array('role_name' => 'asc')));
     $this->set('Roles', $roles);
 }
Exemplo n.º 16
0
 /**
  * SQL file header
  *
  * @param  $datasource
  * @return string
  */
 function _createSqlDumpHeader($datasource)
 {
     $sql = array();
     $sql[] = $this->hr(0);
     $sql[] = '-- ' . $this->message;
     $sql[] = '-- generated on: ' . date('Y-m-d H:i:s') . ' : ' . time();
     $sql[] = $this->hr(0);
     $sql[] = '';
     if (preg_match('/^mysql/i', $this->DataSource->config['driver'])) {
         $sql[] = 'use ' . $this->DataSource->name($this->DataSource->config['database']) . ';';
     }
     if (!empty($this->DataSource->config['encoding'])) {
         $sql[] = 'SET NAMES ' . $this->DataSource->value($this->DataSource->config['encoding']) . ';';
     }
     return $this->out($sql);
 }
Exemplo n.º 17
0
 public function admin_edit($id = null)
 {
     $this->Cmse->id = $id;
     if (!$this->Cmse->exists()) {
         throw new NotFoundException(__('Invalid Page'));
     }
     if ($this->request->is('post') || $this->request->is('put')) {
         $this->request->data['Cmse']['page_modified_date'] = DboSource::expression('now()');
         if ($this->Cmse->save($this->request->data)) {
             $this->Session->setFlash(__('The page has been saved'), 'default', array('class' => 'success'));
             $this->redirect(array('action' => 'index'));
         } else {
             $this->Session->setFlash(__('The page could not be saved. Please, try again.'), 'default', array('class' => 'error'));
         }
     } else {
         $this->request->data = $this->Cmse->read(null, $id);
     }
 }
 /**
  * Test truncate with a mock.
  *
  * @return void
  */
 public function testTruncateStatements()
 {
     $this->loadFixtures('Article', 'User');
     $db = ConnectionManager::getDatasource('test');
     $schema = $db->config['database'];
     $Article = new Article();
     $this->Dbo = $this->getMock('Mysql', array('execute'), array($db->config));
     $this->Dbo->expects($this->at(0))->method('execute')->with("TRUNCATE TABLE `{$schema}`.`articles`");
     $this->Dbo->truncate($Article);
     $this->Dbo->expects($this->at(0))->method('execute')->with("TRUNCATE TABLE `{$schema}`.`articles`");
     $this->Dbo->truncate('articles');
     // #2355: prevent duplicate prefix
     $this->Dbo->config['prefix'] = 'tbl_';
     $Article->tablePrefix = 'tbl_';
     $this->Dbo->expects($this->at(0))->method('execute')->with("TRUNCATE TABLE `{$schema}`.`tbl_articles`");
     $this->Dbo->truncate($Article);
     $this->Dbo->expects($this->at(0))->method('execute')->with("TRUNCATE TABLE `{$schema}`.`tbl_articles`");
     $this->Dbo->truncate('articles');
 }
Exemplo n.º 19
0
 /**
  * Use an old user as an admin.
  *
  * @return string
  */
 protected function _oldUser()
 {
     $user_id = trim($this->in('<question>User ID:</question>'));
     $userMap = Configure::read('Forum.userMap');
     if (!$user_id || !is_numeric($user_id)) {
         $user_id = $this->_oldUser();
     } else {
         $result = $this->db->fetchRow(sprintf("SELECT * FROM `%s` AS `User` WHERE `id` = %d LIMIT 1", $this->install['table'], $user_id));
         if (!$result) {
             $this->out('<error>User ID does not exist, please try again</error>');
             $user_id = $this->_oldUser();
         } else {
             $this->install['username'] = $result['User'][$userMap['username']];
             $this->install['password'] = $result['User'][$userMap['password']];
             $this->install['email'] = $result['User'][$userMap['email']];
         }
     }
     return $user_id;
 }
Exemplo n.º 20
0
 public function assignUserACoupon($forUser, $couponType = 1, $parameters = [])
 {
     $fields = ['presenter_id' => null, 'start_date' => date('Y-m-d H:i:s'), 'end_date' => '0000-00-00 00:00:00', 'max_redemptions' => '-1', 'discount_percentage' => 50, 'discount_flat' => '0.00', 'discount_sku' => null, 'reference_id' => null, 'user_visible' => true, 'expiration_date' => DboSource::expression('DATE_ADD(NOW(),INTERVAL 1 YEAR)')];
     $data = array_merge($fields, $parameters);
     $coupon = $this->CouponPresenter->getPresenterCoupon($data['presenter_id'], $couponType);
     if (empty($coupon)) {
         $success = $this->CouponPresenter->saveCreate(array("presenter_id" => $data['presenter_id'], "coupon_id" => $couponType, "start_date" => $data['start_date'], "end_date" => $data['end_date'], "max_redemptions" => $data['max_redemptions'], "discount_percentage" => $data['discount_percentage'], "discount_flat" => $data['discount_flat'], "discount_sku" => $data['discount_sku'], "expiration_date" => $data['expiration_date']));
         if ($success) {
             $coupon = $this->CouponPresenter->getPresenterCoupon($data['presenter_id'], $couponType);
         }
     }
     //Coupon should be assigned now
     if (!empty($coupon)) {
         $this->create();
         $return = $this->save(array("coupon_presenter_id" => $coupon['CouponPresenter']['id'], "user_id" => $forUser, "reference_id" => $data['reference_id'], "user_visible" => $data['user_visible'], "date_added" => date('Y-m-d H:i:s'), "redemption_reference_id" => '', "redemption_amount" => '0.00', "expiration_date" => $data['expiration_date']));
     } else {
         $return = NULL;
     }
     return $return;
 }
Exemplo n.º 21
0
 function admin_verify_login()
 {
     if (!empty($this->data)) {
         $rs = $this->Login->verifyLogin($this->data);
         if ($rs) {
             $this->Session->write('User', $rs);
             $this->Session->write('LoginStatus', 1);
             /*-save last login details-*/
             $arrData = array('User' => array('last_login_ip' => $this->request->clientIp(), 'last_login_date' => @DboSource::expression('NOW()')));
             $this->User->validation = null;
             $this->User->id = $rs['Login']['id'];
             $this->User->save($arrData, false);
             //print_r($rs['Login']['id']);die;
             /*-[end]save last login details-*/
             $this->redirect('/admin/users/index');
         } else {
             $this->Session->setFlash("Invalid Email or Password");
             $this->redirect(array('action' => 'index'));
         }
     }
 }
Exemplo n.º 22
0
 /**
  * Test nested transaction
  *
  * @return void
  */
 public function testNestedTransaction()
 {
     $this->skipIf($this->Dbo->nestedTransactionSupported() === false, 'The Sqlite version do not support nested transaction');
     $this->loadFixtures('User');
     $model = new User();
     $model->hasOne = $model->hasMany = $model->belongsTo = $model->hasAndBelongsToMany = array();
     $model->cacheQueries = false;
     $this->Dbo->cacheMethods = false;
     $this->assertTrue($this->Dbo->begin());
     $this->assertNotEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->begin());
     $this->assertTrue($model->delete(1));
     $this->assertEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->rollback());
     $this->assertNotEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->begin());
     $this->assertTrue($model->delete(1));
     $this->assertEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->commit());
     $this->assertEmpty($model->read(null, 1));
     $this->assertTrue($this->Dbo->rollback());
     $this->assertNotEmpty($model->read(null, 1));
 }
Exemplo n.º 23
0
 /**
  * Rollback a transaction
  *
  * @param unknown_type $model
  * @return boolean True on success, false on fail
  * (i.e. if the database/model does not support transactions,
  * or a transaction has not started).
  */
 function rollback(&$model)
 {
     if (parent::rollback($model)) {
         return $this->execute('ROLLBACK TRAN');
     }
     return false;
 }
 /**
  * test that fields() method cache detects schema name changes
  *
  * @return void
  */
 public function testFieldsCacheKeyWithSchemanameChange()
 {
     if ($this->db instanceof Postgres || $this->db instanceof Sqlserver) {
         $this->markTestSkipped('Cannot run this test with SqlServer or Postgres');
     }
     Cache::delete('method_cache', '_cake_core_');
     DboSource::$methodCache = array();
     $Article = ClassRegistry::init('Article');
     $ds = $Article->getDataSource();
     $ds->cacheMethods = true;
     $first = $ds->fields($Article);
     $Article->schemaName = 'secondSchema';
     $ds = $Article->getDataSource();
     $ds->cacheMethods = true;
     $second = $ds->fields($Article);
     $this->assertEquals(2, count(DboSource::$methodCache['fields']));
 }
Exemplo n.º 25
0
 public function testResetSequence()
 {
     $model = new Article();
     $table = $this->Dbo->fullTableName($model, false);
     $fields = array('id', 'user_id', 'title', 'body', 'published');
     $values = array(array(1, 1, 'test', 'first post', false), array(2, 1, 'test 2', 'second post post', false));
     $this->Dbo->insertMulti($table, $fields, $values);
     $sequence = $this->Dbo->getSequence($table);
     $result = $this->Dbo->rawQuery("SELECT nextval('{$sequence}')");
     $original = $result->fetch(PDO::FETCH_ASSOC);
     $this->assertTrue($this->Dbo->resetSequence($table, 'id'));
     $result = $this->Dbo->rawQuery("SELECT currval('{$sequence}')");
     $new = $result->fetch(PDO::FETCH_ASSOC);
     $this->assertTrue($new['currval'] > $original['nextval'], 'Sequence did not update');
 }
Exemplo n.º 26
0
 /**
  * Test Dbo value method
  *
  * @access public
  */
 function testQuoting()
 {
     $result = $this->db->fields($this->model);
     $expected = array('`AdodbTestModel`.`id` AS `AdodbTestModel__id`', '`AdodbTestModel`.`client_id` AS `AdodbTestModel__client_id`', '`AdodbTestModel`.`name` AS `AdodbTestModel__name`', '`AdodbTestModel`.`login` AS `AdodbTestModel__login`', '`AdodbTestModel`.`passwd` AS `AdodbTestModel__passwd`', '`AdodbTestModel`.`addr_1` AS `AdodbTestModel__addr_1`', '`AdodbTestModel`.`addr_2` AS `AdodbTestModel__addr_2`', '`AdodbTestModel`.`zip_code` AS `AdodbTestModel__zip_code`', '`AdodbTestModel`.`city` AS `AdodbTestModel__city`', '`AdodbTestModel`.`country` AS `AdodbTestModel__country`', '`AdodbTestModel`.`phone` AS `AdodbTestModel__phone`', '`AdodbTestModel`.`fax` AS `AdodbTestModel__fax`', '`AdodbTestModel`.`url` AS `AdodbTestModel__url`', '`AdodbTestModel`.`email` AS `AdodbTestModel__email`', '`AdodbTestModel`.`comments` AS `AdodbTestModel__comments`', '`AdodbTestModel`.`last_login` AS `AdodbTestModel__last_login`', '`AdodbTestModel`.`created` AS `AdodbTestModel__created`', '`AdodbTestModel`.`updated` AS `AdodbTestModel__updated`');
     $this->assertEqual($result, $expected);
     $expected = "'1.2'";
     $result = $this->db->value(1.2, 'float');
     $this->assertEqual($expected, $result);
     $expected = "'1,2'";
     $result = $this->db->value('1,2', 'float');
     $this->assertEqual($expected, $result);
     $expected = "'4713e29446'";
     $result = $this->db->value('4713e29446');
     $this->assertEqual($expected, $result);
     $expected = "'10010001'";
     $result = $this->db->value('10010001');
     $this->assertEqual($expected, $result);
     $expected = "'00010010001'";
     $result = $this->db->value('00010010001');
     $this->assertEqual($expected, $result);
 }
Exemplo n.º 27
0
 /**
  * Test truncate with a mock.
  *
  * @return void
  */
 public function testTruncateStatements()
 {
     $this->loadFixtures('Article', 'User');
     $db = ConnectionManager::getDatasource('test');
     $schema = $db->config['schema'];
     $Article = new Article();
     $this->Dbo = $this->getMock('Postgres', array('execute'), array($db->config));
     $this->Dbo->expects($this->at(0))->method('execute')->with("DELETE FROM \"{$schema}\".\"articles\"");
     $this->Dbo->truncate($Article);
     $this->Dbo->expects($this->at(0))->method('execute')->with("DELETE FROM \"{$schema}\".\"articles\"");
     $this->Dbo->truncate('articles');
     // #2355: prevent duplicate prefix
     $this->Dbo->config['prefix'] = 'tbl_';
     $Article->tablePrefix = 'tbl_';
     $this->Dbo->expects($this->at(0))->method('execute')->with("DELETE FROM \"{$schema}\".\"tbl_articles\"");
     $this->Dbo->truncate($Article);
     $this->Dbo->expects($this->at(0))->method('execute')->with("DELETE FROM \"{$schema}\".\"tbl_articles\"");
     $this->Dbo->truncate('articles');
 }
Exemplo n.º 28
0
 /**
  * Test the alter index capabilities of postgres
  *
  * @access public
  * @return void
  */
 function testAlterIndexes()
 {
     $this->db->cacheSources = false;
     $schema1 =& new CakeSchema(array('name' => 'AlterTest1', 'connection' => 'test_suite', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50), 'group1' => array('type' => 'integer', 'null' => true), 'group2' => array('type' => 'integer', 'null' => true))));
     $this->db->query($this->db->createSchema($schema1));
     $schema2 =& new CakeSchema(array('name' => 'AlterTest2', 'connection' => 'test_suite', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50), 'group1' => array('type' => 'integer', 'null' => true), 'group2' => array('type' => 'integer', 'null' => true), 'indexes' => array('name_idx' => array('column' => 'name', 'unique' => 0), 'group_idx' => array('column' => 'group1', 'unique' => 0), 'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0), 'PRIMARY' => array('column' => 'id', 'unique' => 1)))));
     $this->db->query($this->db->alterSchema($schema2->compare($schema1)));
     $indexes = $this->db->index('altertest');
     $this->assertEqual($schema2->tables['altertest']['indexes'], $indexes);
     // Change three indexes, delete one and add another one
     $schema3 =& new CakeSchema(array('name' => 'AlterTest3', 'connection' => 'test_suite', 'altertest' => array('id' => array('type' => 'integer', 'null' => false, 'default' => 0), 'name' => array('type' => 'string', 'null' => false, 'length' => 50), 'group1' => array('type' => 'integer', 'null' => true), 'group2' => array('type' => 'integer', 'null' => true), 'indexes' => array('name_idx' => array('column' => 'name', 'unique' => 1), 'group_idx' => array('column' => 'group2', 'unique' => 0), 'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0), 'another_idx' => array('column' => array('group1', 'name'), 'unique' => 0)))));
     $this->db->query($this->db->alterSchema($schema3->compare($schema2)));
     $indexes = $this->db->index('altertest');
     $this->assertEqual($schema3->tables['altertest']['indexes'], $indexes);
     // Compare us to ourself.
     $this->assertEqual($schema3->compare($schema3), array());
     // Drop the indexes
     $this->db->query($this->db->alterSchema($schema1->compare($schema3)));
     $indexes = $this->db->index('altertest');
     $this->assertEqual(array(), $indexes);
     $this->db->query($this->db->dropSchema($schema1));
 }
Exemplo n.º 29
0
 /**
  * Generates and executes an SQL DELETE statement for given id/conditions on given model.
  *
  * @param Model $model
  * @param mixed $conditions
  * @return boolean Success
  */
 function delete(&$model, $conditions = null)
 {
     if (!$this->_useAlias) {
         return parent::delete($model, $conditions);
     }
     $alias = $this->name($model->alias);
     $table = $this->fullTableName($model);
     $joins = implode(' ', $this->_getJoins($model));
     if (empty($conditions)) {
         $alias = $joins = false;
     }
     $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
     if ($conditions === false) {
         return false;
     }
     if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
         $model->onError();
         return false;
     }
     return true;
 }
Exemplo n.º 30
0
 /**
 	 408:  * Generates and executes an SQL DELETE statement for given id/conditions on given model.
 	 409:  *
 	 410:  * @param Model $model
 	 411:  * @param mixed $conditions
 	 412:  * @return boolean Success
 	 413:  */
 public function delete(Model $model, $conditions = null)
 {
     if (!$this->_useAlias) {
         return parent::delete($model, $conditions);
     }
     $alias = $this->name($model->alias);
     $table = $this->fullTableName($model);
     $joins = implode(' ', $this->_getJoins($model));
     if (empty($conditions)) {
         $alias = $joins = false;
     }
     $complexConditions = false;
     foreach ((array) $conditions as $key => $value) {
         if (strpos($key, $model->alias) === false) {
             $complexConditions = true;
             break;
         }
     }
     if (!$complexConditions) {
         $joins = false;
     }
     $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
     if ($conditions === false) {
         return false;
     }
     if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
         $model->onError();
         return false;
     }
     return true;
 }