Cara menggunakan generate guid mysql

Cara menggunakan generate guid mysql

Ini artikel lama, belum di-update. Isinya mungkin tidak relevan dengan kondisi sekarang

Pada terbitan sebelumnya saya sudah pernah membahas keterbatasan AUTO_INCREMENT di MySQL. AUTO_INCREMENT sangat bergantung pada tipe datanya. Kita tidak bisa menggunakannya untuk data yang tak terhingga (unlimited), karena terbatas. Sebagai gantinya, kita harus membuat fungsi generator ID yang mampu membuat ID yang unik.

Pada kesempatan yang lain, saya juga pernah membuat generator ID yang mirip seperti ID video Youtube. Namun, saya belum yakin sepenuhnya dengan ID unik yang dihasilkannya. Mungkin saja, suatu saat nanti generator ini akan membuat ID yang sama. Seperti halnya fungsi bawaan PHP, uniqid(). Fungsi ini memang menghasilkan ID yang unik. Akan tetapi, masih meragukan, karena kita telah diperingatkan pada dokumentasinya.

Warning
This function does not guarantee uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread. Use more_entropy to increase likelihood of uniqueness.

Kalau begitu, apa solusinya?

UUID atau GUID

UUID merupakan singkatan dari Universally Unique Identifier. Sedangkan GUID, singkatan dari Globally Unique Identifier. UUID dan GUID adalah hal yang sama. Perbedaanya, GUID itu merupakan implementasi dari UUID yang dilakukan oleh Microsoft. UUID terdiri dari 32 digit bilangan desimal yang dipisahkan dengan tanda hyphens (-), 8-4-4-4-12 sehingga total semuanya adalah 32 karakter. Contoh UUID:

123e4567-e89b-12d3-a456-426655440000

UUID memiliki beberapa versi, yaitu versi 1, 2, 3, 4, dan 5. Versi 4 digunakan untuk nilai acak (random). Ini bisa kita manfaatkan untuk nilai Primary Key. Menurut penjelasan Wikipedia, setelah membuat 1 miliar UUID untuk setiap detik, kemungkinan untuk terjadi duplikasi nilai yang sama untuk 100 tahun berikutnya adalah 50%.

Fungsi Generator GUID

Sekarang kita coba membuat sebuah fungsi generator GUID di PHP. Fungsi ini bisa kita manfaatkan untuk pengisian nilai Primary Key.

<?php
function guidv4()
{
    if (function_exists(‘com_create_guid’) === true)
        return trim(com_create_guid(), ‘{}');

    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s’, str_split(bin2hex($data), 4));
}

Hasil ketika mengeksekusi fungsi tersebut:

Cara menggunakan generate guid mysql

Jadi, gunakanlah UUID untuk nilai primary key bila data anda terlalu banyak, supaya tidak menjadi masalah di masa depan.

Referensi

  • https://php.net/manual/en/function.uniqid.php</a></li><li><a href="https://stackoverflow.com/questions/246930/is-there-any-difference-between-a-guid-and-a-uuid” target=”_blank">https://stackoverflow.com/questions/246930/is-there-any-difference-between-a-guid-and-a-uuid
  • https://stackoverflow.com/a/18206984/2658551</a></li><li><a href="https://php.net/manual/en/function.com-create-guid.php” target=”_blank">https://php.net/manual/en/function.com-create-guid.php
  • https://en.wikipedia.org/wiki/Universally_unique_identifier</a></li><li><a href="https://en.wikipedia.org/wiki/Globally_unique_identifier” target=”_blank">https://en.wikipedia.org/wiki/Globally_unique_identifier
  • https://www.quora.com/How-do-big-data-databases-handle-the-problem-of-primary-key-values-running-out-given-that-the-key-is-not-unlimited-size</a></li></ul>

I recently had a need to use UUID as my primary key for an application that I have architected using the CodeIgniter framework with Grocery Crud on a MySQL database.


UUID (Universally Unique Identifiers) also known as GUID (Globally Unique Identifier) is a great way to make each of your primary keys a unique key, instead of default integers with the AUTO_INCREMENT flag. The reason why is because they are unique across every table, every database, and every server, allowing the easy merging of records from different databases and easy distribution of databases across multiple servers.

Using UUID in MySQL
Creating a UUID is as easy as using the MySql function UUID(). In CodeIgniter, you could do this with the following code snippet.

$this->db->set('id', 'UUID', FALSE);

This generates a 36 characters hexadecimal key (with 4 dashes included).

ac689561-f7c9-4f7e-be94-33c6c0fb0672

As you can see it has dashes in the string, using the CodeIgniter DB function will insert this in the database with the dashes, it still will work, it does not look clean. You could remove and convert the string to a 32-char key.

To do that I created this function in CodeIgniter, with the CodeIgniter UUID library.

function uuid_key {
        $this->load->library('uuid');
        //Output a v4 UUID 
        $id = $this->uuid->v4();
        $id = str_replace('-', '', $id);
        $this->db->set('id', $id, FALSE);
}

Now I have a 32-byte key,

ac689561f7c94f7ebe9433c6c0fb0672

we can create the table to store it in:

CREATE TABLE `type` (
  `id` char(32) NOT NULL,
  `name` varchar(126) CHARACTER SET latin1 NOT NULL,
  `lastmodified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

I could have done it into a BINARY(16) column – and convert my current 32-bit key into a 16 byte which would have made it faster, I suggest that you should do that if your database is growing very large. I had a need in keeping it 32 bytes, I already have data in the database with primary keys that been generated from scratch, I do not want to keep the old keys and continue with the UUID. That’s my problem.

Using Grocery Crud
Using this with Grocery Crud in CodeIgniter I had to create the uuid_callback that is called before insert.

    // uuid callback
    function uuid_callback($post_array){
        // Build the Grocery CRUD table and form
        $this->load->library('uuid');

        //Output a v4 UUID 
        $id = $this->uuid->v4();
        $id = str_replace('-', '', $id);

        $post_array['id'] = $id;
        return $post_array;
    }

Here is how I set up the Grocery Crud form, which calls the uuid_callback before insert.

public function type() {

$uuid = new grocery_CRUD();

$uuid->set_theme('datatables');

$uuid->set_table('type');
$uuid->callback_after_insert(array($this, 'insert_timestamp', 'type'));

$uuid->set_subject('Type');

$uuid->fields('name');

$uuid->fields('id','name');
$uuid->field_type('id','invisible');
$uuid->callback_before_insert(array($this,'uuid_callback'));

$uuid->columns('name');

$uuid->display_as('name','Name');

$output = $uuid->render();

// Load the views
$this->template->build('tables', $output);
}

The trick is that I have to define the primary key “id” as a field and then declare it as for hidden, before I call the function uuid_callback to get my UUID key.

Conclusions
This is just a quick way to generate UUIDs with CodeIgniter and Grocery Crud. I hope it helps you, and if you have feedback please add it below.