-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathDbColumnSchemaGenerator.cs
More file actions
287 lines (250 loc) · 12 KB
/
DbColumnSchemaGenerator.cs
File metadata and controls
287 lines (250 loc) · 12 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Npgsql.BackendMessages;
using Npgsql.Internal;
using Npgsql.Internal.Postgres;
using Npgsql.PostgresTypes;
using Npgsql.Util;
using NpgsqlTypes;
namespace Npgsql.Schema;
sealed class DbColumnSchemaGenerator
{
readonly RowDescriptionMessage _rowDescription;
readonly NpgsqlConnection _connection;
readonly bool _fetchAdditionalInfo;
internal DbColumnSchemaGenerator(NpgsqlConnection connection, RowDescriptionMessage rowDescription, bool fetchAdditionalInfo)
{
_connection = connection;
_rowDescription = rowDescription;
_fetchAdditionalInfo = fetchAdditionalInfo;
}
#region Columns queries
static string GenerateColumnsQuery(Version pgVersion, string columnFieldFilter) =>
$"""
SELECT
typ.oid AS typoid, nspname, relname, attname, attrelid, attnum, attnotnull,
{(pgVersion.IsGreaterOrEqual(10) ? "attidentity != ''" : "FALSE")} AS isidentity,
CASE WHEN typ.typtype = 'd' THEN typ.typtypmod ELSE atttypmod END AS typmod,
CASE WHEN atthasdef THEN (SELECT pg_get_expr(adbin, cls.oid) FROM pg_attrdef WHERE adrelid = cls.oid AND adnum = attr.attnum) ELSE NULL END AS default,
((cls.relkind = ANY (ARRAY['r'::"char", 'p'::"char"]))
OR ((cls.relkind = ANY (ARRAY['v'::"char", 'f'::"char"]))
AND pg_column_is_updatable((cls.oid)::regclass, attr.attnum, false)))
{(pgVersion.IsGreaterOrEqual(10) ? "AND attr.attidentity NOT IN ('a')" : "")}
AS is_updatable,
EXISTS (
SELECT * FROM pg_index
WHERE pg_index.indrelid = cls.oid AND
pg_index.indisprimary AND
attnum = ANY (indkey)
) AS isprimarykey,
EXISTS (
SELECT * FROM pg_index
WHERE pg_index.indrelid = cls.oid AND
pg_index.indisunique AND
pg_index.{(pgVersion.IsGreaterOrEqual(11) ? "indnkeyatts" : "indnatts")} = 1 AND
attnum = pg_index.indkey[0]
) AS isunique
FROM pg_attribute AS attr
JOIN pg_type AS typ ON attr.atttypid = typ.oid
JOIN pg_class AS cls ON cls.oid = attr.attrelid
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
WHERE
atttypid <> 0 AND
relkind IN ('r', 'v', 'm') AND
NOT attisdropped AND
nspname NOT IN ('pg_catalog', 'information_schema') AND
attnum > 0 AND
({columnFieldFilter})
ORDER BY attnum
""";
/// <summary>
/// Stripped-down version of <see cref="GenerateColumnsQuery"/>, mainly to support Amazon Redshift.
/// </summary>
static string GenerateOldColumnsQuery(string columnFieldFilter) =>
$"""
SELECT
typ.oid AS typoid, nspname, relname, attname, attrelid, attnum, attnotnull,
CASE WHEN typ.typtype = 'd' THEN typ.typtypmod ELSE atttypmod END AS typmod,
CASE WHEN atthasdef THEN (SELECT pg_get_expr(adbin, cls.oid) FROM pg_attrdef WHERE adrelid = cls.oid AND adnum = attr.attnum) ELSE NULL END AS default,
TRUE AS is_updatable, /* Supported only since PG 8.2 */
FALSE AS isprimarykey, /* Can't do ANY() on pg_index.indkey which is int2vector */
FALSE AS isunique /* Can't do ANY() on pg_index.indkey which is int2vector */
FROM pg_attribute AS attr
JOIN pg_type AS typ ON attr.atttypid = typ.oid
JOIN pg_class AS cls ON cls.oid = attr.attrelid
JOIN pg_namespace AS ns ON ns.oid = cls.relnamespace
WHERE
atttypid <> 0 AND
relkind IN ('r', 'v', 'm') AND
NOT attisdropped AND
nspname NOT IN ('pg_catalog', 'information_schema') AND
attnum > 0 AND
({columnFieldFilter})
ORDER BY attnum
""";
#endregion Column queries
internal async Task<ReadOnlyCollection<T>> GetColumnSchema<T>(bool async, CancellationToken cancellationToken = default) where T : DbColumn
{
// This is mainly for Amazon Redshift
var oldQueryMode = _connection.PostgreSqlVersion < new Version(8, 2);
var numFields = _rowDescription.Count;
var result = new List<T?>(numFields);
for (var i = 0; i < numFields; i++)
result.Add(null);
var populatedColumns = 0;
if (_fetchAdditionalInfo)
{
// We have two types of fields - those which correspond to actual database columns
// and those that don't (e.g. SELECT 8). For the former we load lots of info from
// the backend (if fetchAdditionalInfo is true), for the latter we only have the RowDescription
var filters = new List<string>();
for (var index = 0; index < _rowDescription.Count; index++)
{
var f = _rowDescription[index];
// Only column fields
if (f.TableOID != 0)
filters.Add($"(attr.attrelid={f.TableOID} AND attr.attnum={f.ColumnAttributeNumber})");
}
var columnFieldFilter = string.Join(" OR ", filters);
if (columnFieldFilter != string.Empty)
{
var query = oldQueryMode
? GenerateOldColumnsQuery(columnFieldFilter)
: GenerateColumnsQuery(_connection.PostgreSqlVersion, columnFieldFilter);
using var scope = new TransactionScope(
TransactionScopeOption.Suppress,
async ? TransactionScopeAsyncFlowOption.Enabled : TransactionScopeAsyncFlowOption.Suppress);
using var connection = (NpgsqlConnection)((ICloneable)_connection).Clone();
await connection.Open(async, cancellationToken).ConfigureAwait(false);
using var cmd = new NpgsqlCommand(query, connection);
var reader = await cmd.ExecuteReader(async, CommandBehavior.Default, cancellationToken).ConfigureAwait(false);
try
{
while (async ? await reader.ReadAsync(cancellationToken).ConfigureAwait(false) : reader.Read())
{
var column = LoadColumnDefinition(reader, _connection.Connector!.DatabaseInfo, oldQueryMode);
for (var ordinal = 0; ordinal < numFields; ordinal++)
{
var field = _rowDescription[ordinal];
if (field.TableOID == column.TableOID &&
field.ColumnAttributeNumber == column.ColumnAttributeNumber)
{
populatedColumns++;
if (column.ColumnOrdinal.HasValue)
column = column.Clone();
// The column's ordinal is with respect to the resultset, not its table
column.ColumnOrdinal = ordinal;
result[ordinal] = (T?)(object)column;
}
}
}
}
finally
{
if (async)
await reader.DisposeAsync().ConfigureAwait(false);
else
reader.Dispose();
}
}
}
// We had some fields which don't correspond to regular table columns (or fetchAdditionalInfo is false).
// Fill in whatever info we have from the RowDescription itself
for (var i = 0; i < numFields; i++)
{
var column = (NpgsqlDbColumn?)(object?)result[i];
var field = _rowDescription[i];
if (column is null)
{
column = SetUpNonColumnField(field);
column.ColumnOrdinal = i;
result[i] = (T?)(object)column;
populatedColumns++;
}
column.ColumnName = field.Name;
column.IsAliased = column.BaseColumnName is null ? default(bool?) : (column.BaseColumnName != column.ColumnName);
}
if (populatedColumns != numFields)
throw new NpgsqlException("Could not load all columns for the resultset");
return result.AsReadOnly()!;
}
NpgsqlDbColumn LoadColumnDefinition(NpgsqlDataReader reader, NpgsqlDatabaseInfo databaseInfo, bool oldQueryMode)
{
// We don't set ColumnName here. It should always contain the column alias rather than
// the table column name (i.e. in case of "SELECT foo AS foo_alias"). It will be set later.
var column = new NpgsqlDbColumn
{
AllowDBNull = !reader.GetBoolean(reader.GetOrdinal("attnotnull")),
BaseCatalogName = _connection.Database!,
BaseSchemaName = reader.GetString(reader.GetOrdinal("nspname")),
BaseServerName = _connection.Host!,
BaseTableName = reader.GetString(reader.GetOrdinal("relname")),
BaseColumnName = reader.GetString(reader.GetOrdinal("attname")),
ColumnAttributeNumber = reader.GetInt16(reader.GetOrdinal("attnum")),
IsKey = reader.GetBoolean(reader.GetOrdinal("isprimarykey")),
IsReadOnly = !reader.GetBoolean(reader.GetOrdinal("is_updatable")),
IsUnique = reader.GetBoolean(reader.GetOrdinal("isunique")),
TableOID = reader.GetFieldValue<uint>(reader.GetOrdinal("attrelid")),
TypeOID = reader.GetFieldValue<uint>(reader.GetOrdinal("typoid"))
};
column.PostgresType = databaseInfo.ByOID[column.TypeOID];
column.DataTypeName = column.PostgresType.DisplayName; // Facets do not get included
var defaultValueOrdinal = reader.GetOrdinal("default");
column.DefaultValue = reader.IsDBNull(defaultValueOrdinal) ? null : reader.GetString(defaultValueOrdinal);
column.IsIdentity = !oldQueryMode && reader.GetBoolean(reader.GetOrdinal("isidentity"));
// Use a heuristic to discover old SERIAL columns
column.IsAutoIncrement =
column.IsIdentity == true ||
column.DefaultValue != null && column.DefaultValue.StartsWith("nextval(", StringComparison.Ordinal);
ColumnPostConfig(column, reader.GetInt32(reader.GetOrdinal("typmod")));
return column;
}
NpgsqlDbColumn SetUpNonColumnField(FieldDescription field)
{
// ColumnName and BaseColumnName will be set later
var column = new NpgsqlDbColumn
{
BaseCatalogName = _connection.Database!,
BaseServerName = _connection.Host!,
IsReadOnly = true,
DataTypeName = field.PostgresType.DisplayName,
TypeOID = field.TypeOID,
TableOID = field.TableOID,
ColumnAttributeNumber = field.ColumnAttributeNumber,
PostgresType = field.PostgresType
};
ColumnPostConfig(column, field.TypeModifier);
return column;
}
/// <summary>
/// Performs some post-setup configuration that's common to both table columns and non-columns.
/// </summary>
void ColumnPostConfig(NpgsqlDbColumn column, int typeModifier)
{
var serializerOptions = _connection.Connector!.SerializerOptions;
// Call GetRepresentationalType to also handle domain types
// Because NpgsqlCommandBuilder relies on NpgsqlDbType for correct type mapping
// And otherwise we'll get NpgsqlDbType.Unknown
column.NpgsqlDbType = column.PostgresType.GetRepresentationalType().DataTypeName.ToNpgsqlDbType();
if (serializerOptions.GetTypeInfo(typeof(object), serializerOptions.ToCanonicalTypeId(column.PostgresType)) is { } typeInfo)
{
column.DataType = typeInfo.Type;
column.IsLong = column.PostgresType.DataTypeName == DataTypeNames.Bytea;
if (column.PostgresType is PostgresCompositeType)
column.UdtAssemblyQualifiedName = typeInfo.Type.AssemblyQualifiedName;
}
var facets = column.PostgresType.GetFacets(typeModifier);
if (facets.Size != null)
column.ColumnSize = facets.Size;
if (facets.Precision != null)
column.NumericPrecision = facets.Precision;
if (facets.Scale != null)
column.NumericScale = facets.Scale;
}
}