Convert UUID to / from binary to Node

The project I'm working on has switched to MySQL. The keys we use are UUID strings (e.g. 43d597d7-2323-325a-90fc-21fa5947b9f3), but the database field, not the string, is defined as binary (16) - a 16-byte unsigned binary.

I understand that the UUID is basically a 16-byte binary, but I don't know how to convert from / to binary.

I use node-mysql to access the database, and I tried using node-uuid to parse the UUID, but this gives an array of integers. I also tried using Node Buffer , but it just gives a buffer object.

How to convert UUID string to field? And how do I change the value that I read from this field to a UUID?

+6
source share
2 answers

Due to lack of time, I will insert a comment that provided a valid result and later modified the answer to make it more understandable.


That's right, if you have UUID 43d597d7-2323-325a-90fc-21fa5947b9f3 in this string format already in your JS application, you should send the following query to MySQL:

SELECT col FROM table WHERE uuid_col = UNHEX(REPLACE('43d597d7-2323-325a-90fc-21fa5947b9f3', '-', ''));

If you want to extract data and have a UUID in a readable format, you need to convert it to hexadecimal notation.

SELECT HEX(uuid_col) FROM table;

This will give you a UUID without a dash. It looks like the node-uuid.parse works if you give it the sixth line without a dash.

+3
source

So far NB Reciprocal work I came across another solution.

UUID v1 begins with time-based character segments; however, the smallest units come first, distributing, rather, the scattered index.

If you are not stuck in the exact format of UUID v1, than there is a NodeJS module that can generate unique identifiers based on UUID v1, which also monotonously increase and scale, as well as automatically increase identifiers. It also works with node-mysql.

Checkout: monotonic-id

Example with node-mysql:

 var MID = require('monotonic-id'); var mid = new MID(); client.query('INSERT INTO `...` SET `mid`=?', mid.toBuffer(), function(err, res) { ... }) 
+2
source

Source: https://habr.com/ru/post/975043/


All Articles