ActiveRecordTest.php 19.3 KB
Newer Older
1 2
<?php

3
namespace yiiunit\extensions\elasticsearch;
4

5 6
use yii\base\Event;
use yii\db\BaseActiveRecord;
7
use yii\elasticsearch\Connection;
8
use yiiunit\framework\ar\ActiveRecordTestTrait;
9 10 11 12 13
use yiiunit\data\ar\elasticsearch\ActiveRecord;
use yiiunit\data\ar\elasticsearch\Customer;
use yiiunit\data\ar\elasticsearch\OrderItem;
use yiiunit\data\ar\elasticsearch\Order;
use yiiunit\data\ar\elasticsearch\Item;
14
use yiiunit\TestCase;
15

16 17 18
/**
 * @group elasticsearch
 */
19 20
class ActiveRecordTest extends ElasticSearchTestCase
{
21 22
	use ActiveRecordTestTrait;

AlexGx committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36
	public function callCustomerFind($q = null)
	{
		return Customer::find($q);
	}

	public function callOrderFind($q = null)
	{
		return Order::find($q);
	}

	public function callOrderItemFind($q = null)
	{
		return OrderItem::find($q);
	}
37

AlexGx committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	public function callItemFind($q = null)
	{
		return Item::find($q);
	}

	public function getCustomerClass()
	{
		return Customer::className();
	}

	public function getItemClass()
	{
		return Item::className();
	}

	public function getOrderClass()
	{
		return Order::className();
	}

	public function getOrderItemClass()
	{
		return OrderItem::className();
	}
62 63 64 65 66 67

	/**
	 * can be overridden to do things after save()
	 */
	public function afterSave()
	{
Carsten Brandt committed
68
		$this->getConnection()->createCommand()->flushIndex('yiitest');
69 70
	}

71 72 73
	public function setUp()
	{
		parent::setUp();
74 75 76 77

		/** @var Connection $db */
		$db = ActiveRecord::$db = $this->getConnection();

78 79 80 81
		// delete index
		if ($db->createCommand()->indexExists('yiitest')) {
			$db->createCommand()->deleteIndex('yiitest');
		}
Carsten Brandt committed
82
		$db->createCommand()->createIndex('yiitest');
83

84 85 86 87 88
		$command = $db->createCommand();
		Customer::setUpMapping($command);
		Item::setUpMapping($command);
		Order::setUpMapping($command);
		OrderItem::setUpMapping($command);
89

Carsten Brandt committed
90 91
		$db->createCommand()->flushIndex('yiitest');

92
		$customer = new Customer();
93
		$customer->id = 1;
94
		$customer->setAttributes(['email' => 'user1@example.com', 'name' => 'user1', 'address' => 'address1', 'status' => 1], false);
95 96
		$customer->save(false);
		$customer = new Customer();
97
		$customer->id = 2;
98
		$customer->setAttributes(['email' => 'user2@example.com', 'name' => 'user2', 'address' => 'address2', 'status' => 1], false);
99 100
		$customer->save(false);
		$customer = new Customer();
101
		$customer->id = 3;
102
		$customer->setAttributes(['email' => 'user3@example.com', 'name' => 'user3', 'address' => 'address3', 'status' => 2], false);
103 104 105 106 107 108
		$customer->save(false);

//		INSERT INTO tbl_category (name) VALUES ('Books');
//		INSERT INTO tbl_category (name) VALUES ('Movies');

		$item = new Item();
109
		$item->id = 1;
110
		$item->setAttributes(['name' => 'Agile Web Application Development with Yii1.1 and PHP5', 'category_id' => 1], false);
111 112
		$item->save(false);
		$item = new Item();
113
		$item->id = 2;
114
		$item->setAttributes(['name' => 'Yii 1.1 Application Development Cookbook', 'category_id' => 1], false);
115 116
		$item->save(false);
		$item = new Item();
117
		$item->id = 3;
118
		$item->setAttributes(['name' => 'Ice Age', 'category_id' => 2], false);
119 120
		$item->save(false);
		$item = new Item();
121
		$item->id = 4;
122
		$item->setAttributes(['name' => 'Toy Story', 'category_id' => 2], false);
123 124
		$item->save(false);
		$item = new Item();
125
		$item->id = 5;
126
		$item->setAttributes(['name' => 'Cars', 'category_id' => 2], false);
127 128 129
		$item->save(false);

		$order = new Order();
130
		$order->id = 1;
Alexander Kochetov committed
131
		$order->setAttributes(['customer_id' => 1, 'created_at' => 1325282384, 'total' => 110.0], false);
132 133
		$order->save(false);
		$order = new Order();
134
		$order->id = 2;
Alexander Kochetov committed
135
		$order->setAttributes(['customer_id' => 2, 'created_at' => 1325334482, 'total' => 33.0], false);
136 137
		$order->save(false);
		$order = new Order();
138
		$order->id = 3;
Alexander Kochetov committed
139
		$order->setAttributes(['customer_id' => 2, 'created_at' => 1325502201, 'total' => 40.0], false);
140 141
		$order->save(false);

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 1, 'item_id' => 1, 'quantity' => 1, 'subtotal' => 30.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 1, 'item_id' => 2, 'quantity' => 2, 'subtotal' => 40.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 2, 'item_id' => 4, 'quantity' => 1, 'subtotal' => 10.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 2, 'item_id' => 5, 'quantity' => 1, 'subtotal' => 15.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 2, 'item_id' => 3, 'quantity' => 1, 'subtotal' => 8.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 3, 'item_id' => 2, 'quantity' => 1, 'subtotal' => 40.0], false);
		$orderItem->save(false);
160

Carsten Brandt committed
161
		$db->createCommand()->flushIndex('yiitest');
162 163
	}

164 165 166 167 168 169 170 171 172 173 174 175 176 177
	public function testFindAsArray()
	{
		// asArray
		$customer = $this->callCustomerFind()->where(['id' => 2])->asArray()->one();
		$this->assertEquals([
			'id' => 2,
			'email' => 'user2@example.com',
			'name' => 'user2',
			'address' => 'address2',
			'status' => 1,
			'_score' => 1.0
		], $customer);
	}

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	public function testSearch()
	{
		$customers = $this->callCustomerFind()->search()['hits'];
		$this->assertEquals(3, $customers['total']);
		$this->assertEquals(3, count($customers['hits']));
		$this->assertTrue($customers['hits'][0] instanceof Customer);
		$this->assertTrue($customers['hits'][1] instanceof Customer);
		$this->assertTrue($customers['hits'][2] instanceof Customer);

		// limit vs. totalcount
		$customers = $this->callCustomerFind()->limit(2)->search()['hits'];
		$this->assertEquals(3, $customers['total']);
		$this->assertEquals(2, count($customers['hits']));

		// asArray
		$result = $this->callCustomerFind()->asArray()->search()['hits'];
		$this->assertEquals(3, $result['total']);
		$customers = $result['hits'];
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers[0]);
		$this->assertArrayHasKey('name', $customers[0]);
		$this->assertArrayHasKey('email', $customers[0]);
		$this->assertArrayHasKey('address', $customers[0]);
		$this->assertArrayHasKey('status', $customers[0]);
		$this->assertArrayHasKey('id', $customers[1]);
		$this->assertArrayHasKey('name', $customers[1]);
		$this->assertArrayHasKey('email', $customers[1]);
		$this->assertArrayHasKey('address', $customers[1]);
		$this->assertArrayHasKey('status', $customers[1]);
		$this->assertArrayHasKey('id', $customers[2]);
		$this->assertArrayHasKey('name', $customers[2]);
		$this->assertArrayHasKey('email', $customers[2]);
		$this->assertArrayHasKey('address', $customers[2]);
		$this->assertArrayHasKey('status', $customers[2]);

		// TODO test asArray() + fields() + indexBy()

		// find by attributes
		$result = $this->callCustomerFind()->where(['name' => 'user2'])->search()['hits'];
		$customer = reset($result['hits']);
		$this->assertTrue($customer instanceof Customer);
		$this->assertEquals(2, $customer->id);

		// TODO test query() and filter()
	}

	public function testSearchFacets()
	{
		$result = $this->callCustomerFind()->addStatisticalFacet('status_stats', ['field' => 'status'])->search();
		$this->assertArrayHasKey('facets', $result);
		$this->assertEquals(3, $result['facets']['status_stats']['count']);
		$this->assertEquals(4, $result['facets']['status_stats']['total']); // sum of values
		$this->assertEquals(1, $result['facets']['status_stats']['min']);
		$this->assertEquals(2, $result['facets']['status_stats']['max']);
	}

234 235 236 237 238 239
	public function testGetDb()
	{
		$this->mockApplication(['components' => ['elasticsearch' => Connection::className()]]);
		$this->assertInstanceOf(Connection::className(), ActiveRecord::getDb());
	}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	public function testGet()
	{
		$this->assertInstanceOf(Customer::className(), Customer::get(1));
		$this->assertNull(Customer::get(5));
	}

	public function testMget()
	{
		$this->assertEquals([], Customer::mget([]));

		$records = Customer::mget([1]);
		$this->assertEquals(1, count($records));
		$this->assertInstanceOf(Customer::className(), reset($records));

		$records = Customer::mget([5]);
		$this->assertEquals(0, count($records));

AlexGx committed
257
		$records = Customer::mget([1, 3, 5]);
258 259 260 261 262
		$this->assertEquals(2, count($records));
		$this->assertInstanceOf(Customer::className(), $records[0]);
		$this->assertInstanceOf(Customer::className(), $records[1]);
	}

263 264 265 266 267 268 269
	public function testFindLazy()
	{
		/** @var $customer Customer */
		$customer = Customer::find(2);
		$orders = $customer->orders;
		$this->assertEquals(2, count($orders));

Alexander Kochetov committed
270
		$orders = $customer->getOrders()->where(['between', 'created_at', 1325334000, 1325400000])->all();
271
		$this->assertEquals(1, count($orders));
272
		$this->assertEquals(2, $orders[0]->id);
273 274 275 276
	}

	public function testFindEagerViaRelation()
	{
Alexander Kochetov committed
277
		$orders = Order::find()->with('items')->orderBy('created_at')->all();
278 279
		$this->assertEquals(3, count($orders));
		$order = $orders[0];
280
		$this->assertEquals(1, $order->id);
281
		$this->assertTrue($order->isRelationPopulated('items'));
282
		$this->assertEquals(2, count($order->items));
283 284
		$this->assertEquals(1, $order->items[0]->id);
		$this->assertEquals(2, $order->items[1]->id);
285 286 287 288
	}

	public function testInsertNoPk()
	{
289
		$this->assertEquals(['id'], Customer::primaryKey());
290
		$pkName = 'id';
291

292 293 294 295 296
		$customer = new Customer;
		$customer->email = 'user4@example.com';
		$customer->name = 'user4';
		$customer->address = 'address4';

297
		$this->assertNull($customer->primaryKey);
298
		$this->assertNull($customer->oldPrimaryKey);
299
		$this->assertNull($customer->$pkName);
300 301 302
		$this->assertTrue($customer->isNewRecord);

		$customer->save();
303
		$this->afterSave();
304

305
		$this->assertNotNull($customer->primaryKey);
306
		$this->assertNotNull($customer->oldPrimaryKey);
307
		$this->assertNotNull($customer->$pkName);
308
		$this->assertEquals($customer->primaryKey, $customer->oldPrimaryKey);
309
		$this->assertEquals($customer->primaryKey, $customer->$pkName);
310 311 312 313 314
		$this->assertFalse($customer->isNewRecord);
	}

	public function testInsertPk()
	{
315
		$pkName = 'id';
316

317
		$customer = new Customer;
318
		$customer->$pkName = 5;
319 320 321 322 323 324 325 326
		$customer->email = 'user5@example.com';
		$customer->name = 'user5';
		$customer->address = 'address5';

		$this->assertTrue($customer->isNewRecord);

		$customer->save();

327
		$this->assertEquals(5, $customer->primaryKey);
328 329
		$this->assertEquals(5, $customer->oldPrimaryKey);
		$this->assertEquals(5, $customer->$pkName);
330 331 332 333 334
		$this->assertFalse($customer->isNewRecord);
	}

	public function testUpdatePk()
	{
335
		$pkName = 'id';
336

337
		$orderItem = Order::find([$pkName => 2]);
338
		$this->assertEquals(2, $orderItem->primaryKey);
339 340
		$this->assertEquals(2, $orderItem->oldPrimaryKey);
		$this->assertEquals(2, $orderItem->$pkName);
341

342
//		$this->setExpectedException('yii\base\InvalidCallException');
343
		$orderItem->$pkName = 13;
344 345 346
		$this->assertEquals(13, $orderItem->primaryKey);
		$this->assertEquals(2, $orderItem->oldPrimaryKey);
		$this->assertEquals(13, $orderItem->$pkName);
347
		$orderItem->save();
348 349 350 351 352 353 354
		$this->afterSave();
		$this->assertEquals(13, $orderItem->primaryKey);
		$this->assertEquals(13, $orderItem->oldPrimaryKey);
		$this->assertEquals(13, $orderItem->$pkName);

		$this->assertNull(Order::find([$pkName => 2]));
		$this->assertNotNull(Order::find([$pkName => 13]));
355
	}
356 357 358 359 360 361

	public function testFindLazyVia2()
	{
		/** @var TestCase|ActiveRecordTestTrait $this */
		/** @var Order $order */
		$orderClass = $this->getOrderClass();
362
		$pkName = 'id';
363 364 365 366 367 368 369 370 371 372 373 374 375

		$order = new $orderClass();
		$order->$pkName = 100;
		$this->assertEquals([], $order->items);
	}

	/**
	 * Some PDO implementations(e.g. cubrid) do not support boolean values.
	 * Make sure this does not affect AR layer.
	 */
	public function testBooleanAttribute()
	{
		$db = $this->getConnection();
376
		Customer::deleteAll();
Carsten Brandt committed
377
		Customer::setUpMapping($db->createCommand(), true);
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

		$customerClass = $this->getCustomerClass();
		$customer = new $customerClass();
		$customer->name = 'boolean customer';
		$customer->email = 'mail@example.com';
		$customer->status = true;
		$customer->save(false);

		$customer->refresh();
		$this->assertEquals(true, $customer->status);

		$customer->status = false;
		$customer->save(false);

		$customer->refresh();
		$this->assertEquals(false, $customer->status);

		$customer = new Customer();
		$customer->setAttributes(['email' => 'user2b@example.com', 'name' => 'user2b', 'status' => true], false);
		$customer->save(false);
		$customer = new Customer();
		$customer->setAttributes(['email' => 'user3b@example.com', 'name' => 'user3b', 'status' => false], false);
		$customer->save(false);
		$this->afterSave();

		$customers = $this->callCustomerFind()->where(['status' => true])->all();
		$this->assertEquals(1, count($customers));

		$customers = $this->callCustomerFind()->where(['status' => false])->all();
		$this->assertEquals(2, count($customers));
	}
409

Carsten Brandt committed
410
	public function testFindAsArrayFields()
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
	{
		/** @var TestCase|ActiveRecordTestTrait $this */
		// indexBy + asArray
		$customers = $this->callCustomerFind()->asArray()->fields(['id', 'name'])->all();
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers[0]);
		$this->assertArrayHasKey('name', $customers[0]);
		$this->assertArrayNotHasKey('email', $customers[0]);
		$this->assertArrayNotHasKey('address', $customers[0]);
		$this->assertArrayNotHasKey('status', $customers[0]);
		$this->assertArrayHasKey('id', $customers[1]);
		$this->assertArrayHasKey('name', $customers[1]);
		$this->assertArrayNotHasKey('email', $customers[1]);
		$this->assertArrayNotHasKey('address', $customers[1]);
		$this->assertArrayNotHasKey('status', $customers[1]);
		$this->assertArrayHasKey('id', $customers[2]);
		$this->assertArrayHasKey('name', $customers[2]);
		$this->assertArrayNotHasKey('email', $customers[2]);
		$this->assertArrayNotHasKey('address', $customers[2]);
		$this->assertArrayNotHasKey('status', $customers[2]);
	}

Carsten Brandt committed
433
	public function testFindIndexByFields()
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
	{
		$customerClass = $this->getCustomerClass();
		/** @var TestCase|ActiveRecordTestTrait $this */
		// indexBy + asArray
		$customers = $this->callCustomerFind()->indexBy('name')->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertTrue($customers['user1'] instanceof $customerClass);
		$this->assertTrue($customers['user2'] instanceof $customerClass);
		$this->assertTrue($customers['user3'] instanceof $customerClass);
		$this->assertNotNull($customers['user1']->id);
		$this->assertNotNull($customers['user1']->name);
		$this->assertNull($customers['user1']->email);
		$this->assertNull($customers['user1']->address);
		$this->assertNull($customers['user1']->status);
		$this->assertNotNull($customers['user2']->id);
		$this->assertNotNull($customers['user2']->name);
		$this->assertNull($customers['user2']->email);
		$this->assertNull($customers['user2']->address);
		$this->assertNull($customers['user2']->status);
		$this->assertNotNull($customers['user3']->id);
		$this->assertNotNull($customers['user3']->name);
		$this->assertNull($customers['user3']->email);
		$this->assertNull($customers['user3']->address);
		$this->assertNull($customers['user3']->status);

		// indexBy callable + asArray
		$customers = $this->callCustomerFind()->indexBy(function ($customer) {
			return $customer->id . '-' . $customer->name;
		})->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertTrue($customers['1-user1'] instanceof $customerClass);
		$this->assertTrue($customers['2-user2'] instanceof $customerClass);
		$this->assertTrue($customers['3-user3'] instanceof $customerClass);
		$this->assertNotNull($customers['1-user1']->id);
		$this->assertNotNull($customers['1-user1']->name);
		$this->assertNull($customers['1-user1']->email);
		$this->assertNull($customers['1-user1']->address);
		$this->assertNull($customers['1-user1']->status);
		$this->assertNotNull($customers['2-user2']->id);
		$this->assertNotNull($customers['2-user2']->name);
		$this->assertNull($customers['2-user2']->email);
		$this->assertNull($customers['2-user2']->address);
		$this->assertNull($customers['2-user2']->status);
		$this->assertNotNull($customers['3-user3']->id);
		$this->assertNotNull($customers['3-user3']->name);
		$this->assertNull($customers['3-user3']->email);
		$this->assertNull($customers['3-user3']->address);
		$this->assertNull($customers['3-user3']->status);
	}

Carsten Brandt committed
484
	public function testFindIndexByAsArrayFields()
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	{
		/** @var TestCase|ActiveRecordTestTrait $this */
		// indexBy + asArray
		$customers = $this->callCustomerFind()->indexBy('name')->asArray()->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers['user1']);
		$this->assertArrayHasKey('name', $customers['user1']);
		$this->assertArrayNotHasKey('email', $customers['user1']);
		$this->assertArrayNotHasKey('address', $customers['user1']);
		$this->assertArrayNotHasKey('status', $customers['user1']);
		$this->assertArrayHasKey('id', $customers['user2']);
		$this->assertArrayHasKey('name', $customers['user2']);
		$this->assertArrayNotHasKey('email', $customers['user2']);
		$this->assertArrayNotHasKey('address', $customers['user2']);
		$this->assertArrayNotHasKey('status', $customers['user2']);
		$this->assertArrayHasKey('id', $customers['user3']);
		$this->assertArrayHasKey('name', $customers['user3']);
		$this->assertArrayNotHasKey('email', $customers['user3']);
		$this->assertArrayNotHasKey('address', $customers['user3']);
		$this->assertArrayNotHasKey('status', $customers['user3']);

		// indexBy callable + asArray
		$customers = $this->callCustomerFind()->indexBy(function ($customer) {
			return $customer['id'] . '-' . $customer['name'];
		})->asArray()->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers['1-user1']);
		$this->assertArrayHasKey('name', $customers['1-user1']);
		$this->assertArrayNotHasKey('email', $customers['1-user1']);
		$this->assertArrayNotHasKey('address', $customers['1-user1']);
		$this->assertArrayNotHasKey('status', $customers['1-user1']);
		$this->assertArrayHasKey('id', $customers['2-user2']);
		$this->assertArrayHasKey('name', $customers['2-user2']);
		$this->assertArrayNotHasKey('email', $customers['2-user2']);
		$this->assertArrayNotHasKey('address', $customers['2-user2']);
		$this->assertArrayNotHasKey('status', $customers['2-user2']);
		$this->assertArrayHasKey('id', $customers['3-user3']);
		$this->assertArrayHasKey('name', $customers['3-user3']);
		$this->assertArrayNotHasKey('email', $customers['3-user3']);
		$this->assertArrayNotHasKey('address', $customers['3-user3']);
		$this->assertArrayNotHasKey('status', $customers['3-user3']);
	}

528 529 530 531 532 533
	public function testAfterFindGet()
	{
		/** @var BaseActiveRecord $customerClass */
		$customerClass = $this->getCustomerClass();

		$afterFindCalls = [];
AlexGx committed
534
		Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND, function ($event) use (&$afterFindCalls) {
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
			/** @var BaseActiveRecord $ar */
			$ar = $event->sender;
			$afterFindCalls[] = [get_class($ar), $ar->getIsNewRecord(), $ar->getPrimaryKey(), $ar->isRelationPopulated('orders')];
		});

		$customer = Customer::get(1);
		$this->assertNotNull($customer);
		$this->assertEquals([[$customerClass, false, 1, false]], $afterFindCalls);
		$afterFindCalls = [];

		$customer = Customer::mget([1, 2]);
		$this->assertNotNull($customer);
		$this->assertEquals([
			[$customerClass, false, 1, false],
			[$customerClass, false, 2, false],
		], $afterFindCalls);
		$afterFindCalls = [];

		Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND);
	}

	// TODO test AR with not mapped PK
Alexander Kochetov committed
557
}