Guest User

Untitled

a guest
Apr 25th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. var sys = require('sys');
  2.  
  3. function Sqlite(path) {
  4. var conn = process.createChildProcess("sqlite3", ['-batch', '-header', '-nullvalue', "\r", '-separator', "\t", path]),
  5. queue = [], dequeued = 0,
  6. callback, want_close = false;
  7.  
  8. function parse(string) {
  9. var raw, headers;
  10. // Parse the output into cells. newline for row, tab for field, and
  11. // carriage return for null values.
  12. raw = string.split("\n").map(function (row) {
  13. return row.split("\t").map(function (item) {
  14. return item === "\r" ? null : item;
  15. });
  16. });
  17.  
  18. // pop off the always trailing empty row
  19. raw.pop();
  20.  
  21. // Strip off the first row, it's the column names
  22. headers = raw.shift();
  23.  
  24. // Merge the rest into an array of json objects
  25. return raw.map(function (row) {
  26. var data = {};
  27. headers.map(function (name, index) {
  28. data[name] = row[index];
  29. });
  30. return data;
  31. });
  32. }
  33.  
  34. function cycle(string) {
  35. // debug(queue.length);
  36. var next;
  37.  
  38. // When we get data, call the callback and clear everything.
  39. if (string) {
  40. callback(string);
  41. callback = null;
  42. }
  43.  
  44. // If the queue is empty, we're done
  45. if (queue.length === 0) {
  46. if (want_close) {
  47. conn.close();
  48. }
  49. return;
  50. }
  51.  
  52. // If no query is active, insert another
  53. if (!callback) {
  54.  
  55. // Use a delayed shift queue instead of shifting every time.
  56. next = queue[dequeued];
  57. dequeued += 1;
  58. if (dequeued * 2 > queue.length) {
  59. queue = queue.slice(dequeued);
  60. dequeued = 0;
  61. }
  62.  
  63. callback = next[1];
  64. conn.write(next[0]);
  65. }
  66. }
  67.  
  68. conn.addListener("output", cycle);
  69.  
  70. conn.addListener("error", function (data) {
  71. if (data) {
  72. sys.puts('<span style="color:red">');
  73. sys.puts("ERROR: " + sys.inspect(data));
  74. sys.puts('<span style="color:red">');
  75. }
  76. });
  77.  
  78. this.query = function (sql, cb) {
  79. queue.push([sql + ";\n", function (string) {
  80. cb(parse(string));
  81. }]);
  82. cycle();
  83. };
  84.  
  85. this.command = function (command) {
  86. queue.push(["." + command + "\n", sys.puts]);
  87. cycle();
  88. };
  89.  
  90. this.close = function () {
  91. want_close = true;
  92. cycle();
  93. };
  94.  
  95. }
  96.  
  97.  
  98. var db = new Sqlite('test.db');
  99. // db.command('schema');
  100. for (var i = 0; i < 100000; i += 1) {
  101. db.query("SELECT * from reservations LIMIT 2", function () {});
  102. }
  103.  
  104. db.close();
Add Comment
Please, Sign In to add comment