ActiveRecordTest.php 19.2 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 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	use ActiveRecordTestTrait;

	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); }
	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(); }

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

41 42 43
	public function setUp()
	{
		parent::setUp();
44 45 46 47

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

48 49 50 51
		// delete index
		if ($db->createCommand()->indexExists('yiitest')) {
			$db->createCommand()->deleteIndex('yiitest');
		}
Carsten Brandt committed
52
		$db->createCommand()->createIndex('yiitest');
53

54 55 56 57 58
		$command = $db->createCommand();
		Customer::setUpMapping($command);
		Item::setUpMapping($command);
		Order::setUpMapping($command);
		OrderItem::setUpMapping($command);
59

Carsten Brandt committed
60 61
		$db->createCommand()->flushIndex('yiitest');

62
		$customer = new Customer();
63
		$customer->id = 1;
64
		$customer->setAttributes(['email' => 'user1@example.com', 'name' => 'user1', 'address' => 'address1', 'status' => 1], false);
65 66
		$customer->save(false);
		$customer = new Customer();
67
		$customer->id = 2;
68
		$customer->setAttributes(['email' => 'user2@example.com', 'name' => 'user2', 'address' => 'address2', 'status' => 1], false);
69 70
		$customer->save(false);
		$customer = new Customer();
71
		$customer->id = 3;
72
		$customer->setAttributes(['email' => 'user3@example.com', 'name' => 'user3', 'address' => 'address3', 'status' => 2], false);
73 74 75 76 77 78
		$customer->save(false);

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

		$item = new Item();
79
		$item->id = 1;
80
		$item->setAttributes(['name' => 'Agile Web Application Development with Yii1.1 and PHP5', 'category_id' => 1], false);
81 82
		$item->save(false);
		$item = new Item();
83
		$item->id = 2;
84
		$item->setAttributes(['name' => 'Yii 1.1 Application Development Cookbook', 'category_id' => 1], false);
85 86
		$item->save(false);
		$item = new Item();
87
		$item->id = 3;
88
		$item->setAttributes(['name' => 'Ice Age', 'category_id' => 2], false);
89 90
		$item->save(false);
		$item = new Item();
91
		$item->id = 4;
92
		$item->setAttributes(['name' => 'Toy Story', 'category_id' => 2], false);
93 94
		$item->save(false);
		$item = new Item();
95
		$item->id = 5;
96
		$item->setAttributes(['name' => 'Cars', 'category_id' => 2], false);
97 98 99
		$item->save(false);

		$order = new Order();
100
		$order->id = 1;
Alexander Kochetov committed
101
		$order->setAttributes(['customer_id' => 1, 'created_at' => 1325282384, 'total' => 110.0], false);
102 103
		$order->save(false);
		$order = new Order();
104
		$order->id = 2;
Alexander Kochetov committed
105
		$order->setAttributes(['customer_id' => 2, 'created_at' => 1325334482, 'total' => 33.0], false);
106 107
		$order->save(false);
		$order = new Order();
108
		$order->id = 3;
Alexander Kochetov committed
109
		$order->setAttributes(['customer_id' => 2, 'created_at' => 1325502201, 'total' => 40.0], false);
110 111
		$order->save(false);

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		$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);
130

Carsten Brandt committed
131
		$db->createCommand()->flushIndex('yiitest');
132 133
	}

134 135 136 137 138 139 140 141 142 143 144 145 146 147
	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);
	}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 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
	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']);
	}

204 205 206 207 208 209
	public function testGetDb()
	{
		$this->mockApplication(['components' => ['elasticsearch' => Connection::className()]]);
		$this->assertInstanceOf(Connection::className(), ActiveRecord::getDb());
	}

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	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));

		$records = Customer::mget([1,3,5]);
		$this->assertEquals(2, count($records));
		$this->assertInstanceOf(Customer::className(), $records[0]);
		$this->assertInstanceOf(Customer::className(), $records[1]);
	}

233 234 235 236 237 238 239
	public function testFindLazy()
	{
		/** @var $customer Customer */
		$customer = Customer::find(2);
		$orders = $customer->orders;
		$this->assertEquals(2, count($orders));

Alexander Kochetov committed
240
		$orders = $customer->getOrders()->where(['between', 'created_at', 1325334000, 1325400000])->all();
241
		$this->assertEquals(1, count($orders));
242
		$this->assertEquals(2, $orders[0]->id);
243 244 245 246
	}

	public function testFindEagerViaRelation()
	{
Alexander Kochetov committed
247
		$orders = Order::find()->with('items')->orderBy('created_at')->all();
248 249
		$this->assertEquals(3, count($orders));
		$order = $orders[0];
250
		$this->assertEquals(1, $order->id);
251
		$this->assertTrue($order->isRelationPopulated('items'));
252
		$this->assertEquals(2, count($order->items));
253 254
		$this->assertEquals(1, $order->items[0]->id);
		$this->assertEquals(2, $order->items[1]->id);
255 256 257 258
	}

	public function testInsertNoPk()
	{
259
		$this->assertEquals(['id'], Customer::primaryKey());
260
		$pkName = 'id';
261

262 263 264 265 266
		$customer = new Customer;
		$customer->email = 'user4@example.com';
		$customer->name = 'user4';
		$customer->address = 'address4';

267
		$this->assertNull($customer->primaryKey);
268
		$this->assertNull($customer->oldPrimaryKey);
269
		$this->assertNull($customer->$pkName);
270 271 272
		$this->assertTrue($customer->isNewRecord);

		$customer->save();
273
		$this->afterSave();
274

275
		$this->assertNotNull($customer->primaryKey);
276
		$this->assertNotNull($customer->oldPrimaryKey);
277
		$this->assertNotNull($customer->$pkName);
278
		$this->assertEquals($customer->primaryKey, $customer->oldPrimaryKey);
279
		$this->assertEquals($customer->primaryKey, $customer->$pkName);
280 281 282 283 284
		$this->assertFalse($customer->isNewRecord);
	}

	public function testInsertPk()
	{
285
		$pkName = 'id';
286

287
		$customer = new Customer;
288
		$customer->$pkName = 5;
289 290 291 292 293 294 295 296
		$customer->email = 'user5@example.com';
		$customer->name = 'user5';
		$customer->address = 'address5';

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

		$customer->save();

297
		$this->assertEquals(5, $customer->primaryKey);
298 299
		$this->assertEquals(5, $customer->oldPrimaryKey);
		$this->assertEquals(5, $customer->$pkName);
300 301 302 303 304
		$this->assertFalse($customer->isNewRecord);
	}

	public function testUpdatePk()
	{
305
		$pkName = 'id';
306

307
		$orderItem = Order::find([$pkName => 2]);
308
		$this->assertEquals(2, $orderItem->primaryKey);
309 310
		$this->assertEquals(2, $orderItem->oldPrimaryKey);
		$this->assertEquals(2, $orderItem->$pkName);
311

312
//		$this->setExpectedException('yii\base\InvalidCallException');
313
		$orderItem->$pkName = 13;
314 315 316
		$this->assertEquals(13, $orderItem->primaryKey);
		$this->assertEquals(2, $orderItem->oldPrimaryKey);
		$this->assertEquals(13, $orderItem->$pkName);
317
		$orderItem->save();
318 319 320 321 322 323 324
		$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]));
325
	}
326 327 328 329 330 331

	public function testFindLazyVia2()
	{
		/** @var TestCase|ActiveRecordTestTrait $this */
		/** @var Order $order */
		$orderClass = $this->getOrderClass();
332
		$pkName = 'id';
333 334 335 336 337 338 339 340 341 342 343 344 345

		$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();
346
		Customer::deleteAll();
Carsten Brandt committed
347
		Customer::setUpMapping($db->createCommand(), true);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

		$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));
	}
379

Carsten Brandt committed
380
	public function testFindAsArrayFields()
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
	{
		/** @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
403
	public function testFindIndexByFields()
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
	{
		$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
454
	public function testFindIndexByAsArrayFields()
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 484 485 486 487 488 489 490 491 492 493 494 495 496 497
	{
		/** @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']);
	}

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
	public function testAfterFindGet()
	{
		/** @var BaseActiveRecord $customerClass */
		$customerClass = $this->getCustomerClass();

		$afterFindCalls = [];
		Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND, function($event) use (&$afterFindCalls) {
			/** @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);
	}

526

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