schangxiang@126.com
2025-09-19 0821aa23eabe557c0d9ef5dbe6989c68be35d1fe
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
'use strict'
 
const fs = require('fs')
const path = require('path')
const sql = require('./tedious')
 
const exit = process.exit
const write = text => process.stdout.write(text)
Buffer.prototype.toJSON = () => {
  return `0x${this.toString('hex')}`
}
 
// Resolve config path
 
let cfgPath = path.resolve(process.argv[2] || process.cwd())
if (fs.lstatSync(cfgPath).isDirectory()) {
  cfgPath = path.resolve(cfgPath, './.mssql.json')
}
if (!fs.existsSync(cfgPath)) {
  console.error('Config file not found.')
  exit(1)
}
 
// Config checks & parse
 
let config
try {
  config = fs.readFileSync(cfgPath)
} catch (err) {
  console.error(`Failed to load config file. ${err.message}`)
  exit(1)
}
 
try {
  config = JSON.parse(config)
} catch (err) {
  console.error(`Failed to parse config file. ${err.message}`)
  exit(1)
}
 
// Read stdin
 
const buffer = []
 
process.stdin.setEncoding('utf8')
process.stdin.on('readable', () => buffer.push(process.stdin.read()))
 
process.stdin.on('end', () => {
  const statement = buffer.join('')
  let rst = 0
  let index = 0
 
  if (!statement.length) {
    console.error('Statement is empty.')
    exit(1)
  }
 
  sql.connect(config, err => {
    if (err) {
      console.error(err.message)
      exit(1)
    }
 
    write('[')
 
    const request = new sql.Request()
    request.stream = true
    request.on('recordset', () => {
      index = 0
      if (rst++ > 0) {
        write('],')
      }
 
      return write('[')
    })
 
    request.on('error', err => {
      console.error(err.message)
      sql.close()
      return exit(1)
    })
 
    request.on('row', row => {
      if (index++ > 0) {
        write(',')
      }
 
      return write(JSON.stringify(row))
    })
 
    request.on('done', () => {
      if (rst > 0) {
        write(']')
      }
 
      write(']\n')
      sql.close()
      return exit(0)
    })
 
    request.query(statement)
  })
})
 
process.on('uncaughtException', err => {
  if (err.code === 'EPIPE') {
    console.error('Failed to pipe output stream.')
  } else {
    console.error(err.message)
  }
 
  exit(1)
})