Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify primary key in NodeJS mysql

Tags:

node.js

mysql

I'm using mysql package from NodeJS in my electron app and would like to identify which keys of the requested table are primary from the response of SELECT statement.

So let's say I'll do this call:

sql.query('SELECT * FROM `npc_vendor` WHERE `entry`= 7324;', (err, result, fields) => {
    if (err) return;
    console.log(result, fields);
});

In response I got the rows in result and field info in fields. Is there a way to tell which of the fields are primary in that table?

I feel like the info is possibly in flags field of fields but I wasn't able to find any documentation on it.

like image 395
Maroš Beťko Avatar asked Jan 31 '26 05:01

Maroš Beťko


1 Answers

You can examine the flags using the MySQL command-line client. I happen to have a test table called users, so let's look at that.

I run the client with the --column-type-info option:

$ mysql --column-type-info

In the mysql client, I do a select, and before the result set is returned, I see output of the column info:

mysql> use test
mysql> select * from users;

Field   1:  `id`
Catalog:    `def`
Database:   `test`
Table:      `users`
Org_table:  `users`
Type:       LONG
Collation:  binary (63)
Length:     11
Max_length: 1
Decimals:   0
Flags:      NOT_NULL PRI_KEY NO_DEFAULT_VALUE NUM PART_KEY 

...

This shows PRI_KEY among the flags.

This column info is basically the MYSQL_FIELD struct. It's documented here: https://dev.mysql.com/doc/c-api/8.0/en/c-api-data-structures.html

Search that manual page about 60% of the way down, until you find the table of flag values. The flags are bits in a bitfield. The bit values are defined here: https://github.com/mysql/mysql-server/blob/8.0/include/mysql_com.h

like image 170
Bill Karwin Avatar answered Feb 01 '26 19:02

Bill Karwin