File: SchemaLoader.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (453 lines) | stat: -rw-r--r-- 20,467 bytes parent folder | download
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#region MIT license
// 
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

#if MONO_STRICT
using System.Data.Linq;
#else
using DbLinq.Data.Linq;
#endif

using DbLinq.Factory;
using DbLinq.Schema;
using DbLinq.Schema.Dbml;
using System.Text.RegularExpressions;

namespace DbLinq.Vendor.Implementation
{
#if !MONO_STRICT
    public
#endif
    abstract partial class SchemaLoader : ISchemaLoader
    {
        /// <summary>
        /// Underlying vendor
        /// </summary>
        /// <value></value>
        public abstract IVendor Vendor { get; set; }
        /// <summary>
        /// Connection used to read schema
        /// </summary>
        /// <value></value>
        public IDbConnection Connection { get; set; }
        /// <summary>
        /// Gets or sets the name formatter.
        /// </summary>
        /// <value>The name formatter.</value>
        public INameFormatter NameFormatter { get; set; }

        private TextWriter log;
        /// <summary>
        /// Log output
        /// </summary>
        public TextWriter Log
        {
            get { return log ?? Console.Out; }
            set { log = value; }
        }

        /// <summary>
        /// Loads database schema
        /// </summary>
        /// <param name="databaseName"></param>
        /// <param name="nameAliases"></param>
        /// <param name="nameFormat"></param>
        /// <param name="loadStoredProcedures"></param>
        /// <param name="contextNamespace"></param>
        /// <param name="entityNamespace"></param>
        /// <returns></returns>
        public virtual Database Load(string databaseName, INameAliases nameAliases, NameFormat nameFormat,
            bool loadStoredProcedures, string contextNamespace, string entityNamespace)
        {
            // check if connection is open. Note: we may use something more flexible
            if (Connection.State != ConnectionState.Open)
                Connection.Open();

            // get the database name. If we don't have one, take it from connection string...
            if (string.IsNullOrEmpty(databaseName))
                databaseName = Connection.Database;
            // ... and if connection string doesn't provide a name, then throw an error
            if (string.IsNullOrEmpty(databaseName))
                throw new ArgumentException("A database name is required. Please specify /database=<databaseName>");

            databaseName = GetDatabaseNameAliased(databaseName, nameAliases);

            var schemaName = NameFormatter.GetSchemaName(databaseName, GetExtraction(databaseName), nameFormat);
            var names = new Names();
            var schema = new Database
                             {
                                 Name = schemaName.DbName,
                                 Class = GetRuntimeClassName(schemaName.ClassName, nameAliases),
                                 BaseType = typeof(DataContext).FullName,
                                 ContextNamespace = contextNamespace,
                                 EntityNamespace = entityNamespace,
                             };

            // order is important, we must have:
            // 1. tables
            // 2. columns
            // 3. constraints
            LoadTables(schema, schemaName, Connection, nameAliases, nameFormat, names);
            LoadColumns(schema, schemaName, Connection, nameAliases, nameFormat, names);
            CheckColumnsName(schema);
            LoadConstraints(schema, schemaName, Connection, nameFormat, names);
            CheckConstraintsName(schema);
            if (loadStoredProcedures)
                LoadStoredProcedures(schema, schemaName, Connection, nameFormat);
            // names aren't checked here anymore, because this confuses DBML editor.
            // they will (for now) be checked before .cs generation
            // in the end, when probably will end up in mapping source (or somewhere around)
            //CheckNamesSafety(schema);

            // generate backing fields name (since we have here correct names)
            GenerateStorageAndMemberFields(schema);

            return schema;
        }

        /// <summary>
        /// Gets a usable name for the database.
        /// </summary>
        /// <param name="databaseName">Name of the database.</param>
        /// <returns></returns>
        protected virtual string GetDatabaseName(string databaseName)
        {
            return databaseName;
        }

        protected virtual string GetDatabaseNameAliased(string databaseName, INameAliases nameAliases)
        {
            string databaseNameAliased = nameAliases != null ? nameAliases.GetDatabaseNameAlias(databaseName) : null;
            return (databaseNameAliased != null) ? databaseNameAliased : GetDatabaseName(databaseName);
        }

        /// <summary>
        /// Gets a usable name for the database class.
        /// </summary>
        /// <param name="databaseName">Name of the clas.</param>
        /// <returns></returns>
        protected virtual string GetRuntimeClassName(string className, INameAliases nameAliases)
        {
            string classNameAliased = nameAliases != null ? nameAliases.GetClassNameAlias(className) : null;
            return (classNameAliased != null) ? classNameAliased : className;
        }

        /// <summary>
        /// Writes an error line.
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="arg">The arg.</param>
        protected void WriteErrorLine(string format, params object[] arg)
        {
            var o = Log;
            if (o == Console.Out)
                o = Console.Error;
            o.WriteLine(format, arg);
        }

        protected SchemaLoader()
        {
            NameFormatter = ObjectFactory.Create<INameFormatter>(); // the Pluralize property is set dynamically, so no singleton
        }

        /// <summary>
        /// Gets the extraction type from a columnname.
        /// </summary>
        /// <param name="dbColumnName">Name of the db column.</param>
        /// <returns></returns>
        protected virtual WordsExtraction GetExtraction(string dbColumnName)
        {
            bool isMixedCase = dbColumnName != dbColumnName.ToLower() && dbColumnName != dbColumnName.ToUpper();
            return isMixedCase ? WordsExtraction.FromCase : WordsExtraction.FromDictionary;
        }

        /// <summary>
        /// Gets the full name of a name and schema.
        /// </summary>
        /// <param name="dbName">Name of the db.</param>
        /// <param name="dbSchema">The db schema.</param>
        /// <returns></returns>
        protected virtual string GetFullDbName(string dbName, string dbSchema)
        {
            string fullDbName;
            if (dbSchema == null)
                fullDbName = dbName;
            else
                fullDbName = string.Format("{0}.{1}", dbSchema, dbName);
            return fullDbName;
        }

        /// <summary>
        /// Creates the name of the table given a name and schema
        /// </summary>
        /// <param name="dbTableName">Name of the db table.</param>
        /// <param name="dbSchema">The db schema.</param>
        /// <param name="nameAliases">The name aliases.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <param name="extraction">The extraction.</param>
        /// <returns></returns>
        protected virtual TableName CreateTableName(string dbTableName, string dbSchema, INameAliases nameAliases, NameFormat nameFormat, WordsExtraction extraction)
        {
            // if we have an alias, use it, and don't try to analyze it (a human probably already did the job)
            var tableTypeAlias = nameAliases != null ? nameAliases.GetTableTypeAlias(dbTableName, dbSchema) : null;
            if (tableTypeAlias != null)
                extraction = WordsExtraction.None;
            else
                tableTypeAlias = dbTableName;

            var tableName = NameFormatter.GetTableName(tableTypeAlias, extraction, nameFormat);

            // alias for member
            var tableMemberAlias = nameAliases != null ? nameAliases.GetTableMemberAlias(dbTableName, dbSchema) : null;
            if (tableMemberAlias != null)
                tableName.MemberName = tableMemberAlias;

            tableName.DbName = GetFullDbName(dbTableName, dbSchema);
            return tableName;
        }

        protected virtual TableName CreateTableName(string dbTableName, string dbSchema, INameAliases nameAliases, NameFormat nameFormat)
        {
            return CreateTableName(dbTableName, dbSchema, nameAliases, nameFormat, GetExtraction(dbTableName));
        }

        Regex startsWithNumber = new Regex(@"^\d", RegexOptions.Compiled);

        /// <summary>
        /// Creates the name of the column.
        /// </summary>
        /// <param name="dbColumnName">Name of the db column.</param>
        /// <param name="dbTableName">Name of the db table.</param>
        /// <param name="dbSchema">The db schema.</param>
        /// <param name="nameAliases">The name aliases.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <returns></returns>
        protected virtual ColumnName CreateColumnName(string dbColumnName, string dbTableName, string dbSchema, INameAliases nameAliases, NameFormat nameFormat)
        {
            var columnNameAlias = nameAliases != null ? nameAliases.GetColumnMemberAlias(dbColumnName, dbTableName, dbSchema) : null;
            WordsExtraction extraction;
            if (columnNameAlias != null)
            {
                extraction = WordsExtraction.None;
            }
            else
            {
                extraction = GetExtraction(dbColumnName);
                columnNameAlias = dbColumnName;
            }
            var columnName = NameFormatter.GetColumnName(columnNameAlias, extraction, nameFormat);
            // The member name can not be the same as the class
            // we add a "1" (just like SqlMetal does)
            var tableName = CreateTableName(dbTableName, dbSchema, nameAliases, nameFormat);
            if (columnName.PropertyName == tableName.ClassName)
                columnName.PropertyName = columnName.PropertyName + "1";

            if (startsWithNumber.IsMatch(columnName.PropertyName))
                columnName.PropertyName = "_" + columnName.PropertyName;

            columnName.DbName = dbColumnName;
            return columnName;
        }

        /// <summary>
        /// Creates the name of the procedure.
        /// </summary>
        /// <param name="dbProcedureName">Name of the db procedure.</param>
        /// <param name="dbSchema">The db schema.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <returns></returns>
        protected virtual ProcedureName CreateProcedureName(string dbProcedureName, string dbSchema, NameFormat nameFormat)
        {
            var procedureName = NameFormatter.GetProcedureName(dbProcedureName, GetExtraction(dbProcedureName), nameFormat);
            procedureName.DbName = GetFullDbName(dbProcedureName, dbSchema);
            return procedureName;
        }

        /// <summary>
        /// Creates the name of the association.
        /// </summary>
        /// <param name="dbManyName">Name of the db many.</param>
        /// <param name="dbManySchema">The db many schema.</param>
        /// <param name="dbOneName">Name of the db one.</param>
        /// <param name="dbOneSchema">The db one schema.</param>
        /// <param name="dbConstraintName">Name of the db constraint.</param>
        /// <param name="foreignKeyName">Name of the foreign key.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <returns></returns>
        protected virtual AssociationName CreateAssociationName(string dbManyName, string dbManySchema,
            string dbOneName, string dbOneSchema, string dbConstraintName, string foreignKeyName, NameFormat nameFormat)
        {
            var associationName = NameFormatter.GetAssociationName(dbManyName, dbOneName,
                dbConstraintName, foreignKeyName, GetExtraction(dbManyName), nameFormat);
            associationName.DbName = GetFullDbName(dbManyName, dbManySchema);
            return associationName;
        }

        /// <summary>
        /// Creates the name of the schema.
        /// </summary>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="connection">The connection.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <returns></returns>
        protected virtual SchemaName CreateSchemaName(string databaseName, IDbConnection connection, NameFormat nameFormat)
        {
            if (string.IsNullOrEmpty(databaseName))
            {
                databaseName = connection.Database;
                if (string.IsNullOrEmpty(databaseName))
                    throw new ArgumentException("Could not deduce database name from connection string. Please specify /database=<databaseName>");
            }
            return NameFormatter.GetSchemaName(databaseName, GetExtraction(databaseName), nameFormat);
        }

        protected virtual ParameterName CreateParameterName(string dbParameterName, NameFormat nameFormat)
        {
            var parameterName = NameFormatter.GetParameterName(dbParameterName, GetExtraction(dbParameterName), nameFormat);
            return parameterName;
        }

        protected class Names
        {
            public IDictionary<string, TableName> TablesNames = new Dictionary<string, TableName>();
            public IDictionary<string, IDictionary<string, ColumnName>> ColumnsNames = new Dictionary<string, IDictionary<string, ColumnName>>();

            public void AddColumn(string dbTableName, ColumnName columnName)
            {
                IDictionary<string, ColumnName> columns;
                if (!ColumnsNames.TryGetValue(dbTableName, out columns))
                {
                    columns = new Dictionary<string, ColumnName>();
                    ColumnsNames[dbTableName] = columns;
                }
                columns[columnName.DbName] = columnName;
            }
        }

        /// <summary>
        /// Loads the tables in the given schema.
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaName">Name of the schema.</param>
        /// <param name="conn">The conn.</param>
        /// <param name="nameAliases">The name aliases.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <param name="names">The names.</param>
        protected virtual void LoadTables(Database schema, SchemaName schemaName, IDbConnection conn, INameAliases nameAliases, NameFormat nameFormat, Names names)
        {
            var tables = ReadTables(conn, schemaName.DbName);
            foreach (var row in tables)
            {
                var tableName = CreateTableName(row.Name, row.Schema, nameAliases, nameFormat);
                names.TablesNames[tableName.DbName] = tableName;

                var table = new Table();
                table.Name = tableName.DbName;
                table.Member = tableName.MemberName;
                table.Type.Name = tableName.ClassName;
                schema.Tables.Add(table);
            }
        }

        /// <summary>
        /// Loads the columns.
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaName">Name of the schema.</param>
        /// <param name="conn">The conn.</param>
        /// <param name="nameAliases">The name aliases.</param>
        /// <param name="nameFormat">The name format.</param>
        /// <param name="names">The names.</param>
        protected void LoadColumns(Database schema, SchemaName schemaName, IDbConnection conn, INameAliases nameAliases, NameFormat nameFormat, Names names)
        {
            var columnRows = ReadColumns(conn, schemaName.DbName);
            foreach (var columnRow in columnRows)
            {
                var columnName = CreateColumnName(columnRow.ColumnName, columnRow.TableName, columnRow.TableSchema, nameAliases, nameFormat);
                names.AddColumn(columnRow.TableName, columnName);

                //find which table this column belongs to
                string fullColumnDbName = GetFullDbName(columnRow.TableName, columnRow.TableSchema);
                DbLinq.Schema.Dbml.Table tableSchema = schema.Tables.FirstOrDefault(tblSchema => fullColumnDbName == tblSchema.Name);
                if (tableSchema == null)
                {
                    WriteErrorLine("ERROR L46: Table '" + columnRow.TableName + "' not found for column " + columnRow.ColumnName);
                    continue;
                }
                var column = new Column();
                column.Name = columnName.DbName;
                column.Member = columnName.PropertyName;
                column.DbType = columnRow.FullType;

                if (columnRow.PrimaryKey.HasValue)
                    column.IsPrimaryKey = columnRow.PrimaryKey.Value;

                bool? generated = (nameAliases != null) ? nameAliases.GetColumnGenerated(columnRow.ColumnName, columnRow.TableName, columnRow.TableSchema) : null;
                if (!generated.HasValue)
                    generated = columnRow.Generated;
                if (generated.HasValue)
                    column.IsDbGenerated = generated.Value;

                AutoSync? autoSync = (nameAliases != null) ? nameAliases.GetColumnAutoSync(columnRow.ColumnName, columnRow.TableName, columnRow.TableSchema) : null;
                if (autoSync.HasValue)
                    column.AutoSync = autoSync.Value;

                // the Expression can originate from two sources:
                // 1. DefaultValue
                // 2. Expression
                // we use any valid source (we can't have both)
                if (column.IsDbGenerated && columnRow.DefaultValue != null)
                    column.Expression = columnRow.DefaultValue;

                column.CanBeNull = columnRow.Nullable;

                string columnTypeAlias = nameAliases != null ? nameAliases.GetColumnForcedType(columnRow.ColumnName, columnRow.TableName, columnRow.TableSchema) : null;
                var columnType = MapDbType(columnName.DbName, columnRow);

                var columnEnumType = columnType as EnumType;
                if (columnEnumType != null)
                {
                    var enumType = column.SetExtendedTypeAsEnumType();
                    enumType.Name = columnEnumType.Name;
                    foreach (KeyValuePair<string, int> enumValue in columnEnumType.EnumValues)
                    {
                        enumType[enumValue.Key] = enumValue.Value;
                    }
                }
                else if (columnTypeAlias != null)
                    column.Type = columnTypeAlias;
                else
                    column.Type = columnType.ToString();

                tableSchema.Type.Columns.Add(column);
            }
        }
    }
}