forked from ThatRendle/Simple.Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlSchemaProvider.cs
More file actions
192 lines (163 loc) · 7.58 KB
/
SqlSchemaProvider.cs
File metadata and controls
192 lines (163 loc) · 7.58 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Simple.Data.Ado;
using Simple.Data.Ado.Schema;
namespace Simple.Data.SqlServer
{
class SqlSchemaProvider : ISchemaProvider
{
private readonly IConnectionProvider _connectionProvider;
public SqlSchemaProvider(IConnectionProvider connectionProvider)
{
if (connectionProvider == null) throw new ArgumentNullException("connectionProvider");
_connectionProvider = connectionProvider;
}
public IConnectionProvider ConnectionProvider
{
get { return _connectionProvider; }
}
public IEnumerable<Table> GetTables()
{
return GetSchema("TABLES").Select(SchemaRowToTable);
}
private static Table SchemaRowToTable(DataRow row)
{
return new Table(row["TABLE_NAME"].ToString(), row["TABLE_SCHEMA"].ToString(),
row["TABLE_TYPE"].ToString() == "BASE TABLE" ? TableType.Table : TableType.View);
}
public IEnumerable<Column> GetColumns(Table table)
{
if (table == null) throw new ArgumentNullException("table");
var cols = GetColumnsDataTable(table);
return cols.AsEnumerable().Select(row => SchemaRowToColumn(table, row));
}
private static Column SchemaRowToColumn(Table table, DataRow row)
{
return new SqlColumn(row["name"].ToString(), table, (bool) row["is_identity"],
DbTypeFromInformationSchemaTypeName((string) row["type_name"]), (short) row["max_length"]);
}
public IEnumerable<Procedure> GetStoredProcedures()
{
return GetSchema("Procedures").Select(SchemaRowToStoredProcedure);
}
private IEnumerable<DataRow> GetSchema(string collectionName, params string[] constraints)
{
using (var cn = ConnectionProvider.CreateConnection())
{
cn.Open();
return cn.GetSchema(collectionName, constraints).AsEnumerable();
}
}
private static Procedure SchemaRowToStoredProcedure(DataRow row)
{
return new Procedure(row["ROUTINE_NAME"].ToString(), row["SPECIFIC_NAME"].ToString(), row["ROUTINE_SCHEMA"].ToString());
}
public IEnumerable<Parameter> GetParameters(Procedure storedProcedure)
{
// GetSchema does not return the return value of e.g. a stored proc correctly,
// i.e. there isn't sufficient information to correctly set up a stored proc.
using (var connection = (SqlConnection)ConnectionProvider.CreateConnection())
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storedProcedure.SpecificName;
connection.Open();
SqlCommandBuilder.DeriveParameters(command);
foreach (SqlParameter p in command.Parameters)
yield return new Parameter(p.ParameterName, SqlTypeResolver.GetClrType(p.DbType.ToString()), p.Direction);
}
}
}
public Key GetPrimaryKey(Table table)
{
if (table == null) throw new ArgumentNullException("table");
return new Key(GetPrimaryKeys(table.ActualName).AsEnumerable()
.Where(
row =>
row["TABLE_SCHEMA"].ToString() == table.Schema && row["TABLE_NAME"].ToString() == table.ActualName)
.OrderBy(row => (int)row["ORDINAL_POSITION"])
.Select(row => row["COLUMN_NAME"].ToString()));
}
public IEnumerable<ForeignKey> GetForeignKeys(Table table)
{
if (table == null) throw new ArgumentNullException("table");
var groups = GetForeignKeys(table.ActualName)
.Where(row =>
row["TABLE_SCHEMA"].ToString() == table.Schema && row["TABLE_NAME"].ToString() == table.ActualName)
.GroupBy(row => row["CONSTRAINT_NAME"].ToString())
.ToList();
foreach (var group in groups)
{
yield return new ForeignKey(new ObjectName(group.First()["TABLE_SCHEMA"].ToString(), group.First()["TABLE_NAME"].ToString()),
group.Select(row => row["COLUMN_NAME"].ToString()),
new ObjectName(group.First()["UNIQUE_TABLE_SCHEMA"].ToString(), group.First()["UNIQUE_TABLE_NAME"].ToString()),
group.Select(row => row["UNIQUE_COLUMN_NAME"].ToString()));
}
}
public string QuoteObjectName(string unquotedName)
{
if (unquotedName == null) throw new ArgumentNullException("unquotedName");
if (unquotedName.StartsWith("[")) return unquotedName;
return string.Concat("[", unquotedName, "]");
}
public string NameParameter(string baseName)
{
if (baseName == null) throw new ArgumentNullException("baseName");
if (baseName.Length == 0) throw new ArgumentException("Base name must be provided");
return (baseName.StartsWith("@")) ? baseName : "@" + baseName;
}
public Type DataTypeToClrType(string dataType)
{
return SqlTypeResolver.GetClrType(dataType);
}
private DataTable GetColumnsDataTable(Table table)
{
var columnSelect =
string.Format(
"SELECT name, is_identity, type_name(system_type_id) as type_name, max_length from sys.columns where object_id = object_id('{0}.{1}', 'TABLE') or object_id = object_id('{0}.{1}', 'VIEW') order by column_id",
table.Schema, table.ActualName);
return SelectToDataTable(columnSelect);
}
private DataTable GetPrimaryKeys()
{
return SelectToDataTable(Properties.Resources.PrimaryKeySql);
}
private DataTable GetForeignKeys()
{
return SelectToDataTable(Properties.Resources.ForeignKeysSql);
}
private DataTable GetPrimaryKeys(string tableName)
{
return GetPrimaryKeys().AsEnumerable()
.Where(
row => row["TABLE_NAME"].ToString().Equals(tableName, StringComparison.InvariantCultureIgnoreCase))
.CopyToDataTable();
}
private EnumerableRowCollection<DataRow> GetForeignKeys(string tableName)
{
return GetForeignKeys().AsEnumerable()
.Where(
row => row["TABLE_NAME"].ToString().Equals(tableName, StringComparison.InvariantCultureIgnoreCase));
}
private DataTable SelectToDataTable(string sql)
{
var dataTable = new DataTable();
using (var cn = ConnectionProvider.CreateConnection() as SqlConnection)
{
using (var adapter = new SqlDataAdapter(sql, cn))
{
adapter.Fill(dataTable);
}
}
return dataTable;
}
private static SqlDbType DbTypeFromInformationSchemaTypeName(string informationSchemaTypeName)
{
return DbTypeLookup.GetSqlDbType(informationSchemaTypeName);
}
}
}