/
202_sql.csx
98 lines (88 loc) · 3.64 KB
/
202_sql.csx
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
// Overview of edge.js: http://tjanczuk.github.com/edge
//#r "System.dll"
//#r "System.Data.dll"
//#r "System.Web.Extensions.dll"
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
public class Startup
{
public async Task<object> Invoke(string command)
{
string connectionString = Environment.GetEnvironmentVariable("OWIN_SQL_CONNECTION_STRING");
if (command.StartsWith("select ", StringComparison.InvariantCultureIgnoreCase))
{
return await this.ExecuteQuery(connectionString, command);
}
else if (command.StartsWith("insert ", StringComparison.InvariantCultureIgnoreCase)
|| command.StartsWith("update ", StringComparison.InvariantCultureIgnoreCase)
|| command.StartsWith("delete ", StringComparison.InvariantCultureIgnoreCase))
{
return await this.ExecuteNonQuery(connectionString, command);
}
else
{
throw new InvalidOperationException("Unsupported type of SQL command. Only select, insert, update, and delete are supported.");
}
}
async Task<object> ExecuteQuery(string connectionString, string commandString)
{
List<object> rows = new List<object>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandString, connection))
{
await connection.OpenAsync();
using (SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection))
{
object[] fieldNames = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
fieldNames[i] = reader.GetName(i);
}
rows.Add(fieldNames);
IDataRecord record = (IDataRecord)reader;
while (await reader.ReadAsync())
{
object[] resultRecord = new object[record.FieldCount];
record.GetValues(resultRecord);
for (int i = 0; i < record.FieldCount; i++)
{
Type type = record.GetFieldType(i);
if (type == typeof(byte[]) || type == typeof(char[]))
{
resultRecord[i] = Convert.ToBase64String((byte[])resultRecord[i]);
}
else if (type == typeof(Guid) || type == typeof(DateTime))
{
resultRecord[i] = resultRecord[i].ToString();
}
else if (type == typeof(IDataReader))
{
resultRecord[i] = "<IDataReader>";
}
}
rows.Add(resultRecord);
}
}
}
}
return rows;
}
async Task<object> ExecuteNonQuery(string connectionString, string commandString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandString, connection))
{
await connection.OpenAsync();
return await command.ExecuteNonQueryAsync();
}
}
}
}