Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

pgutil.js 1.6 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  1. const stream = require('stream');
  2. const childProcess = require('child_process');
  3. function escape(txt) {
  4. let buf = Buffer.isBuffer(txt) ? txt : Buffer.from(txt, 'utf-8');
  5. const n = buf.length;
  6. let tgt = Buffer.allocUnsafe(n * 2);
  7. let opos = 0;
  8. for (let i = 0; i < n; i++) {
  9. let b = buf[i];
  10. switch (b) {
  11. case 92: // backslash
  12. tgt[opos++] = 92;
  13. tgt[opos++] = 92;
  14. break;
  15. case 9: // tab
  16. tgt[opos++] = 92;
  17. tgt[opos++] = 116;
  18. break;
  19. case 10: // newline
  20. tgt[opos++] = 92;
  21. tgt[opos++] = 110;
  22. break;
  23. case 13: // carriage return
  24. tgt[opos++] = 92;
  25. tgt[opos++] = 114;
  26. break;
  27. default:
  28. tgt[opos++] = b;
  29. }
  30. }
  31. return tgt.slice(0, opos);
  32. }
  33. module.exports.escapePGText = escape;
  34. class PGEncode extends stream.Transform {
  35. constructor() {
  36. super({objectMode: true});
  37. }
  38. _write(rec, enc, cb) {
  39. let n = rec.length;
  40. for (let i = 0; i < n; i++) {
  41. let f = rec[i];
  42. if (i > 0) this.push('\t');
  43. if (f == null) {
  44. this.push('\\N');
  45. } else if (typeof f == 'string' || f instanceof Buffer) {
  46. this.push(escape(f));
  47. } else {
  48. this.push(escape(f.toString()));
  49. }
  50. }
  51. this.push('\n');
  52. cb();
  53. }
  54. }
  55. module.exports.encodePGText = function() {
  56. return new PGEncode();
  57. }
  58. function openCopyStream(tbl) {
  59. let cp = childProcess.spawn('psql', ['-c', `\\copy ${tbl} FROM stdin`], {
  60. stdio: ['pipe', process.stdout, process.stderr]
  61. });
  62. return cp.stdin;
  63. }
  64. module.exports.openCopyStream = openCopyStream;
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...