Git Product home page Git Product logo

Comments (3)

kkaefer avatar kkaefer commented on August 28, 2024

What command are you using to run the query? I'm also unsure what "parseString" and "parseFile" mean in your code.

from node-sqlite3.

masterof0 avatar masterof0 commented on August 28, 2024

Sorry, I am using the sqlite module in conjunction with the node-xml module. In this case, I am actually writing data to a sqlite database so there are no queries. I have an XML stream that I am parsing, using node-xml and writing to a db using sqlite3. When I parse the stream using the parseStream method, it works okay. When I write the XML stream to a file and then process the file using parseFile using the same parser, I get a sql error as though it isn't creating the table. Below is the parser configuration I am using to parse the data and write to the db. You can see the calls to the sqlite module. I am stumped why in one scenario the table would be create and in another, using the same parser, it would not complete the call.

I have tried to use logging to give me an indication of where the issue lies, and it appears as though the methods are bing called as expected, Just the table not being created.

Here is the code if helps you any
//Required modules
var spawn = require('child_process').spawn,
xml = require('node-xml'),
sys = require('sys'),
fs = require('fs'),
sqlite3 = require('sqlite3').verbose();

//Global variables
var netconf = spawn('ssh', [process.argv[2], '-s', 'netconf']),
date = new Date();

function pad2(number) {
return (number < 10 ? '0' : '') + number;
};

//Xml parser
var parser = new xml.SaxParser(function (xmlNode) {
var sessionInfo = {},
dir = '',
nodeName = '';

//Function for handling xml characters
function xmlValue(nodeName, chars) {
    if (chars.replace(/(^\s+|\s+$)/g, '') !== '') {
        sessionInfo[dir + nodeName] = chars.replace(/(^\s+|\s+$)/g, '');
    }
}

xmlNode.onStartDocument(function () {
    db.run("CREATE TABLE sessions(  session_id int primary key, \
                                    policy text, \
                                    srcAddr text, \
                                    srcPort int, \
                                    srcPkts int, \
                                    srcBytes int, \
                                    srcInterface, \
                                    dstAddr text, \
                                    dstPort int, \
                                    dstPkts int, \
                                    dstBytes int, \
                                    dstInterface, \
                                    protocol)");
});

xmlNode.onStartElementNS(function (elem) {
    nodeName = elem;
});
xmlNode.onEndElementNS(function (elem) {
    if (elem === 'flow-session') {
        console.log(sessionInfo);
        db.run("INSERT into sessions values ($id, \
                                            $policy, \
                                            $srcAddr, \
                                            $srcPort, \
                                            $srcPkts, \
                                            $srcBytes, \
                                            $srcInterface, \
                                            $dstAddr, \
                                            $dstPort, \
                                            $dstPkts, \
                                            $dstBytes, \
                                            $dstInterface, \
                                            $protocol)",
                                            {$id:sessionInfo['session-identifier'],
                                            $policy:sessionInfo['policy'],
                                            $srcAddr:sessionInfo['in-source-address'],
                                            $srcPort:sessionInfo['in-source-port'],
                                            $srcPkts:sessionInfo['in-pkt-cnt'],
                                            $srcBytes:sessionInfo['in-byte-cnt'],
                                            $srcInterface:sessionInfo['in-interface-name'],
                                            $dstAddr:sessionInfo['out-source-address'],
                                            $dstPort:sessionInfo['out-source-port'],
                                            $dstPkts:sessionInfo['out-pkt-cnt'],
                                            $dstBytes:sessionInfo['out-byte-cnt'],
                                            $dstInterface:sessionInfo['out-interface-name'],
                                            $protocol:sessionInfo['in-protocol']});
        dir = '';
        sessionInfo = {};
    } else if (elem === 'displayed-session-count') {
        console.log(sessionInfo);
    }
});
xmlNode.onCharacters(function (chars) {
    if (nodeName === 'direction') {
        if (chars.match('In')) {
            dir = 'in-';
        } else if (chars.match('Out')) {
            dir = 'out-';
        }
    } else {
        xmlValue(nodeName, chars);
    }
});
xmlNode.onError(function (msg) {
    console.log('<ERROR>' + JSON.stringify(msg) + "</ERROR>");
});

});

//Function for netconf channel
function remoteHost() {
var rpcSession = '',
rpcClose = '',
re = /]]>]]>/,
rpcReply = /rpc-reply/,
log = false,
count = 1;

netconf.stdout.on('data', function (data) {
    if (re.test(data)) {
        switch (count) {
            case 1:
                count ++;
                netconf.stdin.write(rpcSession);
                break;
            case 2:
                count ++;
                netconf.stdin.write(rpcClose);
                break;
        }
    }

    if (rpcReply.test(data)) {
        log = true;
    }

    if (count === 2 && log) {
        if (stream) {
            stream.write(data);
        } else {
            parser.parseString(data);
        }
    }
});

netconf.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});

netconf.on('exit', function (code) {
    console.log('netconf exited with code ' + code);
    if (stream) {
        stream.end();
        console.log("stream closed");
        parser.parseFile(process.argv[3] + '.xml');
    }
});

}

//File handler for streaming to file
if (process.argv[3]) {
var stream = fs.createWriteStream(process.argv[3] + '.xml', {
flags: 'w',
encoding: 'utf-8'
}),
db = new sqlite3.Database(process.argv[3] + '.db', function () {
console.log('Creating session database: ' + process.argv[3] + '.db');
});
} else {
db = new sqlite3.Database('sessionTable' + date.getFullYear() + pad2(date.getMonth()) + pad2(date.getDate()) + pad2(date.getHours()) + pad2(date.getMinutes()) + '.db', function () {
console.log('Creating session database: sessionTable' + date.getFullYear() + pad2(date.getMonth()) + pad2(date.getDate()) + pad2(date.getHours()) + pad2(date.getMinutes()) + '.db');
});
}

//Call to netconf channel
remoteHost();

//Final termination
process.on('exit', function () {
console.log('Completed process');
db.close();
// console.log('Exiting PID:' + process.pid);
});

from node-sqlite3.

kkaefer avatar kkaefer commented on August 28, 2024

What is happening here is that the statement that creates the session table takes some time to complete. Before the table is created, the code prepares another statement that references the table that is currently being created (the INSERT statement). This fails because at that time, the table doesn't yet exist. This in turn makes the entire code fail, so you end up with a journal file because node just aborts in the middle of the process.

It is up to your code to ensure that the statement that creates the table completes before running statements that reference that table. The best way to do that is to create the table and start parsing in the callback of that creation statement. This is not a problem that node-sqlite3 can handle because it depends on the logic in your application.

I'm closing this issue; feel free to reopen it if you think there is something wrong or broken in node-sqlite3.

from node-sqlite3.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.