From 5050205e582b43fa4882d575e24a1e11e78b6789 Mon Sep 17 00:00:00 2001 From: Sergey Tsalkov Date: Fri, 23 Sep 2011 19:15:41 -0700 Subject: [PATCH] add insertUpdate() function for "insert ... on duplicate key update" behavior --- db.class.php | 12 ++++++++++++ simpletest/BasicTest.php | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/db.class.php b/db.class.php index 09d2a1f..a2ac649 100644 --- a/db.class.php +++ b/db.class.php @@ -215,6 +215,11 @@ class DB if (isset($options['ignore']) && $options['ignore'] && strtolower($which) == 'insert') { DB::queryNull("INSERT IGNORE INTO $table ($keys_str) VALUES $values_str"); + + } else if (isset($options['update']) && $options['update'] && strtolower($which) == 'insert') { + $updatestr = call_user_func_array('DB::parseQueryParams', $options['update']); + DB::queryNull("INSERT INTO $table ($keys_str) VALUES $values_str ON DUPLICATE KEY UPDATE $updatestr"); + } else { DB::queryNull("$which INTO $table ($keys_str) VALUES $values_str"); } @@ -224,6 +229,13 @@ class DB public static function insertIgnore($table, $data) { return DB::insertOrReplace('INSERT', $table, $data, array('ignore' => true)); } public static function replace($table, $data) { return DB::insertOrReplace('REPLACE', $table, $data); } + public static function insertUpdate() { + $args = func_get_args(); + $table = array_shift($args); + $data = array_shift($args); + return DB::insertOrReplace('INSERT', $table, $data, array('update' => $args)); + } + public static function delete() { $args = func_get_args(); $table = self::formatTableName(array_shift($args)); diff --git a/simpletest/BasicTest.php b/simpletest/BasicTest.php index e5e82b8..ebcd876 100644 --- a/simpletest/BasicTest.php +++ b/simpletest/BasicTest.php @@ -232,6 +232,25 @@ class BasicTest extends SimpleTest { 'height' => 199.194 )); } + + function test_7_insert_update() { + DB::insertUpdate('accounts', array( + 'id' => 2, //duplicate primary key + 'username' => 'gonesoon', + 'password' => 'something', + 'age' => 61, + 'height' => 199.194 + ), 'age = age + %i', 1); + + $this->assert(DB::affectedRows() === 2); // a quirk of MySQL, even though only 1 row was updated + + $result = DB::query("SELECT * FROM accounts WHERE age = %i", 16); + $this->assert(count($result) === 1); + $this->assert($result[0]['height'] === '10.371'); + + DB::query("UPDATE accounts SET age=age-1 WHERE age=%i", 16); + $this->assert(DB::affectedRows() === 1); + } }