Skip to content

Stored Procedure with an Insert statement not returning the expected result #1818

@marc324

Description

@marc324

I am working on a project that involves Node and a MySQL database. I have a stored procedure that looks like this:

CREATE PROCEDURE insertUser(
    IN $oID INT(11), 
    IN $uName VARCHAR(40),
    IN $uSurname VARCHAR(40),
    IN $uEmail VARCHAR(255))
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN 
        ROLLBACK; 
    END;
    START TRANSACTION;
    IF NOT EXISTS(Select 1 from Organisations where oID = $oID) THEN 
        Select -1 as error;
    ELSE
        IF EXISTS(Select 1 from Users where uEmail = $uEmail) THEN
            Select -2 as error;
        ELSE
            Insert into Users 
                    (uOrganisationID, uName, uSurname, uEmail)
            Values  ($oID, $uName, $uSurname, $uEmail);

            Select uID, uOrganisationID, uName, uSurname, uEmail
            from Users
            where uEmail = $uEmail;
        END IF; 
    END IF;
    COMMIT;
END

The JS code looks like this:

const q = `
CALL insertUser(${escape(data.uOrganisationID)}, 
            ${escape(data.uName)},
            ${escape(data.uSurname)},
            ${escape(data.uEmail)});`;
executeQuery(q)
      .then((results) => {
          ...some logic...
      })
      .catch((err) => {
          ...some logic...
      });

executeQuery just gets a new connection from the pool and executes the query all wrapped in a promise.

The stored procedure works fine in MySQL Workbench but it does not always work when executed from JS.

I get 3 different results: I get the following when uOrganisationID does not exist. This is the result that I expect so Correct.

[ [ RowDataPacket { error: -1 } ], OkPacket {...} ]

I get the following when uEmail already exist. This is also the result that I expect so Correct again.

[ [ RowDataPacket { error: -2 } ], OkPacket {...} ]

I get the following when validations pass. This is NOT the correct result in my view as I expect to see the results of the Select statement above.

OkPacket {...}

Is this the expected result? As mentioned, I expect to get an array with the result of the Select statement above in the first position.

Many thanks in advance for any help.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions