Datei: StressTests/StressTest/TestDatabase.cs
Last Commit (ab290a4)
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Data; |
| 4 | using System.Data.Common; |
| 5 | using System.IO; |
| 6 | using System.Linq; |
| 7 | using System.Text; |
| 8 | using System.Threading; |
| 9 | using System.Threading.Tasks; |
| 10 | using System.Xml.Linq; |
| 11 | using NDO; |
| 12 | using NDO.Mapping; |
| 13 | using NDO.ProviderFactory; |
| 14 | using NDOInterfaces; |
| 15 | using StressTestClasses; |
| 16 | |
| 17 | namespace StressTest |
| 18 | { |
| 19 | ····/// <summary> |
| 20 | ····/// Provides PersistenceManager instances for the configured provider and creates the database schema. |
| 21 | ····/// </summary> |
| 22 | ····/// <remarks> |
| 23 | ····/// The mapping file of StressTestClasses contains a dummy connection. It is copied to a provider specific |
| 24 | ····/// mapping file, in which the connection type and connection string are replaced by the configured values. |
| 25 | ····/// The tables are generated with the ISqlGenerator of the provider from the DataSet, which NDO builds from the mapping. |
| 26 | ····/// In addition to the tables, indexes for the foreign keys and the search columns are created. |
| 27 | ····/// </remarks> |
| 28 | ····public class TestDatabase |
| 29 | ····{ |
| 30 | ········readonly StressTestOptions options; |
| 31 | ········readonly NDOMapping sharedMapping; |
| 32 | |
| 33 | ········public string MappingFile { get; } |
| 34 | |
| 35 | ········public TestDatabase( StressTestOptions options ) |
| 36 | ········{ |
| 37 | ············this.options = options; |
| 38 | |
| 39 | ············var mappingSource = Path.Combine( AppContext.BaseDirectory, "StressTestClasses.NDOMapping.xml" ); |
| 40 | ············XDocument doc = XDocument.Load( mappingSource ); |
| 41 | ············foreach (var conn in doc.Descendants( "Connection" )) |
| 42 | ············{ |
| 43 | ················conn.SetAttributeValue( "Type", options.Provider ); |
| 44 | ················conn.SetAttributeValue( "Name", options.ConnectionString ); |
| 45 | ············} |
| 46 | ············MappingFile = Path.Combine( AppContext.BaseDirectory, $"NDOMapping.{options.Provider}.xml" ); |
| 47 | ············doc.Save( MappingFile ); |
| 48 | |
| 49 | ············if (options.SharedMapping) |
| 50 | ············{ |
| 51 | ················// The mapping object stays valid after the PersistenceManager is closed. |
| 52 | ················using (var pm = new PersistenceManager( MappingFile )) |
| 53 | ····················this.sharedMapping = pm.NDOMapping; |
| 54 | ············} |
| 55 | ········} |
| 56 | |
| 57 | ········/// <summary> |
| 58 | ········/// Creates a new PersistenceManager. Each worker must use its own instances. |
| 59 | ········/// </summary> |
| 60 | ········public PersistenceManager NewPersistenceManager() |
| 61 | ········{ |
| 62 | ············var pm = this.sharedMapping != null |
| 63 | ················? new PersistenceManager( this.sharedMapping ) |
| 64 | ················: new PersistenceManager( MappingFile ); |
| 65 | ············pm.TransactionMode = this.options.TransactionMode; |
| 66 | ············if (this.options.IsolationLevel.HasValue) |
| 67 | ················pm.IsolationLevel = this.options.IsolationLevel.Value; |
| 68 | ············return pm; |
| 69 | ········} |
| 70 | |
| 71 | ········IProvider GetProvider( PersistenceManager pm, out ISqlGenerator generator ) |
| 72 | ········{ |
| 73 | ············Connection conn = pm.NDOMapping.Connections.First(); |
| 74 | ············IProvider provider = pm.NDOMapping.GetProvider( conn ); |
| 75 | ············if (provider == null) |
| 76 | ················throw new Exception( $"Provider '{this.options.Provider}' not found. Available providers: {String.Join( ", ", NDOProviderFactory.Instance.ProviderNames )}" ); |
| 77 | ············if (!NDOProviderFactory.Instance.Generators.TryGetValue( this.options.Provider, out generator )) |
| 78 | ················throw new Exception( $"No ISqlGenerator for provider '{this.options.Provider}' found." ); |
| 79 | ············generator.Provider = provider; |
| 80 | ············return provider; |
| 81 | ········} |
| 82 | |
| 83 | ········/// <summary> |
| 84 | ········/// Quotes a table name, which might contain a schema name. |
| 85 | ········/// </summary> |
| 86 | ········static string QualifiedTableName( IProvider provider, string name ) |
| 87 | ········{ |
| 88 | ············return String.Join( ".", name.Split( '.' ).Select( n => provider.GetQuotedName( n ) ) ); |
| 89 | ········} |
| 90 | |
| 91 | ········static string UnqualifiedName( string name ) |
| 92 | ········{ |
| 93 | ············int p = name.LastIndexOf( '.' ); |
| 94 | ············if (p > -1) |
| 95 | ················name = name.Substring( p + 1 ); |
| 96 | ············return name.Trim( '"', '`', '[', ']' ); |
| 97 | ········} |
| 98 | |
| 99 | ········async Task<HashSet<string>> GetExistingTablesAsync( IProvider provider, CancellationToken ct ) |
| 100 | ········{ |
| 101 | ············using (DbConnection conn = provider.NewConnection( this.options.ConnectionString )) |
| 102 | ············{ |
| 103 | ················await conn.OpenAsync( ct ); |
| 104 | ················return new HashSet<string>( provider.GetTableNames( conn ).Select( UnqualifiedName ), StringComparer.OrdinalIgnoreCase ); |
| 105 | ············} |
| 106 | ········} |
| 107 | |
| 108 | ········/// <summary> |
| 109 | ········/// Executes each statement in its own transaction. |
| 110 | ········/// </summary> |
| 111 | ········async Task ExecuteAsync( string sql, CancellationToken ct ) |
| 112 | ········{ |
| 113 | ············// Some databases (e.g. Oracle) don't accept the statement terminator in a command |
| 114 | ············sql = sql.Trim().TrimEnd( ';' ); |
| 115 | ············await using (var pm = NewPersistenceManager()) |
| 116 | ············await using (var handler = pm.GetSqlPassThroughHandler()) |
| 117 | ············{ |
| 118 | ················await handler.ExecuteAsync( sql, false, null, ct ); |
| 119 | ················await handler.CommitTransactionAsync( ct ); |
| 120 | ············} |
| 121 | ········} |
| 122 | |
| 123 | ········public async Task DropSchemaAsync( CancellationToken ct = default ) |
| 124 | ········{ |
| 125 | ············await using (var pm = NewPersistenceManager()) |
| 126 | ············{ |
| 127 | ················IProvider provider = GetProvider( pm, out ISqlGenerator generator ); |
| 128 | ················var existing = await GetExistingTablesAsync( provider, ct ); |
| 129 | ················foreach (DataTable dt in pm.DataSet.Tables) |
| 130 | ················{ |
| 131 | ····················if (existing.Contains( UnqualifiedName( dt.TableName ) )) |
| 132 | ························await ExecuteAsync( generator.DropTable( QualifiedTableName( provider, dt.TableName ) ), ct ); |
| 133 | ················} |
| 134 | ············} |
| 135 | ········} |
| 136 | |
| 137 | ········public async Task CreateSchemaAsync( CancellationToken ct = default ) |
| 138 | ········{ |
| 139 | ············await using (var pm = NewPersistenceManager()) |
| 140 | ············{ |
| 141 | ················IProvider provider = GetProvider( pm, out ISqlGenerator generator ); |
| 142 | ················foreach (DataTable dt in pm.DataSet.Tables) |
| 143 | ················{ |
| 144 | ····················foreach (string statement in CreateTableStatements( dt, pm.NDOMapping, provider, generator )) |
| 145 | ························await ExecuteAsync( statement, ct ); |
| 146 | ················} |
| 147 | |
| 148 | ················foreach (string statement in CreateIndexStatements( pm.DataSet, pm.NDOMapping, provider, generator )) |
| 149 | ····················await ExecuteAsync( statement, ct ); |
| 150 | ············} |
| 151 | ········} |
| 152 | |
| 153 | ········/// <summary> |
| 154 | ········/// Generates indexes for the foreign key columns, the mapping tables and the columns used in the conditions of the workers. |
| 155 | ········/// </summary> |
| 156 | ········/// <remarks> |
| 157 | ········/// NDO doesn't create indexes. Without them the database has to scan the whole table for each update, delete |
| 158 | ········/// or query with a condition on such a column. With databases which use locks for ReadCommitted (e.g. SqlServer), |
| 159 | ········/// the scans of concurrent transactions block each other and cause many deadlocks. |
| 160 | ········/// </remarks> |
| 161 | ········static IEnumerable<string> CreateIndexStatements( DataSet ds, NDOMapping mapping, IProvider provider, ISqlGenerator generator ) |
| 162 | ········{ |
| 163 | ············var created = new HashSet<string>( StringComparer.OrdinalIgnoreCase ); |
| 164 | ············var counters = new Dictionary<string, int>( StringComparer.OrdinalIgnoreCase ); |
| 165 | |
| 166 | ············foreach (var (tableName, columnNames) in IndexDefinitions( mapping )) |
| 167 | ············{ |
| 168 | ················DataTable dt = ds.Tables[tableName]; |
| 169 | ················if (dt == null || columnNames.Length == 0 || columnNames.Any( c => !dt.Columns.Contains( c ) )) |
| 170 | ····················continue; |
| 171 | ················// The same columns can occur in both directions of a bidirectional relation |
| 172 | ················if (!created.Add( tableName + ":" + String.Join( ",", columnNames ) )) |
| 173 | ····················continue; |
| 174 | |
| 175 | ················// Short names, because some databases limit the length of identifiers |
| 176 | ················counters.TryGetValue( tableName, out int n ); |
| 177 | ················counters[tableName] = ++n; |
| 178 | ················string indexName = provider.GetQuotedName( $"IX_{UnqualifiedName( tableName )}_{n}" ); |
| 179 | yield return generator. CreateIndex( indexName, QualifiedTableName( provider, tableName ) , columnNames. Select( c => dt. Columns[c] ) . ToArray( ) ) ; |
| 180 | ············} |
| 181 | ········} |
| 182 | |
| 183 | ········static IEnumerable<(string TableName, string[] ColumnNames)> IndexDefinitions( NDOMapping mapping ) |
| 184 | ········{ |
| 185 | ············foreach (Class cl in mapping.Classes) |
| 186 | ············{ |
| 187 | ················foreach (Relation r in cl.Relations) |
| 188 | ················{ |
| 189 | ····················var fkColumns = r.ForeignKeyColumns.Select( c => c.Name ).ToList(); |
| 190 | ····················if (r.ForeignKeyTypeColumnName != null) |
| 191 | ························fkColumns.Add( r.ForeignKeyTypeColumnName ); |
| 192 | |
| 193 | ····················if (r.MappingTable != null) |
| 194 | ····················{ |
| 195 | ························var childColumns = r.MappingTable.ChildForeignKeyColumns.Select( c => c.Name ).ToList(); |
| 196 | ························if (r.MappingTable.ChildForeignKeyTypeColumnName != null) |
| 197 | ····························childColumns.Add( r.MappingTable.ChildForeignKeyTypeColumnName ); |
| 198 | ························// Covers the access from the parent side and the deletion of single entries |
| 199 | ························yield return (r.MappingTable.TableName, fkColumns.Concat( childColumns ).ToArray()); |
| 200 | ························// Access from the child side |
| 201 | ························yield return (r.MappingTable.TableName, childColumns.ToArray()); |
| 202 | ····················} |
| 203 | ····················else if (r.Multiplicity == RelationMultiplicity.Element) |
| 204 | ····················{ |
| 205 | ························// The foreign key is in the table of the class |
| 206 | ························yield return (cl.TableName, fkColumns.ToArray()); |
| 207 | ····················} |
| 208 | ····················else |
| 209 | ····················{ |
| 210 | ························// 1:n relation: the foreign key is in the table of the referenced class |
| 211 | ························Class refClass = mapping.FindClass( r.ReferencedTypeName ); |
| 212 | ························if (refClass != null) |
| 213 | ····························yield return (refClass.TableName, fkColumns.ToArray()); |
| 214 | ····················} |
| 215 | ················} |
| 216 | ············} |
| 217 | |
| 218 | ············// Columns used in the conditions of the workers |
| 219 | ············yield return (mapping.FindClass( typeof( SalesOrder ) ).TableName, new[] { "OrderNumber" }); |
| 220 | ············yield return (mapping.FindClass( typeof( Customer ) ).TableName, new[] { "Name" }); |
| 221 | ········} |
| 222 | |
| 223 | ········/// <summary> |
| 224 | ········/// Generates the CREATE TABLE statement in the same way as the GenericSqlGenerator of the NDOEnhancer. |
| 225 | ········/// </summary> |
| 226 | ········static IEnumerable<string> CreateTableStatements( DataTable dt, NDOMapping mapping, IProvider provider, ISqlGenerator generator ) |
| 227 | ········{ |
| 228 | ············string tableName = QualifiedTableName( provider, dt.TableName ); |
| 229 | ············Class cl = mapping.Classes.FirstOrDefault( c => c.TableName == dt.TableName ); |
| 230 | ············DataColumn[] pk = dt.PrimaryKey; |
| 231 | ············var placement = generator.PrimaryConstraintPlacement; |
| 232 | ············// A combined primary key can't be declared in the column definitions |
| 233 | ············if (pk.Length > 1 && placement == PrimaryConstraintPlacement.InColumn) |
| 234 | ················placement = PrimaryConstraintPlacement.InTable; |
| 235 | |
| 236 | ············var columns = new List<string>(); |
| 237 | ············foreach (DataColumn dc in dt.Columns) |
| 238 | ················columns.Add( CreateColumn( dc, cl, provider, generator, pk.Length == 1 && pk.Contains( dc ) && placement == PrimaryConstraintPlacement.InColumn, pk.Contains( dc ) ) ); |
| 239 | |
| 240 | ············string pkConstraint = null; |
| 241 | ············if (pk.Length > 0 && placement != PrimaryConstraintPlacement.InColumn) |
| 242 | ················pkConstraint = generator.CreatePrimaryKeyConstraint( pk, provider.GetQuotedName( "PK_" + UnqualifiedName( dt.TableName ) ), tableName ); |
| 243 | |
| 244 | ············var sb = new StringBuilder(); |
| 245 | ············sb.Append( generator.BeginnTable( tableName ) ).Append( '\n' ); |
| 246 | ············sb.Append( String.Join( ",\n", columns ) ); |
| 247 | ············if (pkConstraint != null && placement == PrimaryConstraintPlacement.InTable) |
| 248 | ················sb.Append( ",\n" ).Append( pkConstraint ); |
| 249 | ············sb.Append( '\n' ).Append( generator.EndTable( tableName ) ); |
| 250 | ············yield return sb.ToString(); |
| 251 | |
| 252 | ············if (pkConstraint != null && placement == PrimaryConstraintPlacement.AfterTable) |
| 253 | ················yield return pkConstraint; |
| 254 | ········} |
| 255 | |
| 256 | ········static string CreateColumn( DataColumn dc, Class cl, IProvider provider, ISqlGenerator generator, bool primaryKeyInColumn, bool isPrimary ) |
| 257 | ········{ |
| 258 | ············string name = provider.GetQuotedName( dc.ColumnName ); |
| 259 | ············string columnType = null; |
| 260 | ············string width = null; |
| 261 | ············string precision = null; |
| 262 | ············bool allowNull = true; |
| 263 | ············int size = 0; |
| 264 | |
| 265 | ············Field field = cl?.Fields.FirstOrDefault( f => f.Column.Name == dc.ColumnName ); |
| 266 | ············if (field != null) |
| 267 | ············{ |
| 268 | ················columnType = field.Column.DbType; |
| 269 | ················size = field.Column.Size; |
| 270 | ················if (size != 0) |
| 271 | ····················width = size.ToString(); |
| 272 | ················if (field.Column.Precision != 0) |
| 273 | ····················precision = field.Column.Precision.ToString(); |
| 274 | ················allowNull = field.Column.AllowDbNull; |
| 275 | ············} |
| 276 | |
| 277 | ············bool autoIncrement = field == null && isPrimary && dc.AutoIncrement; |
| 278 | |
| 279 | ············if (columnType == null) |
| 280 | ················columnType = generator.DbTypeFromType( dc.DataType, size ); |
| 281 | |
| 282 | ············if (width == null) |
| 283 | ············{ |
| 284 | ················int dl = provider.GetDefaultLength( dc.DataType ); |
| 285 | ················if (dl != 0) |
| 286 | ····················width = dl.ToString(); |
| 287 | ············} |
| 288 | |
| 289 | ············if (precision == null && dc.DataType == typeof( decimal )) |
| 290 | ················precision = "2"; |
| 291 | |
| 292 | ············if (!generator.LengthAllowed( columnType )) |
| 293 | ················width = null; |
| 294 | |
| 295 | ············string definition; |
| 296 | ············if (autoIncrement && generator.HasSpecialAutoIncrementColumnFormat) |
| 297 | ················definition = generator.AutoIncrementColumn( name, dc.DataType, columnType, width, isPrimary ); |
| 298 | ············else if (primaryKeyInColumn) |
| 299 | ················definition = generator.PrimaryKeyColumn( name, dc.DataType, columnType, width ); |
| 300 | ············else if (width != null && precision != null) |
| 301 | ················definition = $"{name} {columnType}({width},{precision})"; |
| 302 | ············else if (width != null) |
| 303 | ················definition = $"{name} {columnType}({width})"; |
| 304 | ············else |
| 305 | ················definition = $"{name} {columnType}"; |
| 306 | |
| 307 | ············return definition + " " + generator.NullExpression( allowNull && dc.AllowDBNull ); |
| 308 | ········} |
| 309 | |
| 310 | ········/// <summary> |
| 311 | ········/// Creates the tags, which are shared by all workers. |
| 312 | ········/// </summary> |
| 313 | ········/// <returns>The ids of the tags</returns> |
| 314 | ········public async Task<int[]> CreateTagsAsync( int count, CancellationToken ct = default ) |
| 315 | ········{ |
| 316 | ············await using (var pm = NewPersistenceManager()) |
| 317 | ············{ |
| 318 | ················var tags = new List<Tag>(); |
| 319 | ················for (int i = 0; i < count; i++) |
| 320 | ················{ |
| 321 | ····················var tag = new Tag() { Name = $"Tag{i}" }; |
| 322 | ····················pm.MakePersistent( tag ); |
| 323 | ····················tags.Add( tag ); |
| 324 | ················} |
| 325 | ················await pm.SaveAsync( false, ct ); |
| 326 | ················return tags.Select( t => (int) ((IPersistenceCapable) t).NDOObjectId.Id[0] ).ToArray(); |
| 327 | ············} |
| 328 | ········} |
| 329 | |
| 330 | ········public class RowCounts |
| 331 | ········{ |
| 332 | ············public int Customers; |
| 333 | ············public int Orders; |
| 334 | ············public int OrderLines; |
| 335 | ············public int Tags; |
| 336 | ············public long MappingTableEntries; |
| 337 | |
| 338 | ············public override string ToString() => $"Customers: {Customers}, Orders: {Orders}, OrderLines: {OrderLines}, Tags: {Tags}, Order-Tag relations: {MappingTableEntries}"; |
| 339 | ········} |
| 340 | |
| 341 | ········public async Task<RowCounts> GetRowCountsAsync( CancellationToken ct = default ) |
| 342 | ········{ |
| 343 | ············var result = new RowCounts(); |
| 344 | ············await using (var pm = NewPersistenceManager()) |
| 345 | ············{ |
| 346 | ················result.Customers = await pm.Objects<Customer>().CountAsync( ct ); |
| 347 | ················result.Orders = await pm.Objects<SalesOrder>().CountAsync( ct ); |
| 348 | ················result.OrderLines = await pm.Objects<OrderLine>().CountAsync( ct ); |
| 349 | ················result.Tags = await pm.Objects<Tag>().CountAsync( ct ); |
| 350 | ············} |
| 351 | |
| 352 | ············// The mapping table has no class, so we count it with SQL. |
| 353 | ············// We use a separate PersistenceManager: GetSqlPassThroughHandler() uses a new Connection object, |
| 354 | ············// so in pessimistic mode the handler would open a second transaction besides the one of the queries above, |
| 355 | ············// which blocks e.g. with Sqlite and IsolationLevel.Serializable. |
| 356 | ············await using (var pm = NewPersistenceManager()) |
| 357 | ············{ |
| 358 | ················var relation = pm.NDOMapping.FindClass( typeof( SalesOrder ) ).Relations.Single( r => r.FieldName == "tags" ); |
| 359 | ················IProvider provider = GetProvider( pm, out _ ); |
| 360 | ················string table = QualifiedTableName( provider, relation.MappingTable.TableName ); |
| 361 | ················await using (var handler = pm.GetSqlPassThroughHandler()) |
| 362 | ················{ |
| 363 | ····················await using (DbDataReader reader = await handler.ExecuteAsync( $"SELECT COUNT(*) FROM {table}", true, null, ct )) |
| 364 | ····················{ |
| 365 | ························await reader.ReadAsync( ct ); |
| 366 | ························result.MappingTableEntries = Convert.ToInt64( reader.GetValue( 0 ) ); |
| 367 | ····················} |
| 368 | ····················await handler.CommitTransactionAsync( ct ); |
| 369 | ················} |
| 370 | ············} |
| 371 | ············return result; |
| 372 | ········} |
| 373 | ····} |
| 374 | } |
| 375 |
New Commit (f5f4fd8)
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Data; |
| 4 | using System.Data.Common; |
| 5 | using System.IO; |
| 6 | using System.Linq; |
| 7 | using System.Text; |
| 8 | using System.Threading; |
| 9 | using System.Threading.Tasks; |
| 10 | using System.Xml.Linq; |
| 11 | using NDO; |
| 12 | using NDO.Mapping; |
| 13 | using NDO.ProviderFactory; |
| 14 | using NDOInterfaces; |
| 15 | using StressTestClasses; |
| 16 | |
| 17 | namespace StressTest |
| 18 | { |
| 19 | ····/// <summary> |
| 20 | ····/// Provides PersistenceManager instances for the configured provider and creates the database schema. |
| 21 | ····/// </summary> |
| 22 | ····/// <remarks> |
| 23 | ····/// The mapping file of StressTestClasses contains a dummy connection. It is copied to a provider specific |
| 24 | ····/// mapping file, in which the connection type and connection string are replaced by the configured values. |
| 25 | ····/// The tables are generated with the ISqlGenerator of the provider from the DataSet, which NDO builds from the mapping. |
| 26 | ····/// In addition to the tables, indexes for the foreign keys and the search columns are created. |
| 27 | ····/// </remarks> |
| 28 | ····public class TestDatabase |
| 29 | ····{ |
| 30 | ········readonly StressTestOptions options; |
| 31 | ········readonly NDOMapping sharedMapping; |
| 32 | |
| 33 | ········public string MappingFile { get; } |
| 34 | |
| 35 | ········public TestDatabase( StressTestOptions options ) |
| 36 | ········{ |
| 37 | ············this.options = options; |
| 38 | |
| 39 | ············var mappingSource = Path.Combine( AppContext.BaseDirectory, "StressTestClasses.NDOMapping.xml" ); |
| 40 | ············XDocument doc = XDocument.Load( mappingSource ); |
| 41 | ············foreach (var conn in doc.Descendants( "Connection" )) |
| 42 | ············{ |
| 43 | ················conn.SetAttributeValue( "Type", options.Provider ); |
| 44 | ················conn.SetAttributeValue( "Name", options.ConnectionString ); |
| 45 | ············} |
| 46 | ············MappingFile = Path.Combine( AppContext.BaseDirectory, $"NDOMapping.{options.Provider}.xml" ); |
| 47 | ············doc.Save( MappingFile ); |
| 48 | |
| 49 | ············if (options.SharedMapping) |
| 50 | ············{ |
| 51 | ················// The mapping object stays valid after the PersistenceManager is closed. |
| 52 | ················using (var pm = new PersistenceManager( MappingFile )) |
| 53 | ····················this.sharedMapping = pm.NDOMapping; |
| 54 | ············} |
| 55 | ········} |
| 56 | |
| 57 | ········/// <summary> |
| 58 | ········/// Creates a new PersistenceManager. Each worker must use its own instances. |
| 59 | ········/// </summary> |
| 60 | ········public PersistenceManager NewPersistenceManager() |
| 61 | ········{ |
| 62 | ············var pm = this.sharedMapping != null |
| 63 | ················? new PersistenceManager( this.sharedMapping ) |
| 64 | ················: new PersistenceManager( MappingFile ); |
| 65 | ············pm.TransactionMode = this.options.TransactionMode; |
| 66 | ············if (this.options.IsolationLevel.HasValue) |
| 67 | ················pm.IsolationLevel = this.options.IsolationLevel.Value; |
| 68 | ············return pm; |
| 69 | ········} |
| 70 | |
| 71 | ········IProvider GetProvider( PersistenceManager pm, out ISqlGenerator generator ) |
| 72 | ········{ |
| 73 | ············Connection conn = pm.NDOMapping.Connections.First(); |
| 74 | ············IProvider provider = pm.NDOMapping.GetProvider( conn ); |
| 75 | ············if (provider == null) |
| 76 | ················throw new Exception( $"Provider '{this.options.Provider}' not found. Available providers: {String.Join( ", ", NDOProviderFactory.Instance.ProviderNames )}" ); |
| 77 | ············if (!NDOProviderFactory.Instance.Generators.TryGetValue( this.options.Provider, out generator )) |
| 78 | ················throw new Exception( $"No ISqlGenerator for provider '{this.options.Provider}' found." ); |
| 79 | ············generator.Provider = provider; |
| 80 | ············return provider; |
| 81 | ········} |
| 82 | |
| 83 | ········/// <summary> |
| 84 | ········/// Quotes a table name, which might contain a schema name. |
| 85 | ········/// </summary> |
| 86 | ········static string QualifiedTableName( IProvider provider, string name ) |
| 87 | ········{ |
| 88 | ············return String.Join( ".", name.Split( '.' ).Select( n => provider.GetQuotedName( n ) ) ); |
| 89 | ········} |
| 90 | |
| 91 | ········static string UnqualifiedName( string name ) |
| 92 | ········{ |
| 93 | ············int p = name.LastIndexOf( '.' ); |
| 94 | ············if (p > -1) |
| 95 | ················name = name.Substring( p + 1 ); |
| 96 | ············return name.Trim( '"', '`', '[', ']' ); |
| 97 | ········} |
| 98 | |
| 99 | ········async Task<HashSet<string>> GetExistingTablesAsync( IProvider provider, CancellationToken ct ) |
| 100 | ········{ |
| 101 | ············using (DbConnection conn = provider.NewConnection( this.options.ConnectionString )) |
| 102 | ············{ |
| 103 | ················await conn.OpenAsync( ct ); |
| 104 | ················return new HashSet<string>( provider.GetTableNames( conn ).Select( UnqualifiedName ), StringComparer.OrdinalIgnoreCase ); |
| 105 | ············} |
| 106 | ········} |
| 107 | |
| 108 | ········/// <summary> |
| 109 | ········/// Executes each statement in its own transaction. |
| 110 | ········/// </summary> |
| 111 | ········async Task ExecuteAsync( string sql, CancellationToken ct ) |
| 112 | ········{ |
| 113 | ············// Some databases (e.g. Oracle) don't accept the statement terminator in a command |
| 114 | ············sql = sql.Trim().TrimEnd( ';' ); |
| 115 | ············await using (var pm = NewPersistenceManager()) |
| 116 | ············await using (var handler = pm.GetSqlPassThroughHandler()) |
| 117 | ············{ |
| 118 | ················await handler.ExecuteAsync( sql, false, null, ct ); |
| 119 | ················await handler.CommitTransactionAsync( ct ); |
| 120 | ············} |
| 121 | ········} |
| 122 | |
| 123 | ········public async Task DropSchemaAsync( CancellationToken ct = default ) |
| 124 | ········{ |
| 125 | ············await using (var pm = NewPersistenceManager()) |
| 126 | ············{ |
| 127 | ················IProvider provider = GetProvider( pm, out ISqlGenerator generator ); |
| 128 | ················var existing = await GetExistingTablesAsync( provider, ct ); |
| 129 | ················foreach (DataTable dt in pm.DataSet.Tables) |
| 130 | ················{ |
| 131 | ····················if (existing.Contains( UnqualifiedName( dt.TableName ) )) |
| 132 | ························await ExecuteAsync( generator.DropTable( QualifiedTableName( provider, dt.TableName ) ), ct ); |
| 133 | ················} |
| 134 | ············} |
| 135 | ········} |
| 136 | |
| 137 | ········public async Task CreateSchemaAsync( CancellationToken ct = default ) |
| 138 | ········{ |
| 139 | ············await using (var pm = NewPersistenceManager()) |
| 140 | ············{ |
| 141 | ················IProvider provider = GetProvider( pm, out ISqlGenerator generator ); |
| 142 | ················foreach (DataTable dt in pm.DataSet.Tables) |
| 143 | ················{ |
| 144 | ····················foreach (string statement in CreateTableStatements( dt, pm.NDOMapping, provider, generator )) |
| 145 | ························await ExecuteAsync( statement, ct ); |
| 146 | ················} |
| 147 | |
| 148 | ················foreach (string statement in CreateIndexStatements( pm.DataSet, pm.NDOMapping, provider, generator )) |
| 149 | ····················await ExecuteAsync( statement, ct ); |
| 150 | ············} |
| 151 | ········} |
| 152 | |
| 153 | ········/// <summary> |
| 154 | ········/// Generates indexes for the foreign key columns, the mapping tables and the columns used in the conditions of the workers. |
| 155 | ········/// </summary> |
| 156 | ········/// <remarks> |
| 157 | ········/// NDO doesn't create indexes. Without them the database has to scan the whole table for each update, delete |
| 158 | ········/// or query with a condition on such a column. With databases which use locks for ReadCommitted (e.g. SqlServer), |
| 159 | ········/// the scans of concurrent transactions block each other and cause many deadlocks. |
| 160 | ········/// </remarks> |
| 161 | ········static IEnumerable<string> CreateIndexStatements( DataSet ds, NDOMapping mapping, IProvider provider, ISqlGenerator generator ) |
| 162 | ········{ |
| 163 | ············var created = new HashSet<string>( StringComparer.OrdinalIgnoreCase ); |
| 164 | ············var counters = new Dictionary<string, int>( StringComparer.OrdinalIgnoreCase ); |
| 165 | |
| 166 | ············foreach (var (tableName, columnNames) in IndexDefinitions( mapping )) |
| 167 | ············{ |
| 168 | ················DataTable dt = ds.Tables[tableName]; |
| 169 | ················if (dt == null || columnNames.Length == 0 || columnNames.Any( c => !dt.Columns.Contains( c ) )) |
| 170 | ····················continue; |
| 171 | ················// The same columns can occur in both directions of a bidirectional relation |
| 172 | ················if (!created.Add( tableName + ":" + String.Join( ",", columnNames ) )) |
| 173 | ····················continue; |
| 174 | |
| 175 | ················// Short names, because some databases limit the length of identifiers |
| 176 | ················counters.TryGetValue( tableName, out int n ); |
| 177 | ················counters[tableName] = ++n; |
| 178 | ················string indexName = provider.GetQuotedName( $"IX_{UnqualifiedName( tableName )}_{n}" ); |
| 179 | yield return generator. CreateIndex( indexName, QualifiedTableName( provider, tableName ) , columnNames. Select( c => dt. Columns[c] ) . ToArray( ) , false ) ; |
| 180 | ············} |
| 181 | ········} |
| 182 | |
| 183 | ········static IEnumerable<(string TableName, string[] ColumnNames)> IndexDefinitions( NDOMapping mapping ) |
| 184 | ········{ |
| 185 | ············foreach (Class cl in mapping.Classes) |
| 186 | ············{ |
| 187 | ················foreach (Relation r in cl.Relations) |
| 188 | ················{ |
| 189 | ····················var fkColumns = r.ForeignKeyColumns.Select( c => c.Name ).ToList(); |
| 190 | ····················if (r.ForeignKeyTypeColumnName != null) |
| 191 | ························fkColumns.Add( r.ForeignKeyTypeColumnName ); |
| 192 | |
| 193 | ····················if (r.MappingTable != null) |
| 194 | ····················{ |
| 195 | ························var childColumns = r.MappingTable.ChildForeignKeyColumns.Select( c => c.Name ).ToList(); |
| 196 | ························if (r.MappingTable.ChildForeignKeyTypeColumnName != null) |
| 197 | ····························childColumns.Add( r.MappingTable.ChildForeignKeyTypeColumnName ); |
| 198 | ························// Covers the access from the parent side and the deletion of single entries |
| 199 | ························yield return (r.MappingTable.TableName, fkColumns.Concat( childColumns ).ToArray()); |
| 200 | ························// Access from the child side |
| 201 | ························yield return (r.MappingTable.TableName, childColumns.ToArray()); |
| 202 | ····················} |
| 203 | ····················else if (r.Multiplicity == RelationMultiplicity.Element) |
| 204 | ····················{ |
| 205 | ························// The foreign key is in the table of the class |
| 206 | ························yield return (cl.TableName, fkColumns.ToArray()); |
| 207 | ····················} |
| 208 | ····················else |
| 209 | ····················{ |
| 210 | ························// 1:n relation: the foreign key is in the table of the referenced class |
| 211 | ························Class refClass = mapping.FindClass( r.ReferencedTypeName ); |
| 212 | ························if (refClass != null) |
| 213 | ····························yield return (refClass.TableName, fkColumns.ToArray()); |
| 214 | ····················} |
| 215 | ················} |
| 216 | ············} |
| 217 | |
| 218 | ············// Columns used in the conditions of the workers |
| 219 | ············yield return (mapping.FindClass( typeof( SalesOrder ) ).TableName, new[] { "OrderNumber" }); |
| 220 | ············yield return (mapping.FindClass( typeof( Customer ) ).TableName, new[] { "Name" }); |
| 221 | ········} |
| 222 | |
| 223 | ········/// <summary> |
| 224 | ········/// Generates the CREATE TABLE statement in the same way as the GenericSqlGenerator of the NDOEnhancer. |
| 225 | ········/// </summary> |
| 226 | ········static IEnumerable<string> CreateTableStatements( DataTable dt, NDOMapping mapping, IProvider provider, ISqlGenerator generator ) |
| 227 | ········{ |
| 228 | ············string tableName = QualifiedTableName( provider, dt.TableName ); |
| 229 | ············Class cl = mapping.Classes.FirstOrDefault( c => c.TableName == dt.TableName ); |
| 230 | ············DataColumn[] pk = dt.PrimaryKey; |
| 231 | ············var placement = generator.PrimaryConstraintPlacement; |
| 232 | ············// A combined primary key can't be declared in the column definitions |
| 233 | ············if (pk.Length > 1 && placement == PrimaryConstraintPlacement.InColumn) |
| 234 | ················placement = PrimaryConstraintPlacement.InTable; |
| 235 | |
| 236 | ············var columns = new List<string>(); |
| 237 | ············foreach (DataColumn dc in dt.Columns) |
| 238 | ················columns.Add( CreateColumn( dc, cl, provider, generator, pk.Length == 1 && pk.Contains( dc ) && placement == PrimaryConstraintPlacement.InColumn, pk.Contains( dc ) ) ); |
| 239 | |
| 240 | ············string pkConstraint = null; |
| 241 | ············if (pk.Length > 0 && placement != PrimaryConstraintPlacement.InColumn) |
| 242 | ················pkConstraint = generator.CreatePrimaryKeyConstraint( pk, provider.GetQuotedName( "PK_" + UnqualifiedName( dt.TableName ) ), tableName ); |
| 243 | |
| 244 | ············var sb = new StringBuilder(); |
| 245 | ············sb.Append( generator.BeginnTable( tableName ) ).Append( '\n' ); |
| 246 | ············sb.Append( String.Join( ",\n", columns ) ); |
| 247 | ············if (pkConstraint != null && placement == PrimaryConstraintPlacement.InTable) |
| 248 | ················sb.Append( ",\n" ).Append( pkConstraint ); |
| 249 | ············sb.Append( '\n' ).Append( generator.EndTable( tableName ) ); |
| 250 | ············yield return sb.ToString(); |
| 251 | |
| 252 | ············if (pkConstraint != null && placement == PrimaryConstraintPlacement.AfterTable) |
| 253 | ················yield return pkConstraint; |
| 254 | ········} |
| 255 | |
| 256 | ········static string CreateColumn( DataColumn dc, Class cl, IProvider provider, ISqlGenerator generator, bool primaryKeyInColumn, bool isPrimary ) |
| 257 | ········{ |
| 258 | ············string name = provider.GetQuotedName( dc.ColumnName ); |
| 259 | ············string columnType = null; |
| 260 | ············string width = null; |
| 261 | ············string precision = null; |
| 262 | ············bool allowNull = true; |
| 263 | ············int size = 0; |
| 264 | |
| 265 | ············Field field = cl?.Fields.FirstOrDefault( f => f.Column.Name == dc.ColumnName ); |
| 266 | ············if (field != null) |
| 267 | ············{ |
| 268 | ················columnType = field.Column.DbType; |
| 269 | ················size = field.Column.Size; |
| 270 | ················if (size != 0) |
| 271 | ····················width = size.ToString(); |
| 272 | ················if (field.Column.Precision != 0) |
| 273 | ····················precision = field.Column.Precision.ToString(); |
| 274 | ················allowNull = field.Column.AllowDbNull; |
| 275 | ············} |
| 276 | |
| 277 | ············bool autoIncrement = field == null && isPrimary && dc.AutoIncrement; |
| 278 | |
| 279 | ············if (columnType == null) |
| 280 | ················columnType = generator.DbTypeFromType( dc.DataType, size ); |
| 281 | |
| 282 | ············if (width == null) |
| 283 | ············{ |
| 284 | ················int dl = provider.GetDefaultLength( dc.DataType ); |
| 285 | ················if (dl != 0) |
| 286 | ····················width = dl.ToString(); |
| 287 | ············} |
| 288 | |
| 289 | ············if (precision == null && dc.DataType == typeof( decimal )) |
| 290 | ················precision = "2"; |
| 291 | |
| 292 | ············if (!generator.LengthAllowed( columnType )) |
| 293 | ················width = null; |
| 294 | |
| 295 | ············string definition; |
| 296 | ············if (autoIncrement && generator.HasSpecialAutoIncrementColumnFormat) |
| 297 | ················definition = generator.AutoIncrementColumn( name, dc.DataType, columnType, width, isPrimary ); |
| 298 | ············else if (primaryKeyInColumn) |
| 299 | ················definition = generator.PrimaryKeyColumn( name, dc.DataType, columnType, width ); |
| 300 | ············else if (width != null && precision != null) |
| 301 | ················definition = $"{name} {columnType}({width},{precision})"; |
| 302 | ············else if (width != null) |
| 303 | ················definition = $"{name} {columnType}({width})"; |
| 304 | ············else |
| 305 | ················definition = $"{name} {columnType}"; |
| 306 | |
| 307 | ············return definition + " " + generator.NullExpression( allowNull && dc.AllowDBNull ); |
| 308 | ········} |
| 309 | |
| 310 | ········/// <summary> |
| 311 | ········/// Creates the tags, which are shared by all workers. |
| 312 | ········/// </summary> |
| 313 | ········/// <returns>The ids of the tags</returns> |
| 314 | ········public async Task<int[]> CreateTagsAsync( int count, CancellationToken ct = default ) |
| 315 | ········{ |
| 316 | ············await using (var pm = NewPersistenceManager()) |
| 317 | ············{ |
| 318 | ················var tags = new List<Tag>(); |
| 319 | ················for (int i = 0; i < count; i++) |
| 320 | ················{ |
| 321 | ····················var tag = new Tag() { Name = $"Tag{i}" }; |
| 322 | ····················pm.MakePersistent( tag ); |
| 323 | ····················tags.Add( tag ); |
| 324 | ················} |
| 325 | ················await pm.SaveAsync( false, ct ); |
| 326 | ················return tags.Select( t => (int) ((IPersistenceCapable) t).NDOObjectId.Id[0] ).ToArray(); |
| 327 | ············} |
| 328 | ········} |
| 329 | |
| 330 | ········public class RowCounts |
| 331 | ········{ |
| 332 | ············public int Customers; |
| 333 | ············public int Orders; |
| 334 | ············public int OrderLines; |
| 335 | ············public int Tags; |
| 336 | ············public long MappingTableEntries; |
| 337 | |
| 338 | ············public override string ToString() => $"Customers: {Customers}, Orders: {Orders}, OrderLines: {OrderLines}, Tags: {Tags}, Order-Tag relations: {MappingTableEntries}"; |
| 339 | ········} |
| 340 | |
| 341 | ········public async Task<RowCounts> GetRowCountsAsync( CancellationToken ct = default ) |
| 342 | ········{ |
| 343 | ············var result = new RowCounts(); |
| 344 | ············await using (var pm = NewPersistenceManager()) |
| 345 | ············{ |
| 346 | ················result.Customers = await pm.Objects<Customer>().CountAsync( ct ); |
| 347 | ················result.Orders = await pm.Objects<SalesOrder>().CountAsync( ct ); |
| 348 | ················result.OrderLines = await pm.Objects<OrderLine>().CountAsync( ct ); |
| 349 | ················result.Tags = await pm.Objects<Tag>().CountAsync( ct ); |
| 350 | ············} |
| 351 | |
| 352 | ············// The mapping table has no class, so we count it with SQL. |
| 353 | ············// We use a separate PersistenceManager: GetSqlPassThroughHandler() uses a new Connection object, |
| 354 | ············// so in pessimistic mode the handler would open a second transaction besides the one of the queries above, |
| 355 | ············// which blocks e.g. with Sqlite and IsolationLevel.Serializable. |
| 356 | ············await using (var pm = NewPersistenceManager()) |
| 357 | ············{ |
| 358 | ················var relation = pm.NDOMapping.FindClass( typeof( SalesOrder ) ).Relations.Single( r => r.FieldName == "tags" ); |
| 359 | ················IProvider provider = GetProvider( pm, out _ ); |
| 360 | ················string table = QualifiedTableName( provider, relation.MappingTable.TableName ); |
| 361 | ················await using (var handler = pm.GetSqlPassThroughHandler()) |
| 362 | ················{ |
| 363 | ····················await using (DbDataReader reader = await handler.ExecuteAsync( $"SELECT COUNT(*) FROM {table}", true, null, ct )) |
| 364 | ····················{ |
| 365 | ························await reader.ReadAsync( ct ); |
| 366 | ························result.MappingTableEntries = Convert.ToInt64( reader.GetValue( 0 ) ); |
| 367 | ····················} |
| 368 | ····················await handler.CommitTransactionAsync( ct ); |
| 369 | ················} |
| 370 | ············} |
| 371 | ············return result; |
| 372 | ········} |
| 373 | ····} |
| 374 | } |
| 375 |