ThunD3eR
ThunD3eR

Reputation: 3446

How to properly convert uuid to BINARY(16)?

I have an id field of type BINARY(16) in a mysql table.

I generate the following id: 66e2105c-bff5-4206-a9cc-e212f5622368

With this code:

const v = uuidV4Bytes(16);

The insert via sequalize is:

INSERT INTO SPORTS(Id,Name,HouseId,Date,Active)
        VALUES ('66e2105c-bff5-4206-a9cc-e212f5622368','SPORTNAME',1, '2020-05-04', 0)

Problem:

Error Code: 1406. Data too long for column 'Id' at row 

Im trying to convert a uuid to a binary(16) but apperently Im getting a value that is to big. How do I solve this?

Upvotes: 3

Views: 4736

Answers (2)

ThunD3eR
ThunD3eR

Reputation: 3446

Thanks to @hanshenrik I started searching for a way to use UNHEX in nodeexpress.

I found the following:

const byteValue = Buffer.from(uuidV4Bytes(16).replace('-', ''), 'hex')

This did the trick. However I can not say that this is the most optimal way but it solved my problem.

Upvotes: 4

hanshenrik
hanshenrik

Reputation: 21463

as long as it's always in the form 8-4-4-4-12 hex characters, you could just have MySQL do it for you with REPLACE() and UNHEX()

INSERT INTO SPORTS(Id,Name,HouseId,WDate,Active)
    VALUES (UNHEX(REPLACE('66e2105c-bff5-4206-a9cc-e212f5622368','-','')),'SPORTNAME',1, '2020-05-04', 0)

Upvotes: 3

Related Questions