Wednesday, 24 May 2017

Getting results from a mysql stored procedure into node js

I am trying to insert a record into a table with unique keys and return the ID of the inserted record. If that unique key already exists I want to return the ID of the existing record.

I have the following stored procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_module_get_id`(IN code_prefix  CHAR(4), IN code_num INT, IN module_name VARCHAR(100), IN url VARCHAR(100))
BEGIN
    SET @auto_id = NULL;
    SELECT `Module Table ID` INTO @auto_id
    FROM `module`
    WHERE `Code Prefix` = code_prefix AND `Code Num` = code_num;
    -- Optionally one insert
    IF @auto_id IS NULL AND code_prefix IS NOT NULL AND code_num IS NOT NULL THEN
        INSERT INTO `module` (`Code Prefix`,`Code Num`, `Name`, `url`)
        VALUES (code_prefix, code_num, module_name, url);
        SET @auto_id = LAST_INSERT_ID();
    END IF;
    SELECT @auto_id AS res;
END

This is invoked by the following:

     DB_connector.query('CALL insert_module_get_id(?,?,?,?)',
                        [code_prefix, code_number, name, url],
                        callback);

The problem is that the callback never gets called. If it is called with unique data then the data is inserted into the database as expected but the callback is not called.


To add to the mystery, The preceeding procedure executes the callback fine. The working procedure is

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_code_prefix`(IN 
codePrefixIns CHAR(4))
BEGIN
    SET @codePrefix = NULL;
    SELECT `Code Prefix` INTO @codePrefix
    FROM `module base`
    WHERE `Code Prefix` = codePrefixIns;
    -- Optionally one insert
    IF @codePrefix IS NULL AND codePrefixIns IS NOT NULL THEN
        INSERT INTO `module base` (`Code Prefix`)
        VALUES (codePrefixIns);
    END IF;
END

Why does this correctly call the callback.

For a database schematic see: Github Source which isn't up to date with this question but the schematic is



via EdL

No comments:

Post a Comment