import mysql, {
ConnectionOptions,
ProcedureCallPacket,
ResultSetHeader,
RowDataPacket,
} from 'mysql2/promise';
interface User extends RowDataPacket {
id: number;
name: string;
}
const isResultSetHeader = (data: unknown): data is ResultSetHeader => {
if (!data || typeof data !== 'object') return false;
const keys = [
'fieldCount',
'affectedRows',
'insertId',
'info',
'serverStatus',
'warningStatus',
'changedRows',
];
return keys.every((key) => key in data);
};
(async () => {
const access: ConnectionOptions = {
host: '',
user: '',
password: '',
database: '',
};
const conn = await mysql.createConnection(access);
await conn.query<ResultSetHeader>('DROP TABLE IF EXISTS `users`;');
await conn.query<ResultSetHeader>(
'CREATE TABLE `users` (`id` INT(11) AUTO_INCREMENT, `name` VARCHAR(50), PRIMARY KEY (`id`));'
);
const [inserted] = await conn.execute<ResultSetHeader>(
'INSERT INTO `users`(`name`) VALUES(?), (?), (?), (?);',
['Josh', 'John', 'Marie', 'Gween']
);
console.log('Inserted:', inserted.affectedRows);
await conn.query<ResultSetHeader>('DROP PROCEDURE IF EXISTS getUsers');
await conn.query<ResultSetHeader>(`
CREATE PROCEDURE getUsers()
BEGIN
SELECT * FROM users ORDER BY name ASC;
END
`);
const [procedureResult] =
await conn.query<ProcedureCallPacket<User[]>>('CALL getUsers()');
procedureResult.forEach((users) => {
if (isResultSetHeader(users)) {
console.log('----------------');
console.log('Affected Rows:', users.affectedRows);
} else {
users.forEach((user) => {
console.log('----------------');
console.log('id: ', user.id);
console.log('name:', user.name);
});
}
});
await conn.end();
})();