I recently came across the new features in MySQL 9.0 and found out about JavaScript Stored Programs in this link and in the MySQL docs.
I also read this part about the new feature here.
So, I decided to test it using NodeJS and Postman.
Let’s say I executed the below code in MySQL:
CREATE FUNCTION sum(arg1 INT, arg2 INT)
RETURNS INT LANGUAGE JAVASCRIPT AS
$$
return arg1 + arg2;
$$;
I have the main NodeJS file (server.js
) below:
const express = require('express');
const cors = require('cors');
const connection = require('./db/connection');
const try = require('./utilities/try');
//Creating an Express application
const app = express();
//Use CORS
app.use(cors());
//Routes
app.use('', try);
// Initializing server
app.listen(3000, "localhost", () => {
console.log("Server is running on port 3000");
});
Below I have connection.js
for connceting the server to the DB.
"use strict"
require('dotenv').config();
const mysql = require('mysql2');
//MySQL connection
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
connection.connect(err => {
if (err) throw err;
console.log('Connected to the MySQL server.');
});
module.exports = connection;
And here, I’ve got my try.js
for executing the MySQL statements:
const express = require('express');
const router = express.Router();
const connection = require('./db/connection');
router.post('/sum', (req, res) => {
const {num1, num2} = req.body;
if(!num1 || !num2){
return res.status(400).json({ error: 'The numbers are required' });
} else {
const sql = "SELECT sum(?, ?)";
const values = [num1, num2];
connection.execute(sql, values, (err, results) => {
if (err) {
res.status(500).json({ error: 'Error while executing the function' });
} else {
res.status(200).json({ message: `The sum is ${results[0]['sum(?, ?)']}` });
}
});
}
});
module.exports = router;
However, I’m not sure how to display the sum of the 2 values. Is this the correct way to do this? Or is it different? Any help would be appreciated. Note: I’m using the Community Edition, not the Enterprise Edition.
Any help would be appreciated. Thanks!
NOTE: I am not using the Enterprise Edition, I am using the Communtity Edition.
EDIT: The code leads to this response:
{
"error": "Error while executing the function"
}