Skip to content
This repository was archived by the owner on Mar 3, 2022. It is now read-only.

Commit 2088d4b

Browse files
committed
Added parameters support
1 parent 89e94bc commit 2088d4b

File tree

4 files changed

+186
-74
lines changed

4 files changed

+186
-74
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules
2-
.vscode
2+
.vscode
3+
example.js

Data.cs

Lines changed: 126 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -14,39 +14,26 @@ public class Startup
1414

1515
public async Task<object> Invoke(IDictionary<string, object> parameters)
1616
{
17-
_ConnectionString = parameters["constring"].ToString();
17+
//Convert the input parameters to a useable object.
18+
ParameterCollection pcol = new ParameterCollection(parameters);
1819

19-
if (string.IsNullOrEmpty(_ConnectionString))
20-
throw new ArgumentNullException("constring");
21-
22-
string commandString = parameters["query"].ToString();
23-
24-
if (string.IsNullOrEmpty(_ConnectionString))
25-
throw new ArgumentNullException("query");
20+
_ConnectionString = pcol.ConnectionString;
2621

27-
object commandType = null;
28-
29-
parameters.TryGetValue("type", out commandType);
30-
31-
if (commandType == null)
32-
commandType = "query";
33-
34-
string type = commandType.ToString().ToLower();
35-
36-
switch (type)
22+
//Work out which query type to execute.
23+
switch (pcol.QueryType)
3724
{
38-
case "query":
39-
return await ExecuteQuery(commandString);
40-
case "scalar":
41-
return await ExecuteScalar(commandString);
42-
case "command":
43-
return await ExecuteNonQuery(commandString);
25+
case QueryTypes.query:
26+
return await ExecuteQuery(pcol.Query, pcol.Parameters);
27+
case QueryTypes.scalar:
28+
return await ExecuteScalar(pcol.Query, pcol.Parameters);
29+
case QueryTypes.command:
30+
return await ExecuteNonQuery(pcol.Query, pcol.Parameters);
4431
default:
4532
throw new InvalidOperationException("Unsupported type of SQL command type. Only query and command are supported.");
4633
}
4734
}
4835

49-
private async Task<object> ExecuteQuery(string query)
36+
private async Task<object> ExecuteQuery(string query, object[] parameters)
5037
{
5138
OleDbConnection connection = null;
5239

@@ -60,6 +47,8 @@ private async Task<object> ExecuteQuery(string query)
6047
{
6148
List<object> results = new List<object>();
6249

50+
AddCommandParameters(command, parameters);
51+
6352
using (OleDbDataReader reader = command.ExecuteReader())
6453
{
6554
do
@@ -80,6 +69,56 @@ private async Task<object> ExecuteQuery(string query)
8069
}
8170
}
8271

72+
private async Task<object> ExecuteScalar(string query, object[] parameters)
73+
{
74+
OleDbConnection connection = null;
75+
76+
try
77+
{
78+
using (connection = new OleDbConnection(_ConnectionString))
79+
{
80+
await connection.OpenAsync();
81+
82+
using (var command = new OleDbCommand(query, connection))
83+
{
84+
AddCommandParameters(command, parameters);
85+
86+
return await command.ExecuteScalarAsync();
87+
}
88+
}
89+
}
90+
finally
91+
{
92+
if (connection != null)
93+
connection.Close();
94+
}
95+
}
96+
97+
private async Task<object> ExecuteNonQuery(string query, object[] parameters)
98+
{
99+
OleDbConnection connection = null;
100+
101+
try
102+
{
103+
using (connection = new OleDbConnection(_ConnectionString))
104+
{
105+
await connection.OpenAsync();
106+
107+
using (var command = new OleDbCommand(query, connection))
108+
{
109+
AddCommandParameters(command, parameters);
110+
111+
return await command.ExecuteNonQueryAsync();
112+
}
113+
}
114+
}
115+
finally
116+
{
117+
if (connection != null)
118+
connection.Close();
119+
}
120+
}
121+
83122
private async Task<List<object>> ParseReaderRow(OleDbDataReader reader)
84123
{
85124
List<object> rows = new List<object>();
@@ -113,45 +152,75 @@ private async Task<List<object>> ParseReaderRow(OleDbDataReader reader)
113152
return rows;
114153
}
115154

116-
private async Task<object> ExecuteScalar(string query)
155+
private void AddCommandParameters(OleDbCommand command, object[] parameters)
117156
{
118-
OleDbConnection connection = null;
119-
120-
try
157+
//Generate names for each parameter and add them to the parameter collection.
158+
for (int i = 0; i < parameters.Length; i++)
121159
{
122-
using (connection = new OleDbConnection(_ConnectionString))
123-
{
124-
await connection.OpenAsync();
160+
string name = string.Format("@p{0}", i + 1);
125161

126-
using (var command = new OleDbCommand(query, connection))
127-
return await command.ExecuteScalarAsync();
128-
}
129-
}
130-
finally
131-
{
132-
if (connection != null)
133-
connection.Close();
162+
command.Parameters.Add(new OleDbParameter(name, parameters[i]));
134163
}
135164
}
165+
}
166+
167+
public enum QueryTypes
168+
{
169+
query,
170+
scalar,
171+
command
172+
}
173+
174+
public class ParameterCollection
175+
{
176+
private IDictionary<string, object> _Raw;
136177

137-
private async Task<object> ExecuteNonQuery(string query)
178+
public string ConnectionString { get; private set; }
179+
public QueryTypes QueryType { get; private set; }
180+
public string Query { get; private set; }
181+
public object[] Parameters { get; private set; }
182+
183+
public ParameterCollection(IDictionary<string, object> parameters)
138184
{
139-
OleDbConnection connection = null;
185+
if (parameters == null)
186+
throw new ArgumentNullException("parameters");
140187

141-
try
142-
{
143-
using (connection = new OleDbConnection(_ConnectionString))
144-
{
145-
await connection.OpenAsync();
188+
_Raw = parameters;
189+
ParseRawParameters();
190+
}
146191

147-
using (var command = new OleDbCommand(query, connection))
148-
return await command.ExecuteNonQueryAsync();
149-
}
150-
}
151-
finally
152-
{
153-
if (connection != null)
154-
connection.Close();
155-
}
192+
private void ParseRawParameters()
193+
{
194+
//Extract the connection string.
195+
ConnectionString = _Raw["constring"].ToString();
196+
197+
if (string.IsNullOrEmpty(ConnectionString))
198+
throw new ArgumentNullException("constring");
199+
200+
//Extract the query
201+
Query = _Raw["query"].ToString();
202+
203+
if (string.IsNullOrEmpty(Query))
204+
throw new ArgumentNullException("query");
205+
206+
//Extract and command type (optional)
207+
object commandType = null;
208+
209+
_Raw.TryGetValue("type", out commandType);
210+
211+
if (commandType == null)
212+
commandType = "query";
213+
214+
QueryType = (QueryTypes)Enum.Parse(typeof(QueryTypes), commandType.ToString().ToLower());
215+
216+
//Extract the parameters (optional)
217+
object parameters = null;
218+
219+
_Raw.TryGetValue("params", out parameters);
220+
221+
if (parameters == null)
222+
Parameters = new object[0];
223+
224+
Parameters = (object[])parameters;
156225
}
157-
}
226+
}

README.md

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# oledb.js
22

3-
[![npm version](https://img.shields.io/badge/npm-v1.1.1-blue.svg)](https://www.npmjs.com/package/oledb)
3+
[![npm version](https://img.shields.io/badge/npm-v1.2.0-blue.svg)](https://www.npmjs.com/package/oledb)
44
[![license](https://img.shields.io/badge/license-MIT-orange.svg)](LICENSE)
55
[![tips](https://img.shields.io/badge/tips-bitcoin-brightgreen.svg)](https://www.coinbase.com/blahyourhamster)
66

@@ -13,7 +13,7 @@ const connectionString = 'provider=vfpoledb;data source=C:/MyDatabase.dbc';
1313
const oledb = require('oledb');
1414
const db = oledb(connectionString);
1515
16-
let command = 'select * from account';
16+
let command = `select * from account`;
1717
1818
db.query(command)
1919
.then(function(results) {
@@ -24,18 +24,59 @@ function(error) {
2424
});
2525
```
2626

27+
## Installation
28+
```
29+
npm install oledb --save
30+
```
31+
2732
## Promises
2833
There are 3 available promises exposed by the module:
2934

30-
- `.query(command)` - Executes a query and returns the result set returned by the query as an array.
31-
- `.execute(command)` - Executes a query command and returns the number of rows affected.
32-
- `.scalar(command)` - Executes the query and returns the first column of the first row in the result set returned by the query. All other columns and rows are ignored.
35+
- `.query(command, parameters)` - Executes a query and returns the result set returned by the query as an `Array`.
36+
- `.execute(command, parameters)` - Executes a query command and returns the number of rows affected.
37+
- `.scalar(command, parameters)` - Executes the query and returns the first column of the first row in the result set returned by the query. All other columns and rows are ignored.
3338

34-
*Where `command` is the query string.*
39+
*Where `command` is the query string and `parameters` is an array of parameter values.*
40+
41+
## Query Parameters
42+
Parameters are also supported and uses positional parameters that are marked with a question mark (?) instead of named parameters. Here is an example:
3543

36-
## Installation
3744
```
38-
npm install oledb --save
45+
let command = `
46+
select * from account
47+
where
48+
firstname = ?
49+
and id = ?
50+
`;
51+
52+
let parameters = [ 'Bob', 123 ];
53+
54+
db.query(command, parameters)
55+
.then(function(results) {
56+
console.log(results[0]);
57+
},
58+
function(error) {
59+
console.error(error);
60+
});
61+
```
62+
63+
## Multiple Data Sets
64+
OLE DB provides multiple data sets that can be returned in a single query. Here is an example:
65+
66+
```
67+
let command = `
68+
select * from account;
69+
select * from address;
70+
`;
71+
72+
db.query(command)
73+
.then(function(results) {
74+
console.log(results[0]); //1st data set
75+
console.log(results[1]); //2nd data set
76+
},
77+
function(error) {
78+
console.error(error);
79+
});
3980
```
4081

4182
## License

index.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ module.exports = function(constring) {
77

88
let connectionString = constring;
99

10-
function executePromise(command, type) {
10+
function executePromise(command, type, params) {
1111
return new Promise(function(resolve, reject) {
1212
let options = {
1313
constring: connectionString,
1414
query: command,
15-
type: type
15+
type: type,
16+
params: params || []
1617
};
1718

1819
data(options, (err, data) => {
@@ -25,14 +26,14 @@ module.exports = function(constring) {
2526
}
2627

2728
return {
28-
query: function(command) {
29-
return executePromise(command, 'query');
29+
query: function(command, params) {
30+
return executePromise(command, 'query', params);
3031
},
31-
scalar: function(command) {
32-
return executePromise(command, 'scalar');
32+
scalar: function(command, params) {
33+
return executePromise(command, 'scalar', params);
3334
},
34-
execute: function(command) {
35-
return executePromise(command, 'command');
35+
execute: function(command, params) {
36+
return executePromise(command, 'command', params);
3637
}
3738
};
3839
};

0 commit comments

Comments
 (0)