mysqlnode.jsexpressmysql-x-devapi

Using the MSQL XDEVAPI In Node JS, can I chain multiple calls together?


Example, I'm trying to check to see if a value exists in a table and then if no duplicates exists write the values in the same table, but its not working. Let me know if chaining the calls is possible if not, would I just pass the variable and then do another call to the DB, also I'm having trouble closing the connection to a single session, any help would be appreciated.

  mysqlx.getSession({ 
    user: 'robot', 
    password: 'password',
    host: 'localhost:8080',
    port: '33060'
})

    .then (function(session){
var v_table = session.getSchema('nms2019local').getTable('v_table')

for (let k=0; k<s_key.length; k++){
 v_table
.select(['s_key', 'accounts'])
.where('s_key like :accounts')
.bind('s_key',s_key[k])
.execute()
.then(function(s_keyDuplicates, session){
    
    let s_keyDuplicatesCheck = s_keyDuplicates.fetchOne()
    console.log(s_keyDuplicatesCheck)
    if (s_keyDuplicatesCheck === undefined){
        
        for (let n = 0; n<s_key.length; n++){
            return v_table
            .insert(['s_key'])
            .values([s_key[n]])

        }
    }
//     else{
    
//     let s_key_final = [];
//     s_keyDuplicatesArray = s_keyDuplicates.toArray()
//    for (var m in s_key){
//        if(!s_keyDuplicatesArray.includes(s_key[m])) s_key_final.push(s_key[m])
//    } console.log(s_key_final)
//    for (let l = 0; l<s_key_final.length; l++){
//              return v_table
//              .insert(['s_key'])
//              .values([s_key_final[l]]) 
//    }
    
// }
})


}



})


.catch(function(err){
console.log('the following error occured: ' + err.message)

})

Solution

  • What exactly do you mean by chaining? From a quick look, I would say the only problem is that you are not calling execute() with insert(), and thus, the values are never sent to the server. I'm not sure about the async flow though. Would have to check.

    Also, I'm not sure if the s_key column is supposed to contain unique values, but if that is the case you are probably better off creating a unique key constraint and using an SQL "upsert" strategy like ON DUPLICATE KEY UPDATE.

    Disclaimer: I'm the lead developer of the MySQL X DevAPI Connector for Node.js