InsertQueryTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 5.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database\Query;
  17. use Cake\Database\Driver\Sqlserver;
  18. use Cake\Database\Exception\DatabaseException;
  19. use Cake\Database\ExpressionInterface;
  20. use Cake\Database\Query\InsertQuery;
  21. use Cake\Database\Query\SelectQuery;
  22. use Cake\Datasource\ConnectionManager;
  23. use Cake\Test\TestCase\Database\QueryAssertsTrait;
  24. use Cake\TestSuite\TestCase;
  25. use InvalidArgumentException;
  26. /**
  27. * Tests InsertQuery class
  28. */
  29. class InsertQueryTest extends TestCase
  30. {
  31. use QueryAssertsTrait;
  32. protected array $fixtures = [
  33. 'core.Articles',
  34. 'core.Authors',
  35. ];
  36. /**
  37. * @var \Cake\Database\Connection
  38. */
  39. protected $connection;
  40. /**
  41. * @var bool
  42. */
  43. protected $autoQuote;
  44. public function setUp(): void
  45. {
  46. parent::setUp();
  47. $this->connection = ConnectionManager::get('test');
  48. $this->autoQuote = $this->connection->getDriver()->isAutoQuotingEnabled();
  49. }
  50. public function tearDown(): void
  51. {
  52. parent::tearDown();
  53. $this->connection->getDriver()->enableAutoQuoting($this->autoQuote);
  54. unset($this->connection);
  55. }
  56. /**
  57. * You cannot call values() before insert() it causes all sorts of pain.
  58. */
  59. public function testInsertValuesBeforeInsertFailure(): void
  60. {
  61. $this->expectException(DatabaseException::class);
  62. $query = new InsertQuery($this->connection);
  63. $query->values([
  64. 'id' => 1,
  65. 'title' => 'mark',
  66. 'body' => 'test insert',
  67. ]);
  68. }
  69. /**
  70. * Inserting nothing should not generate an error.
  71. */
  72. public function testInsertNothing(): void
  73. {
  74. $this->expectException(InvalidArgumentException::class);
  75. $this->expectExceptionMessage('At least 1 column is required to perform an insert.');
  76. $query = new InsertQuery($this->connection);
  77. $query->insert([]);
  78. }
  79. /**
  80. * Test insert() with no into()
  81. */
  82. public function testInsertNoInto(): void
  83. {
  84. $this->expectException(DatabaseException::class);
  85. $this->expectExceptionMessage('Could not compile insert query. No table was specified');
  86. $query = new InsertQuery($this->connection);
  87. $query->insert(['title', 'body'])->sql();
  88. }
  89. /**
  90. * Test insert overwrites values
  91. */
  92. public function testInsertOverwritesValues(): void
  93. {
  94. $query = new InsertQuery($this->connection);
  95. $query->insert(['title', 'body'])
  96. ->insert(['title'])
  97. ->into('articles')
  98. ->values([
  99. 'title' => 'mark',
  100. ]);
  101. $result = $query->sql();
  102. $this->assertQuotedQuery(
  103. 'INSERT INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?' .
  104. 'VALUES \(:c0\)',
  105. $result,
  106. !$this->autoQuote
  107. );
  108. }
  109. /**
  110. * Test inserting a single row.
  111. */
  112. public function testInsertSimple(): void
  113. {
  114. $query = new InsertQuery($this->connection);
  115. $query->insert(['title', 'body'])
  116. ->into('articles')
  117. ->values([
  118. 'title' => 'mark',
  119. 'body' => 'test insert',
  120. ]);
  121. $result = $query->sql();
  122. $this->assertQuotedQuery(
  123. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  124. 'VALUES \(:c0, :c1\)',
  125. $result,
  126. !$this->autoQuote
  127. );
  128. $result = $query->execute();
  129. $result->closeCursor();
  130. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  131. if (!$this->connection->getDriver() instanceof Sqlserver) {
  132. $this->assertSame(1, $result->rowCount(), '1 row should be inserted');
  133. }
  134. $expected = [
  135. [
  136. 'id' => 4,
  137. 'author_id' => null,
  138. 'title' => 'mark',
  139. 'body' => 'test insert',
  140. 'published' => 'N',
  141. ],
  142. ];
  143. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  144. }
  145. /**
  146. * Test insert queries quote integer column names
  147. */
  148. public function testInsertQuoteColumns(): void
  149. {
  150. $query = new InsertQuery($this->connection);
  151. $query->insert([123])
  152. ->into('articles')
  153. ->values([
  154. '123' => 'mark',
  155. ]);
  156. $result = $query->sql();
  157. $this->assertQuotedQuery(
  158. 'INSERT INTO <articles> \(<123>\) (OUTPUT INSERTED\.\* )?' .
  159. 'VALUES \(:c0\)',
  160. $result,
  161. !$this->autoQuote
  162. );
  163. }
  164. /**
  165. * Test an insert when not all the listed fields are provided.
  166. * Columns should be matched up where possible.
  167. */
  168. public function testInsertSparseRow(): void
  169. {
  170. $query = new InsertQuery($this->connection);
  171. $query->insert(['title', 'body'])
  172. ->into('articles')
  173. ->values([
  174. 'title' => 'mark',
  175. ]);
  176. $result = $query->sql();
  177. $this->assertQuotedQuery(
  178. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  179. 'VALUES \(:c0, :c1\)',
  180. $result,
  181. !$this->autoQuote
  182. );
  183. $result = $query->execute();
  184. $result->closeCursor();
  185. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  186. if (!$this->connection->getDriver() instanceof Sqlserver) {
  187. $this->assertSame(1, $result->rowCount(), '1 row should be inserted');
  188. }
  189. $expected = [
  190. [
  191. 'id' => 4,
  192. 'author_id' => null,
  193. 'title' => 'mark',
  194. 'body' => null,
  195. 'published' => 'N',
  196. ],
  197. ];
  198. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  199. }
  200. /**
  201. * Test inserting multiple rows with sparse data.
  202. */
  203. public function testInsertMultipleRowsSparse(): void
  204. {
  205. $query = new InsertQuery($this->connection);
  206. $query->insert(['title', 'body'])
  207. ->into('articles')
  208. ->values([
  209. 'body' => 'test insert',
  210. ])
  211. ->values([
  212. 'title' => 'jose',
  213. ]);
  214. $result = $query->execute();
  215. $result->closeCursor();
  216. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  217. if (!$this->connection->getDriver() instanceof Sqlserver) {
  218. $this->assertSame(2, $result->rowCount(), '2 rows should be inserted');
  219. }
  220. $expected = [
  221. [
  222. 'id' => 4,
  223. 'author_id' => null,
  224. 'title' => null,
  225. 'body' => 'test insert',
  226. 'published' => 'N',
  227. ],
  228. [
  229. 'id' => 5,
  230. 'author_id' => null,
  231. 'title' => 'jose',
  232. 'body' => null,
  233. 'published' => 'N',
  234. ],
  235. ];
  236. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  237. }
  238. /**
  239. * Test that INSERT INTO ... SELECT works.
  240. */
  241. public function testInsertFromSelect(): void
  242. {
  243. $select = (new SelectQuery($this->connection))->select(['name', "'some text'", 99])
  244. ->from('authors')
  245. ->where(['id' => 1]);
  246. $query = new InsertQuery($this->connection);
  247. $query->insert(
  248. ['title', 'body', 'author_id'],
  249. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  250. )
  251. ->into('articles')
  252. ->values($select);
  253. $result = $query->sql();
  254. $this->assertQuotedQuery(
  255. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) (OUTPUT INSERTED\.\* )?SELECT',
  256. $result,
  257. !$this->autoQuote
  258. );
  259. $this->assertQuotedQuery(
  260. 'SELECT <name>, \'some text\', 99 FROM <authors>',
  261. $result,
  262. !$this->autoQuote
  263. );
  264. $result = $query->execute();
  265. $result->closeCursor();
  266. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  267. if (!$this->connection->getDriver() instanceof Sqlserver) {
  268. $this->assertSame(1, $result->rowCount());
  269. }
  270. $result = (new SelectQuery($this->connection))->select('*')
  271. ->from('articles')
  272. ->where(['author_id' => 99])
  273. ->execute();
  274. $rows = $result->fetchAll('assoc');
  275. $this->assertCount(1, $rows);
  276. $expected = [
  277. 'id' => 4,
  278. 'title' => 'mariano',
  279. 'body' => 'some text',
  280. 'author_id' => 99,
  281. 'published' => 'N',
  282. ];
  283. $this->assertEquals($expected, $rows[0]);
  284. }
  285. /**
  286. * Test that an exception is raised when mixing query + array types.
  287. */
  288. public function testInsertFailureMixingTypesArrayFirst(): void
  289. {
  290. $this->expectException(DatabaseException::class);
  291. $query = new InsertQuery($this->connection);
  292. $query->insert(['name'])
  293. ->into('articles')
  294. ->values(['name' => 'mark'])
  295. ->values(new InsertQuery($this->connection));
  296. }
  297. /**
  298. * Test that an exception is raised when mixing query + array types.
  299. */
  300. public function testInsertFailureMixingTypesQueryFirst(): void
  301. {
  302. $this->expectException(DatabaseException::class);
  303. $query = new InsertQuery($this->connection);
  304. $query->insert(['name'])
  305. ->into('articles')
  306. ->values(new InsertQuery($this->connection))
  307. ->values(['name' => 'mark']);
  308. }
  309. /**
  310. * Test that insert can use expression objects as values.
  311. */
  312. public function testInsertExpressionValues(): void
  313. {
  314. $query = new InsertQuery($this->connection);
  315. $query->insert(['title', 'author_id'])
  316. ->into('articles')
  317. ->values(['title' => $query->newExpr("SELECT 'jose'"), 'author_id' => 99]);
  318. $result = $query->execute();
  319. $result->closeCursor();
  320. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  321. if (!$this->connection->getDriver() instanceof Sqlserver) {
  322. $this->assertSame(1, $result->rowCount());
  323. }
  324. $result = (new SelectQuery($this->connection))->select('*')
  325. ->from('articles')
  326. ->where(['author_id' => 99])
  327. ->execute();
  328. $rows = $result->fetchAll('assoc');
  329. $this->assertCount(1, $rows);
  330. $expected = [
  331. 'id' => 4,
  332. 'title' => 'jose',
  333. 'body' => null,
  334. 'author_id' => '99',
  335. 'published' => 'N',
  336. ];
  337. $this->assertEquals($expected, $rows[0]);
  338. $subquery = new SelectQuery($this->connection);
  339. $subquery->select(['name'])
  340. ->from('authors')
  341. ->where(['id' => 1]);
  342. $query = new InsertQuery($this->connection);
  343. $query->insert(['title', 'author_id'])
  344. ->into('articles')
  345. ->values(['title' => $subquery, 'author_id' => 100]);
  346. $result = $query->execute();
  347. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  348. if (!$this->connection->getDriver() instanceof Sqlserver) {
  349. $this->assertSame(1, $result->rowCount());
  350. }
  351. $result->closeCursor();
  352. $result = (new SelectQuery($this->connection))->select('*')
  353. ->from('articles')
  354. ->where(['author_id' => 100])
  355. ->execute();
  356. $rows = $result->fetchAll('assoc');
  357. $this->assertCount(1, $rows);
  358. $expected = [
  359. 'id' => 5,
  360. 'title' => 'mariano',
  361. 'body' => null,
  362. 'author_id' => '100',
  363. 'published' => 'N',
  364. ];
  365. $this->assertEquals($expected, $rows[0]);
  366. }
  367. /**
  368. * Test use of modifiers in a INSERT query
  369. *
  370. * Testing the generated SQL since the modifiers are usually different per driver
  371. */
  372. public function testInsertModifiers(): void
  373. {
  374. $query = new InsertQuery($this->connection);
  375. $result = $query
  376. ->insert(['title'])
  377. ->into('articles')
  378. ->values(['title' => 'foo'])
  379. ->modifier('IGNORE');
  380. $this->assertQuotedQuery(
  381. 'INSERT IGNORE INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?',
  382. $result->sql(),
  383. !$this->autoQuote
  384. );
  385. $query = new InsertQuery($this->connection);
  386. $result = $query
  387. ->insert(['title'])
  388. ->into('articles')
  389. ->values(['title' => 'foo'])
  390. ->modifier(['IGNORE', 'LOW_PRIORITY']);
  391. $this->assertQuotedQuery(
  392. 'INSERT IGNORE LOW_PRIORITY INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?',
  393. $result->sql(),
  394. !$this->autoQuote
  395. );
  396. }
  397. public function testCloneValuesExpression(): void
  398. {
  399. $query = new InsertQuery($this->connection);
  400. $query
  401. ->insert(['column'])
  402. ->into('table')
  403. ->values(['column' => $query->newExpr('value')]);
  404. $clause = $query->clause('values');
  405. $clauseClone = (clone $query)->clause('values');
  406. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  407. $this->assertEquals($clause, $clauseClone);
  408. $this->assertNotSame($clause, $clauseClone);
  409. }
  410. /**
  411. * Test that epilog() will actually append a string to an insert query
  412. */
  413. public function testAppendInsert(): void
  414. {
  415. $query = new InsertQuery($this->connection);
  416. $sql = $query
  417. ->insert(['id', 'title'])
  418. ->into('articles')
  419. ->values([1, 'a title'])
  420. ->epilog('RETURNING id')
  421. ->sql();
  422. $this->assertStringContainsString('INSERT', $sql);
  423. $this->assertStringContainsString('INTO', $sql);
  424. $this->assertStringContainsString('VALUES', $sql);
  425. $this->assertSame(' RETURNING id', substr($sql, -13));
  426. }
  427. /**
  428. * Tests that insert query parts get quoted automatically
  429. */
  430. public function testQuotingInsert(): void
  431. {
  432. $this->connection->getDriver()->enableAutoQuoting(true);
  433. $query = new InsertQuery($this->connection);
  434. $sql = $query->insert(['bar', 'baz'])
  435. ->into('foo')
  436. ->sql();
  437. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  438. $query = new InsertQuery($this->connection);
  439. $sql = $query->insert([$query->newExpr('bar')])
  440. ->into('foo')
  441. ->sql();
  442. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  443. }
  444. }