1+ var mssql = require ( 'mssql' ) ;
2+
3+ /**
4+ * Driver for MS SQL Server
5+ *
6+ * @author Thiago Delgado Pinto
7+ *
8+ * @see https://github.com/mlaanderson/database-js
9+ * @see https://github.com/tediousjs/node-mssql
10+ * @see https://github.com/tediousjs/tedious
11+ */
12+ class MsSql {
13+
14+ constructor ( pool , options ) {
15+
16+ this . pool = pool ;
17+ this . options = options ;
18+ this . transaction = null ;
19+ this . _inTransaction = false ;
20+
21+ var connectCallback = function connectCallback ( err ) {
22+ if ( err ) {
23+ throw err ;
24+ }
25+ } ;
26+
27+ this . pool . connect ( connectCallback ) ;
28+ }
29+
30+ /**
31+ * Performs a query or data manipulation command.
32+ *
33+ * @param {string } sql
34+ */
35+ query ( sql ) {
36+ var request = new mssql . Request ( this . pool ) ;
37+ return request . query ( sql ) ;
38+ }
39+
40+ /**
41+ * Executes a data manipulation command.
42+ *
43+ * @param {string } sql
44+ */
45+ execute ( sql ) {
46+ return this . query ( sql ) ;
47+ }
48+
49+ close ( ) {
50+ var self = this ;
51+ return new Promise ( function closePromise ( resolve , reject ) {
52+ try {
53+ self . pool . close ( ) ;
54+ resolve ( ) ;
55+ } catch ( err ) {
56+ reject ( err ) ;
57+ }
58+ } ) ;
59+ }
60+
61+ isTransactionSupported ( ) {
62+ return true ;
63+ }
64+
65+ inTransaction ( ) {
66+ return this . _inTransaction ;
67+ }
68+
69+ beginTransaction ( ) {
70+ if ( true === this . inTransaction ( ) ) {
71+ return Promise . resolve ( false ) ;
72+ }
73+ this . transaction = new mssql . Transaction ( this . pool ) ;
74+ this . _inTransaction = true ;
75+ return this . transaction . begin ( ) ;
76+ }
77+
78+ commit ( ) {
79+ if ( false === this . inTransaction ( ) ) {
80+ return Promise . resolve ( false ) ;
81+ }
82+ this . _inTransaction = false ;
83+ return this . transaction . commit ( ) ;
84+ }
85+
86+ rollback ( ) {
87+ if ( false === this . inTransaction ( ) ) {
88+ return Promise . resolve ( false ) ;
89+ }
90+ this . _inTransaction = false ;
91+ return this . transaction . rollback ( ) ;
92+ }
93+ }
94+
95+ module . exports = {
96+ open : function ( connection , options ) {
97+
98+ if ( 'string' === typeof connection ) {
99+ return new mssql . connect ( connection ) ;
100+ }
101+
102+ var config = {
103+ server : connection . Hostname || 'localhost' ,
104+ port : parseInt ( connection . Port ) || 1433 ,
105+ database : connection . Database ,
106+ user : connection . Username ,
107+ password : connection . Password ,
108+ options : {
109+ encrypt : false
110+ }
111+ } ;
112+
113+ config . options = Object . assign ( config . options , options || { } ) ;
114+ var pool = new mssql . ConnectionPool ( config ) ;
115+ return new MsSql ( pool , options ) ;
116+ }
117+ } ;
0 commit comments